Beispiel #1
0
class LaserRangeFinder(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletLaserRangeFinder, *args)

        self.lrf = self.device

        self.cbe_distance = CallbackEmulator(self.lrf.get_distance,
                                             self.cb_distance,
                                             self.increase_error_count)
        self.cbe_velocity = CallbackEmulator(self.lrf.get_velocity,
                                             self.cb_velocity,
                                             self.increase_error_count)

        self.current_distance = None  # int, cm
        self.current_velocity = None  # float, m/s

        plots_distance = [('Distance', Qt.red, lambda: self.current_distance,
                           format_distance)]
        plots_velocity = [('Velocity', Qt.red, lambda: self.current_velocity,
                           '{:.2f} m/s'.format)]
        self.plot_widget_distance = PlotWidget('Distance [cm]', plots_distance)
        self.plot_widget_velocity = PlotWidget('Velocity [m/s]',
                                               plots_velocity)

        self.mode_label = QLabel('Mode:')
        self.mode_combo = QComboBox()
        self.mode_combo.addItem("Distance: 1cm resolution, 40m max")
        self.mode_combo.addItem("Velocity: 0.10 m/s resolution, 12.70m/s max")
        self.mode_combo.addItem("Velocity: 0.25 m/s resolution, 31.75m/s max")
        self.mode_combo.addItem("Velocity: 0.50 m/s resolution, 63.50m/s max")
        self.mode_combo.addItem("Velocity: 1.00 m/s resolution, 127.00m/s max")
        self.mode_combo.currentIndexChanged.connect(self.mode_changed)
        self.mode_combo.hide()

        self.label_average_distance = QLabel('Moving Average for Distance:')

        self.spin_average_distance = QSpinBox()
        self.spin_average_distance.setMinimum(0)
        self.spin_average_distance.setMaximum(50)
        self.spin_average_distance.setSingleStep(1)
        self.spin_average_distance.setValue(10)
        self.spin_average_distance.editingFinished.connect(
            self.spin_average_finished)

        self.label_average_velocity = QLabel('Moving Average for Velocity:')

        self.spin_average_velocity = QSpinBox()
        self.spin_average_velocity.setMinimum(0)
        self.spin_average_velocity.setMaximum(50)
        self.spin_average_velocity.setSingleStep(1)
        self.spin_average_velocity.setValue(10)
        self.spin_average_velocity.editingFinished.connect(
            self.spin_average_finished)

        self.enable_laser = QCheckBox("Enable Laser")
        self.enable_laser.stateChanged.connect(self.enable_laser_changed)

        self.label_acquisition_count = QLabel('Acquisition Count:')
        self.spin_acquisition_count = QSpinBox()
        self.spin_acquisition_count.setMinimum(1)
        self.spin_acquisition_count.setMaximum(255)
        self.spin_acquisition_count.setSingleStep(1)
        self.spin_acquisition_count.setValue(128)

        self.enable_qick_termination = QCheckBox("Quick Termination")

        self.label_threshold = QLabel('Threshold:')
        self.threshold = QCheckBox("Automatic Threshold")

        self.spin_threshold = QSpinBox()
        self.spin_threshold.setMinimum(1)
        self.spin_threshold.setMaximum(255)
        self.spin_threshold.setSingleStep(1)
        self.spin_threshold.setValue(1)

        self.label_frequency = QLabel('Frequency [Hz]:')
        self.frequency = QCheckBox(
            "Automatic Frequency (Disable for Velocity)")

        self.spin_frequency = QSpinBox()
        self.spin_frequency.setMinimum(10)
        self.spin_frequency.setMaximum(500)
        self.spin_frequency.setSingleStep(1)
        self.spin_frequency.setValue(10)

        self.spin_acquisition_count.editingFinished.connect(
            self.configuration_changed)
        self.enable_qick_termination.stateChanged.connect(
            self.configuration_changed)
        self.spin_threshold.editingFinished.connect(self.configuration_changed)
        self.threshold.stateChanged.connect(self.configuration_changed)
        self.spin_frequency.editingFinished.connect(self.configuration_changed)
        self.frequency.stateChanged.connect(self.configuration_changed)

        layout_h1 = QHBoxLayout()
        layout_h1.addWidget(self.plot_widget_distance)
        layout_h1.addWidget(self.plot_widget_velocity)

        layout_h2 = QHBoxLayout()
        layout_h2.addWidget(self.mode_label)
        layout_h2.addWidget(self.mode_combo)
        layout_h2.addWidget(self.label_average_distance)
        layout_h2.addWidget(self.spin_average_distance)
        layout_h2.addWidget(self.label_average_velocity)
        layout_h2.addWidget(self.spin_average_velocity)
        layout_h2.addStretch()
        layout_h2.addWidget(self.enable_laser)

        layout_h3 = QHBoxLayout()
        layout_h3.addWidget(self.label_frequency)
        layout_h3.addWidget(self.spin_frequency)
        layout_h3.addWidget(self.frequency)
        layout_h3.addStretch()
        layout_h3.addWidget(self.enable_qick_termination)

        layout_h4 = QHBoxLayout()
        layout_h4.addWidget(self.label_threshold)
        layout_h4.addWidget(self.spin_threshold)
        layout_h4.addWidget(self.threshold)
        layout_h4.addStretch()
        layout_h4.addWidget(self.label_acquisition_count)
        layout_h4.addWidget(self.spin_acquisition_count)

        self.widgets_distance = [
            self.plot_widget_distance, self.spin_average_distance,
            self.label_average_distance
        ]
        self.widgets_velocity = [
            self.plot_widget_velocity, self.spin_average_velocity,
            self.label_average_velocity
        ]

        for w in self.widgets_distance:
            w.hide()
        for w in self.widgets_velocity:
            w.hide()

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addLayout(layout_h1)
        layout.addWidget(line)
        layout.addLayout(layout_h2)
        layout.addLayout(layout_h3)
        layout.addLayout(layout_h4)

        self.has_sensor_hardware_version_api = self.firmware_version >= (2, 0,
                                                                         3)
        self.has_configuration_api = self.firmware_version >= (2, 0, 3)

    def start(self):
        if self.has_sensor_hardware_version_api:
            async_call(self.lrf.get_sensor_hardware_version, None,
                       self.get_sensor_hardware_version_async,
                       self.increase_error_count)
        else:
            self.get_sensor_hardware_version_async(1)

        if self.has_configuration_api:
            async_call(self.lrf.get_configuration, None,
                       self.get_configuration_async, self.increase_error_count)

        async_call(self.lrf.get_mode, None, self.get_mode_async,
                   self.increase_error_count)
        async_call(self.lrf.is_laser_enabled, None,
                   self.is_laser_enabled_async, self.increase_error_count)
        async_call(self.lrf.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.lrf.get_distance, None, self.cb_distance,
                   self.increase_error_count)
        async_call(self.lrf.get_velocity, None, self.cb_velocity,
                   self.increase_error_count)
        self.cbe_distance.set_period(25)
        self.cbe_velocity.set_period(25)

        self.plot_widget_distance.stop = False
        self.plot_widget_velocity.stop = False

    def stop(self):
        self.cbe_distance.set_period(0)
        self.cbe_velocity.set_period(0)

        self.plot_widget_distance.stop = True
        self.plot_widget_velocity.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletLaserRangeFinder.DEVICE_IDENTIFIER

    def is_laser_enabled_async(self, enabled):
        if enabled:
            self.enable_laser.setChecked(True)
        else:
            self.enable_laser.setChecked(False)

    def enable_laser_changed(self, state):
        if state == Qt.Checked:
            self.lrf.enable_laser()
        else:
            self.lrf.disable_laser()

    def mode_changed(self, value):
        if value < 0 or value > 4:
            return

        self.lrf.set_mode(value)
        if value == 0:
            for w in self.widgets_velocity:
                w.hide()
            for w in self.widgets_distance:
                w.show()
        else:
            for w in self.widgets_distance:
                w.hide()
            for w in self.widgets_velocity:
                w.show()

    def cb_distance(self, distance):
        self.current_distance = distance

    def cb_velocity(self, velocity):
        self.current_velocity = velocity / 100.0

    def configuration_changed(self):
        acquisition_count = self.spin_acquisition_count.value()
        enable_quick_termination = self.enable_qick_termination.isChecked()

        if self.threshold.isChecked():
            threshold = 0
        else:
            threshold = self.spin_threshold.value()

        if self.frequency.isChecked():
            frequency = 0
            for w in self.widgets_velocity:
                w.hide()
        else:
            frequency = self.spin_frequency.value()
            for w in self.widgets_velocity:
                w.show()

        self.spin_threshold.setDisabled(threshold == 0)
        self.spin_frequency.setDisabled(frequency == 0)

        self.lrf.set_configuration(acquisition_count, enable_quick_termination,
                                   threshold, frequency)

    def get_configuration_async(self, conf):
        self.spin_acquisition_count.blockSignals(True)
        self.spin_acquisition_count.setValue(conf.acquisition_count)
        self.spin_acquisition_count.blockSignals(False)

        self.enable_qick_termination.blockSignals(True)
        self.enable_qick_termination.setChecked(conf.enable_quick_termination)
        self.enable_qick_termination.blockSignals(False)

        self.spin_threshold.blockSignals(True)
        self.spin_threshold.setValue(conf.threshold_value)
        self.spin_threshold.setDisabled(conf.threshold_value == 0)
        self.spin_threshold.blockSignals(False)

        self.spin_frequency.blockSignals(True)
        self.spin_frequency.setValue(conf.measurement_frequency)
        self.spin_frequency.setDisabled(conf.measurement_frequency == 0)
        self.spin_frequency.blockSignals(False)

        self.threshold.blockSignals(True)
        self.threshold.setChecked(conf.threshold_value == 0)
        self.threshold.blockSignals(False)

        self.frequency.blockSignals(True)
        self.frequency.setChecked(conf.measurement_frequency == 0)
        self.frequency.blockSignals(False)

        self.configuration_changed()

    def get_sensor_hardware_version_async(self, value):
        if value == 1:
            self.mode_combo.show()
            self.mode_label.show()
            self.label_acquisition_count.hide()
            self.spin_acquisition_count.hide()
            self.enable_qick_termination.hide()
            self.label_threshold.hide()
            self.spin_threshold.hide()
            self.threshold.hide()
            self.label_frequency.hide()
            self.spin_frequency.hide()
            self.frequency.hide()
        else:
            self.mode_combo.hide()
            self.mode_label.hide()
            self.label_acquisition_count.show()
            self.spin_acquisition_count.show()
            self.enable_qick_termination.show()
            self.label_threshold.show()
            self.spin_threshold.show()
            self.threshold.show()
            self.label_frequency.show()
            self.spin_frequency.show()
            self.frequency.show()

            for w in self.widgets_distance:
                w.show()
            for w in self.widgets_velocity:
                w.show()

    def get_mode_async(self, value):
        self.mode_combo.setCurrentIndex(value)
        self.mode_changed(value)

    def get_moving_average_async(self, avg):
        self.spin_average_distance.setValue(avg.distance_average_length)
        self.spin_average_velocity.setValue(avg.velocity_average_length)

    def spin_average_finished(self):
        self.lrf.set_moving_average(self.spin_average_distance.value(),
                                    self.spin_average_velocity.value())
