class LabelDistributionOptionsDlg( QDialog ):
            """
            A little dialog to let the user specify how the labels should be
            distributed from the current stages to the other stages.
            """
            def __init__(self, source_stage_index, num_stages, *args, **kwargs):
                super(LabelDistributionOptionsDlg, self).__init__(*args, **kwargs)

                from PyQt5.QtCore import Qt
                from PyQt5.QtWidgets import QGroupBox, QCheckBox, QRadioButton, QDialogButtonBox
            
                self.setWindowTitle("Distributing from Stage {}".format(source_stage_index+1))

                self.stage_checkboxes = []
                for stage_index in range(1, num_stages+1):
                    self.stage_checkboxes.append( QCheckBox("Stage {}".format( stage_index )) )
                
                # By default, send labels back into the current stage, at least.
                self.stage_checkboxes[source_stage_index].setChecked(True)
                
                stage_selection_layout = QVBoxLayout()
                for checkbox in self.stage_checkboxes:
                    stage_selection_layout.addWidget( checkbox )

                stage_selection_groupbox = QGroupBox("Send labels from Stage {} to:".format( source_stage_index+1 ), self)
                stage_selection_groupbox.setLayout(stage_selection_layout)
                
                self.copy_button = QRadioButton("Copy", self)
                self.partition_button = QRadioButton("Partition", self)
                self.partition_button.setChecked(True)
                distribution_mode_layout = QVBoxLayout()
                distribution_mode_layout.addWidget(self.copy_button)
                distribution_mode_layout.addWidget(self.partition_button)
                
                distribution_mode_group = QGroupBox("Distribution Mode", self)
                distribution_mode_group.setLayout(distribution_mode_layout)
                
                buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self )
                buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel )
                buttonbox.accepted.connect( self.accept )
                buttonbox.rejected.connect( self.reject )
                
                dlg_layout = QVBoxLayout()
                dlg_layout.addWidget(stage_selection_groupbox)
                dlg_layout.addWidget(distribution_mode_group)
                dlg_layout.addWidget(buttonbox)
                self.setLayout(dlg_layout)

            def distribution_mode(self):
                if self.copy_button.isChecked():
                    return "copy"
                if self.partition_button.isChecked():
                    return "partition"
                assert False, "Shouldn't get here."
            
            def destination_stages(self):
                """
                Return the list of stage_indexes (0-based) that the user checked.
                """
                return [ i for i,box in enumerate(self.stage_checkboxes) if box.isChecked() ]
Example #2
0
class StartSession(preferences.Group):
    def __init__(self, page):
        super(StartSession, self).__init__(page)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.custom.isChecked())
        
        self.none = QRadioButton(toggled=changed)
        self.lastused = QRadioButton(toggled=changed)
        self.custom = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)
        
        grid.addWidget(self.none, 0, 0, 1, 2)
        grid.addWidget(self.lastused, 1, 0, 1, 2)
        grid.addWidget(self.custom, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)

        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Session to load if Frescobaldi is started without arguments"))
        self.none.setText(_("Start with no session"))
        self.lastused.setText(_("Start with last used session"))
        self.custom.setText(_("Start with session:"))
        
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("session")
        startup = s.value("startup", "none", str)
        if startup ==  "lastused":
            self.lastused.setChecked(True)
        elif startup == "custom":
            self.custom.setChecked(True)
        else:
            self.none.setChecked(True)
        sessionNames = sessions.sessionNames()
        self.combo.clear()
        self.combo.addItems(sessionNames)
        custom = s.value("custom", "", str)
        if custom in sessionNames:
            self.combo.setCurrentIndex(sessionNames.index(custom))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("session")
        s.setValue("custom", self.combo.currentText())
        if self.custom.isChecked():
            startup = "custom"
        elif self.lastused.isChecked():
            startup = "lastused"
        else:
            startup = "none"
        s.setValue("startup", startup)
Example #3
0
class QtUserTypeSelectionDialog(QDialog):
    """A modal dialog presenting the user with options for what kind of
    user to sign in as.
    """

    def __init__(self, message, parent=None):
        super(QtUserTypeSelectionDialog, self).__init__(parent)

        lbl_message = QLabel(message, self)

        self.rb_tutor = QRadioButton('Tutor', self)
        self.rb_student = QRadioButton('Student', self)
        self.rb_tutor.setFocusPolicy(Qt.StrongFocus)
        self.rb_student.setFocusPolicy(Qt.StrongFocus)

        radio_vbox = QVBoxLayout()
        radio_vbox.addWidget(self.rb_tutor)
        radio_vbox.addWidget(self.rb_student)

        radios = QGroupBox(self)
        radios.setLayout(radio_vbox)

        btn_sign_in = QPushButton('Sign In', self)
        btn_sign_in.setDefault(True)
        btn_sign_in.setAutoDefault(True)
        btn_cancel = QPushButton('Cancel', self)
        btn_cancel.setAutoDefault(True)

        btn_sign_in.clicked.connect(self.update_user_type)
        btn_cancel.clicked.connect(self.reject)

        self.rb_tutor.setChecked(True)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(btn_sign_in)
        hbox.addWidget(btn_cancel)

        vbox = QVBoxLayout()
        vbox.addWidget(lbl_message)
        vbox.addWidget(radios)
        vbox.addStretch(1)
        vbox.addLayout(hbox)

        self.setLayout(vbox)
        self.setWindowTitle('User Type Selection')

    def update_user_type(self):
        """Return either 'tutor' or 'student' based on which radio
        button is selected.
        """
        if self.rb_tutor.isChecked():
            self.user_type = 'tutor'
        elif self.rb_student.isChecked():
            self.user_type = 'student'
        self.accept()
Example #4
0
class OnOffToggleWidget(QWidget):
    """
    A widget that contains a label and two 'On'/'Off' radio buttons on a
    single horizontal row.
    """

    def __init__(self, label='', value=True, parent=None):
        super(OnOffToggleWidget, self).__init__(parent)
        self.setup(label, value)

    def setup(self, label, value):
        """Setup the widget with the provided options."""
        self.toggle_on = QRadioButton('On')
        self.toggle_off = QRadioButton('Off')
        self.set_value(value)

        layout = QGridLayout(self)
        layout.addWidget(QLabel(label + ' :'), 0, 0)
        layout.addWidget(self.toggle_on, 0, 2)
        layout.addWidget(self.toggle_off, 0, 3)
        layout.setColumnStretch(1, 100)
        layout.setContentsMargins(0, 0, 0, 0)

    def value(self):
        """Return True if the toggle is 'On' and False if it is 'Off'."""
        return self.toggle_on.isChecked()

    def set_value(self, value):
        """Set to 'On' if value is True and set to 'Off' if it is False."""
        if value:
            self.toggle_on.toggle()
        else:
            self.toggle_off.toggle()
Example #5
0
class FilterConfigDialog(ConfigDialog):

    def __init__(self, mode=None, params=None):
        super().__init__()
        self.initUI()
        self.setSelectedFilterMode(mode)
        self.kSizeSlider.initValueAndRange(minimum=2, maximum=20, value=params["ksize"])
        self.sigmaSlider.initValueAndRange(value=params["sigma"])

    def initUI(self):
        super().initUI()
        self.setWindowTitle("フィルタリング(ぼかし)設定")
        self.layout = QGridLayout()
        self.gaussBtn = QRadioButton("Gaussianフィルタ")
        self.aveBtn = QRadioButton("移動平均フィルタ")
        self.kSizeSlider = HorizontalSlider()
        self.sigmaSlider = HorizontalSlider()
        self.kSizeTextLine = TextLine(text=str(self.kSizeSlider.value()),
                                                    width=50, readmode=True)
        self.sigmaTextLine = TextLine(text=str(self.sigmaSlider.value()),
                                                    width=50, readmode=True)
        self.kSizeSlider.valueChanged[int].connect(self.changedKSizeSliderValue)
        self.sigmaSlider.valueChanged[int].connect(self.changedSigmaSliderValue)
        self.layout.addWidget(self.gaussBtn, 0, 0)
        self.layout.addWidget(self.aveBtn, 0, 1)
        self.layout.addWidget(QLabel("フィルタサイズ"), 1, 0, Qt.AlignCenter)
        self.layout.addWidget(self.kSizeSlider, 1, 1, 1, 2)
        self.layout.addWidget(self.kSizeTextLine, 1, 4)
        self.layout.addWidget(QLabel("分散"), 2, 0, Qt.AlignCenter)
        self.layout.addWidget(self.sigmaSlider, 2, 1, 1, 2)
        self.layout.addWidget(self.sigmaTextLine, 2, 4)
        self.layout.addWidget(self.btnBox, 4, 4)
        self.setLayout(self.layout)

    """フィルタリング設定モードUI反映処理"""
    def setSelectedFilterMode(self, mode):
        if mode == Constant.GAUSSIAN_FILTER_MODE or mode is None:
            self.gaussBtn.setChecked(True)
        else:
            self.aveBtn.setChecked(True)

    """フィルタリング設定モード取得処理"""
    def getSelectedFilterMode(self):
        if self.gaussBtn.isChecked():
            return Constant.GAUSSIAN_FILTER_MODE
        else:
            return Constant.AVERAGE_FILTER_MODE

    """フィルタリング設定パラメータ値取得処理"""
    def getSelectedFilterConfig(self):
        filterParams = {"ksize": self.kSizeSlider.value(),
                        "sigma": self.sigmaSlider.value()}
        return self.getSelectedFilterMode(), filterParams

    """スライダー値変更反映処理"""
    def changedKSizeSliderValue(self, value):
        self.kSizeTextLine.setText(str(value))

    def changedSigmaSliderValue(self, value):
        self.sigmaTextLine.setText(str(value))
Example #6
0
def radio_dialog(options, name='Selection', default_idx=0):

    ok = False
    def _pressed_ok():
        nonlocal ok
        w.close()
        app.quit()
        ok |= True
    def _pressed_cancel():
        nonlocal ok
        w.close()
        app.quit()
        ok &= False

    app = QCoreApplication.instance() or QApplication([])

    w = QWidget()
    w.setWindowTitle(name)
    grid = QGridLayout()
    grid.setSpacing(10)
    edit = []
    for i in range(len(options)):
        r = QRadioButton(options[i])
        if i == default_idx:
            r.setChecked(True)
        edit.append(r)
        grid.addWidget(r,0,i)



    #Ok Button
    qbtn = QPushButton('Ok', w)
    qbtn.clicked.connect(_pressed_ok)
    qbtn.resize(qbtn.sizeHint())
    grid.addWidget(qbtn, 2*(i+1), 0)
    #Cancel Button
    qbtn = QPushButton('Cancel', w)
    qbtn.clicked.connect(_pressed_cancel)
    qbtn.resize(qbtn.sizeHint())
    grid.addWidget(qbtn, 2*(i+1), 1)

    #Defining the layout of the window:
    w.setLayout(grid)
    w.resize(50, i*50)
    qr = w.frameGeometry()
    cp = QDesktopWidget().availableGeometry().center()
    qr.moveCenter(cp)
    w.move(qr.topLeft())

    w.show()
    app.exec_()

    for r in edit:
        if r.isChecked(): text = r.text()
    return ok, text
Example #7
0
    def __init__(self, result):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.result = result
        observation_window = result.observation_window

        group = QButtonGroup(self)
        use_simu_duration = QRadioButton("Use entire simulation.")
        use_simu_duration.setChecked(
            observation_window[0] == 0
            and observation_window[1] == result.model.duration)
        group.addButton(use_simu_duration)
        self.layout.addWidget(use_simu_duration)

        use_custom = QRadioButton("Use a custom observation window:")
        use_custom.setChecked(not use_simu_duration.isChecked())
        group.addButton(use_custom)
        self.layout.addWidget(use_custom)

        self._slider = QxtSpanSliderWidget(
            0, result.model.now() // result.model.cycles_per_ms, self)
        self._slider.setSpan(
            observation_window[0] // result.model.cycles_per_ms,
            observation_window[1] // result.model.cycles_per_ms)
        self._slider.setEnabled(use_custom.isChecked())
        group.buttonClicked.connect(
            lambda x: self._slider.setEnabled(x == use_custom))

        self.layout.addWidget(self._slider)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)
Example #8
0
class CopyConfigDialog(ConfigDialog):

    def __init__(self, mode=None):
        super().__init__()
        self.__initUI()
        self.setSelectedCopyMode(mode)

    def __initUI(self):
        super().initUI()
        self.setWindowTitle("画像コピー設定")
        self.layout = QGridLayout()
        self.radioGroup = QButtonGroup()
        self.radioButton1 = QRadioButton("左右反転")
        self.radioButton2 = QRadioButton("上下反転")
        self.radioButton3 = QRadioButton("左右上下反転")
        self.radioGroup.addButton(self.radioButton1)
        self.radioGroup.addButton(self.radioButton2)
        self.radioGroup.addButton(self.radioButton3)
        self.layout.addWidget(self.radioButton1, 0, 0)
        self.layout.addWidget(self.radioButton2, 1, 0)
        self.layout.addWidget(self.radioButton3, 2, 0)
        self.layout.addWidget(self.btnBox, 3, 1)
        self.setLayout(self.layout)

    """コピー設定モードUI反映処理"""
    def setSelectedCopyMode(self, mode):
        if mode == Constant.LR_REVERSAL_MODE or mode is None:
            self.radioButton1.setChecked(True)
        elif mode == Constant.TB_REVERSAL_MODE:
            self.radioButton2.setChecked(True)
        else:
            self.radioButton3.setChecked(True)

    """コピー設定モード取得処理"""
    def getSelectedCopyMode(self):
        if self.radioButton1.isChecked():
            return Constant.LR_REVERSAL_MODE
        elif self.radioButton2.isChecked():
            return Constant.TB_REVERSAL_MODE
        else:
            return Constant.LRTB_REVERSAL_MODE
Example #9
0
class Target(preferences.Group):
    def __init__(self, page):
        super(Target, self).__init__(page)
        
        layout = QGridLayout()
        self.setLayout(layout)
        
        self.targetPDF = QRadioButton(toggled=page.changed)
        self.targetSVG = QRadioButton(toggled=page.changed)
        self.openDefaultView = QCheckBox(clicked=page.changed)
        
        layout.addWidget(self.targetPDF, 0, 0)
        layout.addWidget(self.targetSVG, 0, 1)
        layout.addWidget(self.openDefaultView, 1, 0, 1, 5)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Default output format"))
        self.targetPDF.setText(_("PDF"))
        self.targetPDF.setToolTip(_(
            "Create PDF (Portable Document Format) documents by default."))
        self.targetSVG.setText(_("SVG"))
        self.targetSVG.setToolTip(_(
            "Create SVG (Scalable Vector Graphics) documents by default."))
        self.openDefaultView.setText(_("Open default viewer after successful compile"))
        self.openDefaultView.setToolTip(_(
            "Shows the PDF or SVG music view when a compile job finishes "
            "successfully."))
    
    def loadSettings(self):
        s = settings()
        target = s.value("default_output_target", "pdf", str)
        if target == "svg":
            self.targetSVG.setChecked(True)
            self.targetPDF.setChecked(False)
        else:
            self.targetSVG.setChecked(False)
            self.targetPDF.setChecked(True)
        self.openDefaultView.setChecked(s.value("open_default_view", True, bool))
        
    def saveSettings(self):
        s = settings()
        if self.targetSVG.isChecked():
            target = "svg"
        else:
            target = "pdf"
        s.setValue("default_output_target", target)
        s.setValue("open_default_view", self.openDefaultView.isChecked())
Example #10
0
class Book(_base.Group):
    @staticmethod
    def title(_=_base.translate):
        return _("Book")

    def accepts(self):
        return (BookPart, Score, StaffGroup, _base.Part)

    def createWidgets(self, layout):
        self.bookOutputInfo = QLabel(wordWrap=True)
        self.bookOutputLabel = QLabel()
        self.bookOutput = widgets.lineedit.LineEdit()
        self.bookOutputFileName = QRadioButton()
        self.bookOutputSuffix = QRadioButton(checked=True)
        
        layout.addWidget(self.bookOutputInfo)
        grid = QGridLayout(spacing=0)
        grid.addWidget(self.bookOutputLabel, 0, 0)
        grid.addWidget(self.bookOutput, 0, 1, 1, 2)
        grid.addWidget(self.bookOutputFileName, 1, 1)
        grid.addWidget(self.bookOutputSuffix, 1, 2)
        layout.addLayout(grid)
    
    def translateWidgets(self):
        self.bookOutputInfo.setText(_(
            "<p>Here you can specify a filename or suffix (without extension) "
            "to set the names of generated output files for this book.</p>\n"
            "<p>If you choose \"Suffix\" the entered name will be appended "
            "to the document's file name; if you choose \"Filename\", just "
            "the entered name will be used.</p>"))
        self.bookOutputLabel.setText(_("Output Filename:"))
        self.bookOutputFileName.setText(_("Filename"))
        self.bookOutputSuffix.setText(_("Suffix"))

    def makeNode(self, node):
        book = ly.dom.Book(node)
        name = self.bookOutput.text().strip()
        if name:
            cmd = 'bookOutputName' if self.bookOutputFileName.isChecked() else 'bookOutputSuffix'
            ly.dom.Line(r'\{0} "{1}"'.format(cmd, name.replace('"', r'\"')), book)
        return book
Example #11
0
class RadioParameter:
    def __init__(self, text, checked):

        self.text = QLabel(text)

        self.layout = QHBoxLayout()

        self.group = QButtonGroup()
        self.high = QRadioButton()
        self.low = QRadioButton()

        if "low" in checked:
            self.low.setChecked(True)
        else:
            self.high.setChecked(True)

        self.label = {0: QLabel("low"), 1: QLabel("high")}

        self.setup()

    def setup(self):

        self.layout.addWidget(self.label[0])
        self.layout.addWidget(self.low)

        self.layout.addWidget(self.label[1])
        self.layout.addWidget(self.high)

        self.group.addButton(self.high)
        self.group.addButton(self.low)

    def get_value(self):

        return ("low_t_cost", "high_t_cost")[self.high.isChecked()]

    def add_to_grid_layout(self, layout, x, y):

        layout.addWidget(self.text, x, y, alignment=Qt.AlignLeft)
        layout.addLayout(self.layout, x, y + 1, alignment=Qt.AlignCenter)
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.off_button = QRadioButton('off', self)  # 1
        self.on_button = QRadioButton('on', self)  # 2

        self.pic_label = QLabel(self)  # 3
        self.button_h_layout = QHBoxLayout()
        self.pic_h_layout = QHBoxLayout()
        self.all_v_layout = QVBoxLayout()

        self.layout_init()
        self.radiobutton_init()
        self.label_init()

    def layout_init(self):
        self.pic_h_layout.addStretch(1)  # 4
        self.pic_h_layout.addWidget(self.pic_label)
        self.pic_h_layout.addStretch(1)
        self.button_h_layout.addWidget(self.off_button)
        self.button_h_layout.addWidget(self.on_button)
        self.all_v_layout.addLayout(self.pic_h_layout)
        self.all_v_layout.addLayout(self.button_h_layout)

        self.setLayout(self.all_v_layout)

    def radiobutton_init(self):
        self.off_button.setCheckable(True)
        self.off_button.toggled.connect(self.on_off_bulb_func)

    def label_init(self):
        self.pic_label.setPixmap(QPixmap("off.png"))

    def on_off_bulb_func(self):
        if self.off_button.isChecked():
            self.pic_label.setPixmap(QPixmap('off.png'))
        else:
            self.pic_label.setPixmap(QPixmap('on.png'))
Example #13
0
class RadioParameter:
    """
    role (firm/customer)
    """
    def __init__(self, parent, checked):

        self.parent = parent

        self.layout = QHBoxLayout()

        self.group = QButtonGroup()

        self.firm = QRadioButton()
        self.customer = QRadioButton()

        self.setup(checked)

    def setup(self, checked):

        if checked == "customer":
            self.customer.setChecked(True)
        else:
            self.firm.setChecked(True)

        self.group.addButton(self.firm)
        self.group.addButton(self.customer)

        self.layout.addWidget(self.firm)
        self.layout.addWidget(self.customer)

    def get_value(self):

        return ("customer", "firm")[self.firm.isChecked()]

    def add_to_grid_layout(self, layout, x, y):

        layout.addLayout(self.layout, x, y)
Example #14
0
class HistoryRecordEditor(QWidget):
    class Agent:
        def __init__(self):
            pass

        def on_apply(self):
            pass

        def on_cancel(self):
            pass

    def __init__(self, parent: QWidget):
        super(HistoryRecordEditor, self).__init__(parent)

        self.__records = []
        self.__source = ''
        self.__current_record = None
        self.__operation_agents = []

        self.__ignore_combo = False

        self.__tab_main = QTabWidget()
        self.__current_depot = 'default'
        # self.__combo_depot = QComboBox()
        self.__combo_records = QComboBox()

        self.__label_uuid = QLabel()
        self.__label_source = QLabel()
        self.__line_time = QLineEdit()
        self.__line_location = QLineEdit()
        self.__line_people = QLineEdit()
        self.__line_organization = QLineEdit()
        self.__line_default_tags = QLineEdit()

        self.__button_auto_time = QPushButton('Auto Detect')
        self.__button_auto_location = QPushButton('Auto Detect')
        self.__button_auto_people = QPushButton('Auto Detect')
        self.__button_auto_organization = QPushButton('Auto Detect')

        self.__radio_time = QRadioButton('Time')
        self.__radio_location = QRadioButton('Location')
        self.__radio_people = QRadioButton('Participant')
        self.__radio_organization = QRadioButton('Organization')
        self.__radio_record = QRadioButton('Event')

        self.__check_time = QCheckBox('Lock')
        self.__check_location = QCheckBox('Lock')
        self.__check_people = QCheckBox('Lock')
        self.__check_organization = QCheckBox('Lock')
        self.__check_default_tags = QCheckBox('Lock')

        self.__line_title = QLineEdit()
        self.__text_brief = QTextEdit()
        self.__text_record = QTextEdit()

        self.__table_tags = EasyQTableWidget()

        self.__button_new = QPushButton('New Event')
        self.__button_new_file = QPushButton('New File')
        self.__button_del = QPushButton('Del Event')
        self.__button_apply = QPushButton('Apply')
        self.__button_cancel = QPushButton('Cancel')

        self.init_ui()
        self.config_ui()

    def init_ui(self):
        root_layout = QVBoxLayout()

        line = QHBoxLayout()
        # line.addWidget(QLabel('Event Source'), 0)
        line.addWidget(self.__label_source, 1)
        line.addWidget(self.__button_new_file, 0)
        root_layout.addLayout(line)

        line = QHBoxLayout()
        line.addWidget(self.__combo_records, 1)
        line.addWidget(self.__button_new, 0)
        line.addWidget(self.__button_del, 0)
        root_layout.addLayout(line)

        root_layout.addWidget(self.__tab_main)
        root_layout.addLayout(
            horizon_layout([self.__button_apply, self.__button_cancel]))
        self.setLayout(root_layout)

        record_page_layout = create_new_tab(self.__tab_main, 'Event Editor')

        property_layout = QGridLayout()

        row = 0
        property_layout.addWidget(QLabel('Event ID'), row, 0)
        property_layout.addWidget(self.__label_uuid, row, 1)

        row += 1
        property_layout.addWidget(QLabel('Event Tags'), row, 0)
        property_layout.addWidget(self.__line_default_tags, row, 1, 1, 2)
        property_layout.addWidget(self.__check_default_tags, row, 3)

        row += 1
        # property_layout.addWidget(QLabel('Event Time'), 1, 0)
        property_layout.addWidget(self.__radio_time, row, 0)
        property_layout.addWidget(self.__line_time, row, 1)
        property_layout.addWidget(self.__button_auto_time, row, 2)
        property_layout.addWidget(self.__check_time, row, 3)

        row += 1
        # property_layout.addWidget(QLabel('Event Location'), 2, 0)
        property_layout.addWidget(self.__radio_location, row, 0)
        property_layout.addWidget(self.__line_location, row, 1)
        property_layout.addWidget(self.__button_auto_location, row, 2)
        property_layout.addWidget(self.__check_location, row, 3)

        row += 1
        # property_layout.addWidget(QLabel('Event Participant'), 3, 0)
        property_layout.addWidget(self.__radio_people, row, 0)
        property_layout.addWidget(self.__line_people, row, 1)
        property_layout.addWidget(self.__button_auto_people, row, 2)
        property_layout.addWidget(self.__check_people, row, 3)

        row += 1
        # property_layout.addWidget(QLabel('Event Organization'), 4, 0)
        property_layout.addWidget(self.__radio_organization, row, 0)
        property_layout.addWidget(self.__line_organization, row, 1)
        property_layout.addWidget(self.__button_auto_organization, row, 2)
        property_layout.addWidget(self.__check_organization, row, 3)

        row += 1
        self.__radio_record.setChecked(True)
        property_layout.addWidget(self.__radio_record, row, 0)

        record_page_layout.addLayout(property_layout)

        group, layout = create_v_group_box('')
        record_page_layout.addWidget(group)

        layout.addWidget(QLabel('Event Title'))
        layout.addWidget(self.__line_title)

        layout.addWidget(QLabel('Event Brief'))
        layout.addWidget(self.__text_brief, 2)

        layout.addWidget(QLabel('Event Description'))
        layout.addWidget(self.__text_record, 5)

        layout = create_new_tab(self.__tab_main, 'Label Tag Editor')
        layout.addWidget(self.__table_tags)

        self.setMinimumSize(700, 500)

    def config_ui(self):
        self.__button_auto_time.clicked.connect(self.on_button_auto_time)
        self.__button_auto_location.clicked.connect(
            self.on_button_auto_location)
        self.__button_auto_people.clicked.connect(self.on_button_auto_people)
        self.__button_auto_organization.clicked.connect(
            self.on_button_auto_organization)

        self.__button_new.clicked.connect(self.on_button_new)
        self.__button_new_file.clicked.connect(self.on_button_file)
        self.__button_del.clicked.connect(self.on_button_del)
        self.__button_apply.clicked.connect(self.on_button_apply)
        self.__button_cancel.clicked.connect(self.on_button_cancel)

        self.__combo_records.currentIndexChanged.connect(self.on_combo_records)

    def update_combo_records(self):
        index = -1
        self.__ignore_combo = True
        self.__combo_records.clear()

        sorted_records = History.sort_records(self.__records)

        for i in range(0, len(sorted_records)):
            record = sorted_records[i]
            self.__combo_records.addItem(
                '[' + HistoryTime.tick_to_standard_string(record.since()) +
                '] ' + record.uuid())
            self.__combo_records.setItemData(i, record.uuid())
            if record == self.__current_record:
                index = i
        self.__ignore_combo = False

        if index >= 0:
            self.__combo_records.setCurrentIndex(index)
            self.on_combo_records()
        else:
            if self.__combo_records.count() > 0:
                self.__combo_records.setCurrentIndex(0)
                self.on_combo_records()
            print('Cannot find the current record in combobox - use index 0.')

    # ---------------------------------------------------- Features ----------------------------------------------------

    def add_agent(self, agent):
        self.__operation_agents.append(agent)

    def set_current_depot(self, depot: str):
        self.__current_depot = depot
        print('| Editor current depot: ' + depot)

    def set_current_source(self, source: str):
        self.__source = source
        print('Editor current source: ' + source)

    def edit_source(self, source: str, current_uuid: str = '') -> bool:
        # TODO: Do we need this?
        loader = HistoricalRecordLoader()
        if not loader.from_source(source):
            return False
        self.set_current_source(source)
        self.__records = loader.get_loaded_records()
        self.__current_record = None

        for record in self.__records:
            if current_uuid is None or current_uuid == '' or record.uuid(
            ) == current_uuid:
                self.__current_record = record
                break

        if self.__current_record is None:
            self.__current_record = HistoricalRecord()
        self.update_combo_records()
        self.record_to_ui(self.__current_record)

    def set_records(self, records: HistoricalRecord or [HistoricalRecord],
                    source: str):
        self.__records = records if isinstance(records, list) else [records]
        self.__current_record = self.__records[0]
        self.set_current_source(source)
        self.update_combo_records()

    def get_source(self) -> str:
        return self.__source

    def get_records(self) -> [HistoricalRecord]:
        return self.__records

    def get_current_record(self) -> HistoricalRecord:
        return self.__current_record

    # ---------------------------------------------------- UI Event ----------------------------------------------------

    def on_button_auto_time(self):
        pass

    def on_button_auto_location(self):
        pass

    def on_button_auto_people(self):
        pass

    def on_button_auto_organization(self):
        pass

    def on_button_new(self):
        self.create_new_record()

    def on_button_file(self):
        self.create_new_file()

    def on_button_del(self):
        if self.__current_record in self.__records:
            self.__records.remove(self.__current_record)
        self.__current_record = None
        self.update_combo_records()

    def on_button_apply(self):
        if self.__current_record is None:
            self.__current_record = HistoricalRecord()
            self.__records.append(self.__current_record)
        else:
            self.__current_record.reset()

        if not self.ui_to_record(self.__current_record):
            return

        for agent in self.__operation_agents:
            agent.on_apply()

    def on_button_cancel(self):
        for agent in self.__operation_agents:
            agent.on_cancel()

    def on_combo_records(self):
        if self.__ignore_combo:
            return

        _uuid = self.__combo_records.currentData()
        record = self.__look_for_record(_uuid)

        if record is None:
            print('Cannot find record for uuid: ' + _uuid)
            return

        self.__current_record = record
        self.record_to_ui(record)

    # --------------------------------------------------- Operation ----------------------------------------------------

    def clear_ui(self):
        lock_time = self.__check_time.isChecked()
        lock_location = self.__check_location.isChecked()
        lock_people = self.__check_people.isChecked()
        lock_organization = self.__check_organization.isChecked()
        lock_default_tags = self.__check_default_tags.isChecked()

        self.__label_uuid.setText('')
        self.__label_source.setText('')

        if not lock_time:
            self.__line_time.setText('')
        if not lock_location:
            self.__line_location.setText('')
        if not lock_people:
            self.__line_people.setText('')
        if not lock_organization:
            self.__line_organization.setText('')
        if not lock_default_tags:
            self.__line_default_tags.setText('')

        self.__line_title.clear()
        self.__text_brief.clear()
        self.__text_record.clear()

        restore_text_editor(self.__text_brief)
        restore_text_editor(self.__text_record)

    def ui_to_record(self, record: HistoricalRecord) -> bool:
        input_time = self.__line_time.text()
        input_location = self.__line_location.text()
        input_people = self.__line_people.text()
        input_organization = self.__line_organization.text()
        input_default_tags = self.__line_default_tags.text()

        input_title = self.__line_title.text()
        input_brief = self.__text_brief.toPlainText()
        input_event = self.__text_record.toPlainText()

        focus_time = self.__radio_time.isChecked()
        focus_location = self.__radio_location.isChecked()
        focus_poeple = self.__radio_people.isChecked()
        focus_organization = self.__radio_organization.isChecked()
        focus_record = self.__radio_record.isChecked()

        focus_label = ''
        input_valid = False

        if focus_time:
            focus_label = 'time'
            input_valid = (len(input_time.strip()) != 0)
        if focus_location:
            focus_label = 'location'
            input_valid = (len(input_location.strip()) != 0)
        if focus_poeple:
            focus_label = 'people'
            input_valid = (len(input_people.strip()) != 0)
        if focus_organization:
            focus_label = 'organization'
            input_valid = (len(input_organization.strip()) != 0)
        if focus_record:
            focus_label = 'event'
            input_valid = (len(input_title.strip()) != 0
                           or len(input_brief.strip()) != 0
                           or len(input_event.strip()) != 0)
        if not input_valid:
            tips = 'The focus label you select is: ' + focus_label + ".\n\nBut you didn't put content in it."
            QMessageBox.information(None, 'Save', tips, QMessageBox.Ok)
            return False

        record.set_label_tags('time', input_time.split(','))
        record.set_label_tags('location', input_location.split(','))
        record.set_label_tags('people', input_people.split(','))
        record.set_label_tags('organization', input_organization.split(','))
        record.set_label_tags('tags', input_default_tags.split(','))

        record.set_label_tags('title', input_title)
        record.set_label_tags('brief', input_brief)
        record.set_label_tags('event', input_event)

        record.set_focus_label(focus_label)

        return True

    def record_to_ui(self, record: HistoricalRecord or str):
        self.clear_ui()

        self.__label_uuid.setText(LabelTagParser.tags_to_text(record.uuid()))
        self.__label_source.setText(self.__source)
        self.__line_time.setText(LabelTagParser.tags_to_text(record.time()))

        self.__line_location.setText(
            LabelTagParser.tags_to_text(record.get_tags('location')))
        self.__line_people.setText(
            LabelTagParser.tags_to_text(record.get_tags('people')))
        self.__line_organization.setText(
            LabelTagParser.tags_to_text(record.get_tags('organization')))
        self.__line_default_tags.setText(
            LabelTagParser.tags_to_text(record.get_tags('tags')))

        self.__line_title.setText(LabelTagParser.tags_to_text(record.title()))
        self.__text_brief.setText(LabelTagParser.tags_to_text(record.brief()))
        self.__text_record.setText(LabelTagParser.tags_to_text(record.event()))

    def create_new_record(self):
        if self.__current_record is not None:
            # TODO:
            pass
        self.__new_record()

        self.clear_ui()
        self.update_combo_records()
        self.__label_uuid.setText(
            LabelTagParser.tags_to_text(self.__current_record.uuid()))
        self.__label_source.setText(self.__source)

    def create_new_file(self):
        self.__new_file()

        self.clear_ui()
        self.update_combo_records()
        self.__label_uuid.setText(
            LabelTagParser.tags_to_text(self.__current_record.uuid()))
        self.__label_source.setText(self.__source)

        # self.__source = path.join(self.__current_depot, str(self.__current_record.uuid()) + '.his')
        # self.__records.clear()
        # self.create_new_record()

    # def save_records(self):
    #     result = History.Loader().to_local_depot(self.__records, 'China', self.__source)
    #     tips = 'Save Successful.' if result else 'Save Fail.'
    #     tips += '\nSave File: ' + self.__source
    #     QMessageBox.information(None, 'Save', tips, QMessageBox.Ok)

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

    def __new_file(self):
        self.__records.clear()
        self.set_current_source('')
        self.__new_record()

    def __new_record(self):
        self.__current_record = HistoricalRecord()
        self.__records.append(self.__current_record)
        if self.__source is None or self.__source == '':
            self.__source = path.join(
                self.__current_depot,
                str(self.__current_record.uuid()) + '.his')
            self.set_current_source(self.__source)
        self.__current_record.set_source(self.__source)

    def __look_for_record(self, _uuid: str):
        for record in self.__records:
            if record.uuid() == _uuid:
                return record
        return None
Example #15
0
class Widget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.a = 26
        self.b = 76
        self.p = 18
        self.q = 22
        self.omega = 2

        # Right
        # a=26,b=79,p=18,q=22,omega=2
        self.plot_figure = plot_figure(width=8, height=4)
        self.right = QVBoxLayout()
        self.right.addWidget(self.plot_figure)

        # Left: selectMechanism radio buttons
        self.fourbar = QRadioButton("Four bar")
        self.slidercrank = QRadioButton("Slider crank")
        self.sixbar = QRadioButton("Six bar")

        self.selectMechanism = QHBoxLayout()
        self.selectMechanism.addWidget(self.fourbar)
        self.selectMechanism.addWidget(self.slidercrank)
        self.selectMechanism.addWidget(self.sixbar)

        self.fourbar.setChecked(True)
        self.fourbar.toggled.connect(self.four_bar)
        self.slidercrank.toggled.connect(self.slider_crank)
        self.sixbar.toggled.connect(self.six_bar)

        # left: link lengths input
        self.lenA = QLineEdit()
        self.lenAbox = QHBoxLayout()
        self.lenAbox.addWidget(QLabel("Link A length"))
        self.lenAbox.addWidget(self.lenA)
        self.lenAbox.addWidget(QLabel("cm"))

        self.lenB = QLineEdit()
        self.lenB.setEnabled(False)
        self.lenBbox = QHBoxLayout()
        self.lenBbox.addWidget(QLabel("Link B length"))
        self.lenBbox.addWidget(self.lenB)
        self.lenBbox.addWidget(QLabel("cm"))

        self.lenP = QLineEdit()
        self.lenPbox = QHBoxLayout()
        self.lenPbox.addWidget(QLabel("Link P length"))
        self.lenPbox.addWidget(self.lenP)
        self.lenPbox.addWidget(QLabel("cm"))

        self.lenQ = QLineEdit()
        self.lenQbox = QHBoxLayout()
        self.lenQbox.addWidget(QLabel("Link Q length"))
        self.lenQbox.addWidget(self.lenQ)
        self.lenQbox.addWidget(QLabel("cm"))

        self.omega = QLineEdit()
        self.omegabox = QHBoxLayout()
        self.omegabox.addWidget(QLabel("Angular speed"))
        self.omegabox.addWidget(self.omega)
        self.omegabox.addWidget(QLabel("rad/s"))

        # left
        self.description = QLineEdit()
        self.price = QLineEdit()
        self.add = QPushButton("Simulate")
        # Disabling 'Add' button
        self.add.setEnabled(False)
        self.reset = QPushButton("Reset")
        self.clear = QPushButton("Clear")
        self.quit = QPushButton("Quit")

        self.left = QVBoxLayout()
        self.left.addWidget(QLabel("Select the mechanism"))
        self.left.addLayout(self.selectMechanism)
        self.left.addWidget(QLabel("Specify the mechanism params"))
        self.left.addLayout(self.lenAbox)
        self.left.addLayout(self.lenBbox)
        self.left.addLayout(self.lenPbox)
        self.left.addLayout(self.lenQbox)
        self.left.addLayout(self.omegabox)
        self.left.addWidget(self.add)
        self.left.addWidget(self.reset)
        self.left.addWidget(self.clear)
        self.left.addWidget(self.quit)

        # Signals and pyqtSlots
        self.add.clicked.connect(self.add_element)
        self.quit.clicked.connect(self.quit_application)
        self.reset.clicked.connect(self.reset_values)
        self.clear.clicked.connect(self.clear_inputs)
        # check when to enable Simulate button
        self.lenA.textChanged[str].connect(self.check_disable)
        self.lenB.textChanged[str].connect(self.check_disable)
        self.lenP.textChanged[str].connect(self.check_disable)
        self.lenQ.textChanged[str].connect(self.check_disable)
        self.omega.textChanged[str].connect(self.check_disable)

        # QWidget Layout
        self.layout = QHBoxLayout()

        # self.layout.addWidget(self.table)
        self.layout.addLayout(self.left)
        self.layout.addLayout(self.right)

        # Set the layout to the QWidget
        self.setLayout(self.layout)

    @pyqtSlot()
    def teting(self):
        plot_figure(self.a,
                    self.b,
                    self.p,
                    self.q,
                    self.omega,
                    width=8,
                    height=4)

    # onClick for fourbar radio
    @pyqtSlot()
    def four_bar(self):
        if self.sender().isChecked():
            self.lenP.setEnabled(True)
            self.lenQ.setEnabled(True)
            self.lenA.setEnabled(True)
            self.lenB.setEnabled(False)

    # onClick for slidercrank radio
    @pyqtSlot()
    def slider_crank(self):
        if self.sender().isChecked():
            self.lenP.setEnabled(False)
            self.lenQ.setEnabled(False)
            self.lenA.setEnabled(True)
            self.lenB.setEnabled(True)

    # onClick for sixbar radio
    @pyqtSlot()
    def six_bar(self):
        if self.sender().isChecked():
            self.lenP.setEnabled(True)
            self.lenQ.setEnabled(True)
            self.lenA.setEnabled(True)
            self.lenB.setEnabled(True)

    @pyqtSlot()
    def add_element(self):
        if self.fourbar.isChecked():
            print(self.lenA.text(), self.lenP.text(), self.lenQ.text(),
                  self.omega.text())
        if self.slidercrank.isChecked():
            print(self.lenA.text(), self.lenB.text(), self.omega.text())
        if self.sixbar.isChecked():

            self.plot_figure.draw_graph(int(self.lenA.text()),
                                        int(self.lenB.text()),
                                        int(self.lenP.text()),
                                        int(self.lenQ.text()),
                                        int(self.omega.text()))
            print(self.lenA.text(), self.lenB.text(), self.lenP.text(),
                  self.lenQ.text(), self.omega.text())

    # enable add button after required inputs are met
    @pyqtSlot()
    def check_disable(self):
        if self.fourbar.isChecked():
            if not self.lenA.text() or not self.lenP.text(
            ) or not self.lenQ.text() or not self.omega.text():
                self.add.setEnabled(False)
            else:
                self.add.setEnabled(True)

        if self.slidercrank.isChecked():
            if not self.lenA.text() or not self.lenB.text(
            ) or not self.omega.text():
                self.add.setEnabled(False)
            else:
                self.add.setEnabled(True)

        if self.sixbar.isChecked():
            if not self.lenA.text() or not self.lenB.text(
            ) or not self.lenP.text() or not self.lenQ.text(
            ) or not self.omega.text():
                self.add.setEnabled(False)
            else:
                self.add.setEnabled(True)

    @pyqtSlot()
    def quit_application(self):
        QApplication.quit()

    # sets the default values i.e.six bar constant velocity
    @pyqtSlot()
    def reset_values(self):
        # a=26,b=79,p=18,q=22,omega=2
        self.lenA.setText("26")
        self.lenB.setText("79")
        self.lenP.setText("18")
        self.lenQ.setText("22")
        self.omega.setText("2")
        self.sixbar.setChecked(True)

    # clears all input fields
    @pyqtSlot()
    def clear_inputs(self):
        self.lenA.setText("")
        self.lenB.setText("")
        self.lenP.setText("")
        self.lenQ.setText("")
        self.omega.setText("")
        self.fourbar.setChecked(True)
        self.plot_figure.clear_plot()
Example #16
0
class ServerPlugin(Plugin):
    __icon__ = "fa.qrcode"
    __pname__ = "server"
    __views__ = ["slice_viewer"]
    __tab__ = "server"

    def __init__(self, parent=None):
        super().__init__(parent=parent)

        run_config = {
            "server_ip": "127.0.0.1",
            "server_port": "8134",
            "workspace_name": "test_hunt_d4b",
            "use_ssh": False,
            "ssh_host": "ws168.diamond.ac.uk",
            "ssh_port": "22",
        }

        workspace_config = {
            "dataset_name": "data",
            "datasets_dir": "/path/to/my/data/dir",
            "vol_fname": "myfile.h5",
            "workspace_name": "my_survos_workspace",
            "downsample_by": "1",
        }

        from survos2.server.config import cfg

        pipeline_config = dict(cfg)

        self.run_config = run_config
        self.workspace_config = workspace_config
        self.pipeline_config = pipeline_config

        self.server_process = None
        self.client_process = None

        self.layout = QVBoxLayout()
        tabwidget = QTabWidget()
        tab1 = QWidget()
        tab2 = QWidget()

        tabwidget.addTab(tab1, "Setup and Start Survos")
        self.create_workspace_button = QPushButton("Create workspace")

        tab1.layout = QVBoxLayout()
        tab1.setLayout(tab1.layout)
        chroot_fields = self.get_chroot_fields()
        tab1.layout.addWidget(chroot_fields)
        workspace_fields = self.get_workspace_fields()
        tab1.layout.addWidget(workspace_fields)

        self.setup_adv_run_fields()
        self.adv_run_fields.hide()

        run_fields = self.get_run_fields()
        tab1.layout.addWidget(run_fields)
        output_config_button = QPushButton("Save config")

        self.create_workspace_button.clicked.connect(
            self.create_workspace_clicked)
        output_config_button.clicked.connect(self.output_config_clicked)
        self.layout.addWidget(tabwidget)

        self.setGeometry(300, 300, 600, 400)
        self.setWindowTitle("SuRVoS Settings Editor")
        current_fpth = os.path.dirname(os.path.abspath(__file__))
        self.setWindowIcon(
            QIcon(os.path.join(current_fpth, "resources", "logo.png")))
        self.setLayout(self.layout)
        self.show()

    def get_chroot_fields(self):
        chroot_fields = QGroupBox("Set Main Directory for Storing Workspaces:")
        chroot_fields.setMaximumHeight(130)
        chroot_layout = QGridLayout()
        self.given_chroot_linedt = QLineEdit(CHROOT)
        chroot_layout.addWidget(self.given_chroot_linedt, 1, 0, 1, 2)
        set_chroot_button = QPushButton("Set Workspaces Root")
        chroot_layout.addWidget(set_chroot_button, 1, 2)
        chroot_fields.setLayout(chroot_layout)
        set_chroot_button.clicked.connect(self.set_chroot)
        return chroot_fields

    def get_workspace_fields(self):
        """Gets the QGroupBox that contains all the fields for setting up the workspace.

        Returns:
            PyQt5.QWidgets.GroupBox: GroupBox with workspace fields.
        """
        select_data_button = QPushButton("Select")
        workspace_fields = QGroupBox("Create New Workspace:")
        wf_layout = QGridLayout()
        wf_layout.addWidget(QLabel("Data File Path:"), 0, 0)
        current_data_path = Path(self.workspace_config["datasets_dir"],
                                 self.workspace_config["vol_fname"])
        self.data_filepth_linedt = QLineEdit(str(current_data_path))
        wf_layout.addWidget(self.data_filepth_linedt, 1, 0, 1, 2)
        wf_layout.addWidget(select_data_button, 1, 2)
        wf_layout.addWidget(QLabel("HDF5 Internal Data Path:"), 2, 0, 1, 1)
        ws_dataset_name = self.workspace_config["dataset_name"]
        internal_h5_path = (ws_dataset_name
                            if str(ws_dataset_name).startswith("/") else "/" +
                            ws_dataset_name)
        self.h5_intpth_linedt = QLineEdit(internal_h5_path)
        wf_layout.addWidget(self.h5_intpth_linedt, 2, 1, 1, 1)
        wf_layout.addWidget(QLabel("Workspace Name:"), 3, 0)
        self.ws_name_linedt_1 = QLineEdit(
            self.workspace_config["workspace_name"])
        wf_layout.addWidget(self.ws_name_linedt_1, 3, 1)
        wf_layout.addWidget(QLabel("Downsample Factor:"), 4, 0)
        self.downsample_spinner = QSpinBox()
        self.downsample_spinner.setRange(1, 10)
        self.downsample_spinner.setSpecialValueText("None")
        self.downsample_spinner.setMaximumWidth(60)
        self.downsample_spinner.setValue(
            int(self.workspace_config["downsample_by"]))
        wf_layout.addWidget(self.downsample_spinner, 4, 1, 1, 1)
        # ROI
        self.setup_roi_fields()
        wf_layout.addWidget(self.roi_fields, 4, 2, 1, 2)
        self.roi_fields.hide()

        wf_layout.addWidget(self.create_workspace_button, 5, 0, 1, 3)
        workspace_fields.setLayout(wf_layout)
        select_data_button.clicked.connect(self.launch_data_loader)
        return workspace_fields

    def setup_roi_fields(self):
        """Sets up the QGroupBox that displays the ROI dimensions, if selected."""
        self.roi_fields = QGroupBox("ROI:")
        roi_fields_layout = QHBoxLayout()
        # z
        roi_fields_layout.addWidget(QLabel("z:"), 0)
        self.zstart_roi_val = QLabel("0")
        roi_fields_layout.addWidget(self.zstart_roi_val, 1)
        roi_fields_layout.addWidget(QLabel("-"), 2)
        self.zend_roi_val = QLabel("0")
        roi_fields_layout.addWidget(self.zend_roi_val, 3)
        # y
        roi_fields_layout.addWidget(QLabel("y:"), 4)
        self.ystart_roi_val = QLabel("0")
        roi_fields_layout.addWidget(self.ystart_roi_val, 5)
        roi_fields_layout.addWidget(QLabel("-"), 6)
        self.yend_roi_val = QLabel("0")
        roi_fields_layout.addWidget(self.yend_roi_val, 7)
        # x
        roi_fields_layout.addWidget(QLabel("x:"), 8)
        self.xstart_roi_val = QLabel("0")
        roi_fields_layout.addWidget(self.xstart_roi_val, 9)
        roi_fields_layout.addWidget(QLabel("-"), 10)
        self.xend_roi_val = QLabel("0")
        roi_fields_layout.addWidget(self.xend_roi_val, 11)

        self.roi_fields.setLayout(roi_fields_layout)

    def setup_adv_run_fields(self):
        """Sets up the QGroupBox that displays the advanced optiona for starting SuRVoS2."""
        self.adv_run_fields = QGroupBox("Advanced Run Settings:")
        adv_run_layout = QGridLayout()
        adv_run_layout.addWidget(QLabel("Server IP Address:"), 0, 0)
        self.server_ip_linedt = QLineEdit(self.run_config["server_ip"])
        adv_run_layout.addWidget(self.server_ip_linedt, 0, 1)
        adv_run_layout.addWidget(QLabel("Server Port:"), 1, 0)
        self.server_port_linedt = QLineEdit(self.run_config["server_port"])
        adv_run_layout.addWidget(self.server_port_linedt, 1, 1)

        # SSH Info
        self.ssh_button = QRadioButton("Use SSH")
        self.ssh_button.setAutoExclusive(False)
        adv_run_layout.addWidget(self.ssh_button, 0, 2)
        ssh_flag = self.run_config.get("use_ssh", False)
        if ssh_flag:
            self.ssh_button.setChecked(True)
        self.ssh_button.toggled.connect(self.toggle_ssh)

        self.adv_ssh_fields = QGroupBox("SSH Settings:")
        adv_ssh_layout = QGridLayout()
        adv_ssh_layout.setColumnStretch(2, 2)
        ssh_host_label = QLabel("Host")
        self.ssh_host_linedt = QLineEdit(self.run_config.get("ssh_host", ""))
        adv_ssh_layout.addWidget(ssh_host_label, 0, 0)
        adv_ssh_layout.addWidget(self.ssh_host_linedt, 0, 1, 1, 2)
        ssh_user_label = QLabel("Username")
        self.ssh_username_linedt = QLineEdit(self.get_login_username())
        adv_ssh_layout.addWidget(ssh_user_label, 1, 0)
        adv_ssh_layout.addWidget(self.ssh_username_linedt, 1, 1, 1, 2)
        ssh_port_label = QLabel("Port")
        self.ssh_port_linedt = QLineEdit(self.run_config.get("ssh_port", ""))
        adv_ssh_layout.addWidget(ssh_port_label, 2, 0)
        adv_ssh_layout.addWidget(self.ssh_port_linedt, 2, 1, 1, 2)
        self.adv_ssh_fields.setLayout(adv_ssh_layout)
        #adv_run_layout.addWidget(self.adv_ssh_fields, 1, 2, 2, 5)

        self.adv_run_fields.setLayout(adv_run_layout)

    def get_run_fields(self):
        """Gets the QGroupBox that contains the fields for starting SuRVoS.

        Returns:
            PyQt5.QWidgets.GroupBox: GroupBox with run fields.
        """
        self.run_button = QPushButton("Start Server")
        self.stop_button = QPushButton("Stop Server")

        self.existing_button = QPushButton("Use Existing Server")

        advanced_button = QRadioButton("Advanced")
        run_fields = QGroupBox("Run SuRVoS:")
        run_layout = QGridLayout()

        workspaces = os.listdir(CHROOT)
        self.workspaces_list = ComboBox()
        for s in workspaces:
            self.workspaces_list.addItem(key=s)

        run_layout.addWidget(QLabel("Workspace Name:"), 0, 0)
        self.ws_name_linedt_2 = QLineEdit(
            self.workspace_config["workspace_name"])
        self.ws_name_linedt_2.setAlignment(Qt.AlignLeft)
        self.workspaces_list.setLineEdit(self.ws_name_linedt_2)

        # run_layout.addWidget(self.ws_name_linedt_2, 0, 1)

        run_layout.addWidget(self.workspaces_list, 0, 1)
        run_layout.addWidget(advanced_button, 1, 0)
        run_layout.addWidget(self.adv_run_fields, 2, 1)
        run_layout.addWidget(self.run_button, 3, 0, 1, 3)
        run_layout.addWidget(self.stop_button, 4, 0, 1, 3)
        run_layout.addWidget(self.existing_button, 5, 0, 1, 3)
        run_fields.setLayout(run_layout)

        advanced_button.toggled.connect(self.toggle_advanced)
        self.run_button.clicked.connect(self.run_clicked)
        self.stop_button.clicked.connect(self.stop_clicked)
        self.existing_button.clicked.connect(self.existing_clicked)

        return run_fields

    def get_login_username(self):
        try:
            user = getpass.getuser()
        except Exception:
            user = ""
        return user

    def refresh_chroot(self):
        workspaces = os.listdir(DataModel.g.CHROOT)
        self.workspaces_list.clear()
        for s in workspaces:
            self.workspaces_list.addItem(key=s)

    @pyqtSlot()
    def set_chroot(self):
        CHROOT = self.given_chroot_linedt.text()
        Config.update({"model": {"chroot": CHROOT}})
        logger.debug(f"Setting CHROOT to {CHROOT}")
        DataModel.g.CHROOT = CHROOT
        self.refresh_chroot()

    @pyqtSlot()
    def launch_data_loader(self):
        """Load the dialog box widget to select data with data preview window and ROI selection."""
        path = None
        int_h5_pth = None
        dialog = LoadDataDialog(self)
        result = dialog.exec_()
        self.roi_limits = None
        if result == QDialog.Accepted:
            path = dialog.winput.path.text()
            int_h5_pth = dialog.int_h5_pth.text()
            down_factor = dialog.downsample_spinner.value()
        if path and int_h5_pth:
            self.data_filepth_linedt.setText(path)
            self.h5_intpth_linedt.setText(int_h5_pth)
            self.downsample_spinner.setValue(down_factor)
            if dialog.roi_changed:
                self.roi_limits = tuple(map(str, dialog.get_roi_limits()))
                self.roi_fields.show()
                self.update_roi_fields_from_dialog()
            else:
                self.roi_fields.hide()

    def update_roi_fields_from_dialog(self):
        """Updates the ROI fields in the main window."""
        x_start, x_end, y_start, y_end, z_start, z_end = self.roi_limits
        self.xstart_roi_val.setText(x_start)
        self.xend_roi_val.setText(x_end)
        self.ystart_roi_val.setText(y_start)
        self.yend_roi_val.setText(y_end)
        self.zstart_roi_val.setText(z_start)
        self.zend_roi_val.setText(z_end)

    @pyqtSlot()
    def toggle_advanced(self):
        """Controls displaying/hiding the advanced run fields on radio button toggle."""
        rbutton = self.sender()
        if rbutton.isChecked():
            self.adv_run_fields.show()
        else:
            self.adv_run_fields.hide()

    @pyqtSlot()
    def toggle_ssh(self):
        """Controls displaying/hiding the SSH fields on radio button toggle."""
        rbutton = self.sender()
        if rbutton.isChecked():
            self.adv_ssh_fields.show()
        else:
            self.adv_ssh_fields.hide()

    @pyqtSlot()
    def create_workspace_clicked(self):
        """Performs checks and coordinates workspace creation on button press."""
        logger.debug("Creating workspace: ")
        # Set the path to the data file
        vol_path = Path(self.data_filepth_linedt.text())
        if not vol_path.is_file():
            err_str = f"No data file exists at {vol_path}!"
            logger.error(err_str)
            self.button_feedback_response(err_str,
                                          self.create_workspace_button,
                                          "maroon")
        else:
            self.workspace_config["datasets_dir"] = str(vol_path.parent)
            self.workspace_config["vol_fname"] = str(vol_path.name)
            dataset_name = self.h5_intpth_linedt.text()
            self.workspace_config["dataset_name"] = str(dataset_name).strip(
                "/")
            # Set the workspace name
            ws_name = self.ws_name_linedt_1.text()
            self.workspace_config["workspace_name"] = ws_name
            # Set the downsample factor
            ds_factor = self.downsample_spinner.value()
            self.workspace_config["downsample_by"] = ds_factor
            # Set the ROI limits if they exist
            if self.roi_limits:
                self.workspace_config["roi_limits"] = self.roi_limits
            try:
                response = init_ws(self.workspace_config)
                _, error = response
                if not error:
                    self.button_feedback_response(
                        "Workspace created sucessfully",
                        self.create_workspace_button,
                        "green",
                    )
                    # Update the workspace name in the 'Run' section
                    self.ws_name_linedt_2.setText(self.ws_name_linedt_1.text())
            except WorkspaceException as e:
                logger.exception(e)
                self.button_feedback_response(str(e),
                                              self.create_workspace_button,
                                              "maroon")
            self.refresh_chroot()

    def button_feedback_response(self, message, button, colour_str, timeout=2):
        """Changes button colour and displays feedback message for a limited time period.

        Args:
            message (str): Message to display in button.
            button (PyQt5.QWidgets.QBushButton): The button to manipulate.
            colour_str (str): The standard CSS colour string or hex code describing the colour to change the button to.
        """
        timeout *= 1000
        msg_old = button.text()
        col_old = button.palette().button().color
        txt_col_old = button.palette().buttonText().color
        button.setText(message)
        button.setStyleSheet(f"background-color: {colour_str}; color: white")
        timer = QTimer()
        timer.singleShot(
            timeout,
            lambda: self.reset_button(button, msg_old, col_old, txt_col_old))

    @pyqtSlot()
    def reset_button(self, button, msg_old, col_old, txt_col_old):
        """Sets a button back to its original display settings.

        Args:
            button (PyQt5.QWidgets.QBushButton): The button to manipulate.
            msg_old (str): Message to display in button.
            col_old (str): The standard CSS colour string or hex code describing the colour to change the button to.
            txt_col_old (str): The standard CSS colour string or hex code describing the colour to change the button text to.
        """
        button.setStyleSheet(f"background-color: {col_old().name()}")
        button.setStyleSheet(f"color: {txt_col_old().name()}")
        button.setText(msg_old)
        button.update()

    @pyqtSlot()
    def output_config_clicked(self):
        """Outputs pipeline config YAML file on button click."""
        out_fname = "pipeline_cfg.yml"
        logger.debug(f"Outputting pipeline config: {out_fname}")
        with open(out_fname, "w") as outfile:
            yaml.dump(self.pipeline_config,
                      outfile,
                      default_flow_style=False,
                      sort_keys=False)

    def get_ssh_params(self):
        ssh_host = self.ssh_host_linedt.text()
        ssh_user = self.ssh_username_linedt.text()
        ssh_port = int(self.ssh_port_linedt.text())
        return ssh_host, ssh_user, ssh_port

    def start_server_over_ssh(self):
        params = self.get_ssh_params()
        if not all(params):
            logger.error(
                "Not all SSH parameters given! Not connecting to SSH.")
            pass
        ssh_host, ssh_user, ssh_port = params
        # Pop up dialog to ask for password
        text, ok = QInputDialog.getText(None, "Login",
                                        f"Password for {ssh_user}@{ssh_host}",
                                        QLineEdit.Password)
        if ok and text:
            self.ssh_worker = SSHWorker(params, text, self.run_config)
            self.ssh_thread = QThread(self)
            self.ssh_worker.moveToThread(self.ssh_thread)
            self.ssh_worker.button_message_signal.connect(
                self.send_msg_to_run_button)
            self.ssh_worker.error_signal.connect(self.on_ssh_error)
            self.ssh_worker.finished.connect(self.start_client)
            self.ssh_worker.update_ip_linedt_signal.connect(
                self.update_ip_linedt)
            self.ssh_thread.started.connect(
                self.ssh_worker.start_server_over_ssh)
            self.ssh_thread.start()

    def closeEvent(self, event):
        reply = QMessageBox.question(
            self,
            "Quit",
            "Are you sure you want to quit? "
            "The server will be stopped.",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No,
        )
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    @pyqtSlot()
    def on_ssh_error(self):
        self.ssh_error = True

    @pyqtSlot(str)
    def update_ip_linedt(self, ip):
        self.server_ip_linedt.setText(ip)

    @pyqtSlot(list)
    def send_msg_to_run_button(self, param_list):
        self.button_feedback_response(param_list[0], self.run_button,
                                      param_list[1], param_list[2])

    @pyqtSlot()
    def stop_clicked(self):
        logger.debug("Stopping server")
        if self.server_process is not None:
            self.server_process.kill()

    @pyqtSlot()
    def run_clicked(self):
        """Starts SuRVoS2 server and client as subprocesses when 'Run' button pressed.

        Raises:
            Exception: If survos.py not found.
        """
        with progress(total=3) as pbar:
            pbar.set_description("Starting server...")
            pbar.update(1)

        self.ssh_error = (
            False  # Flag which will be set to True if there is an SSH error
        )
        command_dir = os.path.abspath(os.path.dirname(__file__))  # os.getcwd()

        # Set current dir to survos root
        from pathlib import Path

        command_dir = Path(
            command_dir).absolute().parent.parent.parent.resolve()
        os.chdir(command_dir)

        self.script_fullname = os.path.join(command_dir, "survos.py")
        if not os.path.isfile(self.script_fullname):
            raise Exception("{}: Script not found".format(
                self.script_fullname))
        # Retrieve the parameters from the fields TODO: Put some error checking in
        self.run_config["workspace_name"] = self.ws_name_linedt_2.text()
        self.run_config["server_port"] = self.server_port_linedt.text()
        # Temporary measure to check whether the workspace exists or not
        full_ws_path = os.path.join(Config["model.chroot"],
                                    self.run_config["workspace_name"])
        if not os.path.isdir(full_ws_path):
            logger.error(
                f"No workspace can be found at {full_ws_path}, Not starting SuRVoS."
            )
            self.button_feedback_response(
                f"Workspace {self.run_config['workspace_name']} does not appear to exist!",
                self.run_button,
                "maroon",
            )
            return
        pbar.update(1)
        # Try some fancy SSH stuff here
        if self.ssh_button.isChecked():
            self.start_server_over_ssh()
        else:
            self.server_process = subprocess.Popen([
                "python",
                self.script_fullname,
                "start_server",
                self.run_config["workspace_name"],
                self.run_config["server_port"],
                DataModel.g.CHROOT,
            ])
            try:
                outs, errs = self.server_process.communicate(timeout=10)
                print(f"OUTS: {outs, errs}")
            except subprocess.TimeoutExpired:
                pass

            # self.start_client()
            logger.info(f"setting remote: {self.server_port_linedt.text()}")
            remote_ip_port = "127.0.0.1:" + self.server_port_linedt.text()
            logger.info(f"setting remote: {remote_ip_port}")
            resp = Launcher.g.set_remote(remote_ip_port)
            logger.info(f"Response from server to setting remote: {resp}")

            cfg.ppw.clientEvent.emit({
                "source": "server_tab",
                "data": "set_workspace",
                "workspace": self.ws_name_linedt_2.text(),
            })
            cfg.ppw.clientEvent.emit({
                "source": "panel_gui",
                "data": "refresh",
                "value": None
            })
            #cfg.ppw.clientEvent.emit({'data' : 'view_feature', 'feature_id' : '001_raw'})
        pbar.update(1)

    @pyqtSlot()
    def existing_clicked(self):
        ssh_ip = self.server_ip_linedt.text()
        remote_ip_port = ssh_ip + ":" + self.server_port_linedt.text()
        logger.info(f"setting remote: {remote_ip_port}")
        resp = Launcher.g.set_remote(remote_ip_port)
        logger.info(f"Response from server to setting remote: {resp}")

        cfg.ppw.clientEvent.emit({
            "source": "server_tab",
            "data": "set_workspace",
            "workspace": self.ws_name_linedt_2.text(),
        })
        cfg.ppw.clientEvent.emit({
            "source": "panel_gui",
            "data": "refresh",
            "value": None
        })

    def start_client(self):
        if not self.ssh_error:
            self.button_feedback_response("Starting Client.", self.run_button,
                                          "green", 7)
            self.run_config["server_ip"] = self.server_ip_linedt.text()
            self.client_process = subprocess.Popen([
                "python",
                self.script_fullname,
                "nu_gui",
                self.run_config["workspace_name"],
                str(self.run_config["server_ip"]) + ":" +
                str(self.run_config["server_port"]),
            ])
class StockHistoryUi(QWidget):
    ADJUST_TAIL = 0
    ADJUST_HEAD = 1
    ADJUST_NONE = 2

    RETURN_LOG = 3
    RETURN_SIMPLE = 4

    def __init__(self, sas: StockAnalysisSystem):
        super(StockHistoryUi, self).__init__()

        self.__sas = sas
        self.__paint_securities = ''
        self.__paint_trade_data = None

        # Record set
        project_path = sas.get_project_path(
        ) if sas is not None else os.getcwd()
        self.__root_path = memo_path_from_project_path(project_path)
        self.__memo_recordset = RecordSet(self.__root_path)

        # vnpy chart
        self.__vnpy_chart = ChartWidget()

        # Memo editor
        self.__memo_editor = StockMemoEditor(self.__sas, self.__memo_recordset)

        # Timer for workaround signal fired twice
        self.__accepted = False
        self.__timer = QTimer()
        self.__timer.setInterval(1000)
        self.__timer.timeout.connect(self.on_timer)
        self.__timer.start()

        # Ui component
        data_utility = self.__sas.get_data_hub_entry().get_data_utility(
        ) if self.__sas is not None else None
        self.__combo_name = SecuritiesSelector(data_utility)
        self.__button_ensure = QPushButton('确定')

        self.__check_memo = QCheckBox('笔记')
        self.__check_volume = QCheckBox('成交量')

        self.__radio_adj_tail = QRadioButton('后复权')
        self.__radio_adj_head = QRadioButton('前复权')
        self.__radio_adj_none = QRadioButton('不复权')
        self.__group_adj = QButtonGroup(self)

        self.__radio_log_return = QRadioButton('对数收益')
        self.__radio_simple_return = QRadioButton('算术收益')
        self.__group_return = QButtonGroup(self)

        self.__init_ui()
        self.__config_ui()

    def __init_ui(self):
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)

        self.__group_adj.addButton(self.__radio_adj_tail)
        self.__group_adj.addButton(self.__radio_adj_head)
        self.__group_adj.addButton(self.__radio_adj_none)
        group_box_adj, group_layout = create_h_group_box('')
        group_layout.addWidget(self.__radio_adj_tail)
        group_layout.addWidget(self.__radio_adj_head)
        group_layout.addWidget(self.__radio_adj_none)

        self.__group_return.addButton(self.__radio_log_return)
        self.__group_return.addButton(self.__radio_simple_return)
        group_box_return, group_layout = create_h_group_box('')
        group_layout.addWidget(self.__radio_log_return)
        group_layout.addWidget(self.__radio_simple_return)

        group_box, group_layout = create_v_group_box('Securities')

        main_layout.addWidget(self.__vnpy_chart, 99)
        main_layout.addWidget(group_box)

        group_layout.addLayout(
            horizon_layout([
                self.__combo_name, group_box_adj, group_box_return,
                self.__button_ensure, self.__check_volume, self.__check_memo
            ]))

    def __config_ui(self):
        data_utility = self.__sas.get_data_hub_entry().get_data_utility()
        index_dict = data_utility.get_support_index()

        self.__combo_name.setEditable(True)
        for key in index_dict:
            self.__combo_name.addItem(key + ' | ' + index_dict.get(key), key)

        self.__radio_adj_none.setChecked(True)
        self.__radio_simple_return.setChecked(True)

        self.__check_memo.clicked.connect(self.on_button_memo)
        self.__check_volume.clicked.connect(self.on_button_volume)
        self.__button_ensure.clicked.connect(self.on_button_ensure)

        self.setMinimumWidth(1280)
        self.setMinimumHeight(800)

        # --------------------- Editor ----------------------

        self.__memo_editor.closeEvent = self.on_editor_closed

        # ---------------------- Chart ----------------------

        self.__vnpy_chart.add_plot("candle", hide_x_axis=True)
        self.__vnpy_chart.add_plot("volume", maximum_height=200)
        self.__vnpy_chart.add_plot("memo", maximum_height=50)

        self.__vnpy_chart.add_item(CandleItem, "candle", "candle")
        self.__vnpy_chart.add_item(VolumeItem, "volume", "volume")
        self.__vnpy_chart.add_item(MemoItem, "memo", "memo")

        self.__vnpy_chart.add_cursor()
        self.__vnpy_chart.scene().sigMouseClicked.connect(
            self.on_chart_clicked)

    @pyqtSlot(MouseClickEvent)
    def on_chart_clicked(self, event: MouseClickEvent):
        if not event.double or self.__accepted:
            return
        self.__accepted = True
        scene_pt = event.scenePos()
        items = self.__vnpy_chart.scene().items(scene_pt)
        for i in items:
            if isinstance(i, pg.PlotItem):
                view = i.getViewBox()
                view_pt = view.mapSceneToView(scene_pt)
                self.popup_memo_editor(view_pt.x())
                break
        # print("Plots:" + str([x for x in items if isinstance(x, pg.PlotItem)]))

    def on_timer(self):
        # Workaround for click event double fire
        self.__accepted = False

    def on_button_memo(self):
        enable = self.__check_memo.isChecked()

    def on_button_volume(self):
        enable = self.on_button_volume.isChecked()

    def on_button_ensure(self):
        input_securities = self.__combo_name.currentText()
        if '|' in input_securities:
            input_securities = input_securities.split('|')[0].strip()

        if self.__radio_adj_tail.isChecked():
            adjust_method = StockHistoryUi.ADJUST_TAIL
        elif self.__radio_adj_head.isChecked():
            adjust_method = StockHistoryUi.ADJUST_HEAD
        elif self.__radio_adj_none.isChecked():
            adjust_method = StockHistoryUi.ADJUST_NONE
        else:
            adjust_method = StockHistoryUi.ADJUST_NONE

        if self.__radio_log_return.isChecked():
            return_style = StockHistoryUi.RETURN_LOG
        elif self.__radio_simple_return.isChecked():
            return_style = StockHistoryUi.RETURN_SIMPLE
        else:
            return_style = StockHistoryUi.RETURN_SIMPLE

        if not self.load_security_data(input_securities, adjust_method,
                                       return_style):
            QMessageBox.information(
                self, QtCore.QCoreApplication.translate('History', '没有数据'),
                QtCore.QCoreApplication.translate('History',
                                                  '没有交易数据,请检查证券编码或更新本地数据'),
                QMessageBox.Ok, QMessageBox.Ok)
        else:
            self.load_security_memo()
            self.__vnpy_chart.refresh_history()

    def on_editor_closed(self, event):
        self.load_security_memo()
        self.__vnpy_chart.refresh_history()

    def popup_memo_editor(self, ix: float):
        bar_data = self.__vnpy_chart.get_bar_manager().get_bar(ix)
        if bar_data is not None:
            _time = bar_data.datetime.to_pydatetime()
            self.popup_memo_editor_by_time(_time)
        else:
            self.popup_memo_editor_by_time(now())

    def popup_memo_editor_by_time(self, _time: datetime):
        self.__memo_editor.select_memo_by_time(_time)
        # self.__memo_editor.show()
        self.__memo_editor.exec()

    def load_security_data(self, securities: str, adjust_method: int,
                           return_style: int) -> bool:
        data_utility = self.__sas.get_data_hub_entry().get_data_utility()
        index_dict = data_utility.get_support_index()

        if securities != self.__paint_securities or self.__paint_trade_data is None:
            if securities in index_dict.keys():
                uri = 'TradeData.Index.Daily'
            else:
                uri = 'TradeData.Stock.Daily'
            trade_data = self.__sas.get_data_hub_entry().get_data_center(
            ).query(uri, securities)

            # base_path = os.path.dirname(os.path.abspath(__file__))
            # history_path = os.path.join(base_path, 'History')
            # depot_path = os.path.join(history_path, 'depot')
            # his_file = os.path.join(depot_path, securities + '.his')

            # self.__memo_file = his_file
            self.__paint_trade_data = trade_data
            self.__paint_securities = securities

        if self.__paint_trade_data is None or len(
                self.__paint_trade_data) == 0:
            return False

        trade_data = pd.DataFrame()
        if adjust_method == StockHistoryUi.ADJUST_TAIL and 'adj_factor' in self.__paint_trade_data.columns:
            trade_data['open'] = self.__paint_trade_data[
                'open'] * self.__paint_trade_data['adj_factor']
            trade_data['close'] = self.__paint_trade_data[
                'close'] * self.__paint_trade_data['adj_factor']
            trade_data['high'] = self.__paint_trade_data[
                'high'] * self.__paint_trade_data['adj_factor']
            trade_data['low'] = self.__paint_trade_data[
                'low'] * self.__paint_trade_data['adj_factor']
        elif adjust_method == StockHistoryUi.ADJUST_HEAD and 'adj_factor' in self.__paint_trade_data.columns:
            trade_data['open'] = self.__paint_trade_data[
                'open'] / self.__paint_trade_data['adj_factor']
            trade_data['close'] = self.__paint_trade_data[
                'close'] / self.__paint_trade_data['adj_factor']
            trade_data['high'] = self.__paint_trade_data[
                'high'] / self.__paint_trade_data['adj_factor']
            trade_data['low'] = self.__paint_trade_data[
                'low'] / self.__paint_trade_data['adj_factor']
        else:
            trade_data['open'] = self.__paint_trade_data['open']
            trade_data['close'] = self.__paint_trade_data['close']
            trade_data['high'] = self.__paint_trade_data['high']
            trade_data['low'] = self.__paint_trade_data['low']
        trade_data['amount'] = self.__paint_trade_data['amount']
        trade_data['trade_date'] = pd.to_datetime(
            self.__paint_trade_data['trade_date'])

        if return_style == StockHistoryUi.RETURN_LOG:
            trade_data['open'] = np.log(trade_data['open'])
            trade_data['close'] = np.log(trade_data['close'])
            trade_data['high'] = np.log(trade_data['high'])
            trade_data['low'] = np.log(trade_data['low'])

        bars = self.df_to_bar_data(trade_data, securities)
        self.__vnpy_chart.get_bar_manager().update_history(bars)

        return True

    def load_security_memo(self) -> bool:
        self.__memo_editor.select_stock(self.__paint_securities)

        memo_record = self.__memo_recordset.get_record(self.__paint_securities)
        bar_manager = self.__vnpy_chart.get_bar_manager()

        if memo_record is None or bar_manager is None:
            return False

        try:
            memo_df = memo_record.get_records().copy()
            memo_df['normalised_time'] = memo_df['time'].dt.normalize()
            memo_df_grouped = memo_df.groupby('normalised_time')
        except Exception as e:
            return False
        finally:
            pass

        max_memo_count = 0
        for group_time, group_df in memo_df_grouped:
            memo_count = len(group_df)
            max_memo_count = max(memo_count, max_memo_count)
            bar_manager.set_item_data(group_time, 'memo', group_df)
        bar_manager.set_item_data_range('memo', 0.0, max_memo_count)

        # memo_item = self.__vnpy_chart.get_item('memo')
        # if memo_item is not None:
        #     memo_item.refresh_history()
        # self.__vnpy_chart.update_history()

        return True

    # TODO: Move it to common place
    @staticmethod
    def df_to_bar_data(df: pd.DataFrame,
                       securities: str,
                       exchange: Exchange = Exchange.SSE) -> [BarData]:
        # 98 ms
        bars = []
        for trade_date, amount, open, close, high, low in \
                zip(df['trade_date'], df['amount'], df['open'], df['close'], df['high'], df['low']):
            bar = BarData(datetime=trade_date,
                          exchange=exchange,
                          symbol=securities)

            bar.interval = Interval.DAILY
            bar.volume = amount * 10000
            bar.open_interest = 0
            bar.open_price = open
            bar.high_price = high
            bar.low_price = low
            bar.close_price = close
            bars.append(bar)
        return bars
Example #18
0
    class WMWidget(QWidget):
        # handled = False # flag that value is written from wavemeter
        def __init__(self, parent=None, data=None, signals=None):
            self.parent = parent
            self.data = data
            self.signals = signals
            self.lastMessage = ''
            super().__init__(parent=self.parent)
            self.setWindowTitle('My WavelengthMeter')
            self.setWindowIcon(QIcon('Devices\WavelengthMeter\icon.jpg'))
            self.plot_window1 = pg.PlotWidget()
            self.plot_window2 = pg.PlotWidget()
            self.read_data = []
            self.shotN = 0
            # self.plot_window.plot(range(10),range(10))

            main_layout = QVBoxLayout()

            menu_layout = QHBoxLayout()
            chan_btn = QPushButton('Channels')
            chan_menu = QMenu(chan_btn)
            chan_menu.aboutToShow.connect(self.updateChannelsMenu)
            chan_btn.setMenu(chan_menu)
            menu_layout.addWidget(chan_btn)

            n_channels_per_line = QSpinBox()
            n_channels_per_line.setMinimum(2)
            n_channels_per_line.setMaximum(10)
            n_channels_per_line.setValue(self.data.n_channels)
            n_channels_per_line.valueChanged.connect(self.nCannelsChanged)
            menu_layout.addWidget(n_channels_per_line)

            menu_layout.addWidget(QLabel('per line'))

            menu_layout.addStretch(1)

            timer_len = QSpinBox()
            timer_len.setMinimum(10)
            timer_len.setMaximum(10000)
            timer_len.setValue(self.data.timer_interval)
            timer_len.valueChanged.connect(self.temerIntervalChanged)
            menu_layout.addWidget(timer_len)

            mode_group = QButtonGroup()
            self.all_btn = QRadioButton('all')
            self.all_btn.setChecked(self.data.mode == 'all')
            self.all_btn.toggled.connect(self.modeChanged)
            mode_group.addButton(self.all_btn)
            menu_layout.addWidget(self.all_btn)

            self.single_btn = QRadioButton('single')
            self.single_btn.setChecked(self.data.mode != 'all')
            self.single_btn.toggled.connect(self.modeChanged)
            mode_group.addButton(self.single_btn)
            menu_layout.addWidget(self.single_btn)

            single_menu_btn = QPushButton('Single ch.')
            single_menu = QMenu(single_menu_btn)
            single_menu.aboutToShow.connect(self.updateSingleMenu)
            single_menu_btn.setMenu(single_menu)
            menu_layout.addWidget(single_menu_btn)

            main_layout.addLayout(menu_layout)

            temp_layout = QHBoxLayout()
            self.arduinoWidget = self.data.arduino.Widget(
                parent=self, data=self.data.arduino)
            self.arduinoWidget.setMaximumWidth(300)
            temp_layout.addWidget(self.arduinoWidget)

            plots_layout = QVBoxLayout()
            plots_layout.addWidget(self.plot_window1)
            plots_layout.addWidget(self.plot_window2)

            temp_layout.addLayout(plots_layout)
            main_layout.addLayout(temp_layout)

            self.channels_layout = QGridLayout()
            self.drawChannels()

            main_layout.addLayout(self.channels_layout)
            self.setLayout(main_layout)

            self.window().setGeometry(1920, 1080, 1920, 1080)
            self.setWindowState(Qt.WindowMaximized)
            # print('WLM_GUI created')
            self.timer = QTimer(self)
            self.timer.setInterval(self.data.timer_interval)
            self.timer.timeout.connect(self.routine)
            self.timer.start()
            self.timer2 = QTimer(self)
            self.timer2.timeout.connect(self.checkWM)
            if self.signals:
                self.signals.arduinoReceived.connect(self.timer2.start)

        def temerIntervalChanged(self, new_val):
            self.data.timer_interval = new_val
            self.data.save()
            self.timer.stop()
            self.timer.setInterval(self.data.timer_interval)
            self.timer.start()

        def nCannelsChanged(self, new_val):
            self.data.n_channels = new_val
            self.data.save()

        def modeChanged(self):
            if self.sender().text() == 'all':
                self.single_btn.setChecked(not self.all_btn.isChecked())
            if self.sender().text() == 'single':
                self.all_btn.setChecked(not self.single_btn.isChecked())
            # print(self.sender().text(),self.sender().isChecked())
            self.data.mode = 'all' if self.all_btn.isChecked() else 'single'

        def updateSingleMenu(self):
            channels_menu = self.sender()
            channels_menu.clear()
            for channel in self.data.channels:
                # print(channel.name)
                act = channels_menu.addAction(channel.name)
                act.triggered.connect(self.updateSingleIndex)

        def updateSingleIndex(self):
            name = self.sender().text()
            # print('single ',name)
            for i, channel in enumerate(self.data.channels):
                if channel.name == name:
                    self.data.single_index = i
                    break
            # print('single index ', self.data.single_index)

        def keyPressEvent(self, QKeyEvent):
            if QKeyEvent.key() == Qt.Key_F5 and self.shotN == 0:
                self.signals.shutterChange.emit(self.lastMessage)
            return

        def routine(self):
            # global cicle_counter
            # cicle_counter += 1
            print(self.data.arduino.connected)
            if not self.data.arduino.connected:
                return False
            self.timer.stop()
            # print("Cicle #",cicle_counter)
            # print(self.data.current_index)
            # print(self.data.active_channels_indexes)
            if self.data.mode == 'all':
                self.data.current_index = self.data.active_channels_indexes[
                    (self.data.active_channels_indexes.index(
                        self.data.current_index) + 1) %
                    len(self.data.active_channels_indexes)]
            else:
                self.data.current_index = self.data.single_index
            # print('current index ',self.data.current_index)
            arr_to_arduino = [(self.data.channels[i].shutter_number,
                               int(i == self.data.current_index))
                              for i in range(len(self.data.channels))]
            # resp = self.data.arduino.setWMShutters(arr_to_arduino)
            message = 'WMShutters'
            for chan, state in arr_to_arduino:
                message += ' %i %i' % (chan, state)
            message += '!'
            # print(message)
            # status, readout = self.write_read_com(message)
            # check resp
            time_per_shot = self.data.wavemeter.exposure
            # print('Time per shot ',time_per_shot)
            self.read_data = []
            read_success = False
            self.shotN = 0
            self.timer2.setInterval(time_per_shot)
            self.lastMessage = message
            self.timer2.start()
            # self.signals.shutterChange.emit(message)
            # self.cycleTimer.start()

        def checkWM(self):
            # print('checkWM')
            self.shotN += 1
            i = self.shotN
            try:
                wm_data = {
                    'wavelength': self.data.wavemeter.wavelength,
                    'frequency': self.data.wavemeter.frequency,
                    'amplitudes': self.data.wavemeter.amplitudes,
                    'spectrum': self.data.wavemeter.spectrum,
                    'exposure': self.data.wavemeter.exposure
                }
            except Exception as e:
                print(e)
                raise e
            # print(wm_data['wavelength'])
            self.read_data.append(wm_data)
            # print(wm_data['wavelength'])
            if (i > self.data.N_SHOTS_MIN
                    and abs(wm_data['wavelength'] -
                            self.read_data[-2]['wavelength']) <=
                    self.data.EXCEPTABLE_WAVELENGTH_ERROR
                    and abs(wm_data['wavelength'] -
                            self.read_data[-2]['wavelength']) <=
                    self.data.EXCEPTABLE_WAVELENGTH_ERROR
                    and wm_data["exposure"] * i > 100
                    or i > self.data.N_SHOTS_MAX):
                self.timer2.stop()
                # print('Steady state reached; i=', i)
                # print(wm_data['wavelength'])
                read_success = True
                channel = self.data.channels[self.data.current_index]
                channel.wavelength = wm_data['wavelength']
                channel.frequency = wm_data['frequency']
                channel.amplitudes = wm_data['amplitudes']
                channel.spectrum = wm_data['spectrum']
                # self.signals.wvlChanged.emit(' '.join([str(channel.frequency) for channel in self.data.channels]))
                self.drawChannels()
                self.drawSpecta()
                self.timer.start()

        def drawSpecta(self):
            self.plot_window1.clear()
            self.plot_window2.clear()
            active_channels = [
                channel for channel in self.data.channels
                if (channel.is_active and channel.show_spectrum)
            ]
            for i, channel in enumerate(active_channels):
                spectr = channel.spectrum[0]
                # for spectr in channel.spectrum[:1]:
                if len(spectr):
                    # print(len(spectr))
                    self.plot_window1.plot(np.arange(1024),
                                           spectr[:1024],
                                           pen=pg.mkPen(color=channel.color))
                spectr = channel.spectrum[1]
                # for spectr in channel.spectrum[:1]:
                if len(spectr):
                    # print(len(spectr))
                    self.plot_window2.plot(np.arange(1024),
                                           spectr[:1024],
                                           pen=pg.mkPen(color=channel.color))

        def drawChannels(self):
            # cleen up previous grid
            while self.channels_layout.count():
                item = self.channels_layout.takeAt(0)
                item.widget().deleteLater()
            active_channels = [
                channel for channel in self.data.channels if channel.is_active
            ]
            self.data.active_channels_indexes = [
                i for i, channel in enumerate(self.data.channels)
                if channel.is_active
            ]
            # print(active_channels)
            # print('Frame ',self.frameGeometry().width())
            # print('widget', active_channels[0].width())
            for i, channel in enumerate(active_channels):
                # print(i % 2, i // 2)
                chan_widget = channel.WMChannelGUI(parent=self, data=channel)
                # print('Widget ', chan_widget.frameGeometry().width())
                self.channels_layout.addWidget(chan_widget,
                                               i // self.data.n_channels,
                                               i % self.data.n_channels)

        def updateChannelsMenu(self):
            # print('updateAllScanParams')
            # print(self.data.globals)
            channels_menu = self.sender()
            channels_menu.clear()
            for channel in self.data.channels:
                # print(channel.name)
                m = channels_menu.addMenu(channel.name)
                text = 'hide' if channel.is_active else 'show'
                act = m.addAction(text)
                # act.triggered.connect(lambda:self.showHideChannel(channel))
                act.triggered.connect(self.showHideChannel)
                act = m.addAction('del')
                # act.triggered.connect(lambda:self.delChannel(channel))
                act.triggered.connect(self.delChannel)
            new_chan_act = channels_menu.addAction('new')
            new_chan_act.triggered.connect(
                lambda: self.NewChannelWidget(parent=self))

        def showHideChannel(self, channel):
            # channel.is_active = not channel.is_active
            name = self.sender().parent().title()
            for channel in self.data.channels:
                if channel.name == name:
                    channel.is_active = not channel.is_active
                    break
            self.drawChannels()
            self.data.save()

        def delChannel(self):
            # print(self.sender().parent().title())
            name = self.sender().parent().title()
            self.data.delChannel(name)
            self.drawChannels()
            self.data.save()

        def addNewChannel(self, caller):
            if caller.exit_status:
                # a = self.NewChannelWidget(parent=self)
                new_name = caller.name.text()
                new_shutter_channel = caller.shutter_channel.value()
                self.data.addChannel(name=new_name,
                                     shutter_number=new_shutter_channel)
                # self.data.channels.append(new_channel)
                # print(new_name, new_shutter_channel)
                self.drawChannels()
            del caller
            self.data.save()

        class NewChannelWidget(QDialog):
            def __init__(self, parent=None, data=None):
                super().__init__(parent)
                self.parent = parent
                # self.data = data
                # self.initUI()
                main_layout = QVBoxLayout()

                line1 = QHBoxLayout()
                line1.addWidget(QLabel('Name'))
                self.name = QLineEdit()
                line1.addWidget(self.name)
                main_layout.addLayout(line1)

                line2 = QHBoxLayout()
                line2.addWidget(QLabel('Shutter_channel'))
                self.shutter_channel = QSpinBox()
                self.shutter_channel.setMaximum(18)
                self.shutter_channel.setMinimum(0)
                self.shutter_channel.setMinimumWidth(10)
                line2.addWidget(self.shutter_channel)
                # line1.addWidget(self.name)
                main_layout.addLayout(line2)

                ok_cancel = QHBoxLayout()
                ok_btn = QPushButton('Create')
                ok_btn.clicked.connect(self.createChannel)
                ok_cancel.addWidget(ok_btn)

                cancel_btn = QPushButton('Cancel')
                cancel_btn.clicked.connect(self.cancelPressed)
                ok_cancel.addWidget(cancel_btn)

                main_layout.addLayout(ok_cancel)
                self.setLayout(main_layout)
                self.show()

            def createChannel(self):
                self.exit_status = True
                # data_to_send = {'name':self.name, 'shutter_channel':self.shutter_channel}
                self.close()
                self.parent.addNewChannel(self)

            def cancelPressed(self):
                self.exit_status = False
                self.close()
                self.parent.addNewChannel(self)
Example #19
0
File: SafeB.py Project: lebik/SafeB
class SafeB(QWidget):
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.initUI()

    def initUI(self):
        self.center()
        self.setFixedSize(435, 400)
        self.setWindowTitle('SafeB')
        self.setWindowIcon(QIcon('logo.png'))

        # Add LineEdit for Puth
        self.line_edit = QLineEdit(self)
        self.line_edit.setReadOnly(True)
        self.line_edit.resize(250, 23)
        self.line_edit.move(5, 5)
        self.line_edit.setText('Path to file')
        self.line_edit.setStyleSheet("color: rgb(167, 167, 167);")
        self.line_edit.setAcceptDrops(True)
        self.line_edit.textChanged.connect(self.onChangedPath)

        self.radio1 = QRadioButton(self)
        self.radio1.setText('one image')
        self.radio1.move(262, 37)
        self.radio1.setChecked(True)
        config.rad1 = self.radio1

        self.radio2 = QRadioButton(self)
        self.radio2.setText('few images')
        self.radio2.move(340, 37)
        config.rad2 = self.radio2

        # Add LineEdit for Username
        self.username = QLineEdit(self)
        self.username.resize(250, 23)
        self.username.move(5, 33)
        self.username.setText('Username')
        self.username.setStyleSheet("color: rgb(167, 167, 167);")
        self.username.textChanged.connect(self.onChanged2)
        self.username.mousePressEvent = lambda _: \
            self.username.selectAll()
        config.usern = self.username

        # Add LineEdit for Password
        self.password = QLineEdit(self)
        self.password.resize(250, 23)
        self.password.move(5, 61)
        self.password.setText('Password')
        self.password.setStyleSheet("color: rgb(167, 167, 167);")
        self.password.textChanged.connect(self.onChanged)
        self.password.mousePressEvent = lambda _: \
            self.password.selectAll()
        config.pwd = self.password

        # Add result textline
        self.resultText = QLabel(self)
        self.resultText.move(262, 50) #262
        self.resultText.resize(200, 46)
        self.resultText.setText('Score: ')
        self.resultText.setStyleSheet("color: rgb(167, 167, 167);")
        config.res = self.resultText


        # Add LineEdit for classifier_ids
        self.classifier_ids = QLineEdit(self)
        self.classifier_ids.resize(250, 23)
        self.classifier_ids.move(5, 89)
        self.classifier_ids.setText('Classifier_ids')
        self.classifier_ids.setStyleSheet("color: rgb(167, 167, 167);")
        self.classifier_ids.textChanged.connect(self.onChanged3)
        self.classifier_ids.mousePressEvent = lambda _: \
            self.classifier_ids.selectAll()
        config.c_id = self.classifier_ids

        # image for send
        self.pic = QLabel(self)
        self.pic.resize(567, 278)
        self.pic.move(5, 117)
        config.pic = self.pic

        # Add AddButton to type the Puth
        self.btn_add = QPushButton('Add', self)
        self.btn_add.resize(self.btn_add.sizeHint())
        self.btn_add.move(260, 5)
        self.btn_add.clicked.connect(self.showDialog)
        config.addB = self.btn_add

        # Add SendButton to send a picture
        self.btn_send = QPushButton('Send', self)
        self.btn_send.resize(self.btn_send.sizeHint())
        self.btn_send.move(340, 5)
        self.btn_send.clicked.connect(self.sendPic)
        config.sendB = self.btn_send

        self.show()

    def showDialog(self):
        if self.radio1.isChecked():
            path = QFileDialog.getOpenFileName()
        else:
            path = QFileDialog.getExistingDirectory()
        if ''.join(path) != '':
            config.path = ''.join(path)
            self.line_edit.setText(config.path)

    def onChangedPath(self, text):
        self.line_edit.setStyleSheet("color: rgb(0, 0, 0);")
        if text[0:8] == 'file:///':
            config.path = text[8:]
            self.line_edit.setText(config.path)
        # use full ABSOLUTE path to the image, not relative
        try:
            self.pic.setPixmap(QtGui.QPixmap(config.path).scaledToHeight(278))
        except:
            print('Not image!')
        str = config.path
        str_split = str.split('/')
        if parse_name(str_split):
            self.radio1.setChecked(True)
        else:
            self.radio2.setChecked(True)

    def onChanged(self, text):
        config.password = text
        self.password.setEchoMode(2)
        self.password.setStyleSheet("color: rgb(0, 0, 0);")

    def onChanged2(self, text):
        config.username = text
        self.username.setStyleSheet("color: rgb(0, 0, 0);")

    def onChanged3(self, text):
        config.classifier_ids = text
        self.classifier_ids.setStyleSheet("color: rgb(0, 0, 0);")

    def sendPic(self):
        self.resultText.setText('Processing...')
        self.resultText.setStyleSheet("color: rgb(0, 0, 0);")
        self.btn_send.setEnabled(False)
        self.btn_add.setEnabled(False)
        self.radio1.setEnabled(False)
        self.radio2.setEnabled(False)
        config.usern.setEnabled(False)
        config.pwd.setEnabled(False)
        config.c_id.setEnabled(False)
        runnable = Runnable()
        QtCore.QThreadPool.globalInstance().start(runnable)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            super(SafeB, self).dragEnterEvent(event)

    def dropEvent(self, e):
        self.line_edit.setStyleSheet("color: rgb(0, 0, 0);")
        self.line_edit.setText(e.mimeData().text())
        config.path = self.line_edit.text()
Example #20
0
class SortDialog(QDialog):

    def __init__(self, desc=None, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Sort…"))

        self.smartSortBox = QRadioButton(self.tr("Canned sort"), self)
        self.smartSortBox.setToolTip(
            self.tr("A combination of simple, complex and custom "
                    "sorts that give optimized ordering results."))
        self.glyphSetBox = QRadioButton(self.tr("Glyph set"), self)
        self.glyphSetBox.toggled.connect(self.glyphSetToggle)
        self.glyphSetDrop = QComboBox(self)
        self.glyphSetDrop.setEnabled(False)
        glyphSets = settings.readGlyphSets()
        for name, glyphNames in glyphSets.items():
            self.glyphSetDrop.addItem(name, glyphNames)
        self.customSortBox = QRadioButton(self.tr("Custom…"), self)
        self.customSortBox.toggled.connect(self.customSortToggle)

        self.customSortGroup = QGroupBox(parent=self)
        self.customSortGroup.setEnabled(False)
        descriptorsCount = 6
        if desc is None:
            pass
        elif desc[0]["type"] == "glyphSet":
            self.glyphSetBox.setChecked(True)
            self.glyphSetDrop.setEnabled(True)
            # XXX: we must handle unknown glyphSets... or glyphSets with
            # the same name but different
            self.glyphSetDrop.setCurrentText(desc[0]["name"])
        elif desc[0]["type"] == "cannedDesign":
            self.smartSortBox.setChecked(True)
        else:
            self.customSortBox.setChecked(True)
            self.customSortGroup.setEnabled(True)
            descriptorsCount = len(desc)
        self.customDescriptors = [[] for i in range(descriptorsCount)]
        self.customSortLayout = QGridLayout()
        for i, line in enumerate(self.customDescriptors):
            line.append(QComboBox(self))
            line[0].insertItems(0, sortItems)
            line.append(QCheckBox(self.tr("Ascending"), self))
            line.append(QCheckBox(self.tr("Allow pseudo-unicode"), self))
            if self.customSortBox.isChecked():
                line[0].setCurrentIndex(
                    self.indexFromItemName(desc[i]["type"]))
                line[1].setChecked(desc[i]["ascending"])
                line[2].setChecked(desc[i]["allowPseudoUnicode"])
            else:
                line[0].setCurrentIndex(i)
                line[1].setChecked(True)
                line[2].setChecked(True)
            self.customSortLayout.addWidget(line[0], i, 0)
            self.customSortLayout.addWidget(line[1], i, 1)
            self.customSortLayout.addWidget(line[2], i, 2)
            btn = QPushButton(self)
            btn.setFixedWidth(32)
            btn.setProperty("index", i)
            line.append(btn)
            self.customSortLayout.addWidget(btn, i, 3)
            if i == 0:
                btn.setText("+")
                btn.clicked.connect(self._addRow)
                self.addLineButton = btn
            else:
                btn.setText("−")
                btn.clicked.connect(self._deleteRow)
        self.customSortGroup.setLayout(self.customSortLayout)

        buttonBox = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QVBoxLayout(self)
        layout.addWidget(self.smartSortBox)
        layout.addWidget(self.glyphSetBox)
        layout.addWidget(self.glyphSetDrop)
        layout.addWidget(self.customSortBox)
        layout.addWidget(self.customSortGroup)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

    def _addRow(self):
        i = len(self.customDescriptors)
        line = []
        line.append(QComboBox(self))
        line[0].insertItems(0, sortItems)
        line[0].setCurrentIndex(0)
        line.append(QCheckBox("Ascending", self))
        line.append(QCheckBox("Allow pseudo-unicode", self))
        btn = QPushButton("−", self)
        btn.setFixedWidth(32)
        btn.setProperty("index", i)
        btn.clicked.connect(self._deleteRow)
        line.append(btn)
        self.customDescriptors.append(line)
        self.customSortLayout.addWidget(line[0], i, 0)
        self.customSortLayout.addWidget(line[1], i, 1)
        self.customSortLayout.addWidget(line[2], i, 2)
        self.customSortLayout.addWidget(line[3], i, 3)
        if i == 7:
            self.sender().setEnabled(False)

    def _deleteRow(self):
        rel = self.sender().property("index")
        desc = self.customDescriptors
        for i in range(rel + 1, len(desc) - 1):
            desc[i][0].setCurrentIndex(desc[i + 1][0].currentIndex())
            desc[i][1].setChecked(desc[i + 1][1].isChecked())
            desc[i][2].setChecked(desc[i + 1][2].isChecked())
        for elem in desc[-1]:
            elem.setParent(None)
        del self.customDescriptors[-1]
        self.addLineButton.setEnabled(True)
        self.adjustSize()

    def indexFromItemName(self, name):
        for index, item in enumerate(sortItems):
            if name == item:
                return index
        print(self.tr("Unknown descriptor name: %s"), name)
        return 0

    @classmethod
    def getDescriptor(cls, parent, sortDescriptor=None):
        dialog = cls(sortDescriptor, parent)
        result = dialog.exec_()
        if dialog.glyphSetBox.isChecked():
            data = dialog.glyphSetDrop.currentData()
            name = dialog.glyphSetDrop.currentText()
            ret = [
                dict(type="glyphSet", glyphs=data, name=name)
            ]
        elif dialog.customSortBox.isChecked():
            descriptors = []
            for line in dialog.customDescriptors:
                descriptors.append(dict(
                    type=line[0].currentText(),
                    ascending=line[1].isChecked(),
                    allowPseudoUnicode=line[2].isChecked()))
            ret = descriptors
        else:
            ret = [
                dict(type="cannedDesign", allowPseudoUnicode=True)
            ]
        return (ret, result)

    def glyphSetToggle(self):
        checkBox = self.sender()
        self.glyphSetDrop.setEnabled(checkBox.isChecked())

    def customSortToggle(self):
        checkBox = self.sender()
        self.customSortGroup.setEnabled(checkBox.isChecked())
Example #21
0
class IconEditorPalette(QWidget):
    """
    Class implementing a palette widget for the icon editor.
    
    @signal colorSelected(QColor) emitted after a new color has been selected
    @signal compositingChanged(QPainter.CompositionMode) emitted to signal a
        change of the compositing mode
    """
    colorSelected = pyqtSignal(QColor)
    compositingChanged = pyqtSignal(QPainter.CompositionMode)
    
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(IconEditorPalette, self).__init__(parent)
        
        if self.layoutDirection == Qt.Horizontal:
            direction = QBoxLayout.LeftToRight
        else:
            direction = QBoxLayout.TopToBottom
        self.__layout = QBoxLayout(direction, self)
        self.setLayout(self.__layout)
        
        self.__preview = QLabel(self)
        self.__preview.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.__preview.setFixedHeight(64)
        self.__preview.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.__preview.setWhatsThis(self.tr(
            """<b>Preview</b>"""
            """<p>This is a 1:1 preview of the current icon.</p>"""
        ))
        self.__layout.addWidget(self.__preview)
        
        self.__color = QLabel(self)
        self.__color.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.__color.setFixedHeight(24)
        self.__color.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.__color.setWhatsThis(self.tr(
            """<b>Current Color</b>"""
            """<p>This is the currently selected color used for drawing.</p>"""
        ))
        self.__layout.addWidget(self.__color)
        
        self.__colorTxt = QLabel(self)
        self.__colorTxt.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.__colorTxt.setWhatsThis(self.tr(
            """<b>Current Color Value</b>"""
            """<p>This is the currently selected color value used for"""
            """ drawing.</p>"""
        ))
        self.__layout.addWidget(self.__colorTxt)
        
        self.__colorButton = QPushButton(self.tr("Select Color"), self)
        self.__colorButton.setWhatsThis(self.tr(
            """<b>Select Color</b>"""
            """<p>Select the current drawing color via a color selection"""
            """ dialog.</p>"""
        ))
        self.__colorButton.clicked.connect(self.__selectColor)
        self.__layout.addWidget(self.__colorButton)
        
        self.__colorAlpha = QSpinBox(self)
        self.__colorAlpha.setRange(0, 255)
        self.__colorAlpha.setWhatsThis(self.tr(
            """<b>Select alpha channel value</b>"""
            """<p>Select the value for the alpha channel of the current"""
            """ color.</p>"""
        ))
        self.__layout.addWidget(self.__colorAlpha)
        self.__colorAlpha.valueChanged[int].connect(self.__alphaChanged)
        
        self.__compositingGroup = QGroupBox(self.tr("Compositing"), self)
        self.__compositingGroupLayout = QVBoxLayout(self.__compositingGroup)
        self.__compositingGroup.setLayout(self.__compositingGroupLayout)
        self.__sourceButton = QRadioButton(self.tr("Replace"),
                                           self.__compositingGroup)
        self.__sourceButton.setWhatsThis(self.tr(
            """<b>Replace</b>"""
            """<p>Replace the existing pixel with a new color.</p>"""
        ))
        self.__sourceButton.clicked[bool].connect(self.__compositingChanged)
        self.__compositingGroupLayout.addWidget(self.__sourceButton)
        self.__sourceOverButton = QRadioButton(self.tr("Blend"),
                                               self.__compositingGroup)
        self.__sourceOverButton.setWhatsThis(self.tr(
            """<b>Blend</b>"""
            """<p>Blend the new color over the existing pixel.</p>"""
        ))
        self.__sourceOverButton.setChecked(True)
        self.__sourceOverButton.clicked[bool].connect(
            self.__compositingChanged)
        self.__compositingGroupLayout.addWidget(self.__sourceOverButton)
        self.__layout.addWidget(self.__compositingGroup)
        
        spacer = QSpacerItem(
            10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.__layout.addItem(spacer)
    
    def previewChanged(self, pixmap):
        """
        Public slot to update the preview.
        
        @param pixmap new preview pixmap (QPixmap)
        """
        self.__preview.setPixmap(pixmap)
    
    def colorChanged(self, color):
        """
        Public slot to update the color preview.
        
        @param color new color (QColor)
        """
        self.__currentColor = color
        self.__currentAlpha = color.alpha()
        
        pm = QPixmap(90, 18)
        pm.fill(color)
        self.__color.setPixmap(pm)
        
        self.__colorTxt.setText(
            "{0:d}, {1:d}, {2:d}, {3:d}".format(
                color.red(), color.green(), color.blue(), color.alpha()))
        
        self.__colorAlpha.setValue(self.__currentAlpha)
    
    def __selectColor(self):
        """
        Private slot to select a new drawing color.
        """
        col = QColorDialog.getColor(self.__currentColor)
        col.setAlpha(self.__currentAlpha)
        
        if col.isValid():
            self.colorSelected.emit(col)
    
    def __alphaChanged(self, val):
        """
        Private slot to track changes of the alpha channel.
        
        @param val value of the alpha channel
        """
        if val != self.__currentAlpha:
            col = QColor(self.__currentColor)
            col.setAlpha(val)
            self.colorSelected.emit(col)
    
    def setCompositingMode(self, mode):
        """
        Public method to set the compositing mode.
        
        @param mode compositing mode to set (QPainter.CompositionMode)
        """
        if mode == QPainter.CompositionMode_Source:
            self.__sourceButton.setChecked(True)
        elif mode == QPainter.CompositionMode_SourceOver:
            self.__sourceOverButton.setChecked(True)
    
    def __compositingChanged(self, on):
        """
        Private slot to handle a change of the compositing mode.
        
        @param on flag indicating the checked state of the compositing button
            (boolean)
        """
        if on:
            if self.__sourceButton.isChecked():
                self.compositingChanged.emit(
                    QPainter.CompositionMode_Source)
            elif self.__sourceOverButton.isChecked():
                self.compositingChanged.emit(
                    QPainter.CompositionMode_SourceOver)
Example #22
0
class TransitionCodeDialog(QDialog):
    codeChanged = pyqtSignal('int', 'QString', 'QString')

    def __init__(self, name, transition):
        super(QDialog, self).__init__()
        self.transition = transition
        self.setWindowTitle(name)
        self.resize(800, 600)

        self.codeEdit = QsciScintilla()
        self.codeEdit.setText(self.transition.getCode())
        fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        self.codeEdit.setFont(fixedWidthFont)
        fontmetrics = QFontMetrics(fixedWidthFont)
        self.codeEdit.setMarginWidth(0, fontmetrics.width("000"))
        self.codeEdit.setMarginLineNumbers(0, True)
        self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc"))

        self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.codeEdit.setCaretLineVisible(True)
        self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4"))
        lexer = QsciLexerPython()
        lexer.setDefaultFont(fixedWidthFont)
        self.codeEdit.setLexer(lexer)
        self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.codeEdit.setUtf8(True)

        self.codeEdit.setTabWidth(4)
        self.codeEdit.setIndentationsUseTabs(True)
        self.codeEdit.setIndentationGuides(True)
        self.codeEdit.setTabIndents(True)
        self.codeEdit.setAutoIndent(True)

        self.cancelButton = QPushButton('Cancel')
        self.cancelButton.clicked.connect(self.cancel)
        self.acceptButton = QPushButton('Accept')
        self.acceptButton.clicked.connect(self.accept)

        self.language = 'python'
        self.pythonButton = QRadioButton('Python')
        self.pythonButton.setChecked(True)
        self.pythonButton.clicked.connect(self.pythonClicked)
        self.cppButton = QRadioButton('C++')
        self.cppButton.clicked.connect(self.cppClicked)

        codeLanguageContainer = QWidget()
        hLayout0 = QHBoxLayout()
        hLayout0.addWidget(self.pythonButton)
        hLayout0.addWidget(self.cppButton)
        codeLanguageContainer.setLayout(hLayout0)

        self.temporalButton = QRadioButton('Temporal', self)
        self.temporalButton.toggled.connect(self.temporalToggled)
        self.conditionalButton = QRadioButton('Conditional', self)
        self.conditionalButton.toggled.connect(self.conditionalToggled)

        radioButtonContainer = QGroupBox()
        radioButtonContainer.setTitle('Transition Type')
        vLayout = QVBoxLayout()
        vLayout.addWidget(self.temporalButton)
        vLayout.addWidget(self.conditionalButton)
        radioButtonContainer.setLayout(vLayout)

        self.transitionTypeCode = QTextEdit()
        self.transitionTypeCode.setFont(fixedWidthFont)
        self.transitionGroupBox = QGroupBox()
        self.transitionGroupBox.setTitle('Temporal (number in ms)')
        h3Layout = QHBoxLayout()
        h3Layout.addWidget(self.transitionTypeCode)
        self.transitionGroupBox.setLayout(h3Layout)

        typeContainer = QWidget()
        h2Layout = QHBoxLayout()
        h2Layout.addWidget(radioButtonContainer)
        h2Layout.addWidget(self.transitionGroupBox)
        typeContainer.setLayout(h2Layout)

        verticalLayout = QVBoxLayout()
        verticalLayout.addWidget(typeContainer)
        verticalLayout.addWidget(codeLanguageContainer)
        verticalLayout.addWidget(self.codeEdit)

        container = QWidget()
        hLayout =QHBoxLayout()
        hLayout.addWidget(self.cancelButton)
        hLayout.addWidget(self.acceptButton)
        container.setLayout(hLayout)

        verticalLayout.addWidget(container)
        self.setLayout(verticalLayout)

        if self.transition.getType() == TransitionType.CONDITIONAL:
            self.conditionalButton.setChecked(True)
            self.conditionalToggled()
        elif self.transition.getType() == TransitionType.TEMPORAL:
            self.temporalButton.setChecked(True)
            self.temporalToggled()

    def cancel(self):
        self.close()

    def accept(self):
        type = None
        typeValue = None

        if self.temporalButton.isChecked():
            type = int(TransitionType.TEMPORAL)
            typeValue = self.transitionTypeCode.toPlainText()
        elif self.conditionalButton.isChecked():
            type = int(TransitionType.CONDITIONAL)
            typeValue = self.transitionTypeCode.toPlainText()

        self.codeChanged.emit(type, typeValue, self.codeEdit.text())
        self.close()

    def temporalToggled(self):
        if (self.temporalButton.isChecked()):
            self.transitionGroupBox.setTitle('Temporal (number in ms)')
            self.transitionTypeCode.setPlainText(str(self.transition.getTemporalTime()))
            # print('temporal toggled')

    def conditionalToggled(self):
        if (self.conditionalButton.isChecked()):
            self.transitionGroupBox.setTitle('Condition (evaluates to true or false)')
            self.transitionTypeCode.setPlainText(self.transition.getCondition())
            # print('conditional toggled')

    def pythonClicked(self):
        fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        lexer = QsciLexerPython()
        lexer.setDefaultFont(fixedWidthFont)
        self.codeEdit.setLexer(lexer)
        self.language = 'python'

    def cppClicked(self):
        fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        lexer = QsciLexerCPP()
        lexer.setDefaultFont(fixedWidthFont)
        self.codeEdit.setLexer(lexer)
        self.language = 'cpp'
Example #23
0
class AimAssist(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):      
        # Buttons:
        BTN_H = 20
        BTN_W = 80
        BUTTON_COL = 0
        LABEL_COL1 = 1
        DATA_COL = 2
        RADIO_COL = 3
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        # Buttons:
        acq = QPushButton("&ACK", self)
        acq.clicked.connect(self.drawRect)
        grid.addWidget(acq, 0, BUTTON_COL)
        calc = QPushButton("&Calc", self)
        calc.clicked.connect(self.solve_tank)
        grid.addWidget(calc, 1, BUTTON_COL)
        
        # Radio buttons:
        settings = QLabel("Shot Type:")
        grid.addWidget(settings, 0, RADIO_COL)
        # settings.setAlignment(Qt.AlignBottom)
        self.radNorm = QRadioButton("&Normal")
        self.radNorm.setChecked(True)
        grid.addWidget(self.radNorm, 1, RADIO_COL)
        self.radHover = QRadioButton("&Hover (Post hang only)")
        grid.addWidget(self.radHover, 2, RADIO_COL)
        self.radDig = QRadioButton("&Digger")
        grid.addWidget(self.radDig, 3, RADIO_COL)
        
        # Text areas (with labels):
        # Width
        self.wbox = QSpinBox(self)
        grid.addWidget(self.wbox, 0, DATA_COL)
        self.wbox.setMaximum(1000)
        self.wbox.setMinimum(-1000)
        wlabel = QLabel("Width:")
        grid.addWidget(wlabel, 0, LABEL_COL1)
        wlabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        # Height
        self.hbox = QSpinBox(self)
        grid.addWidget(self.hbox, 1, DATA_COL)
        self.hbox.setMaximum(1000)
        self.hbox.setMinimum(-1000)
        hlabel = QLabel("Height:")
        grid.addWidget(hlabel, 1, LABEL_COL1)
        hlabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        # Wind
        self.windbox = QSpinBox(self)
        grid.addWidget(self.windbox, 2, DATA_COL)
        self.windbox.setMaximum(30)
        self.windbox.setMinimum(-30)
        windlabel = QLabel("Wind:")
        grid.addWidget(windlabel, 2, LABEL_COL1)
        windlabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        # Angle
        self.anglebox = QSpinBox(self)
        grid.addWidget(self.anglebox, 3, DATA_COL)
        self.anglebox.setMaximum(359)
        self.anglebox.setMinimum(0)
        self.anglebox.setValue(45)
        self.anglebox.setWrapping(True)
        angleLabel = QLabel("<i>θ</i>(0-259):")
        grid.addWidget(angleLabel, 3, LABEL_COL1)
        angleLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        
        # Power out:
        self.vbox = QLineEdit("Power")
        self.vbox.setStyleSheet("color: #ff0000")
        grid.addWidget(self.vbox, 2, BUTTON_COL)
        self.vbox.setAlignment(Qt.AlignRight)
        self.vbox.setReadOnly(True)
        
        self.move(50, 50)
        self.setWindowTitle('Aim Assistant')
        self.show()
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        
    def setWH(self, rectw, recth):
        self.wbox.setValue(int(rectw))
        self.hbox.setValue(int(recth))
        self.solve_tank()
        
    def drawRect(self):
        self.lower()
        pair = Popen(["./deathmeasure"], stdout=PIPE).communicate()[0].decode('utf-8').split()
        self.setWH(pair[0], pair[1])
        # self.show()
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape or e.key() == Qt.Key_Q:
            self.close()
        # elif e.key() == Qt.Key_A:
        #     self.drawRect()
        
    def solve_tank(self):
        # Earth:
        gc = 9.529745042492918
        wf = 0.08173443651742651    # wind
        hc = 3.660218073939021      # hover
        
        v_0 = None
        
        dx = self.wbox.value()
        dy = self.hbox.value()
        theta = self.anglebox.value()
        if self.radDig.isChecked():
            theta = -theta+360
            dy = -dy
        theta = rad(theta)
        w = self.windbox.value()
        hang = int(self.radHover.isChecked())
            
        flags = ""
        
        # Solve these equations:
        # x=v_0*cos(theta)*t
        # Other x terms:
        #   Hover:     hc*v_0*cos(theta)
        #   Wind:      wf*w*(t**2)  <-- forgot if it was t^2 or just t
        # y=v_0*sin(theta)*t-1/2*gc*(t**2)
        if v_0 is None:
            diff = 50
            vat = -1
            for n in range(1,111):
                t = quadform(gc/2, -n*sin(theta), dy)[0]
                # if t<0:
                #     continue
                x = n*cos(theta)*t + .5*wf*w*t**2 + hang*hc*n*cos(theta)
                # print(fabs(x-dx))
                if fabs(x-dx) < fabs(diff):
                    print(str(n)+":\t", round(x), round(dx), round(fabs(dx-x)))
                    diff = dx-x
                    vat = n
            catstr = ""
            if(vat > 100):
                catstr = "!"
            self.vbox.setText(str(round(vat,0))+catstr+","+str(round(diff,1))+"px")
            if vat<0:
                call(["notify-send", "Error:", "Bad Value"])
            else:
                call(["notify-send", "Power:", str(round(vat,0))+catstr])
                
        else:
            print("Error. Broken.")
            self.vbox.setText(str(-1.0))
Example #24
0
class ViewOptions(QWidget):
    """Contains all of the user configurable options related to the music player window."""

    def __init__(self, parent=None):
        """Initiate the View Options page in the preferences dialog."""
        super(ViewOptions, self).__init__(parent)

        self.user_config_file = os.path.join(AppDirs('mosaic', 'Mandeep').user_config_dir,
                                             'settings.toml')

        with open(self.user_config_file) as conffile:
            config = toml.load(conffile)

        dock_config = QGroupBox('Dock Configuration')

        self.media_library_view_button = QCheckBox('Show Media Library on Start', self)
        self.playlist_view_button = QCheckBox('Show Playlist on Start', self)

        dock_start_layout = QVBoxLayout()
        dock_start_layout.addWidget(self.media_library_view_button)
        dock_start_layout.addWidget(self.playlist_view_button)

        self.dock_position = QLabel('Dock Position:')
        self.dock_left_side = QRadioButton('Left Side')
        self.dock_right_side = QRadioButton('Right Side')

        dock_position_layout = QHBoxLayout()
        dock_position_layout.addWidget(self.dock_position)
        dock_position_layout.addWidget(self.dock_left_side)
        dock_position_layout.addWidget(self.dock_right_side)

        main_dock_layout = QVBoxLayout()
        main_dock_layout.addLayout(dock_start_layout)
        main_dock_layout.addLayout(dock_position_layout)
        dock_config.setLayout(main_dock_layout)

        window_config = QGroupBox("Window Configuration")

        size_option = QLabel('Window Size', self)

        self.dropdown_box = QComboBox()
        self.dropdown_box.addItem('900 x 900')
        self.dropdown_box.addItem('800 x 800')
        self.dropdown_box.addItem('700 x 700')
        self.dropdown_box.addItem('600 x 600')
        self.dropdown_box.addItem('500 x 500')
        self.dropdown_box.addItem('400 x 400')

        window_size_layout = QHBoxLayout()
        window_size_layout.addWidget(size_option)
        window_size_layout.addWidget(self.dropdown_box)

        window_config.setLayout(window_size_layout)

        main_layout = QVBoxLayout()
        main_layout.addWidget(dock_config)
        main_layout.addWidget(window_config)
        main_layout.addStretch(1)
        self.setLayout(main_layout)

        self.check_window_size(config)
        self.check_media_library(config)
        self.check_playlist_dock(config)
        self.check_dock_position(config)

        self.dropdown_box.currentIndexChanged.connect(lambda: self.change_size(config))
        self.media_library_view_button.clicked.connect(lambda: self.media_library_view_settings(config))
        self.playlist_view_button.clicked.connect(lambda: self.playlist_view_settings(config))
        self.dock_left_side.clicked.connect(lambda: self.dock_positon_settings(config))
        self.dock_right_side.clicked.connect(lambda: self.dock_positon_settings(config))

    def change_size(self, config):
        """Record the change in window size to the settings.toml file."""
        if self.dropdown_box.currentIndex() != -1:
            config.setdefault('view_options', {})['window_size'] = self.dropdown_box.currentIndex()

        with open(self.user_config_file, 'w') as conffile:
            toml.dump(config, conffile)

    def check_window_size(self, config):
        """Set the dropdown box to the current window size provided by settings.toml."""
        self.dropdown_box.setCurrentIndex(config['view_options']['window_size'])

    def media_library_view_settings(self, config):
        """Change the behavior of the Media Library dock widget.

        The default setting hides the dock on application start. With this option
        checked, the media library dock will show on start.
        """
        if self.media_library_view_button.isChecked():
            config.setdefault('media_library', {})['show_on_start'] = True

        elif not self.media_library_view_button.isChecked():
            config.setdefault('media_library', {})['show_on_start'] = False

        with open(self.user_config_file, 'w') as conffile:
            toml.dump(config, conffile)

    def check_media_library(self, config):
        """Set the media library checkbox state from settings.toml."""
        self.media_library_view_button.setChecked(config['media_library']['show_on_start'])

    def playlist_view_settings(self, config):
        """Change the behavior of the Playlist dock widget.

        The default setting hides the dock on application start. With this option
        checked, the playlist dock will show on start.
        """
        if self.playlist_view_button.isChecked():
            config.setdefault('playlist', {})['show_on_start'] = True

        elif not self.playlist_view_button.isChecked():
            config.setdefault('playlist', {})['show_on_start'] = False

        with open(self.user_config_file, 'w') as conffile:
            toml.dump(config, conffile)

    def check_playlist_dock(self, config):
        """Set the playlist dock checkbox state from settings.toml."""
        self.playlist_view_button.setChecked(config['playlist']['show_on_start'])

    def dock_positon_settings(self, config):
        """Write to the settings.toml the radio button chosen by the user."""
        if self.dock_left_side.isChecked():
            config.setdefault('dock', {})['position'] = 'left'

        elif self.dock_right_side.isChecked():
            config.setdefault('dock', {})['position'] = 'right'

        with open(self.user_config_file, 'w') as conffile:
            toml.dump(config, conffile)

    def check_dock_position(self, config):
        """Select the radio button previously chosen by the user in the preferences dialog."""
        if config['dock']['position'] == 'left':
            self.dock_left_side.setChecked(True)
        elif config['dock']['position'] == 'right':
            self.dock_right_side.setChecked(True)
Example #25
0
class UnitConverter(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()

    def initUI(self):
    
        self.tab = QTabWidget(self)
        
        # Length Tab
        self.length = QWidget()
        
        self.lengthLabel = QLabel("Length Converter")
        self.lengthFrom = QLineEdit()
        self.lengthTo = QLineEdit()
        self.kilometersFrom = QRadioButton('Km',self)
        self.kilometersTo = QRadioButton('Km',self)
        self.metersFrom = QRadioButton('m', self)
        self.metersTo = QRadioButton('m', self)
        self.feetFrom = QRadioButton('ft', self)
        self.feetTo = QRadioButton('ft',self)
        self.inchesFrom = QRadioButton('in', self)
        self.inchesTo = QRadioButton('in', self)
        
        self.lengthButton = QPushButton("Convert")
        self.lengthButton.clicked.connect(self.convertLength)
        
        self.groupLength = QButtonGroup()
        self.groupLength.addButton(self.kilometersFrom)
        self.groupLength.addButton(self.kilometersTo)
        self.groupLength.addButton(self.metersFrom)
        self.groupLength.addButton(self.metersTo)
        self.groupLength.addButton(self.feetFrom)
        self.groupLength.addButton(self.feetTo)
        self.groupLength.addButton(self.inchesFrom)
        self.groupLength.addButton(self.inchesTo)
        self.groupLength.setExclusive(False)
        
        self.gridLength = QGridLayout()
        
        self.gridLength.addWidget(self.lengthLabel,0,1)
        self.gridLength.addWidget(self.lengthFrom,1,1)
        self.gridLength.addWidget(self.lengthTo,1,2)
        self.gridLength.addWidget(self.kilometersFrom,2,1)
        self.gridLength.addWidget(self.kilometersTo,2,2)
        self.gridLength.addWidget(self.metersFrom,3,1)
        self.gridLength.addWidget(self.metersTo,3,2)
        self.gridLength.addWidget(self.feetFrom,4,1)
        self.gridLength.addWidget(self.feetTo,4,2)
        self.gridLength.addWidget(self.inchesFrom,5,1)
        self.gridLength.addWidget(self.inchesTo,5,2)
        self.gridLength.addWidget(self.lengthButton,6,2)
        
        self.length.setLayout(self.gridLength)
        
        # Volume Tab
        self.volume = QWidget()
        
        self.volumeLabel = QLabel("Volume Converter")
        self.volumeFrom = QLineEdit()
        self.volumeTo = QLineEdit()
        self.litresFrom = QRadioButton('L',self)
        self.litresTo = QRadioButton('L', self)
        self.millilitresFrom = QRadioButton('mL', self)
        self.millilitresTo = QRadioButton('mL', self)
        self.fluidOuncesFrom = QRadioButton('fl oz', self)
        self.fluidOuncesTo = QRadioButton('fl oz', self) 
        
        self.volumeButton = QPushButton("Convert")
        self.volumeButton.clicked.connect(self.convertVolume)        
        
        self.groupVolume = QButtonGroup()
        self.groupVolume.addButton(self.litresFrom)
        self.groupVolume.addButton(self.litresTo)
        self.groupVolume.addButton(self.millilitresFrom)
        self.groupVolume.addButton(self.millilitresTo)
        self.groupVolume.addButton(self.fluidOuncesFrom)
        self.groupVolume.addButton(self.fluidOuncesTo)
        self.groupVolume.setExclusive(False)
        
        self.gridVolume = QGridLayout()
        
        self.gridVolume.addWidget(self.volumeLabel,0,1)
        self.gridVolume.addWidget(self.volumeFrom,1,1)
        self.gridVolume.addWidget(self.volumeTo,1,2)
        self.gridVolume.addWidget(self.litresFrom,2,1)
        self.gridVolume.addWidget(self.litresTo,2,2)
        self.gridVolume.addWidget(self.millilitresFrom,3,1)
        self.gridVolume.addWidget(self.millilitresTo,3,2)
        self.gridVolume.addWidget(self.fluidOuncesFrom,4,1)
        self.gridVolume.addWidget(self.fluidOuncesTo,4,2)
        self.gridVolume.addWidget(self.volumeButton,5,2)
        
        self.volume.setLayout(self.gridVolume)
        
        # Weight Tab
        self.weight = QWidget()
        
        self.weightLabel = QLabel("Weight Converter")
        self.weightFrom = QLineEdit()
        self.weightTo = QLineEdit()
        self.poundsFrom = QRadioButton('lbs',self)
        self.poundsTo = QRadioButton('lbs', self)
        self.kilogramFrom = QRadioButton('kg', self)
        self.kilogramTo = QRadioButton('kg', self)
        
        self.weightButton = QPushButton("Convert")
        self.weightButton.clicked.connect(self.convertWeight)
        
        self.groupWeight = QButtonGroup()
        self.groupWeight.addButton(self.poundsFrom)
        self.groupWeight.addButton(self.poundsTo)
        self.groupWeight.addButton(self.kilogramFrom)
        self.groupWeight.addButton(self.kilogramTo)
        self.groupWeight.setExclusive(False)
        
        self.gridWeight = QGridLayout()
        
        self.gridWeight.addWidget(self.weightLabel,0,1)
        self.gridWeight.addWidget(self.weightFrom,1,1)
        self.gridWeight.addWidget(self.weightTo,1,2)
        self.gridWeight.addWidget(self.poundsFrom,2,1)
        self.gridWeight.addWidget(self.poundsTo,2,2)
        self.gridWeight.addWidget(self.kilogramFrom,3,1)
        self.gridWeight.addWidget(self.kilogramTo,3,2)
        self.gridWeight.addWidget(self.weightButton,4,2)
        
        self.weight.setLayout(self.gridWeight)
        
        self.tab.addTab(self.length,"Length")
        self.tab.addTab(self.volume,"Volume")
        self.tab.addTab(self.weight, "Weight")
        
    
        self.setGeometry(300,300,300,200)
        self.setWindowTitle('Unit Converter')
        self.show()
    
    def convertLength(self):
        self.quantity = int(self.lengthFrom.text())
        
        if self.kilometersFrom.isChecked():
            km = Kilometer("Kilometer","km",self.quantity,"Length")
            if self.kilometersTo.isChecked():
                message = QMessageBox.warning(self,"Warning", "Can't convert km to km")
            elif self.metersTo.isChecked():
                converted = km.convert_to("meter",km.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.feetTo.isChecked():
                converted = km.convert_to("feet",km.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.inchesTo.isChecked():
                converted = km.convert_to("inches",km.magnitude)
                self.lengthTo.setText(str(converted))
        
        if self.metersFrom.isChecked():
            m = Meter("Meter", "m", self.quantity,"Length")
            if self.metersTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert m to m")
            elif self.kilometersTo.isChecked():
                converted = m.convert_to("kilometer",m.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.feetTo.isChecked():
                converted = m.convert_to("feet",m.magnitude) 
                self.lengthTo.setText(str(converted))
            elif self.inchesTo.isChecked():
                converted = m.convert_to("inches",m.magnitude)
                self.lengthTo.setText(str(converted))

        if self.feetFrom.isChecked():
            ft = Feet("Feet", "ft", self.quantity, "Length")
            if self.feetTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert ft to ft")
            elif self.kilometersTo.isChecked():
                converted = ft.convert_to("kilometer",ft.magnitude)  
                self.lengthTo.setText(str(converted))
            elif self.metersTo.isChecked():
                converted = ft.convert_to("meter",ft.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.inchesTo.isChecked():
                converted = ft.convert_to("inches",ft.magnitude)  
                self.lengthTo.setText(str(converted))  

        if self.inchesFrom.isChecked():
            inch = Inch("Inches", "in", self.quantity, "Length")
            if self.inchesTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert in to in")
            elif self.kilometersTo.isChecked():
                converted = inches.convert_to("kilometer",inches.magnitude) 
                self.lengthTo.setText(str(converted))
            elif self.metersTo.isChecked():
                converted = inches.convert_to("meters",inches.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.feetTo.isChecked():
                converted = inches.convert_to("feet",inches.magnitude) 
                self.lengthTo.setText(str(converted))
    
    def convertVolume(self):
        self.quantity = int(self.volumeFrom.text())
        
        if self.litresFrom.isChecked():
            L = Litre("Litre", "L", self.quantity, "Volume")
            if self.litresTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert L to L")
            elif self.millilitresTo.isChecked():
                converted = L.convert_to("millilitres",L.magnitude)
                self.volumeTo.setText(str(converted))
            elif self.fluidOuncesTo.isChecked():
                converted = km.convert_to("fluid ounce",L.magnitude)
                self.volumeTo.setText(str(converted))
                
        if self.millilitresFrom.isChecked():
            mL = Millilitre("Millilitre", "mL", self.quantity, "Volume")
            if self.millilitresTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert mL to mL")
            elif self.litresTo.isChecked():
                converted = mL.convert_to("litre",mL.magnitude)
                self.volumeTo.setText(str(converted))
            elif self.fluidOuncesTo.isChecked():
                converted = mL.convert_to("fluid ounce",mL.magnitude)
                self.volumeTo.setText(str(converted))
                
        if self.fluidOuncesFrom.isChecked():
            flOz = FluidOunce("Fluid Ounce", "fl oz", self.quantity, "Volume")
            if self.fluidOuncesTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert fl oz to fl oz")
            elif self.litresTo.isChecked():
                converted = flOz.convert_to("litre",flOz.magnitude)
                self.volumeTo.setText(str(converted))
            elif self.millilitresTo.isChecked():
                converted = flOz.convert_to("millilitre",flOz.magnitude)
                self.volumeTo.setText(str(converted))
                
    def convertWeight(self):
        self.quantity = int(self.weightFrom.text())

        if self.kilogramFrom.isChecked():
            kg = Kilogram("Kilogram", "kg", self.quantity,"Weight")
            if self.kilogramTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert kg to kg")
            elif self.poundsTo.isChecked():
                converted = kg.convert_to("pound",kg.magnitude)
                self.weightTo.setText(str(converted))

        if self.poundsFrom.isChecked():
            lbs = Pound("Pound", "lbs", self.quantity, "Weight")
            if self.poundsTo.isChecked():
                message = QMessageBox.warning(self,"Warning", "Can't convert lbs to lbs")
            elif self.kilogramTo.isChecked():
                converted = lbs.convert_to("kilogram",lbs.magnitude)
                self.weightTo.setText(str(converted))                
class ShortcutEditDialog(QDialog):
    """A modal dialog to view and/or edit keyboard shortcuts."""
    
    def __init__(self, parent=None, conflictCallback=None, *cbArgs):
        """conflictCallback is a optional method called when a shortcut is changed.
        
        cbArgs is optional arguments of the conflictCallback method.
        it should return the name of the potential conflict or a null value """
        
        super(ShortcutEditDialog, self).__init__(parent)
        self.conflictCallback = conflictCallback
        self.cbArgs = cbArgs
        self.setMinimumWidth(400)
        # create gui
        
        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)
        
        top = QHBoxLayout()
        top.setSpacing(4)
        p = self.toppixmap = QLabel()
        l = self.toplabel = QLabel()
        top.addWidget(p)
        top.addWidget(l, 1)
        layout.addLayout(top)
        grid = QGridLayout()
        grid.setSpacing(4)
        grid.setColumnStretch(1, 2)
        layout.addLayout(grid)
        
        self.buttonDefault = QRadioButton(self, toggled=self.slotButtonDefaultToggled)
        self.buttonNone = QRadioButton(self)
        self.lconflictDefault = QLabel('test')
        self.lconflictDefault.setStyleSheet("color : red;")
        self.lconflictDefault.setVisible(False)
        self.buttonCustom = QRadioButton(self)
        grid.addWidget(self.buttonDefault, 0, 0, 1, 2)
        grid.addWidget(self.lconflictDefault, 1, 0, 1, 2)
        grid.addWidget(self.buttonNone, 2, 0, 1, 2)
        grid.addWidget(self.buttonCustom, 3, 0, 1, 2)
        
        self.keybuttons = []
        self.keylabels = []
        self.conflictlabels = []
        for num in range(4):
            l = QLabel(self)
            l.setStyleSheet("margin-left: 2em;")
            l.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            b = KeySequenceWidget(self, num)
            b.keySequenceChanged.connect(self.slotKeySequenceChanged)
            l.setBuddy(b)
            self.keylabels.append(l)
            self.keybuttons.append(b)
            grid.addWidget(l, num+4+num, 0)
            grid.addWidget(b, num+4+num, 1)
            lconflict = QLabel()
            lconflict.setStyleSheet("color : red;")
            self.conflictlabels.append(lconflict)
            lconflict.setVisible(False)
            grid.addWidget(lconflict, num+5+num, 0, 1, 2, Qt.AlignHCenter)
        
        layout.addWidget(Separator(self))
        
        b = QDialogButtonBox(self)
        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout.addWidget(b)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        app.translateUI(self)
    
    def translateUI(self):
        self.setWindowTitle(app.caption(_("window title", "Edit Shortcut")))
        self.buttonNone.setText(_("&No shortcut"))
        self.buttonCustom.setText(_("Use a &custom shortcut:"))
        for num in range(4):
            self.keylabels[num].setText(_("Alternative #{num}:").format(num=num) if num else _("Primary shortcut:"))
    
    def slotKeySequenceChanged(self, num):
        """Called when one of the keysequence buttons has changed."""
        self.checkConflict(num)
        self.buttonCustom.setChecked(True)
    
    def slotButtonDefaultToggled(self, val):
        if self.conflictCallback is not None:
            if not val:
                self.lconflictDefault.setVisible(False)
            else:
                if self._default:
                    conflictList = []
                    for s in self._default:
                        conflictName = self.conflictCallback(s, *self.cbArgs)
                        if conflictName:
                            conflictList.append(conflictName)
                    if conflictList:
                        text = _("Conflict with: {name}").format(
                            name="<b>{0}</b>".format(', '.join(conflictList)))
                        self.lconflictDefault.setText(text)
                        self.lconflictDefault.setVisible(True)
            QTimer.singleShot(0, self.adjustSize)
                    
    def checkConflict(self, num):
        if self.conflictCallback is not None:
            conflictName = self.conflictCallback(self.keybuttons[num].shortcut(), *self.cbArgs)
            if conflictName:
                text = _("Conflict with: {name}").format(
                    name="<b>{0}</b>".format(conflictName))
                self.conflictlabels[num].setText(text)
                self.conflictlabels[num].setVisible(True)
            else:
                self.conflictlabels[num].setVisible(False)
            QTimer.singleShot(0, self.adjustSize)
     
    def editAction(self, action, default=None):
        # load the action
        self._action = action
        self._default = default
        self.toplabel.setText('<p>{0}</p>'.format(
            _("Here you can edit the shortcuts for {name}").format(
                name='<br/><b>{0}</b>:'.format(action.text()))))
        self.toppixmap.setPixmap(action.icon().pixmap(32))
        shortcuts = action.shortcuts()
        self.buttonDefault.setVisible(bool(default))
        if default is not None and shortcuts == default:
            self.buttonDefault.setChecked(True)
        else:
            if shortcuts:
                self.buttonCustom.setChecked(True)
                for num, key in enumerate(shortcuts[:4]):
                    self.keybuttons[num].setShortcut(key)
                    self.checkConflict(num)
            else:
                self.buttonNone.setChecked(True)
            
        if default:
            ds = "; ".join(key.toString(QKeySequence.NativeText) for key in default)
        else:
            ds = _("no keyboard shortcut", "none")
        self.buttonDefault.setText(_("Use &default shortcut ({name})").format(name=ds))
        return self.exec_()
        
    def done(self, result):
        if result:
            shortcuts = []
            if self.buttonDefault.isChecked():
                shortcuts = self._default
            elif self.buttonCustom.isChecked():
                for num in range(4):
                    seq = self.keybuttons[num].shortcut()
                    if not seq.isEmpty():
                        shortcuts.append(seq)
            self._action.setShortcuts(shortcuts)
        super(ShortcutEditDialog, self).done(result)
Example #27
0
class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyProject'
        self.left = 550
        self.top = 350
        self.width = 625
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        fileButton = QPushButton('Select a DataSet', self)
        fileButton.move(60, 30)
        fileButton.clicked.connect(self.getfile)
        self.applyButton = QPushButton('Apply Tests', self)
        self.applyButton.move(215, 30)
        self.applyButton.clicked.connect(self.newWindow)
        self.applyButton.setEnabled(False)

        self.displayText = QLabel("", self)
        self.displayText.move(375, 0)
        self.displayText.setFixedHeight(150)
        self.displayText.setFixedWidth(250)
        self.displayText.setAlignment(Qt.AlignTop)
        self.displayText.setAlignment(Qt.AlignLeft)
        self.displayText.setWordWrap(True)
        self.displayText.setAutoFillBackground(True)
        self.displayText.setStyleSheet(
            "QLabel { background-color: rgba(169,169,169); }")

        self.displayResult = QLabel("", self)
        self.displayResult.move(375, 155)
        self.displayResult.setFixedHeight(200)
        self.displayResult.setFixedWidth(250)
        self.displayResult.setAlignment(Qt.AlignTop)
        self.displayResult.setAlignment(Qt.AlignLeft)
        self.displayResult.setWordWrap(True)
        self.displayResult.setAutoFillBackground(True)
        self.displayResult.setStyleSheet(
            "QLabel { background-color: rgba(169,169,169); }")

        paraNonPara = QButtonGroup(self)
        anovaPara = QButtonGroup(self)
        pairUnPair = QButtonGroup(self)
        studentAnova = QButtonGroup(self)

        self.anova = QRadioButton('Anova', self)
        self.anova.move(250, 90)
        self.anova.setChecked(False)
        self.student = QRadioButton('Student-T', self)
        self.student.move(60, 90)
        self.student.setChecked(False)
        studentAnova.addButton(self.anova)
        studentAnova.addButton(self.student)

        self.stuPara = QRadioButton('Parametric', self)
        self.stuPara.move(10, 120)
        self.stuPara.setChecked(False)
        self.stuNonpara = QRadioButton('non-Parametric', self)
        self.stuNonpara.move(10, 150)
        self.stuNonpara.setChecked(False)
        paraNonPara.addButton(self.stuPara)
        paraNonPara.addButton(self.stuNonpara)

        self.anoPara = QRadioButton('Parametric', self)
        self.anoPara.move(250, 120)
        self.anoPara.setChecked(False)
        self.anoNonpara = QRadioButton('non-Parametric', self)
        self.anoNonpara.move(250, 150)
        self.anoNonpara.setChecked(False)
        anovaPara.addButton(self.anoPara)
        anovaPara.addButton(self.anoNonpara)

        self.pair = QRadioButton('Paired', self)
        self.pair.move(130, 120)
        self.pair.setChecked(False)
        self.unPair = QRadioButton('Unpaired', self)
        self.unPair.move(130, 150)
        self.unPair.setChecked(False)
        pairUnPair.addButton(self.pair)
        pairUnPair.addButton(self.unPair)

        self.pair.setEnabled(False)
        self.unPair.setEnabled(False)
        self.anoPara.setEnabled(False)
        self.anoNonpara.setEnabled(False)
        self.stuPara.setEnabled(False)
        self.stuNonpara.setEnabled(False)
        self.anova.setEnabled(False)
        self.student.setEnabled(False)

    def newWindow(self):
        if (self.student.isChecked()):
            #para=student t, non-para-paird=signrank, non-para-unpaird=ranksum
            if (self.stuPara.isChecked()):
                if (self.pair.isChecked()):
                    self.displayResult.setText(
                        stats.ttest_rel(df.iloc[:, 0], df.iloc[:,
                                                               1]).__str__())
                else:
                    self.displayResult.setText(
                        stats.ttest_ind(df.iloc[:, 0],
                                        df.iloc[:, 1],
                                        equal_var=False).__str__())
            else:
                if (self.pair.isChecked()):
                    self.displayResult.setText(
                        stats.wilcoxon(df.iloc[:, 0],
                                       df.iloc[:, 1],
                                       zero_method='wilcox',
                                       correction=False).__str__())
                else:
                    self.displayResult.setText(
                        stats.ranksums(df.iloc[:, 0], df.iloc[:, 1]).__str__())
        if (self.anova.isChecked()):
            #para=anova, non-para=kruskalwallis
            #pca reduce to 3 or 2
            if (self.anoPara.isChecked()):
                self.displayResult.setText(
                    stats.f_oneway(df.iloc[:, 0], df.iloc[:, 1],
                                   df.iloc[:, 2]).__str__())
            else:
                self.displayResult.setText(
                    stats.kruskal(df.iloc[:, 0], df.iloc[:, 1],
                                  df.iloc[:, 2]).__str__())

    def getfile(self):
        #get the file name and if it is not empty do stuff
        filename = askopenfilename()
        if (filename != ''):
            #check that it is an xlsx file
            if (filename.endswith('.xlsx')):
                xls_file = pd.ExcelFile(filename)
                sheetName = xls_file.sheet_names
                tempParse = xls_file.parse(sheetName[0])
                tempParse = tempParse.dropna(axis=1, how='all')
                #if the data set is empty
                if (len(tempParse.columns) == 0):
                    self.displayText.setText("DataSet is Empty!")
                    self.displayResult.setText("")
                    self.applyButton.setEnabled(False)
                    self.pair.setEnabled(False)
                    self.unPair.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuNonpara.setEnabled(False)
                    self.anova.setEnabled(False)
                    self.student.setEnabled(False)
                    return
                if (len(tempParse.columns) > 3):
                    self.displayText.setText("DataSet is too Large!")
                    self.displayResult.setText("")
                    self.applyButton.setEnabled(False)
                    self.pair.setEnabled(False)
                    self.unPair.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuNonpara.setEnabled(False)
                    self.anova.setEnabled(False)
                    self.student.setEnabled(False)
                    return
                tempParse = list(tempParse)
                global df
                #use tempParse to check if file had headers
                if (isinstance(tempParse[0], float)
                        or isinstance(tempParse[0], int)):
                    df = xls_file.parse(sheetName[0], header=None)
                else:
                    df = xls_file.parse(sheetName[0])
                #cut the NaN columns out
                df = df.dropna(axis=1, how='all')
                #cut any NaN values out
                df = df.dropna()
                #activate the buttons and radio buttons depending on your data set
                self.displayText.setText(
                    df.describe(include='all').to_string())
                self.displayResult.setText("")
                if (len(df.columns) == 1):
                    self.applyButton.setEnabled(False)
                    self.student.setEnabled(False)
                    self.student.setChecked(False)
                    self.pair.setEnabled(False)
                    self.pair.setChecked(False)
                    self.unPair.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuPara.setChecked(False)
                    self.stuNonpara.setEnabled(False)
                    self.anova.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                elif (len(df.columns) == 2):
                    self.applyButton.setEnabled(True)
                    self.student.setEnabled(True)
                    self.student.setChecked(True)
                    self.pair.setEnabled(True)
                    self.pair.setChecked(True)
                    self.unPair.setEnabled(True)
                    self.stuPara.setEnabled(True)
                    self.stuPara.setChecked(True)
                    self.stuNonpara.setEnabled(True)
                    self.anova.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                else:
                    self.applyButton.setEnabled(True)
                    self.anova.setEnabled(True)
                    self.anova.setChecked(True)
                    self.anoPara.setEnabled(True)
                    self.anoPara.setChecked(True)
                    self.anoNonpara.setEnabled(True)
                    self.student.setEnabled(False)
                    self.pair.setEnabled(False)
                    self.unPair.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuNonpara.setEnabled(False)
            else:
                #need warning for wrong file type
                self.displayText.setText("Wrong file type")
                self.displayResult.setText("")
                self.applyButton.setEnabled(False)
                self.pair.setEnabled(False)
                self.unPair.setEnabled(False)
                self.anoPara.setEnabled(False)
                self.anoNonpara.setEnabled(False)
                self.stuPara.setEnabled(False)
                self.stuNonpara.setEnabled(False)
                self.anova.setEnabled(False)
                self.student.setEnabled(False)
        else:
            #need warning for no file chosen
            self.displayText.setText("No file selected")
            self.displayResult.setText("")
            self.applyButton.setEnabled(False)
            self.pair.setEnabled(False)
            self.unPair.setEnabled(False)
            self.anoPara.setEnabled(False)
            self.anoNonpara.setEnabled(False)
            self.stuPara.setEnabled(False)
            self.stuNonpara.setEnabled(False)
            self.anova.setEnabled(False)
            self.student.setEnabled(False)
Example #28
0
class NewDocument(preferences.Group):
    def __init__(self, page):
        super(NewDocument, self).__init__(page)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.template.isChecked())
        
        self.emptyDocument = QRadioButton(toggled=changed)
        self.lilyVersion = QRadioButton(toggled=changed)
        self.template = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)
        
        grid.addWidget(self.emptyDocument, 0, 0, 1, 2)
        grid.addWidget(self.lilyVersion, 1, 0, 1, 2)
        grid.addWidget(self.template, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)
        self.loadCombo()
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("When creating new documents"))
        self.emptyDocument.setText(_("Create an empty document"))
        self.lilyVersion.setText(_("Create a document that contains the LilyPond version statement"))
        self.template.setText(_("Create a document from a template:"))
        from snippet import snippets
        for i, name in enumerate(self._names):
            self.combo.setItemText(i, snippets.title(name))
    
    def loadCombo(self):
        from snippet import snippets
        self._names = [name for name in snippets.names()
                        if snippets.get(name).variables.get('template')]
        self.combo.clear()
        self.combo.addItems([''] * len(self._names))
        
    def loadSettings(self):
        s = QSettings()
        ndoc = s.value("new_document", "empty", str)
        template = s.value("new_document_template", "", str)
        if template in self._names:
            self.combo.setCurrentIndex(self._names.index(template))
        if ndoc == "template":
            self.template.setChecked(True)
        elif ndoc == "version":
            self.lilyVersion.setChecked(True)
        else:
            self.emptyDocument.setChecked(True)

    def saveSettings(self):
        s = QSettings()
        if self._names and self.template.isChecked():
            s.setValue("new_document", "template")
            s.setValue("new_document_template", self._names[self.combo.currentIndex()])
        elif self.lilyVersion.isChecked():
            s.setValue("new_document", "version")
        else:
            s.setValue("new_document", "empty")
Example #29
0
class ui_cbf(QMainWindow):
    def __init__(self, parent, lan=0):
        super(ui_cbf, self).__init__(parent)
        # print(parent.fname)
        self.temp = parent
        self.setGeometry(303, 304, 500, 350)  # 设置子窗口的尺寸
        self.setMinimumSize(200, 130)  # 设置子窗口的最小尺寸
        self.lan = lan
        self.path_single = self.temp.fname
        self.path_dwi = ""
        self.path_ref = ""
        self.path_pre = ""
        self.path_lat = ""
        self.display_type = 0
        # 设置计算cbf图像的输入情况,0:输入单幅图像,其中不同volume对应dwi和ref像(GE),1:输入DWI像和REF像,2:输入两次采样的ASL像和REF像self.display_type = 0 # 用于确认输入nii的模式,与calculation的ui_cbf.display_type一致

        self.display_asl = 0  # 用于确认ASL的不同形式,0代表PCASL,1代表QUIPSS II PASL,两者计算CBF使用的参数有区别
        self.lamda = 0.9
        """ brain/blood partition coefficient,单位为ml/g,使用What Is the Correct Value for the Brain-Blood Partition Coefficient
for Water?中的结论"""
        self.PLD = 2000 / 1000
        """ post labeling delay,单位为秒,使用Recommended Implementation of Arterial Spin Labeled Perfusion MRI for Clinical
Applications: A consensus of the ISMRM Perfusion Study Group and the European Consortium for ASL in Dementia给出的参考值
        ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
        ┃ PCASL Labeling Duration              ┃     1800ms    ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PCASL PLD - Neonates                 ┃     2000ms    ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PCASL PLD - Children                 ┃     1500ms    ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PCASL PLD - Healthy subjects < 70 yrs┃     1800ms    ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PCASL PLD - Healthy subjects > 70 yrs┃     2000 ms   ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PCASL PLD - Adult clinical patients  ┃     2000 ms   ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PASL TI1                             ┃      800 ms   ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ PASL TI                              ┃ Use PCASL PLD ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ λ (blood-brain partition coefficient)┃     0.9 ml/g  ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ T1, blood at 3.0 Tesla               ┃     1650 ms   ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ T1, blood at 1.5 Tesla               ┃     1350 ms   ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ α (labeling efficiency) for PCASL    ┃     0.85      ┃
        ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━┫
        ┃ α (labeling efficiency) for PASL     ┃     0.98      ┃
        ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━┛
        """
        self.T1_blood = 1650 / 1000  # 3T为1650ms, 1.5T为1350ms
        # longitudinal relaxation time of blood,单位为秒
        self.alpha = 0.85  # PCASL为0.85, PASL为0.98
        # labeling efficiency
        self.tau = 1800 / 1000
        # label duration,单位为秒
        self.TI = 2000 / 1000
        # inversion time,单位是秒
        self.TI_1 = 800 / 1000
        # bolus duration,单位为秒
        self.ratio = 1
        # 通过参数计算出的系数,默认是1(但通常不是)

        self.initUI()

    def initUI(self):
        if self.lan == 0:
            self.setWindowTitle("CBF Calculation")
            self.button_settings = QPushButton("Details...", self)
            self.button_operate = QPushButton("Operate", self)
        elif self.lan == 1:
            self.setWindowTitle("CBF计算")
            self.button_settings = QPushButton("参数设置...", self)
            self.button_operate = QPushButton("开始计算", self)
        self.button_settings.setSizePolicy(150, 50)

        self.button_operate.setSizePolicy(150, 50)
        self.button_operate.clicked.connect(self.calcCBF)
        self.button_settings.clicked.connect(self.createSetting)

        if self.lan == 0:
            self.label_radio = QLabel("Input Mode", self)
            self.button_type_single = QRadioButton("Single", self)
            self.button_type_dwi = QRadioButton("PWI and Ref", self)
            self.button_type_asl = QRadioButton("ASLs and Ref", self)
            self.label_name_dir_single = QLabel("The whole Image:", self)
            self.label_name_dir_dwi = QLabel("PWI Image:", self)
            self.label_name_dir_preasl = QLabel("Control ASL:", self)
            self.label_name_dir_lateasl = QLabel("Label ASL:", self)
            self.label_name_dir_ref = QLabel("Reference Image:", self)
            self.cb_autothr = QCheckBox("Auto Threshold", self)
            self.cb_autosave = QCheckBox("Auto Save", self)
        elif self.lan == 1:
            self.label_radio = QLabel("输入模式", self)
            self.button_type_single = QRadioButton("单张nii", self)
            self.button_type_dwi = QRadioButton("灌注差及参考像", self)
            self.button_type_asl = QRadioButton("不同ASL及参考像", self)
            self.label_name_dir_single = QLabel("图像路径:", self)
            self.label_name_dir_dwi = QLabel("ASL差值路径:", self)
            self.label_name_dir_preasl = QLabel("ASL控制像路径:", self)
            self.label_name_dir_lateasl = QLabel("ASL标记像路径:", self)
            self.label_name_dir_ref = QLabel("参考像路径:", self)
            self.cb_autothr = QCheckBox("自动阈值处理", self)
            self.cb_autosave = QCheckBox("自动保存", self)

        self.button_type_single.clicked.connect(self.radiobutton_clicked)
        self.button_type_dwi.clicked.connect(self.radiobutton_clicked)
        self.button_type_asl.clicked.connect(self.radiobutton_clicked)
        self.cb_autothr.setChecked(True)
        self.cb_autosave.setChecked(True)

        # 使用单选框选择ASL图像的输入模式,对应不同的display_type

        self.grid_radiobutton = QGridLayout()
        self.grid_dir = QGridLayout()
        self.grid_operate = QGridLayout()
        self.grid_full = QGridLayout()
        self.grid_ui = QGridLayout()
        self.grid_cb = QGridLayout()

        self.label_val_dir_single = QLineEdit(self)
        self.label_val_dir_dwi = QLineEdit(self)
        self.label_val_dir_preasl = QLineEdit(self)
        self.label_val_dir_lateasl = QLineEdit(self)
        self.label_val_dir_ref = QLineEdit(self)

        if type(self.path_single) == str:
            self.label_val_dir_single.setText(self.path_single)
        else:
            self.path_single = ""
            self.label_val_dir_single.setText(self.path_single)

        self.button_dir_single = QPushButton("...", self)
        self.button_dir_dwi = QPushButton("...", self)
        self.button_dir_preasl = QPushButton("...", self)
        self.button_dir_lateasl = QPushButton("...", self)
        self.button_dir_ref = QPushButton("...", self)

        self.button_dir_single.setSizePolicy(50, 50)
        self.button_dir_dwi.setSizePolicy(50, 50)
        self.button_dir_preasl.setSizePolicy(50, 50)
        self.button_dir_lateasl.setSizePolicy(50, 50)
        self.button_dir_ref.setSizePolicy(50, 50)

        self.button_dir_single.clicked.connect(self.select_file_single)
        self.button_dir_dwi.clicked.connect(self.select_file_dwi)
        self.button_dir_ref.clicked.connect(self.select_file_ref)
        self.button_dir_preasl.clicked.connect(self.select_file_pre)
        self.button_dir_lateasl.clicked.connect(self.select_file_lat)

        self.grid_cb.addWidget(self.cb_autothr, 0, 0)
        self.grid_cb.addWidget(self.cb_autosave, 0, 1)

        self.grid_dir.addWidget(self.label_name_dir_single, 0, 0)
        self.grid_dir.addWidget(self.label_val_dir_single, 0, 1)
        self.grid_dir.addWidget(self.button_dir_single, 0, 2)

        self.grid_dir.addWidget(self.label_name_dir_dwi, 0, 0)
        self.grid_dir.addWidget(self.label_val_dir_dwi, 0, 1)
        self.grid_dir.addWidget(self.button_dir_dwi, 0, 2)

        self.grid_dir.addWidget(self.label_name_dir_preasl, 0, 0)
        self.grid_dir.addWidget(self.label_val_dir_preasl, 0, 1)
        self.grid_dir.addWidget(self.button_dir_preasl, 0, 2)

        self.grid_dir.addWidget(self.label_name_dir_lateasl, 1, 0)
        self.grid_dir.addWidget(self.label_val_dir_lateasl, 1, 1)
        self.grid_dir.addWidget(self.button_dir_lateasl, 1, 2)

        self.grid_dir.addWidget(self.label_name_dir_ref, 2, 0)
        self.grid_dir.addWidget(self.label_val_dir_ref, 2, 1)
        self.grid_dir.addWidget(self.button_dir_ref, 2, 2)

        self.grid_dir.addLayout(self.grid_cb, 3, 0)

        self.grid_radiobutton.addWidget(self.label_radio, 0, 0)
        self.grid_radiobutton.addWidget(self.button_type_single, 1, 0)
        self.grid_radiobutton.addWidget(self.button_type_dwi, 2, 0)
        self.grid_radiobutton.addWidget(self.button_type_asl, 3, 0)
        # self.grid_radiobutton.addWidget(self.cb_directory, 4, 0)
        self.grid_radiobutton.setSpacing(10)

        self.grid_operate.addWidget(self.button_operate, 0, 0)
        self.grid_operate.addWidget(self.button_settings, 0, 1)
        self.grid_operate.setSpacing(10)

        self.grid_full.addLayout(self.grid_dir, 0, 0)
        self.grid_full.addLayout(self.grid_operate, 1, 0)

        self.grid_ui.addLayout(self.grid_radiobutton, 0, 0)
        self.grid_ui.addLayout(self.grid_full, 0, 1)
        self.grid_ui.setGeometry(QRect(50, 50, 400, 250))

        self.set_hiden(self.display_type)

        self.resizeEvent = self.adjustSize

    def set_hiden(self, index):
        # index0-2对应display_type的0-2,其他值时将所有模块设为可见以便调节
        if index == 0:
            self.label_name_dir_single.setHidden(False)
            self.label_val_dir_single.setHidden(False)
            self.button_dir_single.setHidden(False)
            self.label_name_dir_dwi.setHidden(True)
            self.label_val_dir_dwi.setHidden(True)
            self.button_dir_dwi.setHidden(True)
            self.label_name_dir_preasl.setHidden(True)
            self.label_val_dir_preasl.setHidden(True)
            self.button_dir_preasl.setHidden(True)
            self.label_name_dir_lateasl.setHidden(True)
            self.label_val_dir_lateasl.setHidden(True)
            self.button_dir_lateasl.setHidden(True)
            self.label_name_dir_ref.setHidden(True)
            self.label_val_dir_ref.setHidden(True)
            self.button_dir_ref.setHidden(True)
            self.button_type_single.setChecked(True)
            self.button_type_dwi.setChecked(False)
            self.button_type_asl.setChecked(False)
        elif index == 1:
            self.label_name_dir_single.setHidden(True)
            self.label_val_dir_single.setHidden(True)
            self.button_dir_single.setHidden(True)
            self.label_name_dir_dwi.setHidden(False)
            self.label_val_dir_dwi.setHidden(False)
            self.button_dir_dwi.setHidden(False)
            self.label_name_dir_preasl.setHidden(True)
            self.label_val_dir_preasl.setHidden(True)
            self.button_dir_preasl.setHidden(True)
            self.label_name_dir_lateasl.setHidden(True)
            self.label_val_dir_lateasl.setHidden(True)
            self.button_dir_lateasl.setHidden(True)
            self.label_name_dir_ref.setHidden(False)
            self.label_val_dir_ref.setHidden(False)
            self.button_dir_ref.setHidden(False)
            self.button_type_single.setChecked(False)
            self.button_type_dwi.setChecked(True)
            self.button_type_asl.setChecked(False)
        elif index == 2:
            self.label_name_dir_single.setHidden(True)
            self.label_val_dir_single.setHidden(True)
            self.button_dir_single.setHidden(True)
            self.label_name_dir_dwi.setHidden(True)
            self.label_val_dir_dwi.setHidden(True)
            self.button_dir_dwi.setHidden(True)
            self.label_name_dir_preasl.setHidden(False)
            self.label_val_dir_preasl.setHidden(False)
            self.button_dir_preasl.setHidden(False)
            self.label_name_dir_lateasl.setHidden(False)
            self.label_val_dir_lateasl.setHidden(False)
            self.button_dir_lateasl.setHidden(False)
            self.label_name_dir_ref.setHidden(False)
            self.label_val_dir_ref.setHidden(False)
            self.button_dir_ref.setHidden(False)
            self.button_type_single.setChecked(False)
            self.button_type_dwi.setChecked(False)
            self.button_type_asl.setChecked(True)
        else:
            self.label_name_dir_single.setHidden(False)
            self.label_val_dir_single.setHidden(False)
            self.button_dir_single.setHidden(False)
            self.label_name_dir_dwi.setHidden(False)
            self.label_val_dir_dwi.setHidden(False)
            self.button_dir_dwi.setHidden(False)
            self.label_name_dir_preasl.setHidden(False)
            self.label_val_dir_preasl.setHidden(False)
            self.button_dir_preasl.setHidden(False)
            self.label_name_dir_lateasl.setHidden(False)
            self.label_val_dir_lateasl.setHidden(False)
            self.button_dir_lateasl.setHidden(False)
            self.label_name_dir_ref.setHidden(False)
            self.label_val_dir_ref.setHidden(False)
            self.button_dir_ref.setHidden(False)

    def select_file_single(self):
        if self.lan == 0:
            self.path_single = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_single = QFileDialog.getOpenFileNames(
                self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
        temp_text = ""
        self.label_val_dir_single.setText(
            str(self.path_single).replace('[', '').replace(']', ''))

    def select_file_dwi(self):
        if self.lan == 0:
            self.path_dwi = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_dwi = QFileDialog.getOpenFileNames(
                self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
        self.label_val_dir_dwi.setText(
            str(self.path_dwi).replace('[', '').replace(']', ''))

    def select_file_ref(self):
        if self.lan == 0:
            self.path_ref = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_ref = QFileDialog.getOpenFileNames(
                self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
        self.label_val_dir_ref.setText(
            str(self.path_ref).replace('[', '').replace(']', ''))

    def select_file_pre(self):
        if self.lan == 0:
            self.path_pre = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_pre = QFileDialog.getOpenFileNames(
                self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
        self.label_val_dir_preasl.setText(
            str(self.path_pre).replace('[', '').replace(']', ''))

    def select_file_lat(self):
        if self.lan == 0:
            self.path_lat = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_lat = QFileDialog.getOpenFileNames(
                self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
        self.label_val_dir_lateasl.setText(
            str(self.path_lat).replace('[', '').replace(']', ''))

    def radiobutton_clicked(self):
        if self.button_type_single.isChecked() == True:
            self.display_type = 0
        elif self.button_type_dwi.isChecked() == True:
            self.display_type = 1
        elif self.button_type_asl.isChecked() == True:
            self.display_type = 2
        self.set_hiden(self.display_type)

    def createSetting(self):
        # 创建设置面板,包含对CBF计算参数的选择和输入
        settings = ui_setting(self, self.lan)
        # settings.set_value(self.display_asl, lamda, self.PLD, self.T1_blood, self.alpha, self.tau, self.TI, self.TI_1)
        settings.show()

    def adjustSize(self, event):
        self.set_hiden(10086)  # 只要是else里的值就行
        self.grid_ui.setGeometry(
            QRect(50, 50, (self.width() - 100),
                  (self.height() - 100)))  # 将组件全部显示后调整尺寸
        self.set_hiden(self.display_type)  # 设置组件隐藏状态

    def get_value(self):
        return self.display_asl, self.lamda, self.PLD, self.T1_blood, self.alpha, self.tau, self.TI, self.TI_1

    def set_value(self, display_asl, lamda, PLD, T1_blood, alpha, tau, TI,
                  TI_1):
        self.display_asl = display_asl
        self.lamda = lamda
        self.PLD = PLD
        self.T1_blood = T1_blood
        self.alpha = alpha
        self.tau = tau
        self.TI = TI
        self.TI_1 = TI_1

    def calcCBF(self):
        if self.display_type == 0:
            self.calcbf_simple()
        elif self.display_type == 1:
            self.calcbf_dwi()
        elif self.display_type == 2:
            self.calcbf_asl()

    def make_cbf(self, data_dwi, data_ref, nii):
        data = self.ratio * data_dwi / data_ref
        data[np.isnan(data)] = 0
        data[np.isinf(data)] = 0
        thr = np.sum(data * (data > 1)) / np.sum(data > 1)
        if self.cb_autothr.isChecked():
            nii_save = ni.Nifti1Image(data >= thr, nii.affine, nii.header)
        else:
            nii_save = ni.Nifti1Image(data, nii.affine, nii.header)
        return nii_save

    def get_cbfrom_asl(self, path_1, path_2, path_3):
        nii_output = []
        if path_3 == "":
            if path_2 == "":
                # path_2, path_3均为空,认为读取了calcbf_simple的路径信息
                # getOpenFileNames返回值为路径的list,而非路径对应的str
                self.temp.fname = [
                    item.replace(".nii", "_cbf.nii") for item in path_1
                ]
                for path in path_1:
                    nii = ni.load(path)
                    if len(nii.get_fdata().shape) == 4:
                        if nii.get_fdata().shape[3] == 2:
                            nii_output.append(
                                self.make_cbf(nii.get_fdata()[:, :, :, 0],
                                              nii.get_fdata()[:, :, :, 1],
                                              nii))
                        else:
                            if self.lan == 0:
                                warn_msg(
                                    self,
                                    "The Nifti File does not contain PWI Image and PD Image."
                                )
                            elif self.lan == 1:
                                warn_msg(self, "单幅NII图像并未正确包含PWI和PD信息")
                    else:
                        if self.lan == 0:
                            warn_msg(
                                self,
                                "The Nifti File does not contain PWI Image and PD Image."
                            )
                        elif self.lan == 1:
                            warn_msg(self, "单幅NII图像并未正确包含PWI和PD信息")
                self.temp.set_nii(nii_output)

            elif path_1 != "":
                # path_3为空,认为读取了calcbf_dwi的路径信息
                # 如果其中一个路径只有一项,则认为是对应所有另一个路径(可能导致其他问题,可以考虑进行warning)
                if len(path_1) != len(path_2) and len(path_1) != 1 and len(
                        path_2) != 1:
                    if self.lan == 0:
                        warn_msg(
                            self,
                            "DWI series and PD series have different components."
                        )
                    elif self.lan == 1:
                        warn_msg(self, "DWI与PD像数量不一致")
                elif len(path_1) == 1:
                    self.temp.fname = [
                        item.replace(".nii", "_cbf.nii") for item in path_2
                    ]
                    nii_dwi = ni.load(path_1)
                    for path in path_2:
                        nii_ref = ni.load(path)
                        if len(nii_ref.get_fdata().shape) >= 3:
                            nii_output.append(
                                self.make_cbf(nii_dwi.get_fdata(),
                                              nii_ref.get_fdata(), nii_dwi))
                        else:
                            if self.lan == 0:
                                warn_msg(
                                    self,
                                    "The Nifti File does not contain proper Image."
                                )
                            elif self.lan == 1:
                                warn_msg(self, "NII图像存在问题")
                elif len(path_2) == 1:
                    self.temp.fname = [
                        item.replace(".nii", "_cbf.nii") for item in path_1
                    ]
                    nii_ref = ni.load(path_2)
                    for path in path_1:
                        nii_dwi = ni.load(path)
                        if len(nii_ref.get_fdata().shape) >= 3:
                            nii_output.append(
                                self.make_cbf(nii_dwi.get_fdata(),
                                              nii_ref.get_fdata(), nii_dwi))
                        else:
                            if self.lan == 0:
                                warn_msg(
                                    self,
                                    "The Nifti File does not contain proper Image."
                                )
                            elif self.lan == 1:
                                warn_msg(self, "NII图像存在问题")
                else:
                    self.temp.fname = [
                        item.replace(".nii", "_cbf.nii") for item in path_2
                    ]
                    for index in range(len(path_1)):
                        nii_dwi = ni.load(path_1[index])
                        nii_ref = ni.load(path_2[index])
                        if len(nii_ref.get_fdata().shape) >= 3:
                            nii_output.append(
                                self.make_cbf(nii_dwi.get_fdata(),
                                              nii_ref.get_fdata(), nii_dwi))
                        else:
                            if self.lan == 0:
                                warn_msg(
                                    self,
                                    "The Nifti File does not contain proper Image."
                                )
                            elif self.lan == 1:
                                warn_msg(self, "NII图像存在问题")
                self.temp.set_nii(nii_output)
            else:
                if self.lan == 0:
                    warn_msg(self, "Input Directory of PWI Images.")
                elif self.lan == 1:
                    warn_msg(self, "输入ASL差异像路径")

        elif path_1 != "" and path_2 != "":
            # 输入三个路径list时,认为是两次时间的ASL和一次PD
            if len(nii_lat) != len(nii_pre):
                if self.lan == 0:
                    warn_msg(
                        self,
                        "ASL series have different components after delay.")
                elif self.lan == 1:
                    warn_msg(self, "延迟前后ASL图像的数量不一致")
            elif len(nii_lat) != len(nii_ref):
                if self.lan == 0:
                    warn_msg(
                        self,
                        "DWI series and PD series have different components.")
                elif self.lan == 1:
                    warn_msg(self, "DWI与PD像数量不一致")
            else:
                self.temp.fname = [
                    item.replace(".nii", "_cbf.nii") for item in path_3
                ]
                for index in range(len(path_1)):
                    nii_lat = ni.load(path_1[index])
                    nii_pre = ni.load(path_2[index])
                    nii_ref = ni.load(path_3[index])
                    if len(nii_ref.get_data(shape)) >= 3:
                        nii_output.append(
                            self.make_cbf(
                                nii_lat.get_fdata() - nii_pre.get_fdata(),
                                nii_ref.get_fdata(), nii_lat))
                    else:
                        if self.lan == 0:
                            warn_msg(
                                self,
                                "The Nifti File does not contain proper Image."
                            )
                        elif self.lan == 1:
                            warn_msg(self, "NII图像存在问题")
                self.temp.set_nii(nii_output)

        else:
            if self.lan == 0:
                warn_msg(self, "Input Directory of ASL Images.")
            elif self.lan == 1:
                warn_msg(self, "输入ASL像路径")

        self.nii_display = nii2display(self.temp, self.temp.display_vol,
                                       self.temp.niilist[0].get_fdata(),
                                       self.temp.display_min,
                                       self.temp.display_max, self.temp.lan)
        self.temp.idx_fname = len(self.temp.fname) - 1
        self.temp.PrevFile()
        if self.cb_autosave.isChecked():
            for i in range(len(nii_output)):
                ni.save(nii_output[i], self.temp.fname[i])
        self.close()

    def calcbf_dwi(self):
        if self.display_asl == 0:
            self.ratio = 100 * self.lamda * np.exp(
                self.PLD /
                self.T1_blood) / (2 * self.alpha * self.T1_blood *
                                  (1 - np.exp(-self.tau / self.T1_blood)))
        elif self.display_asl == 1:
            self.ratio = 100 * self.lamda * np.exp(
                self.TI / self.T1_blood) / (2 * self.alpha * self.TI_1)
        try:
            self.get_cbfrom_asl(self.path_dwi, self.path_ref, "")
        except FileNotFoundError:
            if self.lan == 0:
                warn_msg(self, "Ensure your directory is correct.")
            elif self.lan == 1:
                warn_msg(self, "文件路径错误")

    def calcbf_asl(self):
        if self.display_asl == 0:
            self.ratio = 100 * self.lamda * np.exp(
                self.PLD /
                self.T1_blood) / (2 * self.alpha * self.T1_blood *
                                  (1 - np.exp(-self.tau / self.T1_blood)))
        elif self.display_asl == 1:
            self.ratio = 100 * self.lamda * np.exp(
                self.TI / self.T1_blood) / (2 * self.alpha * self.TI_1)
        try:
            self.get_cbfrom_asl(self.path_lat, self.path_pre, self.path_ref)
        except FileNotFoundError:
            if self.lan == 0:
                warn_msg(self, "Ensure your directory is correct.")
            elif self.lan == 1:
                warn_msg(self, "文件路径错误")

    def calcbf_simple(self):
        if self.display_asl == 0:
            self.ratio = 100 * self.lamda * np.exp(
                self.PLD /
                self.T1_blood) / (2 * self.alpha * self.T1_blood *
                                  (1 - np.exp(-self.tau / self.T1_blood)))
        elif self.display_asl == 1:
            self.ratio = 100 * self.lamda * np.exp(
                self.TI / self.T1_blood) / (2 * self.alpha * self.TI_1)
        try:
            self.get_cbfrom_asl(self.path_single, "", "")
        except FileNotFoundError:
            if self.lan == 0:
                warn_msg(self, "Ensure your directory is correct.")
            elif self.lan == 1:
                warn_msg(self, "文件路径错误")
Example #30
0
class GainUi(QDialog):

    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowModality(Qt.ApplicationModal)
        self.setMaximumSize(380, 210)
        self.setMinimumSize(380, 210)
        self.resize(380, 210)

        self.setLayout(QGridLayout())

        # ReplayGain mode

        self.gainRadio = QRadioButton(self)
        self.gainRadio.setChecked(True)
        self.layout().addWidget(self.gainRadio, 0, 0)

        self.gainSpinBox = QSpinBox(self)
        self.gainSpinBox.setMaximum(150)
        self.gainSpinBox.setValue(89)
        self.layout().addWidget(self.gainSpinBox, 0, 1)

        # Normalize mode

        self.normalizeRadio = QRadioButton(self)
        self.layout().addWidget(self.normalizeRadio, 1, 0)

        self.normalizeSpinBox = QSpinBox(self)
        self.normalizeSpinBox.setRange(-100, 0)
        self.normalizeSpinBox.setEnabled(False)
        self.layout().addWidget(self.normalizeSpinBox, 1, 1)

        # All/Only selected

        self.selectionMode = QCheckBox(self)
        self.layout().addWidget(self.selectionMode, 2, 0, 1, 2)

        self.line = QFrame(self)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.layout().addWidget(self.line, 3, 0, 1, 2)

        # Max threads (up to cpu count)

        self.cpuLabel = QLabel(self)
        self.layout().addWidget(self.cpuLabel, 4, 0)

        self.cpuSpinBox = QSpinBox(self)
        max_cpu = cpu_count()
        max_cpu = max_cpu if max_cpu is not None else 1
        self.cpuSpinBox.setRange(1, max_cpu)
        self.cpuSpinBox.setValue(max_cpu)
        self.layout().addWidget(self.cpuSpinBox, 4, 1)

        self.dialogButtons = QDialogButtonBox(self)
        self.dialogButtons.setStandardButtons(QDialogButtonBox.Ok |
                                              QDialogButtonBox.Cancel)
        self.layout().addWidget(self.dialogButtons, 5, 0, 1, 2)

        self.normalizeRadio.toggled.connect(self.normalizeSpinBox.setEnabled)
        self.normalizeRadio.toggled.connect(self.gainSpinBox.setDisabled)

        self.dialogButtons.accepted.connect(self.accept)
        self.dialogButtons.rejected.connect(self.reject)

        self.modeGroup = QButtonGroup()
        self.modeGroup.addButton(self.gainRadio)
        self.modeGroup.addButton(self.normalizeRadio)

        self.retranslateUi()

    def retranslateUi(self):
        self.setWindowTitle("ReplayGain / Normalization")
        self.cpuLabel.setText("Threads number")
        self.selectionMode.setText("Apply only to selected media")
        self.gainRadio.setText("ReplayGain to (dB SPL)")
        self.normalizeRadio.setText("Normalize to (dB)")

    def mode(self):
        return 0 if self.gainRadio.isChecked() else 1

    def only_selected(self):
        return self.selectionMode.isChecked()

    def norm_level(self):
        return self.normalizeSpinBox.value()

    def ref_level(self):
        return self.gainSpinBox.value()

    def threads(self):
        return self.cpuSpinBox.value()
Example #31
0
class Root(QMainWindow):
    def __init__(self):

        super().__init__()

        self.setFixedSize(600, 800)
        self.title = "Stego Tool"
        self.top = 400
        self.left = 100
        self.width = 400
        self.height = 600

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('About')

        aboutButton = QAction('Details', self)
        aboutButton.setShortcut('Ctrl+i')
        aboutButton.setStatusTip('Application Information')
        aboutButton.triggered.connect(self.About)
        fileMenu.addAction(aboutButton)

        self.InitWindow()

    def InitWindow(self):

        self.setWindowIcon(QtGui.QIcon("flamingo.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)

        self.image1 = QLabel(self)
        self.image1.setPixmap(QtGui.QPixmap("flamingo.png"))
        self.image1.resize(100, 100)
        self.image1.move(50, 50)
        self.image1.show()

        self.image2 = QLabel(self)
        self.image2.setPixmap(QtGui.QPixmap("hide.png"))
        self.image2.resize(100, 100)
        self.image2.move(420, 220)
        self.image2.show()

        self.image3 = QLabel(self)
        self.image3.setPixmap(QtGui.QPixmap("file.png"))
        self.image3.resize(100, 100)
        self.image3.move(120, 210)
        self.image3.show()

        self.button1 = QPushButton('Cover File', self)
        self.button1.clicked.connect(self.Cover)
        self.button1.move(100, 310)
        self.button1.resize(100, 40)

        self.button2 = QPushButton('File to embed', self)
        self.button2.clicked.connect(self.Embed)
        self.button2.move(400, 310)
        self.button2.resize(100, 40)

        self.button3 = QPushButton('Launch', self)
        self.button3.clicked.connect(
            lambda: self.Launch(self.radio1.isChecked()))
        self.button3.move(250, 635)
        self.button3.resize(100, 40)

        self.radio1 = QRadioButton('None', self)
        self.radio1.setChecked(True)
        self.radio1.move(100, 480)
        self.radio1.resize(80, 20)

        self.radio2 = QRadioButton('AES', self)
        self.radio2.move(100, 505)
        self.radio2.resize(80, 20)

        self.radio3 = QRadioButton('DES', self)
        self.radio3.move(100, 530)
        self.radio3.resize(80, 20)

        self.radio4 = QRadioButton('Blowfish', self)
        self.radio4.move(100, 555)
        self.radio4.resize(80, 20)

        self.spinbox = QSpinBox(self)
        self.spinbox.move(390, 500)
        self.spinbox.resize(100, 50)
        self.spinbox.setMinimum(1)
        self.spinbox.setMaximum(9)
        self.spinbox.valueChanged.connect(self.Compression)
        self.spinbox.show()

        self.font = QFont("SansSerif")
        self.font.setBold(True)

        self.label1 = QLabel(self)
        self.label1.setFont(self.font)
        self.label1.setText("User-friendly Steganography Tool")
        self.label1.move(220, 90)
        self.label1.resize(400, 20)

        self.label2 = QLabel(self)
        self.label2.setFont(self.font)
        self.label2.setText("Type of Encryption")
        self.label2.move(80, 450)
        self.label2.resize(140, 20)

        self.label3 = QLabel(self)
        self.label3.setFont(self.font)
        self.label3.setText("Quality of Compression")
        self.label3.move(370, 450)
        self.label3.resize(180, 20)

        self.label4 = QLabel(self)
        self.label4.setText("Version: 1.0")
        self.label4.move(50, 780)
        self.label4.resize(180, 20)

        self.label5 = QLabel(self)
        self.label5.setText("License: GPL 3.0")
        self.label5.move(430, 780)
        self.label5.resize(180, 20)

        self.label6 = QLabel(self)
        self.label6.setStyleSheet("color: red; ")
        self.label6.setText("")
        self.label6.move(175, 700)
        self.label6.resize(260, 20)

        self.label7 = QLabel(self)
        self.label7.setStyleSheet("color: green; ")
        self.label7.setText("")
        self.label7.move(195, 700)
        self.label7.resize(260, 20)

        self.show()

    def Cover(self):
        self.file1 = QFileDialog.getOpenFileName(
            self, "Select a File", "/home/",
            "Files (*.jpg *.jpeg *.au *.bmp *.wav)")[0]
        self.button1.setText(os.path.basename(self.file1))
        if self.button1.text() == '':
            self.label6.setText("Cover or Embed File has not been selected.")
            self.button1.setText("Cover File")
        try:
            if self.file1 and self.file2 != '':
                self.label6.setText("")
                self.label7.setText("Your file is ready to be concealed.")
            else:
                self.label7.setText("")
        except AttributeError:
            self.label6.setText("Cover or Embed File has not been selected.")

    def Embed(self):
        self.file2 = QFileDialog.getOpenFileName(self, "Select a File",
                                                 "/home/",
                                                 "All Files (*.*)")[0]
        self.button2.setText(os.path.basename(self.file2))
        if self.button2.text() == '':
            self.button2.setText("File to Embed")
            self.label6.setText("Cover or Embed File has not been selected.")
        try:
            if self.file1 and self.file2 != '':
                self.label6.setText("")
                self.label7.setText("Your file is ready to be concealed.")
            else:
                self.label7.setText("")
        except AttributeError:
            self.label6.setText("Cover or Embed File has not been selected.")

    def Compression(self):
        print(str(self.spinbox.value()))

    def Launch(self, check):
        if self.radio1.isChecked():
            try:
                if self.file1 and self.file2 != '':
                    subprocess.call([
                        'bash', 'launch.sh', '-cf', self.file1, '-ef',
                        self.file2, 'none',
                        str(self.spinbox.value())
                    ])
                    self.label7.setText("Your file is ready to be concealed.")
                else:
                    self.label6.setText(
                        "Cover or Embed File has not been selected.")
            except AttributeError:
                self.label6.setText(
                    "Cover or Embed File has not been selected.")
        if self.radio2.isChecked():
            try:
                if self.file1 and self.file2 != '':
                    subprocess.call([
                        'bash', 'launch.sh', '-cf', self.file1, '-ef',
                        self.file2, 'rijndael-128',
                        str(self.spinbox.value())
                    ])
                    self.label7.setText("Your file is ready to be concealed.")
                else:
                    self.label6.setText(
                        "Cover or Embed File has not been selected.")
            except AttributeError:
                self.label6.setText(
                    "Cover or Embed File has not been selected.")
        if self.radio3.isChecked():
            try:
                if self.file1 and self.file2 != '':
                    subprocess.call([
                        'bash', 'launch.sh', '-cf', self.file1, '-ef',
                        self.file2, 'des',
                        str(self.spinbox.value())
                    ])
                    self.label7.setText("Your file is ready to be concealed.")
                else:
                    self.label6.setText(
                        "Cover or Embed File has not been selected.")
            except AttributeError:
                self.label6.setText(
                    "Cover or Embed File has not been selected.")
        if self.radio4.isChecked():
            try:
                if self.file1 and self.file2 != '':
                    subprocess.call([
                        'bash', 'launch.sh', '-cf', self.file1, '-ef',
                        self.file2, 'blowfish',
                        str(self.spinbox.value())
                    ])
                    self.label7.setText("Your file is ready to be concealed.")
                else:
                    self.label6.setText(
                        "Cover or Embed File has not been selected.")
            except AttributeError:
                self.label6.setText(
                    "Cover or Embed File has not been selected.")

        self.answer = subprocess.call(['bash', 'out.sh'])
        if self.answer == 0:
            self.msg = QMessageBox()
            self.top3 = 600
            self.left3 = 200
            self.width3 = 400
            self.height3 = 600
            self.msg.setGeometry(self.top3, self.left3, self.width3,
                                 self.height3)
            self.msg.setText("Your file has been concealed     ")
            self.msg.show()
        else:
            self.msg = QMessageBox()
            self.top3 = 600
            self.left3 = 200
            self.width3 = 400
            self.height3 = 600
            self.msg.setGeometry(self.top3, self.left3, self.width3,
                                 self.height3)
            self.msg.setText("Something went Wrong      ")
            self.msg.show()

    def About(self):
        self.info = QMessageBox()
        self.top2 = 600
        self.left2 = 200
        self.width2 = 400
        self.height2 = 600
        self.info.setGeometry(self.top2, self.left2, self.width2, self.height2)
        self.info.setWindowTitle("Information")
        self.info.setText("\nThis tool is a free/open-source software \
that helps the user to hide a file inside another file in a user-friendly way. \
\n\n Version: 1.0 \n\n License: GPL v3.0")
        self.info.show()
Example #32
0
File: add.py Project: z411/trackma
class AddDialog(QDialog):
    worker = None
    selected_show = None
    results = []

    def __init__(self, parent, worker, current_status, default=None):
        QDialog.__init__(self, parent)
        self.resize(950, 700)
        self.setWindowTitle('Search/Add from Remote')
        self.worker = worker
        self.current_status = current_status
        self.default = default
        if default:
            self.setWindowTitle('Search/Add from Remote for new show: %s' % default)
        
        # Get available search methods and default to keyword search if not reported by the API
        search_methods = self.worker.engine.mediainfo.get('search_methods', [utils.SEARCH_METHOD_KW])

        layout = QVBoxLayout()

        # Create top layout
        top_layout = QHBoxLayout()

        if utils.SEARCH_METHOD_KW in search_methods:
            self.search_rad = QRadioButton('By keyword:')
            self.search_rad.setChecked(True)
            self.search_txt = QLineEdit()
            self.search_txt.returnPressed.connect(self.s_search)
            if default:
                self.search_txt.setText(default)
            self.search_btn = QPushButton('Search')
            self.search_btn.clicked.connect(self.s_search)
            top_layout.addWidget(self.search_rad)
            top_layout.addWidget(self.search_txt)
        else:
            top_layout.setAlignment(QtCore.Qt.AlignRight)

        top_layout.addWidget(self.search_btn)
        
        # Create filter line
        filters_layout = QHBoxLayout()
        
        if utils.SEARCH_METHOD_SEASON in search_methods:
            self.season_rad = QRadioButton('By season:')
            self.season_combo = QComboBox()
            self.season_combo.addItem('Winter', utils.SEASON_WINTER)
            self.season_combo.addItem('Spring', utils.SEASON_SPRING)
            self.season_combo.addItem('Summer', utils.SEASON_SUMMER)
            self.season_combo.addItem('Fall', utils.SEASON_FALL)
        
            self.season_year = QSpinBox()

            today = date.today()
            current_season = (today.month - 1) / 3

            self.season_year.setRange(1900, today.year)
            self.season_year.setValue(today.year)
            self.season_combo.setCurrentIndex(current_season)

            filters_layout.addWidget(self.season_rad)
            filters_layout.addWidget(self.season_combo)
            filters_layout.addWidget(self.season_year)
        
            filters_layout.setAlignment(QtCore.Qt.AlignLeft)
            filters_layout.addWidget(QSplitter())
        else:
            filters_layout.setAlignment(QtCore.Qt.AlignRight)
        
        view_combo = QComboBox()
        view_combo.addItem('Table view')
        view_combo.addItem('Card view')
        view_combo.currentIndexChanged.connect(self.s_change_view)
        
        filters_layout.addWidget(view_combo)

        # Create central content
        self.contents = QStackedWidget()
        
        # Set up views
        tableview = AddTableDetailsView(None, self.worker)
        tableview.changed.connect(self.s_selected)
        self.contents.addWidget(tableview)
        
        cardview = AddCardView(api_info=self.worker.engine.api_info)
        cardview.changed.connect(self.s_selected)
        cardview.activated.connect(self.s_show_details)
        self.contents.addWidget(cardview)
        
        # Use for testing
        #self.set_results([{'id': 1, 'title': 'Hola', 'image': 'https://omaera.org/icon.png'}])

        bottom_buttons = QDialogButtonBox()
        bottom_buttons.addButton("Cancel", QDialogButtonBox.RejectRole)
        self.add_btn = bottom_buttons.addButton("Add", QDialogButtonBox.AcceptRole)
        self.add_btn.setEnabled(False)
        bottom_buttons.accepted.connect(self.s_add)
        bottom_buttons.rejected.connect(self.close)

        # Finish layout
        layout.addLayout(top_layout)
        layout.addLayout(filters_layout)
        layout.addWidget(self.contents)
        layout.addWidget(bottom_buttons)
        self.setLayout(layout)

        if utils.SEARCH_METHOD_SEASON in search_methods:
            self.search_txt.setFocus()

    def worker_call(self, function, ret_function, *args, **kwargs):
        # Run worker in a thread
        self.worker.set_function(function, ret_function, *args, **kwargs)
        self.worker.start()

    def _enable_widgets(self, enable):
        self.search_btn.setEnabled(enable)
        self.contents.currentWidget().setEnabled(enable)

    def set_results(self, results):
        self.results = results
        self.contents.currentWidget().setResults(self.results)

    # Slots
    def s_show_details(self):
        detailswindow = DetailsDialog(self, self.worker, self.selected_show)
        detailswindow.setModal(True)
        detailswindow.show()

    def s_change_view(self, item):
        self.contents.currentWidget().getModel().setResults(None)
        self.contents.setCurrentIndex(item)
        self.contents.currentWidget().getModel().setResults(self.results)
        
    def s_search(self):
        if self.search_rad.isChecked():
            criteria = self.search_txt.text().strip()
            if not criteria:
                return
            method = utils.SEARCH_METHOD_KW
        elif self.season_rad.isChecked():
            criteria = (self.season_combo.itemData(self.season_combo.currentIndex()), self.season_year.value())
            method = utils.SEARCH_METHOD_SEASON
        
        self.contents.currentWidget().clearSelection()
        self.selected_show = None
        
        self._enable_widgets(False)
        self.add_btn.setEnabled(False)
        
        self.worker_call('search', self.r_searched, criteria, method)
    
    def s_selected(self, show):
        self.selected_show = show
        self.add_btn.setEnabled(True)
        
    def s_add(self):
        if self.selected_show:
            self.worker_call('add_show', self.r_added, self.selected_show, self.current_status)

    # Worker responses
    def r_searched(self, result):
        self._enable_widgets(True)
        
        if result['success']:
            self.set_results(result['result'])
            
            """
            if self.table.currentRow() is 0:  # Row number hasn't changed but the data probably has!
                self.s_show_selected(self.table.item(0, 0))
            self.table.setCurrentItem(self.table.item(0, 0))"""
        else:
            self.set_results(None)

    def r_added(self, result):
        if result['success']:
            if self.default:
                self.accept()
Example #33
0
class App(QWidget):

    buttonList = list()
    _thUpdate = 0
    currentTime = 0
    _planLoad = dict()
    _planSave = Counter()
    _DAYOFWEEK = ("monday", "tuesday", "wednesday", "thursday", "friday",
                  "saturday", "sunday")

    def __init__(self, parent):
        super(App, self).__init__(parent)
        self.initUI()

    def initUI(self):
        #open file with data for blocks
        try:
            with open('dataLoad.json', 'r') as readData:
                self._planLoad = json.load(readData)
                print('read the dataLoad')
        except:
            self._planLoad = dict()
            self._planLoad[str(
                datetime.datetime.utcnow().isocalendar()[0])] = dict()

        #open file with saved data
        try:
            with open('dataSave.json', 'r') as readData:
                self._planSave = json.load(readData)
                print('read the dataSave')
        except:
            self._planSave = dict()
            self._planSave[str(
                datetime.datetime.utcnow().isocalendar()[0])] = dict()

        #open file with blockStrings
        try:
            with open('blockStrings.json', 'r') as readData:
                self._blockStrings = json.load(readData)
                print('read the blockStrings')
        except:
            self._blockStrings = dict()
            self._blockStrings.update({
                '0': 'nothing',
                '1': 'learn',
                '2': 'read',
                '3': 'work',
                '4': 'sail',
                '5': 'play'
            })

        print(self._planSave)

        self.work = QLabel(self)
        self.work.setText('')
        self.work.setFixedSize(300, 20)
        self.currentTime = QLabel(self)
        self.currentTime.setText('')
        self.countdownTime = QLabel(self)
        self.dayofweek = [QLabel(self) for i in range(7)]
        self.countdownTime.setText('')
        self.progress = QProgressBar(self)
        self.progress.setGeometry(10, 250, 300, 50)
        self.progress.setMaximum(100)

        self.groupBox = QGroupBox("Check")

        self.b1 = QRadioButton("CheckIn")
        self.b2 = QRadioButton("CheckOut")
        self.b1.setChecked(False)
        self.b2.setChecked(True)

        _vbox = QVBoxLayout()

        _vbox.addWidget(self.b1)
        _vbox.addWidget(self.b2)

        for day in range(7):
            _hboxTable = QHBoxLayout()
            for hour in range(24):
                try:
                    mTime = datetime.datetime.utcnow().isocalendar()
                    color = self._planLoad[str(mTime[0])][str(mTime[1])].get(
                        str(day * 24 + hour))
                except:
                    color = 0
                self.buttonList.append(
                    Blocks(day, hour, self, color, _hboxTable))
            self.dayofweek[day].setText(self._DAYOFWEEK[day])
            _hboxTable.addWidget(self.dayofweek[day])

            _vbox.addLayout(_hboxTable)

        _vbox.addWidget(self.currentTime)
        _vbox.addWidget(self.work)
        _vbox.addWidget(self.countdownTime)
        _vbox.addWidget(self.progress)

        self.setLayout(_vbox)

        self._thUpdate = threading.Timer(1, self.threadUpdate)
        self._thUpdate.start()

    def btnstate(self, b):
        if b.text() == "CheckIn":
            if b.isChecked() == True:
                print(b.text() + "is selected")
        if b.text() == "CheckOut":
            if b.isChecked() == True:
                print(b.text() + "is selected")

    def calcItemPos(self, _day, _hour):
        return (_day * 24) + _hour

    def showTime(self, full):
        _now = time.localtime()
        _actItem = self.calcItemPos(_now.tm_wday, _now.tm_hour)
        _showTimeBlockLeft = 0
        _showTimeBlockPast = 0

        #check blocks in the future
        _showTimeActItem = _actItem
        try:
            while self.buttonList[_showTimeActItem-1].getColor() \
                    == self.buttonList[_showTimeActItem].getColor():
                _showTimeBlockPast += 1
                _showTimeActItem -= 1
        except:
            pass

        #check block in the past
        _showTimeActItem = _actItem
        try:
            while self.buttonList[_showTimeActItem+1].getColor() \
                    == self.buttonList[_showTimeActItem].getColor():
                _showTimeBlockLeft += 1
                _showTimeActItem += 1
        except:
            pass

        _showTimeTotal = (_showTimeBlockLeft + 1 + _showTimeBlockPast) * 60
        _showTimeLeft = ((_showTimeBlockLeft * 60) + 59 - _now.tm_min)
        _workStr = str('dOS activity: ') + self._blockStrings[
            self.buttonList[_actItem].getColorStr()]
        _currentTimeStr = str(_now.tm_hour).zfill(2) + ':' + str(
            _now.tm_min).zfill(2) + ':' + str(_now.tm_sec).zfill(2)
        _countDownStr = str(_showTimeLeft).zfill(2) + ':' + str(
            59 - _now.tm_sec).zfill(2)

        if full:
            self.progress.setValue(100 -
                                   (_showTimeLeft / _showTimeTotal) * 100)
            self.work.setText(_workStr)
            self.currentTime.setText('current time: ' + _currentTimeStr)
            self.countdownTime.setText('time left: ' + _countDownStr)
        else:
            self.progress.setValue(0)
            self.work.setText("")
            self.currentTime.setText('current time: ' + _currentTimeStr)
            self.countdownTime.setText("")

    def calcSeconds(self):
        _now = time.localtime()
        _actItem = self.calcItemPos(_now.tm_wday, _now.tm_hour)
        _Time = datetime.datetime.utcnow().isocalendar()

        try:
            self._planSave[str(_Time[0])][self._blockStrings[
                self.buttonList[_actItem].getColorStr()]] += 1
        except:
            self._planSave[str(_Time[0])][self._blockStrings[
                self.buttonList[_actItem].getColorStr()]] = 0

    def getSeconds(self):
        _now = time.localtime()
        _actItem = self.calcItemPos(_now.tm_wday, _now.tm_hour)
        _Time = datetime.datetime.utcnow().isocalendar()

        try:
            return self._planSave[str(_Time[0])][self._blockStrings[
                self.buttonList[_actItem].getColorStr()]]
        except:
            self._planSave[str(_Time[0])][self._blockStrings[
                self.buttonList[_actItem].getColorStr()]] = 0
            return self._planSave[str(_Time[0])][self._blockStrings[
                self.buttonList[_actItem].getColorStr()]]

    def threadUpdate(self):
        self._thUpdate = threading.Timer(1, self.threadUpdate)
        self._thUpdate.start()

        if self.b1.isChecked():
            self.calcSeconds()
            self.showTime(1)
        else:
            self.showTime(0)

    def getPlan(self):
        _plan = dict()
        for day in range(7):
            for hour in range(24):
                mItem = self.calcItemPos(day, hour)
                _plan.update({mItem: self.buttonList[mItem].getColor()})
        return _plan

    def exitWidget(self):
        #kill thread
        self._thUpdate.cancel()
        #save stuff
        _Time = datetime.datetime.utcnow().isocalendar()
        self._planLoad[str(_Time[0])][str(_Time[1])] = self.getPlan()
        with open('dataLoad.json', 'w') as wrData:
            print('saved dataLoad')
            json.dump(self._planLoad, wrData, indent=2, ensure_ascii=False)
        #self._planSave[str(_Time[0])] = self.getHours()
        with open('dataSave.json', 'w') as wrData:
            print('saved dataSave')
            json.dump(self._planSave, wrData, indent=2, ensure_ascii=False)
        with open('blockStrings.json', 'w') as wrData:
            print('saved blockStrings')
            json.dump(self._blockStrings, wrData, indent=2, ensure_ascii=False)
Example #34
0
class MainWindow(QMainWindow):

    def __init__(self, autoTradingSystem):

        super(MainWindow, self).__init__()
        self.ATM = autoTradingSystem
        self.initUI()

    def initUI(self):

        self.setStyle()
        self.setWindowTitle('Auto Trading System')
        self.initToolBar()
        self.initMenuBar()
        self.initMainBoard()
        self.techAnPage()
        #self.pairTrPage()

        # make window in center point
        self.setFixedSize(1000, 700)
        qr = self.frameGeometry()
        qr.moveCenter(QDesktopWidget().availableGeometry().center())
        self.move(qr.topLeft())

        self.show()

    def initMainBoard(self):

        self.mainBoard = QWidget()
        self.setCentralWidget(self.mainBoard)
        self.pagesStatus = [0]*5
        self.pages = [QWidget(self.mainBoard) for i in self.pagesStatus]
        self.toolButtons

        self.mainBoard.setStyleSheet(self.mainBoardQSS)
        for page in self.pages: page.setStyleSheet(self.pagesQSS)

    def initToolBar(self):

        self.toolBar = QToolBar("Tools")
        self.toolBar.setMovable(False)
        self.addToolBar(Qt.LeftToolBarArea, self.toolBar)
        self.toolBar.setIconSize(QSize(20, 20))

        self.techAnButton = QToolButton()
        self.techAnButton.setText("Technical analysis")
        self.techAnButton.setFixedSize(130, 25)
        self.pairTrButton = QToolButton()
        self.pairTrButton.setText("Pair Trading")
        self.pairTrButton.setFixedSize(130, 25)
        self.atoTrdButton = QToolButton()
        self.atoTrdButton.setText("Monitor")
        self.atoTrdButton.setFixedSize(130, 25)
        self.trdPnlButton = QToolButton()
        self.trdPnlButton.setText("PnL Report")
        self.trdPnlButton.setFixedSize(130, 25)
        self.trdHisButton = QToolButton()
        self.trdHisButton.setText("Trade History")
        self.trdHisButton.setFixedSize(130, 25)

        self.techAnButton.clicked.connect(self.techAnPage)
        self.pairTrButton.clicked.connect(self.pairTrPage)
        self.atoTrdButton.clicked.connect(self.atoTrdPage)
        self.trdPnlButton.clicked.connect(self.trdPnlPage)
        self.trdHisButton.clicked.connect(self.trdHisPage)

        self.toolBar.addWidget(self.techAnButton)
        self.toolBar.addWidget(self.pairTrButton)
        self.toolBar.addWidget(self.atoTrdButton)
        self.toolBar.addWidget(self.trdPnlButton)
        self.toolBar.addWidget(self.trdHisButton)
        self.toolButtons = [self.techAnButton, self.pairTrButton, self.atoTrdButton, self.trdPnlButton, self.trdHisButton]

    def initMenuBar(self):

        exitAction = QAction('&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        techAnAction = QAction('&Technical Analysis', self)
        techAnAction.setShortcut('Ctrl+T')
        techAnAction.triggered.connect(self.techAnPage)
        pairTrAction = QAction('&Pair Trading', self)
        pairTrAction.setShortcut('Ctrl+P')
        pairTrAction.triggered.connect(self.pairTrPage)
        atoTrdAction = QAction('&Monitor', self)
        atoTrdAction.setShortcut('Ctrl+M')
        atoTrdAction.triggered.connect(self.atoTrdPage)
        trdPnlAction = QAction('&Profit And Loss Report', self)
        trdPnlAction.setShortcut('Ctrl+R')
        trdPnlAction.triggered.connect(self.trdPnlPage)
        trdHisAction = QAction('&Trade History', self)
        trdHisAction.setShortcut('Ctrl+H')
        trdHisAction.triggered.connect(self.trdHisPage)

        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fannsMenu = menubar.addMenu('&App')
        fannsMenu.addAction(exitAction)
        naviMenu = menubar.addMenu('&Navigate')
        naviMenu.addAction(techAnAction)
        naviMenu.addAction(pairTrAction)
        naviMenu.addAction(atoTrdAction)
        naviMenu.addAction(trdPnlAction)
        naviMenu.addAction(trdHisAction)

    # The technical analysis page
    def techAnPage(self):

        # hide all pages to show self page
        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in technical analysis page"
        ci = 0
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            self.pageTechAnConfigWidget = QWidget(page)
            self.pageTechAnConfigWidget.setFixedSize(860, 700)

            pageMainVerticalBox = QVBoxLayout()
            pageMainVerticalBox.setContentsMargins(0, 5, 0, 0)

            self.pageTechAnTitleLabel = QLabel("Technical Analysis", page)
            self.pageTechAnTitleLabel.setFixedSize(860, 25)
            self.pageTechAnTitleLabel.setStyleSheet(self.pageTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnTitleLabel)

            # capital config components
            self.pageTechAnCapitalLabel = QLabel("Capital Config", page)
            self.pageTechAnCapitalLabel.setFixedSize(860, 25)
            self.pageTechAnCapitalLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnCapitalLabel)
            capitalHbox = QHBoxLayout()
            capitalHbox.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnCapitalInputLabel = QLabel("Capital: ", page)
            self.pageTechAnCapitalInputLabel.setFont(self.contentFont)
            self.pageTechAnCapitalInputLabel.setFixedSize(100, 25)
            self.pageTechAnCapitalInputLabel.setStyleSheet(self.itemNameQSS)
            capitalHbox.addWidget(self.pageTechAnCapitalInputLabel)
            self.pageTechAnCapitalEdit = QLineEdit("$ 100,000,000")
            self.pageTechAnCapitalEdit.setStyleSheet(self.lineEditQSS)
            self.pageTechAnCapitalEdit.setFixedSize(300, 25)
            self.pageTechAnCapitalEdit.setEnabled(False)
            capitalHbox.addWidget(self.pageTechAnCapitalEdit)
            capitalHbox.addStretch(1)
            pageMainVerticalBox.addLayout(capitalHbox)

            # security code select components
            self.pageTechAnSecurityLabel = QLabel("Security Select", page)
            self.pageTechAnSecurityLabel.setFixedSize(860, 25)
            self.pageTechAnSecurityLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnSecurityLabel)
            securityHbox = QHBoxLayout()
            securityHbox.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnSecurityCode= QLabel("Security Code: ", page)
            self.pageTechAnSecurityCode.setFont(self.contentFont)
            self.pageTechAnSecurityCode.setFixedSize(100, 25)
            self.pageTechAnSecurityCode.setStyleSheet(self.itemNameQSS)
            securityHbox.addWidget(self.pageTechAnSecurityCode)
            self.pageTechAnSecurityCombo = QComboBox(page)
            self.pageTechAnSecurityCombo.setFixedSize(300, 25)
            self.pageTechAnSecurityCombo.setStyleSheet(self.comboQSS)
            self.pageTechAnSecurityCombo.addItem("hsi_futures_jan")
            for item in self.ATM.data.getAssetList("./dataManager/data/hsi_futures"): self.pageTechAnSecurityCombo.addItem(item)
            securityHbox.addWidget(self.pageTechAnSecurityCombo)
            securityHbox.addStretch(1)
            pageMainVerticalBox.addLayout(securityHbox)

            # investment strategies select components
            self.pageTechAnStrategiesLabel = QLabel("Investment Strategies Select", page)
            self.pageTechAnStrategiesLabel.setFixedSize(860, 25)
            self.pageTechAnStrategiesLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnStrategiesLabel)
            self.pageTechAnStrategiesWidget = QWidget(page)
            self.pageTechAnStrategiesWidget.setFixedSize(700, 80)
            strategiesGrid = QGridLayout()
            strategiesGrid.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnStrategyCheckBoxACOscillator = QCheckBox("  ACOscillator")
            self.pageTechAnStrategyCheckBoxCCICorrection= QCheckBox("  CCI Correction")
            self.pageTechAnStrategyCheckBoxDMRSIADX     = QCheckBox("  DM RSI ADX")
            self.pageTechAnStrategyCheckBoxMACD         = QCheckBox("  MACD")
            self.pageTechAnStrategyCheckBoxBreakoutsSwing=QCheckBox("  Breakouts Swing")
            self.pageTechAnStrategyCheckBoxOscillator313= QCheckBox("  Oscillator3 13")
            self.pageTechAnStrategyCheckBoxACOscillator.setChecked(False)
            self.pageTechAnStrategyCheckBoxCCICorrection.setChecked(False)
            self.pageTechAnStrategyCheckBoxDMRSIADX.setChecked(False)
            self.pageTechAnStrategyCheckBoxMACD.setChecked(True)
            self.pageTechAnStrategyCheckBoxBreakoutsSwing.setChecked(False)
            self.pageTechAnStrategyCheckBoxOscillator313.setChecked(False)
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxACOscillator, *(1, 1))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxCCICorrection, *(1, 2))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxDMRSIADX, *(1, 3))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxMACD, *(2,1))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxBreakoutsSwing, *(2,2))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxOscillator313, *(2,3))
            self.pageTechAnStrategiesWidget.setLayout(strategiesGrid)
            pageMainVerticalBox.addWidget(self.pageTechAnStrategiesWidget)

            # trading time config components
            self.pageTechAnTimeSpanLabel = QLabel("Trading Time Config", page)
            self.pageTechAnTimeSpanLabel.setFixedSize(860, 25)
            self.pageTechAnTimeSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnTimeSpanLabel)
            timeVbox = QVBoxLayout()
            timeVbox.setContentsMargins(30, 10, 0, 10)
            startTimeHbox = QHBoxLayout()
            self.pageTechAnStartTimeName = QLabel("Start Time: ", page)
            self.pageTechAnStartTimeName.setFont(self.contentFont)
            self.pageTechAnStartTimeName.setFixedSize(100, 25)
            self.pageTechAnStartTimeName.setStyleSheet(self.itemNameQSS)
            startTimeHbox.addWidget(self.pageTechAnStartTimeName)
            self.pageTechAnStartTimeEdit = QLineEdit("2016-02-10 16:00:00")
            self.pageTechAnStartTimeEdit.setEnabled(False)
            self.pageTechAnStartTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pageTechAnStartTimeEdit.setFixedSize(300, 25)
            startTimeHbox.addWidget(self.pageTechAnStartTimeEdit)
            startTimeHbox.addStretch(1)
            timeVbox.addLayout(startTimeHbox)
            endTimeHbox = QHBoxLayout()
            self.pageTechAnEndTimeName = QLabel("End Time: ", page)
            self.pageTechAnEndTimeName.setFont(self.contentFont)
            self.pageTechAnEndTimeName.setFixedSize(100, 25)
            self.pageTechAnEndTimeName.setStyleSheet(self.itemNameQSS)
            endTimeHbox.addWidget(self.pageTechAnEndTimeName)
            self.pageTechAnEndTimeEdit = QLineEdit("2016-02-26 16:00:00")
            self.pageTechAnEndTimeEdit.setEnabled(False)
            self.pageTechAnEndTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pageTechAnEndTimeEdit.setFixedSize(300, 25)
            endTimeHbox.addWidget(self.pageTechAnEndTimeEdit)
            endTimeHbox.addStretch(1)
            timeVbox.addLayout(endTimeHbox)
            pageMainVerticalBox.addLayout(timeVbox)

            # trading strategies select components
            self.pageTechAnTStrSpanLabel = QLabel("Trading Strategies Select", page)
            self.pageTechAnTStrSpanLabel.setFixedSize(860, 25)
            self.pageTechAnTStrSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnTStrSpanLabel)
            self.pageTechAnTradeStrateWidget = QWidget(page)
            self.pageTechAnTradeStrateWidget.setFixedSize(700, 40)
            tradeStratGrid = QGridLayout()
            tradeStratGrid.setContentsMargins(30, 5, 0, 5)
            self.pageTechAnTStrRadioButtonVWAP = QRadioButton("  VWAP")
            self.pageTechAnTStrRadioButtonVWAP.setCheckable(False)
            self.pageTechAnTStrRadioButtonTWAP = QRadioButton("  TWAP")
            self.pageTechAnTStrRadioButtonTWAP.setChecked(True)
            self.pageTechAnTStrRadioButtonNONE = QRadioButton("  NONE")
            tradeStratGrid.addWidget(self.pageTechAnTStrRadioButtonVWAP, *(1, 1))
            tradeStratGrid.addWidget(self.pageTechAnTStrRadioButtonTWAP, *(1, 2))
            tradeStratGrid.addWidget(self.pageTechAnTStrRadioButtonNONE, *(1, 3))
            tradeStratGrid.addWidget(QLabel(), *(1, 4))
            tradeStratGrid.addWidget(QLabel(), *(1, 5))
            self.pageTechAnTradeStrateWidget.setLayout(tradeStratGrid)
            pageMainVerticalBox.addWidget(self.pageTechAnTradeStrateWidget)

            # position management method select components
            self.pageTechAnPManSpanLabel = QLabel("Position Management Method Select", page)
            self.pageTechAnPManSpanLabel.setFixedSize(860, 25)
            self.pageTechAnPManSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnPManSpanLabel)
            self.pageTechAnPManageMthdWidget = QWidget(page)
            self.pageTechAnPManageMthdWidget.setFixedSize(700, 40)
            pManageMtdGrid = QGridLayout()
            pManageMtdGrid.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnPMtdRadioButtonFixedFraction = QRadioButton("  Fixed Fraction")
            self.pageTechAnPMtdRadioButtonFixedFraction.setChecked(True)
            self.pageTechAnPMtdRadioButtonMaximDrawDown = QRadioButton("  Max Draw Down")
            pManageMtdGrid.addWidget(self.pageTechAnPMtdRadioButtonFixedFraction, *(1, 1))
            pManageMtdGrid.addWidget(self.pageTechAnPMtdRadioButtonMaximDrawDown, *(1, 2))
            pManageMtdGrid.addWidget(QLabel(), *(1, 3))
            pManageMtdGrid.addWidget(QLabel(), *(1, 4))
            pManageMtdGrid.addWidget(QLabel(), *(1, 5))
            self.pageTechAnPManageMthdWidget.setLayout(pManageMtdGrid)
            pageMainVerticalBox.addWidget(self.pageTechAnPManageMthdWidget)

            space = QWidget()
            space.setFixedSize(0, 0)
            pageMainVerticalBox.addWidget(space)

            self.pageTechAnLaunchButton = QPushButton("Launch")
            self.pageTechAnLaunchButton.setFont(self.contentFont)
            self.pageTechAnLaunchButton.setFixedSize(860, 40)
            self.pageTechAnLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
            self.pageTechAnLaunchButton.clicked.connect(self.pageTechAnLaunch)
            pageMainVerticalBox.addWidget(self.pageTechAnLaunchButton)

            page.setLayout(pageMainVerticalBox)

            self.pagesStatus[ci] = 1

        page.show()

    def pageTechAnLaunch(self):

        capital      = int("".join(re.split("\$| |,", self.pageTechAnCapitalEdit.text())))
        securityCode = self.pageTechAnSecurityCombo.currentText()

        investmentStrategies = []
        if self.pageTechAnStrategyCheckBoxACOscillator.isChecked()  : investmentStrategies.append("ACOscillator")
        if self.pageTechAnStrategyCheckBoxCCICorrection.isChecked() : investmentStrategies.append("CCI_Correction")
        if self.pageTechAnStrategyCheckBoxDMRSIADX.isChecked()      : investmentStrategies.append("DM_RSI_ADX")
        if self.pageTechAnStrategyCheckBoxMACD.isChecked()          : investmentStrategies.append("MACD")
        if self.pageTechAnStrategyCheckBoxBreakoutsSwing.isChecked(): investmentStrategies.append("breakouts_swing")
        if self.pageTechAnStrategyCheckBoxOscillator313.isChecked() : investmentStrategies.append("oscillator3_13")

        startTime = self.pageTechAnStartTimeEdit.text()
        endTime   = self.pageTechAnEndTimeEdit.text()

        tradeStrategy = None
        if self.pageTechAnTStrRadioButtonVWAP.isChecked()   : tradeStrategy = "VWAP"
        if self.pageTechAnTStrRadioButtonTWAP.isChecked()   : tradeStrategy = "TWAP"
        # if self.pageTechAnTStrRadioButtonPOV.isChecked()    : tradeStrategy = "POV"
        # if self.pageTechAnTStrRadioButtonSimple.isChecked() : tradeStrategy = "Simple"
        if self.pageTechAnTStrRadioButtonNONE.isChecked()   : tradeStrategy = "Default"

        positionManagement = None
        if self.pageTechAnPMtdRadioButtonFixedFraction.isChecked()  : positionManagement = "FixedFraction"
        if self.pageTechAnPMtdRadioButtonMaximDrawDown.isChecked()  : positionManagement = "MaximumDrawDown"

        thread.start_new_thread(self.ATM.launchTechnicalAnalysis, (capital, securityCode, investmentStrategies, startTime, endTime, tradeStrategy, positionManagement))

    def pageTechAnLaunchProcess(self):
        self.pageTechAnLaunchButton.setStyleSheet(self.launchWdgtProcesQSS)
        self.pageTechAnLaunchButton.setText("Processing")

    def pageTechAnLaunchFinish(self):
        self.pageTechAnLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
        self.pageTechAnLaunchButton.setText("Re-Launch")

    # The pair trading page
    def pairTrPage(self):

        # hide all pages to show self page
        for pi in range(0, len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in pair trading page"
        ci = 1
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:
            self.pagePairTrConfigWidget = QWidget(page)
            self.pagePairTrConfigWidget.setFixedSize(860, 700)

            pageMainVerticalBox = QVBoxLayout()
            pageMainVerticalBox.setContentsMargins(0, 5, 0, 0)

            self.pagePairTrTitleLabel = QLabel("Pair Trading")
            self.pagePairTrTitleLabel.setFixedSize(860, 25)
            self.pagePairTrTitleLabel.setStyleSheet(self.pageTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrTitleLabel)

            self.pagePairTrCapitalLabel = QLabel("Capital Config", page)
            self.pagePairTrCapitalLabel.setFixedSize(860, 25)
            self.pagePairTrCapitalLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrCapitalLabel)
            capitalHbox = QHBoxLayout()
            capitalHbox.setContentsMargins(30, 10, 0, 10)
            self.pagePairTrCapitalInputLabel = QLabel("Capital: ", page)
            self.pagePairTrCapitalInputLabel.setFont(self.contentFont)
            self.pagePairTrCapitalInputLabel.setFixedSize(100, 25)
            self.pagePairTrCapitalInputLabel.setStyleSheet(self.itemNameQSS)
            capitalHbox.addWidget(self.pagePairTrCapitalInputLabel)
            self.pagePairTrCapitalEdit = QLineEdit("$ 100,000,000")
            self.pagePairTrCapitalEdit.setStyleSheet(self.lineEditQSS)
            self.pagePairTrCapitalEdit.setFixedSize(300, 25)
            self.pagePairTrCapitalEdit.setEnabled(False)
            capitalHbox.addWidget(self.pagePairTrCapitalEdit)
            capitalHbox.addStretch(1)
            pageMainVerticalBox.addLayout(capitalHbox)

            self.pagePairTrSecurityLabel = QLabel("Security Select", page)
            self.pagePairTrSecurityLabel.setFixedSize(860, 25)
            self.pagePairTrSecurityLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrSecurityLabel)
            securityHbox = QHBoxLayout()
            securityHbox.setContentsMargins(30, 10, 0, 10)
            self.pagePairTrSecurityCode = QLabel("Security Basket: ", page)
            self.pagePairTrSecurityCode.setFont(self.contentFont)
            self.pagePairTrSecurityCode.setFixedSize(100, 25)
            self.pagePairTrSecurityCode.setStyleSheet(self.itemNameQSS)
            securityHbox.addWidget(self.pagePairTrSecurityCode)
            self.pagePairTrSecurities = QTextEdit(page)
            self.pagePairTrSecurities.setEnabled(False)
            self.pagePairTrSecurities.setFixedSize(600, 148)
            securities = ""
            for item in self.ATM.data.getAssetList("./dataManager/data/hsi_stocks"): securities += item + '   '
            self.pagePairTrSecurities.setText(securities)
            securityHbox.addWidget(self.pagePairTrSecurities)
            securityHbox.addStretch(1)
            pageMainVerticalBox.addLayout(securityHbox)

            self.pagePairTrTimeSpanLabel = QLabel("Trading Time Config", page)
            self.pagePairTrTimeSpanLabel.setFixedSize(860, 25)
            self.pagePairTrTimeSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrTimeSpanLabel)
            timeVbox = QVBoxLayout()
            timeVbox.setContentsMargins(30, 10, 0, 10)
            startTimeHbox = QHBoxLayout()
            self.pagePairTrStartTimeName = QLabel("Start Time: ", page)
            self.pagePairTrStartTimeName.setFont(self.contentFont)
            self.pagePairTrStartTimeName.setFixedSize(100, 25)
            self.pagePairTrStartTimeName.setStyleSheet(self.itemNameQSS)
            startTimeHbox.addWidget(self.pagePairTrStartTimeName)
            self.pagePairTrStartTimeEdit = QLineEdit("2016-02-10 16:00:00")
            self.pagePairTrStartTimeEdit.setEnabled(False)
            self.pagePairTrStartTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pagePairTrStartTimeEdit.setFixedSize(300, 25)
            startTimeHbox.addWidget(self.pagePairTrStartTimeEdit)
            startTimeHbox.addStretch(1)
            timeVbox.addLayout(startTimeHbox)
            endTimeHbox = QHBoxLayout()
            self.pagePairTrEndTimeName = QLabel("End Time: ", page)
            self.pagePairTrEndTimeName.setFont(self.contentFont)
            self.pagePairTrEndTimeName.setFixedSize(100, 25)
            self.pagePairTrEndTimeName.setStyleSheet(self.itemNameQSS)
            endTimeHbox.addWidget(self.pagePairTrEndTimeName)
            self.pagePairTrEndTimeEdit = QLineEdit("2016-02-26 16:00:00")
            self.pagePairTrEndTimeEdit.setEnabled(False)
            self.pagePairTrEndTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pagePairTrEndTimeEdit.setFixedSize(300, 25)
            endTimeHbox.addWidget(self.pagePairTrEndTimeEdit)
            endTimeHbox.addStretch(1)
            timeVbox.addLayout(endTimeHbox)
            pageMainVerticalBox.addLayout(timeVbox)

            self.pagePairTrTStrSpanLabel = QLabel("Trading Strategies Select", page)
            self.pagePairTrTStrSpanLabel.setFixedSize(860, 25)
            self.pagePairTrTStrSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrTStrSpanLabel)
            self.pagePairTrTradeStrateWidget = QWidget(page)
            self.pagePairTrTradeStrateWidget.setFixedSize(700, 40)
            tradeStratGrid = QGridLayout()
            tradeStratGrid.setContentsMargins(30, 5, 0, 5)
            self.pagePairTrTStrRadioButtonVWAP = QRadioButton("  VWAP")
            self.pagePairTrTStrRadioButtonVWAP.setCheckable(False)
            self.pagePairTrTStrRadioButtonTWAP = QRadioButton("  TWAP")
            self.pagePairTrTStrRadioButtonTWAP.setChecked(True)
            self.pagePairTrTStrRadioButtonNONE = QRadioButton("  NONE")
            tradeStratGrid.addWidget(self.pagePairTrTStrRadioButtonVWAP, *(1, 1))
            tradeStratGrid.addWidget(self.pagePairTrTStrRadioButtonTWAP, *(1, 2))
            tradeStratGrid.addWidget(self.pagePairTrTStrRadioButtonNONE, *(1, 3))
            tradeStratGrid.addWidget(QLabel(), *(1, 4))
            tradeStratGrid.addWidget(QLabel(), *(1, 5))
            self.pagePairTrTradeStrateWidget.setLayout(tradeStratGrid)
            pageMainVerticalBox.addWidget(self.pagePairTrTradeStrateWidget)

            self.pagePairTrPManSpanLabel = QLabel("Position Management Method Select", page)
            self.pagePairTrPManSpanLabel.setFixedSize(860, 25)
            self.pagePairTrPManSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrPManSpanLabel)
            self.pagePairTrPManageMthdWidget = QWidget(page)
            self.pagePairTrPManageMthdWidget.setFixedSize(700, 40)
            pManageMtdGrid = QGridLayout()
            pManageMtdGrid.setContentsMargins(30, 10, 0, 10)
            self.pagePairTrPMtdRadioButtonFixedFraction = QRadioButton("  Fixed Fraction")
            self.pagePairTrPMtdRadioButtonFixedFraction.setChecked(True)
            self.pagePairTrPMtdRadioButtonMaximDrawDown = QRadioButton("  Max Draw Down")
            pManageMtdGrid.addWidget(self.pagePairTrPMtdRadioButtonFixedFraction, *(1, 1))
            pManageMtdGrid.addWidget(self.pagePairTrPMtdRadioButtonMaximDrawDown, *(1, 2))
            pManageMtdGrid.addWidget(QLabel(), *(1, 3))
            pManageMtdGrid.addWidget(QLabel(), *(1, 4))
            pManageMtdGrid.addWidget(QLabel(), *(1, 5))
            self.pagePairTrPManageMthdWidget.setLayout(pManageMtdGrid)
            pageMainVerticalBox.addWidget(self.pagePairTrPManageMthdWidget)

            space = QWidget()
            space.setFixedSize(0, 0)
            pageMainVerticalBox.addWidget(space)

            self.pagePairTrLaunchButton = QPushButton("Launch")
            self.pagePairTrLaunchButton.setFont(self.contentFont)
            self.pagePairTrLaunchButton.setFixedSize(860, 40)
            self.pagePairTrLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
            self.pagePairTrLaunchButton.clicked.connect(self.pagePairTrdLaunch)
            pageMainVerticalBox.addWidget(self.pagePairTrLaunchButton)

            page.setLayout(pageMainVerticalBox)

            self.pagesStatus[ci] = 1

        page.show()

    def pagePairTrdLaunch(self):

        capital = int("".join(re.split("\$| |,", self.pagePairTrCapitalEdit.text())))

        investmentStrategies = ["pairstrading", ]

        startTime = self.pagePairTrStartTimeEdit.text()
        endTime = self.pagePairTrEndTimeEdit.text()

        tradeStrategy = None
        if self.pagePairTrTStrRadioButtonVWAP.isChecked(): tradeStrategy = "VWAP"
        if self.pagePairTrTStrRadioButtonTWAP.isChecked(): tradeStrategy = "TWAP"
        if self.pagePairTrTStrRadioButtonNONE.isChecked(): tradeStrategy = "Default"

        positionManagement = None
        if self.pagePairTrPMtdRadioButtonFixedFraction.isChecked(): positionManagement = "FixedFraction"
        if self.pagePairTrPMtdRadioButtonMaximDrawDown.isChecked(): positionManagement = "MaximumDrawDown"

        thread.start_new_thread(self.ATM.launchPairTradingAnalysis, (capital, investmentStrategies, startTime, endTime, tradeStrategy, positionManagement))

    def pagePairTrdLaunchProcess(self):
        self.pagePairTrLaunchButton.setStyleSheet(self.launchWdgtProcesQSS)
        self.pagePairTrLaunchButton.setText("Processing")

    def pagePairTrdLaunchFinish(self):
        self.pagePairTrLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
        self.pagePairTrLaunchButton.setText("Re-Launch")

    def atoTrdPage(self):

        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in monitor page"
        ci = 2
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            if not page.layout() == None:
                while page.layout().count() > 0:
                    page.layout().takeAt(0).widget().setParent(None)

            if page.layout() == None:
                self.pageAutoTrdPageMainVerticalBox = QVBoxLayout()
                self.pageAutoTrdPageMainVerticalBox.setContentsMargins(0, 5, 0, 0)
                page.setLayout(self.pageAutoTrdPageMainVerticalBox)

            self.pageAutoTrdTitleLabel = QLabel("Monitor", page)
            self.pageAutoTrdTitleLabel.setFixedSize(860, 25)
            self.pageAutoTrdTitleLabel.setStyleSheet(self.pageTitleQSS)
            self.pageAutoTrdPageMainVerticalBox.addWidget(self.pageAutoTrdTitleLabel)

            pnlReport = self.ATM.report
            if not len(self.ATM.strategies.strategiesPool.keys()) == 0:
                self.pageAtoTrdPageScroll = QScrollArea(page)
                self.pageAtoTrdPageScroll.setWidgetResizable(True)
                self.pageAtoTrdPageScroll.setBackgroundRole(QPalette.NoRole)
                self.pageAtoTrdPageScroll.setStyleSheet("background: transparent")
                self.pageAtoTrdPageScroll.setFixedSize(860, 635)
                self.pageAtoTrdScrollContentsWidget = QWidget(page)
                scrollContentVBox = QVBoxLayout()
                scrollContentVBox.setAlignment(Qt.AlignTop)
                scrollContentVBox.setContentsMargins(0, 0, 0, 0)

                self.pageAtoTrdSignalPlotLabel = QLabel("Signals Plots", page)
                self.pageAtoTrdSignalPlotLabel.setFixedSize(860, 25)
                self.pageAtoTrdSignalPlotLabel.setStyleSheet(self.pageSubTitleQSS)
                scrollContentVBox.addWidget(self.pageAtoTrdSignalPlotLabel)

                path = "./strategies/image/"
                for file in os.listdir(path):
                    if file.endswith(".png") and file.split('.')[0] in self.ATM.strategies.strategiesPool.keys():
                        pageAtoTrdSignalPlotStrategyLabel = QLabel(file.split('.')[0], page)
                        pageAtoTrdSignalPlotStrategyLabel.setFixedSize(860, 25)
                        pageAtoTrdSignalPlotStrategyLabel.setStyleSheet(self.pageSubSubTitleQSS)
                        scrollContentVBox.addWidget(pageAtoTrdSignalPlotStrategyLabel)

                        widget = QWidget()
                        widget.setFixedHeight(300)
                        hbox = QHBoxLayout()
                        hbox.setContentsMargins(0, 0, 0, 0)
                        hbox.setAlignment(Qt.AlignCenter)
                        lbl = QLabel()
                        pixmap = QPixmap(path + file)
                        scaled_pixmap = pixmap.scaled(860, 330, Qt.KeepAspectRatio)
                        lbl.setPixmap(scaled_pixmap)
                        hbox.addWidget(lbl)
                        widget.setLayout(hbox)
                        scrollContentVBox.addWidget(widget)

                self.pageAtoTrdAllSignalsLabel = QLabel("All Signals", page)
                self.pageAtoTrdAllSignalsLabel.setFixedSize(860, 25)
                self.pageAtoTrdAllSignalsLabel.setStyleSheet(self.pageSubTitleQSS)
                scrollContentVBox.addWidget(self.pageAtoTrdAllSignalsLabel)

                self.pageAtoTrdAllSignalsTitle = QWidget(page)
                self.pageAtoTrdAllSignalsTitle.setFixedSize(860, 25)
                self.pageAtoTrdAllSignalsTitle.setStyleSheet(self.pageSubSubTitleQSS)
                titlesHBox = QHBoxLayout()
                titlesHBox.setContentsMargins(10, 0, 20, 0)
                titlesHBox.addWidget(QLabel("Code"))
                titlesHBox.addWidget(QLabel("Time"))
                titlesHBox.addWidget(QLabel("Action"))
                titlesHBox.addWidget(QLabel("Qnt"))
                titlesHBox.addWidget(QLabel("Price"))
                titlesHBox.addWidget(QLabel("Volumn"))
                titlesHBox.addWidget(QLabel("Strategy"))
                self.pageAtoTrdAllSignalsTitle.setLayout(titlesHBox)
                scrollContentVBox.addWidget(self.pageAtoTrdAllSignalsTitle)

                signals = self.ATM.strategies.signals
                if not len(signals) == 0:
                    for i in xrange(len(signals)):
                        widget = QWidget(page)
                        widget.setFixedHeight(15)
                        widget.setStyleSheet("color:#ffffff")
                        signalHBox = QHBoxLayout()
                        signalHBox.setContentsMargins(20, 0, 10, 0)
                        signalHBox.addWidget(QLabel(signals.ix[i]["Code"]))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Time"])))
                        signalHBox.addWidget(QLabel(signals.ix[i]["Action"]))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Qnt"])))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Price"])))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Volume"])))
                        signalHBox.addWidget(QLabel(signals.ix[i]["Strategy"]))
                        widget.setLayout(signalHBox)
                        scrollContentVBox.addWidget(widget)

                else:
                    widget = QLabel("No Data.")
                    widget.setFixedSize(860, 550)
                    widget.setStyleSheet(self.noDataLabelQSS)
                    widget.setAlignment(Qt.AlignCenter)
                    scrollContentVBox.addWidget(widget)

                self.pageAtoTrdScrollContentsWidget.setLayout(scrollContentVBox)
                self.pageAtoTrdPageScroll.setWidget(self.pageAtoTrdScrollContentsWidget)
                self.pageAutoTrdPageMainVerticalBox.addWidget(self.pageAtoTrdPageScroll)

            else:
                widget = QLabel("No Data.")
                widget.setFixedSize(860, 550)
                widget.setStyleSheet(self.noDataLabelQSS)
                widget.setAlignment(Qt.AlignCenter)
                self.pageAutoTrdPageMainVerticalBox.addWidget(widget)

            self.pagesStatus[ci] = 1

        page.show()

    def trdPnlPage(self):

        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in profit and loss report page"
        ci = 3
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            if not page.layout() == None:
                while page.layout().count() > 0:
                    page.layout().takeAt(0).widget().setParent(None)

            if page.layout() == None:
                self.pageTrdPnlPageMainVerticalBox = QVBoxLayout()
                self.pageTrdPnlPageMainVerticalBox.setContentsMargins(0, 5, 0, 0)
                page.setLayout(self.pageTrdPnlPageMainVerticalBox)

            self.pageTrdHisTitleLabel = QLabel("Profit And Loss Report", page)
            self.pageTrdHisTitleLabel.setFixedSize(860, 25)
            self.pageTrdHisTitleLabel.setStyleSheet(self.pageTitleQSS)
            self.pageTrdPnlPageMainVerticalBox.addWidget(self.pageTrdHisTitleLabel)

            pnlReport = self.ATM.report
            if not len(pnlReport) == 0:

                self.pageTrdHisBookTitles = QWidget(page)
                self.pageTrdHisBookTitles.setFixedSize(860, 25)
                self.pageTrdHisBookTitles.setStyleSheet(self.pageSubTitleQSS)
                titlesHBox = QHBoxLayout()
                titlesHBox.setContentsMargins(10, 0, 20, 0)
                strategy = QLabel("Strategy")
                titlesHBox.addWidget(QLabel("Strategy"))
                titlesHBox.addWidget(QLabel("Realized PnL"))
                titlesHBox.addWidget(QLabel("Return"))
                areturn = QLabel("Annual Return")
                areturn.setFixedWidth(130)
                titlesHBox.addWidget(areturn)
                titlesHBox.addWidget(QLabel("Volatility"))
                titlesHBox.addWidget(QLabel("Sharpe Ratio"))
                mdd = QLabel("Maximum Draw Down")
                mdd.setFixedWidth(155)
                titlesHBox.addWidget(mdd)
                self.pageTrdHisBookTitles.setLayout(titlesHBox)
                self.pageTrdPnlPageMainVerticalBox.addWidget(self.pageTrdHisBookTitles)


                self.pageTrdHisPageScroll = QScrollArea(page)
                self.pageTrdHisPageScroll.setWidgetResizable(True)
                self.pageTrdHisPageScroll.setBackgroundRole(QPalette.NoRole)
                self.pageTrdHisPageScroll.setStyleSheet("background: transparent")
                self.pageTrdHisPageScroll.setFixedSize(860, 600)
                self.pageTrdHisScrollContentsWidget = QWidget(page)
                scrollContentVBox = QVBoxLayout()
                scrollContentVBox.setAlignment(Qt.AlignTop)
                scrollContentVBox.setContentsMargins(0, 0, 0, 0)
                for i in xrange(0, len(pnlReport)):
                    widget = QWidget()
                    widget.setFixedHeight(15)
                    if pnlReport.ix[i]["realized PnL"] > 0: widget.setStyleSheet("color:#fa2020")
                    if pnlReport.ix[i]["realized PnL"] < 0: widget.setStyleSheet("color:#27AE60")
                    hbox   = QHBoxLayout()
                    hbox.setContentsMargins(20, 0, 10, 0)
                    strategy = QLabel(pnlReport.ix[i]["Strategy"])
                    strategy.setFixedWidth(100)
                    hbox.addWidget(strategy)
                    hbox.addWidget(QLabel(str("{0:.2f}".format(pnlReport.ix[i]["realized PnL"]))))
                    hbox.addWidget(QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Return"]))))
                    areturn = QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Annualized Return"])))
                    # hbox.addWidget(QLabel(str("{0:.2f}".format(tradeHistory.ix[i]["QntPer"] * 100))))
                    areturn.setFixedWidth(130)
                    hbox.addWidget(areturn)
                    hbox.addWidget(QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Volatility"]))))
                    hbox.addWidget(QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Sharpe Ratio"]))))
                    mdd = QLabel(str("{0:.6f}".format(pnlReport.ix[i]["MDD"])))
                    mdd.setFixedWidth(155)
                    hbox.addWidget(mdd)
                    widget.setLayout(hbox)
                    scrollContentVBox.addWidget(widget)
                self.pageTrdHisScrollContentsWidget.setLayout(scrollContentVBox)
                self.pageTrdHisPageScroll.setWidget(self.pageTrdHisScrollContentsWidget)
                self.pageTrdPnlPageMainVerticalBox.addWidget(self.pageTrdHisPageScroll)

            else:
                widget = QLabel("No Data.")
                widget.setFixedSize(860, 550)
                widget.setStyleSheet(self.noDataLabelQSS)
                widget.setAlignment(Qt.AlignCenter)
                self.pageTrdPnlPageMainVerticalBox.addWidget(widget)

            self.pagesStatus[ci] = 1

        page.show()

    def trdHisPage(self):

        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in trade history page"
        ci = 4
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            if not page.layout() == None:
                while page.layout().count() > 0:
                    page.layout().takeAt(0).widget().setParent(None)

            if page.layout() == None:
                self.pageTrdHisPageMainVerticalBox = QVBoxLayout()
                self.pageTrdHisPageMainVerticalBox.setContentsMargins(0, 5, 0, 0)
                page.setLayout(self.pageTrdHisPageMainVerticalBox)

            self.pageTrdHisTitleLabel = QLabel("Trade History", page)
            self.pageTrdHisTitleLabel.setFixedSize(860, 25)
            self.pageTrdHisTitleLabel.setStyleSheet(self.pageTitleQSS)
            self.pageTrdHisPageMainVerticalBox.addWidget(self.pageTrdHisTitleLabel)

            tradeHistory = self.ATM.account.queryTradeHistory()

            if not len(tradeHistory) == 0:
                self.pageTrdHisBookTitles = QWidget(page)
                self.pageTrdHisBookTitles.setFixedSize(860, 25)
                self.pageTrdHisBookTitles.setStyleSheet(self.pageSubTitleQSS)
                titlesHBox = QHBoxLayout()
                titlesHBox.setContentsMargins(10, 0, 20, 0)
                code = QLabel("Code")
                code.setFixedWidth(100)
                titlesHBox.addWidget(code)
                time = QLabel("Time")
                time.setFixedWidth(145)
                titlesHBox.addWidget(time)
                titlesHBox.addWidget(QLabel("Action"))
                qnt = QLabel("Qnt")
                qnt.setFixedWidth(50)
                titlesHBox.addWidget(qnt)
                titlesHBox.addWidget(QLabel("Occupy"))
                titlesHBox.addWidget(QLabel("Price"))
                titlesHBox.addWidget(QLabel("PnL"))
                titlesHBox.addWidget(QLabel("Equity"))
                strategy = QLabel("Strategy")
                strategy.setFixedWidth(100)
                titlesHBox.addWidget(strategy)
                self.pageTrdHisBookTitles.setLayout(titlesHBox)
                self.pageTrdHisPageMainVerticalBox.addWidget(self.pageTrdHisBookTitles)

                self.pageTrdHisPageScroll = QScrollArea(page)
                self.pageTrdHisPageScroll.setWidgetResizable(True)
                self.pageTrdHisPageScroll.setBackgroundRole(QPalette.NoRole)
                self.pageTrdHisPageScroll.setStyleSheet("background: transparent")
                self.pageTrdHisPageScroll.setFixedSize(860, 600)
                self.pageTrdHisScrollContentsWidget = QWidget(page)
                scrollContentVBox = QVBoxLayout()
                scrollContentVBox.setContentsMargins(0, 0, 0, 0)
                scrollContentVBox.setAlignment(Qt.AlignTop)
                for i in xrange(0, len(tradeHistory)):
                    widget = QWidget()
                    widget.setFixedHeight(15)
                    if tradeHistory.ix[i]["Action"] == "Short" : widget.setStyleSheet("color:#27AE60")
                    if tradeHistory.ix[i]["Action"] == "SellToCover"  : widget.setStyleSheet("color:#27AE60")
                    if tradeHistory.ix[i]["Action"] == "Long" : widget.setStyleSheet("color:#fa2020")
                    if tradeHistory.ix[i]["Action"] == "BuyToCover" : widget.setStyleSheet("color:#fa2020")
                    hbox   = QHBoxLayout()
                    hbox.setContentsMargins(20, 0, 10, 0)
                    code = QLabel(str(tradeHistory.ix[i]["Code"])); code.setFixedWidth(100); hbox.addWidget(code);
                    time = QLabel(str(tradeHistory.ix[i]["Time"])); time.setFixedWidth(145); hbox.addWidget(time);
                    hbox.addWidget(QLabel(tradeHistory.ix[i]["Action"]))
                    qnt = QLabel(str(tradeHistory.ix[i]["Qnt"])); qnt.setFixedWidth(50); hbox.addWidget(qnt);
                    hbox.addWidget(QLabel(str("{0:.2f}".format(tradeHistory.ix[i]["QntPer"] * 100))+"%"))
                    hbox.addWidget(QLabel(str(round(tradeHistory.ix[i]["Price"]))))
                    pnl = QLabel()
                    if not tradeHistory.ix[i]["PnL"] == "": pnl = QLabel(str(round(float(tradeHistory.ix[i]["PnL"]))));
                    hbox.addWidget(pnl)
                    hbox.addWidget(QLabel(str(round(tradeHistory.ix[i]["Equity"]))))
                    strategy = QLabel(tradeHistory.ix[i]["Strategy"]); strategy.setFixedWidth(100); hbox.addWidget(strategy);
                    widget.setLayout(hbox)
                    scrollContentVBox.addWidget(widget)
                self.pageTrdHisScrollContentsWidget.setLayout(scrollContentVBox)
                self.pageTrdHisPageScroll.setWidget(self.pageTrdHisScrollContentsWidget)
                self.pageTrdHisPageMainVerticalBox.addWidget(self.pageTrdHisPageScroll)

            else:
                widget = QLabel("No Data.")
                widget.setFixedSize(860, 550)
                widget.setStyleSheet(self.noDataLabelQSS)
                widget.setAlignment(Qt.AlignCenter)
                self.pageTrdHisPageMainVerticalBox.addWidget(widget)

            self.pagesStatus[ci] = 1

        page.show()

    def setStyle(self):

        self.setStyleSheet(
            "QToolBar {" +
                "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #203138, stop: 1.0 #000000);" +
                "border-right: 1px solid #065279;" +
                "padding: 5px}" +
            "QToolBar > QToolButton {" +
                "color: #ffffff;" +
                "font-family:'ArialRegular';" +
                "font-size: 14px}" +
            "QToolBar > QToolButton:hover {" +
                "background: qlineargradient(x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 #ffcb06, stop: 1.0 #ff9c28);" +
                "border-radius:3px}" +
            "QLabel {" +
                "font-family:'ArialRegular';" +
                "padding: 10px;}" +
            "QPushButton {" +
                "height: 20px}" +
            "QComboBox {" +
                "border-radius: 1px; " +
                "border-top-right-radius:11px;" +
                "border-bottom-right-radius:11px;" +
                "font-family:'ArialRegular'}" +
            "QComboBox::drop-down {" +
                "width:15px;" +
                "background-color: #ff9c28;" +
                "border-top-right-radius:10px;" +
                "border-bottom-right-radius:10px;}" +
            "QCheckBox {" +
                "color: #ffffff;" +
                "font-family:'ArialRegular'}" +
            "QCheckBox::indicator {" +
                "background-color:#ffffff;" +
                "border-radius: 1px}" +
            "QCheckBox::indicator:checked {" +
                "background-color:#ff9c28}" +
            "QLineEdit {" +
                "background:#ff9c28;" +
                "border-radius:1px}" +
            "QLineEdit:focus {" +
                "border-radius:1px;}" +
            "QRadioButton {color: #ffffff}" +
            "QScrollArea {border:0px; background:transparent}" +
            "QTextEdit {padding-left: 5px; border: 0px; font-family: 'ArialRegular'; font-weight:20; font-size:14px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ec2f4b, stop: 1.0 #85030f);}"
        )

        self.mainBoardQSS       = "padding:0px; background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #203138, stop: 1.0 #000000);"
        self.pagesQSS           = "background:none; padding: 0px"
        self.pageTitleQSS       = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ec2f4b, stop: 1.0 #85030f); color: #ffffff; font-family: 'ArialRegular'; font-weight:20; font-size: 16px"
        self.pageSubTitleQSS    = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #495d76, stop: 1.0 #1f4e7c); color: #dddddd; font-family: 'ArialRegular'; font-weight:20; font-size: 14px"
        self.pageSubSubTitleQSS = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #646464, stop: 1.0 #838683); color: #dddddd; font-family: 'ArialRegular'; font-weight:20; font-size: 14px"
        self.toolButtonHideQSS  = "background:none; font-size: 14px; font-family:'ArialRegular'"
        self.toolButtonFocusQSS = "background:qlineargradient(x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 #ffcb06, stop: 1.0 #ff9c28);border-radius:3px; color:#000000"
        self.itemNameQSS        = "color: #ffffff; font-family: 'ArialRegular'"
        self.comboQSS           = "padding-left:5px;background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eeeeee, stop: 1.0 #dddddd);"
        self.lineEditQSS        = "background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eeeeee, stop: 1.0 #dddddd);border: 0px; padding-left:5px; font-family:'ArialRegular'; font-weight:20; font-size: 14px"
        self.launchWdgtReadyQSS = "background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #004900, stop: 1.0 #033502);border: 0px; color:#ffffff"
        self.launchWdgtProcesQSS= "background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #006602, stop: 1.0 #007b03);border: 0px; color:#ffffff"
        self.tableTitleQSS      = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #495d76, stop: 1.0 #1f4e7c); color: #dddddd; font-family: 'ArialRegular'; font-weight:20; font-size: 14px"
        self.noDataLabelQSS     = "color: #ffffff; font-family: ArialRegular; font-weight: 20; font-size: 14px"
        self.pageTitleFont  = QFont('ArialRegular')
        self.titleFont      = QFont('ArialRegular')
        self.contentFont    = QFont('ArialRegular')

        self.pageTitleColor = "#ffffff"
        self.titleColor     = "#ffffff"
        self.contentColor   = "#ffffff"
Example #35
0
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Semantic similarity'
        self.left = 300
        self.top = 300
        self.width = 425
        self.height = 250
        self.textbox1 = QLineEdit(self)
        self.textbox2 = QLineEdit(self)
        self.textbox3 = QLineEdit(self)
        self.l1 = QLabel(self)
        self.l2 = QLabel(self)
        self.l3 = QLabel(self)
        self.l4 = QLabel(self)
        self.checkbox = QCheckBox(self)
        self.button = QPushButton('Calculate', self)
        self.b1_ssa = QRadioButton(self)
        self.b2_maxb = QRadioButton(self)
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.b1_ssa.move(20, 5)
        self.b1_ssa.setText("SSA")
        self.b1_ssa.setChecked(True)
        self.b2_maxb.move(20, 25)
        self.b2_maxb.setText("Sim Max B")

        self.l1.move(20, 53)
        self.l1.setText("word 1: ")
        self.textbox1.move(120, 60)
        self.textbox1.resize(280, 20)

        self.l2.move(20, 83)
        self.l2.setText("word 2: ")
        self.textbox2.move(120, 90)
        self.textbox2.resize(280, 20)

        self.l3.move(20, 113)
        self.l3.setText("draw graph")

        self.checkbox.move(120, 113)
        self.button.move(20, 163)

        self.l4.move(20, 203)
        self.l4.setText("result:")
        self.textbox3.move(120, 210)
        self.textbox3.resize(280, 20)
        self.textbox3.setReadOnly(True)

        self.button.clicked.connect(self.on_click)
        self.show()

    @pyqtSlot()
    def on_click(self):
        word1 = self.textbox1.text()
        word2 = self.textbox2.text()
        if self.b1_ssa.isChecked():
            g, dist, path = calculate_similarity(word1, word2)
            self.textbox3.setText(str(np.round(dist * 10, 2)))
            if self.checkbox.isChecked():
                draw_graph(g, word1, word2, path)
        elif self.b2_maxb.isChecked():
            _, _, sim, nx_graph, _, path = sim_max_b(word1, word2)
            self.textbox3.setText(str(np.round(sim * 10, 2)))
            if self.checkbox.isChecked():
                draw_graph_sim(nx_graph, path, word1, word2, sim)
Example #36
0
class MainWindow(QMainWindow):
    receiveUpdateSignal = pyqtSignal(str)
    errorSignal = pyqtSignal(str)
    isDetectSerialPort = False
    receiveCount = 0
    sendCount = 0
    isScheduledSending = False
    DataPath = "./"
    isHideSettings = False
    isHideFunctinal = False
    app = None

    def __init__(self, app):
        super().__init__()
        self.app = app
        pathDirList = sys.argv[0].replace("\\", "/").split("/")
        pathDirList.pop()
        self.DataPath = os.path.abspath("/".join(str(i) for i in pathDirList))
        if not os.path.exists(self.DataPath + "/" + parameters.strDataDirName):
            pathDirList.pop()
            self.DataPath = os.path.abspath("/".join(
                str(i) for i in pathDirList))
        self.DataPath = (self.DataPath + "/" +
                         parameters.strDataDirName).replace("\\", "/")
        self.initWindow()
        self.initTool()
        self.initEvent()
        self.programStartGetSavedParameters()
        return

    def __del__(self):
        return

    def initTool(self):
        self.com = serial.Serial()
        return

    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        self.settingWidget.setProperty("class", "settingWidget")
        self.receiveSendWidget = QSplitter(Qt.Vertical)
        self.functionalWiget = QWidget()
        settingLayout = QVBoxLayout()
        sendReceiveLayout = QVBoxLayout()
        sendFunctionalLayout = QVBoxLayout()
        mainLayout = QHBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        self.receiveSendWidget.setLayout(sendReceiveLayout)
        self.functionalWiget.setLayout(sendFunctionalLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.addWidget(self.receiveSendWidget)
        mainLayout.addWidget(self.functionalWiget)
        mainLayout.setStretch(0, 2)
        mainLayout.setStretch(1, 6)
        mainLayout.setStretch(2, 2)
        menuLayout = QHBoxLayout()
        mainWidget.setLayout(mainLayout)
        frameLayout.addLayout(menuLayout)
        frameLayout.addWidget(mainWidget)
        frameWidget.setLayout(frameLayout)
        self.setCentralWidget(frameWidget)

        # option layout
        self.settingsButton = QPushButton()
        self.skinButton = QPushButton("")
        self.aboutButton = QPushButton()
        self.functionalButton = QPushButton()
        self.settingsButton.setProperty("class", "menuItem1")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.functionalButton.setProperty("class", "menuItem4")
        self.settingsButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        self.functionalButton.setObjectName("menuItem")
        menuLayout.addWidget(self.settingsButton)
        menuLayout.addWidget(self.skinButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)
        menuLayout.addWidget(self.functionalButton)

        # widgets receive and send area
        self.receiveArea = QTextEdit()
        self.sendArea = QTextEdit()
        self.clearReceiveButtion = QPushButton(parameters.strClearReceive)
        self.sendButtion = QPushButton(parameters.strSend)
        self.sendHistory = ComboBox()
        sendWidget = QWidget()
        sendAreaWidgetsLayout = QHBoxLayout()
        sendWidget.setLayout(sendAreaWidgetsLayout)
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.clearReceiveButtion)
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.sendButtion)
        sendAreaWidgetsLayout.addWidget(self.sendArea)
        sendAreaWidgetsLayout.addLayout(buttonLayout)
        sendReceiveLayout.addWidget(self.receiveArea)
        sendReceiveLayout.addWidget(sendWidget)
        sendReceiveLayout.addWidget(self.sendHistory)
        sendReceiveLayout.setStretch(0, 7)
        sendReceiveLayout.setStretch(1, 2)
        sendReceiveLayout.setStretch(2, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(parameters.strSerialSettings)
        serialSettingsLayout = QGridLayout()
        serialReceiveSettingsLayout = QGridLayout()
        serialSendSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(parameters.strSerialPort)
        serailBaudrateLabel = QLabel(parameters.strSerialBaudrate)
        serailBytesLabel = QLabel(parameters.strSerialBytes)
        serailParityLabel = QLabel(parameters.strSerialParity)
        serailStopbitsLabel = QLabel(parameters.strSerialStopbits)
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("9600")
        self.serailBaudrateCombobox.addItem("19200")
        self.serailBaudrateCombobox.addItem("38400")
        self.serailBaudrateCombobox.addItem("57600")
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.setCurrentIndex(4)
        self.serailBaudrateCombobox.setEditable(True)
        self.serailBytesCombobox = ComboBox()
        self.serailBytesCombobox.addItem("5")
        self.serailBytesCombobox.addItem("6")
        self.serailBytesCombobox.addItem("7")
        self.serailBytesCombobox.addItem("8")
        self.serailBytesCombobox.setCurrentIndex(3)
        self.serailParityCombobox = ComboBox()
        self.serailParityCombobox.addItem("None")
        self.serailParityCombobox.addItem("Odd")
        self.serailParityCombobox.addItem("Even")
        self.serailParityCombobox.addItem("Mark")
        self.serailParityCombobox.addItem("Space")
        self.serailParityCombobox.setCurrentIndex(0)
        self.serailStopbitsCombobox = ComboBox()
        self.serailStopbitsCombobox.addItem("1")
        self.serailStopbitsCombobox.addItem("1.5")
        self.serailStopbitsCombobox.addItem("2")
        self.serailStopbitsCombobox.setCurrentIndex(0)
        self.serialOpenCloseButton = QPushButton(parameters.strOpen)
        serialSettingsLayout.addWidget(serialPortLabek, 0, 0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(serailBytesLabel, 2, 0)
        serialSettingsLayout.addWidget(serailParityLabel, 3, 0)
        serialSettingsLayout.addWidget(serailStopbitsLabel, 4, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsLayout.addWidget(self.serailBytesCombobox, 2, 1)
        serialSettingsLayout.addWidget(self.serailParityCombobox, 3, 1)
        serialSettingsLayout.addWidget(self.serailStopbitsCombobox, 4, 1)
        serialSettingsLayout.addWidget(self.serialOpenCloseButton, 5, 0, 1, 2)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # serial receive settings
        serialReceiveSettingsGroupBox = QGroupBox(
            parameters.strSerialReceiveSettings)
        self.receiveSettingsAscii = QRadioButton(parameters.strAscii)
        self.receiveSettingsHex = QRadioButton(parameters.strHex)
        self.receiveSettingsAscii.setChecked(True)
        self.receiveSettingsAutoLinefeed = QCheckBox(
            parameters.strAutoLinefeed)
        self.receiveSettingsAutoLinefeedTime = QLineEdit(
            parameters.strAutoLinefeedTime)
        self.receiveSettingsAutoLinefeed.setMaximumWidth(75)
        self.receiveSettingsAutoLinefeedTime.setMaximumWidth(75)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAscii, 1, 0,
                                              1, 1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsHex, 1, 1, 1,
                                              1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAutoLinefeed,
                                              2, 0, 1, 1)
        serialReceiveSettingsLayout.addWidget(
            self.receiveSettingsAutoLinefeedTime, 2, 1, 1, 1)
        serialReceiveSettingsGroupBox.setLayout(serialReceiveSettingsLayout)
        settingLayout.addWidget(serialReceiveSettingsGroupBox)

        # serial send settings
        serialSendSettingsGroupBox = QGroupBox(
            parameters.strSerialSendSettings)
        self.sendSettingsAscii = QRadioButton(parameters.strAscii)
        self.sendSettingsHex = QRadioButton(parameters.strHex)
        self.sendSettingsAscii.setChecked(True)
        self.sendSettingsScheduledCheckBox = QCheckBox(parameters.strScheduled)
        self.sendSettingsScheduled = QLineEdit(parameters.strScheduledTime)
        self.sendSettingsScheduledCheckBox.setMaximumWidth(75)
        self.sendSettingsScheduled.setMaximumWidth(75)
        self.sendSettingsCFLF = QCheckBox(parameters.strCRLF)
        self.sendSettingsCFLF.setChecked(False)
        serialSendSettingsLayout.addWidget(self.sendSettingsAscii, 1, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsHex, 1, 1, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduledCheckBox,
                                           2, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduled, 2, 1, 1,
                                           1)
        serialSendSettingsLayout.addWidget(self.sendSettingsCFLF, 3, 0, 1, 2)
        serialSendSettingsGroupBox.setLayout(serialSendSettingsLayout)
        settingLayout.addWidget(serialSendSettingsGroupBox)

        settingLayout.setStretch(0, 5)
        settingLayout.setStretch(1, 2.5)
        settingLayout.setStretch(2, 2.5)

        # right functional layout
        self.addButton = QPushButton(parameters.strAdd)
        functionalGroupBox = QGroupBox(parameters.strFunctionalSend)
        functionalGridLayout = QGridLayout()
        functionalGridLayout.addWidget(self.addButton, 0, 1)
        functionalGroupBox.setLayout(functionalGridLayout)
        sendFunctionalLayout.addWidget(functionalGroupBox)

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                     ("#008200", parameters.strReady))
        self.statusBarSendCount = QLabel(parameters.strSend + "(bytes): " +
                                         "0")
        self.statusBarReceiveCount = QLabel(parameters.strReceive +
                                            "(bytes): " + "0")
        self.statusBar().addWidget(self.statusBarStauts)
        self.statusBar().addWidget(self.statusBarSendCount, 2)
        self.statusBar().addWidget(self.statusBarReceiveCount, 3)
        # self.statusBar()

        self.resize(800, 500)
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName + " V" +
                            str(helpAbout.versionMajor) + "." +
                            str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:" + self.DataPath + "/" + parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath + "/" + parameters.appIcon),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                "comtool")
        self.show()
        return

    def initEvent(self):
        self.serialOpenCloseButton.clicked.connect(self.openCloseSerial)
        self.sendButtion.clicked.connect(self.sendData)
        self.receiveUpdateSignal.connect(self.updateReceivedDataDisplay)
        self.clearReceiveButtion.clicked.connect(self.clearReceiveBuffer)
        self.serialPortCombobox.clicked.connect(self.portComboboxClicked)
        self.sendSettingsHex.clicked.connect(self.onSendSettingsHexClicked)
        self.sendSettingsAscii.clicked.connect(self.onSendSettingsAsciiClicked)
        self.errorSignal.connect(self.errorHint)
        self.sendHistory.currentIndexChanged.connect(
            self.sendHistoryIndexChanged)
        self.settingsButton.clicked.connect(self.showHideSettings)
        self.skinButton.clicked.connect(self.skinChange)
        self.aboutButton.clicked.connect(self.showAbout)
        self.addButton.clicked.connect(self.functionAdd)
        self.functionalButton.clicked.connect(self.showHideFunctional)
        return

    def openCloseSerialProcess(self):
        try:
            if self.com.is_open:
                self.com.close()
                self.serialOpenCloseButton.setText(parameters.strOpen)
                self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                             ("#f31414", parameters.strClosed))
                self.receiveProgressStop = True
                self.serialPortCombobox.setDisabled(False)
                self.serailBaudrateCombobox.setDisabled(False)
                self.serailParityCombobox.setDisabled(False)
                self.serailStopbitsCombobox.setDisabled(False)
                self.serailBytesCombobox.setDisabled(False)
                self.programExitSaveParameters()
            else:
                try:
                    self.com.baudrate = int(
                        self.serailBaudrateCombobox.currentText())
                    self.com.port = self.serialPortCombobox.currentText(
                    ).split(" ")[0]
                    self.com.bytesize = int(
                        self.serailBytesCombobox.currentText())
                    self.com.parity = self.serailParityCombobox.currentText(
                    )[0]
                    self.com.stopbits = float(
                        self.serailStopbitsCombobox.currentText())
                    self.com.timeout = None
                    print(self.com)
                    self.serialOpenCloseButton.setDisabled(True)
                    self.com.open()
                    self.serialOpenCloseButton.setText(parameters.strClose)
                    self.statusBarStauts.setText(
                        "<font color=%s>%s</font>" %
                        ("#008200", parameters.strReady))
                    self.serialPortCombobox.setDisabled(True)
                    self.serailBaudrateCombobox.setDisabled(True)
                    self.serailParityCombobox.setDisabled(True)
                    self.serailStopbitsCombobox.setDisabled(True)
                    self.serailBytesCombobox.setDisabled(True)
                    self.serialOpenCloseButton.setDisabled(False)
                    receiveProcess = threading.Thread(target=self.receiveData)
                    receiveProcess.setDaemon(True)
                    receiveProcess.start()
                except Exception as e:
                    self.com.close()
                    self.receiveProgressStop = True
                    self.errorSignal.emit(parameters.strOpenFailed + "\n" +
                                          str(e))
                    self.serialOpenCloseButton.setDisabled(False)
        except Exception:
            pass
        return

    def openCloseSerial(self):
        t = threading.Thread(target=self.openCloseSerialProcess)
        t.setDaemon(True)
        t.start()
        return

    def portComboboxClicked(self):
        self.detectSerialPort()
        return

    def getSendData(self):
        data = self.sendArea.toPlainText()
        if self.sendSettingsCFLF.isChecked():
            data = data.replace("\n", "\r\n")
        if self.sendSettingsHex.isChecked():
            if self.sendSettingsCFLF.isChecked():
                data = data.replace("\r\n", " ")
            else:
                data = data.replace("\n", " ")
            data = self.hexStringB2Hex(data)
            if data == -1:
                self.errorSignal.emit(parameters.strWriteFormatError)
                return -1
        else:
            data = data.encode()
        return data

    def sendData(self):
        try:
            if self.com.is_open:
                data = self.getSendData()
                if data == -1:
                    return
                print(self.sendArea.toPlainText())
                print("send:", data)
                self.sendCount += len(data)
                self.com.write(data)
                data = self.sendArea.toPlainText()
                self.sendHistoryFindDelete(data)
                self.sendHistory.insertItem(0, data)
                self.sendHistory.setCurrentIndex(0)
                self.receiveUpdateSignal.emit("")
                # scheduled send
                if self.sendSettingsScheduledCheckBox.isChecked():
                    if not self.isScheduledSending:
                        t = threading.Thread(target=self.scheduledSend)
                        t.setDaemon(True)
                        t.start()
        except Exception as e:
            self.errorSignal.emit(parameters.strWriteError)
            print(e)
        return

    def scheduledSend(self):
        self.isScheduledSending = True
        while self.sendSettingsScheduledCheckBox.isChecked():
            self.sendData()
            try:
                time.sleep(
                    int(self.sendSettingsScheduled.text().strip()) / 1000)
            except Exception:
                self.errorSignal.emit(parameters.strTimeFormatError)
        self.isScheduledSending = False
        return

    def receiveData(self):
        self.receiveProgressStop = False
        self.timeLastReceive = 0
        while (not self.receiveProgressStop):
            try:
                length = self.com.in_waiting
                if length > 0:
                    bytes = self.com.read(length)
                    self.receiveCount += len(bytes)
                    if self.receiveSettingsHex.isChecked():
                        strReceived = self.asciiB2HexString(bytes)
                        self.receiveUpdateSignal.emit(strReceived)
                    else:
                        self.receiveUpdateSignal.emit(
                            bytes.decode("utf-8", "ignore"))
                    if self.receiveSettingsAutoLinefeed.isChecked():
                        if time.time() - self.timeLastReceive > int(
                                self.receiveSettingsAutoLinefeedTime.text(
                                )) / 1000:
                            if self.sendSettingsCFLF.isChecked():
                                self.receiveUpdateSignal.emit("\r\n")
                            else:
                                self.receiveUpdateSignal.emit("\n")
                            self.timeLastReceive = time.time()
            except Exception as e:
                print("receiveData error")
                if self.com.is_open and not self.serialPortCombobox.isEnabled(
                ):
                    self.openCloseSerial()
                    self.serialPortCombobox.clear()
                    self.detectSerialPort()
                print(e)
            time.sleep(0.009)
        return

    def updateReceivedDataDisplay(self, str):
        if str != "":
            curScrollValue = self.receiveArea.verticalScrollBar().value()
            self.receiveArea.moveCursor(QTextCursor.End)
            endScrollValue = self.receiveArea.verticalScrollBar().value()
            self.receiveArea.insertPlainText(str)
            if curScrollValue < endScrollValue:
                self.receiveArea.verticalScrollBar().setValue(curScrollValue)
            else:
                self.receiveArea.moveCursor(QTextCursor.End)
        self.statusBarSendCount.setText("%s(bytes):%d" %
                                        (parameters.strSend, self.sendCount))
        self.statusBarReceiveCount.setText(
            "%s(bytes):%d" % (parameters.strReceive, self.receiveCount))
        return

    def onSendSettingsHexClicked(self):

        data = self.sendArea.toPlainText().replace("\n", "\r\n")
        data = self.asciiB2HexString(data.encode())
        self.sendArea.clear()
        self.sendArea.insertPlainText(data)
        return

    def onSendSettingsAsciiClicked(self):
        try:
            data = self.sendArea.toPlainText().replace("\n", " ").strip()
            self.sendArea.clear()
            if data != "":
                data = self.hexStringB2Hex(data).decode('utf-8', 'ignore')
                self.sendArea.insertPlainText(data)
        except Exception as e:
            QMessageBox.information(self, parameters.strWriteFormatError,
                                    parameters.strWriteFormatError)
        return

    def sendHistoryIndexChanged(self):
        self.sendArea.clear()
        self.sendArea.insertPlainText(self.sendHistory.currentText())
        return

    def clearReceiveBuffer(self):
        self.receiveArea.clear()
        self.receiveCount = 0
        self.sendCount = 0
        self.receiveUpdateSignal.emit(None)
        return

    def MoveToCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        return

    def errorHint(self, str):
        QMessageBox.information(self, str, str)
        return

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Sure To Quit?',
                                     "Are you sure to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.com.close()
            self.receiveProgressStop = True
            self.programExitSaveParameters()
            event.accept()
        else:
            event.ignore()

    def findSerialPort(self):
        self.port_list = list(serial.tools.list_ports.comports())
        return self.port_list

    def portChanged(self):
        self.serialPortCombobox.setCurrentIndex(0)
        self.serialPortCombobox.setToolTip(str(self.portList[0]))

    def detectSerialPort(self):
        if not self.isDetectSerialPort:
            self.isDetectSerialPort = True
            t = threading.Thread(target=self.detectSerialPortProcess)
            t.setDaemon(True)
            t.start()

    def detectSerialPortProcess(self):
        self.serialPortCombobox.clear()
        while (1):
            portList = self.findSerialPort()
            for i in portList:
                self.serialPortCombobox.addItem(str(i[0]) + " " + str(i[1]))
            if len(portList) > 0:
                self.serialPortCombobox.setCurrentIndex(0)
                self.serialPortCombobox.setToolTip(str(portList[0]))
                break
            time.sleep(1)
        self.isDetectSerialPort = False
        return

    def sendHistoryFindDelete(self, str):
        self.sendHistory.removeItem(self.sendHistory.findText(str))
        return

    def test(self):
        print("test")
        return

    def asciiB2HexString(self, strB):
        strHex = binascii.b2a_hex(strB).upper()
        return re.sub(r"(?<=\w)(?=(?:\w\w)+$)", " ", strHex.decode()) + " "

    def hexStringB2Hex(self, hexString):
        dataList = hexString.split(" ")
        j = 0
        for i in dataList:
            if len(i) > 2:
                return -1
            elif len(i) == 1:
                dataList[j] = "0" + i
            j += 1
        data = "".join(dataList)
        try:
            data = bytes.fromhex(data)
        except Exception:
            return -1
        print(data)
        return data

    def programExitSaveParameters(self):
        paramObj = parameters.ParametersToSave()
        paramObj.baudRate = self.serailBaudrateCombobox.currentIndex()
        paramObj.dataBytes = self.serailBytesCombobox.currentIndex()
        paramObj.parity = self.serailParityCombobox.currentIndex()
        paramObj.stopBits = self.serailStopbitsCombobox.currentIndex()
        paramObj.skin = self.param.skin
        if self.receiveSettingsHex.isChecked():
            paramObj.receiveAscii = False
        if not self.receiveSettingsAutoLinefeed.isChecked():
            paramObj.receiveAutoLinefeed = False
        else:
            paramObj.receiveAutoLinefeed = True
        paramObj.receiveAutoLindefeedTime = self.receiveSettingsAutoLinefeedTime.text(
        )
        if self.sendSettingsHex.isChecked():
            paramObj.sendAscii = False
        if not self.sendSettingsScheduledCheckBox.isChecked():
            paramObj.sendScheduled = False
        paramObj.sendScheduledTime = self.sendSettingsScheduled.text()
        if not self.sendSettingsCFLF.isChecked():
            paramObj.useCRLF = False
        paramObj.sendHistoryList.clear()
        for i in range(0, self.sendHistory.count()):
            paramObj.sendHistoryList.append(self.sendHistory.itemText(i))
        f = open("settings.config", "wb")
        f.truncate()
        pickle.dump(paramObj, f)
        pickle.dump(paramObj.sendHistoryList, f)
        f.close()
        return

    def programStartGetSavedParameters(self):
        paramObj = parameters.ParametersToSave()
        try:
            f = open("settings.config", "rb")
            paramObj = pickle.load(f)
            paramObj.sendHistoryList = pickle.load(f)
            f.close()
        except Exception as e:
            f = open("settings.config", "wb")
            f.close()
        self.serailBaudrateCombobox.setCurrentIndex(paramObj.baudRate)
        self.serailBytesCombobox.setCurrentIndex(paramObj.dataBytes)
        self.serailParityCombobox.setCurrentIndex(paramObj.parity)
        self.serailStopbitsCombobox.setCurrentIndex(paramObj.stopBits)
        if paramObj.receiveAscii == False:
            self.receiveSettingsHex.setChecked(True)
        if paramObj.receiveAutoLinefeed == False:
            self.receiveSettingsAutoLinefeed.setChecked(False)
        else:
            self.receiveSettingsAutoLinefeed.setChecked(True)
        self.receiveSettingsAutoLinefeedTime.setText(
            paramObj.receiveAutoLindefeedTime)
        if paramObj.sendAscii == False:
            self.sendSettingsHex.setChecked(True)
        if paramObj.sendScheduled == False:
            self.sendSettingsScheduledCheckBox.setChecked(False)
        else:
            self.sendSettingsScheduledCheckBox.setChecked(True)
        self.sendSettingsScheduled.setText(paramObj.sendScheduledTime)
        if paramObj.useCRLF == False:
            self.sendSettingsCFLF.setChecked(False)
        else:
            self.sendSettingsCFLF.setChecked(True)
        for i in range(0, len(paramObj.sendHistoryList)):
            str = paramObj.sendHistoryList[i]
            self.sendHistory.addItem(str)
        self.param = paramObj
        return

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Control:
            self.keyControlPressed = True
        elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            if self.keyControlPressed:
                self.sendData()
        elif event.key() == Qt.Key_L:
            if self.keyControlPressed:
                self.sendArea.clear()
        elif event.key() == Qt.Key_K:
            if self.keyControlPressed:
                self.receiveArea.clear()
        return

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Control:
            self.keyControlPressed = False
        return

    def functionAdd(self):
        QMessageBox.information(self, "On the way", "On the way")
        return

    def showHideSettings(self):
        if self.isHideSettings:
            self.showSettings()
            self.isHideSettings = False
        else:
            self.hideSettings()
            self.isHideSettings = True
        return

    def showSettings(self):
        self.settingWidget.show()
        self.settingsButton.setStyleSheet(
            parameters.strStyleShowHideButtonLeft.replace(
                "$DataPath", self.DataPath))
        return

    def hideSettings(self):
        self.settingWidget.hide()
        self.settingsButton.setStyleSheet(
            parameters.strStyleShowHideButtonRight.replace(
                "$DataPath", self.DataPath))
        return

    def showHideFunctional(self):
        if self.isHideFunctinal:
            self.showFunctional()
            self.isHideFunctinal = False
        else:
            self.hideFunctional()
            self.isHideFunctinal = True
        return

    def showFunctional(self):
        self.functionalWiget.show()
        self.functionalButton.setStyleSheet(
            parameters.strStyleShowHideButtonRight.replace(
                "$DataPath", self.DataPath))
        return

    def hideFunctional(self):
        self.functionalWiget.hide()
        self.functionalButton.setStyleSheet(
            parameters.strStyleShowHideButtonLeft.replace(
                "$DataPath", self.DataPath))
        return

    def skinChange(self):
        if self.param.skin == 1:  # light
            file = open(self.DataPath + '/assets/qss/style-dark.qss', "r")
            self.param.skin = 2
        else:  # elif self.param.skin == 2: # dark
            file = open(self.DataPath + '/assets/qss/style.qss', "r")
            self.param.skin = 1
        self.app.setStyleSheet(file.read().replace("$DataPath", self.DataPath))
        return

    def showAbout(self):
        QMessageBox.information(
            self, "About",
            "<h1 style='color:#f75a5a';margin=10px;>" + parameters.appName +
            '</h1><br><b style="color:#08c7a1;margin = 5px;">V' +
            str(helpAbout.versionMajor) + "." + str(helpAbout.versionMinor) +
            "." + str(helpAbout.versionDev) + "</b><br><br>" + helpAbout.date +
            "<br><br>" + helpAbout.strAbout())
        return

    def action1(self):
        print("action1")
        return

    def autoUpdateDetect(self):
        auto = autoUpdate.AutoUpdate()
        if auto.detectNewVersion():
            auto.OpenBrowser()

    def openDevManagement(self):
        os.system('start devmgmt.msc')
Example #37
0
class Window(QMainWindow):
    """Main Window."""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        self.setWindowTitle('Password Genearator')
        self.setGeometry(10, 10, 1000, 800)
        self._createMenu()
        self._createStatusBar()

    def _createMenu(self):
        """ Create menubar. """

        file_menu = self.menuBar().addMenu("File")

        # File Menu - New
        new_action = QAction("&New", self)
        new_action.setStatusTip('Create a new password.')
        new_action.setShortcut('Ctrl+Shift+N')
        new_action.triggered.connect(self.file_new)
        file_menu.addAction(new_action)

        # File Menu - Open
        open_action = QAction("Open", self)
        open_action.setStatusTip('Open password file.')
        open_action.setShortcut('Ctrl+Shift+O')
        open_action.triggered.connect(self.file_open)
        file_menu.addAction(open_action)

        # File Menu - Save
        save_action = QAction("&Save", self)
        save_action.setStatusTip('Save password file.')
        save_action.setShortcut('Ctrl+Shift+S')
        save_action.triggered.connect(self.file_save)
        file_menu.addAction(save_action)

        # File Menu - Delete
        delete_action = QAction("Delete", self)
        delete_action.setStatusTip('Delete password.')
        delete_action.triggered.connect(self.file_delete)
        file_menu.addAction(delete_action)

        file_menu.addSeparator()

        # File Menu - Exit
        exit_action = QAction("&Exit", self)
        exit_action.setStatusTip('Exit application.')
        exit_action.setShortcut('Ctrl+Shift+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        # About Menu - Help
        about_action = QAction("About", self)
        about_action.setStatusTip('Brief summary about app.')
        about_action.triggered.connect(self.about_help)
        help_menu = self.menuBar().addMenu("Help")
        help_menu.addAction(about_action)

    def _createStatusBar(self):
        """ Create Status Bar """
        status = QStatusBar()
        status.showMessage("Status Bar Area")
        self.setStatusBar(status)

    def file_new(self):
        """ Display fields to capture user data to generate a password """
        # Text box to capture length of password being requested
        self.size_textbox = QLineEdit(self)
        self.size_textbox.move(100, 50)
        self.size_textbox.show()

        # Label for text to capture password length
        self.size_label = QLabel('Password Length', self)
        self.size_label.resize(self.size_label.minimumSizeHint())
        self.size_label.move(210, 50)
        self.size_label.show()

        # Radio button to request PIN
        self.pin_radiobtn = QRadioButton('PIN', self)
        self.pin_radiobtn.resize(self.pin_radiobtn.minimumSizeHint())
        self.pin_radiobtn.move(100, 100)
        self.pin_radiobtn.show()

        # Radio button to request alphanumeric password
        self.alphanum_radiobtn = QRadioButton('Alphanumeric', self)
        self.alphanum_radiobtn.resize(self.alphanum_radiobtn.minimumSizeHint())
        self.alphanum_radiobtn.move(100, 150)
        self.alphanum_radiobtn.show()
        ''' Radio button to request alphanumeric password w/ special characters
        password. '''
        self.special_radiobtn = QRadioButton(
            'Alphanumeric w/ special characters', self)
        self.special_radiobtn.resize(self.special_radiobtn.minimumSizeHint())
        self.special_radiobtn.move(100, 200)
        self.special_radiobtn.show()

        # Button to generate the password when clicked
        self.btn = QPushButton('Generate Password', self)
        self.btn.resize(self.btn.minimumSizeHint())
        self.btn.clicked.connect(self.on_generate_btn_clicked)
        self.btn.move(250, 275)
        self.btn.show()

        # Non-editable text box to display password or error.
        # This box is hide until password or error is returned.
        self.generated_pwd = QLineEdit(self)
        self.generated_pwd.move(60, 325)
        self.generated_pwd.setEnabled(False)
        self.generated_pwd.resize(700, 32)
        self.generated_pwd.hide()

    def file_open(self):
        """ Open file containing passwords. """
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fname = QFileDialog.getOpenFileName(
            self,
            'QFileDialog.getOpenFileNames()',
            '/home/mfsd1809/Dev/FullStackWebDeveloper/GUI/pass-gen/Files',
            'JSON Files (*.json)',
            options=options)
        if fname[0]:
            f = open(fname[0], 'r')

            with f:
                data = json.load(f)
                self.pw = PasswordWindow()
                self.app_label = QLabel(self.pw)
                self.app_label.setText('Application - Password')
                self.app_label.resize(self.app_label.minimumSizeHint())
                self.app_label.move(20, 20)
                self.b = QPlainTextEdit(self.pw)
                count = 1
                for app, pwd in data.items():
                    self.b.insertPlainText(
                        str(count) + '. ' + app + ' - ' + pwd + '\n')
                    count = count + 1
                self.b.setReadOnly(True)
                self.b.move(20, 50)
                self.b.resize(850, 250)
                self.pw.move(100, 150)
                self.pw.show()

    def file_save(self):
        """ Save application name and password to passwords file """
        app, okPressed = QInputDialog.getText(self, "Application Name",
                                              "Enter App Name:",
                                              QLineEdit.Normal, "")
        app = app.lower().strip()
        try:
            if okPressed and app != '' and self.generated_pwd.text() != '':
                # Read JSON file
                with open(
                        '/home/mfsd1809/Dev/FullStackWebDeveloper/GUI/pass-gen/'
                        'Files/passwords.json') as r_file:
                    data = json.load(r_file)
                    # print(json.dumps(data, indent=4))

                # Add/Update JSON file
                data.update({app: self.generated_pwd.text()})

                # Write update to JSON file
                with open(
                        '/home/mfsd1809/Dev/FullStackWebDeveloper/GUI/pass-gen/'
                        'Files/passwords.json', 'w') as w_file:
                    json.dump(data, w_file, indent=4)

                self.get_msg_box(QMessageBox.Information, 'Success',
                                 'Password saved.')
            elif (okPressed and app == ''):
                self.get_msg_box(QMessageBox.Warning, 'Insufficient Data',
                                 'You did not enter an app name.')
        except Exception:
            self.get_msg_box(QMessageBox.Warning, 'Insufficient Data',
                             'No password provided for the app you entered.')

    def file_delete(self):
        """ Delete application name and password from passwords file """
        app, okPressed = QInputDialog.getText(self, "Application Name",
                                              "Enter App Name:",
                                              QLineEdit.Normal, "")
        app = app.lower().strip()
        try:
            if okPressed and app != '':
                # Read JSON file
                with open(
                        '/home/mfsd1809/Dev/FullStackWebDeveloper/GUI/pass-gen/'
                        'Files/passwords.json') as r_file:
                    data = json.load(r_file)
                    # print(json.dumps(data, indent=4))

                # Delete app/password from JSON file
                del data[app]

                # Write update to JSON file
                with open(
                        '/home/mfsd1809/Dev/FullStackWebDeveloper/GUI/pass-gen/'
                        'Files/passwords.json', 'w') as w_file:
                    json.dump(data, w_file, indent=4)

                self.get_msg_box(QMessageBox.Information, 'Success',
                                 'Password deleted.')
            elif (okPressed and app == ''):
                self.get_msg_box(QMessageBox.Warning, 'Insufficient Data',
                                 'You did not enter an app name.')

        except Exception:
            self.get_msg_box(QMessageBox.Warning, 'Insufficient Data',
                             'No password provided for the app you entered.')

    def about_help(self):
        """ Display information about application when Help-->About menu item
            is clicked """
        self.get_msg_box(
            QMessageBox.Information, 'About',
            'This application was created using Python and '
            'PyQt5.  It is used to generate a password based '
            'on the user input of length and selected type.')

    def get_msg_box(self, icon, title, msg):
        """ Message box"""
        self.mb = QMessageBox(self)
        self.mb.setIcon(icon)
        self.mb.setWindowTitle(title)
        self.mb.setText(msg)
        self.mb.setStandardButtons(QMessageBox.Ok)
        self.mb.show()

    def get_pin(self, size):
        """Generate random password, numbers only."""
        # Check if input an integer
        if (isinstance(size, int)):
            # Check if input is positive
            if (size < 0):
                self.get_response('You did not enter a positive integer!',
                                  'error')
            elif (size < 4):
                self.get_response('The number must be greater or equal to 4.',
                                  'error')
            else:
                digits = string.digits
                self.get_response(
                    ''.join(random.choice(digits) for i in range(size)),
                    'success')
        else:
            self.get_response('You did NOT enter an integer!', 'error')

    def get_alphanumeric_password(self, size):
        """ Generate random password, alphanumeric only """
        # Check if input an integer
        if (isinstance(size, int)):
            # Check if input is positive
            if (size < 0):
                self.get_response('You did not enter a positive integer!',
                                  'error')
            elif (size < 8):
                self.get_response('The number must be greater or equal to 8.',
                                  'error')
            else:
                letters_and_digits = string.ascii_letters + string.digits
                self.get_response(
                    ''.join(
                        random.choice(letters_and_digits)
                        for i in range(size)), 'success')
        else:
            self.get_response('You did NOT enter an integer!', 'error')

    def get_alphanumeric_with_symbols_password(self, size):
        """ Generate random password, alphanumeric with symbols included """
        # Check if input an integer
        if (isinstance(size, int)):
            # Check if input is positive
            if (size < 0):
                self.get_response('You did not enter a positive integer!',
                                  'error')
            elif (size < 8):
                self.get_response('The number must be greater or equal to 8.',
                                  'error')
            else:
                letters_digits_symbols = (string.ascii_letters +
                                          string.digits + string.punctuation)
                self.get_response(
                    ''.join(
                        random.choice(letters_digits_symbols)
                        for i in range(size)), 'success')
        else:
            self.get_response('You did NOT enter an integer!', 'error')

    def get_response(self, text, result_type):
        """ Display response from request; password or error in non-editable
            text box """
        self.generated_pwd.setText(text)
        if (result_type == 'error'):
            self.generated_pwd.setStyleSheet("color: rgb(255, 0, 0)")
        else:
            self.generated_pwd.setStyleSheet("color: rgb(0, 153, 0)")
        self.generated_pwd.show()

    def on_generate_btn_clicked(self):
        """ Execute request to generate password with validations """
        try:
            input = self.size_textbox.text().strip()
            if (input == ''):
                self.get_response(
                    'You did not enter a value for password '
                    'length.', 'error')
            else:
                input = int(input)
                if (self.pin_radiobtn.isChecked()):
                    self.get_pin(input)
                elif (self.alphanum_radiobtn.isChecked()):
                    self.get_alphanumeric_password(input)
                elif (self.special_radiobtn.isChecked()):
                    self.get_alphanumeric_with_symbols_password(input)
                else:
                    self.get_response('You must select a password option.',
                                      'error')
        except ValueError:
            self.get_response('You entered a string.', 'error')
class CreateNetworkWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 50, 600, 400)
        self.setWindowTitle("Add a New Connection")
        self.layouts()
        self.widgets()

    def layouts(self):
        self.mainLayout = QVBoxLayout()
        self.topLayout = QFormLayout()
        self.middelLayout = QFormLayout()

        #self.topLayout.setContentsMargins(20,20,20,20)
        self.bottomLayout = QHBoxLayout()

        self.submitBtn = QPushButton("Add")
        self.submitBtn.clicked.connect(self.submitAction)
        self.cancelBtn = QPushButton("Cancel")
        self.cancelBtn.clicked.connect(self.cancelAction)
        self.submitBtn.setFixedHeight(30)
        self.cancelBtn.setFixedHeight(30)
        self.submitBtn.setStyleSheet(
            "color: #ecf0f1; background-color: #27ae60 ; border: 0px solid #27ae60"
        )
        self.cancelBtn.setStyleSheet(
            "color: #ecf0f1; background-color: #e74c3c; border: 0px solid #e74c3c"
        )

        self.bottomLayout.addWidget(self.submitBtn)
        self.bottomLayout.addWidget(self.cancelBtn)
        self.mainLayout.addLayout(self.topLayout)
        self.mainLayout.addStretch()
        self.mainLayout.addLayout(self.bottomLayout)
        self.setLayout(self.mainLayout)

    def widgets(self):
        self.comboInt = QComboBox()
        # fectch interfaces
        try:
            subprocess.run(' ls /sys/class/net > /tmp/networkInterfaces.txt',
                           check=True,
                           shell=True)
            deviceFile = open('/tmp/networkInterfaces.txt', 'rt')
            device = deviceFile.read()
            interName = device.splitlines()
            self.comboInt.addItems(interName)

        except:
            print("Can't fetch network interface ")

        # New
        self.ssid = QLineEdit()
        self.ssid.setPlaceholderText('Required on wifi type ')
        self.typeCombo = QComboBox()
        self.typeCombo.addItem("ethernet")
        self.typeCombo.addItem("wifi")
        self.newconNameEdit = QLineEdit()
        self.newconNameEdit.setPlaceholderText('Required field')
        self.ipEdit = QLineEdit()
        self.ipEdit.setPlaceholderText('Required field')
        self.gatewayEdit = QLineEdit()
        self.gatewayEdit.setPlaceholderText('Required field')
        self.dnsEdit = QLineEdit()
        self.dnsEdit.setPlaceholderText('Optionnel field')
        self.maskListItem = QComboBox()
        self.maskListItem.addItem(" /24:     255.255.255.0      ")
        self.maskListItem.addItem(" /32:     255.255.255.255     ")
        self.maskListItem.addItem(" /31:     255.255.255.254   ")
        self.maskListItem.addItem(" /30:     255.255.255.252    ")
        self.maskListItem.addItem(" /29:     255.255.255.248    ")
        self.maskListItem.addItem(" /28:     255.255.255.240     ")
        self.maskListItem.addItem(" /27:     255.255.255.224    ")
        self.maskListItem.addItem(" /26:     255.255.255.192   ")
        self.maskListItem.addItem(" /25:     255.255.255.128      ")
        self.maskListItem.addItem(" /23:     255.255.254.0    ")
        self.maskListItem.addItem(" /22:     255.255.252.0       ")
        self.maskListItem.addItem(" /21:     255.255.248.255")
        self.maskListItem.addItem(" /20:     255.255.255.240")

        # GROUP LAYOUT
        self.ip_group = QHBoxLayout()
        widget = QWidget(self)
        self.ip_group_button = QButtonGroup(widget)
        self.man = QRadioButton("Manual")
        self.dhcp = QRadioButton("DHCP")
        self.man.setChecked(True)

        self.ip_group_button.addButton(self.man)
        self.ip_group_button.addButton(self.dhcp)
        self.ip_group.addWidget(self.man)
        self.ip_group.addWidget(self.dhcp)

        #GROUP LAYOUT
        self.ethernet = QRadioButton("Ethernet")
        self.wifi = QRadioButton("Wifi")
        self.ethernet.setChecked(True)
        self.type_group = QHBoxLayout()
        self.type_group.addWidget(self.ethernet)
        self.type_group.addWidget(self.wifi)

        self.topLayout.addRow(QLabel('General information'), QLabel(''))
        self.topLayout.addRow(QLabel(''), QLabel(''))
        self.topLayout.addRow(QLabel("Enter New Connection's Name:"),
                              self.newconNameEdit)
        self.topLayout.addRow(QLabel("Enter SSID: "), self.ssid)
        self.topLayout.addRow(QLabel("Select interface:"), self.comboInt)
        self.topLayout.addRow(QLabel("Change Connection Type:"), QLabel(""))
        self.topLayout.addRow(self.type_group)
        self.topLayout.addRow(QLabel(''), QLabel(''))

        self.topLayout.addRow(QLabel('IP Method Assing:'), QLabel(''))
        self.topLayout.addRow(QLabel(''), QLabel(''))

        self.topLayout.addRow(self.ip_group)
        self.topLayout.addRow(QLabel(''), QLabel(''))
        self.topLayout.addRow(QLabel('IP information'), QLabel(''))
        self.topLayout.addRow(QLabel(''), QLabel(''))
        self.topLayout.addRow(QLabel("Enter New IP Address"), self.ipEdit)
        self.topLayout.addRow(QLabel("Enter New Subnet Mask"),
                              self.maskListItem)
        self.topLayout.addRow(QLabel("Enter New GATWAY address"),
                              self.gatewayEdit)
        self.topLayout.addRow(QLabel("Enter DNS Address"), self.dnsEdit)
        self.topLayout.addRow(QLabel(''), QLabel(''))
        self.topLayout.addRow(QLabel(''), QLabel(''))

    def submitAction(self):
        newssid = self.ssid.text()
        newName = self.newconNameEdit
        newInter = self.comboInt
        newIp = self.ipEdit.text()
        newMask = self.maskListItem.currentText()
        newMask = newMask.split(':')[0]
        newGatway = self.gatewayEdit.text()
        newDns = self.dnsEdit.text()

        if str(newName.text()) in ' ':

            QMessageBox.warning(self, 'warning',
                                f"Must Enter Connection name\n")

        elif str(newIp) in ' ' and self.man.isChecked():
            QMessageBox.warning(self, 'warning', f"Must Enter Connection Ip\n")

        elif str(newGatway) in ' ' and self.man.isChecked():
            QMessageBox.warning(self, 'warning',
                                f"Must Enter Connection Gateway\n")

        elif str(newGatway) == str(newIp) and self.man.isChecked():
            QMessageBox.warning(self, 'warning',
                                f"Gateway is the same IP address \n")

        elif self.wifi.isChecked() and newssid in '':

            QMessageBox.warning(self, 'warning',
                                " SSID is missing .\n Enter SSID name  \n")

        else:

            if self.man.isChecked():

                dns = False
                if str(newDns) not in ' ':
                    dns = True

                Mask = str(newMask)
                mask = str(Mask[2:])
                ipMask = f'{newIp}/{mask}'
                name = newName.text()
                #name=name.replace(' ','\\ ')

                command = f'nmcli con add con-name {name} ifname {str(newInter.currentText())}'

                if self.wifi.isChecked():
                    command += f' type wifi ssid {str(newssid)}'
                else:
                    command += f' type ethernet'

                command += f' ipv4.address {ipMask} ipv4.gateway {str(newGatway)}'

                if dns == True:
                    command += f' ipv4.dns {newDns} ipv4.method manual'
                else:
                    command += f' ipv4.method manual'

                try:
                    subprocess.run(command, check=True, shell=True)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(
                        self, 'warning',
                        f"error occured during setting this changes\n")
                else:
                    QMessageBox.information(
                        self, 'success',
                        '\n a New Connection Added  Succesfully.')
                    self.close()

            #DHCP
            if self.dhcp.isChecked():

                command = f'nmcli con add con-name {str(newName.text())} ifname {str(newInter.currentText())}'

                if self.wifi.isChecked():
                    command += f' type wifi ssid {str(newssid)}'
                else:

                    command += f' type ethernet'

                command += f' ipv4.method auto'

                try:
                    subprocess.run(command, check=True, shell=True)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(
                        self, 'warning',
                        f"error occured during setting this changes\n")
                else:
                    QMessageBox.information(
                        self, 'success',
                        '\n a New Connection Added  Succesfully.')
                    self.close()

    def cancelAction(self):
        self.close()
Example #39
0
class SortDialog(QDialog):
    def __init__(self, desc=None, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Sort…"))

        self.smartSortBox = QRadioButton(self.tr("Canned sort"), self)
        self.smartSortBox.setToolTip(
            self.tr("A combination of simple, complex and custom "
                    "sorts that give optimized ordering results."))
        self.glyphSetBox = QRadioButton(self.tr("Glyph set"), self)
        self.glyphSetBox.toggled.connect(self.glyphSetToggle)
        self.glyphSetDrop = QComboBox(self)
        self.glyphSetDrop.setEnabled(False)
        glyphSets = settings.readGlyphSets()
        for name, glyphNames in glyphSets.items():
            self.glyphSetDrop.addItem(name, glyphNames)
        self.customSortBox = QRadioButton(self.tr("Custom…"), self)
        self.customSortBox.toggled.connect(self.customSortToggle)

        self.customSortGroup = QGroupBox(parent=self)
        self.customSortGroup.setEnabled(False)
        descriptorsCount = 6
        if desc is None:
            pass
        elif desc[0]["type"] == "glyphSet":
            self.glyphSetBox.setChecked(True)
            self.glyphSetDrop.setEnabled(True)
            # XXX: we must handle unknown glyphSets... or glyphSets with
            # the same name but different
            self.glyphSetDrop.setCurrentText(desc[0]["name"])
        elif desc[0]["type"] == "cannedDesign":
            self.smartSortBox.setChecked(True)
        else:
            self.customSortBox.setChecked(True)
            self.customSortGroup.setEnabled(True)
            descriptorsCount = len(desc)
        self.customDescriptors = [[] for i in range(descriptorsCount)]
        self.customSortLayout = QGridLayout()
        for i, line in enumerate(self.customDescriptors):
            line.append(QComboBox(self))
            line[0].insertItems(0, sortItems)
            line.append(QCheckBox(self.tr("Ascending"), self))
            line.append(QCheckBox(self.tr("Allow pseudo-unicode"), self))
            if self.customSortBox.isChecked():
                line[0].setCurrentIndex(self.indexFromItemName(
                    desc[i]["type"]))
                line[1].setChecked(desc[i]["ascending"])
                line[2].setChecked(desc[i]["allowPseudoUnicode"])
            else:
                line[0].setCurrentIndex(i)
                line[1].setChecked(True)
                line[2].setChecked(True)
            self.customSortLayout.addWidget(line[0], i, 0)
            self.customSortLayout.addWidget(line[1], i, 1)
            self.customSortLayout.addWidget(line[2], i, 2)
            btn = QPushButton(self)
            btn.setFixedWidth(32)
            btn.setProperty("index", i)
            line.append(btn)
            self.customSortLayout.addWidget(btn, i, 3)
            if i == 0:
                btn.setText("+")
                btn.clicked.connect(self._addRow)
                self.addLineButton = btn
            else:
                btn.setText("−")
                btn.clicked.connect(self._deleteRow)
        self.customSortGroup.setLayout(self.customSortLayout)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QVBoxLayout(self)
        layout.addWidget(self.smartSortBox)
        layout.addWidget(self.glyphSetBox)
        layout.addWidget(self.glyphSetDrop)
        layout.addWidget(self.customSortBox)
        layout.addWidget(self.customSortGroup)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

    def _addRow(self):
        i = len(self.customDescriptors)
        line = []
        line.append(QComboBox(self))
        line[0].insertItems(0, sortItems)
        line[0].setCurrentIndex(0)
        line.append(QCheckBox("Ascending", self))
        line.append(QCheckBox("Allow pseudo-unicode", self))
        btn = QPushButton("−", self)
        btn.setFixedWidth(32)
        btn.setProperty("index", i)
        btn.clicked.connect(self._deleteRow)
        line.append(btn)
        self.customDescriptors.append(line)
        self.customSortLayout.addWidget(line[0], i, 0)
        self.customSortLayout.addWidget(line[1], i, 1)
        self.customSortLayout.addWidget(line[2], i, 2)
        self.customSortLayout.addWidget(line[3], i, 3)
        if i == 7:
            self.sender().setEnabled(False)

    def _deleteRow(self):
        rel = self.sender().property("index")
        desc = self.customDescriptors
        for i in range(rel + 1, len(desc) - 1):
            desc[i][0].setCurrentIndex(desc[i + 1][0].currentIndex())
            desc[i][1].setChecked(desc[i + 1][1].isChecked())
            desc[i][2].setChecked(desc[i + 1][2].isChecked())
        for elem in desc[-1]:
            elem.setParent(None)
        del self.customDescriptors[-1]
        self.addLineButton.setEnabled(True)
        self.adjustSize()

    def indexFromItemName(self, name):
        for index, item in enumerate(sortItems):
            if name == item:
                return index
        print(self.tr("Unknown descriptor name: %s"), name)
        return 0

    @classmethod
    def getDescriptor(cls, parent, sortDescriptor=None):
        dialog = cls(sortDescriptor, parent)
        result = dialog.exec_()
        if dialog.glyphSetBox.isChecked():
            data = dialog.glyphSetDrop.currentData()
            name = dialog.glyphSetDrop.currentText()
            ret = [dict(type="glyphSet", glyphs=data, name=name)]
        elif dialog.customSortBox.isChecked():
            descriptors = []
            for line in dialog.customDescriptors:
                descriptors.append(
                    dict(type=line[0].currentText(),
                         ascending=line[1].isChecked(),
                         allowPseudoUnicode=line[2].isChecked()))
            ret = descriptors
        else:
            ret = [dict(type="cannedDesign", allowPseudoUnicode=True)]
        return (ret, result)

    def glyphSetToggle(self):
        checkBox = self.sender()
        self.glyphSetDrop.setEnabled(checkBox.isChecked())

    def customSortToggle(self):
        checkBox = self.sender()
        self.customSortGroup.setEnabled(checkBox.isChecked())
Example #40
0
class InputProblem(QDialog):
    def __init__(self,parent=None):
        super(InputProblem, self).__init__(parent)
        self.title = ""
        self.numVar = 0
        self.numCons = 0
        self.typeVar = 0
        self.objCrit = True
        ##--topLayout--##
        topLayout = QHBoxLayout()

        self.nameProblemEdit = QLineEdit()
        nameProblemLabel = QLabel("&Problem Title")
        nameProblemLabel.setBuddy(self.nameProblemEdit)

        topLayout.addWidget(nameProblemLabel)
        topLayout.addWidget(self.nameProblemEdit)
        ##--TopBelowLayout--##
        topBelowLayout = QHBoxLayout()

        self.numVariablesSpinBox = QSpinBox()
        self.numVariablesSpinBox.setMinimum(2)
        self.numVariablesSpinBox.setValue(2)
        numVariablesLabel = QLabel("&Number of Variables")
        numVariablesLabel.setBuddy(self.numVariablesSpinBox)

        leftLayout = QHBoxLayout()
        leftLayout.addWidget(numVariablesLabel)
        leftLayout.addWidget(self.numVariablesSpinBox)

        self.numConstraintsSpinBox = QSpinBox()
        self.numConstraintsSpinBox.setMinimum(1)
        self.numConstraintsSpinBox.setValue(1)
        numConstraintsLabel = QLabel("&Number of Constraints")
        numConstraintsLabel.setBuddy(self.numConstraintsSpinBox)

        rightLayout = QHBoxLayout()
        rightLayout.addWidget(numConstraintsLabel)
        rightLayout.addWidget(self.numConstraintsSpinBox)

        topBelowLayout.addLayout(leftLayout)
        topBelowLayout.addLayout(rightLayout)

        ##--GroupLayout--##
        self.createTopLeftGroupBox()
        self.createTopRightGroupBox()

        ##--Buttons--##
        buttonBox=QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.verify)
        buttonBox.rejected.connect(self.reject)

        ##--MainLayout--##
        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addLayout(topBelowLayout, 1, 0, 1, 2)
        mainLayout.addWidget(self.topLeftGroupBox, 2, 0)
        mainLayout.addWidget(self.topRightGroupBox, 2, 1)
        mainLayout.addWidget(buttonBox, 3, 1)

        self.setLayout(mainLayout)
        self.setWindowTitle("Problem Specification")

    def createTopLeftGroupBox(self):
        self.topLeftGroupBox = QGroupBox("Objetive Criterion")
        self.maxRadioButton = QRadioButton("Maximization")
        self.minRadioButton = QRadioButton("Minimization")
        self.maxRadioButton.setChecked(True)
        layout = QVBoxLayout()
        layout.addWidget(self.maxRadioButton)
        layout.addWidget(self.minRadioButton)

        self.topLeftGroupBox.setLayout(layout)

    def createTopRightGroupBox(self):
        self.topRightGroupBox = QGroupBox("Default Variable Type")
        self.nonNegConRadioButton = QRadioButton("Non Negative Continuous")
        self.nonNegIntRadioButton = QRadioButton("Non Negative Integer")
        self.binaryRadioButton = QRadioButton("Binary(0,1)")
        self.unrestrictedRadioButton = QRadioButton("Unrestricted")
        self.unrestrictedRadioButton.setChecked(True)

        layout = QVBoxLayout()
        layout.addWidget(self.nonNegConRadioButton)
        layout.addWidget(self.nonNegIntRadioButton)
        layout.addWidget(self.binaryRadioButton)
        layout.addWidget(self.unrestrictedRadioButton)

        self.topRightGroupBox.setLayout(layout)

    def verify(self):
        if self.nameProblemEdit.text():
            self.title = self.nameProblemEdit.text()
            self.numVar = self.numVariablesSpinBox.value()
            self.numCons = self.numConstraintsSpinBox.value()

            if self.nonNegConRadioButton.isChecked():
                self.typeVar = 1
            elif self.nonNegIntRadioButton.isChecked():
                self.typeVar = 2
            elif self.binaryRadioButton.isChecked():
                self.typeVar = 3
            else:#Unrestricted
                self.typeVar = 4

            if self.maxRadioButton.isChecked():
                self.objCrit = True#Maximitation
            else:
                self.objCrit = False#Minimization

            self.accept()
            return

        answer = QMessageBox.warning(self, "Incomplete Input Problem",
                "Dont contain all the necessary information.\n"
                "Do you want to discard it?",
                QMessageBox.Yes, QMessageBox.No)

        if answer == QMessageBox.Yes:
            self.reject()
    def setupItemsTable(self):
        self.itemsTable = QTableWidget(len(self.items), 2)

        for row, item in enumerate(self.items):
            name = QTableWidgetItem(item)
            name.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.itemsTable.setItem(row, 0, name)
            quantity = QTableWidgetItem('1')
            self.itemsTable.setItem(row, 1, quantity)
Example #41
0
class Ui_MainWindow(object):
    nameFileWave = ''
    overlap = 0.4
    nperseg = 512
    window = 'hamming'
    pause = False
    regionPause = False
    deletePlotFragment = True

    def setupUi(self, MainWindow):

        MainWindow.setGeometry(450, 50, 1000, 785)
        MainWindow.setWindowTitle("CFS")

        self.mainMenu = QMenuBar(MainWindow)
        self.mainMenu.setGeometry(QRect(0, 0, 1000, 21))
        self.fileMenu = QMenu('&Dzwiek', self.mainMenu)
        MainWindow.setMenuBar(self.mainMenu)
        self.actionOpenFile = QAction('&Wczytaj', MainWindow)
        self.actionOpenFile.setShortcut('Ctrl+W')
        self.actionOpenFile.setStatusTip('Wczytaj dzwięk')
        self.actionOpenFile.triggered.connect(self.fileName)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.actionOpenFile)
        self.mainMenu.addAction(self.fileMenu.menuAction())

        self.centralwidget = QWidget(MainWindow)
        self.groupBoxOdtwarzacz = QGroupBox(self.centralwidget)
        self.groupBoxOdtwarzacz.setTitle("Odtwarzacz:")
        self.groupBoxOdtwarzacz.setGeometry(QRect(10, 20, 171, 111))
        self.pushButtonPlay = QPushButton(self.groupBoxOdtwarzacz)
        self.pushButtonPlay.setGeometry(QRect(20, 80, 31, 23))
        self.pushButtonPlay.setText("Play")
        self.pushButtonPlay.clicked.connect(self.filePlay)
        self.pushButtonStop = QPushButton(self.groupBoxOdtwarzacz)
        self.pushButtonStop.setGeometry(QRect(110, 80, 31, 23))
        self.pushButtonStop.setText("Stop")
        self.pushButtonStop.clicked.connect(self.fileStop)
        self.pushButtonPause = QPushButton(self.groupBoxOdtwarzacz)
        self.pushButtonPause.setGeometry(QRect(60, 80, 41, 23))
        self.pushButtonPause.setText("Pause")
        self.pushButtonPause.clicked.connect(self.filePause)
        self.radioButtonCalosc = QRadioButton(self.groupBoxOdtwarzacz)
        self.radioButtonCalosc.setGeometry(QRect(10, 20, 91, 20))
        self.radioButtonCalosc.setText("całe nagranie")
        self.radioButtonCalosc.setChecked(True)
        self.radioButtonFragment = QRadioButton(self.groupBoxOdtwarzacz)
        self.radioButtonFragment.setGeometry(QRect(10, 40, 161, 17))
        self.radioButtonFragment.setText("wybrany przedział nagrania")

        self.groupBoxDlugoscZakladki = QGroupBox(self.centralwidget)
        self.groupBoxDlugoscZakladki.setEnabled(True)
        self.groupBoxDlugoscZakladki.setGeometry(QRect(210, 20, 131, 111))
        self.groupBoxDlugoscZakladki.setTitle("Długość zakładki:")
        self.comboBoxDlugoscZakladki = QComboBox(self.groupBoxDlugoscZakladki)
        self.comboBoxDlugoscZakladki.setGeometry(QRect(10, 30, 70, 25))
        self.comboBoxDlugoscZakladki.addItem("10%")
        self.comboBoxDlugoscZakladki.addItem("20%")
        self.comboBoxDlugoscZakladki.addItem("30%")
        self.comboBoxDlugoscZakladki.addItem("40%")
        self.comboBoxDlugoscZakladki.addItem("50%")
        self.comboBoxDlugoscZakladki.addItem("60%")
        self.comboBoxDlugoscZakladki.addItem("70%")
        self.comboBoxDlugoscZakladki.addItem("80%")
        self.comboBoxDlugoscZakladki.addItem("90%")
        self.comboBoxDlugoscZakladki.setCurrentIndex(3)
        self.comboBoxDlugoscZakladki.currentIndexChanged.connect(
            self.updateSpectrum)

        self.groupBoxOkno = QGroupBox(self.centralwidget)
        self.groupBoxOkno.setEnabled(True)
        self.groupBoxOkno.setGeometry(QRect(530, 20, 131, 111))
        self.groupBoxOkno.setTitle("Okna:")
        self.comboBoxOkno = QComboBox(self.groupBoxOkno)
        self.comboBoxOkno.setEnabled(True)
        self.comboBoxOkno.setGeometry(QRect(10, 30, 81, 25))
        self.comboBoxOkno.addItem("HAMMING")
        self.comboBoxOkno.addItem("BLACKMAN")
        self.comboBoxOkno.addItem("HANN")
        self.comboBoxOkno.addItem("BARTLETT")
        self.comboBoxOkno.addItem("TRIANG")
        self.comboBoxOkno.currentIndexChanged.connect(self.updateSpectrum)

        self.groupBoxDlugoscProbki = QGroupBox(self.centralwidget)
        self.groupBoxDlugoscProbki.setGeometry(QRect(370, 20, 131, 111))
        self.groupBoxDlugoscProbki.setTitle("Dlugość próbki:")
        self.comboBoxDlugoscProbki = QComboBox(self.groupBoxDlugoscProbki)
        self.comboBoxDlugoscProbki.setGeometry(QRect(10, 30, 70, 25))
        self.comboBoxDlugoscProbki.addItem("16")
        self.comboBoxDlugoscProbki.addItem("32")
        self.comboBoxDlugoscProbki.addItem("64")
        self.comboBoxDlugoscProbki.addItem("128")
        self.comboBoxDlugoscProbki.addItem("256")
        self.comboBoxDlugoscProbki.addItem("512")
        self.comboBoxDlugoscProbki.addItem("1024")
        self.comboBoxDlugoscProbki.addItem("2048")
        self.comboBoxDlugoscProbki.addItem("4096")
        self.comboBoxDlugoscProbki.setCurrentIndex(5)
        self.comboBoxDlugoscProbki.currentIndexChanged.connect(
            self.updateSpectrum)
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')

        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(12, 130, 10, 10)
        self.plotCalosc = pg.PlotWidget()
        self.plotCalosc.setTitle("FALA SYGNAŁU")
        self.plotCalosc.setLabel('bottom', "Czas", units='s')
        self.plotCalosc.setLabel('left', "Amplituda", units='')
        self.verticalLayout.addWidget(self.plotCalosc)

        self.plotFragment = pg.PlotWidget()
        self.plotFragment.setTitle("POWIEKSZONY FRAGMENT FALI SYGNAŁU")
        self.plotFragment.setLabel('bottom', "Czas", units='s')
        self.plotFragment.setLabel('left', "Amplituda", units='')
        self.verticalLayout.addWidget(self.plotFragment)

        self.plotSonogram = pg.PlotWidget()
        self.plotSonogram.setTitle("SPEKTOGRAM")
        self.plotSonogram.setLabel('bottom', "Czas", units='s')
        self.plotSonogram.setLabel('left', "Czestotliwosc", units='')
        self.verticalLayout.addWidget(self.plotSonogram)

        MainWindow.setCentralWidget(self.centralwidget)

        app.aboutToQuit.connect(self.closeEvent)

    def fileName(self):
        wave = QFileDialog.getOpenFileName(
            caption='Wczytaj dzwiek',
            filter="Music(*.wav)",
            options=QFileDialog.DontUseNativeDialog)

        if wave == ('', ''):
            QMessageBox.information(None, 'Informacja',
                                    "Nie wczytales dzwieku.", QMessageBox.Ok)
        else:
            self.nameFileWave = ""
            self.nameFileWave = wave[0]
            self.fileReadSound()

    def filePlay(self):

        print("Play")
        try:
            if self.nameFileWave == "":
                QMessageBox.information(None, 'Informacja',
                                        'Nie został wczytany żaden dźwięk.',
                                        QMessageBox.Ok)
            else:
                if self.radioButtonCalosc.isChecked():

                    if self.pause == False:
                        pygame.mixer.music.load(self.nameFileWave)
                        pygame.mixer.music.play()

                    else:
                        pygame.mixer.music.unpause()
                        self.pause = False

                else:
                    if self.regionPause == False:

                        try:
                            pygame.mixer.music.load(self.nameFileWave)
                            wavfile.write('fragment.wav', self.tempRegionRate,
                                          self.tempRegionData)

                        except:
                            pass

                        pygame.mixer.music.load('fragment.wav')
                        pygame.mixer.music.play()

                    else:
                        pygame.mixer.music.unpause()
                        self.regionPause = False

        except:
            QMessageBox.information(
                None, 'Informacja',
                'Program nie moze otworzyc dzwieku, ale przeanalizował sygnal.',
                QMessageBox.Ok)

    def filePause(self):

        print("Pause")
        try:
            if self.nameFileWave == "":
                QMessageBox.information(None, 'Informacja',
                                        'Nie został wczytany żaden dźwięk.',
                                        QMessageBox.Ok)
            else:
                pygame.mixer.music.pause()

                if pygame.mixer.music.get_busy() == 0:
                    self.pause = False
                    self.regionPause = False
                else:
                    self.pause = True
                    self.regionPause = True
        except:
            pass

    def fileStop(self):
        print("Stop")
        try:
            if self.nameFileWave == "":
                QMessageBox.information(None, 'Informacja',
                                        'Nie został wczytany żaden dźwięk.',
                                        QMessageBox.Ok)
            else:
                pygame.mixer.music.stop()
                self.pause = False
                self.regionPause = False
        except:
            pass

    def fileReadSound(self):

        try:
            self.pause = False
            self.regionPause = False

            rate, data = wavfile.read(self.nameFileWave)

            if len(data.shape) == 2:
                data = data[:, 1]

            try:
                pygame.mixer.music.load(self.nameFileWave)
                wavfile.write('fragment.wav', rate, data)
            except:
                QMessageBox.information(
                    None, 'Informacja',
                    'Pliki wav nie moga miec polskich znakow.', QMessageBox.Ok)

            self.tempRegionRate = rate
            self.tempRegionData = data
            times = np.arange(len(data)) / float(rate)
            self.x = times
            self.y = data
            self.tempx = times
            self.tempy = data
            self.makePlot()

        except ValueError:
            self.nameFileWave = ''
            QMessageBox.information(
                None, 'Błąd',
                'Nie można wczytać tego pliku,\n Proszę wybrać inny.',
                QMessageBox.Ok)

    def makePlot(self):

        if self.deletePlotFragment:
            self.plotFragment.close()

        self.plotCalosc.plot(x=self.x, y=self.y, clear=True)
        tempMinX = min(self.x)
        tempMaxX = max(self.x)
        tempMinY = min(self.y)
        tempMaxY = max(self.y)

        tempDistanceX = 0.02
        if tempMaxX <= 10.0:
            pass
        else:
            if tempMaxX <= 100.0:
                tempDistanceX = 0.2
            else:
                tempDistanceX = 2.0

        if tempMinY > 0:
            tempDistanceMinY = tempMinY - tempMinY / 2
        else:
            if tempMinY < 0:
                tempDistanceMinY = tempMinY + tempMinY / 2
            else:
                tempDistanceMinY = -10

        if tempMaxY < 0:
            tempDistanceMaxY = tempMaxX - tempMaxX / 2
        else:
            if tempMaxY > 0:
                tempDistanceMaxY = tempMaxY + tempMaxY / 2
            else:
                tempDistanceMaxY = +10

        self.plotCalosc.setRange(
            xRange=[tempMinX - tempDistanceX, tempMaxX + tempDistanceX],
            yRange=[tempDistanceMinY, tempDistanceMaxY])
        self.plotCalosc.setLimits(xMin=tempMinX - tempDistanceX,
                                  xMax=tempMaxX + tempDistanceX,
                                  yMin=tempDistanceMinY,
                                  yMax=tempDistanceMaxY)

        if (max(self.x) < 90.0):
            self.region = pg.LinearRegionItem([0, self.x[-1]],
                                              bounds=[0, self.x[-1]])
            self.region.setZValue(100)
            self.plotCalosc.addItem(self.region)

            self.region.sigRegionChanged.connect(self.updateRegion)

            self.plotFragment = pg.PlotWidget(x=self.tempx, y=self.tempy)
            self.plotFragment.setRange(
                xRange=[tempMinX - tempDistanceX, tempMaxX + tempDistanceX],
                yRange=[tempDistanceMinY, tempDistanceMaxY])
            self.plotFragment.setLimits(xMin=tempMinX - tempDistanceX,
                                        xMax=tempMaxX + tempDistanceX,
                                        yMin=tempDistanceMinY,
                                        yMax=tempDistanceMaxY)
            self.plotFragment.setTitle("POWIEKSZONY FRAGMENT FALI SYGNAŁU")
            self.plotFragment.setLabel('bottom', "Czas", units='s')
            self.plotFragment.setLabel('left', "Amplituda", units='')
            self.verticalLayout.addWidget(self.plotFragment)
            self.deletePlotFragment = True
        else:
            self.deletePlotFragment = False

        self.makeSpectrum()

    def updateRegion(self):

        temp = (self.x > self.region.getRegion()[0] - 0.000000001) & (
            self.x < self.region.getRegion()[1] + 0.000000001)

        self.tempx = self.x[temp]
        self.tempy = self.y[temp]
        self.tempRegionData = self.tempy
        self.updatePlot()

    def updatePlot(self):

        self.regionPause = False
        tempMinX = min(self.tempx)
        tempMaxX = max(self.tempx)
        tempMinY = min(self.tempy)
        tempMaxY = max(self.tempy)

        if tempMinY > 0:
            tempDistanceMinY = tempMinY - tempMinY / 2
        else:
            if tempMinY < 0:
                tempDistanceMinY = tempMinY + tempMinY / 2
            else:
                tempDistanceMinY = -10

        if tempMaxY < 0:
            tempDistanceMaxY = tempMaxX - tempMaxX / 2
        else:
            if tempMaxY > 0:
                tempDistanceMaxY = tempMaxY + tempMaxY / 2
            else:
                tempDistanceMaxY = +10

        self.plotFragment.setRange(xRange=[tempMinX, tempMaxX],
                                   yRange=[tempDistanceMinY, tempDistanceMaxY])
        self.plotFragment.setLimits(xMin=tempMinX,
                                    xMax=tempMaxX,
                                    yMin=tempDistanceMinY,
                                    yMax=tempDistanceMaxY)
        self.plotFragment.plot(x=self.tempx, y=self.tempy, clear=True)
        self.updateSpectrum()

    def makeSpectrum(self):

        if self.nameFileWave == "":
            overlap = self.dlugoscZakladki(
                self.comboBoxDlugoscZakladki.currentText())
            window = self.comboBoxOkno.currentText().lower()
            nperseg = int(self.comboBoxDlugoscProbki.currentText())
        else:

            overlap = self.dlugoscZakladki(
                self.comboBoxDlugoscZakladki.currentText())
            window = self.comboBoxOkno.currentText().lower()
            nperseg = int(self.comboBoxDlugoscProbki.currentText())

            tempwindow = get_window(window, nperseg)
            tempoverlap = nperseg * overlap
            tempoverlap = int(round(tempoverlap))

            try:
                f, t, S = self.stft(self.tempy, self.tempRegionRate,
                                    tempwindow, nperseg, tempoverlap, window)
                S = 20 * np.log10(S)
                self.plotSonogram.close()
                self.plotSonogram = pg.PlotWidget()
                self.plotSonogram.setTitle("SPEKTOGRAM")
                self.plotSonogram.setLabel('bottom', "Czas", units='s')
                self.plotSonogram.setLabel('left', "Czestotliwosc", units='Hz')

                pg.setConfigOptions(imageAxisOrder='row-major')
                self.img = pg.ImageItem()
                self.plotSonogram.addItem(self.img)
                hist = pg.HistogramLUTItem()
                hist.setImageItem(self.img)
                hist.setLevels(np.min(S), np.max(S))
                hist.gradient.restoreState({
                    'mode':
                    'rgb',
                    'ticks': [(0.0, (0, 255, 255, 255)),
                              (0.25, (0, 0, 255, 255)), (0.5, (0, 0, 0, 255)),
                              (0.75, (255, 0, 0, 255)),
                              (1.0, (255, 255, 0, 255))]
                })
                self.img.setImage(S)
                self.img.scale(t[-1] / np.size(S, axis=1),
                               f[-1] / np.size(S, axis=0))
                self.plotSonogram.setLimits(xMin=0,
                                            xMax=t[-1],
                                            yMin=0,
                                            yMax=f[-1])
                self.verticalLayout.addWidget(self.plotSonogram)

            except:
                pass

    def updateSpectrum(self):

        overlap = self.dlugoscZakladki(
            self.comboBoxDlugoscZakladki.currentText())
        window = self.comboBoxOkno.currentText().lower()
        nperseg = int(self.comboBoxDlugoscProbki.currentText())

        tempwindow = get_window(window, nperseg)
        tempoverlap = nperseg * overlap
        tempoverlap = int(round(tempoverlap))

        try:
            f, t, S = self.stft(self.tempy, self.tempRegionRate, tempwindow,
                                nperseg, tempoverlap, window)

            S = 20 * np.log10(S)

            pg.setConfigOptions(imageAxisOrder='row-major')
            self.img = pg.ImageItem()
            self.plotSonogram.plot(clear=True)
            self.plotSonogram.addItem(self.img)
            hist = pg.HistogramLUTItem()
            hist.setImageItem(self.img)
            hist.setLevels(np.min(S), np.max(S))
            hist.gradient.restoreState({
                'mode':
                'rgb',
                'ticks': [(0.0, (0, 255, 255, 255)), (1.0, (255, 255, 0, 255)),
                          (0.5, (0, 0, 0, 255)), (0.25, (0, 0, 255, 255)),
                          (0.75, (255, 0, 0, 255))]
            })
            self.img.setImage(S)
            self.img.scale(t[-1] / np.size(S, axis=1),
                           f[-1] / np.size(S, axis=0))
            self.plotSonogram.setLimits(xMin=0, xMax=t[-1], yMin=0, yMax=f[-1])

        except:
            pass

    def stft(self, x, fs, window, nperseg, noverlap, nameWindow):

        x = np.asarray(x)
        outdtype = np.result_type(x, np.complex64)

        if x.size == 0:
            return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape)

        if nperseg > x.shape[-1]:
            nperseg = x.shape[-1]
            win = get_window(nameWindow, nperseg)
        else:
            win = window

        if np.result_type(win, np.complex64) != outdtype:
            win = win.astype(outdtype)

        scale = 1.0 / win.sum()**2
        scale = np.sqrt(scale)

        if np.iscomplexobj(x):
            freqs = fftpack.fftfreq(nperseg, 1 / fs)
        else:
            freqs = np.fft.rfftfreq(nperseg, 1 / fs)

        result = self.fft(x, win, nperseg, noverlap)
        result *= scale
        time = np.arange(nperseg / 2, x.shape[-1] - nperseg / 2 + 1,
                         nperseg - noverlap) / float(fs)
        result = result.astype(outdtype)
        result = np.rollaxis(result, -1, -2)
        result = np.abs(result)
        tempResult = result[result != 0]
        result[result == 0] = np.min(tempResult)

        return freqs, time, result

    def fft(self, x, win, nperseg, noverlap):

        if nperseg == 1 and noverlap == 0:
            result = x[..., np.newaxis]
        else:
            step = nperseg - noverlap
            shape = x.shape[:-1] + ((x.shape[-1] - noverlap) // step, nperseg)
            strides = x.strides[:-1] + (step * x.strides[-1], x.strides[-1])
            result = np.lib.stride_tricks.as_strided(x,
                                                     shape=shape,
                                                     strides=strides)

        result = signaltools.detrend(result, type='constant', axis=-1)
        result = win * result

        if np.iscomplexobj(x):
            func = fftpack.fft
        else:
            result = result.real
            func = np.fft.rfft

        result = func(result, n=nperseg)

        return result

    def dlugoscZakladki(self, temp):

        if (temp == '10%'):
            overlap = 0.1
        else:
            if (temp == '20%'):
                overlap = 0.2
            else:
                if (temp == '30%'):
                    overlap = 0.3
                else:
                    if (temp == '40%'):
                        overlap = 0.4
                    else:
                        if (temp == '50%'):
                            overlap = 0.5
                        else:
                            if (temp == '60%'):
                                overlap = 0.6
                            else:
                                if (temp == '70%'):
                                    overlap = 0.7
                                else:
                                    if (temp == '80%'):
                                        overlap = 0.8
                                    else:
                                        overlap = 0.9

        return overlap

    def closeEvent(self):
        if os.path.isfile('fragment.wav'):
            pygame.mixer.quit()
            os.remove('fragment.wav')
Example #42
0
class SettingsDialog(QDialog):
    """ Inherits: QDialog
        This class defines a dialog box.
        This dialog box is composed of two radio buttons, which let the user choose the order of methods and classes in the generated documentation.
    """

    def __init__(self, parent=None):
        """ Constructor
            Params: parent -> the object's parent
            Return: self
            The object is initialized with the super-constructror, the GUI with the initUI method.
        """
        super().__init__(parent)
        self.initUI()


    def initUI(self):
        """ Object method
            Params: None
            Return: None
            This method sets the dialog box's layout.
            The Dialog box conatains two radio buttons and OK/Cancel buttons.
            sizeHint() sets the box to an ideal size.
        """

        #creating layout
        settings_layout = QVBoxLayout();

        #creating Radio buttons
        self.nat_order = QRadioButton("Natural order", self);
        self.alph_order = QRadioButton("Alphabetical", self);

        #creating the buttons
        buttons = QDialogButtonBox();

        #creating OK button and connecting it to the dialog
        buttons.addButton(QDialogButtonBox.Ok);
        buttons.accepted.connect(self.accept)
        
        #creating Cancel button and connecting it to the dialog
        buttons.addButton(QDialogButtonBox.Cancel);
        buttons.rejected.connect(self.reject)

        #adding created buttons to the layout
        settings_layout.addWidget(self.nat_order);
        settings_layout.addWidget(self.alph_order);
        settings_layout.addWidget(buttons);

        #adding layout to dialog
        self.setLayout(settings_layout);
        self.sizeHint()



    def exec_(self):
        """ Object method.
            Params: None.
            Return: None.
            This method displays the window and launches its event loop. 
            Changes are commited when the OK button is pressed.
        """ 
        # If changes was confirmed
        if(super().exec_()):
            
            if self.nat_order.isChecked():
                self.parent()._files._order = NATURAL_ORDER;
            elif self.alph_order.isChecked():
                self.parent()._files._order = ALPHABETICAL_ORDER;
Example #43
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.groupbox_1 = QGroupBox('On and Off', self)  # 1
        self.groupbox_2 = QGroupBox('Change Color', self)

        self.red = QRadioButton('Red', self)  # 2
        self.blue = QRadioButton('Blue', self)
        self.green = QRadioButton('Green', self)
        self.yellow = QRadioButton('Yellow', self)
        self.color_list = [self.red, self.blue, self.green, self.yellow]

        self.on = QRadioButton('On', self)  # 3
        self.off = QRadioButton('Off', self)

        self.pic_label = QLabel(self)  # 4

        self.h1_layout = QHBoxLayout()
        self.h2_layout = QHBoxLayout()
        self.h3_layout = QHBoxLayout()
        self.all_v_layout = QVBoxLayout()

        self.layout_init()
        self.radiobutton_init()
        self.label_init()

    def layout_init(self):
        self.h1_layout.addWidget(self.on)
        self.h1_layout.addWidget(self.off)
        self.groupbox_1.setLayout(self.h1_layout)

        self.h2_layout.addWidget(self.red)
        self.h2_layout.addWidget(self.blue)
        self.h2_layout.addWidget(self.green)
        self.h2_layout.addWidget(self.yellow)
        self.groupbox_2.setLayout(self.h2_layout)

        self.h3_layout.addWidget(self.groupbox_1)
        self.h3_layout.addWidget(self.groupbox_2)

        self.all_v_layout.addWidget(self.pic_label)
        self.all_v_layout.addLayout(self.h3_layout)

        self.setLayout(self.all_v_layout)

    def radiobutton_init(self):
        self.yellow.setChecked(True)  # 5
        [
            btn.clicked.connect(self.change_color_func)
            for btn in self.color_list
        ]

        self.off.setChecked(True)  # 6
        self.off.toggled.connect(self.on_and_off_func)

    def label_init(self):  # 7
        self.pic_label.setPixmap(QPixmap('images/Off.png'))
        self.pic_label.setAlignment(Qt.AlignCenter)

    def change_color_func(self):
        if self.on.isChecked():
            path = 'images/{}.png'.format(
                [btn.text() for btn in self.color_list if btn.isChecked()][0])
            self.pic_label.setPixmap(QPixmap(path))

    def on_and_off_func(self):
        if self.on.isChecked():
            path = 'images/{}.png'.format(
                [btn.text() for btn in self.color_list if btn.isChecked()][0])
            self.pic_label.setPixmap(QPixmap(path))
        else:
            self.pic_label.setPixmap(QPixmap('images/Off.png'))
class Preferences(QDialog):
    def __init__(self, parent=None, test = False):
        super(Preferences, self).__init__(parent)
        self.parent = parent
        self.test = test

        saveQL = QLabel('<html><b>' + self.tr('Save files') + '</b></html>')
        existQL = QLabel(self.tr('Existing files:'))
        self.exst_prefixQRB = QRadioButton(self.tr("Add '~' prefix"))
        self.exst_overwriteQRB = QRadioButton(self.tr('Overwrite'))
        exist_layout = utils.add_to_layout(
                'h', self.exst_prefixQRB, self.exst_overwriteQRB)

        defaultQL = QLabel(self.tr('Default output destination:'))
        self.defaultQLE = QLineEdit()
        self.defaultQTB = QToolButton()
        self.defaultQTB.setText('...')
        deafult_fol_layout = utils.add_to_layout(
                'h', self.defaultQLE, self.defaultQTB)
        nameQL = QLabel('<html><b>' + self.tr('Name files') +'</b></html>')
        prefixQL = QLabel(self.tr('Prefix:'))
        suffixQL = QLabel(self.tr('Suffix:'))
        self.prefixQLE = QLineEdit()
        self.suffixQLE = QLineEdit()
        grid = utils.add_to_grid(
                [prefixQL, self.prefixQLE], [suffixQL, self.suffixQLE])
        prefix_layout = utils.add_to_layout('h', grid, None)

        tabwidget1_layout = utils.add_to_layout(
                'v', saveQL,
                QSpacerItem(14, 13), existQL, exist_layout,
                QSpacerItem(14, 13), defaultQL, deafult_fol_layout,
                QSpacerItem(13, 13), nameQL, QSpacerItem(14, 13),
                prefix_layout, None
                )

        ffmpegQL = QLabel('<html><b>FFmpeg</b></html>')
        ffmpeg_pathQL= QLabel(self.tr('Path to executable:'))
        self.ffmpegpathQLE = QLineEdit()

        default_cmd_ffmpegQL = QLabel(self.tr('Default command:'))
        self.ffmpegcmdQLE = QLineEdit()

        vidcodecsQL = QLabel(
                '<html><b>' + self.tr('Video codecs') +'</b></html>')
        self.vidcodecsQPTE = QPlainTextEdit()
        audcodecsQL = QLabel(
                '<html><b>' + self.tr('Audio codecs') +'</b></html>')
        self.audcodecsQPTE = QPlainTextEdit()
        extraformatsffmpegQL = QLabel(
                '<html><b>' + self.tr('Extra formats') +'</b></html>')
        self.extraformatsffmpegQPTE = QPlainTextEdit()

        gridlayout = utils.add_to_grid(
                [vidcodecsQL, audcodecsQL, extraformatsffmpegQL],
                [self.vidcodecsQPTE, self.audcodecsQPTE,
                 self.extraformatsffmpegQPTE]
                )

        defvidcodecsQPB = QPushButton(self.tr("Default video codecs"))
        defaudcodecsQPB = QPushButton(self.tr("Default audio codecs"))

        hlayout1 = utils.add_to_layout(
                'h', None, defvidcodecsQPB, defaudcodecsQPB)

        tabwidget2_layout = utils.add_to_layout(
                'v', ffmpegQL, QSpacerItem(14, 13), ffmpeg_pathQL,
                self.ffmpegpathQLE, default_cmd_ffmpegQL, self.ffmpegcmdQLE,
                QSpacerItem(20, 20), gridlayout, hlayout1, None
                )

        imagemagickQL = QLabel('<html><b>ImageMagick (convert)</b></html>')
        default_cmd_imageQL = QLabel(self.tr('Default options:'))
        self.imagecmdQLE = QLineEdit()

        extraformatsimageQL = QLabel(
                '<html><b>' + self.tr('Extra formats') +'</b></html>')
        self.extraformatsimageQPTE = QPlainTextEdit()

        hlayout2 = utils.add_to_layout('h',
                self.extraformatsimageQPTE, QSpacerItem(220,20))

        tabwidget3_layout = utils.add_to_layout(
                'v', imagemagickQL,
                QSpacerItem(14,13), default_cmd_imageQL, self.imagecmdQLE,
                QSpacerItem(20,20), extraformatsimageQL, hlayout2, None
                )

        extraformatsdocumentQL = QLabel(
                '<html><b>' + self.tr('Extra formats') +'</b></html>')
        self.extraformatsdocumentQPTE = QPlainTextEdit()

        hlayout3 = utils.add_to_layout('h',
                self.extraformatsdocumentQPTE, QSpacerItem(220,20))

        tabwidget4_layout = utils.add_to_layout(
                'v', extraformatsdocumentQL, hlayout3, None)

        widget1 = QWidget()
        widget1.setLayout(tabwidget1_layout)
        widget2 = QWidget()
        widget2.setLayout(tabwidget2_layout)
        widget3 = QWidget()
        widget3.setLayout(tabwidget3_layout)
        widget4 = QWidget()
        widget4.setLayout(tabwidget4_layout)
        tabWidget = QTabWidget()
        tabWidget.addTab(widget1, self.tr('General'))
        tabWidget.addTab(widget2, self.tr('Audio/Video'))
        tabWidget.addTab(widget3, self.tr('Images'))
        tabWidget.addTab(widget4, self.tr('Documents'))

        buttonBox = QDialogButtonBox(
                QDialogButtonBox.Ok|QDialogButtonBox.Cancel)

        final_layout = utils.add_to_layout('v', tabWidget, None, buttonBox)
        self.setLayout(final_layout)

        self.defaultQTB.clicked.connect(self.open_dir)
        buttonBox.accepted.connect(self.save_settings)
        buttonBox.rejected.connect(self.reject)
        defvidcodecsQPB.clicked.connect(
                lambda: self.set_videocodecs(config.video_codecs))
        defaudcodecsQPB.clicked.connect(
                lambda: self.set_audiocodecs(config.audio_codecs))

        self.resize(400, 450)
        self.setWindowTitle(self.tr('Preferences'))

        QTimer.singleShot(0, self.load_settings)

    def load_settings(self):
        """Load settings and update graphical widgets with loaded values."""
        settings = QSettings()
        overwrite_existing = settings.value('overwrite_existing', type=bool)
        default_output = settings.value('default_output', type=str)
        prefix = settings.value('prefix', type=str)
        suffix = settings.value('suffix', type=str)
        ffmpeg_path = settings.value('ffmpeg_path', type=str)
        default_command = (settings.value('default_command', type=str) or
                config.default_ffmpeg_cmd)
        videocodecs = (settings.value('videocodecs') or config.video_codecs)
        audiocodecs = (settings.value('audiocodecs') or config.audio_codecs)
        extraformats_video = (settings.value('extraformats_video') or [])
        default_command_image = (settings.value('default_command_image',
                type=str) or
                config.default_imagemagick_cmd
                )
        extraformats_image = (settings.value('extraformats_image') or [])
        extraformats_document = (settings.value('extraformats_document') or [])

        if overwrite_existing:
            self.exst_overwriteQRB.setChecked(True)
        else:
            self.exst_prefixQRB.setChecked(True)

        self.defaultQLE.setText(default_output)
        self.prefixQLE.setText(prefix)
        self.suffixQLE.setText(suffix)
        self.ffmpegpathQLE.setText(ffmpeg_path)
        self.ffmpegcmdQLE.setText(default_command)
        self.set_videocodecs(videocodecs)
        self.set_audiocodecs(audiocodecs)
        self.extraformatsffmpegQPTE.setPlainText("\n".join(extraformats_video))
        self.imagecmdQLE.setText(default_command_image)
        self.extraformatsimageQPTE.setPlainText("\n".join(extraformats_image))
        self.extraformatsdocumentQPTE.setPlainText("\n".join(extraformats_document))

    def set_videocodecs(self, codecs):
        self.vidcodecsQPTE.setPlainText("\n".join(codecs))

    def set_audiocodecs(self, codecs):
        self.audcodecsQPTE.setPlainText("\n".join(codecs))

    def open_dir(self):
        """Get a directory name using a standard Qt dialog and update
        self.defaultQLE with dir's name."""
        if self.defaultQLE.isEnabled():
            _dir = QFileDialog.getExistingDirectory(
                    self, 'FF Multi Converter - ' +
                    self.tr('Choose default output destination'), config.home
                    )
            if _dir:
                self.defaultQLE.setText(_dir)

    @staticmethod
    def plaintext_to_list(widget, formats=[]):
        """
        Parse the text from a QPlainTextEdit widget and return a list.
        The list will consist of every text line that is a single word
        and it's not in the formats list. No duplicates allowed.
        """
        _list = []
        for line in widget.toPlainText().split("\n"):
            line = line.strip()
            if len(line.split()) == 1 and line not in (_list+formats):
                _list.append(line)
        return _list

    def save_settings(self):
        """Set settings values by extracting the appropriate information from
        the graphical widgets."""
        videocodecs = self.plaintext_to_list(self.vidcodecsQPTE)
        audiocodecs = self.plaintext_to_list(self.audcodecsQPTE)
        extraformats_video = self.plaintext_to_list(self.extraformatsffmpegQPTE,
                config.video_formats)
        extraformats_image = self.plaintext_to_list(self.extraformatsimageQPTE,
                config.image_formats)
        extraformats_document = self.plaintext_to_list(
                self.extraformatsdocumentQPTE, config.document_formats)

        settings = QSettings()

        ffmpeg_path = os.path.expanduser(self.ffmpegpathQLE.text())
        if not utils.is_installed(ffmpeg_path):
            ffmpeg_path = utils.is_installed('ffmpeg')

        settings.setValue('overwrite_existing', self.exst_overwriteQRB.isChecked())
        settings.setValue('default_output', self.defaultQLE.text())
        settings.setValue('prefix', self.prefixQLE.text())
        settings.setValue('suffix', self.suffixQLE.text())
        settings.setValue('ffmpeg_path', ffmpeg_path)
        settings.setValue('default_command', self.ffmpegcmdQLE.text())
        settings.setValue('videocodecs', sorted(videocodecs))
        settings.setValue('audiocodecs', sorted(audiocodecs))
        settings.setValue('extraformats_video', sorted(extraformats_video))
        settings.setValue('default_command_image', self.imagecmdQLE.text())
        settings.setValue('extraformats_image', sorted(extraformats_image))
        settings.setValue('extraformats_document', sorted(extraformats_document))

        self.accept()
Example #45
0
class SettingsDialog(QDialog):
    worker = None
    config = None
    configfile = None

    saved = QtCore.pyqtSignal()

    def __init__(self, parent, worker, config, configfile):
        QDialog.__init__(self, parent)

        self.worker = worker
        self.config = config
        self.configfile = configfile
        self.setStyleSheet("QGroupBox { font-weight: bold; } ")
        self.setWindowTitle('Settings')
        layout = QGridLayout()

        # Categories
        self.category_list = QListWidget()
        category_media = QListWidgetItem(getIcon('media-playback-start'), 'Media', self.category_list)
        category_sync = QListWidgetItem(getIcon('view-refresh'), 'Sync', self.category_list)
        category_ui = QListWidgetItem(getIcon('window-new'), 'User Interface', self.category_list)
        category_theme = QListWidgetItem(getIcon('applications-graphics'), 'Theme', self.category_list)
        self.category_list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.category_list.setCurrentRow(0)
        self.category_list.setMaximumWidth(self.category_list.sizeHintForColumn(0) + 15)
        self.category_list.setFocus()
        self.category_list.currentItemChanged.connect(self.s_switch_page)

        # Media tab
        page_media = QWidget()
        page_media_layout = QVBoxLayout()
        page_media_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Media settings
        g_media = QGroupBox('Media settings')
        g_media.setFlat(True)
        g_media_layout = QFormLayout()
        self.tracker_enabled = QCheckBox()
        self.tracker_enabled.toggled.connect(self.tracker_type_change)

        self.tracker_type = QComboBox()
        for (n, label) in utils.available_trackers:
            self.tracker_type.addItem(label, n)
        self.tracker_type.currentIndexChanged.connect(self.tracker_type_change)

        self.tracker_interval = QSpinBox()
        self.tracker_interval.setRange(5, 1000)
        self.tracker_interval.setMaximumWidth(60)
        self.tracker_process = QLineEdit()
        self.tracker_update_wait = QSpinBox()
        self.tracker_update_wait.setRange(0, 1000)
        self.tracker_update_wait.setMaximumWidth(60)
        self.tracker_update_close = QCheckBox()
        self.tracker_update_prompt = QCheckBox()
        self.tracker_not_found_prompt = QCheckBox()

        g_media_layout.addRow('Enable tracker', self.tracker_enabled)
        g_media_layout.addRow('Tracker type', self.tracker_type)
        g_media_layout.addRow('Tracker interval (seconds)', self.tracker_interval)
        g_media_layout.addRow('Process name (regex)', self.tracker_process)
        g_media_layout.addRow('Wait before updating (seconds)', self.tracker_update_wait)
        g_media_layout.addRow('Wait until the player is closed', self.tracker_update_close)
        g_media_layout.addRow('Ask before updating', self.tracker_update_prompt)
        g_media_layout.addRow('Ask to add new shows', self.tracker_not_found_prompt)

        g_media.setLayout(g_media_layout)

        # Group: Plex settings
        g_plex = QGroupBox('Plex Media Server')
        g_plex.setFlat(True)
        self.plex_host = QLineEdit()
        self.plex_port = QLineEdit()
        self.plex_user = QLineEdit()
        self.plex_passw = QLineEdit()
        self.plex_passw.setEchoMode(QLineEdit.Password)
        self.plex_obey_wait = QCheckBox()

        g_plex_layout = QGridLayout()
        g_plex_layout.addWidget(QLabel('Host and Port'),                   0, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_host,                            0, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_port,                            0, 2, 1, 2)
        g_plex_layout.addWidget(QLabel('Use "wait before updating" time'), 1, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_obey_wait,                       1, 2, 1, 1)
        g_plex_layout.addWidget(QLabel('myPlex login (claimed server)'),   2, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_user,                            2, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_passw,                           2, 2, 1, 2)

        g_plex.setLayout(g_plex_layout)

        # Group: Library
        g_playnext = QGroupBox('Library')
        g_playnext.setFlat(True)
        self.player = QLineEdit()
        self.player_browse = QPushButton('Browse...')
        self.player_browse.clicked.connect(self.s_player_browse)
        lbl_searchdirs = QLabel('Media directories')
        lbl_searchdirs.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs = QListWidget()
        self.searchdirs_add = QPushButton('Add...')
        self.searchdirs_add.clicked.connect(self.s_searchdirs_add)
        self.searchdirs_remove = QPushButton('Remove')
        self.searchdirs_remove.clicked.connect(self.s_searchdirs_remove)
        self.searchdirs_buttons = QVBoxLayout()
        self.searchdirs_buttons.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs_buttons.addWidget(self.searchdirs_add)
        self.searchdirs_buttons.addWidget(self.searchdirs_remove)
        self.searchdirs_buttons.addWidget(QSplitter())
        self.library_autoscan = QCheckBox()
        self.scan_whole_list = QCheckBox()
        self.library_full_path = QCheckBox()


        g_playnext_layout = QGridLayout()
        g_playnext_layout.addWidget(QLabel('Player'),                    0, 0, 1, 1)
        g_playnext_layout.addWidget(self.player,                         0, 1, 1, 1)
        g_playnext_layout.addWidget(self.player_browse,                  0, 2, 1, 1)
        g_playnext_layout.addWidget(lbl_searchdirs,                      1, 0, 1, 1)
        g_playnext_layout.addWidget(self.searchdirs,                     1, 1, 1, 1)
        g_playnext_layout.addLayout(self.searchdirs_buttons,             1, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Rescan Library at startup'), 2, 0, 1, 2)
        g_playnext_layout.addWidget(self.library_autoscan,               2, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Scan through whole list'),   3, 0, 1, 2)
        g_playnext_layout.addWidget(self.scan_whole_list,                3, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Take subdirectory name into account'), 4, 0, 1, 2)
        g_playnext_layout.addWidget(self.library_full_path,              4, 2, 1, 1)

        g_playnext.setLayout(g_playnext_layout)

        # Media form
        page_media_layout.addWidget(g_media)
        page_media_layout.addWidget(g_plex)
        page_media_layout.addWidget(g_playnext)
        page_media.setLayout(page_media_layout)

        # Sync tab
        page_sync = QWidget()
        page_sync_layout = QVBoxLayout()
        page_sync_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Autoretrieve
        g_autoretrieve = QGroupBox('Autoretrieve')
        g_autoretrieve.setFlat(True)
        self.autoretrieve_off = QRadioButton('Disabled')
        self.autoretrieve_always = QRadioButton('Always at start')
        self.autoretrieve_days = QRadioButton('After n days')
        self.autoretrieve_days.toggled.connect(self.s_autoretrieve_days)
        self.autoretrieve_days_n = QSpinBox()
        self.autoretrieve_days_n.setRange(1, 100)
        g_autoretrieve_layout = QGridLayout()
        g_autoretrieve_layout.setColumnStretch(0, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_off,    0, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_always, 1, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days,   2, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days_n, 2, 1, 1, 1)
        g_autoretrieve.setLayout(g_autoretrieve_layout)

        # Group: Autosend
        g_autosend = QGroupBox('Autosend')
        g_autosend.setFlat(True)
        self.autosend_off = QRadioButton('Disabled')
        self.autosend_always = QRadioButton('Immediately after every change')
        self.autosend_minutes = QRadioButton('After n minutes')
        self.autosend_minutes.toggled.connect(self.s_autosend_minutes)
        self.autosend_minutes_n = QSpinBox()
        self.autosend_minutes_n.setRange(1, 1000)
        self.autosend_size = QRadioButton('After the queue reaches n items')
        self.autosend_size.toggled.connect(self.s_autosend_size)
        self.autosend_size_n = QSpinBox()
        self.autosend_size_n.setRange(2, 20)
        self.autosend_at_exit = QCheckBox('At exit')
        g_autosend_layout = QGridLayout()
        g_autosend_layout.setColumnStretch(0, 1)
        g_autosend_layout.addWidget(self.autosend_off,      0, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_always,   1, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes,    2, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes_n,  2, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size,     3, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size_n,   3, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_at_exit,  4, 0, 1, 1)
        g_autosend.setLayout(g_autosend_layout)

        # Group: Extra
        g_extra = QGroupBox('Additional options')
        g_extra.setFlat(True)
        self.auto_status_change = QCheckBox('Change status automatically')
        self.auto_status_change.toggled.connect(self.s_auto_status_change)
        self.auto_status_change_if_scored = QCheckBox('Change status automatically only if scored')
        self.auto_date_change = QCheckBox('Change start and finish dates automatically')
        g_extra_layout = QVBoxLayout()
        g_extra_layout.addWidget(self.auto_status_change)
        g_extra_layout.addWidget(self.auto_status_change_if_scored)
        g_extra_layout.addWidget(self.auto_date_change)
        g_extra.setLayout(g_extra_layout)

        # Sync layout
        page_sync_layout.addWidget(g_autoretrieve)
        page_sync_layout.addWidget(g_autosend)
        page_sync_layout.addWidget(g_extra)
        page_sync.setLayout(page_sync_layout)

        # UI tab
        page_ui = QWidget()
        page_ui_layout = QFormLayout()
        page_ui_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Icon
        g_icon = QGroupBox('Notification Icon')
        g_icon.setFlat(True)
        self.tray_icon = QCheckBox('Show tray icon')
        self.tray_icon.toggled.connect(self.s_tray_icon)
        self.close_to_tray = QCheckBox('Close to tray')
        self.start_in_tray = QCheckBox('Start minimized to tray')
        self.tray_api_icon = QCheckBox('Use API icon as tray icon')
        self.notifications = QCheckBox('Show notification when tracker detects new media')
        g_icon_layout = QVBoxLayout()
        g_icon_layout.addWidget(self.tray_icon)
        g_icon_layout.addWidget(self.close_to_tray)
        g_icon_layout.addWidget(self.start_in_tray)
        g_icon_layout.addWidget(self.tray_api_icon)
        g_icon_layout.addWidget(self.notifications)
        g_icon.setLayout(g_icon_layout)

        # Group: Window
        g_window = QGroupBox('Window')
        g_window.setFlat(True)
        self.remember_geometry = QCheckBox('Remember window size and position')
        self.remember_columns = QCheckBox('Remember column layouts and widths')
        self.columns_per_api = QCheckBox('Use different visible columns per API')
        g_window_layout = QVBoxLayout()
        g_window_layout.addWidget(self.remember_geometry)
        g_window_layout.addWidget(self.remember_columns)
        g_window_layout.addWidget(self.columns_per_api)
        g_window.setLayout(g_window_layout)

        # Group: Lists
        g_lists = QGroupBox('Lists')
        g_lists.setFlat(True)
        self.filter_bar_position = QComboBox()
        filter_bar_positions = [(FilterBar.PositionHidden,     'Hidden'),
                                (FilterBar.PositionAboveLists, 'Above lists'),
                                (FilterBar.PositionBelowLists, 'Below lists')]
        for (n, label) in filter_bar_positions:
            self.filter_bar_position.addItem(label, n)
        self.inline_edit = QCheckBox('Enable in-line editing')
        g_lists_layout = QFormLayout()
        g_lists_layout.addRow('Filter bar position:', self.filter_bar_position)
        g_lists_layout.addRow(self.inline_edit)
        g_lists.setLayout(g_lists_layout)

        # UI layout
        page_ui_layout.addWidget(g_icon)
        page_ui_layout.addWidget(g_window)
        page_ui_layout.addWidget(g_lists)
        page_ui.setLayout(page_ui_layout)

        # Theming tab
        page_theme = QWidget()
        page_theme_layout = QFormLayout()
        page_theme_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Episode Bar
        g_ep_bar = QGroupBox('Episode Bar')
        g_ep_bar.setFlat(True)
        self.ep_bar_style = QComboBox()
        ep_bar_styles = [(ShowsTableDelegate.BarStyleBasic,  'Basic'),
                         (ShowsTableDelegate.BarStyle04,     'Trackma'),
                         (ShowsTableDelegate.BarStyleHybrid, 'Hybrid')]
        for (n, label) in ep_bar_styles:
            self.ep_bar_style.addItem(label, n)
        self.ep_bar_style.currentIndexChanged.connect(self.s_ep_bar_style)
        self.ep_bar_text = QCheckBox('Show text label')
        g_ep_bar_layout = QFormLayout()
        g_ep_bar_layout.addRow('Style:', self.ep_bar_style)
        g_ep_bar_layout.addRow(self.ep_bar_text)
        g_ep_bar.setLayout(g_ep_bar_layout)

        # Group: Colour scheme
        g_scheme = QGroupBox('Color Scheme')
        g_scheme.setFlat(True)
        col_tabs = [('rows',     '&Row highlights'),
                    ('progress', '&Progress widget')]
        self.colors = {}
        self.colors['rows'] = [('is_playing',  'Playing'),
                               ('is_queued',   'Queued'),
                               ('new_episode', 'New Episode'),
                               ('is_airing',   'Airing'),
                               ('not_aired',   'Unaired')]
        self.colors['progress'] = [('progress_bg',       'Background'),
                                   ('progress_fg',       'Watched bar'),
                                   ('progress_sub_bg',   'Aired episodes'),
                                   ('progress_sub_fg',   'Stored episodes'),
                                   ('progress_complete', 'Complete')]
        self.color_buttons = []
        self.syscolor_buttons = []
        g_scheme_layout = QGridLayout()
        tw_scheme = QTabWidget()
        for (key, tab_title) in col_tabs:
            page = QFrame()
            page_layout = QGridLayout()
            col = 0
            # Generate widgets from the keys and values
            for (key, label) in self.colors[key]:
                self.color_buttons.append(QPushButton())
                # self.color_buttons[-1].setStyleSheet('background-color: ' + getColor(self.config['colors'][key]).name())
                self.color_buttons[-1].setFocusPolicy(QtCore.Qt.NoFocus)
                self.color_buttons[-1].clicked.connect(self.s_color_picker(key, False))
                self.syscolor_buttons.append(QPushButton('System Colors'))
                self.syscolor_buttons[-1].clicked.connect(self.s_color_picker(key, True))
                page_layout.addWidget(QLabel(label),             col, 0, 1, 1)
                page_layout.addWidget(self.color_buttons[-1],    col, 1, 1, 1)
                page_layout.addWidget(self.syscolor_buttons[-1], col, 2, 1, 1)
                col += 1
            page.setLayout(page_layout)
            tw_scheme.addTab(page, tab_title)
        g_scheme_layout.addWidget(tw_scheme)
        g_scheme.setLayout(g_scheme_layout)

        # UI layout
        page_theme_layout.addWidget(g_ep_bar)
        page_theme_layout.addWidget(g_scheme)
        page_theme.setLayout(page_theme_layout)

        # Content
        self.contents = QStackedWidget()
        self.contents.addWidget(page_media)
        self.contents.addWidget(page_sync)
        self.contents.addWidget(page_ui)
        self.contents.addWidget(page_theme)
        if pyqt_version is not 5:
            self.contents.layout().setMargin(0)

        # Bottom buttons
        bottombox = QDialogButtonBox(
            QDialogButtonBox.Ok
            | QDialogButtonBox.Apply
            | QDialogButtonBox.Cancel
        )
        bottombox.accepted.connect(self.s_save)
        bottombox.button(QDialogButtonBox.Apply).clicked.connect(self._save)
        bottombox.rejected.connect(self.reject)

        # Main layout finish
        layout.addWidget(self.category_list,  0, 0, 1, 1)
        layout.addWidget(self.contents,       0, 1, 1, 1)
        layout.addWidget(bottombox,           1, 0, 1, 2)
        layout.setColumnStretch(1, 1)

        self._load()
        self.update_colors()

        self.setLayout(layout)

    def _add_dir(self, path):
        self.searchdirs.addItem(path)

    def _load(self):
        engine = self.worker.engine
        tracker_type = self.tracker_type.findData(engine.get_config('tracker_type'))
        autoretrieve = engine.get_config('autoretrieve')
        autosend = engine.get_config('autosend')

        self.tracker_enabled.setChecked(engine.get_config('tracker_enabled'))
        self.tracker_type.setCurrentIndex(max(0, tracker_type))
        self.tracker_interval.setValue(engine.get_config('tracker_interval'))
        self.tracker_process.setText(engine.get_config('tracker_process'))
        self.tracker_update_wait.setValue(engine.get_config('tracker_update_wait_s'))
        self.tracker_update_close.setChecked(engine.get_config('tracker_update_close'))
        self.tracker_update_prompt.setChecked(engine.get_config('tracker_update_prompt'))
        self.tracker_not_found_prompt.setChecked(engine.get_config('tracker_not_found_prompt'))

        self.player.setText(engine.get_config('player'))
        self.library_autoscan.setChecked(engine.get_config('library_autoscan'))
        self.scan_whole_list.setChecked(engine.get_config('scan_whole_list'))
        self.library_full_path.setChecked(engine.get_config('library_full_path'))
        self.plex_host.setText(engine.get_config('plex_host'))
        self.plex_port.setText(engine.get_config('plex_port'))
        self.plex_obey_wait.setChecked(engine.get_config('plex_obey_update_wait_s'))
        self.plex_user.setText(engine.get_config('plex_user'))
        self.plex_passw.setText(engine.get_config('plex_passwd'))

        for path in engine.get_config('searchdir'):
            self._add_dir(path)

        if autoretrieve == 'always':
            self.autoretrieve_always.setChecked(True)
        elif autoretrieve == 'days':
            self.autoretrieve_days.setChecked(True)
        else:
            self.autoretrieve_off.setChecked(True)

        self.autoretrieve_days_n.setValue(engine.get_config('autoretrieve_days'))

        if autosend == 'always':
            self.autosend_always.setChecked(True)
        elif autosend in ('minutes', 'hours'):
            self.autosend_minutes.setChecked(True)
        elif autosend == 'size':
            self.autosend_size.setChecked(True)
        else:
            self.autosend_off.setChecked(True)

        self.autosend_minutes_n.setValue(engine.get_config('autosend_minutes'))
        self.autosend_size_n.setValue(engine.get_config('autosend_size'))

        self.autosend_at_exit.setChecked(engine.get_config('autosend_at_exit'))
        self.auto_status_change.setChecked(engine.get_config('auto_status_change'))
        self.auto_status_change_if_scored.setChecked(engine.get_config('auto_status_change_if_scored'))
        self.auto_date_change.setChecked(engine.get_config('auto_date_change'))

        self.tray_icon.setChecked(self.config['show_tray'])
        self.close_to_tray.setChecked(self.config['close_to_tray'])
        self.start_in_tray.setChecked(self.config['start_in_tray'])
        self.tray_api_icon.setChecked(self.config['tray_api_icon'])
        self.notifications.setChecked(self.config['notifications'])
        self.remember_geometry.setChecked(self.config['remember_geometry'])
        self.remember_columns.setChecked(self.config['remember_columns'])
        self.columns_per_api.setChecked(self.config['columns_per_api'])
        self.filter_bar_position.setCurrentIndex(self.filter_bar_position.findData(self.config['filter_bar_position']))
        self.inline_edit.setChecked(self.config['inline_edit'])

        self.ep_bar_style.setCurrentIndex(self.ep_bar_style.findData(self.config['episodebar_style']))
        self.ep_bar_text.setChecked(self.config['episodebar_text'])

        self.autoretrieve_days_n.setEnabled(self.autoretrieve_days.isChecked())
        self.autosend_minutes_n.setEnabled(self.autosend_minutes.isChecked())
        self.autosend_size_n.setEnabled(self.autosend_size.isChecked())
        self.close_to_tray.setEnabled(self.tray_icon.isChecked())
        self.start_in_tray.setEnabled(self.tray_icon.isChecked())
        self.notifications.setEnabled(self.tray_icon.isChecked())

        self.color_values = self.config['colors'].copy()

        self.tracker_type_change(None)

    def _save(self):
        engine = self.worker.engine

        engine.set_config('tracker_enabled',       self.tracker_enabled.isChecked())
        engine.set_config('tracker_type',          self.tracker_type.itemData(self.tracker_type.currentIndex()))
        engine.set_config('tracker_interval',      self.tracker_interval.value())
        engine.set_config('tracker_process',       str(self.tracker_process.text()))
        engine.set_config('tracker_update_wait_s', self.tracker_update_wait.value())
        engine.set_config('tracker_update_close',  self.tracker_update_close.isChecked())
        engine.set_config('tracker_update_prompt', self.tracker_update_prompt.isChecked())
        engine.set_config('tracker_not_found_prompt', self.tracker_not_found_prompt.isChecked())

        engine.set_config('player',            self.player.text())
        engine.set_config('library_autoscan',  self.library_autoscan.isChecked())
        engine.set_config('scan_whole_list', self.scan_whole_list.isChecked())
        engine.set_config('library_full_path', self.library_full_path.isChecked())
        engine.set_config('plex_host',         self.plex_host.text())
        engine.set_config('plex_port',         self.plex_port.text())
        engine.set_config('plex_obey_update_wait_s', self.plex_obey_wait.isChecked())
        engine.set_config('plex_user',         self.plex_user.text())
        engine.set_config('plex_passwd',       self.plex_passw.text())

        engine.set_config('searchdir',         [self.searchdirs.item(i).text() for i in range(self.searchdirs.count())])

        if self.autoretrieve_always.isChecked():
            engine.set_config('autoretrieve', 'always')
        elif self.autoretrieve_days.isChecked():
            engine.set_config('autoretrieve', 'days')
        else:
            engine.set_config('autoretrieve', 'off')

        engine.set_config('autoretrieve_days',   self.autoretrieve_days_n.value())

        if self.autosend_always.isChecked():
            engine.set_config('autosend', 'always')
        elif self.autosend_minutes.isChecked():
            engine.set_config('autosend', 'minutes')
        elif self.autosend_size.isChecked():
            engine.set_config('autosend', 'size')
        else:
            engine.set_config('autosend', 'off')

        engine.set_config('autosend_minutes', self.autosend_minutes_n.value())
        engine.set_config('autosend_size',  self.autosend_size_n.value())

        engine.set_config('autosend_at_exit',   self.autosend_at_exit.isChecked())
        engine.set_config('auto_status_change', self.auto_status_change.isChecked())
        engine.set_config('auto_status_change_if_scored', self.auto_status_change_if_scored.isChecked())
        engine.set_config('auto_date_change',   self.auto_date_change.isChecked())

        engine.save_config()

        self.config['show_tray'] = self.tray_icon.isChecked()
        self.config['close_to_tray'] = self.close_to_tray.isChecked()
        self.config['start_in_tray'] = self.start_in_tray.isChecked()
        self.config['tray_api_icon'] = self.tray_api_icon.isChecked()
        self.config['notifications'] = self.notifications.isChecked()
        self.config['remember_geometry'] = self.remember_geometry.isChecked()
        self.config['remember_columns'] = self.remember_columns.isChecked()
        self.config['columns_per_api'] = self.columns_per_api.isChecked()
        self.config['filter_bar_position'] = self.filter_bar_position.itemData(self.filter_bar_position.currentIndex())
        self.config['inline_edit'] = self.inline_edit.isChecked()

        self.config['episodebar_style'] = self.ep_bar_style.itemData(self.ep_bar_style.currentIndex())
        self.config['episodebar_text'] = self.ep_bar_text.isChecked()

        self.config['colors'] = self.color_values

        utils.save_config(self.config, self.configfile)

        self.saved.emit()

    def s_save(self):
        self._save()
        self.accept()

    def tracker_type_change(self, checked):
        if self.tracker_enabled.isChecked():
            self.tracker_interval.setEnabled(True)
            self.tracker_update_wait.setEnabled(True)
            self.tracker_type.setEnabled(True)
            if self.tracker_type.itemData(self.tracker_type.currentIndex()) == 'plex':
                self.plex_host.setEnabled(True)
                self.plex_port.setEnabled(True)
                self.plex_obey_wait.setEnabled(True)
                self.plex_user.setEnabled(True)
                self.plex_passw.setEnabled(True)
                self.tracker_process.setEnabled(False)
            else:
                self.tracker_process.setEnabled(True)
                self.plex_host.setEnabled(False)
                self.plex_port.setEnabled(False)
                self.plex_user.setEnabled(False)
                self.plex_passw.setEnabled(False)
                self.plex_obey_wait.setEnabled(False)
        else:
            self.tracker_type.setEnabled(False)
            self.plex_host.setEnabled(False)
            self.plex_port.setEnabled(False)
            self.plex_user.setEnabled(False)
            self.plex_passw.setEnabled(False)
            self.plex_obey_wait.setEnabled(False)
            self.tracker_process.setEnabled(False)
            self.tracker_interval.setEnabled(False)
            self.tracker_update_wait.setEnabled(False)

    def s_autoretrieve_days(self, checked):
        self.autoretrieve_days_n.setEnabled(checked)

    def s_autosend_minutes(self, checked):
        self.autosend_minutes_n.setEnabled(checked)

    def s_autosend_size(self, checked):
        self.autosend_size_n.setEnabled(checked)

    def s_tray_icon(self, checked):
        self.close_to_tray.setEnabled(checked)
        self.start_in_tray.setEnabled(checked)
        self.tray_api_icon.setEnabled(checked)
        self.notifications.setEnabled(checked)

    def s_ep_bar_style(self, index):
        if self.ep_bar_style.itemData(index) == ShowsTableDelegate.BarStyle04:
            self.ep_bar_text.setEnabled(False)
        else:
            self.ep_bar_text.setEnabled(True)

    def s_auto_status_change(self, checked):
        self.auto_status_change_if_scored.setEnabled(checked)

    def s_player_browse(self):
        if pyqt_version is 5:
            self.player.setText(QFileDialog.getOpenFileName(caption='Choose player executable')[0])
        else:
            self.player.setText(QFileDialog.getOpenFileName(caption='Choose player executable'))

    def s_searchdirs_add(self):
        self._add_dir(QFileDialog.getExistingDirectory(caption='Choose media directory'))

    def s_searchdirs_remove(self):
        row = self.searchdirs.currentRow()
        if row != -1:
            self.searchdirs.takeItem(row)

    def s_switch_page(self, new, old):
        if not new:
            new = old

        self.contents.setCurrentIndex(self.category_list.row(new))

    def s_color_picker(self, key, system):
        return lambda: self.color_picker(key, system)

    def color_picker(self, key, system):
        if system is True:
            current = self.color_values[key]
            result = ThemedColorPicker.do()
            if result is not None and result is not current:
                self.color_values[key] = result
                self.update_colors()
        else:
            current = getColor(self.color_values[key])
            result = QColorDialog.getColor(current)
            if result.isValid() and result is not current:
                self.color_values[key] = str(result.name())
                self.update_colors()

    def update_colors(self):
        for ((key, label), color) in zip(self.colors['rows']+self.colors['progress'], self.color_buttons):
            color.setStyleSheet('background-color: ' + getColor(self.color_values[key]).name())
Example #46
0
class FindDialog(QDialog):
    alphabetical = [dict(type="alphabetical", allowPseudoUnicode=True)]

    def __init__(self, currentGlyph, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Find…"))
        self.font = currentGlyph.font
        self._sortedGlyphNames = self.font.unicodeData.sortGlyphNames(self.font.keys(), self.alphabetical)

        layout = QGridLayout(self)
        self.glyphLabel = QLabel(self.tr("Glyph:"), self)
        self.glyphEdit = QLineEdit(self)
        self.glyphEdit.textChanged.connect(self.updateGlyphList)
        self.glyphEdit.event = self.lineEvent
        self.glyphEdit.keyPressEvent = self.lineKeyPressEvent

        self.beginsWithBox = QRadioButton(self.tr("Begins with"), self)
        self.containsBox = QRadioButton(self.tr("Contains"), self)
        self.beginsWithBox.setChecked(True)
        self.beginsWithBox.toggled.connect(self.updateGlyphList)

        self.glyphList = QListWidget(self)
        self.glyphList.itemDoubleClicked.connect(self.accept)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        l = 0
        layout.addWidget(self.glyphLabel, l, 0, 1, 2)
        layout.addWidget(self.glyphEdit, l, 2, 1, 4)
        l += 1
        layout.addWidget(self.beginsWithBox, l, 0, 1, 3)
        layout.addWidget(self.containsBox, l, 3, 1, 3)
        l += 1
        layout.addWidget(self.glyphList, l, 0, 1, 6)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 6)
        self.setLayout(layout)
        self.updateGlyphList()

    def lineEvent(self, event):
        if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
            if self.beginsWithBox.isChecked():
                self.containsBox.toggle()
            else:
                self.beginsWithBox.toggle()
            return True
        else:
            return QLineEdit.event(self.glyphEdit, event)

    def lineKeyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Up or key == Qt.Key_Down:
            self.glyphList.keyPressEvent(event)
        else:
            QLineEdit.keyPressEvent(self.glyphEdit, event)

    def updateGlyphList(self):
        beginsWith = self.beginsWithBox.isChecked()
        self.glyphList.clear()
        if not self.glyphEdit.isModified():
            self.glyphList.addItems(self._sortedGlyphNames)
        else:
            text = self.glyphEdit.text()
            if beginsWith:
                glyphs = [glyphName for glyphName in self._sortedGlyphNames if glyphName and glyphName.startswith(text)]
            else:
                glyphs = [glyphName for glyphName in self._sortedGlyphNames if glyphName and text in glyphName]
            self.glyphList.addItems(glyphs)
        self.glyphList.setCurrentRow(0)

    @classmethod
    def getNewGlyph(cls, parent, currentGlyph):
        dialog = cls(currentGlyph, parent)
        result = dialog.exec_()
        currentItem = dialog.glyphList.currentItem()
        newGlyph = None
        if currentItem is not None:
            newGlyphName = currentItem.text()
            if newGlyphName in dialog.font:
                newGlyph = dialog.font[newGlyphName]
        return (newGlyph, result)
class Settings(QDialog):
    # ++++++++++++++++++++++++++++ __init__ +++++++++++++++++++++++++++++++
    def __init__(self, config, parent=None):
        QDialog.__init__(self, parent)
        self.applayState = False
        self.config = config
        self.language = config['language']

        if self.language == "georgian":
            Geo_Checked = True
            Eng_Checked = False
        else:
            Geo_Checked = False
            Eng_Checked = True

        self.setWindowTitle("პარამეტრები")
        self.setWindowIcon(QtGui.QIcon("icon/setting.svg"))

        self.groupBox_language = QGroupBox("ენა")
        self.groupBox_language.setAlignment(Qt.AlignCenter)

        self.groupBox_window_size = QGroupBox("ფანჯრის ზომა")
        self.groupBox_window_size.setAlignment(Qt.AlignCenter)

        VLbox = QVBoxLayout()
        VLbox.addWidget(self.groupBox_language)
        VLbox.addWidget(self.groupBox_window_size)

        hboxLayout_language = QHBoxLayout()
        hboxLayout_size = QHBoxLayout()

        self.Edit_length = QLineEdit()
        self.Edit_width = QLineEdit()

        self.Label_length = QLabel("სიგრძე")
        self.Label_width = QLabel("სიგანე")

        self.Edit_length.setText(str(self.config['length']))
        self.Edit_width.setText(str(self.config['width']))

        hboxLayout_size.addWidget(self.Label_length)
        hboxLayout_size.addWidget(self.Edit_length)
        hboxLayout_size.addWidget(self.Label_width)
        hboxLayout_size.addWidget(self.Edit_width)

        self.Geo_radioButton = QRadioButton("ქართული")
        self.Geo_radioButton.setChecked(Geo_Checked)
        self.Geo_radioButton.setIcon(QtGui.QIcon("icon/georgia.png"))
        self.Geo_radioButton.setIconSize(QtCore.QSize(40, 40))
        self.Geo_radioButton.toggled.connect(self.geo)
        hboxLayout_language.addWidget(self.Geo_radioButton)

        self.Eng_radioButton = QRadioButton("ინგლისური")
        self.Eng_radioButton.setChecked(Eng_Checked)
        self.Eng_radioButton.setIcon(QtGui.QIcon("icon/english.png"))
        self.Eng_radioButton.setIconSize(QtCore.QSize(40, 40))
        hboxLayout_language.addWidget(self.Eng_radioButton)
        self.Eng_radioButton.toggled.connect(self.eng)

        self.ApplySet = QPushButton("დადასტურება", self)
        self.CancelSet = QPushButton("გაუქმება", self)
        self.ApplySet.clicked.connect(self.applySettings)
        self.CancelSet.clicked.connect(self.CancelSettings)

        self.groupBox_language.setLayout(hboxLayout_language)
        self.groupBox_window_size.setLayout(hboxLayout_size)

        VLbox.addWidget(self.ApplySet)
        VLbox.addWidget(self.CancelSet)

        if self.language == "georgian":
            self.geo()
        else:
            self.eng()

        self.setLayout(VLbox)
# ++++++++++++++++++++ Georgian language option +++++++++++++++++++++++

    def geo(self):
        if self.Geo_radioButton.isChecked():
            self.ApplySet.setText("დადასტურება")
            self.CancelSet.setText("გაუქმება")
            self.groupBox_language.setTitle("ენა")
            self.groupBox_window_size.setTitle("ფანჯრის ზომა")
            self.setWindowTitle("პარამეტრები")
            self.Geo_radioButton.setText("ქართული")
            self.Eng_radioButton.setText("ინგლისური")
            self.Label_length.setText("სიგრძე")
            self.Label_width.setText("სიგანე")
            self.language = "georgian"
# +++++++++++++++++++++ English language option +++++++++++++++++++++++

    def eng(self):
        if self.Eng_radioButton.isChecked():
            self.ApplySet.setText("Apply")
            self.CancelSet.setText("Cancel")
            self.groupBox_language.setTitle("Language")
            self.groupBox_window_size.setTitle("Window Size")
            self.setWindowTitle("Settings")
            self.Geo_radioButton.setText("Georgian")
            self.Eng_radioButton.setText("English")
            self.Label_length.setText("Length")
            self.Label_width.setText("width")
            self.language = "english"
# +++++++++++++++++++++++++++ get Settings ++++++++++++++++++++++++++++

    def getSettings(self):
        return self.config, self.applayState
# +++++++++++++++++++++++++ Apply Settings ++++++++++++++++++++++++++++

    def applySettings(self):
        try:
            self.config['length'] = int(self.Edit_length.text())
            self.config['width'] = int(self.Edit_width.text())
            self.config['language'] = self.language
        except ValueError:
            pass
        self.applayState = True
        self.close()


# +++++++++++++++++++++++++ Cancel Settings +++++++++++++++++++++++++++

    def CancelSettings(self):
        self.applayState = False
        self.close()
Example #48
0
class My_Main_window(QtWidgets.QDialog):
    def __init__(self, parent=None):

        super(My_Main_window, self).__init__(parent)

        # set the User Interface
        self.setWindowTitle('NN')
        self.resize(750, 400)

        # set the figure (left&right)
        self.figure_1 = Figure(figsize=(4, 4), dpi=100)
        self.canvas_1 = FigureCanvas(self.figure_1)

        # draw the initial axes of left graph
        self.ax_1 = self.figure_1.add_axes([0.1, 0.1, 0.8, 0.8])
        self.ax_1.set_xlim([0, 5])
        self.ax_1.set_ylim([0, 5])
        self.ax_1.plot()

        # set the group box
        self.file = QGroupBox("Choose Train and Test File")
        self.association = QGroupBox("Choose Association Way")
        self.show_data = QGroupBox("Choose Show Data")
        self.show_result = QGroupBox("Result of Association")

        # set the push button
        self.button_test = QPushButton("Test")
        self.button_train = QPushButton("Train")
        self.button_show = QPushButton("Show the Graph")
        self.button_original = QPushButton("Original Graph")
        self.button_association = QPushButton("Association Graph")

        # set the combo box
        self.combo_train = QComboBox()
        self.combo_test = QComboBox()
        self.combo_train.addItems(["Basic_Training.txt", "Bonus_Training.txt"])
        self.combo_test.addItems(["Basic_Testing.txt", "Bonus_Testing.txt"])

        # set the label
        self.label_train_file = QLabel()
        self.label_test_file = QLabel()
        self.label_train_data = QLabel()
        self.label_test_data = QLabel()
        self.label_correct_rate = QLabel()
        self.label_correct_text = QLabel()
        self.label_iteration_time = QLabel()
        self.label_iteration_text = QLabel()
        self.label_train_file.setText("Train File")
        self.label_test_file.setText("Test File")
        self.label_train_data.setText("Train Data No.")
        self.label_test_data.setText("Test Data No.")
        self.label_correct_rate.setText("Correct Rate")
        self.label_correct_text.setText(" -- ")
        self.label_iteration_time.setText("Iteration Time")
        self.label_iteration_text.setText(" -- ")
        self.label_correct_text.setAlignment(Qt.AlignCenter)
        self.label_iteration_text.setAlignment(Qt.AlignCenter)

        # set the button trigger
        self.button_show.clicked.connect(self.ShowResult)
        self.button_train.clicked.connect(self.TrainData)
        self.button_test.clicked.connect(self.TestData)
        self.button_original.clicked.connect(self.ShowOriginal)
        self.button_association.clicked.connect(self.ShowAssociation)

        # set the combobox trigger
        self.combo_train.activated.connect(self.SetTrainFile)
        self.combo_test.activated.connect(self.SetTestFile)

        # set the radio button
        self.radio_syn = QRadioButton("Synchronization")
        self.radio_asyn = QRadioButton("Asynchronization")
        self.radio_train = QRadioButton("Train Data")
        self.radio_test = QRadioButton("Test Data")
        self.radio_syn.setChecked(True)
        self.radio_asyn.setChecked(False)
        self.radio_train.setChecked(True)
        self.radio_test.setChecked(False)

        # set the spin box
        self.spin_train = QSpinBox()
        self.spin_test = QSpinBox()

        # set the layout
        layout = QtWidgets.QHBoxLayout()
        layout_left = QtWidgets.QVBoxLayout()
        layout_right = QtWidgets.QVBoxLayout()
        layout_right_down = QtWidgets.QHBoxLayout()
        file_layout = QFormLayout()
        association_layout = QFormLayout()
        show_layout = QFormLayout()
        result_layout = QFormLayout()

        file_layout.addRow(self.label_train_file, self.combo_train)
        file_layout.addRow(self.label_test_file, self.combo_test)

        association_layout.addRow(self.radio_syn, self.radio_asyn)
        association_layout.addRow(self.button_train, self.button_test)

        show_layout.addRow(self.radio_train, self.radio_test)
        show_layout.addRow(self.label_train_data, self.spin_train)
        show_layout.addRow(self.label_test_data, self.spin_test)

        result_layout.addRow(self.label_correct_rate, self.label_correct_text)
        result_layout.addRow(self.label_iteration_time,
                             self.label_iteration_text)

        self.file.setLayout(file_layout)
        self.association.setLayout(association_layout)
        self.show_data.setLayout(show_layout)
        self.show_result.setLayout(result_layout)

        layout_left.addWidget(self.file)
        layout_left.addWidget(self.association)
        layout_left.addWidget(self.show_data)
        layout_left.addWidget(self.show_result)
        layout_left.addWidget(self.button_show)

        layout_right_down.addWidget(self.button_original)
        layout_right_down.addWidget(self.button_association)

        layout_right.addWidget(self.canvas_1)
        layout_right.addLayout(layout_right_down)

        layout.addLayout(layout_left, 10)
        layout.addLayout(layout_right, 42)

        self.setLayout(layout)

    # process the train input and calculate the weight & theta matrix
    def SetTrainFile(self):
        self.train_input = []
        f = open(self.combo_train.currentText())
        self.train_count = int(1)
        self.row = int(0)

        self.train_input.append([])
        while 1:
            line = f.readline()
            if line == "":
                break

            line = line[:len(line)].strip("\n")
            if len(line) == 0:
                self.train_input.append([])
                if self.train_count == 1:
                    self.col = int(
                        len(self.train_input[self.train_count - 1]) / self.row)
                self.train_count = self.train_count + 1
            else:
                if self.train_count == 1:
                    self.row += 1
                for i in range(len(line)):
                    if line[i] == '1':
                        self.train_input[self.train_count - 1].append(int(1))
                    else:
                        self.train_input[self.train_count - 1].append(int(-1))

        self.dim = int(len(self.train_input[0]))
        self.weight = []
        self.theta = []

        for i in range(self.dim):
            self.weight.append([])
            for j in range(self.dim):
                self.weight[i].append(int(0))
                for k in range(self.train_count):
                    self.weight[i][j] = self.weight[i][j] + (
                        self.train_input[k][i] * self.train_input[k][j])
                ## weight[i][j]=float(weight[i][j]/dim)

        for i in range(self.dim):
            self.weight[i][i] = self.weight[i][i] - self.train_count

        self.theta = np.zeros((self.dim, ), dtype=np.int)
        ## self.theta = np.sum(self.weight, 1)

        self.spin_train.setRange(1, self.train_count)

    # process the test input
    def SetTestFile(self):
        self.test_input = []
        f = open(self.combo_test.currentText())
        self.test_count = int(1)

        self.test_input.append([])
        while 1:
            line = f.readline()
            if line == "":
                break

            line = line[:len(line)].strip("\n")
            if len(line) == 0:
                self.test_input.append([])
                self.test_count += 1
            else:
                for i in range(len(line)):
                    if line[i] == '1':
                        self.test_input[self.test_count - 1].append(int(1))
                    else:
                        self.test_input[self.test_count - 1].append(int(-1))

        self.spin_test.setRange(1, self.test_count)

    # calculate the association of train data
    def TrainData(self):
        self.train_output = []
        self.train_time = []
        self.train_rate = []

        # Synchronization
        if self.radio_syn.isChecked():
            for z in range(self.train_count):
                temp = np.copy(self.train_input[z])
                run_time = int(0)
                similar = int(0)
                correct_rate = float(0)
                while (similar != self.dim):
                    similar = int(0)
                    sigmoid_data = []
                    run_time += 1

                    for i in range(self.dim):
                        sigmoid_data.append(
                            np.dot(self.weight[i], temp) - self.theta[i])

                    for i in range(self.dim):
                        if sigmoid_data[i] < int(0):
                            if temp[i] == int(-1):
                                similar += 1
                            else:
                                temp[i] = int(-1)
                        elif sigmoid_data[i] > int(0):
                            if temp[i] == int(1):
                                similar += 1
                            else:
                                temp[i] = int(1)
                        else:
                            similar += 1

                for i in range(self.dim):
                    if temp[i] == self.train_input[z][i]:
                        correct_rate += 1

                self.train_output.append(temp)
                self.train_time.append(run_time)
                self.train_rate.append(correct_rate / self.dim)

        # Asynchronization
        else:
            for z in range(self.train_count):
                temp = np.copy(self.train_input[z])
                run_time = int(0)
                similar = True
                correct_rate = float(0)
                while similar:
                    similar = False
                    sigmoid_data = np.copy(temp)
                    run_time += 1

                    for i in range(self.dim):
                        res = np.dot(self.weight[i],
                                     sigmoid_data) - self.theta[i]
                        if res < int(0):
                            sigmoid_data[i] = int(-1)
                        elif res > int(0):
                            sigmoid_data[i] = int(1)

                    for i in range(self.dim):
                        if sigmoid_data[i] != temp[i]:
                            similar = True

                    temp = np.copy(sigmoid_data)

                for i in range(self.dim):
                    if temp[i] == self.train_input[z][i]:
                        correct_rate += 1

                self.train_output.append(temp)
                self.train_time.append(run_time)
                self.train_rate.append(correct_rate / self.dim)

    # calculate the association of test data
    def TestData(self):
        self.test_output = []
        self.test_time = []
        self.test_rate = []

        # Synchronization
        if self.radio_syn.isChecked():
            for z in range(self.test_count):
                temp = np.copy(self.test_input[z])
                run_time = int(0)
                similar = int(0)
                correct_rate = float(0)
                while (similar != self.dim):
                    similar = int(0)
                    sigmoid_data = []
                    run_time += 1

                    for i in range(self.dim):
                        sigmoid_data.append(
                            np.dot(self.weight[i], temp) - self.theta[i])

                    for i in range(self.dim):
                        if sigmoid_data[i] < int(0):
                            if temp[i] == int(-1):
                                similar += 1
                            else:
                                temp[i] = int(-1)
                        elif sigmoid_data[i] > int(0):
                            if temp[i] == int(1):
                                similar += 1
                            else:
                                temp[i] = int(1)
                        else:
                            similar += 1

                for i in range(self.dim):
                    if temp[i] == self.train_input[z][i]:
                        correct_rate += 1

                self.test_output.append(temp)
                self.test_time.append(run_time)
                self.test_rate.append(correct_rate / self.dim)

        # Asynchronization
        else:
            for z in range(self.test_count):
                temp = np.copy(self.test_input[z])
                run_time = int(0)
                similar = True
                correct_rate = float(0)
                while similar:
                    similar = False
                    sigmoid_data = np.copy(temp)
                    run_time += 1

                    for i in range(self.dim):
                        res = np.dot(self.weight[i],
                                     sigmoid_data) - self.theta[i]
                        if res < int(0):
                            sigmoid_data[i] = int(-1)
                        elif res > int(0):
                            sigmoid_data[i] = int(1)

                    for i in range(self.dim):
                        if sigmoid_data[i] != temp[i]:
                            similar = True

                    temp = np.copy(sigmoid_data)

                for i in range(self.dim):
                    if temp[i] == self.train_input[z][i]:
                        correct_rate += 1

                self.test_output.append(temp)
                self.test_time.append(run_time)
                self.test_rate.append(correct_rate / self.dim)

    # show the original graph
    def ShowOriginal(self):
        spacing = 1
        minorLocator = MultipleLocator(spacing)
        self.ax_1.cla()
        self.ax_1.set_xlim([0, self.col])
        self.ax_1.set_ylim([0, self.row])
        self.ax_1.set_title("Original Graph")
        self.ax_1.plot()
        self.ax_1.xaxis.set_minor_locator(minorLocator)
        self.ax_1.yaxis.set_minor_locator(minorLocator)
        self.ax_1.grid(which='minor')
        for i in range(self.row):
            for j in range(self.col):
                if self.graph_original[i * self.col + j] == int(1):
                    self.ax_1.add_patch(
                        patches.Rectangle(
                            (j, self.row - i - 1),  # (x,y)
                            1,  # width
                            1,  # height
                        ))
        self.canvas_1.draw()

    # show the association graph
    def ShowAssociation(self):
        spacing = 1
        minorLocator = MultipleLocator(spacing)
        self.ax_1.cla()
        self.ax_1.set_xlim([0, self.col])
        self.ax_1.set_ylim([0, self.row])
        self.ax_1.set_title("Association Graph")
        self.ax_1.plot()
        self.ax_1.xaxis.set_minor_locator(minorLocator)
        self.ax_1.yaxis.set_minor_locator(minorLocator)
        self.ax_1.grid(which='minor')
        for i in range(self.row):
            for j in range(self.col):
                if self.graph_result[i * self.col + j] == int(1):
                    self.ax_1.add_patch(
                        patches.Rectangle(
                            (j, self.row - i - 1),  # (x,y)
                            1,  # width
                            1,  # height
                        ))
        self.canvas_1.draw()

    # process the original & association graph
    def ShowResult(self):
        index = int(0)
        self.graph_original = []
        self.graph_result = []

        if self.radio_train.isChecked():
            index = self.spin_train.value() - 1
            self.label_correct_text.setText(str(self.train_rate[index]))
            self.label_iteration_text.setText(str(self.train_time[index]))
            self.graph_original = np.copy(self.train_input[index])
            self.graph_result = np.copy(self.train_output[index])
        else:
            index = self.spin_test.value() - 1
            self.label_correct_text.setText(str(self.test_rate[index]))
            self.label_iteration_text.setText(str(self.test_time[index]))
            self.graph_original = np.copy(self.test_input[index])
            self.graph_result = np.copy(self.test_output[index])

        spacing = 1
        minorLocator = MultipleLocator(spacing)
        self.ax_1.cla()
        self.ax_1.set_title("Original Graph")
        self.ax_1.set_xlim([0, self.col])
        self.ax_1.set_ylim([0, self.row])
        self.ax_1.plot()
        self.ax_1.xaxis.set_minor_locator(minorLocator)
        self.ax_1.yaxis.set_minor_locator(minorLocator)
        self.ax_1.grid(which='minor')
        for i in range(self.row):
            for j in range(self.col):
                if self.graph_original[i * self.col + j] == int(1):
                    self.ax_1.add_patch(
                        patches.Rectangle(
                            (j, self.row - i - 1),  # (x,y)
                            1,  # width
                            1,  # height
                        ))
        self.canvas_1.draw()
Example #49
0
class ImgOutPortWidget(QDialog):
    def __init__(self, fWind):
        super().__init__(fWind)
        self.fWindow = fWind

        self.thread = None
        self.tick = 0

        self.initUI()

    def initUI(self):
        self.setStyleSheet(MAIN_STYLE + IOS_RADIOBTN_STYLE)

        self.setWindowTitle('图片识别结果导出')
        self.setFixedSize(300, 200)
        """------------------layout_setting-------------------"""
        layout_setting = QVBoxLayout()
        layout_setting.setContentsMargins(0, 0, 0, 0)
        layout_setting.setSpacing(0)
        layout_setting.setAlignment(Qt.AlignCenter)

        self.settingLabel = QLabel("设置识别操作执行策略")
        self.settingLabel.setAlignment(Qt.AlignCenter)
        self.settingLabel.setFixedHeight(20)

        self.radioButton1 = QRadioButton('全部重新识别')
        self.radioButton1.setChecked(True)
        self.radioButton2 = QRadioButton('已有识别结果的直接保存')
        self.radioButton2.setFixedWidth(200)

        layout_radio = QHBoxLayout()
        layout_radio.setContentsMargins(10, 0, 0, 0)
        layout_radio.setSpacing(10)
        layout_radio.addWidget(self.radioButton1)
        layout_radio.addWidget(self.radioButton2)

        self.startBtn = QPushButton('开始')
        self.startBtn.setFixedSize(300, 30)
        self.startBtn.clicked.connect(self.on_startBtn_clicked)

        layout_setting.addStretch(2)
        layout_setting.addWidget(self.settingLabel)
        layout_setting.addStretch(2)
        layout_setting.addLayout(layout_radio)
        layout_setting.addStretch(3)
        layout_setting.addWidget(self.startBtn)
        """------------------layout_process-------------------"""
        layout_process = QVBoxLayout()
        layout_process.setContentsMargins(0, 0, 0, 0)
        layout_process.setSpacing(0)

        self.processLabel = QLabel("导出:")

        self.progressBar = QProgressBar()
        self.progressBar.setFixedSize(260, 30)
        self.progressBar.setValue(0)

        layout_progress = QVBoxLayout()
        layout_progress.setContentsMargins(20, 0, 0, 0)
        layout_progress.setSpacing(5)
        layout_progress.addWidget(self.processLabel)
        layout_progress.addWidget(self.progressBar)

        self.cancellBtn = QPushButton("取消")
        self.cancellBtn.setFixedSize(300, 30)
        self.cancellBtn.clicked.connect(self.on_cancellBtn_clicked)

        layout_process.addStretch(3)
        layout_process.addLayout(layout_progress)
        layout_process.addStretch(3)
        layout_process.addWidget(self.cancellBtn)
        """------------------layout_end-------------------"""
        layout_end = QVBoxLayout()
        layout_end.setContentsMargins(0, 0, 0, 0)
        layout_end.setSpacing(0)

        self.endLabel = QLabel("导出结束")
        self.endLabel.setAlignment(Qt.AlignCenter)

        self.endBtn = QPushButton("完成")
        self.endBtn.setFixedSize(300, 30)
        self.endBtn.clicked.connect(self.on_endBtn_clicked)

        layout_end.addWidget(self.endLabel)
        layout_end.addWidget(self.endBtn)

        self.settingWidget = QWidget(self)
        self.settingWidget.setFixedSize(300, 200)
        self.settingWidget.setHidden(False)
        self.settingWidget.setLayout(layout_setting)

        self.processWidget = QWidget(self)
        self.processWidget.setFixedSize(300, 200)
        self.processWidget.setHidden(True)
        self.processWidget.setLayout(layout_process)

        self.endWidget = QWidget(self)
        self.endWidget.setFixedSize(300, 200)
        self.endWidget.setHidden(True)
        self.endWidget.setLayout(layout_end)

        self.exec()

    def on_startBtn_clicked(self):
        self.tick = time.time()
        self.settingWidget.setHidden(True)
        self.processWidget.setHidden(False)

        pattern = 0
        if self.radioButton2.isChecked():
            pattern = 1

        # 创建线程
        self.thread = OutportImgThread(self.fWindow, pattern)
        # 连接信号
        self.thread._signal.connect(self.call_backlog)  # 进程连接回传到GUI的事件
        # 开始线程
        self.thread.start()

    def on_cancellBtn_clicked(self):
        self.thread.cancell = True
        self.close()

    def on_endBtn_clicked(self):
        self.close()

    def call_backlog(self, msg):
        if msg == 'end':
            del self.thread
            cost_time = time.time() - self.tick
            self.endLabel.setText("导出结束\n用时:" + TickTimeProcess(cost_time))
            self.processWidget.setHidden(True)
            self.endWidget.setHidden(False)
            return

        checked_index = int(msg)
        checked_length = len(self.fWindow.checkedlist)
        file_index = self.fWindow.checkedlist[checked_index]
        file_name = self.fWindow.filelist[file_index].file_name
        self.processLabel.setText("导出:" + file_name)
        self.progressBar.setValue(
            int((checked_index + 1) / checked_length * 100))  # 将线程的参数传入进度条
class ExchangeQueuesBindingsMenu(QtWidgets.QMainWindow):

    _refresh = QtCore.pyqtSignal(bool)

    def __init__(self, parser, resources_path):
        #super().__init__()
        super(ExchangeQueuesBindingsMenu, self).__init__()

        __IMAGES_PATH__ = resources_path + '/images'

        self.setWindowTitle("RabbitMQ Utility - Add Exchange/Queues/Bindings"
                            )  # Set the window title

        #self.setWindowIcon(QtGui.QIcon(__IMAGES_PATH__ + '/rabbit_icon.jpg'))

        self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint
                            | QtCore.Qt.WindowCloseButtonHint)
        #------------------------------
        #self.app = app

        self.sessionAvailable = False

        self.session = None

        self.eqbConnection = None

        self.elist = None
        self.qlist = None

        self.exchangeadd = False
        self.queueadd = False
        self.bindadd = False

        self.parser = parser
        #------------------------------
        self.qapp = QApplication([])
        #V = self.qapp.desktop().screenGeometry()
        #h = V.height() - 600
        #w = V.width() - 600

        h = 800
        w = 800

        self.resize(w, h)

        #self.login = LoginDialog(self.parser)
        self.login = ConnectMenu(self.parser, resources_path)

        self.login._cancelled.connect(self.loginCancelled)

        self.login._webUrl.connect(self.getWebConnectionUrl)
        self.login._commandUrl.connect(self.getCommandConnectionUrl)
        self.login._userId.connect(self.getConnectionUser)
        self.login._password.connect(self.getConnectionPassword)
        self.login._vhost.connect(self.getConnectionVhost)
        self.login._certName.connect(self.getConnectionCertName)
        self.login._certPass.connect(self.getConnectionCertPass)

        self.loginmw = windows.ModernWindow(self.login, self.parser)

        self.widget = QWidget()

        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)

        self.fromParent = False

        self.frame = None

        #----------------------------------------- MENU BAR -------------------------------------------------
        # Create Connect
        self.connectAction = QAction(QIcon(__IMAGES_PATH__ + '/connect.png'),
                                     '&Connect', self)
        self.connectAction.setShortcut('ALT+C')
        self.connectAction.setStatusTip('Connect')
        self.connectAction.triggered.connect(self.show_login)
        self.connectAction.setEnabled(False)

        # Create Disconnect
        self.disconnectAction = QAction(
            QIcon(__IMAGES_PATH__ + '/disconnect.png'), '&DisConnect', self)
        self.disconnectAction.setShortcut('ALT+D')
        self.disconnectAction.setStatusTip('Disconnect')
        self.disconnectAction.triggered.connect(self.disconnect)

        # Create Refresh
        self.refreshAction = QAction(QIcon(__IMAGES_PATH__ + '/refresh.png'),
                                     '&Refresh', self)
        self.refreshAction.setShortcut('ALT+D')
        self.refreshAction.setStatusTip('Refresh')
        self.refreshAction.triggered.connect(self.refresh)

        # Create Exit action
        self.exitAction = QAction(QIcon(__IMAGES_PATH__ + '/terminate.png'),
                                  '&Exit', self)
        self.exitAction.setShortcut('Ctrl+Q')
        self.exitAction.setStatusTip('Exit application')
        self.exitAction.triggered.connect(self.closewin)

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(self.connectAction)
        fileMenu.addAction(self.disconnectAction)
        fileMenu.addAction(self.refreshAction)
        fileMenu.addAction(self.exitAction)

        self.toolbar = self.addToolBar('')
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.toolbar.setFloatable(False)
        self.toolbar.setMovable(False)

        #self.toolbar.setIconSize(QSize(50,50))
        #self.toolbar.setGeometry(100, 100, 400, 400)

        #------------ Connect -------------
        self.loginButton = QAction(QIcon(__IMAGES_PATH__ + '/connect.png'),
                                   '&Connect', self)
        self.loginButton.setIconText('Connect')
        self.loginButton.triggered.connect(self.show_login)
        self.loginButton.setEnabled(False)
        self.loginButton.setStatusTip("Click here to login into server")
        self.toolbar.addAction(self.loginButton)

        #------------ Refresh -------------
        self.refreshButton = QAction(QIcon(__IMAGES_PATH__ + '/refresh.png'),
                                     '&Refresh', self)
        self.refreshButton.triggered.connect(self.refresh)
        self.refreshButton.setStatusTip("Click here to refresh data")
        self.toolbar.addAction(self.refreshButton)

        self.toolbar.addSeparator()

        #------------ Disconnect -------------
        self.disconnectButton = QAction(
            QIcon(__IMAGES_PATH__ + '/disconnect.png'), '&Disconnect', self)
        self.disconnectButton.triggered.connect(self.disconnect)
        self.disconnectButton.setStatusTip(
            "Click here to disconnect from server")
        self.toolbar.addAction(self.disconnectButton)

        #------------ Exit -------------
        self.exitButton = QAction(QIcon(__IMAGES_PATH__ + '/terminate.png'),
                                  '&Exit', self)
        self.exitButton.triggered.connect(self.closewin)
        self.exitButton.setStatusTip(
            "Click here to close and exit this application")
        self.toolbar.addAction(self.exitButton)

        vBoxEQB = QVBoxLayout()

        #---------------- Top ----------------------------------
        hboxEQB1 = QHBoxLayout()
        vboxEx = QVBoxLayout()
        vboxQ = QVBoxLayout()

        self.xgroupBox = QGroupBox("Add a new exchange")

        layoutEx = QFormLayout()

        self.evhostLabel = QLabel("Virtual Host:")
        self.evhost = QComboBox()

        self.exNameLabel = QLabel("Name:")
        self.exName = QLineEdit()
        self.exName.textChanged[str].connect(
            lambda: self.addExchangeButton.setEnabled(self.exName.text() != ""
                                                      ))
        self.exName.textChanged[str].connect(
            lambda: self.delExchangeButton.setEnabled(self.exName.text() != ""
                                                      ))

        self.exTypeLabel = QLabel("Type:")
        self.exType = QComboBox()
        self.durabilityLabel = QLabel("Durability")
        self.durability = QComboBox()
        self.durability.addItem("Durable")
        self.durability.addItem("Transient")

        self.autoDeleteLabel = QLabel("Auto Delete?:")
        self.autoDelete = QComboBox()
        self.autoDelete.addItem("No")
        self.autoDelete.addItem("Yes")

        self.internalLabel = QLabel("Internal?:")
        self.internal = QComboBox()
        self.internal.addItem("No")
        self.internal.addItem("Yes")

        self.addExchangeButton = QPushButton("Add exchange")
        self.addExchangeButton.setObjectName('addExchange')
        self.addExchangeButton.clicked.connect(self.buttonClicked)
        self.addExchangeButton.setEnabled(False)

        self.delExchangeButton = QPushButton("Delete exchange")
        self.delExchangeButton.setObjectName('delExchange')
        self.delExchangeButton.clicked.connect(self.buttonClicked)
        self.delExchangeButton.setEnabled(False)

        self.exArgsGroupBox = QGroupBox("Arguments")

        vboxexargstable = QVBoxLayout()

        hboxbuttonexargs = QHBoxLayout()

        self.exArgsAddButton = QPushButton("")
        self.exArgsDelButton = QPushButton("")

        self.exArgsAddButton.setIcon(QIcon(__IMAGES_PATH__ + '/addrow.png'))
        self.exArgsAddButton.setIconSize(QSize(25, 25))

        self.exArgsDelButton.setIcon(QIcon(__IMAGES_PATH__ + '/deleterow.png'))
        self.exArgsDelButton.setIconSize(QSize(25, 25))

        self.exArgsAddButton.setObjectName('addExArgsKey')
        self.exArgsDelButton.setObjectName('delExArgsKey')
        self.exArgsDelButton.setEnabled(False)
        self.exArgsAddButton.clicked.connect(self.buttonClicked)
        self.exArgsDelButton.clicked.connect(self.buttonClicked)

        hboxbuttonexargs.addWidget(QLabel("      "))
        hboxbuttonexargs.addWidget(QLabel("      "))
        hboxbuttonexargs.addWidget(QLabel("      "))
        hboxbuttonexargs.addWidget(QLabel("      "))
        hboxbuttonexargs.addWidget(self.exArgsAddButton)
        hboxbuttonexargs.addWidget(self.exArgsDelButton)

        vboxexargstable.addLayout(hboxbuttonexargs)

        headers = ["Key", "Value"]
        datainex = []

        self.exargstablemodel = TableModel(datainex, headers, self)
        self.exargstablemodelview = QTableView()
        self.exargstablemodelview.setSelectionMode(
            QAbstractItemView.SingleSelection)

        self.exargstablemodelview.clicked.connect(
            self.showTableSelectedRowColumn)

        self.set_table_view_attributes(self.exargstablemodelview,
                                       self.exargstablemodel, datainex)

        vboxexargstable.addWidget(self.exargstablemodelview)

        self.exArgsGroupBox.setLayout(vboxexargstable)

        layoutEx.addRow(self.evhostLabel, self.evhost)
        layoutEx.addRow(self.exNameLabel, self.exName)
        layoutEx.addRow(self.exTypeLabel, self.exType)
        layoutEx.addRow(self.durabilityLabel, self.durability)
        layoutEx.addRow(self.autoDeleteLabel, self.autoDelete)
        layoutEx.addRow(self.internalLabel, self.internal)
        layoutEx.addRow(self.exArgsGroupBox)

        exbuttonlayout = QHBoxLayout()
        exbuttonlayout.addWidget(self.addExchangeButton)
        exbuttonlayout.addWidget(self.delExchangeButton)
        exbuttonlayout.addWidget(QLabel(""))

        layoutEx.addRow(exbuttonlayout)

        self.xgroupBox.setLayout(layoutEx)

        vboxEx.addWidget(self.xgroupBox)
        hboxEQB1.addLayout(vboxEx, 0)

        #------------- Queue --------------------------------------------

        self.qgroupBox = QGroupBox("Add a new queue")

        layoutQ = QFormLayout()

        self.qvhostLabel = QLabel("Virtual Host:")
        self.qvhost = QComboBox()

        self.qNameLabel = QLabel("Name:")
        self.qName = QLineEdit()
        self.qName.textChanged[str].connect(
            lambda: self.addQueueButton.setEnabled(self.qName.text() != ""))
        self.qName.textChanged[str].connect(
            lambda: self.delQueueButton.setEnabled(self.qName.text() != ""))
        self.qName.textChanged[str].connect(
            lambda: self.purgeQueueButton.setEnabled(self.qName.text() != ""))

        #self.qNodeLabel = QLabel("Node:")
        #self.qNode = QComboBox()

        self.qDurabilityLabel = QLabel("Durability")
        self.qDurability = QComboBox()
        self.qDurability.addItem("Durable")
        self.qDurability.addItem("Transient")

        self.qAutoDeleteLabel = QLabel("Auto Delete?:")
        self.qAutoDelete = QComboBox()
        self.qAutoDelete.addItem("No")
        self.qAutoDelete.addItem("Yes")

        self.addQueueButton = QPushButton("Add queue")
        self.addQueueButton.setObjectName('addQueue')
        self.addQueueButton.clicked.connect(self.buttonClicked)
        self.addQueueButton.setEnabled(False)

        self.delQueueButton = QPushButton("Delete queue")
        self.delQueueButton.setObjectName('delQueue')
        self.delQueueButton.clicked.connect(self.buttonClicked)
        self.delQueueButton.setEnabled(False)

        self.purgeQueueButton = QPushButton("Purge queue")
        self.purgeQueueButton.setObjectName('purgeQueue')
        self.purgeQueueButton.clicked.connect(self.buttonClicked)
        self.purgeQueueButton.setEnabled(False)

        self.qArgsGroupBox = QGroupBox("Arguments")

        vboxqargstable = QVBoxLayout()

        hboxbuttonqargs = QHBoxLayout()

        self.qArgsAddButton = QPushButton("")
        self.qArgsDelButton = QPushButton("")

        self.qArgsAddButton.setIcon(QIcon(__IMAGES_PATH__ + '/addrow.png'))
        self.qArgsAddButton.setIconSize(QSize(25, 25))

        self.qArgsDelButton.setIcon(QIcon(__IMAGES_PATH__ + '/deleterow.png'))
        self.qArgsDelButton.setIconSize(QSize(25, 25))

        self.qArgsAddButton.setObjectName('addQArgsKey')
        self.qArgsDelButton.setObjectName('delQArgsKey')
        self.qArgsDelButton.setEnabled(False)
        self.qArgsAddButton.clicked.connect(self.buttonClicked)
        self.qArgsDelButton.clicked.connect(self.buttonClicked)

        hboxbuttonqargs.addWidget(QLabel("      "))
        hboxbuttonqargs.addWidget(QLabel("      "))
        hboxbuttonqargs.addWidget(QLabel("      "))
        hboxbuttonqargs.addWidget(QLabel("      "))
        hboxbuttonqargs.addWidget(self.qArgsAddButton)
        hboxbuttonqargs.addWidget(self.qArgsDelButton)

        vboxqargstable.addLayout(hboxbuttonqargs)

        headers = ["Key", "Value"]
        datainq = []

        self.qargstablemodel = TableModel(datainq, headers, self)
        self.qargstablemodelview = QTableView()
        self.qargstablemodelview.setSelectionMode(
            QAbstractItemView.SingleSelection)

        self.qargstablemodelview.clicked.connect(
            self.showTableSelectedRowColumn)

        self.set_table_view_attributes(self.qargstablemodelview,
                                       self.qargstablemodel, datainq)

        vboxqargstable.addWidget(self.qargstablemodelview)

        self.qArgsGroupBox.setLayout(vboxqargstable)

        layoutQ.addRow(self.qvhostLabel, self.qvhost)
        layoutQ.addRow(self.qNameLabel, self.qName)
        layoutQ.addRow(self.qDurabilityLabel, self.qDurability)
        #layoutQ.addRow(self.qNodeLabel, self.qNode)
        layoutQ.addRow(self.qAutoDeleteLabel, self.qAutoDelete)
        layoutQ.addRow(QLabel(""), QLabel(""))
        layoutQ.addRow(QLabel(""), QLabel(""))
        layoutQ.addRow(self.qArgsGroupBox)

        qbuttonlayout = QHBoxLayout()
        qbuttonlayout.addWidget(self.addQueueButton)
        qbuttonlayout.addWidget(self.delQueueButton)
        qbuttonlayout.addWidget(self.purgeQueueButton)

        layoutQ.addRow(qbuttonlayout)

        self.qgroupBox.setLayout(layoutQ)

        vboxQ.addWidget(self.qgroupBox)
        hboxEQB1.addLayout(vboxQ, 0)

        #-------------------  Bottom ----------------------
        hboxEQB2 = QHBoxLayout()

        layoutBinding = QFormLayout()

        self.bindinggroupBox = QGroupBox("Add a new binding")

        self.exchange2queue = QRadioButton("Exchange to Queue")
        self.exchange2exchange = QRadioButton("Exchange to Exchange")

        self.exchange2queue.setChecked(True)

        self.exchange2queue.toggled.connect(
            lambda: self.btnstate(self.exchange2queue))
        self.exchange2exchange.toggled.connect(
            lambda: self.btnstate(self.exchange2exchange))

        self.sourceLabel = QLabel("Source:")
        self.source = QComboBox()

        self.targetLabel = QLabel("Target:")
        self.target = QComboBox()

        self.target.currentIndexChanged['QString'].connect(
            lambda: self.addBindButton.setEnabled(self.target.currentText() !=
                                                  self.source.currentText()))
        self.target.currentIndexChanged['QString'].connect(
            lambda: self.addUnbindButton.setEnabled(self.target.currentText(
            ) != self.source.currentText()))

        self.rkeyLabel = QLabel("Routing Key:")
        self.rkey = QLineEdit()

        self.addBindButton = QPushButton("Bind")
        self.addBindButton.setObjectName('addBind')
        self.addBindButton.setEnabled(False)
        self.addBindButton.clicked.connect(self.buttonClicked)

        self.addUnbindButton = QPushButton("UnBind")
        self.addUnbindButton.setObjectName('unBind')
        self.addUnbindButton.setEnabled(False)
        self.addUnbindButton.clicked.connect(self.buttonClicked)

        self.bindingArgsGroupBox = QGroupBox("Arguments")

        vboxbindingargstable = QVBoxLayout()

        hboxbuttonbindingargs = QHBoxLayout()

        self.bindingArgsAddButton = QPushButton("")
        self.bindingArgsDelButton = QPushButton("")

        self.bindingArgsAddButton.setIcon(
            QIcon(__IMAGES_PATH__ + '/addrow.png'))
        self.bindingArgsAddButton.setIconSize(QSize(25, 25))

        self.bindingArgsDelButton.setIcon(
            QIcon(__IMAGES_PATH__ + '/deleterow.png'))
        self.bindingArgsDelButton.setIconSize(QSize(25, 25))

        self.bindingArgsAddButton.setObjectName('addBindArgsKey')
        self.bindingArgsDelButton.setObjectName('delBindArgsKey')
        self.bindingArgsDelButton.setEnabled(False)

        self.bindingArgsAddButton.clicked.connect(self.buttonClicked)
        self.bindingArgsDelButton.clicked.connect(self.buttonClicked)

        hboxbuttonbindingargs.addWidget(QLabel("      "))
        hboxbuttonbindingargs.addWidget(QLabel("      "))
        hboxbuttonbindingargs.addWidget(QLabel("      "))
        hboxbuttonbindingargs.addWidget(QLabel("      "))
        hboxbuttonbindingargs.addWidget(self.bindingArgsAddButton)
        hboxbuttonbindingargs.addWidget(self.bindingArgsDelButton)

        headers = ["Key", "Value"]
        datainbinding = []

        self.bindingargstablemodel = TableModel(datainbinding, headers, self)
        self.bindingargstablemodelview = QTableView()
        self.bindingargstablemodelview.setSelectionMode(
            QAbstractItemView.SingleSelection)

        self.bindingargstablemodelview.clicked.connect(
            self.showTableSelectedRowColumn)

        self.set_table_view_attributes(self.bindingargstablemodelview,
                                       self.bindingargstablemodel,
                                       datainbinding)

        self.bindingArgsGroupBox.setLayout(vboxbindingargstable)

        vboxbindingargstable.addLayout(hboxbuttonbindingargs)
        vboxbindingargstable.addWidget(self.bindingargstablemodelview)

        layoutBinding.addRow(self.exchange2queue, self.exchange2exchange)
        layoutBinding.addRow(self.sourceLabel, self.source)
        layoutBinding.addRow(self.targetLabel, self.target)
        layoutBinding.addRow(self.rkeyLabel, self.rkey)
        layoutBinding.addRow(self.bindingArgsGroupBox)

        bindbuttonlayout = QHBoxLayout()
        bindbuttonlayout.addWidget(self.addBindButton)
        bindbuttonlayout.addWidget(self.addUnbindButton)

        layoutBinding.addRow(bindbuttonlayout)

        self.bindinggroupBox.setLayout(layoutBinding)

        hboxEQB2.addWidget(self.bindinggroupBox)

        vBoxEQB.addLayout(hboxEQB1)
        vBoxEQB.addLayout(hboxEQB2)

        self.widget.setLayout(vBoxEQB)

        self.setCentralWidget(self.widget)

    def set_table_view_attributes(self, table_view, table_model, data):

        table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
        table_view.setAlternatingRowColors(True)
        table_view.setModel(table_model)
        table_view.setSortingEnabled(True)

        # hide vertical header
        vh = table_view.verticalHeader()
        vh.setVisible(False)
        #vh.setSectionResizeMode(QHeaderView.Stretch)
        #vh.setDefaultSectionSize(75)

        hh = table_view.horizontalHeader()
        #hh.setSectionResizeMode(QHeaderView.Stretch)
        hh.setStretchLastSection(True)
        hh.setSectionsClickable(True)
        hh.setHighlightSections(True)

    def showTableSelectedRowColumn(self, index):
        if self.exchangeadd:
            self.exArgsDelButton.setEnabled(True)

        if self.queueadd:
            self.qArgsDelButton.setEnabled(True)

        if self.bindadd:
            self.bindingArgsDelButton.setEnabled(True)

        self.tableSelectedRow = index.row()
        self.tableSelectedColumn = index.column()

    def btnstate(self, b):
        if b.text() == "Exchange to Queue":
            if b.isChecked() == True:
                self.target.clear()
                for item in self.qlist:
                    name = item["name"]
                    if len(name) == 0 or name.find(
                            self._userId.lower().replace("_", "")) > -1:
                        if (len(name) != 0):
                            self.target.addItem(str(name))

        if b.text() == "Exchange to Exchange":
            if b.isChecked() == True:
                self.target.clear()
                for item in self.elist:
                    name = item["name"]
                    if len(name) == 0 or name.find(
                            self._userId.lower().replace("_", "")) > -1:
                        if (len(name) != 0):
                            self.target.addItem(str(name))

    def buttonClicked(self):
        button = self.sender()
        #print(button.objectName())

        if not button: return

        buttonObjectName = button.objectName()

        exTableModel = self.exargstablemodelview.model()
        qTableModel = self.qargstablemodelview.model()
        bindingTableModel = self.bindingargstablemodelview.model()

        if buttonObjectName == "addExArgsKey":
            data = [[]]
            self.addRow(exTableModel, data)
            self.exchangeadd = True
        elif buttonObjectName == "delExArgsKey":
            del exTableModel.arraydata[self.tableSelectedRow]
            exTableModel.changeData(exTableModel.arraydata)

            self.exArgsDelButton.setEnabled(False)
        elif buttonObjectName == "addQArgsKey":
            data1 = [[]]
            self.addRow(qTableModel, data1)
            self.queueadd = True
        elif buttonObjectName == "delQArgsKey":
            del qTableModel.arraydata[self.tableSelectedRow]
            qTableModel.changeData(qTableModel.arraydata)

            self.qArgsDelButton.setEnabled(False)
        elif buttonObjectName == "addBindArgsKey":
            data2 = [[]]
            self.addRow(bindingTableModel, data2)
            self.bindadd = True
        elif buttonObjectName == "delBindArgsKey":
            del bindingTableModel.arraydata[self.tableSelectedRow]
            bindingTableModel.changeData(bindingTableModel.arraydata)

            self.bindingArgsDelButton.setEnabled(False)
        elif buttonObjectName == "addExchange":
            #exchange_declare(exchange, exchange_type='direct', passive=False, durable=False, auto_delete=False, internal=False, arguments=None, callback=None)

            exchange = self.exName.text()
            exchange_type = str(self.exType.currentText())
            durable = True if str(
                self.durability.currentText()) == "Durable" else False
            auto_delete = False if str(
                self.autoDelete.currentText()) == "No" else True
            internal = False if str(
                self.internal.currentText()) == "No" else True

            exTableModel.removeRowsWithEmptyColumns()
            arguments = dict(exTableModel.arraydata)
            if arguments == {}:
                arguments = None

            #print(exchange, exchange_type, durable, auto_delete, internal, arguments)
            try:
                channel = self.eqbConnection.channel()
                channel.exchange_declare(exchange=exchange,
                                         exchange_type=exchange_type,
                                         durable=durable,
                                         auto_delete=auto_delete,
                                         internal=internal,
                                         arguments=arguments)
                if channel.is_open:
                    channel.close()

                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Exchange",
                    "Exchange Created!",
                    "{exch} has been created.".format(exch=exchange))

                self.elist = RestFunctions.exchange_list(
                    RestFunctions, self, self.sessionAvailable, self.session,
                    self._webUrl, self._userId, self._password, self._certName)

                for item in self.elist:
                    name = item["name"]
                    if len(name) == 0 or name.find(
                            self._userId.lower().replace("_", "")) > -1:
                        if (len(name) != 0):
                            self.source.addItem(str(name))
                self._refresh.emit(True)
            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip(
                ) + ". Check Queue naming policy with your administrator."
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Exchange Creation - Error ({})".format(error[0]),
                    text, infoText)

        elif buttonObjectName == "delExchange":
            #exchange_delete(exchange=None, if_unused=False, callback=None)
            try:
                channel = self.eqbConnection.channel()

                exchange = self.exName.text()
                exch_exist = channel.exchange_declare(exchange=exchange,
                                                      passive=True)

                if exch_exist:
                    channel.exchange_delete(exchange=exchange)

                    MessageBox.message(
                        QMessageBox.Information, "RabbitMQ Exchange",
                        "Exchange Deleted!",
                        "{exch} has been deleted.".format(exch=exchange))

                    self.elist = RestFunctions.exchange_list(
                        RestFunctions, self, self.sessionAvailable,
                        self.session, self._webUrl, self._userId,
                        self._password, self._certName)

                    for item in self.elist:
                        name = item["name"]
                        if len(name) == 0 or name.find(
                                self._userId.lower().replace("_", "")) > -1:
                            if (len(name) != 0):
                                self.source.addItem(str(name))
                    self._refresh.emit(True)

                if channel.is_open:
                    channel.close()

            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip()
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Exchange Deletion - Error ({})".format(error[0]),
                    text, infoText)
        elif buttonObjectName == "addQueue":
            queue = self.qName.text()
            durable = True if str(
                self.qDurability.currentText()) == "Durable" else False
            auto_delete = False if str(
                self.qAutoDelete.currentText()) == "No" else True

            qTableModel.removeRowsWithEmptyColumns()
            arguments = dict(qTableModel.arraydata)

            if arguments == {}:
                arguments = None

            try:
                channel = self.eqbConnection.channel()

                channel.queue_declare(queue=queue,
                                      durable=durable,
                                      auto_delete=auto_delete,
                                      arguments=arguments)
                if channel.is_open:
                    channel.close()

                MessageBox.message(QMessageBox.Information, "RabbitMQ Queue",
                                   "Queue Created!",
                                   "{que} has been added.".format(que=queue))

                self.qlist = RestFunctions.queue_list(
                    RestFunctions, self, self.sessionAvailable, self.session,
                    self._webUrl, self._userId, self._password, self._certName)
                for item in self.qlist:
                    name = item["name"]
                    if len(name) == 0 or name.find(
                            self._userId.lower().replace("_", "")) > -1:
                        if (len(name) != 0):
                            self.target.addItem(str(name))
                self._refresh.emit(True)
            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip(
                ) + ". Check Queue naming policy with your administrator."
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Queue Creation - Error ({})".format(error[0]),
                    text, infoText)

        elif buttonObjectName == "delQueue":
            try:
                channel = self.eqbConnection.channel()
                queue = self.qName.text()

                queue_exist = channel.queue_declare(queue=queue, passive=True)

                if queue_exist:
                    channel.queue_delete(queue=queue)

                    MessageBox.message(
                        QMessageBox.Information, "RabbitMQ Queue",
                        "Queue Deleted!",
                        "{que} has been deleted.".format(que=queue))

                    self.qlist = RestFunctions.queue_list(
                        RestFunctions, self, self.sessionAvailable,
                        self.session, self._webUrl, self._userId,
                        self._password, self._certName)
                    for item in self.qlist:
                        name = item["name"]
                        if len(name) == 0 or name.find(
                                self._userId.lower().replace("_", "")) > -1:
                            if (len(name) != 0):
                                self.target.addItem(str(name))
                    self._refresh.emit(True)

                if channel.is_open:
                    channel.close()

            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip()
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Queue Deletion - Error ({})".format(error[0]),
                    text, infoText)
            self._refresh.emit(True)
        elif buttonObjectName == "purgeQueue":
            try:
                channel = self.eqbConnection.channel()
                queue = self.qName.text()

                queue_exist = channel.queue_declare(queue=queue, passive=True)

                if queue_exist:
                    channel.queue_purge(queue=queue)

                    MessageBox.message(
                        QMessageBox.Information, "RabbitMQ Queue",
                        "Queue Purged!",
                        "{que} has been purged.".format(que=queue))

                    self._refresh.emit(True)
                if channel.is_open:
                    channel.close()
            except Exception as e:
                error = str(e).strip().replace("(", "").replace(")",
                                                                "").split(",")
                textandinfo = error[1].replace("\"", "").split("-")
                text = textandinfo[0].replace("\"", "").strip()
                infoText = textandinfo[1].replace("\"", "").strip()
                MessageBox.message(
                    QMessageBox.Critical,
                    "RabbitMQ Queue Purge - Error ({})".format(error[0]), text,
                    infoText)

        elif buttonObjectName == "addBind":

            destination = self.target.currentText()
            source = self.source.currentText()
            routing_key = self.rkey.text()

            bindingTableModel.removeRowsWithEmptyColumns()
            arguments = dict(bindingTableModel.arraydata)
            if arguments == {}:
                arguments = None

            if self.exchange2exchange.isChecked():

                if len(routing_key) == 0:
                    routing_key = ''

                channel = self.eqbConnection.channel()
                channel.exchange_bind(destination=destination,
                                      source=source,
                                      routing_key=routing_key,
                                      arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Binding",
                    "Exchange to Exchange Binding!",
                    "Binding created between Exchange:{exch1} and Exchange:{exch2}."
                    .format(exch1=destination, exch2=source))

                self._refresh.emit(True)

                if channel.is_open:
                    channel.close()
            elif self.exchange2queue.isChecked():
                if len(routing_key) == 0:
                    routing_key = None

                channel = self.eqbConnection.channel()
                channel.queue_bind(queue=destination,
                                   exchange=source,
                                   routing_key=routing_key,
                                   arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ Binding",
                    "Queue to Exchange Binding!",
                    "Binding created between Queue:{que} and Exchange:{exch1}."
                    .format(que=destination, exch1=source))
                self._refresh.emit(True)
                if channel.is_open:
                    channel.close()

        elif buttonObjectName == "unBind":

            destination = self.target.currentText()
            source = self.source.currentText()
            routing_key = self.rkey.text()

            bindingTableModel.removeRowsWithEmptyColumns()
            arguments = dict(bindingTableModel.arraydata)
            if arguments == {}:
                arguments = None

            if self.exchange2exchange.isChecked():

                if len(routing_key) == 0:
                    routing_key = ''

                channel = self.eqbConnection.channel()
                channel.exchange_unbind(destination=destination,
                                        source=source,
                                        routing_key=routing_key,
                                        arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ UnBinding",
                    "Exchange to Exchange UnBinding!",
                    "Binding removed between Exchange:{exch1} and Exchange:{exch2}."
                    .format(exch1=destination, exch2=source))

                self._refresh.emit(True)
                if channel.is_open:
                    channel.close()
            elif self.exchange2queue.isChecked():

                if len(routing_key) == 0:
                    routing_key = None

                channel = self.eqbConnection.channel()
                channel.queue_unbind(queue=destination,
                                     exchange=source,
                                     routing_key=routing_key,
                                     arguments=arguments)
                MessageBox.message(
                    QMessageBox.Information, "RabbitMQ UnBinding",
                    "Queue to Exchange UnBinding!",
                    "Binding removed between Queue:{que} and Exchange:{exch1}."
                    .format(que=destination, exch1=source))
                self._refresh.emit(True)
                if channel.is_open:
                    channel.close()

    def addRow(self, table_model, data):
        rowcount = table_model.rowCount()
        if rowcount == 0:
            table_model.update(rowcount, data)
        else:
            if len(table_model.arraydata[rowcount - 1][0]) != 0:
                table_model.update(rowcount, data)

    def show_login(self):
        self.login.show()
        self.loginmw.show()
        self.login.setReference(self.loginmw)

    def disconnect(self):
        self.reset()

        if self.session is not None:
            print("Closing Request Session - EQB")
            self.session.close()

        if self.login is not None:
            print("Closing Connection Information Dialog - EQB")
            self.login.close()

        if self.eqbConnection is not None and not self.fromParent:
            print("Closing AMQP Connection - EQB")
            self.eqbConnection.close()
        else:
            self.eqbConnection = None

        self.connectAction.setEnabled(True)
        self.loginButton.setEnabled(True)

    def reset(self):
        self.evhost.clear()
        self.exName.setText("")
        self.exType.clear()

        self.qvhost.clear()
        self.qName.setText("")

        #self.qNode.clear()

        self.source.clear()
        self.target.clear()
        self.rkey.setText("")

        edata = []
        self.exargstablemodelview.model().changeData(edata)

        qdata = []
        self.qargstablemodelview.model().changeData(qdata)

        adata = []
        self.bindingargstablemodelview.model().changeData(adata)

    def loginCancelled(self, cancelled):
        self._cancelled = cancelled
        #print(self._cancelled)

        if self._cancelled == False:
            self.session = requests.Session()
            self.sessionAvailable = True

            self.disconnect()

            self.populate()

            #print("self.eqbConnection = {}".format(self.eqbConnection))

            if self.eqbConnection is None:
                self.eqbConnection = RabbitMQPikaConnection.connect(
                    RabbitMQPikaConnection, self, self._commandUrl,
                    self._userId, self._password, self._certName, self._vhost,
                    'RabbitMQ_Util_EQB')

            self.connectAction.setEnabled(True)
            self.loginButton.setEnabled(True)

    def getWebConnectionUrl(self, url):
        self._webUrl = url
        #print(url)

    def getCommandConnectionUrl(self, url):
        self._commandUrl = url
        #print(url)

    def getConnectionUser(self, user):
        self._userId = user
        #print(user)

    def getConnectionPassword(self, passkeyFile, password):
        decPass = decrypt.decrypt_password(passkeyFile, password.encode())
        self._password = decPass
        #print(self._password)
        #print("*************************************")

    def getConnectionVhost(self, vhost):
        self._vhost = vhost
        #print(vhost)

    def getConnectionCertName(self, cert):
        self._certName = cert
        #print(cert)

    def getConnectionCertPass(self, certpass):
        self._certPass = certpass
        if certpass is not None:
            #print(certpass)
            #print("************************************")
            pass

    def refresh(self):
        self.reset()
        self.populate()

    def setConnection(self, connection, sessionAvailable, session, _webUrl,
                      _userId, _password, _vhost, _certName, _frame):
        self.fromParent = True

        self.eqbConnection = connection

        #print("From rmq main - self.eqbConnection = {}".format(self.eqbConnection))

        self.sessionAvailable = sessionAvailable
        self.session = session
        self._webUrl = _webUrl
        self._userId = _userId
        self._password = _password
        self._vhost = _vhost
        self._certName = _certName

        self.frame = _frame

        self.reset()

        self.populate()

    def populate(self):

        eqvhost = RestFunctions.vhosts(RestFunctions, self,
                                       self.sessionAvailable, self.session,
                                       self._webUrl, self._userId,
                                       self._password, self._certName)
        for item in eqvhost:
            self.evhost.addItem(item[1])
            self.qvhost.addItem(item[1])

        index = self.evhost.findText(self._vhost, Qt.MatchFixedString)
        if index >= 0:
            self.evhost.setCurrentIndex(index)

        index = self.qvhost.findText(self._vhost, Qt.MatchFixedString)
        if index >= 0:
            self.qvhost.setCurrentIndex(index)

        etypesAndNodes = RestFunctions.nodes(RestFunctions, self,
                                             self.sessionAvailable,
                                             self.session, self._webUrl,
                                             self._userId, self._password,
                                             self._certName)

        for item in etypesAndNodes:
            etype = item["exchange_types"]
            for elem in etype:
                name = elem["name"]
                if (name != "x-federation-upstream"):
                    self.exType.addItem(name)

        self.elist = RestFunctions.exchange_list(RestFunctions, self,
                                                 self.sessionAvailable,
                                                 self.session, self._webUrl,
                                                 self._userId, self._password,
                                                 self._certName)
        self.qlist = RestFunctions.queue_list(RestFunctions, self,
                                              self.sessionAvailable,
                                              self.session, self._webUrl,
                                              self._userId, self._password,
                                              self._certName)

        for item in self.elist:
            name = item["name"]
            if len(name) == 0 or name.find(self._userId.lower().replace(
                    "_", "")) > -1:
                if (len(name) != 0):
                    self.source.addItem(str(name))

        for item in self.qlist:
            name = item["name"]
            if len(name) == 0 or name.find(self._userId.lower().replace(
                    "_", "")) > -1:
                if (len(name) != 0):
                    self.target.addItem(str(name))

    def closewin(self):
        if self is not None:
            self.close()

        if self.frame is not None:
            self.frame.close()

        self.login.close()
        self.loginmw.close()

        if self.eqbConnection is not None and self.eqbConnection.is_open:
            self.eqbConnection.close()

        if self.session is not None:
            self.session.close()

        #self.qapp.exit()

    def closeEvent(self, event):
        if self is not None:
            self.close()

        if self.frame is not None:
            self.frame.close()

        self.login.close()
        self.loginmw.close()

        if self.eqbConnection is not None and self.eqbConnection.is_open:
            self.eqbConnection.close()

        if self.session is not None:
            self.session.close()
Example #51
0
class ui_pve(QMainWindow):
    def __init__(self, parent, lan=0):
        super(ui_pve, self).__init__(parent)
        self.temp = parent
        self.setGeometry(303, 304, 500, 350)  # 设置子窗口的尺寸
        self.setMinimumSize(200, 130)  # 设置子窗口的最小尺寸
        self.lan = lan
        self.initUI()
        self.path_cbf = ""
        self.path_gm = ""
        self.path_wm = ""
        self.path_csf = ""
        self.bul_autoreg = 1
        self.index_method = 0  # 0:PET校正,1:线性回归
        self.data_temp = []
        self.idx_file = 0
        self.bul_autosave = 1

    def initUI(self):
        self.setWindowTitle("PVE")
        if self.lan == 0:
            self.label_name_cbf = QLabel("Directory of CBF:", self)
            self.label_name_gm = QLabel("Directory of GM:", self)
            self.label_name_wm = QLabel("Directory of WM:", self)
            self.label_name_csf = QLabel("Directory of CSF:", self)
            self.bt_ok = QPushButton("Operate", self)
            self.checkbox_autoreg = QCheckBox("Auto Coregister", self)
            self.checkbox_autoreg.setChecked(1)
            self.radio_pet = QRadioButton("PET's Correlation", self)
            self.radio_lr = QRadioButton("Linear Regression", self)
            self.radio_pet.setChecked(1)
            self.gb_method = QGroupBox("Method:", self)
            self.checkbox_autosave = QCheckBox("Auto Save", self)
            self.checkbox_autosave.setChecked(1)
        elif self.lan == 1:
            self.label_name_cbf = QLabel("CBF文件路径:", self)
            self.label_name_gm = QLabel("灰质分割结果路径:", self)
            self.label_name_wm = QLabel("白质分割结果路径:", self)
            self.label_name_csf = QLabel("脑脊液分割结果路径:", self)
            self.bt_ok = QPushButton("计算", self)
            self.checkbox_autoreg = QCheckBox("自动配准", self)
            self.checkbox_autoreg.setChecked(1)
            self.radio_pet = QRadioButton("传统PET校正", self)
            self.radio_pet.setChecked(1)
            self.radio_lr = QRadioButton("线性回归校正", self)
            self.gb_method = QGroupBox("校正方法:", self)
            self.checkbox_autosave = QCheckBox("自动保存", self)
            self.checkbox_autosave.setChecked(1)
        self.label_val_cbf = QLineEdit(self)
        self.label_val_gm = QLineEdit(self)
        self.label_val_wm = QLineEdit(self)
        self.label_val_csf = QLineEdit(self)
        self.bt_getcbf = QPushButton("...", self)
        self.bt_getcbf.setFixedWidth(30)
        self.bt_getgm = QPushButton("...", self)
        self.bt_getgm.setFixedWidth(30)
        self.bt_getwm = QPushButton("...", self)
        self.bt_getwm.setFixedWidth(30)
        self.bt_getcsf = QPushButton("...", self)
        self.bt_getcsf.setFixedWidth(30)
        self.bt_ok.setFixedWidth(65)
        self.bt_ok.clicked.connect(self.calc_pve)
        self.bt_getcbf.clicked.connect(self.get_cbf)
        self.bt_getgm.clicked.connect(self.get_gm)
        self.bt_getwm.clicked.connect(self.get_wm)
        self.bt_getcsf.clicked.connect(self.get_csf)
        self.checkbox_autoreg.stateChanged.connect(self.set_autoreg)
        self.checkbox_autosave.stateChanged.connect(self.set_autosave)

        self.radiobox = QVBoxLayout()
        self.radiobox.addWidget(self.radio_pet)
        self.radiobox.addWidget(self.radio_lr)
        self.radiobox.addStretch(1)
        self.gb_method.setLayout(self.radiobox)
        self.radio_pet.clicked.connect(self.switch_method)
        self.radio_lr.clicked.connect(self.switch_method)

        self.grid_label = QGridLayout()
        self.grid_upper = QGridLayout()
        self.grid_all = QGridLayout()

        self.grid_label.addWidget(self.label_name_cbf, 0, 0)
        self.grid_label.addWidget(self.label_val_cbf, 0, 1)
        self.grid_label.addWidget(self.bt_getcbf, 0, 2)
        self.grid_label.addWidget(self.label_name_gm, 1, 0)
        self.grid_label.addWidget(self.label_val_gm, 1, 1)
        self.grid_label.addWidget(self.bt_getgm, 1, 2)
        self.grid_label.addWidget(self.label_name_wm, 2, 0)
        self.grid_label.addWidget(self.label_val_wm, 2, 1)
        self.grid_label.addWidget(self.bt_getwm, 2, 2)
        self.grid_label.addWidget(self.label_name_csf, 3, 0)
        self.grid_label.addWidget(self.label_val_csf, 3, 1)
        self.grid_label.addWidget(self.bt_getcsf, 3, 2)
        self.grid_label.addWidget(self.checkbox_autoreg, 4, 0)
        self.grid_label.addWidget(self.checkbox_autosave, 5, 0)

        self.grid_upper.addWidget(self.gb_method, 0, 0)
        self.grid_upper.addLayout(self.grid_label, 0, 1)

        self.grid_all.addLayout(self.grid_upper, 0, 0)
        self.grid_all.addWidget(self.bt_ok, 1, 0)
        self.grid_all.setGeometry(QRect(50, 50, 400, 250))
        self.grid_all.setAlignment(Qt.AlignCenter)

        self.resizeEvent = self.adjustSize

    def switch_method(self):
        if self.radio_pet.isChecked() == True:
            self.index_method = 0
        elif self.radio_lr.isChecked() == True:
            self.index_method = 1

    def calc_pve(self):
        if self.bt_ok.text() == ("Operate" or "计算"):
            try:
                if self.lan == 0:
                    self.bt_ok.setText("Cancel")
                elif self.lan == 1:
                    self.bt_ok.setText("取消")
                if self.index_method == 0:
                    for idx in range(len(self.path_cbf)):
                        nii_cbf = ni.load(self.path_cbf[idx])
                        nii_gm = ni.load(self.path_gm[idx])
                        nii_wm = ni.load(self.path_wm[idx])
                        if nii_cbf.shape != nii_gm.shape:
                            if self.bul_autoreg == 1:
                                # 预留将结构像与CBF自动配准的功能,用resample代替
                                nii_cbf = resample_to_img(nii_cbf, nii_gm)
                            else:
                                if self.lan == 0:
                                    warn_msg(
                                        self,
                                        "Shape of CBF and T1 are different.")
                                elif self.lan == 1:
                                    warn_msg(self, "CBF与结构像大小不一致")
                                continue
                        data_cbf = nii_cbf.get_fdata()
                        data_gm = nii_gm.get_fdata()
                        data_wm = nii_wm.get_fdata()

                        data_temp = (data_cbf *
                                     ((data_gm + data_wm) > 0.1)) / (
                                         ((data_gm) + 0.4 * (data_wm)) *
                                         ((data_gm + 0.4 * data_wm) > 0.1))

                        data_temp[np.isnan(data)] = 0
                        data_temp[np.isinf(data)] = 0
                        self.data_temp.append(
                            ni.Nifti1Image(data_temp, nii_gm.affine,
                                           nii_gm.header))

                    self.temp.set_nii(self.data_temp)
                    if self.lan == 0:
                        self.bt_ok.setText("Operate")
                    elif self.lan == 1:
                        self.bt_ok.setText("计算")
                    self.temp.fname = [
                        item.replace(".nii", "_pve.nii")
                        for item in self.path_cbf
                    ]

                    self.close()
                elif self.index_method == 1:
                    data_temp = 0
                    self.lr_thread = LRThread(self, self.lan)
                    self.lr_thread.start()
                    self.lr_thread.progress.connect(self.update_progress)
                    self.lr_thread.trigger.connect(self.get_data_thread)
                    self.lr_thread.file.connect(self.get_data_each)
                else:
                    pass  # 预留其他方法

            except FileNotFoundError:
                if self.lan == 0:
                    warn_msg(self, "File not existed.")
                elif self.lan == 1:
                    warn_msg(self, "选择的文件不存在")
            except ni.filebasedimages.ImageFileError:
                if self.lan == 0:
                    warn_msg(self, "Selected file is not an nii file.")
                elif self.lan == 1:
                    warn_msg(self, "选择的文件格式错误")
        elif self.bt_ok.text() == ("Cancel" or "取消"):
            self.lr_thread.stop()
            self.lr_thread.quit()
            self.lr_thread.wait()
            del self.lr_thread
            if self.lan == 0:
                self.bt_ok.setText("Operate")
            elif self.lan == 1:
                self.bt_ok.setText("计算")

    def update_progress(self, float_progress):
        if self.lan == 0:
            self.statusBar().showMessage("Working: " + str(float_progress) +
                                         "%, File: " + str(self.idx_file + 1) +
                                         "/" + str(len(self.path_cbf)))
        elif self.lan == 1:
            self.statusBar().showMessage("正忙: " + str(float_progress) +
                                         "%, 文件: " + str(self.idx_file + 1) +
                                         "/" + str(len(self.path_cbf)))

    def get_data_each(self, int_file):
        self.idx_file = int_file
        data_temp = self.lr_thread.data_result
        self.data_temp.append(
            ni.Nifti1Image(data_temp,
                           ni.load(self.path_cbf[self.idx_file]).affine,
                           ni.load(self.path_cbf[self.idx_file]).header))

    def get_data_thread(self):
        self.temp.fname = [
            item.replace(".nii", "_pve.nii") for item in self.path_cbf
        ]
        if self.lan == 0:
            warn_msg(
                self,
                str(time.localtime().tm_hour) + ":" +
                str(time.localtime().tm_min) + ":" +
                str(time.localtime().tm_sec) + " Done!", 1)
        elif self.lan == 1:
            warn_msg(
                self,
                str(time.localtime().tm_hour) + ":" +
                str(time.localtime().tm_min) + ":" +
                str(time.localtime().tm_sec) + "计算完成", 1)
        self.temp.set_nii(self.data_temp)
        self.temp.idx_fname = len(self.temp.fname) - 1
        self.temp.PrevFile()
        if self.lan == 0:
            self.bt_ok.setText("Operate")
        elif self.lan == 1:
            self.bt_ok.setText("计算")
        if self.bul_autosave == 1:
            for i in range(len(self.data_temp)):
                ni.save(self.data_temp[i], self.temp.fname[i])
        self.lr_thread.deleteLater()
        self.close()

    def get_cbf(self):
        if self.lan == 0:
            self.path_cbf = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_cbf = QFileDialog.getOpenFileNames(
                self, '选择文件', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        self.label_val_cbf.setText(str(self.path_cbf))

    def get_gm(self):
        if self.lan == 0:
            self.path_gm = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_gm = QFileDialog.getOpenFileNames(
                self, '选择文件', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        self.label_val_gm.setText(str(self.path_gm))

    def get_wm(self):
        if self.lan == 0:
            self.path_wm = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_wm = QFileDialog.getOpenFileNames(
                self, '选择文件', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        self.label_val_wm.setText(str(self.path_wm))

    def get_csf(self):
        if self.lan == 0:
            self.path_csf = QFileDialog.getOpenFileNames(
                self, 'Select File', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        elif self.lan == 1:
            self.path_csf = QFileDialog.getOpenFileNames(
                self, '选择文件', './',
                "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
        self.label_val_csf.setText(str(self.path_wm))

    def set_autoreg(self, int):
        if self.checkbox_autoreg.isChecked():
            self.bul_autoreg = 1
        else:
            self.bul_autoreg = 0

    def set_autosave(self, int):
        if self.checkbox_autosave.isChecked():
            self.bul_autosave = 1
        else:
            self.bul_autosave = 0

    def adjustSize(self, event):
        self.grid_all.setGeometry(
            QRect(50, 50, (self.width() - 100),
                  (self.height() - 100)))  # 将组件全部显示后调整尺寸

    def closeEvent(self, event):
        try:
            if self.lr_thread.isRunning():
                self.lr_thread.quit()
                del self.lr_thread
        except NameError:
            pass
        except AttributeError:
            pass
        super(ui_pve, self).closeEvent(event)
Example #52
0
class ChordPairGrid(QWidget):
    """ Widget that contains a grid of buttons for each key in
        the chord pair dictionary, and controls to rearrange them """

    pair_clicked = pyqtSignal(tuple, int)

    def __init__(self, data, *args, **kwargs):
        super(ChordPairGrid, self).__init__(*args, **kwargs)
        self.data = data
        self.button_size = (96, 36)
        self.column_spacing = 8

        self.layout = QVBoxLayout(self)

        self.scroll_area = QScrollArea()
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll_area.setWidgetResizable(True)

        self.grid_container = QWidget()
        self.grid_container.setProperty('id', 'gridcontainer')
        self.pair_grid = QGridLayout(self.grid_container)
        self.pair_grid.setSpacing(self.column_spacing)

        self.scroll_area.setWidget(self.grid_container)
        self.scroll_area.ensureWidgetVisible(self)

        # Controls to rearrange the grid
        sort_controls = QWidget()
        self.sort_layout = QHBoxLayout(sort_controls)
        sort_label = QLabel("Sort")
        # For some reason using the toggle sinal for the radiobuttons and checkbox makes the
        # sort_buttons method execute twice. The clicked signal does not... huh.
        self.sort_alphabetically = QRadioButton("by Chords")
        self.sort_alphabetically.clicked.connect(self.rearrange)
        self.sort_numerically = QRadioButton("by Score")
        self.sort_numerically.clicked.connect(self.rearrange)
        self.reverse = QCheckBox("Reverse")
        self.reverse.clicked.connect(self.rearrange)

        self.sort_layout.addWidget(sort_label)
        self.sort_layout.addWidget(self.sort_alphabetically)
        self.sort_layout.addWidget(self.sort_numerically)
        self.sort_layout.addWidget(self.reverse)

        self.layout.addWidget(self.scroll_area)
        self.layout.addWidget(sort_controls)
        self.init_grid()

    def init_grid(self):
        self.make_buttons()
        self.rearrange()

    def make_buttons(self):
        self.button_dict = {}
        self.buttons = []  # This is used to make it easy to sort the buttons

        for pair in self.data.scores:
            score = self.data.highscore(pair)
            if pair not in self.button_dict:
                new_button = PairButton(pair, score, self.button_size)
                new_button.clicked.connect(self.pair_clicked.emit)
                self.button_dict[pair] = new_button
                self.buttons.append(new_button)

    def sort_buttons(self):
        rev = self.reverse.isChecked()
        if self.sort_alphabetically.isChecked():
            self.buttons = sorted(self.button_dict.values(),
                                  reverse=rev,
                                  key=lambda button: button.pair)
        elif self.sort_numerically.isChecked():
            self.buttons = sorted(self.button_dict.values(),
                                  reverse=rev,
                                  key=lambda button: button.score)

    def set_grid(self):
        # Calculate num_cols based on width of container
        # As far as I am aware there is no way to get the actual width
        # of the scroll bar. So I am estimating...
        scrollbar_width = 20
        row_length = self.scroll_area.width(
        ) - self.column_spacing - scrollbar_width
        button_space = self.button_size[0] + self.column_spacing
        num_cols = row_length // button_space
        for count, button in enumerate(self.buttons):
            row = count // num_cols
            col = count % num_cols
            self.pair_grid.addWidget(button, row, col)

    def new_pairs(self):
        self.make_buttons()
        self.rearrange()

    def clear_grid(self):
        for i in reversed(range(self.pair_grid.count())):
            self.pair_grid.itemAt(i).widget().setParent(None)

    def rearrange(self):
        self.clear_grid()
        self.sort_buttons()
        self.set_grid()

    def resizeEvent(self, e):
        self.rearrange()
Example #53
0
    class WMChannelGUI(QWidget):
        def __init__(self, parent=None, data=None):
            self.parent = parent
            self.data = data
            super().__init__(parent=self.parent)
            main_layout = QVBoxLayout()

            layout1 = QHBoxLayout()
            self.btn_w = QRadioButton('nm')
            self.btn_w.setChecked(self.data.unit == 'nm')
            self.btn_w.toggled.connect(
                self.unitChanged)  # (lambda:self.unitChange(self.btn_w))
            layout1.addWidget(self.btn_w)
            self.btn_f = QRadioButton('THz')
            self.btn_f.setChecked(self.data.unit != 'nm')
            # self.btn_f.toggled.connect(self.unitChanged)  # (lambda: self.unitChange(self.btn_f))
            layout1.addWidget(self.btn_f)
            self.show_sp_chbx = QCheckBox()
            self.show_sp_chbx.setChecked(self.data.show_spectrum)
            self.show_sp_chbx.toggled.connect(self.showSpectrum)
            layout1.addWidget(self.show_sp_chbx)

            self.col_btn = QPushButton()
            self.col_btn.setMinimumWidth(25)
            self.col_btn.setMaximumWidth(25)
            # print('background-color: rgb(%i,%i,%i)' % self.data.color.getRgb()[:3])
            # self.col_btn.setStyleSheet('background-color: rgb(%i,%i,%i)' % self.data.color.getRgb()[:3])
            self.col_btn.setStyleSheet("QWidget { background-color: %s }" %
                                       self.data.color.name())
            self.col_btn.clicked.connect(self.changeColor)
            layout1.addWidget(self.col_btn)
            layout1.addStretch(1)
            # implemented in main window
            # self.show_box = QCheckBox('Show')
            # self.show_box.setChecked(False)
            # self.show_box.stateChanged.connect(lambda:self.showSpectrum(self.show_box.checkState()))
            # layout1.addWidget(self.show_box)

            main_layout.addLayout(layout1)

            self.name_line = QLabel(self.data.name)
            self.name_line.setFont(QFont("Times", 25, QFont.Bold))
            self.name_line.setStyleSheet("QWidget { color: %s }" %
                                         self.data.color.name())
            main_layout.addWidget(self.name_line)

            self.value = QLabel()
            self.value.setFont(QFont("Times", 65))  #,QFont.Bold
            self.setValueText()
            self.value.setStyleSheet("QWidget { color: %s }" %
                                     self.data.color.name())
            main_layout.addWidget(self.value)
            self.setLayout(main_layout)
            # print('Min Width ', self.width())

        def changeColor(self):
            col = QColorDialog.getColor()
            if col.isValid():
                self.data.color = col  #.setStyleSheet("QWidget { background-color: %s }"% col.name())
            self.parent.data.save()

        def unitChanged(self):
            if self.btn_w.isChecked():
                self.data.unit = 'nm'
            else:
                self.data.unit = 'THz'
            self.parent.data.save()

        def setValueText(self):
            if self.data.unit == 'nm':
                self.value.setText("%.5f nm" % self.data.wavelength)
            else:
                self.value.setText("%.5f THz" % self.data.frequency)

        def showSpectrum(self, b):
            # print('Show spectrum', b)
            self.data.show_spectrum = b
            self.parent.data.save()
Example #54
0
class GUI_FastaViewer(QMainWindow):
    """
    A class used to make and change the appearance of the FastaViewer.
    It enables to load a fasta file of a colletion of protein sequences
    and search for proteins by its accesion number, name or subsequence.


    ...

    Attributes
    ----------
    searchButtonP : QtWidgets.QPushButton
        a button to be shown on window and exc action on click

    searchButtonP : QtWidgets.QPushButton
         Button to be shown on window and exc action on click

    boxPro : QLineEdit(self)
         Textfield in wich the user can type inputs

    tw : QtWidgets.QTreeWidget
         Treewidget used to hold and show data on the sceen

    mainwidget : QWidget
         QWidget that contains all the Widgets

    main_layout : QVBoxLayout
        The main Layout of the Window, contains all other Layouts

    set1,set2,set3 : QHBoxLayout()
         Horizontal Layouts that hold different Widgets

    radioname,radioid,radioseq=QRadioButton
            A QRadioButton that appears on sceen an can be cheked


    color : QColor
            Red Color for the searched seq

    colorblack : QColor
            Black color for the found Protein sequence
    fileloaded : int
            Integer to check if file has been loaded
    Methods
    -------
    _init_(self)
        Sets Window size na exc. initUI()

    initUi(self)
            Creates the User Interface

    center(self)
            Centers the Window on screen

    cutstring(self,oldstring,proteinseq)
            Cuts the oldstring when proteinseq appears and returns a list of
            the cuts

    loadFile(self)
            A function for the loadbutton that open QFileDialog and saves the
            Path to the file fo the logic class

    searchClicked(self)
            A function for the searchButtonP, it checks if input is correct
            and exc a search function

    radioIdSearch()
            Searches for the Protein Information by ID


    sequenceSearch()
            Searches for the Protein Information by sequence and also changes
            the color of the are of the sequence that is the same as the input

    nameSearch()
            Searches for the Protein Information by name

    main()
            runs the QApplication
    """
    def __init__(self):
        """Gets self and sets Window size na exc. initUI()

        Parameters
        ----------
        self : QMainWindow


        Returns
        -------
        nothing
        """
        super().__init__()
        self.resize(1280, 720)
        self.initUI()

    def initUI(self):
        """Gets self and creates the User Interface

        Parameters
        ----------
        self : QMainWindow


        Returns
        -------
        nothing
        """

        # creating Buttons
        self.searchButtonP = QtWidgets.QPushButton(self)
        self.searchButtonP.setText("Search")
        self.searchButtonP.clicked.connect(self.searchClicked)

        self.loadbutton = QtWidgets.QPushButton(self)
        self.loadbutton.setText("Load")
        self.loadbutton.clicked.connect(self.loadPath)

        self.changeReversePattern = QtWidgets.QPushButton(self)
        self.changeReversePattern.setText("Add Decoy Pattern")
        self.changeReversePattern.clicked.connect(
            self.user_Dialog_ChangeReversePattern)
        self.changeReversePattern.setFixedWidth(166)

        # creating testboxes for the buttons
        self.boxPro = QLineEdit(self)

        # Creating treewidget for displaying the proteins
        self.tw = QtWidgets.QTreeWidget()
        self.tw.setHeaderLabels(["Accession", "Organism", "Protein Name"])
        self.tw.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # Layout
        self.mainwidget = QWidget(self)
        self.main_layout = QVBoxLayout(self.mainwidget)

        # every set contains all widgets on the level they should be in the UI
        # in set1 there is a textbox and a button
        self.set1 = QHBoxLayout()
        self.set1.addWidget(self.boxPro)
        self.set1.addWidget(self.searchButtonP)
        self.set1.addWidget(self.loadbutton)

        # set 2 contains the radiobuttons and a label
        self.set2 = QHBoxLayout()
        self.radioname = QRadioButton("Name")
        self.radioid = QRadioButton("ID")
        self.radioseq = QRadioButton("Sequence")
        self.radioname.setChecked(True)
        self.decoycheck = QCheckBox("Decoy search", self)
        self.datalabel = QLabel()
        self.datalabel.setText("Fasta not loaded")
        self.set2.addWidget(self.radioname)
        self.set2.addWidget(self.radioid)
        self.set2.addWidget(self.radioseq)
        self.set2.addWidget(self.decoycheck)
        self.set2.addStretch(1)
        self.set2.addWidget(self.changeReversePattern)

        # set 3 contains the table and the result box
        self.set3 = QHBoxLayout()
        self.set3.addWidget(self.tw)

        # adding all QHBoxLayout to the main QVBoxLayout
        self.main_layout.addLayout(self.set1)
        self.main_layout.addLayout(self.set2)
        self.main_layout.addLayout(self.set3)
        self.main_layout.addWidget(self.datalabel)

        self.mainwidget.setLayout(self.main_layout)
        self.setCentralWidget(self.mainwidget)
        self.setWindowTitle('Protein Viewer')

        self.extra_pattern = ''

        # defining some colors to marked searched sequences
        self.color = QColor(255, 0, 0)
        self.colorblack = QColor(0, 0, 0)
        self.center()
        self.show()
        # defining a counter var that checks if a file has been loaded
        # if not than there should be an error Window when a search is done

        self.fileloaded = 0

        # centering the widget
    def center(self):
        """Gets self and centers the Window
        Parameters
        ----------
        self : QMainWindow


        Returns
        -------
        changes so that the Window appears on the center of the screen
        """
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    # defining a help function to cut the sequence that is being search from the
    # Protein sequence that has been found

    def cutstring(self, oldstring: str, proteinseq: str) -> str:
        """Gets two strings and splits the first string in a list
            on the playces where the second string is found. This helps
            to change the color of the sequences later on

    Parameters
    ----------
    oldstring : str
        the enteire proteinseq as a string
    proteinseq : str
        is the searched seq and is used to split the entire seq in parts

    Returns
    -------
    list
        a list of strings to be later put together after recoloring
    """
        cut = oldstring.split(proteinseq)
        return cut

    # defining the function for load button to get path of database
    def clearFastaViewer(self):
        self.tw.clear()

    def loadPath(self):
        self.clearFastaViewer()
        self.filename = QFileDialog.getOpenFileName()
        # if 'cancel' was pressed
        if self.filename[0] == '':
            pass
        else:
            # saving the file path in the dictionary
            Files_Number_Handler.Dictionary_Change_File(
                "fasta", self.filename[0])
            Files_Number_Handler.Dictionary_Change_Boolean("fasta")
            self.loadFile(self.filename[0])

    # creates a user dialog to change default reverse pattern
    def user_Dialog_ChangeReversePattern(self):
        text, okPressed = QInputDialog.getText(self, "Add reverse pattern",
                                               "Add:", QLineEdit.Normal, "")
        if okPressed and text != '':
            self.extra_pattern = text

    def loadFile(self, fasta_path):
        """Gets QMainWindow and opens a QFileDialog and loads path

    Parameters
    ----------
    self : QMainWindow
        the MainWindow of the class


    Returns
    -------
    nothing , it changes the QMainWindow so that the user can see that a file
    has been loaded
    """

        self.fileloaded = 1

        # loading the lists before searching in order to make the search faster

        self.dictKeyAccession, self.proteinList, self.proteinNameList, self.proteinOSList, self.dictKeyAccessionDECOY, self.proteinListDECOY, self.proteinNameListDECOY, self.proteinOSListDECOY = LoadFasta_FastaViewer.protein_dictionary(
            fasta_path, self.extra_pattern)
        self.datalabel.setText("Fasta loaded")
        for i in range(len(self.dictKeyAccession)):
            ID = list(self.dictKeyAccession.keys())[i]
            Proteinname = self.proteinNameList[i]
            OS = self.proteinOSList[i]
            self.cg = QtWidgets.QTreeWidgetItem(self.tw)
            self.cg.setData(0, 0, ID)
            self.cg.setData(1, 0, OS)
            self.cg.setData(2, 0, Proteinname)
        self.tw.itemClicked.connect(self.clickTreeItem)

    # defining a function to creat TreeItems

    def createTreeItem(self, item, ID, Protein):
        """Gets a TreeItem and creats two child Items, a Qlabel and a QTextEdit.
    Firs Child Item holds a QTextEdit with the given Protein sequence.
    Second Cild Item holds a QLabel with a hyperlink to the database UniProt.

    Parameters
    ----------
    self : QMainWindow
        the MainWindow of the class
    item : QTreeWidgetItem
        for which the child items will be created
    ID : The specific protein accesion
        which is needed for the link to the database
    Protein : The specific protein sequence
        that will be displayed in the QTextEdit


    Returns
    -------
    nothing , it changes the Treewidget
    and creates two child items for the handed in tree item
    """
        self.link = QLabel()
        self.link.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.link.setOpenExternalLinks(True)
        self.link.setTextFormat(Qt.RichText)
        self.link.setText("<a href =" + "https://www.uniprot.org/uniprot/" +
                          ID + ">" + "More Information" + " </a>")
        self.textp = QTextEdit()
        self.textp.resize(self.textp.width(), self.textp.height())
        self.textp.insertPlainText("Proteinsequence: " + Protein + "\n")
        self.textp.setReadOnly(True)
        self.cgChild = QtWidgets.QTreeWidgetItem(item)
        self.cgChild2 = QtWidgets.QTreeWidgetItem(item)
        self.cgChild.setFirstColumnSpanned(True)
        self.tw.setItemWidget(self.cgChild, 0, self.textp)
        self.tw.setItemWidget(self.cgChild2, 0, self.link)

    # method when TreeItem was cklicked

    def clickTreeItem(self, item):
        '''Gets a QTreeWidgetItem and its ID data of the first
        collumn. The ID and the corresponding protein sequence are
        handed to the createTreeItem method.

        Parameters
        ----------
        self : QMainWindow
            the MainWindow of the class
        item : clicked QTreeWidgetItem
            from which the ID is obtained

        Returns
        -------
        nothing
        '''
        num = item.childCount()
        # prevents multiple creation of the same child tree items
        if num == 0:
            ID = item.data(0, 0)
            index = list(self.dictKeyAccession.keys()).index(ID)
            Protein = self.proteinList[index]
            self.createTreeItem(item, ID, Protein)

    def clickTreeItemDecoy(self, item):
        '''Does the same as clickTreeItem but
        hands the corresponding DECOY protein sequence
        to the create TreeItem method.
        '''
        num = item.childCount()
        if num == 0:
            ID = item.data(0, 0)
            index = list(self.dictKeyAccessionDECOY).index(ID)
            Protein = self.proteinListDECOY[index]
            self.createTreeItem(item, ID, Protein)

    def createTreeItemSeqSearch(self, item, ID, Protein):
        """Gets a TreeItem and creats two child Items and a Qlabel.
        Firs Child Item holds a QTextEdit with the given Protein sequence.
        Second Cild Item holds a QLabel with a hyperlink to the database UniProt.

        Parameters
        ----------
        self : QMainWindow
            the MainWindow of the class
        item : QTreeWidgetItem
            for which the child items will be created
        ID : The specific protein accesion
            which is needed for the link to the database
        Protein : A QTextEdit widget with the specific portein sequence


        Returns
        -------
        nothing , it changes the Treewidget
        and creates two child items for the handed in tree item
        """
        self.link = QLabel()
        self.link.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.link.setOpenExternalLinks(True)
        self.link.setTextFormat(Qt.RichText)
        self.link.setText("<a href =" + "https://www.uniprot.org/uniprot/" +
                          ID + ">" + "More Information" + " </a>")

        self.cgChild = QtWidgets.QTreeWidgetItem(item)
        self.cgChild2 = QtWidgets.QTreeWidgetItem(item)
        self.cgChild.setFirstColumnSpanned(True)
        self.tw.setItemWidget(self.cgChild, 0, Protein)
        self.tw.setItemWidget(self.cgChild2, 0, self.link)

    def clickTreeItemSeqSearch(self, item):
        '''Gets a QTreeWidgetItem and its ID data of the first
        collumn. The ID and the corresponding QTextEdit widget with the
        protein sequence are handed to the createTreeItem method.

        Parameters
        ----------
        self : QMainWindow
            the MainWindow of the class
        item : clicked QTreeWidgetItem
            from which the ID is obtained

        Returns
        -------
        nothing
        '''
        num = item.childCount()
        if num == 0:
            ID = item.data(0, 0)
            Protein = self.SequencSearchDict.get(ID)
            self.createTreeItemSeqSearch(item, ID, Protein)

    def clickTreeItemSeqSearchDecoy(self, item):
        '''Does the same as clickTreeItemSeqSearch but
        hands the corresponding DECOY protein sequence
        to the create TreeItem method.
        '''
        num = item.childCount()
        if num == 0:
            ID = item.data(0, 0)
            Protein = self.SequencSearchDictDECOY.get(ID)
            self.createTreeItemSeqSearch(item, ID, Protein)

    # defining the searchClicked method for the searchButtonP

    def searchClicked(self):
        """Gets self and searches for Protein and shows the result
        on QMainWindow

    Parameters
    ----------
    self : QMainWindow


    Returns
    -------
    nothing but changes the QMainWindow to show the Protein or an Error message
    """
        if self.fileloaded == 0:
            self.error = QMessageBox()
            self.error.setIcon(QMessageBox.Information)
            self.error.setText("Please load Data before searching")
            self.error.setWindowTitle("Error")
            c = self.error.exec_()
        else:
            self.tw.clear()
            # check if inputbox is empty. if empty return error if not proceed
            if self.boxPro.text() == "":
                self.error = QMessageBox()
                self.error.setIcon(QMessageBox.Information)
                self.error.setText("Please enter input before searching")
                self.error.setWindowTitle("Error")
                a = self.error.exec_()
            else:
                if self.radioid.isChecked():
                    self.radioIdSearch()

                if self.radioseq.isChecked():
                    self.sequenceSearch()

                if self.radioname.isChecked():
                    self.nameSearch()
        # doc recommends enabling sorting after loading the tree with elements
        self.tw.setSortingEnabled(True)

    def radioIdSearch(self):
        """Gets self and searches for Protein based on ID
            and shows the result on QMainWindow, also adds a hyperlink for
            more Information

        Parameters
        ----------
        self : QMainWindow


        Returns
        -------
        nothing but changes the QMainWindow to show the Protein in treewidget
        """
        atLeastOneProteinFound = False
        protein_accession_maybe_sub_sequence = self.boxPro.text()

        if self.decoycheck.isChecked():
            for protein_accession in self.dictKeyAccessionDECOY:
                if protein_accession_maybe_sub_sequence in protein_accession:
                    atLeastOneProteinFound = True
                    index = list(
                        self.dictKeyAccessionDECOY).index(protein_accession)
                    ID = list(self.dictKeyAccessionDECOY.keys())[index]
                    Proteinname = self.proteinNameListDECOY[index]
                    OS = self.proteinOSListDECOY[index]
                    self.cg = QtWidgets.QTreeWidgetItem(self.tw)
                    self.cg.setData(0, 0, ID)
                    self.cg.setData(1, 0, OS)
                    self.cg.setData(2, 0, Proteinname)

            header = self.tw.header()
            header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)
            self.tw.itemClicked.disconnect()
            self.tw.itemClicked.connect(self.clickTreeItemDecoy)

        else:
            for protein_accession in self.dictKeyAccession:
                if protein_accession_maybe_sub_sequence in protein_accession:
                    atLeastOneProteinFound = True
                    index = list(
                        self.dictKeyAccession).index(protein_accession)
                    ID = list(self.dictKeyAccession.keys())[index]
                    Proteinname = self.proteinNameList[index]
                    OS = self.proteinOSList[index]
                    self.dummy = ID
                    self.cg = QtWidgets.QTreeWidgetItem(self.tw)
                    self.cg.setData(0, 0, ID)
                    self.cg.setData(1, 0, OS)
                    self.cg.setData(2, 0, Proteinname)

            header = self.tw.header()
            header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)
            self.tw.itemClicked.disconnect()
            self.tw.itemClicked.connect(self.clickTreeItem)

        if not atLeastOneProteinFound:
            self.msg = QMessageBox()
            self.msg.setIcon(QMessageBox.Information)
            self.msg.setText(
                "No matching protein accession found in database.")
            self.msg.setWindowTitle("Error")
            x = self.msg.exec_()

    def sequenceSearch(self):
        """Gets self and searches for Protein based on sequence
            and shows the result on QMainWindow, also adds a hyperlink for
            more Information

        Parameters
        ----------
        self : QMainWindow


        Returns
        -------
        nothing but changes the QMainWindow to show the Protein in treewidget
        also changes the color of the parts of the sequence
        that are being searched
        """
        atLeastOneProteinFound = False
        protein_sub_sequence = self.boxPro.text()

        # dictionaries with ID as key and corresponding QTextEdit with protein sequence as value

        self.SequencSearchDict = {}
        self.SequencSearchDictDECOY = {}

        if self.decoycheck.isChecked():
            for protein_sequence in self.proteinListDECOY:
                if protein_sub_sequence in protein_sequence:
                    atLeastOneProteinFound = True
                    index = self.proteinListDECOY.index(protein_sequence)
                    ID = list(self.dictKeyAccessionDECOY.keys())[index]
                    Protein = self.proteinListDECOY[index]
                    Proteinname = self.proteinNameListDECOY[index]
                    OS = self.proteinOSListDECOY[index]

                    self.cg = QtWidgets.QTreeWidgetItem(self.tw)
                    self.cg.setData(0, 0, ID)
                    self.cg.setData(1, 0, OS)
                    self.cg.setData(2, 0, Proteinname)

                    self.textp = QTextEdit()
                    self.textp.resize(self.textp.width(), self.textp.height())
                    cuts = self.cutstring(Protein, protein_sub_sequence)
                    self.textp.insertPlainText("Proteinsequence: ")

                    for i in range(len(cuts)):
                        # while we are at the beginning of the list
                        if (cuts[i] == '' and i == 0):
                            self.textp.setTextColor(self.color)
                            self.textp.insertPlainText(protein_sub_sequence)
                            self.textp.setTextColor(self.colorblack)
                        # if we are in the middle of the list and the sub_string appears more than once
                        elif (cuts[i] == ''):
                            self.textp.setTextColor(self.color)
                            self.textp.insertPlainText(protein_sub_sequence)
                            self.textp.setTextColor(self.colorblack)
                        else:
                            if (i == len(cuts) - 1):
                                self.textp.insertPlainText(cuts[i])
                            else:
                                self.textp.insertPlainText(cuts[i])
                                self.textp.setTextColor(self.color)
                                self.textp.insertPlainText(
                                    protein_sub_sequence)
                                self.textp.setTextColor(self.colorblack)
                    self.textp.insertPlainText("\n")

                    self.textp.setReadOnly(True)
                    self.SequencSearchDictDECOY[ID] = self.textp

            header = self.tw.header()
            header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)
            self.tw.itemClicked.disconnect()
            self.tw.itemClicked.connect(self.clickTreeItemSeqSearchDecoy)

        else:
            for protein_sequence in self.proteinList:
                if protein_sub_sequence in protein_sequence:
                    atLeastOneProteinFound = True
                    index = self.proteinList.index(protein_sequence)
                    ID = list(self.dictKeyAccession.keys())[index]
                    Protein = self.proteinList[index]
                    Proteinname = self.proteinNameList[index]
                    OS = self.proteinOSList[index]

                    self.cg = QtWidgets.QTreeWidgetItem(self.tw)
                    self.cg.setData(0, 0, ID)
                    self.cg.setData(1, 0, OS)
                    self.cg.setData(2, 0, Proteinname)

                    self.textp = QTextEdit()
                    self.textp.resize(self.textp.width(), self.textp.height())
                    cuts = self.cutstring(Protein, protein_sub_sequence)
                    self.textp.insertPlainText("Proteinsequence: ")

                    for i in range(len(cuts)):
                        # while we are at the beginning of the list

                        if (cuts[i] == '' and i == 0):
                            self.textp.setTextColor(self.color)
                            self.textp.insertPlainText(protein_sub_sequence)
                            self.textp.setTextColor(self.colorblack)

                        # while we are in the middle of the list

                        elif (cuts[i] == ''):
                            self.textp.setTextColor(self.color)
                            self.textp.insertPlainText(protein_sub_sequence)
                            self.textp.setTextColor(self.colorblack)
                        else:
                            if (i == len(cuts) - 1):
                                self.textp.insertPlainText(cuts[i])
                            else:
                                self.textp.insertPlainText(cuts[i])
                                self.textp.setTextColor(self.color)
                                self.textp.insertPlainText(
                                    protein_sub_sequence)
                                self.textp.setTextColor(self.colorblack)

                    self.textp.setReadOnly(True)
                    self.SequencSearchDict[ID] = self.textp

            header = self.tw.header()
            header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)
            self.tw.itemClicked.disconnect()
            self.tw.itemClicked.connect(self.clickTreeItemSeqSearch)

        if not atLeastOneProteinFound:
            self.msg = QMessageBox()
            self.msg.setIcon(QMessageBox.Information)
            self.msg.setText("No matching protein sequence found in database.")
            self.msg.setWindowTitle("Error")
            x = self.msg.exec_()

    def nameSearch(self):
        """Gets self and searches for Protein based on Proteinname
            and shows the result on QMainWindow, also adds a hyperlink for
            more Information

        Parameters
        ----------
        self : QMainWindow


        Returns
        -------
        nothing but changes the QMainWindow to show the Protein in treewidget
        """
        atLeastOneProteinFound = False
        protein_sub_name = self.boxPro.text()

        if self.decoycheck.isChecked():
            for protein_name in self.proteinNameListDECOY:
                if protein_sub_name in protein_name:
                    atLeastOneProteinFound = True
                    index = self.proteinNameListDECOY.index(protein_name)
                    ID = list(self.dictKeyAccessionDECOY.keys())[index]
                    Proteinname = protein_name
                    OS = self.proteinOSListDECOY[index]

                    self.cg = QtWidgets.QTreeWidgetItem(self.tw)
                    self.cg.setData(0, 0, ID)
                    self.cg.setData(1, 0, OS)
                    self.cg.setData(2, 0, Proteinname)

            header = self.tw.header()
            header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)
            self.tw.itemClicked.disconnect()
            self.tw.itemClicked.connect(self.clickTreeItemDecoy)

        else:
            for protein_name in self.proteinNameList:
                if protein_sub_name in protein_name:
                    atLeastOneProteinFound = True
                    index = self.proteinNameList.index(protein_name)
                    ID = list(self.dictKeyAccession.keys())[index]
                    Proteinname = self.proteinNameList[index]
                    OS = self.proteinOSList[index]

                    self.cg = QtWidgets.QTreeWidgetItem(self.tw, )
                    self.cg.setData(0, 0, ID)
                    self.cg.setData(1, 0, OS)
                    self.cg.setData(2, 0, Proteinname)

            header = self.tw.header()
            header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            header.setStretchLastSection(True)
            self.tw.itemClicked.disconnect()
            self.tw.itemClicked.connect(self.clickTreeItem)

        if not atLeastOneProteinFound:
            self.msg = QMessageBox()
            self.msg.setIcon(QMessageBox.Information)
            self.msg.setText("No matching protein name found in database.")
            self.msg.setWindowTitle("Error")
            x = self.msg.exec_()
Example #55
0
class mainApp(QWidget):

    eventStarted = pyqtSignal(eventManager.eventManager)

    def __init__(self):
        super().__init__()
        self.initUI()
        self.manager = ButtonReleaseManager()
        self.manager.released.connect(self.show_position)
        self.manager.loopStop.connect(self.loopStop)

        self.eventThread = eventManager.eventThread(parent=self)
        self.eventManager = eventManager.eventManager(self.eventThread)

        self.pinList = deque()

    def initUI(self):

        mainLayout = QGridLayout()

        # 제일 위

        currentCoTextLabel = QLabel('현재 좌표: ', self)

        self.currentCoLabel = QLabel('', self)
        self.currentCoLabel.setStyleSheet("border :1px solid grey;")

        # fixCoTextLabel = QLabel('클릭 좌표: ', self)

        # self.fixCoLabel = QLabel('', self)
        # self.fixCoLabel.setStyleSheet("border :1px solid grey;")

        headerGroup = QButtonGroup(self)
        pinRadio = QRadioButton('PIN 입력')
        cashRadio = QRadioButton('기프트 구입')

        headerGroup.addButton(pinRadio)
        headerGroup.addButton(cashRadio)

        pinRadio.setChecked(True)

        # 중간

        inputTypeTextLabel = QLabel('동작 구분: ', self)

        self.inputTypeCombobox = QComboBox(self)
        self.inputTypeCombobox.addItem('클릭')
        self.inputTypeCombobox.addItem('드래그')
        self.inputTypeCombobox.addItem('마우스이동')
        self.inputTypeCombobox.addItem('텍스트')
        self.inputTypeCombobox.addItem('핀입력')
        self.inputTypeCombobox.addItem('핫키')
        self.inputTypeCombobox.addItem('브라우저')
        self.inputTypeCombobox.addItem('컬쳐결과확인')
        self.inputTypeCombobox.addItem('해피결과확인')

        self.inputTypeCombobox.activated[str].connect(self.onActivated)

        self.startCoTextLabel = QLabel('시작 좌표', self)

        self.startCoText = QLineEdit(self)

        self.endCoTextLabel = QLabel('종료 좌표', self)
        self.endCoText = QLineEdit(self)

        self.typoTextLabel = QLabel('텍스트', self)
        self.typoText = QLineEdit(self)

        self.browserLabel = QLabel('URL', self)
        self.browserText = QLineEdit(self)

        hotkeyGroup = QButtonGroup(self)
        self.copyRadio = QRadioButton('복사')
        self.pasteRadio = QRadioButton('붙여넣기')
        self.closeRadio = QRadioButton('창닫기')

        hotkeyGroup.addButton(self.copyRadio)
        hotkeyGroup.addButton(self.pasteRadio)
        hotkeyGroup.addButton(self.closeRadio)

        delayTextLabel = QLabel('지연 시간', self)

        self.delayText = QLineEdit(self)

        actionTypeTextLabel = QLabel('동작 횟수', self)

        self.actionTypeCombobox = QComboBox(self)
        self.actionTypeCombobox.addItem('한번만')
        self.actionTypeCombobox.addItem('반복')

        self.addButton = QPushButton(self)
        self.addButton.setText('추가')
        self.addButton.clicked.connect(self.eventAdd)

        self.startButton = QPushButton(self)
        self.startButton.setText('시작')
        self.startButton.clicked.connect(self.macroStart)

        self.typoTextLabel.hide()
        self.typoText.hide()
        self.browserLabel.hide()
        self.browserText.hide()
        self.copyRadio.hide()
        self.pasteRadio.hide()
        self.closeRadio.hide()
        self.endCoText.setEnabled(False)

        self.copyRadio.setChecked(True)

        # 아래

        # self.pinLabel = QLabel()
        # self.pinLabel.setStyleSheet("border :1px solid grey;")

        self.pinLabelScrollArea = QScrollArea()
        self.pinLabelScrollArea.setWidgetResizable(True)
        self.pinScrollWidget = QWidget(self)
        pinScrollLayout = QVBoxLayout(self)

        self.pinScrollWidget.setLayout(pinScrollLayout)
        self.pinLabelScrollArea.setWidget(self.pinScrollWidget)

        self.eventLabelScrollArea = QScrollArea()
        self.eventLabelScrollArea.setWidgetResizable(True)

        self.scrollWidget = QWidget(self)

        # scrollLayout = QVBoxLayout(self)
        scrollLayout = QGridLayout(self)

        self.scrollWidget.setLayout(scrollLayout)

        # self.eventLabel = QLabel()
        self.eventLabelScrollArea.setWidget(self.scrollWidget)

        # 그리드에 쌓기

        mainLayout.addWidget(currentCoTextLabel, 0, 0)
        mainLayout.addWidget(self.currentCoLabel, 0, 1, 1, 3)
        # mainLayout.addWidget(fixCoTextLabel, 0, 4)
        # mainLayout.addWidget(self.fixCoLabel, 0, 5, 1, 3)
        mainLayout.addWidget(pinRadio, 0, 10)
        mainLayout.addWidget(cashRadio, 0, 11, 1, 2)

        mainLayout.addWidget(inputTypeTextLabel, 1, 0)
        mainLayout.addWidget(self.inputTypeCombobox, 1, 1)
        mainLayout.addWidget(self.startCoTextLabel, 1, 2)
        mainLayout.addWidget(self.startCoText, 1, 3)
        mainLayout.addWidget(self.endCoTextLabel, 1, 4)
        mainLayout.addWidget(self.endCoText, 1, 5)

        mainLayout.addWidget(self.typoTextLabel, 1, 2)
        mainLayout.addWidget(self.typoText, 1, 3, 1, 3)
        mainLayout.addWidget(self.browserLabel, 1, 2)
        mainLayout.addWidget(self.browserText, 1, 3, 1, 3)

        mainLayout.addWidget(self.copyRadio, 1, 2)
        mainLayout.addWidget(self.pasteRadio, 1, 3)
        mainLayout.addWidget(self.closeRadio, 1, 4)

        mainLayout.addWidget(delayTextLabel, 1, 6)
        mainLayout.addWidget(self.delayText, 1, 7)
        mainLayout.addWidget(actionTypeTextLabel, 1, 8)
        mainLayout.addWidget(self.actionTypeCombobox, 1, 9)
        mainLayout.addWidget(self.addButton, 1, 10)
        mainLayout.addWidget(self.startButton, 1, 11)

        mainLayout.addWidget(self.pinLabelScrollArea, 2, 0, 1, 10)
        mainLayout.addWidget(self.eventLabelScrollArea, 3, 0, 1, 10)

        # mouseTrackThread = threading.Thread(target=self.mouseTrack, args=())
        # mouseTrackThread.daemon = True
        # mouseTrackThread.start()

        self.setLayout(mainLayout)

        self.setWindowTitle('Sample Macro')
        self.setFixedSize(1280, 768)
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())
        self.show()

    def mouseTrack(self):
        while 1:
            x, y = pyautogui.position()
            self.currentCoLabel.setText('x={0}, y={1}'.format(x, y))

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            if self.eventThread.isRun:
                self.eventThread.isRun = False
                print('loop end')
            else:
                with open("eventScenario.json", "w") as json_file:
                    json.dump(self.eventManager.eventScenarioJson,
                              json_file,
                              indent=4)
                print('app end')
                self.close()

    def onActivated(self, text):
        self.startCoTextLabel.hide()
        self.startCoText.hide()
        self.endCoTextLabel.hide()
        self.endCoText.hide()
        self.typoTextLabel.hide()
        self.typoText.hide()
        self.browserLabel.hide()
        self.browserText.hide()
        self.copyRadio.hide()
        self.pasteRadio.hide()
        self.closeRadio.hide()

        self.startCoText.setText('')
        self.typoText.setText('')
        self.browserText.setText('')
        self.endCoText.setText('')
        self.delayText.setText('')

        if text == '클릭' or text == '마우스이동':
            self.startCoTextLabel.show()
            self.startCoText.show()
            self.endCoTextLabel.show()
            self.endCoText.show()
            self.endCoText.setEnabled(False)

        elif text == '드래그':
            self.startCoTextLabel.show()
            self.startCoText.show()
            self.endCoTextLabel.show()
            self.endCoText.show()
            self.endCoText.setEnabled(True)

        elif text == '텍스트':
            self.typoTextLabel.show()
            self.typoText.show()

        elif text == '핫키':
            self.copyRadio.show()
            self.pasteRadio.show()
            self.closeRadio.show()
            self.copyRadio.setChecked(True)

        elif text == '브라우저':
            self.browserLabel.show()
            self.browserText.show()

    def eventAdd(self):
        # print('add click')

        eventType = self.inputTypeCombobox.currentText()
        startXy = self.startCoText.text()
        endXy = self.endCoText.text()
        typoText = self.typoText.text()
        url = self.browserText.text()
        hotkey = ''

        if eventType == '핫키':
            if self.copyRadio.isChecked():
                hotkey = 'copy'
            elif self.pasteRadio.isChecked():
                hotkey = 'paste'
            else:
                hotkey = 'close'

        delay = self.delayText.text()
        actionType = self.actionTypeCombobox.currentIndex()

        self.clearEventLayout()

        newSeq = sequence.sequence(startXy, eventType, endXy, typoText, url,
                                   hotkey, delay, actionType, self.pinList)
        self.eventManager.addEvent(newSeq, actionType)
        self.buildEventLayout()

        # print(json.dumps(self.eventManager))

    def jsonEventAdd(self, jsonData):
        # print('add click')

        eventList = jsonData['eventList']
        repeatEventList = jsonData['repeatEventList']

        for eventSeq in eventList:
            eventType = eventSeq['eventType']
            startXy = eventSeq['startXy']
            endXy = eventSeq['endXy']
            typoText = eventSeq['text']
            url = eventSeq['url']
            hotkey = eventSeq['command']

            delay = eventSeq['delayTime']
            actionType = eventSeq['actionType']

            newSeq = sequence.sequence(startXy, eventType, endXy, typoText,
                                       url, hotkey, delay, actionType,
                                       self.pinList)
            self.eventManager.addEvent(newSeq, actionType)

        for eventSeq in repeatEventList:
            eventType = eventSeq['eventType']
            startXy = eventSeq['startXy']
            endXy = eventSeq['endXy']
            typoText = eventSeq['text']
            url = eventSeq['url']
            hotkey = eventSeq['command']

            delay = eventSeq['delayTime']
            actionType = eventSeq['actionType']

            newSeq = sequence.sequence(startXy, eventType, endXy, typoText,
                                       url, hotkey, delay, actionType,
                                       self.pinList)
            self.eventManager.addEvent(newSeq, actionType)

    def clearEventLayout(self):
        while self.scrollWidget.layout().count():
            item = self.scrollWidget.layout().takeAt(0)
            widget = item.widget()
            widget.deleteLater()

    def buildEventLayout(self):
        for idx, eventSeq in enumerate(self.eventManager.eventList):

            seqString = '동작구분={0}, 시작좌표={1}, 끝좌표={2}, 텍스트={3}, 주소={7}, 단축키={4}, 지연시간={5}, 반복구분={6}\n'.format(
                eventSeq.eventType, eventSeq.startXy, eventSeq.endXy,
                eventSeq.text, eventSeq.command, eventSeq.delayTime,
                eventSeq.actionType, eventSeq._url)

            eventLabel = QLabel(seqString)
            # eventEditButton = QPushButton()
            # eventEditButton.setText('수정')

            eventDeleteButton = QPushButton()
            eventDeleteButton.setText('삭제')

            # eventEditButton.clicked.connect(lambda checked, _idx = idx : self.eventEdit(_idx, eventSeq.actionType))
            eventDeleteButton.clicked.connect(
                lambda checked, _idx=idx: self.eventDelete(
                    _idx, eventSeq.actionType))

            self.scrollWidget.layout().addWidget(eventLabel, idx, 0)
            # self.scrollWidget.layout().addWidget(eventEditButton, idx, 1)
            self.scrollWidget.layout().addWidget(eventDeleteButton, idx, 2)

        for idx, repeatEventSeq in enumerate(self.eventManager.repeatEventList,
                                             len(self.eventManager.eventList)):

            seqString = '동작구분={0}, 시작좌표={1}, 끝좌표={2}, 텍스트={3}, 주소={7}단축키={4}, 지연시간={5}, 반복구분={6}\n'.format(
                repeatEventSeq.eventType, repeatEventSeq.startXy,
                repeatEventSeq.endXy, repeatEventSeq.text,
                repeatEventSeq.command, repeatEventSeq.delayTime,
                repeatEventSeq.actionType, repeatEventSeq._url)

            eventLabel = QLabel(seqString)
            # eventEditButton = QPushButton()
            # eventEditButton.setText('수정')

            eventDeleteButton = QPushButton()
            eventDeleteButton.setText('삭제')

            # eventEditButton.clicked.connect(lambda checked, _idx = idx - len(self.eventManager.eventList) : self.eventEdit(_idx, repeatEventSeq.actionType))
            eventDeleteButton.clicked.connect(
                lambda checked, _idx=idx - len(self.eventManager.eventList):
                self.eventDelete(_idx, repeatEventSeq.actionType))

            self.scrollWidget.layout().addWidget(eventLabel, idx, 0)
            # self.scrollWidget.layout().addWidget(eventEditButton, idx, 1)
            self.scrollWidget.layout().addWidget(eventDeleteButton, idx, 2)

    def macroStart(self):
        # print('start click')

        self.eventManager.executeEvent()

    # def on_click(self, x, y, button, pressed):
    #     if pressed == True:
    #         print(x,y)

    def eventEdit(self, _index, actionType):
        print('actionType:{0} index:{1} edit click'.format(actionType, _index))

    def eventDelete(self, _index, actionType):
        # print('actionType:{0} index:{1} delete click'.format(actionType, _index))

        if actionType == 0:
            del self.eventManager.eventList[_index]
            del self.eventManager.eventScenarioJson['eventList'][_index]
        elif actionType == 1:
            del self.eventManager.repeatEventList[_index]
            del self.eventManager.eventScenarioJson['repeatEventList'][_index]

        self.clearEventLayout()
        self.buildEventLayout()

    @pyqtSlot()
    def show_position(self):
        x, y = pyautogui.position()
        coordText = '{0}, {1}'.format(x, y)
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(coordText, win32clipboard.CF_TEXT)
        win32clipboard.CloseClipboard()

        self.currentCoLabel.setText(coordText)

    @pyqtSlot()
    def loopStop(self):
        self.eventManager.isRun = False
        self.eventThread.isRun = False
        print('crtl+d: loop stop')

    def pinLoad(self, _data):
        pinData = _data['pinData']
        count = 0
        # for i in range(2) :
        for pinString in pinData:

            self.pinList.append(pinString)

            pinText = '{0}: {1}'.format(count, pinString)

            pinLabel = QLabel(pinText)

            self.pinScrollWidget.layout().addWidget(pinLabel)
            count += 1
Example #56
0
    def __init__(self, nbprocessors):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.taskset = None

        # Utilizations:
        vbox_utilizations = QVBoxLayout()
        group = QGroupBox("Task Utilizations:")

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Generator:", self))
        self.comboGenerator = QComboBox()
        self.comboGenerator.addItem("RandFixedSum")
        self.comboGenerator.addItem("UUniFast-Discard")
        self.comboGenerator.addItem("Kato's method")
        self.comboGenerator.currentIndexChanged.connect(self.generator_changed)
        hbox.addWidget(self.comboGenerator)
        vbox_utilizations.addLayout(hbox)

        # Load slider + spinner:
        hbox_load = QHBoxLayout()
        sld = _DoubleSlider(QtCore.Qt.Horizontal, self)
        sld.setMinimum(0)
        sld.setMaximum(32)
        self.spin_load = QDoubleSpinBox(self)
        self.spin_load.setMinimum(0)
        self.spin_load.setMaximum(32)
        self.spin_load.setSingleStep(0.1)
        hbox_load.addWidget(QLabel("Total utilization: ", self))
        hbox_load.addWidget(sld)
        hbox_load.addWidget(self.spin_load)
        sld.doubleValueChanged.connect(self.spin_load.setValue)
        self.spin_load.valueChanged.connect(sld.setValue)
        self.spin_load.setValue(nbprocessors / 2.)
        vbox_utilizations.addLayout(hbox_load)

        # Number of periodic tasks:
        self.hbox_tasks = QHBoxLayout()
        self.spin_tasks = QSpinBox(self)
        self.spin_tasks.setMinimum(0)
        self.spin_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self))
        self.hbox_tasks.addStretch(1)
        self.hbox_tasks.addWidget(self.spin_tasks)
        vbox_utilizations.addLayout(self.hbox_tasks)

        # Number of sporadic tasks:
        self.hbox_sporadic_tasks = QHBoxLayout()
        self.spin_sporadic_tasks = QSpinBox(self)
        self.spin_sporadic_tasks.setMinimum(0)
        self.spin_sporadic_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_sporadic_tasks.addWidget(
            QLabel("Number of sporadic tasks: ", self))
        self.hbox_sporadic_tasks.addStretch(1)
        self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks)
        vbox_utilizations.addLayout(self.hbox_sporadic_tasks)

        # Min / Max utilizations
        self.hbox_utilizations = QHBoxLayout()
        self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ",
                                                self))
        self.interval_utilization = IntervalSpinner(
            self, min_=0, max_=1, step=.01, round_option=False)
        self.hbox_utilizations.addWidget(self.interval_utilization)
        vbox_utilizations.addLayout(self.hbox_utilizations)

        group.setLayout(vbox_utilizations)
        self.layout.addWidget(group)

        # Periods:
        vbox_periods = QVBoxLayout()
        group = QGroupBox("Task Periods:")

        # Log uniform
        self.lunif = QRadioButton("log-uniform distribution between:")
        vbox_periods.addWidget(self.lunif)
        self.lunif.setChecked(True)

        self.lunif_interval = IntervalSpinner(self)
        self.lunif_interval.setEnabled(self.lunif.isChecked())
        self.lunif.toggled.connect(self.lunif_interval.setEnabled)
        vbox_periods.addWidget(self.lunif_interval)

        # Uniform
        self.unif = QRadioButton("uniform distribution between:")
        vbox_periods.addWidget(self.unif)

        self.unif_interval = IntervalSpinner(self)
        self.unif_interval.setEnabled(self.unif.isChecked())
        self.unif.toggled.connect(self.unif_interval.setEnabled)
        vbox_periods.addWidget(self.unif_interval)

        # Discrete
        discrete = QRadioButton("chosen among these (space separated) values:")
        vbox_periods.addWidget(discrete)

        self.periods = QLineEdit(self)
        self.periods.setValidator(QRegExpValidator(
            QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$")))

        vbox_periods.addWidget(self.periods)
        self.periods.setEnabled(discrete.isChecked())
        discrete.toggled.connect(self.periods.setEnabled)
        vbox_periods.addStretch(1)

        group.setLayout(vbox_periods)
        self.layout.addWidget(group)

        buttonBox = QDialogButtonBox()
        cancel = buttonBox.addButton(QDialogButtonBox.Cancel)
        generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole)
        cancel.clicked.connect(self.reject)
        generate.clicked.connect(self.generate)
        self.layout.addWidget(buttonBox)

        self.show_randfixedsum_options()
Example #57
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300, 400)
        self.setWindowTitle("Pizza Bestellung")

        # Widgets
        self.preis = 6
        # Alle Label definieren
        self.grLabel = QLabel("Größe der Pizza")
        self.zutLabel = QLabel("Was soll drauf?")
        self.extraLabel = QLabel("Sonderwünsche: ")


        # Radiobuttons definiert und gruppiert
        self.gRadio = QRadioButton("Groß")
        self.gRadio.setChecked(True)
        self.mRadio = QRadioButton("Mittel")
        self.kRadio = QRadioButton("Klein")
        self.size = QButtonGroup()
        self.size.addButton(self.gRadio)
        self.size.addButton(self.mRadio)
        self.size.addButton(self.kRadio)
        self.preisLabel = QLabel(f"Der Preis ist {self.preis}")

        self.size.buttonClicked.connect(self.price)

        # checkboxen definieren
        self.tomate = QCheckBox("Tomate")
        self.tomate.clicked.connect(self.price)
        self.bacon = QCheckBox("Bacon")
        self.bacon.clicked.connect(self.price)
        self.salami = QCheckBox("Salami")
        self.salami.clicked.connect(self.price)
        self.cheese = QCheckBox("Käse")
        self.cheese.clicked.connect(self.price)
        self.chili = QCheckBox("Chili")
        self.chili.clicked.connect(self.price)
        self.pilze = QCheckBox("Pilze")
        self.pilze.clicked.connect(self.price)

        # Textfeld
        self.extraText = QTextEdit()

        # Layout

        rahmen = QVBoxLayout()

        grLayout = QHBoxLayout()
        grLayout.addWidget(self.gRadio)
        grLayout.addWidget(self.mRadio)
        grLayout.addWidget(self.kRadio)

        zutLayout = QGridLayout()
        zutLayout.addWidget(self.tomate, 0, 0)
        zutLayout.addWidget(self.bacon, 0 ,1)
        zutLayout.addWidget(self.salami, 0 , 2)
        zutLayout.addWidget(self.cheese, 1, 0)
        zutLayout.addWidget(self.chili, 1 , 1)
        zutLayout.addWidget(self.pilze, 1, 2)


        rahmen.addWidget(self.grLabel)
        rahmen.addLayout(grLayout)
        rahmen.addWidget(self.zutLabel)
        rahmen.addLayout(zutLayout)
        rahmen.addWidget(self.extraLabel)
        rahmen.addWidget(self.extraText)
        rahmen.addWidget(self.preisLabel)

        self.setLayout(rahmen)
        self.show()

    def price(self):
        # print(self.size.checkedButton().text())
        if self.gRadio.isChecked():
            self.preis = 6
        elif self.mRadio.isChecked():
            self.preis = 4
        elif self.kRadio.isChecked():
            self.preis = 2

        if self.tomate.isChecked():
            self.preis += 1
        if self.bacon.isChecked():
            self.preis += 1
        if self.cheese.isChecked():
            self.preis += 1
        if self.chili.isChecked():
            self.preis += 1
        if self.salami.isChecked():
            self.preis += 1
        if self.pilze.isChecked():
            self.preis += 1

        self.preisLabel.setText(f"Der Preis ist {self.preis:.2f}€")
Example #58
0
class GroupsWindow(QWidget):
    leftGroups = ["@MMK_L", "public.kern1"]
    rightGroups = ["@MMK_R", "public.kern2"]

    def __init__(self, font, parent=None):
        super(GroupsWindow, self).__init__(parent, Qt.Window)
        self.font = font
        self.font.addObserver(self, "_groupsChanged", "Groups.Changed")

        groups = self.font.groups.keys()
        self.groupsList = GroupListWidget(groups, self)
        self.groupsList.currentItemChanged.connect(self._groupChanged)
        self.groupsList.itemChanged.connect(self._groupRenamed)
        self.groupsList.setFocus(True)

        self.stackWidget = GroupStackWidget(self.font, parent=self)

        self.addGroupButton = QPushButton("+", self)
        self.addGroupButton.clicked.connect(self._groupAdd)
        self.removeGroupButton = QPushButton("−", self)
        self.removeGroupButton.clicked.connect(self._groupDelete)
        if not groups:
            self.removeGroupButton.setEnabled(False)

        self.alignLeftBox = QRadioButton("Align left", self)
        self.alignRightBox = QRadioButton("Align right", self)
        self.alignLeftBox.setChecked(True)
        self.alignLeftBox.toggled.connect(self._alignmentChanged)
        self._autoDirection = True

        self.collectionWidget = GroupCollectionWidget(parent=self)
        self.collectionWidget.characterDeletionCallback = \
            self.characterDeleteEvent
        self.collectionWidget.characterDropCallback = self.characterDropEvent
        self._cachedName = None

        layout = QGridLayout(self)
        layout.addWidget(self.groupsList, 0, 0, 5, 4)
        layout.addWidget(self.stackWidget, 0, 4, 5, 4)
        layout.addWidget(self.addGroupButton, 5, 0)
        layout.addWidget(self.removeGroupButton, 5, 3)
        layout.addWidget(self.alignLeftBox, 5, 4)
        layout.addWidget(self.alignRightBox, 5, 7)
        layout.addWidget(self.collectionWidget.scrollArea(), 6, 0, 4, 8)
        # TODO: calib this more
        layout.setColumnStretch(4, 1)
        self.setLayout(layout)
        self.adjustSize()

        self.setWindowTitle("Groups window – %s %s" % (
            self.font.info.familyName, self.font.info.styleName))

    def _alignmentChanged(self):
        alignRight = self.alignRightBox.isChecked()
        self.stackWidget.setAlignment(alignRight)

    def _groupAdd(self):
        groupName = "New group"
        if groupName in self.font.groups:
            index = 1
            while "%s %d" % (groupName, index) in self.font.groups:
                index += 1
            groupName = "%s %d" % (groupName, index)
        self.font.groups[groupName] = []
        item = QListWidgetItem(groupName, self.groupsList)
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self.groupsList.setCurrentItem(item)
        self.groupsList.editItem(item)
        self.removeGroupButton.setEnabled(True)

    def _groupChanged(self):
        currentItem = self.groupsList.currentItem()
        if currentItem is None:
            return
        self._cachedName = currentItem.text()
        if self._autoDirection:
            for name in self.leftGroups:
                if self._cachedName.startswith(name):
                    self.alignRightBox.setChecked(True)
                    break
            for name in self.rightGroups:
                if self._cachedName.startswith(name):
                    self.alignLeftBox.setChecked(True)
                    break
        glyphs = []
        for gName in self.font.groups[self._cachedName]:
            if gName in self.font:
                glyphs.append(self.font[gName])
        self.stackWidget.setGlyphs(glyphs)
        self.collectionWidget.glyphs = glyphs

    def _groupRenamed(self):
        currentItem = self.groupsList.currentItem()
        if currentItem is None:
            return
        newKey = currentItem.text()
        if newKey == self._cachedName:
            return
        self.font.groups[newKey] = self.font.groups[self._cachedName]
        del self.font.groups[self._cachedName]
        self._cachedName = newKey

    def _groupDelete(self):
        newKey = self.groupsList.currentItem().text()
        del self.font.groups[newKey]
        self.groupsList.takeItem(self.groupsList.currentRow())
        if not self.font.groups.keys():
            self.removeGroupButton.setEnabled(False)
        self._groupChanged()

    # XXX: it seems the notification doesn't trigger...
    def _groupsChanged(self, notification):
        self._cachedName = None
        self.groupsList.blockSignals(True)
        self.groupsList.clear()
        self.groupsList.fillGroupNames(self)
        # TODO: consider transferring currentGroup as well
        self.groupsList.blockSignals(False)
        # self.groupsList.setCurrentRow(0)

    def characterDeleteEvent(self, selection):
        currentGroup = self.groupsList.currentItem().text()
        currentGroupList = self.font.groups[currentGroup]
        # relying on ordered group elements
        # reverse to not change index of smaller elements
        for key in sorted(selection, reverse=True):
            del currentGroupList[key]
        self.font.groups[currentGroup] = currentGroupList
        self._groupChanged()

    def characterDropEvent(self, event):
        currentGroup = self.groupsList.currentItem()
        if currentGroup is None:
            return
        currentGroup = currentGroup.text()
        glyphNames = event.mimeData().text().split(" ")
        for gName in glyphNames:
            # TODO: should we accept template glyphs here?
            if self.font[gName].template:
                continue
            # Due to defcon limitations, we must fetch and update for the
            # notification to pass through
            currentGroupList = self.font.groups[currentGroup]
            # TODO: decouple better
            index = self.collectionWidget.currentDropIndex
            currentGroupList.insert(index, gName)
            self.font.groups[currentGroup] = currentGroupList
        event.acceptProposedAction()
        self._groupChanged()

    def closeEvent(self, event):
        self.font.removeObserver(self, "Groups.Changed")
        event.accept()
Example #59
0
class StockTab(OptionsWidget):
    def __init__(self, parent):
        super().__init__(parent)

    def add_contents(self):
        self.add_configure(1)         
        self.add_time_period(3)
        self.add_choice(5)       
        self.add_radio(7)       
        self.add_start_button(9)

    def add_choice(self, h):
        self.checkAktien = QCheckBox("Aktien")
        self.checkFonds = QCheckBox("Fonds")
        self.checkAktien.setChecked(True) 
        self.checkFonds.setChecked(True) 
        self.layout.addWidget(QLabel("Wertpapiere"), h, 0)        
        self.layout.addWidget(self.checkAktien, h, 1)
        self.layout.addWidget(self.checkFonds, h, 2 )

        newl = QLabel()
        newl.setFrameStyle(QFrame.HLine )
        self.layout.addWidget(newl, h+1, 0, 1, 3)


       

    def add_radio(self, h):	
        self.radioPlot2 = QRadioButton("Absolut")	 
        self.radioPlot1 = QRadioButton("Relativ")	 
        self.radioPlot2.setChecked(True) 	   
        # self.layout.addWidget(QColumn(self.radioPlot1, self.radioPlot2 ))
        self.layout.addWidget(QLabel("Veränderungen"), h, 0)
        self.layout.addWidget(self.radioPlot1, h, 1)
        self.layout.addWidget(self.radioPlot2, h, 2 )



    def on_pushButton_config(self):
        to_dict = lambda x: {y: 1 for y in x}
        self.cw = ConfigWindow(self, [to_dict(self.parent.DEPOT.stocks), to_dict(self.parent.DEPOT.fonds)], 
            ["Aktien","Fonds"], self.parent.DEPOT)
        self.cw.show()        

    def on_pushButton_start(self):
        self.set_dates()        
        all_keys = []
        if self.checkFonds.isChecked():
            all_keys += self.parent.DEPOT.fonds 
        if self.checkAktien.isChecked():
            all_keys += self.parent.DEPOT.stocks 

        selected_keys = [x for x in all_keys if x in self.parent.DEPOT.is_included]

        if self.radioPlot1.isChecked():
            relativ = True
        else:
            relativ = False


        arguments_relative = [self.parent.DEPOT.df_depot, selected_keys,
                self.date_start, self.date_end, relativ]             

        arguments = [self.parent.DEPOT.df_depot, selected_keys,
                self.date_start, self.date_end]                

                             

        self.new_plot_window = NewPlotWindow(
            arg1=["ScatterPlot", *analyse.prepare_scatter_total_change_stocks(*arguments_relative), "Gesamte Veränderung des Depots"],
            arg2=["ScatterPlotBar", *analyse.prepare_scatter_daily_changes_stocks(*arguments_relative), "Tägliche Veränderung des Depots"],                                     
            arg3=["StackedBar", *analyse.prepare_stacked_bar_stocks(*arguments), "Absolute Zusammensetzung des Depots"], 
            arg4=["PieChart", *analyse.prepare_pie_total_stocks(*arguments), "Prozentuale Zusammensetzung des Depots"],
            title="Plots")
        self.new_plot_window.show()  
        self.update_data(self.new_plot_window, *arguments)          

    def update_data(self, target, df, keywords, start, end):
        use_data = analyse.last_entry_of_month_stocks(df, keywords, start, end)
        data_tab = DataTabs(target, use_data, rows=4)          
Example #60
0
class MainWindow(QMainWindow):
    receiveUpdateSignal = pyqtSignal(str)
    errorSignal = pyqtSignal(str)
    isDetectSerialPort = False
    receiveCount = 0
    sendCount = 0
    isScheduledSending = False
    DataPath = "./"
    isHideSettings = False
    isHideFunctinal = True
    app = None
    isWaveOpen = False

    def __init__(self,app):
        super().__init__()
        self.app = app
        pathDirList = sys.argv[0].replace("\\", "/").split("/")
        pathDirList.pop()
        self.DataPath = os.path.abspath("/".join(str(i) for i in pathDirList))
        if not os.path.exists(self.DataPath + "/" + parameters.strDataDirName):
            pathDirList.pop()
            self.DataPath = os.path.abspath("/".join(str(i) for i in pathDirList))
        self.DataPath = (self.DataPath + "/" + parameters.strDataDirName).replace("\\", "/")
        self.initWindow()
        self.initTool()
        self.initEvent()
        self.programStartGetSavedParameters()
        return

    def __del__(self):
        return
    def initTool(self):
        self.com = serial.Serial()
        return

    def initWindow(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        # main layout
        frameWidget = QWidget()
        mainWidget = QSplitter(Qt.Horizontal)
        frameLayout = QVBoxLayout()
        self.settingWidget = QWidget()
        self.settingWidget.setProperty("class","settingWidget")
        self.receiveSendWidget = QSplitter(Qt.Vertical)
        self.functionalWiget = QWidget()
        settingLayout = QVBoxLayout()
        sendReceiveLayout = QVBoxLayout()
        sendFunctionalLayout = QVBoxLayout()
        mainLayout = QHBoxLayout()
        self.settingWidget.setLayout(settingLayout)
        self.receiveSendWidget.setLayout(sendReceiveLayout)
        self.functionalWiget.setLayout(sendFunctionalLayout)
        mainLayout.addWidget(self.settingWidget)
        mainLayout.addWidget(self.receiveSendWidget)
        mainLayout.addWidget(self.functionalWiget)
        mainLayout.setStretch(0,2)
        mainLayout.setStretch(1, 6)
        mainLayout.setStretch(2, 2)
        menuLayout = QHBoxLayout()
        mainWidget.setLayout(mainLayout)
        frameLayout.addLayout(menuLayout)
        frameLayout.addWidget(mainWidget)
        frameWidget.setLayout(frameLayout)
        self.setCentralWidget(frameWidget)

        # option layout
        self.settingsButton = QPushButton()
        self.skinButton = QPushButton("")
        self.waveButton = QPushButton("")
        self.aboutButton = QPushButton()
        self.functionalButton = QPushButton()
        self.encodingCombobox = ComboBox()
        self.encodingCombobox.addItem("ASCII")
        self.encodingCombobox.addItem("UTF-8")
        self.encodingCombobox.addItem("UTF-16")
        self.encodingCombobox.addItem("GBK")
        self.encodingCombobox.addItem("GB2312")
        self.encodingCombobox.addItem("GB18030")
        self.settingsButton.setProperty("class", "menuItem1")
        self.skinButton.setProperty("class", "menuItem2")
        self.aboutButton.setProperty("class", "menuItem3")
        self.functionalButton.setProperty("class", "menuItem4")
        self.waveButton.setProperty("class", "menuItem5")
        self.settingsButton.setObjectName("menuItem")
        self.skinButton.setObjectName("menuItem")
        self.aboutButton.setObjectName("menuItem")
        self.functionalButton.setObjectName("menuItem")
        self.waveButton.setObjectName("menuItem")
        menuLayout.addWidget(self.settingsButton)
        menuLayout.addWidget(self.skinButton)
        menuLayout.addWidget(self.waveButton)
        menuLayout.addWidget(self.aboutButton)
        menuLayout.addStretch(0)
        menuLayout.addWidget(self.encodingCombobox)
        menuLayout.addWidget(self.functionalButton)


        # widgets receive and send area
        self.receiveArea = QTextEdit()
        self.sendArea = QTextEdit()
        self.clearReceiveButtion = QPushButton(parameters.strClearReceive)
        self.sendButtion = QPushButton(parameters.strSend)
        self.sendHistory = ComboBox()
        sendWidget = QWidget()
        sendAreaWidgetsLayout = QHBoxLayout()
        sendWidget.setLayout(sendAreaWidgetsLayout)
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.clearReceiveButtion)
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.sendButtion)
        sendAreaWidgetsLayout.addWidget(self.sendArea)
        sendAreaWidgetsLayout.addLayout(buttonLayout)
        sendReceiveLayout.addWidget(self.receiveArea)
        sendReceiveLayout.addWidget(sendWidget)
        sendReceiveLayout.addWidget(self.sendHistory)
        sendReceiveLayout.setStretch(0, 7)
        sendReceiveLayout.setStretch(1, 2)
        sendReceiveLayout.setStretch(2, 1)

        # widgets serial settings
        serialSettingsGroupBox = QGroupBox(parameters.strSerialSettings)
        serialSettingsLayout = QGridLayout()
        serialReceiveSettingsLayout = QGridLayout()
        serialSendSettingsLayout = QGridLayout()
        serialPortLabek = QLabel(parameters.strSerialPort)
        serailBaudrateLabel = QLabel(parameters.strSerialBaudrate)
        serailBytesLabel = QLabel(parameters.strSerialBytes)
        serailParityLabel = QLabel(parameters.strSerialParity)
        serailStopbitsLabel = QLabel(parameters.strSerialStopbits)
        self.serialPortCombobox = ComboBox()
        self.serailBaudrateCombobox = ComboBox()
        self.serailBaudrateCombobox.addItem("9600")
        self.serailBaudrateCombobox.addItem("19200")
        self.serailBaudrateCombobox.addItem("38400")
        self.serailBaudrateCombobox.addItem("57600")
        self.serailBaudrateCombobox.addItem("115200")
        self.serailBaudrateCombobox.setCurrentIndex(4)
        self.serailBaudrateCombobox.setEditable(True)
        self.serailBytesCombobox = ComboBox()
        self.serailBytesCombobox.addItem("5")
        self.serailBytesCombobox.addItem("6")
        self.serailBytesCombobox.addItem("7")
        self.serailBytesCombobox.addItem("8")
        self.serailBytesCombobox.setCurrentIndex(3)
        self.serailParityCombobox = ComboBox()
        self.serailParityCombobox.addItem("None")
        self.serailParityCombobox.addItem("Odd")
        self.serailParityCombobox.addItem("Even")
        self.serailParityCombobox.addItem("Mark")
        self.serailParityCombobox.addItem("Space")
        self.serailParityCombobox.setCurrentIndex(0)
        self.serailStopbitsCombobox = ComboBox()
        self.serailStopbitsCombobox.addItem("1")
        self.serailStopbitsCombobox.addItem("1.5")
        self.serailStopbitsCombobox.addItem("2")
        self.serailStopbitsCombobox.setCurrentIndex(0)
        self.checkBoxRts = QCheckBox("rts")
        self.checkBoxDtr = QCheckBox("dtr")
        self.serialOpenCloseButton = QPushButton(parameters.strOpen)
        serialSettingsLayout.addWidget(serialPortLabek,0,0)
        serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0)
        serialSettingsLayout.addWidget(serailBytesLabel, 2, 0)
        serialSettingsLayout.addWidget(serailParityLabel, 3, 0)
        serialSettingsLayout.addWidget(serailStopbitsLabel, 4, 0)
        serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1)
        serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1)
        serialSettingsLayout.addWidget(self.serailBytesCombobox, 2, 1)
        serialSettingsLayout.addWidget(self.serailParityCombobox, 3, 1)
        serialSettingsLayout.addWidget(self.serailStopbitsCombobox, 4, 1)
        serialSettingsLayout.addWidget(self.checkBoxRts, 5, 0,1,1)
        serialSettingsLayout.addWidget(self.checkBoxDtr, 5, 1,1,1)
        serialSettingsLayout.addWidget(self.serialOpenCloseButton, 6, 0,1,2)
        serialSettingsGroupBox.setLayout(serialSettingsLayout)
        settingLayout.addWidget(serialSettingsGroupBox)

        # serial receive settings
        serialReceiveSettingsGroupBox = QGroupBox(parameters.strSerialReceiveSettings)
        self.receiveSettingsAscii = QRadioButton(parameters.strAscii)
        self.receiveSettingsHex = QRadioButton(parameters.strHex)
        self.receiveSettingsAscii.setChecked(True)
        self.receiveSettingsAutoLinefeed = QCheckBox(parameters.strAutoLinefeed)
        self.receiveSettingsAutoLinefeedTime = QLineEdit(parameters.strAutoLinefeedTime)
        self.receiveSettingsAutoLinefeed.setMaximumWidth(75)
        self.receiveSettingsAutoLinefeedTime.setMaximumWidth(75)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAscii,1,0,1,1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsHex,1,1,1,1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAutoLinefeed, 2, 0, 1, 1)
        serialReceiveSettingsLayout.addWidget(self.receiveSettingsAutoLinefeedTime, 2, 1, 1, 1)
        serialReceiveSettingsGroupBox.setLayout(serialReceiveSettingsLayout)
        settingLayout.addWidget(serialReceiveSettingsGroupBox)

        # serial send settings
        serialSendSettingsGroupBox = QGroupBox(parameters.strSerialSendSettings)
        self.sendSettingsAscii = QRadioButton(parameters.strAscii)
        self.sendSettingsHex = QRadioButton(parameters.strHex)
        self.sendSettingsAscii.setChecked(True)
        self.sendSettingsScheduledCheckBox = QCheckBox(parameters.strScheduled)
        self.sendSettingsScheduled = QLineEdit(parameters.strScheduledTime)
        self.sendSettingsScheduledCheckBox.setMaximumWidth(75)
        self.sendSettingsScheduled.setMaximumWidth(75)
        self.sendSettingsCFLF = QCheckBox(parameters.strCRLF)
        self.sendSettingsCFLF.setChecked(False)
        serialSendSettingsLayout.addWidget(self.sendSettingsAscii,1,0,1,1)
        serialSendSettingsLayout.addWidget(self.sendSettingsHex,1,1,1,1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduledCheckBox, 2, 0, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsScheduled, 2, 1, 1, 1)
        serialSendSettingsLayout.addWidget(self.sendSettingsCFLF, 3, 0, 1, 2)
        serialSendSettingsGroupBox.setLayout(serialSendSettingsLayout)
        settingLayout.addWidget(serialSendSettingsGroupBox)

        settingLayout.setStretch(0, 5)
        settingLayout.setStretch(1, 2.5)
        settingLayout.setStretch(2, 2.5)

        # right functional layout
        self.addButton = QPushButton(parameters.strAdd)
        functionalGroupBox = QGroupBox(parameters.strFunctionalSend)
        functionalGridLayout = QGridLayout()
        functionalGridLayout.addWidget(self.addButton,0,1)
        functionalGroupBox.setLayout(functionalGridLayout)
        sendFunctionalLayout.addWidget(functionalGroupBox)
        self.isHideFunctinal = True
        self.hideFunctional()

        # main window
        self.statusBarStauts = QLabel()
        self.statusBarStauts.setMinimumWidth(80)
        self.statusBarStauts.setText("<font color=%s>%s</font>" %("#008200", parameters.strReady))
        self.statusBarSendCount = QLabel(parameters.strSend+"(bytes): "+"0")
        self.statusBarReceiveCount = QLabel(parameters.strReceive+"(bytes): "+"0")
        self.statusBar().addWidget(self.statusBarStauts)
        self.statusBar().addWidget(self.statusBarSendCount,2)
        self.statusBar().addWidget(self.statusBarReceiveCount,3)
        # self.statusBar()

        self.resize(800, 500)
        self.MoveToCenter()
        self.setWindowTitle(parameters.appName+" V"+str(helpAbout.versionMajor)+"."+str(helpAbout.versionMinor))
        icon = QIcon()
        print("icon path:"+self.DataPath+"/"+parameters.appIcon)
        icon.addPixmap(QPixmap(self.DataPath+"/"+parameters.appIcon), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("comtool")
        self.show()
        return

    def initEvent(self):
        self.serialOpenCloseButton.clicked.connect(self.openCloseSerial)
        self.sendButtion.clicked.connect(self.sendData)
        self.receiveUpdateSignal.connect(self.updateReceivedDataDisplay)
        self.clearReceiveButtion.clicked.connect(self.clearReceiveBuffer)
        self.serialPortCombobox.clicked.connect(self.portComboboxClicked)
        self.sendSettingsHex.clicked.connect(self.onSendSettingsHexClicked)
        self.sendSettingsAscii.clicked.connect(self.onSendSettingsAsciiClicked)
        self.errorSignal.connect(self.errorHint)
        self.sendHistory.currentIndexChanged.connect(self.sendHistoryIndexChanged)
        self.settingsButton.clicked.connect(self.showHideSettings)
        self.skinButton.clicked.connect(self.skinChange)
        self.aboutButton.clicked.connect(self.showAbout)
        self.addButton.clicked.connect(self.functionAdd)
        self.functionalButton.clicked.connect(self.showHideFunctional)
        self.sendArea.currentCharFormatChanged.connect(self.sendAreaFontChanged)
        self.waveButton.clicked.connect(self.openWaveDisplay)
        self.checkBoxRts.clicked.connect(self.rtsChanged)
        self.checkBoxDtr.clicked.connect(self.dtrChanged)
        return


    def openCloseSerialProcess(self):
        try:
            if self.com.is_open:
                self.com.close()
                self.serialOpenCloseButton.setText(parameters.strOpen)
                self.statusBarStauts.setText("<font color=%s>%s</font>" % ("#f31414", parameters.strClosed))
                self.receiveProgressStop = True
                self.serialPortCombobox.setDisabled(False)
                self.serailBaudrateCombobox.setDisabled(False)
                self.serailParityCombobox.setDisabled(False)
                self.serailStopbitsCombobox.setDisabled(False)
                self.serailBytesCombobox.setDisabled(False)
                self.programExitSaveParameters()
            else:
                try:
                    self.com.baudrate = int(self.serailBaudrateCombobox.currentText())
                    self.com.port = self.serialPortCombobox.currentText().split(" ")[0]
                    self.com.bytesize = int(self.serailBytesCombobox.currentText())
                    self.com.parity = self.serailParityCombobox.currentText()[0]
                    self.com.stopbits = float(self.serailStopbitsCombobox.currentText())
                    self.com.timeout = None
                    if self.checkBoxRts.isChecked():
                        self.com.rts = False
                    else:
                        self.com.rts = True
                    if self.checkBoxDtr.isChecked():
                        self.com.dtr = False
                    else:
                        self.com.dtr = True
                    print(self.com)
                    self.serialOpenCloseButton.setDisabled(True)
                    self.com.open()
                    self.serialOpenCloseButton.setText(parameters.strClose)
                    self.statusBarStauts.setText("<font color=%s>%s</font>" % ("#008200", parameters.strReady))
                    self.serialPortCombobox.setDisabled(True)
                    self.serailBaudrateCombobox.setDisabled(True)
                    self.serailParityCombobox.setDisabled(True)
                    self.serailStopbitsCombobox.setDisabled(True)
                    self.serailBytesCombobox.setDisabled(True)
                    self.serialOpenCloseButton.setDisabled(False)
                    receiveProcess = threading.Thread(target=self.receiveData)
                    receiveProcess.setDaemon(True)
                    receiveProcess.start()
                except Exception as e:
                    self.com.close()
                    self.receiveProgressStop = True
                    self.errorSignal.emit( parameters.strOpenFailed +"\n"+ str(e))
                    self.serialOpenCloseButton.setDisabled(False)
        except Exception:
            pass
        return

    def openCloseSerial(self):
        t = threading.Thread(target=self.openCloseSerialProcess)
        t.setDaemon(True)
        t.start()
        return

    def rtsChanged(self):
        if self.checkBoxRts.isChecked():
            self.com.setRTS(False)
        else:
            self.com.setRTS(True)
    
    def dtrChanged(self):
        if self.checkBoxDtr.isChecked():
            self.com.setDTR(False)
        else:
            self.com.setDTR(True)

    def portComboboxClicked(self):
        self.detectSerialPort()
        return

    def getSendData(self):
        data = self.sendArea.toPlainText()
        if self.sendSettingsCFLF.isChecked():
            data = data.replace("\n", "\r\n")
        if self.sendSettingsHex.isChecked():
            if self.sendSettingsCFLF.isChecked():
                data = data.replace("\r\n", " ")
            else:
                data = data.replace("\n", " ")
            data = self.hexStringB2Hex(data)
            if data == -1:
                self.errorSignal.emit( parameters.strWriteFormatError)
                return -1
        else:
            data = data.encode(self.encodingCombobox.currentText(),"ignore")
        return data

    def sendData(self):
        try:
            if self.com.is_open:
                data = self.getSendData()
                if data == -1:
                    return
                print(self.sendArea.toPlainText())
                print("send:",data)
                self.sendCount += len(data)
                self.com.write(data)
                data = self.sendArea.toPlainText()
                self.sendHistoryFindDelete(data)
                self.sendHistory.insertItem(0,data)
                self.sendHistory.setCurrentIndex(0)
                self.receiveUpdateSignal.emit("")
                # scheduled send
                if self.sendSettingsScheduledCheckBox.isChecked():
                    if not self.isScheduledSending:
                        t = threading.Thread(target=self.scheduledSend)
                        t.setDaemon(True)
                        t.start()
        except Exception as e:
            self.errorSignal.emit(parameters.strWriteError)
            print(e)
        return

    def scheduledSend(self):
        self.isScheduledSending = True
        while self.sendSettingsScheduledCheckBox.isChecked():
            self.sendData()
            try:
                time.sleep(int(self.sendSettingsScheduled.text().strip())/1000)
            except Exception:
                self.errorSignal.emit(parameters.strTimeFormatError)
        self.isScheduledSending = False
        return

    def receiveData(self):
        self.receiveProgressStop = False
        self.timeLastReceive = 0
        while(not self.receiveProgressStop):
            try:
                length = self.com.in_waiting
                if length>0:
                    bytes = self.com.read(length)
                    if self.isWaveOpen:
                        self.wave.displayData(bytes)
                    self.receiveCount += len(bytes)
                    if self.receiveSettingsHex.isChecked():
                        strReceived = self.asciiB2HexString(bytes)
                        self.receiveUpdateSignal.emit(strReceived)
                    else:
                        self.receiveUpdateSignal.emit(bytes.decode(self.encodingCombobox.currentText(),"ignore"))
                    if self.receiveSettingsAutoLinefeed.isChecked():
                        if time.time() - self.timeLastReceive> int(self.receiveSettingsAutoLinefeedTime.text())/1000:
                            if self.sendSettingsCFLF.isChecked():
                                self.receiveUpdateSignal.emit("\r\n")
                            else:
                                self.receiveUpdateSignal.emit("\n")
                            self.timeLastReceive = time.time()
            except Exception as e:
                print("receiveData error")
                if self.com.is_open and not self.serialPortCombobox.isEnabled():
                    self.openCloseSerial()
                    self.serialPortCombobox.clear()
                    self.detectSerialPort()
                print(e)
            time.sleep(0.009)
        return

    def updateReceivedDataDisplay(self,str):
        if str != "":
            curScrollValue = self.receiveArea.verticalScrollBar().value()
            self.receiveArea.moveCursor(QTextCursor.End)
            endScrollValue = self.receiveArea.verticalScrollBar().value()
            self.receiveArea.insertPlainText(str)
            if curScrollValue < endScrollValue:
                self.receiveArea.verticalScrollBar().setValue(curScrollValue)
            else:
                self.receiveArea.moveCursor(QTextCursor.End)
        self.statusBarSendCount.setText("%s(bytes):%d" %(parameters.strSend ,self.sendCount))
        self.statusBarReceiveCount.setText("%s(bytes):%d" %(parameters.strReceive ,self.receiveCount))
        return

    def onSendSettingsHexClicked(self):

        data = self.sendArea.toPlainText().replace("\n","\r\n")
        data = self.asciiB2HexString(data.encode())
        self.sendArea.clear()
        self.sendArea.insertPlainText(data)
        return

    def onSendSettingsAsciiClicked(self):
        try:
            data = self.sendArea.toPlainText().replace("\n"," ").strip()
            self.sendArea.clear()
            if data != "":
                data = self.hexStringB2Hex(data).decode(self.encodingCombobox.currentText(),'ignore')
                self.sendArea.insertPlainText(data)
        except Exception as e:
            # QMessageBox.information(self,parameters.strWriteFormatError,parameters.strWriteFormatError)
            print("format error");
        return

    def sendHistoryIndexChanged(self):
        self.sendArea.clear()
        self.sendArea.insertPlainText(self.sendHistory.currentText())
        return

    def clearReceiveBuffer(self):
        self.receiveArea.clear()
        self.receiveCount = 0;
        self.sendCount = 0;
        self.receiveUpdateSignal.emit(None)
        return

    def MoveToCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        return

    def errorHint(self,str):
        QMessageBox.information(self, str, str)
        return

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Sure To Quit?',
                                     "Are you sure to quit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.com.close()
            self.receiveProgressStop = True
            self.programExitSaveParameters()
            event.accept()
        else:
            event.ignore()

    def findSerialPort(self):
        self.port_list = list(serial.tools.list_ports.comports())
        return self.port_list

    def portChanged(self):
        self.serialPortCombobox.setCurrentIndex(0)
        self.serialPortCombobox.setToolTip(str(self.portList[0]))

    def detectSerialPort(self):
        if not self.isDetectSerialPort:
            self.isDetectSerialPort = True
            t = threading.Thread(target=self.detectSerialPortProcess)
            t.setDaemon(True)
            t.start()

    def detectSerialPortProcess(self):
        self.serialPortCombobox.clear()
        while(1):
            portList = self.findSerialPort();
            for i in portList:
                self.serialPortCombobox.addItem(str(i[0])+" "+str(i[1]))
            if len(portList)>0:
                self.serialPortCombobox.setCurrentIndex(0)
                self.serialPortCombobox.setToolTip(str(portList[0]))
                break
            time.sleep(1)
        self.isDetectSerialPort = False
        return

    def sendHistoryFindDelete(self,str):
        self.sendHistory.removeItem(self.sendHistory.findText(str))
        return

    def test(self):
        print("test")
        return

    def asciiB2HexString(self,strB):
        strHex = binascii.b2a_hex(strB).upper()
        return re.sub(r"(?<=\w)(?=(?:\w\w)+$)", " ", strHex.decode())+" "

    def hexStringB2Hex(self,hexString):
        dataList = hexString.split(" ")
        j = 0
        for i in dataList:
            if len(i) > 2:
                return -1
            elif len(i) == 1:
                dataList[j] = "0" + i
            j += 1
        data = "".join(dataList)
        try:
            data = bytes.fromhex(data)
        except Exception:
            return -1
        print(data)
        return data

    def programExitSaveParameters(self):
        paramObj = parameters.ParametersToSave()
        paramObj.baudRate = self.serailBaudrateCombobox.currentIndex()
        paramObj.dataBytes = self.serailBytesCombobox.currentIndex()
        paramObj.parity = self.serailParityCombobox.currentIndex()
        paramObj.stopBits = self.serailStopbitsCombobox.currentIndex()
        paramObj.skin = self.param.skin
        if self.receiveSettingsHex.isChecked():
            paramObj.receiveAscii = False
        if not self.receiveSettingsAutoLinefeed.isChecked():
            paramObj.receiveAutoLinefeed = False
        else:
            paramObj.receiveAutoLinefeed = True
        paramObj.receiveAutoLindefeedTime = self.receiveSettingsAutoLinefeedTime.text()
        if self.sendSettingsHex.isChecked():
            paramObj.sendAscii = False
        if not self.sendSettingsScheduledCheckBox.isChecked():
            paramObj.sendScheduled = False
        paramObj.sendScheduledTime = self.sendSettingsScheduled.text()
        if not self.sendSettingsCFLF.isChecked():
            paramObj.useCRLF = False
        paramObj.sendHistoryList.clear()
        for i in range(0,self.sendHistory.count()):
            paramObj.sendHistoryList.append(self.sendHistory.itemText(i))
        if self.checkBoxRts.isChecked():
            paramObj.rts = 1
        else:
            paramObj.rts = 0
        if self.checkBoxDtr.isChecked():
            paramObj.dtr = 1
        else:
            paramObj.dtr = 0
        paramObj.encodingIndex = self.encodingCombobox.currentIndex()
        f = open("settings.config","wb")
        f.truncate()
        pickle.dump(paramObj, f)
        pickle.dump(paramObj.sendHistoryList,f)
        f.close()
        return

    def programStartGetSavedParameters(self):
        paramObj = parameters.ParametersToSave()
        try:
            f = open("settings.config", "rb")
            paramObj = pickle.load( f)
            paramObj.sendHistoryList = pickle.load(f)
            f.close()
        except Exception as e:
            f = open("settings.config", "wb")
            f.close()
        self.serailBaudrateCombobox.setCurrentIndex(paramObj.baudRate)
        self.serailBytesCombobox.setCurrentIndex(paramObj.dataBytes)
        self.serailParityCombobox.setCurrentIndex(paramObj.parity)
        self.serailStopbitsCombobox.setCurrentIndex(paramObj.stopBits)
        if paramObj.receiveAscii == False:
            self.receiveSettingsHex.setChecked(True)
        if paramObj.receiveAutoLinefeed == False:
            self.receiveSettingsAutoLinefeed.setChecked(False)
        else:
            self.receiveSettingsAutoLinefeed.setChecked(True)
        self.receiveSettingsAutoLinefeedTime.setText(paramObj.receiveAutoLindefeedTime)
        if paramObj.sendAscii == False:
            self.sendSettingsHex.setChecked(True)
        if paramObj.sendScheduled == False:
            self.sendSettingsScheduledCheckBox.setChecked(False)
        else:
            self.sendSettingsScheduledCheckBox.setChecked(True)
        self.sendSettingsScheduled.setText(paramObj.sendScheduledTime)
        if paramObj.useCRLF == False:
            self.sendSettingsCFLF.setChecked(False)
        else:
            self.sendSettingsCFLF.setChecked(True)
        for i in range(0, len(paramObj.sendHistoryList)):
            str = paramObj.sendHistoryList[i]
            self.sendHistory.addItem(str)
        if paramObj.rts == 0:
            self.checkBoxRts.setChecked(False)
        else:
            self.checkBoxRts.setChecked(True)
        if paramObj.dtr == 0:
            self.checkBoxDtr.setChecked(False)
        else:
            self.checkBoxDtr.setChecked(True)
        self.encodingCombobox.setCurrentIndex(paramObj.encodingIndex)
        self.param = paramObj
        return

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Control:
            self.keyControlPressed = True
        elif event.key() == Qt.Key_Return or event.key()==Qt.Key_Enter:
            if self.keyControlPressed:
                self.sendData()
        elif event.key() == Qt.Key_L:
            if self.keyControlPressed:
                self.sendArea.clear()
        elif event.key() == Qt.Key_K:
            if self.keyControlPressed:
                self.receiveArea.clear()
        return

    def keyReleaseEvent(self,event):
        if event.key() == Qt.Key_Control:
            self.keyControlPressed = False
        return

    def sendAreaFontChanged(self,font):
        print("font changed")

        return

    def functionAdd(self):
        QMessageBox.information(self, "On the way", "On the way")
        return

    def showHideSettings(self):
        if self.isHideSettings:
            self.showSettings()
            self.isHideSettings = False
        else:
            self.hideSettings()
            self.isHideSettings = True
        return

    def showSettings(self):
        self.settingWidget.show()
        self.settingsButton.setStyleSheet(
            parameters.strStyleShowHideButtonLeft.replace("$DataPath",self.DataPath))
        return;

    def hideSettings(self):
        self.settingWidget.hide()
        self.settingsButton.setStyleSheet(
            parameters.strStyleShowHideButtonRight.replace("$DataPath", self.DataPath))
        return;

    def showHideFunctional(self):
        if self.isHideFunctinal:
            self.showFunctional()
            self.isHideFunctinal = False
        else:
            self.hideFunctional()
            self.isHideFunctinal = True
        return

    def showFunctional(self):
        self.functionalWiget.show()
        self.functionalButton.setStyleSheet(
            parameters.strStyleShowHideButtonRight.replace("$DataPath",self.DataPath))
        return;

    def hideFunctional(self):
        self.functionalWiget.hide()
        self.functionalButton.setStyleSheet(
            parameters.strStyleShowHideButtonLeft.replace("$DataPath", self.DataPath))
        return;

    def skinChange(self):
        if self.param.skin == 1: # light
            file = open(self.DataPath + '/assets/qss/style-dark.qss', "r")
            self.param.skin = 2
        else: # elif self.param.skin == 2: # dark
            file = open(self.DataPath + '/assets/qss/style.qss', "r")
            self.param.skin = 1
        self.app.setStyleSheet(file.read().replace("$DataPath", self.DataPath))
        return

    def showAbout(self):
        QMessageBox.information(self, "About","<h1 style='color:#f75a5a';margin=10px;>"+parameters.appName+
                                '</h1><br><b style="color:#08c7a1;margin = 5px;">V'+str(helpAbout.versionMajor)+"."+
                                str(helpAbout.versionMinor)+"."+str(helpAbout.versionDev)+
                                "</b><br><br>"+helpAbout.date+"<br><br>"+helpAbout.strAbout())
        return

    def action1(self):
        print("action1")
        return

    def autoUpdateDetect(self):
        auto = autoUpdate.AutoUpdate()
        if auto.detectNewVersion():
            auto.OpenBrowser()

    def openDevManagement(self):
        os.system('start devmgmt.msc')

    def openWaveDisplay(self):
        self.wave = Wave()
        self.isWaveOpen = True
        self.wave.closed.connect(self.OnWaveClosed)

    def OnWaveClosed(self):
        print("wave window closed")
        self.isWaveOpen = False