Beispiel #2
0
class WizardDialog(QDialog):
    """The dialog for update."""
    def __init__(self, main_window):
        super(WizardDialog, self).__init__()
        self.mw = main_window
        vbox = QVBoxLayout(self)

        # label and checkbox
        self.main_text = QLabel(u"init text")
        vbox.addWidget(self.main_text)
        self.notthisagain = QCheckBox(u"No mostrar automáticamente esta ayuda")
        nowizard = config.get('nowizard', False)
        self.notthisagain.setCheckState(nowizard)
        self.notthisagain.stateChanged.connect(self._notthisagain_toggled)
        vbox.addWidget(self.notthisagain)

        # buttons
        bbox = QDialogButtonBox()
        self.navbut_actn = QPushButton(u"init text")
        bbox.addButton(self.navbut_actn, QDialogButtonBox.ActionRole)
        self.navbut_prev = QPushButton(u"Anterior")
        bbox.addButton(self.navbut_prev, QDialogButtonBox.ActionRole)
        self.navbut_next = QPushButton(u"Siguiente")
        bbox.addButton(self.navbut_next, QDialogButtonBox.ActionRole)
        vbox.addWidget(bbox)

        self.show()
        self.step = 0
        self._move(0)

    def _notthisagain_toggled(self, state):
        """The "not this again" checkbutton togled state."""
        logger.info("Configuring 'nowizard' to %s", state)
        config['nowizard'] = state

    def _move(self, delta_step):
        """The engine for the wizard steps."""
        self.step += delta_step
        logger.debug("Entering into step %d", self.step)
        (text, ign_func, act_label, act_func) = STEPS[self.step]
        # if this step should be ignored, just leave
        if ign_func is not None:
            m = getattr(self, "_ign_" + ign_func)
            if m():
                # keep going
                return self._move(delta_step)

        # adjust navigation buttons
        if self.step == 0:
            self.navbut_prev.setEnabled(False)
            self.navbut_next.setText(u"Siguiente")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(lambda: self._move(1))
            self.notthisagain.show()
        elif self.step == len(STEPS) - 1:
            self.navbut_prev.setEnabled(True)
            self.navbut_prev.clicked.disconnect()
            self.navbut_prev.clicked.connect(lambda: self._move(-1))
            self.navbut_next.setText(u"Terminar")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(self.accept)
            self.notthisagain.hide()
        else:
            self.navbut_prev.setEnabled(True)
            self.navbut_prev.clicked.disconnect()
            self.navbut_prev.clicked.connect(lambda: self._move(-1))
            self.navbut_next.setText(u"Siguiente")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(lambda: self._move(1))
            self.notthisagain.hide()

        # adjust main text and action button
        if self.step == len(STEPS) - 1:
            if self.mw.have_metadata() and self.mw.have_config():
                self.main_text.setText(TEXT_HAPPY_END)
            else:
                self.main_text.setText(TEXT_SAD_END)
        else:
            self.main_text.setText(text)

        if act_label is None:
            self.navbut_actn.hide()
        else:
            self.navbut_actn.show()
            self.navbut_actn.setText(act_label)
            method_to_call = getattr(self, "_act_" + act_func)
            self.navbut_actn.clicked.disconnect()
            self.navbut_actn.clicked.connect(method_to_call)

    def _act_configure(self, _):
        """Open the config dialog."""
        self.mw.open_preferences()

    def _act_update(self, *a):
        """Open the update dialog."""
        self.mw.refresh_episodes()

    def _ign_episode(self):
        """Tell if the episode step should be ignored."""
        return self.mw.have_metadata()

    def _ign_config(self):
        """Tell if the configure step should be ignored."""
        return self.mw.have_config()
Beispiel #3
0
    def __init__(self, student, term, parent=None):
        super(TermPayDialog, self).__init__(parent)
        #term data
        self.term = term
        terms = self.pullOnes('terms', self.term)
        session = self.pullOnes('session', terms['sessionID'])
        self.termname = str(
            session['name']) + ' ' + terms['name'] + ' Term Report'
        self.pagetitle = self.termname

        #student data
        self.student = student
        st = self.pullStudent(self.student)
        fullname = str(st['surname'] + ' ' + st['firstname'] + ' ' +
                       st['othername']).title()
        schno = st['schno']
        db_class = 'student_class' + str(self.term)
        student_clasz = self.pullOne(db_class, {'studentID': self.student})

        clasz = self.pullOne('datas', {'id': student_clasz['classID']})
        self.clasz = clasz['subID']
        armz = self.pullOne('datas', {'id': clasz['subID']})
        classname = armz['abbrv'] + ' ' + clasz['abbrv']
        #pull all CA

        fullNameText = QLabel(fullname)
        schnoText = QLabel(schno)
        classText = QLabel(classname)

        topLay = QGridLayout()
        topLay.addWidget(fullNameText, 0, 0)
        topLay.addWidget(schnoText, 1, 0)
        topLay.addWidget(classText, 2, 0)

        groupBox = QGroupBox('Current Payment')
        groupBox.setLayout(topLay)

        payAmountText = QLabel('Amount')
        self.payBalanceText = QLabel('Balance')
        self.payBalanceAmount = QLabel('0.0')
        self.payAmount = QLineEdit()
        self.payAmount.setObjectName("pay")
        self.payAmount.setPlaceholderText("000.00")
        payText = QLabel('Select Account')
        self.payMethod = QComboBox()
        accounts = self.pullAccount()
        self.holdaccount = {}
        i = 0
        for h in accounts:
            tex = str(h['name']).upper()
            self.payMethod.addItem(tex)
            self.holdaccount[i] = h['id']

        payDateText = QLabel('Balance')
        self.payDate = QDateEdit()
        self.payDate.setDateTime(QDateTime.currentDateTime())
        self.payDate.setCalendarPopup(True)
        tellerText = QLabel('Teller/Receipt No.')
        self.teller = QLineEdit()
        self.teller.setObjectName("teller")
        self.teller.textChanged.connect(self.pullTeller)
        self.teller.setPlaceholderText("0000000")

        self.hw = QGridLayout()
        self.hw.addWidget(payAmountText, 0, 0)
        self.hw.addWidget(self.payAmount, 0, 1)
        self.hw.addWidget(tellerText, 0, 2)
        self.hw.addWidget(self.teller, 0, 3)
        self.hw.addWidget(payText, 1, 0)
        self.hw.addWidget(self.payMethod, 1, 1)
        self.hw.addWidget(payDateText, 1, 2)
        self.hw.addWidget(self.payDate, 1, 3)

        head_col1 = QLabel('ITEM')
        head_col2 = QLabel('AMOUNT')
        head_col3 = QLabel('FULL PAY')
        head_col4 = QLabel('PART PAY')
        head_col5 = QLabel('BALANCE')

        layout1 = QGridLayout()
        layout1.addWidget(head_col1, 0, 0)
        layout1.addWidget(head_col2, 0, 1)
        layout1.addWidget(head_col3, 0, 2)
        layout1.addWidget(head_col4, 0, 3)
        layout1.addWidget(head_col5, 0, 4)

        arr = self.pullFees()
        feex = arr[1]
        payx = arr[2]

        normal_pay = []
        full_pay = []
        part_pay = []
        bal_pay = []
        ko = 1

        self.holdval = []
        self.holdfee = {}
        self.holdtextfee = {}
        self.holdtextfeeperm = {}
        self.holdpaid = {}
        self.holdcpaid = {}
        self.holdtextpaid = {}
        self.holdpayments = {}
        self.holdtextbal = {}
        self.holdbal = {}

        for val in arr[0]:
            paid = False
            s_normal_pay = []
            s_full_pay = []
            s_part_pay = []
            self.holdval.append(val)
            mz = self.pullOne('datas', {'id': val})
            self.num = val
            self.d = QLabel('Text')
            self.d.setText(str(mz['name']).upper())
            self.d1 = QLabel()
            if val in feex:
                fk = feex[int(val)].values()
                normal_pay.append(float(fk[0]))
                s_normal_pay.append(float(fk[0]))
                self.d1.setText(str("{:,}".format(float(fk[0]))).upper())
            else:
                self.d1.setText(str('-.-').upper())

            nHbo1 = QVBoxLayout()
            if val in feex:
                fk = feex[int(val)].values()
                fky = feex[int(val)].keys()
                self.c = QCheckBox('cb' + str(val))
                self.c.setEnabled(False)
                self.c.setText(str("{:,}".format(float(fk[0]))).upper())
                self.c.setObjectName("chk" + str(val))
                self.holdfee[int(val)] = self.c
                self.holdtextfee[int(val)] = fk[0]
                self.holdtextfeeperm[int(val)] = fk[0]
                self.c.toggled.connect(lambda state, x=fky[0], fee=int(
                    val), money=fk[0]: self.chkFunc(x, fee, money, self.c))
                if (val in payx) and len(payx[int(val)]) == 1:
                    pk = payx[int(val)].values()
                    self.c.setChecked(True)
                    if float(pk[0]) == float(fk[0]):
                        full_pay.append(float(fk[0]))
                        s_full_pay.append(float(fk[0]))
                        paid = True
                else:
                    self.c.setChecked(False)
                nHbo1.addWidget(self.c)
            else:
                nHbo1.addWidget(QLabel('-.-'))
                #nHbo1.hide()

            nHbo2 = QHBoxLayout()
            fk = feex[int(val)].values()
            fky = feex[int(val)].keys()
            c2 = QCheckBox()
            c2.setEnabled(False)
            c2.setMaximumWidth(15)
            c2.setObjectName("chk2" + str(val))
            p = QLineEdit()
            p.setDisabled(True)
            p.setMaximumWidth(50)
            p.setFixedWidth(51)
            p.setObjectName("pay" + str(val))
            p.setPlaceholderText("00.0")
            self.holdpaid[int(val)] = p
            self.holdcpaid[int(val)] = c2
            self.holdtextpaid[int(val)] = list()
            c2.toggled.connect(
                lambda state, x=fky[0], fee=int(val): self.chkFunc1(x, fee, p))
            if paid == False:
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)
                if val in payx and len(payx[val]) > 0:
                    for j in payx[int(val)]:
                        self.c1 = QCheckBox('cb1' + str(j))
                        self.c1.setEnabled(False)
                        self.c1.setText(str(payx[int(val)][j]).upper())
                        self.c1.setObjectName("chk" + str(j))
                        self.c1.toggled.connect(
                            lambda state, x=j: self.chkFunc1(x))
                        self.c1.setChecked(True)
                        part_pay.append(float(fk[0]))
                        s_part_pay.append(float(fk[0]))
                        self.holdpayments[j] = self.c1
                        self.holdtextpaid[val].append(float(fk[0]))
                        nHbo2.addWidget(self.c1)
                else:
                    pass
            else:
                p.hide()
                c2.hide()
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)

            s_tot = sum(s_normal_pay) - (sum(s_full_pay) + sum(s_part_pay))
            bal_pay.append(float(s_tot))
            d2 = QLabel('')
            self.holdbal[int(val)] = d2
            d2.setText(str("{:,}".format(s_tot)).upper())
            self.holdtextbal[int(val)] = s_tot

            layout1.addWidget(self.d, ko, 0)
            layout1.addWidget(self.d1, ko, 1)
            layout1.addLayout(nHbo1, ko, 2)
            layout1.addLayout(nHbo2, ko, 3)
            layout1.addWidget(d2, ko, 4)
            ko += 1

        normal_payx = sum(normal_pay)
        full_payx = sum(full_pay)
        part_payx = sum(part_pay)
        bal_payx = sum(bal_pay)

        self.head_col1 = QLabel('ITEM')
        self.head_col2 = QLabel(str("{:,}".format(normal_payx)).upper())
        self.head_col3 = QLabel(str("{:,}".format(full_payx)).upper())
        self.head_col4 = QLabel(str("{:,}".format(part_payx)).upper())
        self.head_col5 = QLabel(str("{:,}".format(bal_payx)).upper())

        layout1.addWidget(self.head_col1, ko, 0)
        layout1.addWidget(self.head_col2, ko, 1)
        layout1.addWidget(self.head_col3, ko, 2)
        layout1.addWidget(self.head_col4, ko, 3)
        layout1.addWidget(self.head_col5, ko, 4)

        self.hw1 = QGridLayout()
        self.hw1.addWidget(self.payBalanceText, 0, 0)
        self.hw1.addWidget(self.payBalanceAmount, 1, 0)

        second1 = QGridLayout()
        second1.addLayout(self.hw, 0, 0)
        second1.addLayout(layout1, 1, 0)
        second1.addLayout(self.hw1, 2, 0)

        groupBox1 = QGroupBox('Current Payment')
        groupBox1.setLayout(second1)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Fees")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Add")
        self.pb2.setText("Print Receipts")

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb1)
        hbo.addStretch()
        hbo.addWidget(self.pb)
        hbo.addStretch()
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('')
        groupBox2.setLayout(hbo)

        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        grid.addWidget(groupBox1, 1, 0)
        grid.addWidget(groupBox2, 2, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))

        self.setWindowTitle(self.pagetitle)
Beispiel #4
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file ')
        self.infile.returnPressed.connect(self.run)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.infile.setCompleter(self.completer)

        self.menu = QMenu('Base64')
        self.menu.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu, lang='all')

        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to Encode...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['*', 'jpg', 'png', 'webp', 'svg', 'gif', 'webm']])))))
        self.chckbx1 = QCheckBox('Use basic Caesar Cipher (ROT13)')
        self.chckbx1.setToolTip('Use "string".decode("rot13") to Decipher ! ')
        self.chckbx2 = QCheckBox('Use "data:type/subtype;base64,..."')
        self.chckbx2.setChecked(True)
        self.chckbx3 = QCheckBox('Copy encoded output to Clipboard')
        self.chckbx4 = QCheckBox('Use URL-Safe Base64 Encoder')
        self.combo1 = QComboBox()
        self.combo1.addItems(['Do Not Generate Code', 'Generate CSS embed Code',
            'Generate Python Embed Code', 'Generate HTML embed Code',
            'Generate JS embed Code', 'Generate QML embed Code'])
        self.combo1.currentIndexChanged.connect(self.combo_changed)

        self.output = QTextEdit('''
        We can only see a short distance ahead,
        but we can see plenty there that needs to be done.
        - Alan Turing ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton(QIcon.fromTheme("face-cool"), 'Encode BASE64')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>Encode file as plain text string</i>'),
            QLabel('<b>File to Encode:'), self.infile, self.open, self.chckbx2,
            self.chckbx3, self.chckbx1, self.chckbx4,
            QLabel('<b>Embedding Template Code:'), self.combo1,
            QLabel(' <b>Base64 String Output: '), self.output,
            QLabel('<center><small><i>' + ''.join((__doc__, __version__,
                   __license__, 'by', __author__))), self.button
        ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Base64")
        self.guimode = QComboBox(self.dock)
        self.guimode.addItems(['Full Mode', 'Simple Mode'])
        self.guimode.currentIndexChanged.connect(self.guimode_change)

    def guimode_change(self):
        """ Change from Simple Mode to Full Mode by Hide or Show Widgets """
        if self.guimode.currentIndex() is 0:
            self.chckbx1.show()
            self.chckbx2.show()
            self.chckbx3.show()
            self.chckbx4.show()
        else:
            self.chckbx1.hide()
            self.chckbx2.hide()
            self.chckbx3.hide()
            self.chckbx4.hide()
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(True)
            self.chckbx3.setChecked(False)
            self.chckbx4.setChecked(False)

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu.clear()
        if self.ex_locator.get_current_project_item().isFolder is not True:
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            self.menu.addActions([
                QAction('Copy {} as Base64'.format(path.basename(filenam)[:50]),
                        self, triggered=lambda:
                        QApplication.clipboard().setText(
                        '"data:{};charset=utf-8;base64,{}"'.format(
                            guess_type(filenam, strict=False)[0],
                            b64encode(open(filenam, "rb").read())))),
                QAction('Copy {} as Base64 URL-Safe'.format(
                        path.basename(filenam)[:50]),
                        self, triggered=lambda:
                        QApplication.clipboard().setText(
                        '"data:{};charset=utf-8;base64,{}"'.format(
                            guess_type(filenam, strict=False)[0],
                            urlsafe_b64encode(open(filenam, "rb").read()))))])
            self.menu.show()

    def run(self):
        ' run the encoding '
        mimetype = guess_type(str(self.infile.text()).strip(), strict=False)[0]
        _mime = mimetype if mimetype is not None else self.ask_mime()
        fle = str(self.infile.text()).strip().replace('file:///', '/')
        encoder = urlsafe_b64encode if self.chckbx4.isChecked() else b64encode
        if int(path.getsize(fle)) / 1024 / 1024 >= 1:
            QMessageBox.information(self.dock, __doc__,
            '''<b style="color:red"> WARNING!: File size is > 1 Megabyte!,<br>
            this will take some time, depending your CPU Processing power!.''')
        output = '"{}{}{}{}"'.format(
            'data:' if self.chckbx2.isChecked() is True else '',
            _mime if self.chckbx2.isChecked() is True else '',
           ';charset=utf-8;base64,' if self.chckbx2.isChecked() is True else '',
            encoder(open(fle, "rb").read()))
        if self.combo1.currentIndex() is 1:
            output = ('html, body { margin:0; padding:0; background: url(' +
            output + ') no-repeat center center fixed; background-size:cover }')
        elif self.combo1.currentIndex() is 2:
            output = PY_EMBED.format(getuser(),
                     datetime.now().isoformat().split('.')[0], output)
        elif self.combo1.currentIndex() is 3:
            output = '<img src={} alt="{}" title="{}"/>'.format(output,
                     fle.split(sep)[-1], fle.split(sep)[-1])
        elif self.combo1.currentIndex() is 4:
            output = 'var embedded_file = window.atob({}); '.format(output)
        elif self.combo1.currentIndex() is 5:
            output = 'Image { source: ' + output + ' } '
        if self.chckbx1.isChecked() is True:
            output = str(output).encode('rot13')
        if self.chckbx3.isChecked() is True:
            QApplication.clipboard().setText(output)
        self.output.setPlainText(output)
        self.output.setFocus()
        self.output.selectAll()

    def ask_mime(self):
        ' ask user for mime type '
        return str(QInputDialog.getText(self.dock, __doc__, 'Write a MIME-Type',
               QLineEdit.Normal, 'application/octet-stream')[0]).strip().lower()

    def combo_changed(self):
        ' on combo changed '
        if self.combo1.currentIndex() is 1 or self.combo1.currentIndex() is 3:
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(True)
        elif self.combo1.currentIndex() is 2 or self.combo1.currentIndex() is 4:
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(False)
Beispiel #5
0
class History(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF

        self.BOOK = {
            "bought": [],
            "sold": []
        }

        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 975, 555)
        self.setStyleSheet(
            "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_History.png'); }"
        )

        self.PAIR_COMBO = QComboBox(self)
        self.PAIR_COMBO.setGeometry(86, 20, 108, 44)
        self.connect(self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'),
                     self.CREATE_LISTS)
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False)
        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_History_line.png'); }"
        # ./data/imgs/BookKeeping_line.png
        lable_style = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"
        # -------------------------------------------------------------------

        # Bought
        self.BOOKKEEPING_BOUGHT_WIDGET = QListWidget(self)
        self.BOOKKEEPING_BOUGHT_WIDGET.setGeometry(13, 144, 469, 400)
        self.BOOKKEEPING_BOUGHT_WIDGET.setStyleSheet(list_style)

        self.connect(
            self.BOOKKEEPING_BOUGHT_WIDGET, SIGNAL('itemSelectionChanged()'),
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("BOUGHT_WIDGET"))
        self.BOOKKEEPING_BOUGHT_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("BOUGHT_WIDGET"))

        self.BOUGHT_TTL_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_LABLE.setGeometry(272, 406, 85, 17)
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_LABLE.hide()
        self.BOUGHT_TTL = 0

        self.BOUGHT_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry(362, 406, 118, 17)
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.hide()
        self.BOUGHT_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        # Sold
        self.LAST_ACTIVE_WIDGET = None

        self.BOOKKEEPING_SOLD_WIDGET = QListWidget(self)
        self.BOOKKEEPING_SOLD_WIDGET.setGeometry(493, 144, 469, 400)
        self.BOOKKEEPING_SOLD_WIDGET.setStyleSheet(list_style)

        self.connect(self.BOOKKEEPING_SOLD_WIDGET,
                     SIGNAL('itemSelectionChanged()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))
        self.BOOKKEEPING_SOLD_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))

        self.SOLD_TTL_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_LABLE.setGeometry(752, 406, 85, 17)
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_LABLE.hide()
        self.SOLD_TTL = 0

        self.SOLD_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry(842, 406, 118, 17)
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_PLUS_FEE_LABLE.hide()
        self.SOLD_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        """
        self.DATA_TO_SEND                   = None;

        self.SEND_ID_LABLE                  = QLabel("n/a", self);
        self.SEND_ID_LABLE.setGeometry( 18, 467, 43, 17 );
        self.SEND_ID_LABLE.setStyleSheet( lable_style );

        self.SEND_AMOUNT_LABLE              = QLabel("n/a", self);
        self.SEND_AMOUNT_LABLE.setGeometry( 66, 467, 85, 17 );
        self.SEND_AMOUNT_LABLE.setStyleSheet( lable_style );

        self.SEND_AT_PRICE_LABLE            = QLabel("n/a", self);
        self.SEND_AT_PRICE_LABLE.setGeometry( 156, 467, 43, 17 );
        self.SEND_AT_PRICE_LABLE.setStyleSheet( lable_style );

        self.SEND_VALUES_BTN                = QPushButton("", self); 
        self.SEND_VALUES_BTN.setGeometry( 60, 502, 131, 33 );
        self.SEND_VALUES_BTN.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        self.connect( self.SEND_VALUES_BTN, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );
        """

        # -------------------------------------------------------------------
        self._i_ = "|"
        # List delimiter

        # -------------------------------------------------------------------
        self.ONLY_FILLED_CHECKBOX = QCheckBox("", self)
        self.ONLY_FILLED_CHECKBOX.setGeometry(647, 444, 17, 17)
        self.ONLY_FILLED_CHECKBOX.setCheckState(Qt.Checked)
        #self.ONLY_FILLED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_FILLED_CHECKBOX, SIGNAL('stateChanged(int)'),
                     lambda: self.CHANGE_VALUES("only_filled"))
        self.ONLY_FILLED_CHECKBOX.hide()

        self.CALCULATE_ONLY_FILLED = True
        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR()
            self.CREATE_LISTS()

        except Exception as _exception:
            print("-----------------------------------------------------")
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower()

        # -------------------------------------------------------------------
        self.BOOK = {
            "bought": [],
            "sold": []
        }

        self.BOUGHT_TTL = 0
        self.BOUGHT_TTL_PLUS_FEE = 0

        self.SOLD_TTL = 0
        self.SOLD_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        # Bought List
        # id, order_id, unix_time, action, filled, amount, at_price, fee, ttl, grand_ttl

        #self.PARENT.DB.EXEC( "HISTORY_DB", "DELETE FROM "+CURR_PAIR+" WHERE id>7" );

        DATA = self.PARENT.DB.FETCH("HISTORY_DB",
                                    "SELECT * FROM " + CURR_PAIR +
                                    " WHERE action='bought' ORDER BY id DESC",
                                    ALL=True)
        self.BOOKKEEPING_BOUGHT_WIDGET.clear()

        for data in DATA:

            # ---------------------------------------------------------------
            # In-Memory DATA

            self.BOOK[data[3]].append({
                "id": data[0],
                "order_id": data[1],
                "unix_time": data[2],
                "action": data[3],
                "filled": data[4],
                "amount": data[5],
                "at_price": data[6],
                "fee": data[7],
                "ttl": data[8],
                "grand_ttl": data[9]
            })

            if self.CALCULATE_ONLY_FILLED:
                if data[4] == 1:
                    self.BOUGHT_TTL += data[8]
                    self.BOUGHT_TTL_PLUS_FEE += data[9]

            else:
                self.BOUGHT_TTL += data[8]
                self.BOUGHT_TTL_PLUS_FEE += data[9]

            # ---------------------------------------------------------------
            # Formatinf data to Display in BookKeeping Wodget

            item = ""

            item += "DEL{:6} DEL".format(str(data[0]))
            # id
            #item += "{:11} DEL".format( data[1] ); # order_id
            #item += "{:11} DEL".format( data[2] ); # unix_time
            #item += "{:11} DEL".format( data[3] ); # action
            #item += "{:11} DEL".format( data[4] ); # filed
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[5])).strip())
            # Amount
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[6])).strip())
            # at_price
            #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[8])).strip())
            # ttl
            item += "{:13}".format(str("{:10,.6f}".format(data[9])).strip())
            # grand_ttl

            #self.BOOKKEEPING_BOUGHT_WIDGET.addItem( item.replace("DEL", self._i_) );
            newItem = QListWidgetItem(
                QIcon("./data/imgs/icon_filled_status_" + str(data[4]) +
                      ".png"), item.replace("DEL", self._i_),
                self.BOOKKEEPING_BOUGHT_WIDGET, 0)
            newItemToolTip = "Order ID: #" + str(
                data[1]) + " Created: " + time.ctime(int(data[2]))

            newItem.setToolTip(newItemToolTip)

            # ---------------------------------------------------------------
        # / for
        # -------------------------------------------------------------------
        self.BOUGHT_TTL_LABLE.setText(
            str("{:10,.6f}".format(self.BOUGHT_TTL).strip()))
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setText(
            str("{:10,.6f}".format(self.BOUGHT_TTL_PLUS_FEE).strip()))

        # -------------------------------------------------------------------
        # Sold List
        # id, order_id, unix_time, action, filled, amount, at_price, fee, ttl, grand_ttl

        DATA = self.PARENT.DB.FETCH("HISTORY_DB",
                                    "SELECT * FROM " + CURR_PAIR +
                                    " WHERE action='sold' ORDER BY id DESC",
                                    ALL=True)
        self.BOOKKEEPING_SOLD_WIDGET.clear()

        for data in DATA:

            # ---------------------------------------------------------------
            # In-Memory DATA

            self.BOOK[data[3]].append({
                "id": data[0],
                "order_id": data[1],
                "unix_time": data[2],
                "action": data[3],
                "filled": data[4],
                "amount": data[5],
                "at_price": data[6],
                "fee": data[7],
                "ttl": data[8],
                "grand_ttl": data[9]
            })

            if self.CALCULATE_ONLY_FILLED:
                if data[4] == 1:
                    self.SOLD_TTL += data[8]
                    self.SOLD_TTL_PLUS_FEE += data[9]

            else:
                self.SOLD_TTL += data[8]
                self.SOLD_TTL_PLUS_FEE += data[9]

            # ---------------------------------------------------------------
            # Formatinf data to Display in BookKeeping Wodget

            item = ""

            item += "DEL{:6} DEL".format(str(data[0]))
            # id
            #item += "{:11} DEL".format( data[1] ); # order_id
            #item += "{:11} DEL".format( data[2] ); # unix_time
            #item += "{:11} DEL".format( data[3] ); # action
            #item += "{:11} DEL".format( data[4] ); # filed
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[5])).strip())
            # Amount
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[6])).strip())
            # at_price
            #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[8])).strip())
            # ttl
            item += "{:13}".format(str("{:10,.6f}".format(data[9])).strip())
            # grand_ttl

            #self.BOOKKEEPING_SOLD_WIDGET.addItem( item.replace("DEL", self._i_) );
            newItem = QListWidgetItem(
                QIcon("./data/imgs/icon_filled_status_" + str(data[4]) +
                      ".png"), item.replace("DEL", self._i_),
                self.BOOKKEEPING_SOLD_WIDGET, 0)

            newItemToolTip = "Order ID: #" + str(
                data[1]) + " Created: " + time.ctime(int(data[2]))

            newItem.setToolTip(newItemToolTip)
            # ---------------------------------------------------------------
        # / for
        # -------------------------------------------------------------------
        self.SOLD_TTL_LABLE.setText(
            str("{:10,.6f}".format(self.SOLD_TTL).strip()))
        self.SOLD_TTL_PLUS_FEE_LABLE.setText(
            str("{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE).strip()))

        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_filled":
            if self.ONLY_FILLED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_FILLED = True
            else:
                self.CALCULATE_ONLY_FILLED = False

        # -------------------------------------------------------------------
        self.CREATE_LISTS()
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData(i, QColor("#333"), Qt.BackgroundRole)
            self.PAIR_COMBO.setItemData(i, QColor("#fff"), Qt.ForegroundRole)
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "BOUGHT_WIDGET":

            self.LAST_ACTIVE_WIDGET = "BOUGHT_WIDGET"
            self.DATA_TO_SEND = str(self.BOOKKEEPING_BOUGHT_WIDGET.currentItem(
            ).text()).strip().split("|")

            #self.SEND_ID_LABLE.setFocus();

        elif _action == "SOLD_WIDGET":

            self.LAST_ACTIVE_WIDGET = "SOLD_WIDGET"
            self.DATA_TO_SEND = str(self.BOOKKEEPING_SOLD_WIDGET.currentItem().
                                    text()).strip().split("|")

            #self.SEND_ID_LABLE.setFocus();

        elif _action == "SEND_VALUES":

            if self.LAST_ACTIVE_WIDGET is not None:

                self.PARENT.GUI.USER_SELL_AMOUNT.setText(
                    self.DATA_TO_SEND[2].strip())
                self.PARENT.GUI.USER_SELL_AT_PRICE.setText(
                    self.DATA_TO_SEND[3].strip())

                self.PARENT.GUI.USER_BUY_AMOUNT.setText(
                    self.DATA_TO_SEND[2].strip())
                self.PARENT.GUI.USER_BUY_AT_PRICE.setText(
                    self.DATA_TO_SEND[3].strip())

                self.LAST_ACTIVE_WIDGET = None
                self.DATA_TO_SEND = None

                # Show Tradeer Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0)

                # Clear Lables
                self.SEND_ID_LABLE.setText("n/a")
                self.SEND_AMOUNT_LABLE.setText("n/a")
                self.SEND_AT_PRICE_LABLE.setText("n/a")

            else:

                self.PARENT.GUI.SHOW_QMESSAGE(
                    "info",
                    " Select first item which one you would like<br/> send to the Trade-Terminal !"
                )
                return

        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:

            self.SEND_ID_LABLE.setText(self.DATA_TO_SEND[1])
            self.SEND_AMOUNT_LABLE.setText(self.DATA_TO_SEND[2])
            self.SEND_AT_PRICE_LABLE.setText(self.DATA_TO_SEND[3])

        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # ------------------------------------------------------------------
        self.PARENT.DB.EXEC(
            "HISTORY_DB",
            "DELETE FROM " + _pair + " WHERE order_id=" + str(_order_id))
Beispiel #6
0
class WizardDialog(QDialog):
    """The dialog for update."""
    def __init__(self, main_window):
        super(WizardDialog, self).__init__()
        self.mw = main_window
        vbox = QVBoxLayout(self)

        # label and checkbox
        self.main_text = QLabel(u"init text")
        vbox.addWidget(self.main_text)
        self.notthisagain = QCheckBox(u"No mostrar automáticamente esta ayuda")
        nowizard = config.get('nowizard', False)
        self.notthisagain.setCheckState(nowizard)
        self.notthisagain.stateChanged.connect(self._notthisagain_toggled)
        vbox.addWidget(self.notthisagain)

        # buttons
        bbox = QDialogButtonBox()
        self.navbut_actn = QPushButton(u"init text")
        bbox.addButton(self.navbut_actn, QDialogButtonBox.ActionRole)
        self.navbut_prev = QPushButton(u"Anterior")
        bbox.addButton(self.navbut_prev, QDialogButtonBox.ActionRole)
        self.navbut_next = QPushButton(u"Siguiente")
        bbox.addButton(self.navbut_next, QDialogButtonBox.ActionRole)
        vbox.addWidget(bbox)

        self.show()
        self.step = 0
        self._move(0)

    def _notthisagain_toggled(self, state):
        """The "not this again" checkbutton togled state."""
        logger.info("Configuring 'nowizard' to %s", state)
        config['nowizard'] = state

    def _move(self, delta_step):
        """The engine for the wizard steps."""
        self.step += delta_step
        logger.debug("Entering into step %d", self.step)
        (text, ign_func, act_label, act_func) = STEPS[self.step]
        # if this step should be ignored, just leave
        if ign_func is not None:
            m = getattr(self, "_ign_" + ign_func)
            if m():
                # keep going
                return self._move(delta_step)

        # adjust navigation buttons
        if self.step == 0:
            self.navbut_prev.setEnabled(False)
            self.navbut_next.setText(u"Siguiente")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(lambda: self._move(1))
            self.notthisagain.show()
        elif self.step == len(STEPS) - 1:
            self.navbut_prev.setEnabled(True)
            self.navbut_prev.clicked.disconnect()
            self.navbut_prev.clicked.connect(lambda: self._move(-1))
            self.navbut_next.setText(u"Terminar")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(self.accept)
            self.notthisagain.hide()
        else:
            self.navbut_prev.setEnabled(True)
            self.navbut_prev.clicked.disconnect()
            self.navbut_prev.clicked.connect(lambda: self._move(-1))
            self.navbut_next.setText(u"Siguiente")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(lambda: self._move(1))
            self.notthisagain.hide()

        # adjust main text and action button
        if self.step == len(STEPS) - 1:
            if self.mw.have_metadata() and self.mw.have_config():
                self.main_text.setText(TEXT_HAPPY_END)
            else:
                self.main_text.setText(TEXT_SAD_END)
        else:
            self.main_text.setText(text)

        if act_label is None:
            self.navbut_actn.hide()
        else:
            self.navbut_actn.show()
            self.navbut_actn.setText(act_label)
            method_to_call = getattr(self, "_act_" + act_func)
            self.navbut_actn.clicked.disconnect()
            self.navbut_actn.clicked.connect(method_to_call)

    def _act_configure(self, _):
        """Open the config dialog."""
        self.mw.open_preferences()

    def _act_update(self, *a):
        """Open the update dialog."""
        self.mw.refresh_episodes()

    def _ign_episode(self):
        """Tell if the episode step should be ignored."""
        return self.mw.have_metadata()

    def _ign_config(self):
        """Tell if the configure step should be ignored."""
        return self.mw.have_config()