def add_radiobuttons(self, tab=False):
     from PyQt5.QtWidgets import QRadioButton, QButtonGroup, QVBoxLayout
     scrollLayout = QVBoxLayout()
     buttonGroup = QButtonGroup()
     buttongroup_results = {}
     i = 1
     if tab:
         name = "tab"
         i = 2
     elif arguments.radiolist:
         name = "radiolist"
     elif arguments.menu:
         name = "menu"
     arglen = len(arguments.__dict__[name])
     while i < arglen:
         if arguments.radiolist:
             radiobutton = QRadioButton(arguments.__dict__[name][i+1])
             buttongroup_results[radiobutton] = arguments.__dict__[name][i]
             if arguments.__dict__[name][i+2].lower() in ["true", "on"]:
                 radiobutton.setChecked(True)
             i += 3
         else:
             radiobutton = QRadioButton(arguments.__dict__[name][i+1])
             buttongroup_results[radiobutton] = arguments.__dict__[name][i]
             if i == 1:
                 radiobutton.setChecked(True)
             i += 2
         scrollLayout.addWidget(radiobutton)
         buttonGroup.addButton(radiobutton)
     return scrollLayout, buttonGroup, buttongroup_results
Example #2
0
class NewValuesWidget(QGroupBox):
    def __init__(self, parent):
        super(NewValuesWidget, self).__init__(parent)

        self.new_rd = QRadioButton(self)
        self.new_sb = QSpinBox(self)
        self.system_missing = QRadioButton(self)
        self.copy_old_values = QRadioButton(self)
        self.grid = QGridLayout(self)

        self.ui()
        self.properties()

        self.new_rd.toggled.connect(self.new_rd_toggled)

    def new_rd_toggled(self, event):
        self.new_sb.setEnabled(event)

    def properties(self):
        self.setTitle("New Values")
        self.new_rd.setText("Value")
        self.system_missing.setText("System missing")
        self.copy_old_values.setText("Copy old values")

        self.new_rd.setChecked(True)

    def ui(self):
        self.grid.addWidget(self.new_rd, 0, 0, 1, 1, Qt.AlignTop)
        self.grid.addWidget(self.new_sb, 0, 1, 1, 9, Qt.AlignTop)
        self.grid.addWidget(self.system_missing, 1, 0, 1, 10, Qt.AlignTop)
        self.grid.addWidget(self.copy_old_values, 2, 0, 1, 10)
        self.grid.setSpacing(1)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
Example #3
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 #4
0
    def __init__(self, msg, choices, on_clicked=None, checked_index=0):
        vbox = QVBoxLayout()
        if len(msg) > 50:
            vbox.addWidget(WWLabel(msg))
            msg = ""
        gb2 = QGroupBox(msg)
        vbox.addWidget(gb2)

        vbox2 = QVBoxLayout()
        gb2.setLayout(vbox2)

        self.group = group = QButtonGroup()
        for i,c in enumerate(choices):
            button = QRadioButton(gb2)
            button.setText(c)
            vbox2.addWidget(button)
            group.addButton(button)
            group.setId(button, i)
            if i==checked_index:
                button.setChecked(True)

        if on_clicked:
            group.buttonClicked.connect(partial(on_clicked, self))

        self.vbox = vbox
Example #5
0
    def __init__(self, currentGlyph, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Layer actions…"))
        self._workableLayers = []
        for layer in currentGlyph.layerSet:
            if layer != currentGlyph.layer:
                self._workableLayers.append(layer)

        copyBox = QRadioButton(self.tr("Copy"), self)
        moveBox = QRadioButton(self.tr("Move"), self)
        swapBox = QRadioButton(self.tr("Swap"), self)
        self.otherCheckBoxes = (moveBox, swapBox)
        copyBox.setChecked(True)

        self.layersList = QListWidget(self)
        self.layersList.addItems(layer.name for layer in self._workableLayers)
        if self.layersList.count():
            self.layersList.setCurrentRow(0)
        self.layersList.itemDoubleClicked.connect(self.accept)

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

        layout = QGridLayout(self)
        l = 0
        layout.addWidget(copyBox, l, 0, 1, 2)
        layout.addWidget(moveBox, l, 2, 1, 2)
        layout.addWidget(swapBox, l, 4, 1, 2)
        l += 1
        layout.addWidget(self.layersList, l, 0, 1, 6)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 6)
        self.setLayout(layout)
    def _initUi(self, dlgName):
        self.setWindowTitle(dlgName)
 
        allRadioButton = QRadioButton('所有'); allRadioButton.setChecked(True)
        highlightRadioButton = QRadioButton('高亮')

        # 添加到QButtonGroup
        self._buttonGroup = QButtonGroup()
        self._buttonGroup.addButton(allRadioButton, 1); 
        self._buttonGroup.addButton(highlightRadioButton, 2)

        cancelPushButton = QPushButton('Cancel')
        okPushButton = QPushButton('OK')
        cancelPushButton.clicked.connect(self._cancel)
        okPushButton.clicked.connect(self._ok)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(allRadioButton, 1, 0)
        grid.addWidget(highlightRadioButton, 1, 1)

        grid.addWidget(okPushButton, 2, 1)
        grid.addWidget(cancelPushButton, 2, 0)
 
        self.setLayout(grid)
        self.setMinimumWidth(QApplication.desktop().size().width()//5)
Example #7
0
    def _show_templates(self):
        """
        Update templates on shoeEvent.
        """

        cols = 3
        templates = template_module.Template.get_all()

        for j, item in enumerate(self.visible_items):
            if not templates[item.id]:
                l = QLabel("Нет шаблонов для данного объекта\nУправлять шаблонами можно на вкладке настроек")
                l.setAlignment(Qt.AlignCenter)
                self.templates_layout.addWidget(l)
                continue
            layouts = [QVBoxLayout() for _ in range(cols)]
            for i, each in enumerate(templates[item.id]):
                b = QRadioButton(each.name)
                b.setChecked(item.template == each)
                b.clicked.connect(functools.partial(self._template_clicked, j, each))
                b.mouseDoubleClickEvent = functools.partial(self.open_template_edit_widget, j, each)
                layouts[i % cols].addWidget(b)

            wrapper = QHBoxLayout()
            for each in layouts:
                each.addStretch()
                wrapper.addLayout(each, stretch=int(100 / cols))
            self.templates_layout.addWidget(utils.get_scrollable(wrapper))
        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 #9
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()
    def _initUi(self):
        self.setWindowTitle('指数均线K线图统计')
 
        # 控件
        startDateLable = QLabel('开始日期')
        self._startDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

        endDateLable = QLabel('结束日期')
        self._endDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

        # 指数和股票代码
        shIndexRadioButton = QRadioButton('上证指数'); shIndexRadioButton.setChecked(True)
        szIndexRadioButton = QRadioButton('深证成指')
        cybIndexRadioButton = QRadioButton('创业板指')
        zxbIndexRadioButton = QRadioButton('中小板指')

        hs300IndexRadioButton = QRadioButton('沪深300')
        zz500IndexRadioButton = QRadioButton('中证500')

        # 添加到QButtonGroup
        self._stocksButtonGroup = QButtonGroup()
        self._stocksButtonGroup.addButton(shIndexRadioButton, 1); 
        self._stocksButtonGroup.addButton(szIndexRadioButton, 2)
        self._stocksButtonGroup.addButton(cybIndexRadioButton, 3)
        self._stocksButtonGroup.addButton(zxbIndexRadioButton, 4)

        self._stocksButtonGroup.addButton(hs300IndexRadioButton, 4)
        self._stocksButtonGroup.addButton(zz500IndexRadioButton, 4)

        cancelPushButton = QPushButton('Cancel')
        okPushButton = QPushButton('OK')
        cancelPushButton.clicked.connect(self._cancel)
        okPushButton.clicked.connect(self._ok)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(startDateLable, 0, 0)
        grid.addWidget(self._startDateLineEdit, 1, 0)

        grid.addWidget(endDateLable, 0, 1)
        grid.addWidget(self._endDateLineEdit, 1, 1)

        grid.addWidget(shIndexRadioButton, 2, 0)
        grid.addWidget(szIndexRadioButton, 2, 1)
        grid.addWidget(cybIndexRadioButton, 3, 0)
        grid.addWidget(zxbIndexRadioButton, 3, 1)

        grid.addWidget(hs300IndexRadioButton, 4, 0)
        grid.addWidget(zz500IndexRadioButton, 4, 1)

        grid.addWidget(okPushButton, 5, 1)
        grid.addWidget(cancelPushButton, 5, 0)
 
        self.setLayout(grid)
Example #11
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 #12
0
    def createGroupBox(self):
        self.groupBox = QGroupBox(self.tr("View"))
        perspectiveRadioButton = QRadioButton(self.tr("Perspective"))
        isometricRadioButton = QRadioButton(self.tr("Isometric"))
        obliqueRadioButton = QRadioButton(self.tr("Oblique"))
        perspectiveRadioButton.setChecked(True)

        self.groupBoxLayout = QVBoxLayout()
        self.groupBoxLayout.addWidget(perspectiveRadioButton)
        self.groupBoxLayout.addWidget(isometricRadioButton)
        self.groupBoxLayout.addWidget(obliqueRadioButton)
        self.groupBox.setLayout(self.groupBoxLayout)
Example #13
0
    def show_available_colormaps(self):
        height = 50

        selected = colormaps.read_selected_colormap_name_from_settings()
        for colormap_name in sorted(colormaps.maps.keys()):
            image = Spectrogram.create_colormap_image(colormap_name, height=height)
            rb = QRadioButton(colormap_name)
            rb.setObjectName(colormap_name)
            rb.setChecked(colormap_name == selected)
            rb.setIcon(QIcon(QPixmap.fromImage(image)))
            rb.setIconSize(QSize(256, height))
            self.ui.scrollAreaWidgetSpectrogramColormapContents.layout().addWidget(rb)
Example #14
0
    def __init__(self, parent=None):
        super(ClassInfoPage, self).__init__(parent)

        self.setTitle("Class Information")
        self.setSubTitle("Specify basic information about the class for "
                "which you want to generate skeleton source code files.")
        self.setPixmap(QWizard.LogoPixmap, QPixmap(':/images/logo1.png'))

        classNameLabel = QLabel("&Class name:")
        classNameLineEdit = QLineEdit()
        classNameLabel.setBuddy(classNameLineEdit)

        baseClassLabel = QLabel("B&ase class:")
        baseClassLineEdit = QLineEdit()
        baseClassLabel.setBuddy(baseClassLineEdit)

        qobjectMacroCheckBox = QCheckBox("Generate Q_OBJECT &macro")

        groupBox = QGroupBox("C&onstructor")

        qobjectCtorRadioButton = QRadioButton("&QObject-style constructor")
        qwidgetCtorRadioButton = QRadioButton("Q&Widget-style constructor")
        defaultCtorRadioButton = QRadioButton("&Default constructor")
        copyCtorCheckBox = QCheckBox("&Generate copy constructor and operator=")

        defaultCtorRadioButton.setChecked(True)

        defaultCtorRadioButton.toggled.connect(copyCtorCheckBox.setEnabled)

        self.registerField('className*', classNameLineEdit)
        self.registerField('baseClass', baseClassLineEdit)
        self.registerField('qobjectMacro', qobjectMacroCheckBox)
        self.registerField('qobjectCtor', qobjectCtorRadioButton)
        self.registerField('qwidgetCtor', qwidgetCtorRadioButton)
        self.registerField('defaultCtor', defaultCtorRadioButton)
        self.registerField('copyCtor', copyCtorCheckBox)

        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.addWidget(qobjectCtorRadioButton)
        groupBoxLayout.addWidget(qwidgetCtorRadioButton)
        groupBoxLayout.addWidget(defaultCtorRadioButton)
        groupBoxLayout.addWidget(copyCtorCheckBox)
        groupBox.setLayout(groupBoxLayout)

        layout = QGridLayout()
        layout.addWidget(classNameLabel, 0, 0)
        layout.addWidget(classNameLineEdit, 0, 1)
        layout.addWidget(baseClassLabel, 1, 0)
        layout.addWidget(baseClassLineEdit, 1, 1)
        layout.addWidget(qobjectMacroCheckBox, 2, 0, 1, 2)
        layout.addWidget(groupBox, 3, 0, 1, 2)
        self.setLayout(layout)
Example #15
0
 def add_radiobuttons(self):
     from PyQt5.QtWidgets import QRadioButton, QButtonGroup
     self.buttonGroup = QButtonGroup()
     self.buttongroup_results = {}
     i = 1
     while i < len(arguments.radiolist):
         radiobutton = QRadioButton(arguments.radiolist[i+1])
         self.buttongroup_results[radiobutton] = arguments.radiolist[i]
         if arguments.radiolist[i+2].lower() == "true":
             radiobutton.setChecked(True)
         self.scrollLayout.addWidget(radiobutton)
         self.buttonGroup.addButton(radiobutton)
         i += 3
    def _create_libdmtx(self, settings):
        radio = QRadioButton('My objects are labelled with Data Matrix barcodes')
        radio.setChecked('libdmtx' == settings['engine'])
        radio.setEnabled(libdmtx_available())
        self._layout.addWidget(radio)

        prompt = QLabel(HTML_LINK_TEMPLATE.format(
            'Barcodes will be decoded using the open-source '
            '<a href="http://libdmtx.sourceforge.net/">libdmtx</a> library'
        ))
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        self._layout.addWidget(HorizontalLine())
        return radio
    def _create_inlite(self, settings):
        radio = QRadioButton(
            'Either my objects are labelled with a barcode not listed above '
            'or I would like the performance and reliability of a commercial '
            'library')
        radio.setChecked('inlite' == settings['engine'])
        radio.setEnabled(inlite_available())
        self._layout.addWidget(radio)

        prompt = QLabel(HTML_LINK_TEMPLATE.format(
            'Only available on Windows. '
            'Visit <a href="http://www.inliteresearch.com/">Inlite Research</a> '
            'to download and install Inlite Research\'s ClearImage library.'
        ))
        prompt.setWordWrap(True)
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        prompt = QLabel('My objects are labelled with:')
        format = settings['inlite-format']
        radio_1d = QRadioButton('1D barcodes')
        radio_1d.setChecked('1d' == format)
        radio_datamatrix = QRadioButton('Data Matrix barcodes')
        radio_datamatrix.setChecked('datamatrix' == format)
        radio_pdf417 = QRadioButton('PDF 417 barcodes')
        radio_pdf417.setChecked('pdf417' == format)
        radio_qr = QRadioButton('QR codes')
        radio_qr.setChecked('qrcode' == format)

        layout = QVBoxLayout()
        layout.addWidget(prompt)
        layout.addWidget(radio_1d)
        layout.addWidget(radio_datamatrix)
        layout.addWidget(radio_pdf417)
        layout.addWidget(radio_qr)

        group = QWidget()
        group.setLayout(layout)
        group.setStyleSheet(self.STYLESHEET)
        radio.toggled.connect(group.setEnabled)
        group.setEnabled(inlite_available() and 'inlite' == settings['engine'])

        self._layout.addWidget(group)

        return radio, radio_1d, radio_datamatrix, radio_pdf417, radio_qr
Example #18
0
    def create_example_group():
        group_box = QGroupBox("Best Food")

        radio1 = QRadioButton("&Radio pizza")
        radio2 = QRadioButton("R&adio taco")
        radio3 = QRadioButton("Ra&dio burrito")

        radio1.setChecked(True)

        vbox = QVBoxLayout()
        vbox.addWidget(radio1)
        vbox.addWidget(radio2)
        vbox.addWidget(radio3)
        vbox.addStretch(1)
        group_box.setLayout(vbox)

        return group_box
Example #19
0
    def createFirstExclusiveGroup(self):
        groupBox = QGroupBox("Exclusive Radio Buttons")

        radio1 = QRadioButton("&Radio button 1")
        radio2 = QRadioButton("R&adio button 2")
        radio3 = QRadioButton("Ra&dio button 3")

        radio1.setChecked(True)

        vbox = QVBoxLayout()
        vbox.addWidget(radio1)
        vbox.addWidget(radio2)
        vbox.addWidget(radio3)
        vbox.addStretch(1)
        groupBox.setLayout(vbox)

        return groupBox
Example #20
0
class InputRadioGroup(QWidget):
    """Create an horizontal radio group"""
    def __init__(self, parent=None, option_list=None, default_select=0):
        super().__init__(parent=parent)
        layout = QHBoxLayout(self)
        self.group = QButtonGroup()
        for idx, op in enumerate(option_list):
            self.op = QRadioButton(_(op))
            if idx == default_select:
                self.op.setChecked(True)
            layout.addWidget(self.op)
            self.group.addButton(self.op)
        self.setLayout(layout)

    @pyqtProperty(str)
    def currentItemData(self):
        return str(abs(int(self.group.checkedId())) - 1)
Example #21
0
def _make_widget( item ) :

    if item.kind == 'checkbox' :
        # Checkbox is just that
        widget = QCheckBox( item.label )
        if item.result is not None :
            widget.setChecked( bool( item.result ) )

    elif item.kind == 'string' :
        # String is a Line-Edit
        widget = QLineEdit()
        if item.result is not None :
            widget.setText( item.result )

    elif item.kind == 'number' :
        # Number is a SpinBox with optional min/max
        widget = QSpinBox()
        if item.minimum is not None :
            widget.setMinimum( item.minimum )
        if item.maximum is not None :
            widget.setMaximum( item.maximum )
        if item.result is not None :
            widget.setValue( item.result )

    elif item.kind == 'choice' :
        # Choice is a QGroupBox with some number of radio buttons in a stack
        widget = QGroupBox()
        widget.setFlat( True )
        widget.setTitle( item.label )
        vbl = QVBoxLayout()
        for id, (lbl, tip) in enumerate( item.choices ) :
            button = QRadioButton( lbl )
            button.setToolTip( tip )
            button.setChecked( id == item.result )
            vbl.addWidget( button )
        widget.setLayout( vbl )

    else : # item.kind == 'error'
        # Put in a label "Error in definition"
        widget = QLabel( 'Error in definition' )

    widget.setToolTip( item.tooltip )

    return widget
Example #22
0
    def createTopLeftGroupBox(self):
        self.topLeftGroupBox = QGroupBox("Group 1")

        radioButton1 = QRadioButton("Radio button 1")
        radioButton2 = QRadioButton("Radio button 2")
        radioButton3 = QRadioButton("Radio button 3")
        radioButton1.setChecked(True)

        checkBox = QCheckBox("Tri-state check box")
        checkBox.setTristate(True)
        checkBox.setCheckState(Qt.PartiallyChecked)

        layout = QVBoxLayout()
        layout.addWidget(radioButton1)
        layout.addWidget(radioButton2)
        layout.addWidget(radioButton3)
        layout.addWidget(checkBox)
        layout.addStretch(1)
        self.topLeftGroupBox.setLayout(layout)    
Example #23
0
    def _show_menu(self):
        """
        Update menu on showEvent.
        """

        for i, item in enumerate(self.visible_items):
            b = QRadioButton(self._get_button_name(item))
            b.setChecked(i == 0)
            b.clicked.connect(functools.partial(self.templates_layout.setCurrentIndex, i))
            b.setObjectName("menu_button")
            self.menu_layout.addWidget(b)

        if not self.visible_items:
            self.menu_layout.addStretch()
            l = QLabel("Чтобы создать отчет\nначните заполнять данные")
            l.setAlignment(Qt.AlignCenter)
            self.menu_layout.addWidget(l)

        self.menu_layout.addStretch()
Example #24
0
def filename_field(parent, config, defaultname, select_msg):

    vbox = QVBoxLayout()
    vbox.addWidget(QLabel(_("Format")))
    gb = QGroupBox("format", parent)
    b1 = QRadioButton(gb)
    b1.setText(_("CSV"))
    b1.setChecked(True)
    b2 = QRadioButton(gb)
    b2.setText(_("json"))
    vbox.addWidget(b1)
    vbox.addWidget(b2)

    hbox = QHBoxLayout()

    directory = config.get('io_dir', os.path.expanduser('~'))
    path = os.path.join( directory, defaultname )
    filename_e = QLineEdit()
    filename_e.setText(path)

    def func():
        text = filename_e.text()
        _filter = "*.csv" if text.endswith(".csv") else "*.json" if text.endswith(".json") else None
        p, __ = QFileDialog.getSaveFileName(None, select_msg, text, _filter)
        if p:
            filename_e.setText(p)

    button = QPushButton(_('File'))
    button.clicked.connect(func)
    hbox.addWidget(button)
    hbox.addWidget(filename_e)
    vbox.addLayout(hbox)

    def set_csv(v):
        text = filename_e.text()
        text = text.replace(".json",".csv") if v else text.replace(".csv",".json")
        filename_e.setText(text)

    b1.clicked.connect(lambda: set_csv(True))
    b2.clicked.connect(lambda: set_csv(False))

    return vbox, filename_e, b1
Example #25
0
    def create_example_group():
        group_box = QGroupBox("Slider Example")

        radio1 = QRadioButton("&Radio horizontal slider")

        slider = QSlider(Qt.Horizontal)
        slider.setFocusPolicy(Qt.StrongFocus)
        slider.setTickPosition(QSlider.TicksBothSides)
        slider.setTickInterval(10)
        slider.setSingleStep(1)

        radio1.setChecked(True)

        vbox = QVBoxLayout()
        vbox.addWidget(radio1)
        vbox.addWidget(slider)
        vbox.addStretch(1)
        group_box.setLayout(vbox)

        return group_box
    def _initUi(self, title, backward):
        self.setWindowTitle('添加{0}列'.format(title))
 
        # 控件
        increaseColumnsLable = QLabel('基准日期几日{0}'.format(title))
        self._increaseColumnsLineEdit = QLineEdit(','.join([str(x) for x in self._data['days']]) if self._data else '2,3,4,5,10' )

        # 前 & 后
        forwardRadioButton = QRadioButton('向前')
        backwardRadioButton = QRadioButton('向后');
        if backward:
            backwardRadioButton.setChecked(True)
        else:
            forwardRadioButton.setChecked(True)

        # 添加到QButtonGroup
        self._wardButtonGroup = QButtonGroup()
        self._wardButtonGroup.addButton(forwardRadioButton, 1); 
        self._wardButtonGroup.addButton(backwardRadioButton, 2)

        cancelPushButton = QPushButton('Cancel')
        okPushButton = QPushButton('OK')
        cancelPushButton.clicked.connect(self._cancel)
        okPushButton.clicked.connect(self._ok)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(increaseColumnsLable, 0, 0, 1, 2)
        grid.addWidget(self._increaseColumnsLineEdit, 1, 0, 1, 2)

        grid.addWidget(forwardRadioButton, 2, 0)
        grid.addWidget(backwardRadioButton, 2, 1)

        grid.addWidget(okPushButton, 3, 1)
        grid.addWidget(cancelPushButton, 3, 0)
 
 
        self.setLayout(grid)
        self.setMinimumWidth(QApplication.desktop().size().width()//5)
Example #27
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 #28
0
    def createSecondExclusiveGroup(self):
        groupBox = QGroupBox("E&xclusive Radio Buttons")
        groupBox.setCheckable(True)
        groupBox.setChecked(False)

        radio1 = QRadioButton("Rad&io button 1")
        radio2 = QRadioButton("Radi&o button 2")
        radio3 = QRadioButton("Radio &button 3")
        radio1.setChecked(True)
        checkBox = QCheckBox("Ind&ependent checkbox")
        checkBox.setChecked(True)

        vbox = QVBoxLayout()
        vbox.addWidget(radio1)
        vbox.addWidget(radio2)
        vbox.addWidget(radio3)
        vbox.addWidget(checkBox)
        vbox.addStretch(1)
        groupBox.setLayout(vbox)

        return groupBox
Example #29
0
    def __make_cell(self, c, name, col_type, col_type_def):
        cell = QWidget(self.inner)
        rbtn = QRadioButton('', cell)
        rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c)))
        hbl = QHBoxLayout(cell)
        hbl.addWidget(rbtn)
        hbl.setContentsMargins(0, 0, 0, 0)
        hbl.setAlignment(Qt.AlignCenter)
        cell.setLayout(hbl)
        if name == 'cat':
            if col_type == 'object':
                rbtn.setChecked(True)
            self.lst_cat.append(rbtn)
        elif name == 'num':
            if col_type != 'object':
                rbtn.setChecked(True)
            if col_type_def == 'object':
                rbtn.setEnabled(False)
            self.lst_num.append(rbtn)
        elif name == 'obj':
            if col_type == 'object' and self.params.task == 'Regression':
                rbtn.setEnabled(False)
            elif col_type != 'object' and self.params.task == 'Classification':
                rbtn.setEnabled(False)
            if self.params.columns[c] == self.params.objective:
                rbtn.setChecked(True)
            self.lst_obj.append(rbtn)

        return cell
Example #30
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 #31
0
    def __init__(self, elder):
        super().__init__()
        self.elder = elder
        self.layout = QGridLayout(self)
        self.settings = elder.settings
        self.listener = elder.listener

        paths = QGroupBox(self)
        paths.setTitle('Paths')
        paths_layout = QGridLayout(paths)
        self.layout.addWidget(paths)

        label = QLabel(paths)
        label.setText('Fiddler')
        paths_layout.addWidget(label, 0, 0, 1, 1)

        self.fiddler_path = QLineEdit(paths)
        self.fiddler_path.setText(self.settings.paths['Fiddler'])
        self.fiddler_path.setDisabled(True)
        paths_layout.addWidget(self.fiddler_path, 0, 1, 1, 1)

        button = QPushButton(paths)
        button.setText('...')
        button.clicked.connect(lambda: self.set_path('fiddler'))
        paths_layout.addWidget(button, 0, 2, 1, 1)

        label = QLabel(paths)
        label.setText('TurboHUD')
        paths_layout.addWidget(label, 1, 0, 1, 1)

        self.turbohud_path = QLineEdit(paths)
        self.turbohud_path.setText(self.settings.paths['TurboHUD'])
        self.turbohud_path.setDisabled(True)
        paths_layout.addWidget(self.turbohud_path, 1, 1, 1, 1)

        button = QPushButton(paths)
        button.setText('...')
        button.clicked.connect(lambda: self.set_path('turbohud'))
        paths_layout.addWidget(button, 1, 2, 1, 1)

        label = QLabel(paths)
        label.setText('pHelper')
        paths_layout.addWidget(label, 2, 0, 1, 1)

        self.phelper_path = QLineEdit(paths)
        self.phelper_path.setText(self.settings.paths['pHelper'])
        self.phelper_path.setDisabled(True)
        paths_layout.addWidget(self.phelper_path, 2, 1, 1, 1)

        button = QPushButton(paths)
        button.setText('...')
        button.clicked.connect(lambda: self.set_path('phelper'))
        paths_layout.addWidget(button, 2, 2, 1, 1)

        image_recognition = QGroupBox(self)
        image_recognition.setTitle('Auto Stuff (Image Recognition)')
        image_recognition_layout = QGridLayout(image_recognition)
        self.layout.addWidget(image_recognition, 0, 1)

        checkbox = QCheckBox(image_recognition)
        checkbox.setText('Auto start Game')
        checkbox.setChecked(self.settings.special['auto_start'])
        checkbox.clicked.connect(lambda: self.checkbox_clicked('auto_start'))
        image_recognition_layout.addWidget(checkbox, 0, 0)

        checkbox = QCheckBox(image_recognition)
        checkbox.setText('Auto open Rift / Grift')
        checkbox.setChecked(self.settings.special['auto_open'])
        checkbox.clicked.connect(lambda: self.checkbox_clicked('auto_open'))
        image_recognition_layout.addWidget(checkbox, 1, 0)

        radio = QRadioButton(image_recognition)
        radio.setText('Rift')
        radio.setChecked(self.settings.special['auto_open_option'] == 'rift')
        radio.clicked.connect(lambda: self.radio_clicked('rift'))
        image_recognition_layout.addWidget(radio, 2, 0)

        radio = QRadioButton(image_recognition)
        radio.setText('Grift')
        radio.setChecked(self.settings.special['auto_open_option'] == 'grift')
        radio.clicked.connect(lambda: self.radio_clicked('grift'))
        image_recognition_layout.addWidget(radio, 2, 1)

        checkbox = QCheckBox(image_recognition)
        checkbox.setText('Auto accept Grift')
        checkbox.setChecked(self.settings.special['auto_accept_gr'])
        checkbox.clicked.connect(
            lambda: self.checkbox_clicked('auto_accept_gr'))
        image_recognition_layout.addWidget(checkbox, 3, 0)

        checkbox = QCheckBox(image_recognition)
        checkbox.setText('Auto upgrade Gem')
        checkbox.setChecked(self.settings.special['auto_upgrade_gem'])
        checkbox.clicked.connect(
            lambda: self.checkbox_clicked('auto_upgrade_gem'))
        image_recognition_layout.addWidget(checkbox, 4, 0)

        checkbox = QCheckBox(image_recognition)
        checkbox.setText('Auto gamble')
        checkbox.setChecked(self.settings.special['auto_gamble'])
        checkbox.clicked.connect(lambda: self.checkbox_clicked('auto_gamble'))
        image_recognition_layout.addWidget(checkbox, 5, 0)

        poolspots = QGroupBox(self)
        poolspots.setTitle('Poolspots')
        poolspots_layout = QGridLayout(poolspots)
        self.layout.addWidget(poolspots, 1, 0)

        self.poolspot_list = QListWidget(poolspots)
        self.poolspot_list.setSelectionMode(QListWidget.MultiSelection)
        for act, ps in ressources.poolspots().items():
            for poolspot in ps:
                item = QListWidgetItem(self.poolspot_list)
                item.setText(
                    f'Act {act}: {string.capwords(poolspot.replace("_", " "))}'
                )
                item.poolspot = poolspot
                if poolspot in self.settings.poolspots:
                    item.setSelected(True)
        self.poolspot_list.itemSelectionChanged.connect(self.update_poolspots)
        poolspots_layout.addWidget(self.poolspot_list)

        # button = QPushButton(poolspots)
        # button.setText('Save')
        # button.clicked.connect(self.update_poolspots)
        # poolspots_layout.addWidget(button)

        gamble_item = QGroupBox(self)
        gamble_item.setTitle('Gamble Item')
        gamble_item_layout = QGridLayout(gamble_item)
        self.layout.addWidget(gamble_item, 1, 1)

        self.gamble_item_list = QListWidget(gamble_item)
        self.gamble_item_list.setSelectionMode(QListWidget.SingleSelection)
        for _item in ressources.items():
            item = QListWidgetItem(self.gamble_item_list)
            item.setText(string.capwords(_item.replace('_', ' ')))
            item.item = _item
            if _item == self.settings.special['gamble_item']:
                item.setSelected(True)
        self.gamble_item_list.itemSelectionChanged.connect(
            self.update_gamble_item)
        gamble_item_layout.addWidget(self.gamble_item_list)

        self.setLayout(self.layout)
    widget.show()

    modifier = SurfaceGraph(graph)

    heightMapModelRB.toggled.connect(modifier.enableHeightMapModel)
    sqrtSinModelRB.toggled.connect(modifier.enableSqrtSinModel)
    modeNoneRB.toggled.connect(modifier.toggleModeNone)
    modeItemRB.toggled.connect(modifier.toggleModeItem)
    modeSliceRowRB.toggled.connect(modifier.toggleModeSliceRow)
    modeSliceColumnRB.toggled.connect(modifier.toggleModeSliceColumn)
    axisMinSliderX.valueChanged.connect(modifier.adjustXMin)
    axisMaxSliderX.valueChanged.connect(modifier.adjustXMax)
    axisMinSliderZ.valueChanged.connect(modifier.adjustZMin)
    axisMaxSliderZ.valueChanged.connect(modifier.adjustZMax)
    rhoSlider.valueChanged.connect(modifier.setRhoSlider)
    themeList.currentIndexChanged.connect(modifier.changeTheme)
    gradientBtoYPB.pressed.connect(modifier.setBlackToYellowGradient)
    gradientGtoRPB.pressed.connect(modifier.setGreenToRedGradient)

    modifier.setAxisMinSliderX(axisMinSliderX)
    modifier.setAxisMaxSliderX(axisMaxSliderX)
    modifier.setAxisMinSliderZ(axisMinSliderZ)
    modifier.setAxisMaxSliderZ(axisMaxSliderZ)

    sqrtSinModelRB.setChecked(True)
    modeItemRB.setChecked(True)
    themeList.setCurrentIndex(2)

    sys.exit(app.exec_())
Example #33
0
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.train_path = "D:/test/train"
        self.val_path = "D:/test/val"
        self.test_path = ""
        self.new_path_model = "Model_1_85aug.h5"
        self.list_ale, self.list_epi, self.list_tot = [], [], []
        self.epoch = 100
        self.model = 'drop'
        self.batch_dim = 100
        self.monte = 5
        self.train_js, self.val_js, self.test_js = "new_train_js.txt", "new_val_js.txt", ""
        self.path_work = "D:/test"
        self.path_tiles_train, self.path_tiles_val, self.path_tiles_test = '', '', ''
        self.selected_th, self.path_save_clean = '', ''
        self.flag, self.aug = 0, 0
        self.layout = QVBoxLayout(self)

        self.threadPool = QThreadPool()

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tab5 = QWidget()

        # Add tabs
        self.tabs.addTab(self.tab1, "Get Tiles")
        self.tabs.addTab(self.tab2, "Training")
        self.tabs.addTab(self.tab3, "Uncertainty analysis")
        self.tabs.addTab(self.tab4, "Data cleaning")
        self.t5 = TestTab(parent=self)
        self.tabs.addTab(self.t5, "Testing")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.tab2.layout = QVBoxLayout(self)
        self.tab3.layout = QVBoxLayout(self)
        self.tab4.layout = QVBoxLayout(self)

        # Elements section 1
        self.first = QLabel(
            "First things first, select a place where put all data sets:")
        self.first_button = QPushButton("Select folder")
        self.first_button.clicked.connect(self.first_selection)

        newfont = QFont("Helvetica", 15, QFont.Bold)
        self.title_train = QLabel('TRAINING SET')
        self.title_train.setFont(newfont)
        self.title_val = QLabel('VALIDATION SET')
        self.title_val.setFont(newfont)
        self.title_test = QLabel('TEST SET')
        self.title_test.setFont(newfont)

        self.start = QPushButton("Start")
        self.start.clicked.connect(self.start_tiles)
        self.description_t = QLabel("Press here to select the train folder: ")
        self.description_v = QLabel(
            "Press here to select the validation folder: ")
        self.description_test = QLabel(
            "Press here to select the test folder: ")
        self.folder_train = QPushButton("Select folder")
        self.folder_train.clicked.connect(self.select_folder_train)
        self.folder_val = QPushButton("Select folder")
        self.folder_val.clicked.connect(self.select_folder_val)
        self.folder_test = QPushButton("Select folder")
        self.folder_test.clicked.connect(self.select_folder_test)
        self.prog1 = QProgressBar(self)
        self.prog2 = QProgressBar(self)
        self.prog3 = QProgressBar(self)
        self.prog1_v = QProgressBar(self)
        self.prog2_v = QProgressBar(self)
        self.prog3_v = QProgressBar(self)
        self.prog1_test = QProgressBar(self)
        self.prog2_test = QProgressBar(self)
        self.prog3_test = QProgressBar(self)
        # train
        self.list_ac = QListWidget(self)
        self.list_ad = QListWidget(self)
        self.list_h = QListWidget(self)
        # validation
        self.list_ac_v = QListWidget(self)
        self.list_ad_v = QListWidget(self)
        self.list_h_v = QListWidget(self)
        # test
        # validation
        self.list_ac_test = QListWidget(self)
        self.list_ad_test = QListWidget(self)
        self.list_h_test = QListWidget(self)

        self.first_layout = QHBoxLayout(self)
        self.first_layout.addWidget(self.first)
        self.first_layout.addWidget(self.first_button)

        self.h_train = QHBoxLayout(self)
        self.h_train.addWidget(self.description_t)
        self.h_train.addWidget(self.folder_train)

        self.h_val = QHBoxLayout(self)
        self.h_val.addWidget(self.description_v)
        self.h_val.addWidget(self.folder_val)

        self.h_test = QHBoxLayout(self)
        self.h_test.addWidget(self.description_test)
        self.h_test.addWidget(self.folder_test)

        self.list_t = QHBoxLayout(self)
        self.list_t.addWidget(self.list_ac)
        self.list_t.addWidget(self.list_ad)
        self.list_t.addWidget(self.list_h)

        self.list_v = QHBoxLayout(self)
        self.list_v.addWidget(self.list_ac_v)
        self.list_v.addWidget(self.list_ad_v)
        self.list_v.addWidget(self.list_h_v)

        self.list_test = QHBoxLayout(self)
        self.list_test.addWidget(self.list_ac_test)
        self.list_test.addWidget(self.list_ad_test)
        self.list_test.addWidget(self.list_h_test)

        self.pr = QHBoxLayout(self)
        self.pr.addWidget(self.prog1)
        self.pr.addWidget(self.prog2)
        self.pr.addWidget(self.prog3)

        self.pr_v = QHBoxLayout(self)
        self.pr_v.addWidget(self.prog1_v)
        self.pr_v.addWidget(self.prog2_v)
        self.pr_v.addWidget(self.prog3_v)

        self.pr_test = QHBoxLayout(self)
        self.pr_test.addWidget(self.prog1_test)
        self.pr_test.addWidget(self.prog2_test)
        self.pr_test.addWidget(self.prog3_test)

        # tab1
        self.tab1.layout.addLayout(self.first_layout)
        self.tab1.layout.addWidget(QHLine())
        self.tab1.layout.addWidget(self.title_train)
        self.tab1.layout.addLayout(self.h_train)
        self.tab1.layout.addLayout(self.list_t)
        self.tab1.layout.addLayout(self.pr)
        self.tab1.layout.addWidget(QHLine())
        self.tab1.layout.addWidget(self.title_val)
        self.tab1.layout.addLayout(self.h_val)
        self.tab1.layout.addLayout(self.list_v)
        self.tab1.layout.addLayout(self.pr_v)
        self.tab1.layout.addWidget(QHLine())
        self.tab1.layout.addWidget(self.title_test)
        self.tab1.layout.addLayout(self.h_test)
        self.tab1.layout.addLayout(self.list_test)
        self.tab1.layout.addLayout(self.pr_test)
        self.tab1.layout.addWidget(QHLine())
        self.tab1.layout.addWidget(self.start)

        self.tab1.setLayout(self.tab1.layout)

        # Elements section 2
        self.progrestrain = QProgressBar(self)
        self.text = QLineEdit(self)
        self.text_batch = QLineEdit(self)
        self.start_train = QPushButton("Start")
        self.start_train.clicked.connect(self.train)
        self.state_train = QLabel("Press start to train the model.")
        self.state_train.setMargin(10)
        self.state_train.setFixedWidth(900)
        self.state_train.setFixedHeight(1500)
        self.state_train.setAlignment(Qt.AlignTop)

        self.scrolltr = QScrollArea()
        self.scrolltr.setAlignment(Qt.AlignTop)
        self.scrolltr.setWidget(self.state_train)

        self.description_tr = QLabel('Insert numer of epochs:  ')
        self.description_batch = QLabel('Insert dimension of batch:  ')
        self.description_batch2 = QLabel('Default value: 100')

        self.description_model = QLabel(
            'Select one of the 2 available models:')
        self.description_tr2 = QLabel('Default epochs: 100')
        self.kl = QRadioButton('Kl divergence')
        self.kl.toggled.connect(self.load_kl)
        self.drop = QRadioButton('Drop-Out')
        self.drop.setChecked(True)
        self.drop.toggled.connect(self.load_drop)

        self.ok_text = QPushButton('Ok')
        self.ok_text.clicked.connect(self.ok_epochs)

        self.ok_batc = QPushButton('Ok')
        self.ok_batc.clicked.connect(self.ok_batch)

        self.set_epochs = QHBoxLayout(self)
        self.set_epochs.addWidget(self.description_tr)
        self.set_epochs.addWidget(self.text)
        self.set_epochs.addWidget(self.ok_text)
        self.set_epochs.addWidget(self.description_tr2)

        self.set_batch_size = QHBoxLayout(self)
        self.set_batch_size.addWidget(self.description_batch)
        self.set_batch_size.addWidget(self.text_batch)
        self.set_batch_size.addWidget(self.ok_batc)
        self.set_batch_size.addWidget(self.description_batch2)

        self.set_model = QHBoxLayout(self)
        self.set_model.addWidget(self.description_model)
        self.set_model.addWidget(self.kl)
        self.set_model.addWidget(self.drop)

        self.description_optional = QLabel(
            'Optional, select two folder where can retrive '
            'the training end validation tiles:')
        self.retrive_train = QPushButton('Train')
        self.retrive_train.clicked.connect(self.ret_train)
        self.retrive_test = QPushButton('Val')
        self.retrive_test.clicked.connect(self.ret_test)
        self.new_folder = QHBoxLayout(self)
        self.new_folder.addWidget(self.retrive_train)
        self.new_folder.addWidget(self.retrive_test)
        self.new_folder.addStretch(1)

        self.data_aug = QCheckBox('Data Agumentation')
        self.data_aug.stateChanged.connect(self.agumentation)
        # tab2
        self.tab2.layout.addLayout(self.set_model)
        self.tab2.layout.addLayout(self.set_epochs)
        self.tab2.layout.addLayout(self.set_batch_size)
        self.tab2.layout.addWidget(self.data_aug)
        self.tab2.layout.addWidget(QHLine())
        self.tab2.layout.addWidget(self.description_optional)
        self.tab2.layout.addLayout(self.new_folder)
        self.tab2.layout.addWidget(QHLine())
        self.tab2.layout.addWidget(self.start_train)

        self.tab2.layout.addWidget(self.scrolltr)
        self.tab2.layout.addWidget(self.progrestrain)

        self.tab2.setLayout(self.tab2.layout)

        # Elements section 3
        self.description_clas = QLabel(
            'The purpose of this step is to obtain the values of uncertainty values'
        )
        self.description_monte = QLabel('Write here Monte Carlo samples:')
        self.title_train_cl = QLabel('TRAINING SET')
        self.title_val_cl = QLabel('VALIDATION SET')
        self.title_test_cl = QLabel('TEST SET')
        self.title_train_cl.setFont(newfont)
        self.title_val_cl.setFont(newfont)
        self.title_test_cl.setFont(newfont)

        self.description_monte2 = QLabel('Default value: {}'.format(
            self.monte))
        self.text_monte = QLineEdit()
        self.prog_monte = QProgressBar()
        self.ok_monte = QPushButton('Ok')
        self.ok_monte.clicked.connect(self.ok_m)
        self.start_classify_train = QPushButton('Start')
        self.start_classify_train.clicked.connect(self.cl_train)

        self.start_classify_val = QPushButton('Start')
        self.start_classify_val.clicked.connect(self.cl_val)

        self.start_classify_test = QPushButton('Start')
        self.start_classify_test.clicked.connect(self.cl_test)

        self.HMonte = QHBoxLayout(self)
        self.HMonte.addWidget(self.description_monte)
        self.HMonte.addWidget(self.text_monte)
        self.HMonte.addWidget(self.ok_monte)
        self.HMonte.addWidget(self.description_monte2)

        # tab 3
        self.tab3.layout.addWidget(self.description_clas,
                                   alignment=Qt.AlignTop)
        self.tab3.layout.addWidget(QHLine())
        self.tab3.layout.addLayout(self.HMonte)
        self.tab3.layout.addWidget(self.title_train_cl)
        self.tab3.layout.addWidget(self.start_classify_train)
        self.tab3.layout.addWidget(QHLine())
        self.tab3.layout.addWidget(self.title_val_cl)
        self.tab3.layout.addWidget(self.start_classify_val)
        self.tab3.layout.addWidget(QHLine())
        self.tab3.layout.addWidget(self.title_test_cl)
        self.tab3.layout.addWidget(self.start_classify_test)
        self.tab3.layout.addStretch(1)
        self.tab3.layout.addWidget(self.prog_monte)

        self.tab3.setLayout(self.tab3.layout)

        # Elements 4
        self.hist_ale = MplCanvas('Aleatoric uncertainty',
                                  self,
                                  width=5,
                                  height=4,
                                  dpi=100)
        self.hist_epi = MplCanvas('Epistemic uncertainty',
                                  self,
                                  width=5,
                                  height=4,
                                  dpi=100)
        self.hist_tot = MplCanvas('Total uncertainty',
                                  self,
                                  width=5,
                                  height=4,
                                  dpi=100)
        self.hist_removed = QPushButton(
            'Show number of tiles that i will remove for class')
        self.hist_removed.hide()
        self.hist_removed.clicked.connect(self.show_class_removed)

        self.description_total_before = QLabel()
        self.description_total_before.hide()
        self.description_total_after = QLabel()
        self.description_total_after.hide()
        self.description_select_data = QLabel('Select which dataset analyze:')
        self.description_types = QLabel(
            'Select one of the two modes, Auto the software will find the correct '
            'threshold to divide the images between certain and uncertain; in Manual '
            'you have to write the desired value in the text box.')
        self.description_folder = QLabel(
            'Folder where the dataset cleaned will be created:')
        self.folder_cl_data = QPushButton('Select a emplty folder')
        self.folder_cl_data.clicked.connect(self.conclusion_folder)
        self.auto = QRadioButton('Auto')
        self.auto.setEnabled(False)
        self.control = QRadioButton('Control')
        self.control.hide()
        self.auto.toggled.connect(self.update_auto)
        self.manual = QRadioButton('Manual')
        self.manual.setEnabled(False)
        self.manual.toggled.connect(self.update_man)
        self.mode_group = QButtonGroup()
        self.mode_group.addButton(self.auto)
        self.mode_group.addButton(self.manual)
        self.mode_group.addButton(self.control)
        self.prog_copy = QProgressBar()

        self.dataset_train = QRadioButton('Training set')
        self.dataset_train.toggled.connect(self.clean_train)
        self.dataset_val = QRadioButton('Validation set')
        self.dataset_val.toggled.connect(self.clean_val)
        self.dataset_group = QButtonGroup()
        self.dataset_group.addButton(self.dataset_train)
        self.dataset_group.addButton(self.dataset_val)

        self.manual_value = QLineEdit()
        self.manual_value.hide()
        self.start_clean = QPushButton('Start analysis with manual threshold')
        self.start_clean.clicked.connect(self.push_manual)
        self.start_clean.hide()
        self.create_new_dataset = QPushButton('Create new data set')
        self.create_new_dataset.clicked.connect(self.conclusion_cleaning)
        self.create_new_dataset.setEnabled(False)

        self.mode = QHBoxLayout()
        self.mode.addWidget(self.auto, alignment=Qt.AlignCenter)
        self.mode.addWidget(self.manual, alignment=Qt.AlignCenter)
        self.mode.addWidget(self.manual_value)
        self.mode.addWidget(self.start_clean)
        self.mode.addStretch(1)

        self.hist_v = QVBoxLayout()
        self.hist_v.addWidget(self.hist_ale)
        self.hist_v.addWidget(self.hist_epi)

        self.hist_o = QHBoxLayout()
        self.hist_o.addWidget(self.hist_tot)
        self.hist_o.addLayout(self.hist_v)

        self.folder_cl = QHBoxLayout()
        self.folder_cl.addWidget(self.description_folder)
        self.folder_cl.addWidget(self.folder_cl_data)

        self.number = QVBoxLayout()
        self.number.addWidget(self.description_total_before)
        self.number.addWidget(self.description_total_after)

        self.h_number = QHBoxLayout()
        self.h_number.addLayout(self.number)
        self.h_number.addWidget(self.hist_removed)

        self.h_select_dataset = QHBoxLayout()
        self.h_select_dataset.addWidget(self.description_select_data)
        self.h_select_dataset.addWidget(self.dataset_train)
        self.h_select_dataset.addWidget(self.dataset_val)

        self.otsu_th = QRadioButton('Otsu threshold')
        self.otsu_th.setEnabled(False)
        self.otsu_th.toggled.connect(self.sel_otsu)
        self.new_th = QRadioButton('New threshold')
        self.new_th.setEnabled(False)
        self.new_th.toggled.connect(self.sel_new)
        self.manul_th = QRadioButton('Manual threshold')
        self.manul_th.setEnabled(False)
        self.manul_th.toggled.connect(self.sel_manual)
        self.group_th = QButtonGroup()
        self.group_th.addButton(self.otsu_th)
        self.group_th.addButton(self.new_th)
        self.group_th.addButton(self.manul_th)

        self.h_selection_th = QHBoxLayout()
        self.h_selection_th.addWidget(self.otsu_th)
        self.h_selection_th.addWidget(self.new_th)
        self.h_selection_th.addWidget(self.manul_th)
        self.h_selection_th.addStretch(1)
        # tab 4
        self.tab4.layout.addLayout(self.h_select_dataset)
        self.tab4.layout.addWidget(QHLine())
        self.tab4.layout.addLayout(self.hist_o)
        self.tab4.layout.addLayout(self.h_number)
        self.tab4.layout.addWidget(QHLine())
        self.tab4.layout.addWidget(self.description_types)
        self.tab4.layout.addLayout(self.mode)
        self.tab4.layout.addWidget(QHLine())
        self.tab4.layout.addLayout(self.folder_cl)
        self.tab4.layout.addLayout(self.h_selection_th)
        self.tab4.layout.addWidget(self.create_new_dataset)
        self.tab4.layout.addStretch(1)
        self.tab4.layout.addWidget(self.prog_copy)

        self.tab4.setLayout(self.tab4.layout)

        # Add tabs to widget

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        start_time = time.asctime(time.localtime(time.time()))
        self.log_epoch = "Start  {}".format(start_time)

    def sel_otsu(self):
        self.selected_th = 'otsu'

    def sel_new(self):
        self.selected_th = 'new'

    def sel_manual(self):
        self.selected_th = 'manual'

    def agumentation(self, state):
        if Qt.Checked == state:
            self.aug = 1
        else:
            self.aug = 0

    def show_class_removed(self):
        self.obj_clean.removed_class()

    def ret_test(self):
        fl = QFileDialog.getExistingDirectory(self, "Select Directory")
        if fl != '':
            self.path_tiles_val = fl
        else:
            pass

    def ret_train(self):
        fl = QFileDialog.getExistingDirectory(self, "Select Directory")
        if fl != '':
            self.path_tiles_train = fl
        else:
            pass

    def conclusion_cleaning(self):
        if not os.path.exists(os.path.join(self.path_save_clean, 'AC')):
            os.mkdir(os.path.join(self.path_save_clean, 'AC'))
            os.mkdir(os.path.join(self.path_save_clean, 'H'))
            os.mkdir(os.path.join(self.path_save_clean, 'AD'))

        work_copy = WorkerLong(self.obj_clean.clean_js, self.selected_th,
                               self.path_save_clean)

        work_copy.signals.result.connect(self.print_output)
        work_copy.signals.progress.connect(self.progress_fn)
        work_copy.signals.progress.connect(self.prog_copy.setValue)
        work_copy.signals.finished.connect(self.thread_complete)
        self.threadPool.start(work_copy)

    def conclusion_folder(self):
        save_fl = QFileDialog.getExistingDirectory(self, "Select Directory")
        if save_fl != '':
            self.path_save_clean = save_fl
            self.create_new_dataset.setEnabled(True)
        else:
            pass

    def first_selection(self):
        fl = QFileDialog.getExistingDirectory(self, "Select Directory")
        if fl != '':
            self.path_work = fl
            self.path_tiles_train = os.path.join(fl, 'train')
            self.path_tiles_val = os.path.join(fl, 'val')
            self.path_tiles_test = os.path.join(fl, 'test')
        else:
            pass

    def ok_m(self):
        tex = self.text_monte.text()
        if tex.isdecimal() and int(tex) > 0:
            self.description_monte2.setText(
                'Monte Carlo samples:  {}'.format(tex))
            self.monte = tex
        else:
            pass

    def ok_batch(self):
        tex = self.text_batch.text()
        if tex.isdecimal() and int(tex) > 0:
            self.description_batch2.setText('Batch dimension:  {}'.format(tex))
            self.batch_dim = tex
        else:
            pass

    def draw_hist(self, path_js, name):
        self.obj_clean = Th(path_js, name)
        self.list_ale, self.list_epi, self.list_tot = self.obj_clean.create_list(
        )
        lim = max(self.list_tot)
        n_bin = round((len(self.list_tot)) / 100)
        self.hist_tot.axes.clear()
        self.hist_tot.axes.set_xlim(0, lim)
        self.hist_tot.axes.set_title('Total uncertainty')
        self.hist_tot.axes.hist(self.list_tot, bins=n_bin, color='#FFA420')
        self.hist_tot.draw()
        self.hist_ale.axes.clear()
        self.hist_ale.axes.set_xlim(0, lim)
        self.hist_ale.axes.set_title('Aleatoric uncertainty')
        self.hist_ale.axes.hist(self.list_ale, bins=n_bin, color='#FFA420')
        self.hist_ale.draw()
        self.hist_epi.axes.clear()
        self.hist_epi.axes.set_xlim(0, lim)
        self.hist_epi.axes.set_title('Epistemic uncertainty')
        self.hist_epi.axes.hist(self.list_epi, bins=n_bin, color='#FFA420')
        self.hist_epi.draw()

    def unlock_an(self):
        self.auto.setEnabled(True)
        self.manual.setEnabled(True)

        self.auto.setChecked(False)
        self.manual.setChecked(False)
        self.control.setChecked(True)
        self.control.setChecked(True)

    def clean_train(self):
        self.unlock_an()
        self.draw_hist(self.train_js, 'train')
        self.description_total_before.setText(
            'Total number of tiles before cleaning: {}'.format(
                len(self.list_tot)))
        self.description_total_before.show()
        self.description_total_after.hide()
        self.hist_removed.hide()

    def clean_val(self):
        self.unlock_an()
        self.draw_hist(self.val_js, 'val')
        self.description_total_before.setText(
            'Total number of tiles before cleaning: {}'.format(
                len(self.list_tot)))
        self.description_total_before.show()
        self.description_total_after.hide()
        self.hist_removed.hide()

    def load_kl(self):
        self.model = 'kl'

    def load_drop(self):
        self.model = 'drop'

    def update_auto(self):
        self.obj_clean.otsu()
        self.newth, self.thfin, number_new_dataset1, number_new_dataset = self.obj_clean.th_managment(
        )
        self.description_total_after.setText(
            'Total number of tiles after cleaning: \n'
            'Otsu Threshold:   {:10}\n'
            'New Threshold:    {:10}'.format(number_new_dataset,
                                             number_new_dataset1))
        self.description_total_after.show()
        self.hist_removed.show()
        self.hist_tot.axes.axvline(x=self.newth,
                                   ls='--',
                                   color='k',
                                   label='New Threshold')
        self.hist_tot.axes.axvline(x=self.thfin,
                                   color='red',
                                   label='Otsu Threshold')
        self.hist_tot.axes.axvline(x=-3,
                                   ls='--',
                                   color='y',
                                   label='Manual Threshold')
        if self.flag == 0:
            self.hist_tot.axes.legend(prop={'size': 10})
            self.flag = 1
        else:
            pass
        self.hist_tot.draw()

        if self.auto.isChecked():
            self.manual_value.hide()
            self.start_clean.hide()
            self.th_update()

    def th_update(self):
        self.otsu_th.setEnabled(True)
        self.new_th.setEnabled(True)
        self.manul_th.setEnabled(True)

    def update_man(self):
        if self.manual.isChecked():
            self.manual_value.show()
            self.start_clean.show()

    def select_folder_train(self):
        self.train_path = QFileDialog.getExistingDirectory(
            self, "Select Directory")
        if self.train_path != '':
            cl = os.listdir(self.train_path)
            try:
                for i in cl:
                    nfiles = os.listdir(os.path.join(self.train_path, i))
                    if i == 'AC' or i == 'ac':
                        self.list_ac.addItems(nfiles)
                    elif i == 'AD' or i == 'ad':
                        self.list_ad.addItems(nfiles)
                    elif i == 'H' or i == 'h':
                        self.list_h.addItems(nfiles)
                    else:
                        pass
                    print(self.train_path)
            except:
                pass
        else:
            pass

    def select_folder_test(self):
        self.test_path = QFileDialog.getExistingDirectory(
            self, "Select Directory")
        if self.test_path != '':
            cl = os.listdir(self.test_path)
            try:
                for i in cl:
                    nfiles = os.listdir(os.path.join(self.test_path, i))
                    if i == 'AC' or i == 'ac':
                        self.list_ac_test.addItems(nfiles)
                    elif i == 'AD' or i == 'ad':
                        self.list_ad_test.addItems(nfiles)
                    elif i == 'H' or i == 'h':
                        self.list_h_test.addItems(nfiles)
                    else:
                        pass
                    print(self.test_path)
            except:
                pass
        else:
            pass

    def select_folder_val(self):
        self.val_path = QFileDialog.getExistingDirectory(
            self, "Select Directory")
        if self.val_path != '':
            cl = os.listdir(self.val_path)
            try:
                for i in cl:
                    nfiles = os.listdir(os.path.join(self.val_path, i))
                    if i == 'AC' or i == 'ac':
                        self.list_ac_v.addItems(nfiles)
                    elif i == 'AD' or i == 'ad':
                        self.list_ad_v.addItems(nfiles)
                    elif i == 'H' or i == 'h':
                        self.list_h_v.addItems(nfiles)
                    else:
                        pass
                    print(self.val_path)
            except:
                pass
        else:
            pass

    def push_manual(self):
        tex = float(self.manual_value.text())
        self.th_update()
        if 1 > tex > 0.1:
            print('dentro id')
            self.selected_th = tex
            self.obj_clean.otsu()
            print('TEXT--------', tex)

            self.man, self.thfin, number_new_dataset1, number_new_dataset = self.obj_clean.th_managment(
                self.selected_th)
            self.description_total_after.setText(
                'Total number of tiles after cleaning: \n'
                'Otsu Threshold:        {:10}\n'
                'Manual Threshold:      {:10}'.format(number_new_dataset,
                                                      number_new_dataset1))
            self.description_total_after.show()
            self.hist_removed.show()
            self.hist_tot.axes.axvline(x=self.man,
                                       ls='--',
                                       color='y',
                                       label='Manual Threshold')
            self.hist_tot.draw()

    def progress_fn(self, n):
        print("%d%% done" % n)

    def print_output(self, s):
        self.state_train.setText(str(s))
        print(s)

    def thread_complete(self):
        print("THREAD COMPLETE!")

    def thread_train_complete(self):
        self.state_train.setText(
            'Training completed! The history is saved in the work folder.')
        print("THREAD COMPLETE!")

    def th_tiles(self, pr, path, name):
        cl = os.listdir(self.path)
        for y, k in enumerate(cl, 0):
            save_folder = os.path.join(self.path_work, name, k)
            f_p = os.path.join(path, k)
            print(save_folder)
            if os.path.exists(save_folder):
                pass
            else:
                os.makedirs(save_folder)

            st_tile = StartAnalysis(tile_size=256, lev_sec=0)
            print('inizio il threading \n', f_p, save_folder)
            name_th = str(k) + name
            name_th = WorkerLong(st_tile.list_files, f_p, save_folder)

            name_th.signals.result.connect(self.print_output)
            name_th.signals.progress.connect(self.progress_fn)
            name_th.signals.progress.connect(pr[y].setValue)
            name_th.signals.finished.connect(self.thread_complete)
            self.threadPool.start(name_th)

    def start_tiles(self):
        pr = [[self.prog1, self.prog2, self.prog3],
              [self.prog1_v, self.prog2_v, self.prog3_v],
              [self.prog1_test, self.prog2_test, self.prog3_test]]
        ph = [self.train_path, self.val_path, self.test_path]
        dataset = ['train', 'val', 'test']

        for t, i in enumerate(dataset):
            print(pr[t], ph[t], i)
            self.th_tiles(pr[t], ph[t], name=i)

    def ok_epochs(self):
        text_value = self.text.text()
        if text_value.isdecimal() and int(text_value) > 0:
            self.description_tr2.setText(
                'Limit epochs:  {}'.format(text_value))
            self.epoch = text_value
        else:
            pass

    def train(self):
        self.state_train.setText(
            'The training is starting, in few second other information will be showed...'
        )
        t_stamp = time.strftime("%Y_%m%d_%H%M%S")
        if self.model == 'drop':
            self.new_path_model = os.path.join(self.path_work,
                                               'ModelDrop-' + t_stamp + '.h5')
            print(self.train_path)
            obj_model = ModelDropOut(n_model=self.new_path_model,
                                     epochs=self.epoch,
                                     path_train=self.path_tiles_train,
                                     path_val=self.path_tiles_val,
                                     b_dim=int(self.batch_dim),
                                     aug=self.aug)
        else:
            self.new_path_model = os.path.join(self.path_work,
                                               'ModelKl-' + t_stamp + '.h5')
            obj_model = ModelKl(n_model=self.new_path_model,
                                epochs=self.epoch,
                                path_train=self.path_tiles_train,
                                path_val=self.path_tiles_val,
                                b_dim=int(self.batch_dim),
                                aug=self.aug)

        k = WorkerLong(obj_model.start_train)
        k.signals.result.connect(self.print_output)
        k.signals.progress.connect(self.progrestrain.setValue)
        k.signals.result1.connect(self.tr_view)
        k.signals.finished.connect(self.thread_train_complete)
        self.threadPool.start(k)

    def cl_train(self):
        self.start_an(self.path_tiles_train)
        self.train_js = os.path.join(
            self.path_tiles_train,
            'dictionary_monte_' + str(self.monte) + '_js.txt')
        self.t5.traincm.setEnabled(True)
        self.t5.get_paths(train=self.train_js)

    def cl_test(self):
        self.start_an(self.path_tiles_test)
        self.test_js = os.path.join(
            self.path_tiles_test,
            'dictionary_monte_' + str(self.monte) + '_js.txt')
        self.t5.testcm.setEnabled(True)
        self.t5.get_paths(test=self.test_js)

    def cl_val(self):
        self.start_an(self.path_tiles_val)
        self.val_js = os.path.join(
            self.path_tiles_val,
            'dictionary_monte_' + str(self.monte) + '_js.txt')
        self.t5.valcm.setEnabled(True)
        self.t5.get_paths(val=self.val_js)

    def start_an(self, data):
        cls = Classification(data, ty='datacleaning')
        worker_cl = WorkerLong(cls.classify, 'datacleaning', int(self.monte),
                               self.new_path_model)
        worker_cl.signals.result.connect(self.print_output)
        worker_cl.signals.progress.connect(self.progress_fn)
        worker_cl.signals.progress.connect(self.prog_monte.setValue)
        worker_cl.signals.finished.connect(self.thread_complete)
        self.threadPool.start(worker_cl)

    def tr_view(self, val):
        if 'Epoch' in str(val):
            self.log_epoch = self.log_epoch + '\n' + str(val)
            self.state_train.setText(str(self.log_epoch))
            print('trova la parola epoca EMETTE:', self.log_epoch)
        else:
            show_b = self.log_epoch + '\n' + str(val)
            self.state_train.setText(str(show_b))
Example #34
0
class userLoginForm(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.setWindowTitle("Kullanıcı Girişi")
        self.dir_path = get_dir_path()
        self.userDatabaseControl()
        self.userDB = sql_functions("{}Databases/users.db".format(
            self.dir_path))  #Kullanıcı veritabanı ile bağlantının kurulması
        self.setMaximumSize(356, 206)  #Ekran boyutları
        self.initUI()  #Arayüz tasarım kodlarının çalıştırılması

    def initUI(self):

        #Layout'ların tanımlanması
        self.mainVerticalLayout = QVBoxLayout()
        self.headerLayout = QHBoxLayout()
        self.upLayout = QHBoxLayout()
        self.middleLayout = QHBoxLayout()
        self.downLayout = QHBoxLayout()
        self.notificationLayout = QHBoxLayout()

        # Widgetlerin tanımlanması,tasarımının yapılması ve Layout'lara yüklenmesi.

        self.header = QLabel()
        self.header.setText("Kullanıcı Girişi")
        self.header.setStyleSheet("""
        font-family:Courier;
        font-size:32px;
        color:#003366;
        border-left: 4px solid #221354;

        padding:3px;
        background-color: lightgrey;
        """)
        self.headerLayout.addStretch()
        self.headerLayout.addWidget(self.header)
        self.headerLayout.addStretch()

        self.userNameLabel = QLabel()
        self.userNameLabel.setText("Kullanıcı Adı : ")
        self.userNameLabel.setStyleSheet("""
        border-right:4px solid #221354;          
        font-family:Verdana;
        font-size:14px;
        color:#201A1E;
        """)
        self.userNameLineEdit = QLineEdit()
        self.userNameLineEdit.setMaximumWidth(150)

        self.upLayout.addStretch()
        self.upLayout.addWidget(self.userNameLabel)
        self.upLayout.addWidget(self.userNameLineEdit)
        self.upLayout.addStretch()

        self.passwordLabel = QLabel()
        self.passwordLabel.setText("                 Şifre : ")
        self.passwordLabel.setStyleSheet("""
        font-family:Verdana;
        font-size:14px;
        color:#201A1E;
        """)
        self.passwordLineEdit = QLineEdit()
        self.passwordLineEdit.setMaximumWidth(150)
        self.readablePassword = QRadioButton()

        self.timer = QTimer()
        self.timer.timeout.connect(self._update)
        self.timer.start(1000)

        self.middleLayout.addStretch()
        self.middleLayout.addWidget(self.passwordLabel)
        self.middleLayout.addWidget(self.passwordLineEdit)
        self.middleLayout.addWidget(self.readablePassword)
        self.middleLayout.addStretch()

        self.registerbutton = QPushButton("Kayıt")
        self.registerbutton.setStyleSheet("""
        color:  #80004d;
        background-color:#aaaaaa;
        font-weight: 650 ;
        font-style:Verdana;       
        """)
        shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3)
        self.registerbutton.setGraphicsEffect(shadow)
        self.registerbutton.clicked.connect(
            self.register
        )  #Kayıt sayfasına yönlendirecek fonksiyonun çağrılması

        self.loginbutton = QPushButton("Giriş")
        self.loginbutton.setStyleSheet("""
        color: #008080;
        background-color:#aaaaaa;
        font-weight: 650 ;
        font-style:Verdana;       
        """)
        shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3)
        self.loginbutton.setGraphicsEffect(shadow)
        self.loginbutton.clicked.connect(
            self.login
        )  #Veritabanında bilgi kontrolünü yapacak fonksiyonun çağrılması

        self.downLayout.addStretch()
        self.downLayout.addWidget(self.loginbutton)
        self.downLayout.addWidget(self.registerbutton)

        self.registeredNotificationLabel = QLabel()
        self.registeredNotificationImage = QLabel()

        self.notificationLayout.addStretch()
        self.notificationLayout.addWidget(self.registeredNotificationImage)
        self.notificationLayout.addWidget(self.registeredNotificationLabel)
        self.notificationLayout.addStretch()

        #İşlenen Layout'ların ana Layout'a eklenmesi
        self.mainVerticalLayout.addStretch()
        self.mainVerticalLayout.addLayout(self.headerLayout)
        self.mainVerticalLayout.addLayout(self.upLayout)
        self.mainVerticalLayout.addLayout(self.middleLayout)
        self.mainVerticalLayout.addLayout(self.downLayout)
        self.mainVerticalLayout.addLayout(self.notificationLayout)
        self.mainVerticalLayout.addStretch()

        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(240, 250, 253))
        self.setPalette(p)

        self.setLayout(self.mainVerticalLayout)

    def userDatabaseControl(self):
        condition1 = os.path.isdir("{}Databases/".format(
            self.dir_path))  #Dizinin kontrolü
        condition2 = os.path.exists("{}Databases/users.db".format(
            self.dir_path))  #Veritabanının kontrolü
        condition3 = tableCheck("{}Databases/users.db".format(self.dir_path),
                                "Users")  #Tablonun varlığının kontrolü

        if not condition1:
            #Dizin kontrol ==> yanlış
            os.mkdir("{}Databases/".format(self.dir_path))

        elif condition2:
            usersConf()

        elif condition3:
            os.remove("{}Databases/users.db".format(self.dir_path))
            usersConf()

    def _update(
        self
    ):  #Şifrenenin görünürlüğünü anlık olarak radiobutton'a bakarak kontrol eder ve değiştiririr.
        if self.readablePassword.isChecked():
            self.passwordLineEdit.setEchoMode(False)
        else:
            self.passwordLineEdit.setEchoMode(QLineEdit.Password)

        self.setLayout(self.mainVerticalLayout)

    def register(self):  #Kayıt sayfasına yönlendirir.
        from registrationPage import registrationForm  #Eğer en başta belirtilir ise import hatası verecektir

        self.close()
        self.openWindow = registrationForm()
        self.openWindow.show()

    def login(self):  #Giriş yapar
        nickname = self.userNameLineEdit.text()
        password = self.passwordLineEdit.text()

        nicknameExistance = nickname in [
            tup[0]
            for tup in self.userDB.get_column_by_name("users", "Username")
        ]  #kullanıcı isminin veri tabanında varlığını boolean veri tipinde değişkene atar
        userData = self.userDB.get_row("users", "Username", nickname)

        if nicknameExistance:  #Kullanıcı imi olursa bu bölge çalışır
            hashedPassword = userData[5]  #SHA256 ile şifrelenmiş şifre bilgisi

            if sha256_crypt.verify(
                    password, hashedPassword
            ):  #Eğer şifre bilgisi ile girilen şifre doğrulanırsa bu bölge çalışır.
                self.registeredNotificationLabel.setText(
                    "Hoşgeldin {} ".format(userData[3]))

                self.registeredNotificationImage.setPixmap(
                    QPixmap("{}Images/tickIconAdjusted.png".format(
                        self.dir_path)))
                QTimer.singleShot(
                    1800, lambda: self.registeredNotificationLabel.setText(""))
                QTimer.singleShot(
                    1800,
                    lambda: self.registeredNotificationImage.setPixmap(QPixmap(
                    )))

                userIndex = [
                    tup[0] for tup in self.userDB.get_column_by_name(
                        "users", "Username")
                ].index(nickname)
                from interface import mainScreen
                self.openWindow = mainScreen(
                    userIndex)  #Ana ekrana giriş yapılır
                self.openWindow.show()
                self.close()

            else:  #Hatalı şifre durumunda çalışır
                self.readablePassword.setChecked(True)
                self.passwordLineEdit.setText(
                    "Şifre yanlış girildi.Tekrar deneyiniz.")
        else:  #Kullanıcı adı geçersiz ise çalışır
            self.userNameLineEdit.setText("Geçersiz kullanıcı adı.")
Example #35
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.new_img = "temp/new.jpg"
        self.initUI()

    def initUI(self):
        self.screen = QDesktopWidget().screenGeometry()
        # Первоначальные настройки
        self.setGeometry(0, 0, self.screen.width(), self.screen.height())
        self.showMaximized()
        self.setWindowTitle('Certificate')

        # создаем рабочую область
        grid = QGridLayout()
        grid.setSpacing(10)

        self.imgWidth = int(self.screen.width() - self.screen.width() / 4)
        self.imgHeight = self.screen.height()

        # Пустой сертификат
        self.img = Image.open("image/first.jpg").resize(
            (self.imgWidth, self.imgHeight))
        self.img.save(self.new_img)
        self.pixmap = QPixmap(self.new_img)
        self.image = QLabel(self)
        self.image.setPixmap(self.pixmap)

        grid.addWidget(self.image, 0, 0, 10, 1)

        # Выбор шаблона сертификата
        self.template = 0
        self.rbt0 = QRadioButton("Образец 1")
        self.rbt0.setChecked(True)
        self.rbt1 = QRadioButton("Образец 2")
        grid.addWidget(self.rbt0, 1, 1)
        grid.addWidget(self.rbt1, 1, 2)
        # radioBtn = self.sender()

        # Метка (Код)
        self.lbl_code = QLabel(text="Номер")
        grid.addWidget(self.lbl_code, 2, 1)
        # Поле ввода текста (Код)
        self.ent_code = QLineEdit()
        grid.addWidget(self.ent_code, 2, 2, 1, 4)

        # Метка (Имя)
        self.lbl_name = QLabel(text="Имя")
        grid.addWidget(self.lbl_name, 3, 1)
        # Поле ввода текста (Имя)
        self.ent_name = QLineEdit()
        grid.addWidget(self.ent_name, 3, 2, 1, 4)

        # Метка (Процедура1)
        self.lbl_pro1 = QLabel(text="Процедура")
        grid.addWidget(self.lbl_pro1, 4, 1)
        # Поле ввода текста (Процедура1)
        self.ent_pro1 = QLineEdit()

        pro1List = ['SPA Комплекс', 'SPA Комплекс 2']
        completer = QCompleter(pro1List, self.ent_pro1)
        self.ent_pro1.setCompleter(completer)

        grid.addWidget(self.ent_pro1, 4, 2, 1, 4)

        # Метка (Процедура2)
        self.lbl_pro2 = QLabel(text="Доплнение")
        grid.addWidget(self.lbl_pro2, 5, 1)
        # Поле ввода текста (Процедура2)
        self.ent_pro2 = QLineEdit()

        pro2List = ['Классика на двоих', 'Еще что-нибудь']
        completer = QCompleter(pro2List, self.ent_pro1)
        self.ent_pro2.setCompleter(completer)

        grid.addWidget(self.ent_pro2, 5, 2, 1, 4)

        # Метка (Дата)
        self.lbl_date = QLabel(text="Дата")
        grid.addWidget(self.lbl_date, 6, 1)
        # Фрейм ввода текста (Дата)

        # Создание даты
        self.lbl_dateEnd = QLabel(text=datetime.now().strftime("%d.%m.%Y"))
        grid.addWidget(self.lbl_dateEnd, 6, 2)
        self.ent_dateDel = QLineEdit()
        grid.addWidget(self.ent_dateDel, 6, 3, 1, 3)

        # Кнопка обновить
        button = QPushButton('Обновить', self)
        button.clicked.connect(self.but_upgrade)
        grid.addWidget(button, 7, 1, 1, 5)

        # Кнопка сохранить
        button = QPushButton('Сохранить', self)
        button.clicked.connect(self.but_save)
        grid.addWidget(button, 8, 1, 1, 5)

        self.ent_code.editingFinished.connect(self.but_upgrade)
        self.ent_name.editingFinished.connect(self.but_upgrade)
        self.ent_pro1.editingFinished.connect(self.but_upgrade)
        self.ent_pro2.editingFinished.connect(self.but_upgrade)
        self.ent_dateDel.editingFinished.connect(self.but_upgrade)

        self.setLayout(grid)
        self.show()

    def change_data(self):
        today = datetime.now()
        if len(self.ent_dateDel.text()) == 0 or not (
                self.ent_dateDel.text().isdigit()):
            self.ent_dateDel.setText("0")

        if (today.month + int(self.ent_dateDel.text())) // 12:
            yearDelta = 1
        else:
            yearDelta = 0
        dateEnd = str(today.day) + '.' + str(
            (today.month + int(self.ent_dateDel.text())) %
            12).zfill(2) + '.' + str(today.year + yearDelta)

        return dateEnd

    def but_save(self):
        path = str(
            "C:\\Users\\zdrav\\Desktop\\ПС, АБ, карты\\Подарочные сертификаты электронные\\готовые подарочные\\") + \
               str(datetime.now().strftime("%d.%m.%Y")) + ' ' + str(self.ent_name.text()) + '.jpg'
        self.img.save(path)

    def but_upgrade(self):

        if self.rbt0.isChecked():
            self.img = Image.open("image/first.jpg").resize(
                (self.imgWidth, self.imgHeight))

            writeCodeX = self.imgWidth * 0.81
            writeCodeY = self.imgHeight * 0.15
            writeCodeColor = '#033'

            writeNameX = self.imgWidth * 0.56
            writeNameY = self.imgHeight * 0.56
            writeNameColor = '#009D91'

            writePro1X = self.imgWidth * 0.61
            writePro1Y = self.imgHeight * 0.62
            writePro1Color = '#009D91'

            writePro2X = self.imgWidth * 0.49
            writePro2Y = self.imgHeight * 0.67
            writePro2Color = '#009D91'

            writeDateX = self.imgWidth * 0.54
            writeDateY = self.imgHeight * 0.72
            writeDateColor = '#033'

            font1 = ImageFont.truetype("font/Appetite_Medium.otf", 40)
            font2 = ImageFont.truetype("font/arial_bold.ttf", 25)

        else:
            self.img = Image.open("image/second.jpg").resize(
                (self.imgWidth, self.imgHeight))

            writeCodeX = self.imgWidth * 0.837
            writeCodeY = self.imgHeight * 0.13
            writeCodeColor = '#333'

            writeNameX = self.imgWidth * 0.57
            writeNameY = self.imgHeight * 0.475
            writeNameColor = '#654321'

            writePro1X = self.imgWidth * 0.63
            writePro1Y = self.imgHeight * 0.535
            writePro1Color = '#654321'

            writePro2X = self.imgWidth * 0.51
            writePro2Y = self.imgHeight * 0.585
            writePro2Color = '#654321'

            writeDateX = self.imgWidth * 0.59
            writeDateY = self.imgHeight * 0.64
            writeDateColor = '#033'

            font1 = ImageFont.truetype("font/Appetite_Medium.otf", 40)
            font2 = ImageFont.truetype("font/arial_bold.ttf", 25)

        # Код
        writeCode = ImageDraw.Draw(self.img)
        writeCode.text((writeCodeX, writeCodeY),
                       self.ent_code.text(),
                       font=font2,
                       fill=writeCodeColor,
                       anchor="ms")

        # Имя
        writeName = ImageDraw.Draw(self.img)
        writeName.text((writeNameX, writeNameY),
                       self.ent_name.text(),
                       font=font1,
                       fill=writeNameColor,
                       anchor="ms")

        # Процедура 1
        writePro1 = ImageDraw.Draw(self.img)
        writePro1.text((writePro1X, writePro1Y),
                       self.ent_pro1.text(),
                       font=font1,
                       fill=writePro1Color,
                       anchor="ms")

        # Процедура 2
        writePro2 = ImageDraw.Draw(self.img)
        writePro2.text((writePro2X, writePro2Y),
                       self.ent_pro2.text(),
                       font=font1,
                       fill=writePro2Color,
                       anchor="ms")

        # Дата
        writeDate = ImageDraw.Draw(self.img)
        writeDate.text((writeDateX, writeDateY),
                       self.change_data(),
                       font=font2,
                       fill=writeDateColor,
                       anchor="ms")

        # Показ фото
        self.img.save(self.new_img)
        self.pixmap = QPixmap(self.new_img)
        self.image.setPixmap(self.pixmap)
Example #36
0
    def __init__(self, parent):
        super().__init__()
        self.layout = QGridLayout(self)
        self.settings = parent.settings
        self.listener = parent.listener

        self.buttons = {}

        general = QGroupBox(self)
        general_layout = QGridLayout(general)
        general.setTitle('General')
        self.layout.addWidget(general, 0, 0)

        ###################################

        label = QLabel(general)
        label.setText('Spam Right Click')
        general_layout.addWidget(label, 0, 0)

        button = QPushButton(general)
        self.buttons['right_click'] = button
        button.setText(nicer_text(self.settings.hotkeys['right_click']))
        button.clicked.connect(lambda: self.set_hotkey('right_click'))
        general_layout.addWidget(button, 0, 1)

        label = QLabel(general)
        label.setText('Spam Left Click')
        general_layout.addWidget(label, 1, 0)

        button = QPushButton(general)
        self.buttons['left_click'] = button
        button.setText(nicer_text(self.settings.hotkeys['left_click']))
        button.clicked.connect(lambda: self.set_hotkey('left_click'))
        general_layout.addWidget(button, 1, 1)

        label = QLabel(general)
        label.setText('Normalize Difficulty')
        general_layout.addWidget(label, 2, 0)

        button = QPushButton(general)
        self.buttons['lower_difficulty'] = button
        button.setText(nicer_text(self.settings.hotkeys['lower_difficulty']))
        button.clicked.connect(lambda: self.set_hotkey('lower_difficulty'))
        general_layout.addWidget(button, 2, 1)

        label = QLabel(general)
        label.setText('Swap Armor')
        general_layout.addWidget(label, 3, 0)

        button = QPushButton(general)
        self.buttons['swap_armor'] = button
        button.setText(nicer_text(self.settings.hotkeys['swap_armor']))
        button.clicked.connect(lambda: self.set_hotkey('swap_armor'))
        general_layout.addWidget(button, 3, 1)

        radio = QRadioButton(general)
        radio.setText('Cains')
        radio.clicked.connect(lambda: self.radio_clicked('cains'))
        radio.setChecked(self.settings.special['armor_swap_amount'] == 3)
        general_layout.addWidget(radio, 4, 0)

        radio = QRadioButton(general)
        radio.setText('Bounty DH')
        radio.setDisabled(True)
        radio.clicked.connect(lambda: self.radio_clicked('bounty_dh'))
        radio.setChecked(self.settings.special['armor_swap_amount'] == 2)
        general_layout.addWidget(radio, 4, 1)

        label = QLabel(general)
        label.setText('Pause Eule')
        general_layout.addWidget(label, 5, 0)

        button = QPushButton(general)
        self.buttons['pause'] = button
        button.setText(nicer_text(self.settings.hotkeys['pause']))
        button.clicked.connect(lambda: self.set_hotkey('pause'))
        general_layout.addWidget(button, 5, 1)

        porting = QGroupBox(self)
        porting_layout = QGridLayout(porting)
        porting.setTitle('Porting')
        self.layout.addWidget(porting, 1, 0)

        ######################

        label = QLabel(porting)
        label.setText('Port to A1 Town')
        porting_layout.addWidget(label, 0, 0)

        button = QPushButton(porting)
        self.buttons['port_a1'] = button
        button.setText(nicer_text(self.settings.hotkeys['port_a1']))
        button.clicked.connect(lambda: self.set_hotkey('port_a1'))
        porting_layout.addWidget(button, 0, 1)

        label = QLabel(porting)
        label.setText('Port to A2 Town')
        porting_layout.addWidget(label, 1, 0)

        button = QPushButton(porting)
        self.buttons['port_a2'] = button
        button.setText(nicer_text(self.settings.hotkeys['port_a2']))
        button.clicked.connect(lambda: self.set_hotkey('port_a2'))
        porting_layout.addWidget(button, 1, 1)

        label = QLabel(porting)
        label.setText('Port to A3 Town')
        porting_layout.addWidget(label, 2, 0)

        button = QPushButton(porting)
        self.buttons['port_a3'] = button
        button.setText(nicer_text(self.settings.hotkeys['port_a3']))
        button.clicked.connect(lambda: self.set_hotkey('port_a3'))
        porting_layout.addWidget(button, 2, 1)

        label = QLabel(porting)
        label.setText('Port to A4 Town')
        porting_layout.addWidget(label, 3, 0)

        button = QPushButton(porting)
        self.buttons['port_a4'] = button
        button.setText(nicer_text(self.settings.hotkeys['port_a4']))
        button.clicked.connect(lambda: self.set_hotkey('port_a4'))
        porting_layout.addWidget(button, 3, 1)

        label = QLabel(porting)
        label.setText('Port to A5 Town')
        porting_layout.addWidget(label, 4, 0)

        button = QPushButton(porting)
        self.buttons['port_a5'] = button
        button.setText(nicer_text(self.settings.hotkeys['port_a5']))
        button.clicked.connect(lambda: self.set_hotkey('port_a5'))
        porting_layout.addWidget(button, 4, 1)

        label = QLabel(porting)
        label.setText('Port to Pool')
        porting_layout.addWidget(label, 5, 0)

        button = QPushButton(porting)
        self.buttons['port_pool'] = button
        button.setText(nicer_text(self.settings.hotkeys['port_pool']))
        button.clicked.connect(lambda: self.set_hotkey('port_pool'))
        porting_layout.addWidget(button, 5, 1)

        label = QLabel(porting)
        label.setText('Port to A2 Temple')
        porting_layout.addWidget(label, 6, 0)

        button = QPushButton(porting)
        self.buttons['tpa2temple'] = button
        button.setText(nicer_text(self.settings.hotkeys['tpa2temple']))
        button.clicked.connect(lambda: self.set_hotkey('tpa2temple'))
        porting_layout.addWidget(button, 6, 1)

        greater_rift = QGroupBox(self)
        greater_rift_layout = QGridLayout(greater_rift)
        greater_rift.setTitle('Greater Rift')
        self.layout.addWidget(greater_rift, 0, 1)

        ####################

        label = QLabel(greater_rift)
        label.setText('Open Grift')
        greater_rift_layout.addWidget(label, 0, 0)

        button = QPushButton(greater_rift)
        self.buttons['open_gr'] = button

        button.setText(nicer_text(self.settings.hotkeys['open_gr']))
        button.clicked.connect(lambda: self.set_hotkey('open_gr'))
        greater_rift_layout.addWidget(button, 0, 1)

        label = QLabel(greater_rift)
        label.setText('Upgrade Gem')
        greater_rift_layout.addWidget(label, 1, 0)

        button = QPushButton(greater_rift)
        self.buttons['upgrade_gem'] = button
        button.setText(nicer_text(self.settings.hotkeys['upgrade_gem']))
        button.clicked.connect(lambda: self.set_hotkey('upgrade_gem'))
        greater_rift_layout.addWidget(button, 1, 1)

        checkbox = QCheckBox(greater_rift)
        checkbox.setText('Empowered')
        checkbox.stateChanged.connect(
            lambda: self.checkbox_clicked('empowered'))
        checkbox.setChecked(self.settings.special['empowered'])
        greater_rift_layout.addWidget(checkbox, 2, 0)

        checkbox = QCheckBox(greater_rift)
        checkbox.setText('Choose Gem to upgrade')
        checkbox.setToolTip(
            'If checked, will upgrade the gem currently selected.')
        checkbox.stateChanged.connect(
            lambda: self.checkbox_clicked('choose_gem'))
        checkbox.setChecked(self.settings.special['choose_gem'])
        greater_rift_layout.addWidget(checkbox, 2, 1)

        label = QLabel(greater_rift)
        label.setText('Leave Game')
        greater_rift_layout.addWidget(label, 3, 0)

        button = QPushButton(greater_rift)
        self.buttons['leave_game'] = button

        button.setText(nicer_text(self.settings.hotkeys['leave_game']))
        button.clicked.connect(lambda: self.set_hotkey('leave_game'))
        greater_rift_layout.addWidget(button, 3, 1)

        after_rift = QGroupBox(self)
        after_rift_layout = QGridLayout(after_rift)
        after_rift.setTitle('After Rift')
        self.layout.addWidget(after_rift, 1, 1)

        ######################

        label = QLabel(after_rift)
        label.setText('Salvage')
        after_rift_layout.addWidget(label, 0, 0)

        button = QPushButton(after_rift)
        self.buttons['salvage'] = button
        button.setText(nicer_text(self.settings.hotkeys['salvage']))
        button.clicked.connect(lambda: self.set_hotkey('salvage'))
        after_rift_layout.addWidget(button, 0, 1)

        label = QLabel(after_rift)
        label.setText('Drop Inventory')
        after_rift_layout.addWidget(label, 1, 0)

        button = QPushButton(after_rift)
        self.buttons['drop_inventory'] = button
        button.setText(nicer_text(self.settings.hotkeys['drop_inventory']))
        button.clicked.connect(lambda: self.set_hotkey('drop_inventory'))
        after_rift_layout.addWidget(button, 1, 1)

        label = QLabel(after_rift)
        label.setText('Spare Columns')
        after_rift_layout.addWidget(label, 2, 0)

        spinbox = QSpinBox(after_rift)
        spinbox.setMinimum(0)
        spinbox.setMaximum(10)
        spinbox.setValue(self.settings.special['spare_columns'])
        spinbox.valueChanged.connect(self.spinbox_changed)
        after_rift_layout.addWidget(spinbox, 2, 1)

        label = QLabel(after_rift)
        label.setText('Gamble')
        after_rift_layout.addWidget(label, 3, 0)

        button = QPushButton(after_rift)
        self.buttons['gamble'] = button
        button.setText(nicer_text(self.settings.hotkeys['gamble']))
        button.clicked.connect(lambda: self.set_hotkey('gamble'))
        after_rift_layout.addWidget(button, 3, 1)

        cube_converter = QGroupBox(self)
        cube_converter_layout = QGridLayout(cube_converter)
        cube_converter.setTitle('Cube Converter')
        self.layout.addWidget(cube_converter, 2, 1)

        ######################

        label = QLabel(cube_converter)
        label.setText('Convert 1-Slot')
        cube_converter_layout.addWidget(label, 0, 0, 1, 3)

        button = QPushButton(cube_converter)
        self.buttons['cube_conv_sm'] = button
        button.setText(nicer_text(self.settings.hotkeys['cube_conv_sm']))
        button.clicked.connect(lambda: self.set_hotkey('cube_conv_sm'))
        cube_converter_layout.addWidget(button, 0, 3, 1, 3)

        label = QLabel(cube_converter)
        label.setText('Convert 2-Slot')
        cube_converter_layout.addWidget(label, 1, 0, 1, 3)

        button = QPushButton(cube_converter)
        self.buttons['cube_conv_lg'] = button
        button.setText(nicer_text(self.settings.hotkeys['cube_conv_lg']))
        button.clicked.connect(lambda: self.set_hotkey('cube_conv_lg'))
        cube_converter_layout.addWidget(button, 1, 3, 1, 3)

        radio = QRadioButton(cube_converter)
        radio.setText('SoL')
        radio.setChecked(self.settings.special['cube_conv_speed'] == 'sol')
        radio.clicked.connect(lambda: self.radio_clicked('sol'))
        cube_converter_layout.addWidget(radio, 2, 0, 1, 2)

        radio = QRadioButton(cube_converter)
        radio.setText('Normal')
        radio.setChecked(self.settings.special['cube_conv_speed'] == 'normal')
        radio.clicked.connect(lambda: self.radio_clicked('normal'))
        cube_converter_layout.addWidget(radio, 2, 2, 1, 2)

        radio = QRadioButton(cube_converter)
        radio.setText('Slow')
        radio.setChecked(self.settings.special['cube_conv_speed'] == 'slow')
        radio.clicked.connect(lambda: self.radio_clicked('slow'))
        cube_converter_layout.addWidget(radio, 2, 4, 1, 2)

        label = QLabel(cube_converter)
        label.setText('Reforge / Convert Set')
        cube_converter_layout.addWidget(label, 3, 0, 1, 3)

        button = QPushButton(cube_converter)
        self.buttons['reforge'] = button
        button.setText(nicer_text(self.settings.hotkeys['reforge']))
        button.clicked.connect(lambda: self.set_hotkey('reforge'))

        cube_converter_layout.addWidget(button, 3, 3, 1, 3)

        # ------------------------------------
        # reforge until ancient & primal
        label = QLabel(cube_converter)
        label.setText('Reforge Until Ancient or Primal')
        cube_converter_layout.addWidget(label, 4, 0, 1, 3)

        button = QPushButton(cube_converter)
        self.buttons['reforge_ancient_primal'] = button
        button.setText(
            nicer_text(self.settings.hotkeys['reforge_ancient_primal']))
        button.clicked.connect(
            lambda: self.set_hotkey('reforge_ancient_primal'))

        cube_converter_layout.addWidget(button, 4, 3, 1, 3)

        # reforge until primal
        label = QLabel(cube_converter)
        label.setText('Reforge Until Primal')
        cube_converter_layout.addWidget(label, 5, 0, 1, 3)

        button = QPushButton(cube_converter)
        self.buttons['reforge_primal'] = button
        button.setText(nicer_text(self.settings.hotkeys['reforge_primal']))
        button.clicked.connect(lambda: self.set_hotkey('reforge_primal'))

        cube_converter_layout.addWidget(button, 5, 3, 1, 3)
        #------------------------------------

        skill_macro = QGroupBox(self)
        skill_macro_layout = QGridLayout(skill_macro)
        skill_macro.setTitle('Skill Macro')
        self.layout.addWidget(skill_macro, 2, 0, -1, 1)

        label = QLabel(skill_macro)
        label.setText('Activate / Deactivate')
        skill_macro_layout.addWidget(label, 0, 0)

        button = QPushButton(self)
        self.buttons['skill_macro'] = button
        button.setText(nicer_text(self.settings.hotkeys['skill_macro']))
        button.clicked.connect(lambda: self.set_hotkey('skill_macro'))
        skill_macro_layout.addWidget(button, 0, 1)

        self.setLayout(self.layout)
Example #37
0
class MainWindow(QMainWindow):
    receiveUpdateSignal = pyqtSignal(str)
    errorSignal = pyqtSignal(str)
    showSerialComboboxSignal = pyqtSignal()
    setDisableSettingsSignal = pyqtSignal(bool)
    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()

    def __del__(self):
        pass

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

    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.filePathWidget = QLineEdit()
        self.openFileButton = QPushButton("Open File")
        self.sendFileButton = QPushButton("Send File")
        self.clearHistoryButton = QPushButton("Clear History")
        self.addButton = QPushButton(parameters.strAdd)
        fileSendGroupBox = QGroupBox(parameters.strSendFile)
        fileSendGridLayout = QGridLayout()
        fileSendGridLayout.addWidget(self.filePathWidget, 0, 0, 1, 1)
        fileSendGridLayout.addWidget(self.openFileButton, 0, 1, 1, 1)
        fileSendGridLayout.addWidget(self.sendFileButton, 1, 0, 1, 2)
        fileSendGroupBox.setLayout(fileSendGridLayout)
        sendFunctionalLayout.addWidget(fileSendGroupBox)
        sendFunctionalLayout.addWidget(self.clearHistoryButton)
        sendFunctionalLayout.addWidget(self.addButton)
        sendFunctionalLayout.addStretch(1)
        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()
        print("config file path:", parameters.configFilePath)

    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.showSerialComboboxSignal.connect(self.showCombobox)
        # self.showBaudComboboxSignal.connect(self.showBaudCombobox)
        self.setDisableSettingsSignal.connect(self.setDisableSettings)
        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.openFileButton.clicked.connect(self.selectFile)
        self.sendFileButton.clicked.connect(self.sendFile)
        self.clearHistoryButton.clicked.connect(self.clearHistory)
        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)

        self.myObject = MyClass(self)
        slotLambda = lambda: self.indexChanged_lambda(self.myObject)
        self.serialPortCombobox.currentIndexChanged.connect(slotLambda)

    # @QtCore.pyqtSlot(str)
    def indexChanged_lambda(self, obj):
        mainObj = obj.arg
        # print("item changed:",mainObj.serialPortCombobox.currentText())
        self.serialPortCombobox.setToolTip(
            mainObj.serialPortCombobox.currentText())

    def openCloseSerialProcess(self):
        try:
            if self.com.is_open:
                self.receiveProgressStop = True
                self.com.close()
                self.setDisableSettingsSignal.emit(False)
            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
                    self.com.open()
                    # print("open success")
                    # print(self.com)
                    self.setDisableSettingsSignal.emit(True)
                    self.receiveProcess = threading.Thread(
                        target=self.receiveData)
                    self.receiveProcess.setDaemon(True)
                    self.receiveProcess.start()
                except Exception as e:
                    self.com.close()
                    self.receiveProgressStop = True
                    self.errorSignal.emit(parameters.strOpenFailed + "\n" +
                                          str(e))
                    self.setDisableSettingsSignal.emit(False)
        except Exception as e:
            print(e)

    def setDisableSettings(self, disable):
        if disable:
            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)
        else:
            self.serialOpenCloseButton.setText(parameters.strOpen)
            self.statusBarStauts.setText("<font color=%s>%s</font>" %
                                         ("#f31414", parameters.strClosed))
            self.serialPortCombobox.setDisabled(False)
            self.serailBaudrateCombobox.setDisabled(False)
            self.serailParityCombobox.setDisabled(False)
            self.serailStopbitsCombobox.setDisabled(False)
            self.serailBytesCombobox.setDisabled(False)
            self.programExitSaveParameters()

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

    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()

    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)

    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

    def receiveData(self):
        self.receiveProgressStop = False
        self.timeLastReceive = 0
        while (not self.receiveProgressStop):
            try:
                # length = self.com.in_waiting
                length = max(1, min(2048, self.com.in_waiting))
                bytes = self.com.read(length)
                if bytes != None:

                    # if self.isWaveOpen:
                    #     self.wave.displayData(bytes)
                    self.receiveCount += len(bytes)
                    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()
                    if self.receiveSettingsHex.isChecked():
                        strReceived = self.asciiB2HexString(bytes)
                        self.receiveUpdateSignal.emit(strReceived)
                    else:
                        self.receiveUpdateSignal.emit(
                            bytes.decode(self.encodingCombobox.currentText(),
                                         "ignore"))
            except Exception as e:
                # print("receiveData error")
                # if self.com.is_open and not self.serialPortCombobox.isEnabled():
                #     self.openCloseSerial()
                #     self.serialPortCombobox.clear()
                #     self.detectSerialPort()
                if 'multiple access' in str(e):
                    self.errorSignal.emit(
                        "device disconnected or multiple access on port?")
                break
            # time.sleep(0.009)

    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))

    def onSendSettingsHexClicked(self):

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

    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")

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

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

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

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

    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 showCombobox(self):
        self.serialPortCombobox.showPopup()

    def detectSerialPortProcess(self):
        while (1):
            portList = self.findSerialPort()
            if len(portList) > 0:
                currText = self.serialPortCombobox.currentText()
                self.serialPortCombobox.clear()
                for i in portList:
                    showStr = str(i[0]) + " " + str(i[1])
                    if i[0].startswith("/dev/cu.Bluetooth-Incoming-Port"):
                        continue
                    self.serialPortCombobox.addItem(showStr)
                index = self.serialPortCombobox.findText(currText)
                if index >= 0:
                    self.serialPortCombobox.setCurrentIndex(index)
                else:
                    self.serialPortCombobox.setCurrentIndex(0)
                break
            time.sleep(1)
        self.showSerialComboboxSignal.emit()
        self.isDetectSerialPort = False

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

    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(parameters.configFilePath, "wb")
        f.truncate()
        pickle.dump(paramObj, f)
        pickle.dump(paramObj.sendHistoryList, f)
        f.close()

    def programStartGetSavedParameters(self):
        paramObj = parameters.ParametersToSave()
        try:
            f = open(parameters.configFilePath, "rb")
            paramObj = pickle.load(f)
            paramObj.sendHistoryList = pickle.load(f)
            f.close()
        except Exception as e:
            f = open(parameters.configFilePath, "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

    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()

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

    def sendAreaFontChanged(self, font):
        print("font changed")

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

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

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

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

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

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

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

    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))

    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())

    def selectFile(self):
        oldPath = self.filePathWidget.text()
        if oldPath == "":
            oldPath = os.getcwd()
        fileName_choose, filetype = QFileDialog.getOpenFileName(
            self, "SelectFile", oldPath, "All Files (*);;")

        if fileName_choose == "":
            return
        self.filePathWidget.setText(fileName_choose)

    def sendFile(self):
        filename = self.filePathWidget.text()
        if not os.path.exists(filename):
            self.errorSignal.emit("File path error\npath:%s" % (filename))
            return
        try:
            f = open(filename, "rb")
        except Exception as e:
            self.errorSignal.emit("Open file %s failed! \n %s" %
                                  (filename, str(e)))
            return
        self.com.write(f.read())  #TODO: optimize send in new thread
        f.close()

    def clearHistory(self):
        self.param.sendHistoryList.clear()
        self.sendHistory.clear()
        self.errorSignal.emit("History cleared!")

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

    def openDevManagement(self):
        os.system('start devmgmt.msc')
Example #38
0
class window(QWidget):
    def __init__(self, parent=None):
        #initialise the windows(compulsory all time)
        super().__init__(parent)
        #title of window
        self.title = "Passwordify"
        #set position of widget(geometry)
        self.left = 500
        self.top = 200
        #set size of widget
        self.minimumWidth = 350
        self.minimumHeight = 500
        self.maxiheight = 500
        self.maximumWid = 600
        self.setWindowIcon(QtGui.QIcon('padlock.svg'))
        self.setStyleSheet('background-color:#01579b')

        #add icon
        #self.iconed=''
        #initialise windows,items are to be placed within the initwindows

        self.initwindow()
        self.layout_widget()

    def initwindow(self):
        self.setWindowTitle(self.title, )

        self.setMaximumHeight(self.maxiheight)
        self.setMaximumWidth(self.maximumWid)
        self.setGeometry(self.left, self.top, self.minimumHeight,
                         self.minimumWidth)
        self.show()

    def command(self):
        #aadd functionality to widgets
        spinval = self.spinbox.value()
        global new
        #if password is set to weak do this
        if self.radio3.isChecked() == True:
            ans = random.choices(weak, k=(spinval))
            new = ''.join(ans)
            self.linedisplay.setText(str(new))

    #if password is set to mediuum do this
        elif self.radio2.isChecked() == True:
            ans = random.choices(mediuum, k=(spinval))
            new = ''.join(ans)
            self.linedisplay.setText(str(new))

    #if password is set to strong do this
        elif self.radio1.isChecked() == True:
            ans = random.choices(strong, k=(spinval))
            new = ''.join(ans)
            self.linedisplay.setText(str(new))

    #copy password to paste to clipboard

    def copy(self):
        try:
            pc.copy(new)
            self.message.exec_()

        except NameError:
            self.linedisplay.setText('NULL')

    def layout_widget(self):
        #create layout
        grid = QGridLayout()
        self.setLayout(grid)

        #create widgets 'QSpinbox,QPushButton,QRadioButton,Qlinedisplay and QLabel'
        self.spinbox = QSpinBox()

        self.radio3 = QRadioButton('Weak')
        self.radio2 = QRadioButton('Medium')
        self.radio1 = QRadioButton('Strong')

        self.button1 = QPushButton('Copy')
        self.button2 = QPushButton('Shuffle password')

        self.linedisplay = QLineEdit()

        self.label = QLabel('Password Length:')

        self.message = QMessageBox()

        #add widgets to grid layout
        grid.addWidget(self.label, 0, 0, 1, 3)
        grid.addWidget(self.spinbox, 0, 2, 1, 3)
        grid.addWidget(self.radio3, 1, 0)
        grid.addWidget(self.radio2, 1, 3, 1, 4)
        grid.addWidget(self.radio1, 1, 6)
        grid.addWidget(self.linedisplay, 2, 1, 1, 5)
        grid.addWidget(self.button1, 3, 0, 1, 2)
        grid.addWidget(self.button2, 3, 5, 1, 2)

        #setstyle sheet  and functionality for widgett and window
        self.radio1.setStyleSheet(
            'color:white;font-size:20px;font-family:cambria')
        self.radio2.setStyleSheet(
            'color:yellow;font-size:20px;font-family:cambria')
        self.radio2.setChecked(True)
        self.radio3.setStyleSheet(
            'color:red;font-size:20px;font-family:cambria')

        self.button1.setStyleSheet(
            'padding:10px;color:black;font-family:cambria;font-size:15px;')
        self.button1.setToolTip('Copy to clipboard and paste where needed')
        self.button1.clicked.connect(self.copy)

        self.button2.setStyleSheet(
            'padding:10px;color:white;font-family:cambria;font-size:15px;')
        self.button2.clicked.connect(self.command)

        self.linedisplay.setStyleSheet(
            'background-color:none;padding:10px;font-size:30px')
        self.linedisplay.setPlaceholderText('Generated Password')
        self.linedisplay.setReadOnly(True)

        self.spinbox.setStyleSheet('background-color:white;font-size:50px')
        self.spinbox.setRange(6, 14)
        self.spinbox.valueChanged.connect(self.command)

        self.label.setStyleSheet(
            'color:white;font-family:cambria;font-size:15px')

        self.message.setText('Copied to clipboard')
        self.message.setIcon(QMessageBox.Information)
        self.message.buttonClicked.connect(self.copy)
Example #39
0
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)

        # curr mouse position in plot coordinates
        self.curr_x = 0
        self.curr_y = 0
        # circle color (color picker)
        self.color = QColor()
        # circles size (slider)
        self.curr_size = 10

        # list with circles
        self.circles = []
        # artist for the plot
        self.artists = []

        self.fileName = 'some_qml.xml'
        # gui stuff
        self.layout = QVBoxLayout(self)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 200)

        # Add tabs
        self.tabs.addTab(self.tab1, "Edit")
        self.tabs.addTab(self.tab2, "Model")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.tab1.setLayout(self.tab1.layout)

        # Creating widgets
        self.m = PlotCanvas(self.tab1, width=5, height=5)
        self.m.move(0, 0)

        pb_plus = Button('+', self.tab1, 500, 0, 140, 100)
        pb_minus = Button('-', self.tab1, 500, 100, 140, 100)
        pb_choose_color = Button('Choose Color', self.tab1)

        self.le_x_coord = QLineEdit()
        self.le_y_coord = QLineEdit()
        self.le_slider = QLineEdit()
        self.le_x_coord.setDisabled(True)
        self.le_y_coord.setDisabled(True)
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(1.0, 100.0)
        pb_save_qml = Button('Save to xml', self.tab1)
        pb_open_qml = Button('Open xml', self.tab1)
        pb_draw_system = Button('Draw Sun system', self.tab1)
        pb_start_animation = Button('Start animation', self.tab1)

        # tab Edit
        # Adding widgets to layout
        self.tab1.layout.addWidget(self.m)
        self.tab1.layout_coords = QHBoxLayout()
        self.tab1.layout.addLayout(self.tab1.layout_coords)
        self.tab1.layout_coords.addWidget(self.le_x_coord)
        self.tab1.layout_coords.addWidget(self.le_y_coord)
        self.tab1.layout_coords.addWidget(pb_plus)
        self.tab1.layout_coords.addWidget(pb_minus)

        self.tab1.layout_size = QHBoxLayout()
        self.tab1.layout.addLayout(self.tab1.layout_size)
        self.tab1.layout.addWidget(pb_choose_color)
        self.tab1.label_size = QLabel('Choose size ')
        self.tab1.layout_size.addWidget(self.tab1.label_size)
        self.tab1.layout_size.addWidget(self.slider)
        self.tab1.layout_size.addWidget(self.le_slider)

        layout_save = QHBoxLayout()
        layout_open = QHBoxLayout()
        self.tab1.le_saveFileName = QLineEdit()
        self.tab1.le_openFileName = QLineEdit()
        self.tab1.layout.addLayout(layout_save)
        self.tab1.layout.addLayout(layout_open)
        layout_save.addWidget(pb_save_qml)
        layout_save.addWidget(self.tab1.le_saveFileName)
        self.tab1.le_saveFileName.setText(self.fileName)
        layout_open.addWidget(pb_open_qml)
        layout_open.addWidget(self.tab1.le_openFileName)
        self.tab1.le_openFileName.setText(self.fileName)
        self.tab1.layout.addWidget(pb_draw_system)
        self.tab1.layout.addWidget(pb_start_animation)

        # connecting slots
        pb_plus.clicked.connect(self.m.zoomIn)
        pb_minus.clicked.connect(self.m.zoomOut)
        pb_choose_color.clicked.connect(self.showColorPicker)
        pb_save_qml.clicked.connect(self.showSaveDialog)
        pb_open_qml.clicked.connect(self.showOpenDialog)
        pb_draw_system.clicked.connect(self.drawSunEarthMoonSystem)
        pb_start_animation.clicked.connect(self.startAnimation)
        self.slider.valueChanged.connect(self.sliderValueChanged)
        self.le_slider.textChanged.connect(self.textSliderValueChanged)
        self.m.mpl_connect('motion_notify_event', self.changeCoords)
        self.m.mpl_connect('button_press_event', self.drawCircleMouseClick)

        self.slider.setValue(10)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        # tab Model
        self.tab2.layout = QVBoxLayout(self)
        self.tab2.setLayout(self.tab2.layout)

        rb_scipy = QRadioButton('scipy')
        rb_verlet = QRadioButton('verlet')
        rb_verletThreading = QRadioButton('verlet-threading')
        rb_verletMultiprocessing = QRadioButton('verlet-multiprocessing')
        rb_verletCython = QRadioButton('verlet-cython')
        rb_verletOpenCL = QRadioButton('verlet-opencl')
        rb_verlet.setChecked(True)
        vbox = QVBoxLayout()
        vbox.addWidget(rb_scipy)
        vbox.addWidget(rb_verlet)
        vbox.addWidget(rb_verletThreading)
        vbox.addWidget(rb_verletCython)
        vbox.addWidget(rb_verletMultiprocessing)
        vbox.addWidget(rb_verletOpenCL)
        groupBox = QGroupBox()
        groupBox.setTitle('Select mode')
        groupBox.setLayout(vbox)
        self.tab2.layout.addWidget(groupBox)
class MatchDataWidget(QWidget):
    """Widget to display match data."""
    def __init__(self, parent, tabWidget, matchData, closeable=True):
        """Init widget."""
        super().__init__(parent)

        self.max_no_sets = scctool.settings.max_no_sets
        self.max_no_vetoes = int(scctool.settings.max_no_sets / 2) * 2
        self.scoreWidth = 35
        self.raceWidth = 50
        self.labelWidth = 35
        self.mimumLineEditWidth = 130

        self._tabWidget = tabWidget
        self.matchData = matchData
        self._ctrlID = self.matchData.getControlID()
        self.parent = parent
        self.controller = parent.controller
        self.tlock = TriggerLock()
        self._tabIdx = self._tabWidget.addTab(self, '')
        with self.tlock:
            self._createView()
            self.updateForms()
        self._radioButton = QRadioButton()
        self._radioButton.setStyleSheet("color: green")
        self._radioButton.setToolTip(_('Activate Match'))
        if self.controller.matchControl.selectedMatchId() == self._ctrlID:
            self._tabWidget.setCurrentIndex(self._tabIdx)
        self._tabWidget.tabBar().setTabButton(self._tabIdx,
                                              QTabBar.ButtonPosition.LeftSide,
                                              self._radioButton)
        self._radioButton.toggled.connect(self.activate)
        if self.controller.matchControl.activeMatchId() == self._ctrlID:
            self.checkButton()

        self._closeButton = QPushButton()
        pixmap = QIcon(scctool.settings.getResFile('close.png'))
        self._closeButton.setIcon(pixmap)
        self._closeButton.setFlat(True)
        self._closeButton.clicked.connect(self.closeTab)
        self._closeButton.setToolTip(_('Close Match'))
        self._tabWidget.tabBar().setTabButton(self._tabIdx,
                                              QTabBar.ButtonPosition.RightSide,
                                              self._closeButton)
        self.setClosable(closeable)

    def setClosable(self, closeable):
        """Make the tab closable."""
        self._closeButton.setHidden(not closeable)

    def closeTab(self):
        """Close the tab."""
        self.controller.matchControl.mutex.lock()
        try:
            if self._tabWidget.count() > 1:
                idx = self._tabWidget.indexOf(self)
                ident = self.matchData.getControlID()
                self._tabWidget.removeTab(idx)
                new_index = self.controller.matchControl.removeMatch(ident)
                if new_index is not None:
                    self._tabWidget.widget(new_index).checkButton()
            count = self._tabWidget.count()
            if count == 1:
                self._tabWidget.widget(0).setClosable(False)
        finally:
            self.controller.matchControl.mutex.unlock()

    def checkButton(self):
        """Check the button."""
        self._radioButton.setChecked(True)

    def activate(self, checked):
        """Activate match tab."""
        self.controller.matchControl.mutex.lock()
        try:
            if (checked and self.controller.matchControl.activeMatchId() !=
                    self._ctrlID):
                self.controller.matchControl.activateMatch(
                    self.matchData.getControlID())
                self.autoSetNextMap(send=False)
                self.controller.mapstatsManager.sendMapPool()
                self.parent.updateAllMapButtons()
                self.controller.updateLogosWebsocket()
            elif self.controller.matchControl.countMatches() == 1:
                self._radioButton.toggled.disconnect()
                self._radioButton.setChecked(True)
                self._radioButton.toggled.connect(self.activate)
        finally:
            self.controller.matchControl.mutex.unlock()

    def setName(self):
        """Set the name of the tab."""
        team1 = self.matchData.getTeamOrPlayer(0).replace('&', '&&')
        team2 = self.matchData.getTeamOrPlayer(1).replace('&', '&&')
        name = " {} vs {}".format(team1, team2)
        self._tabWidget.tabBar().setTabText(self._tabIdx, name)

    def _createView(self):
        """Create the view."""
        layout = QVBoxLayout()

        self.le_league = MonitoredLineEdit()
        self.le_league.setText("League TBD")
        self.le_league.setAlignment(Qt.AlignCenter)
        self.le_league.setPlaceholderText("League TBD")
        self.le_league.textModified.connect(self.league_changed)
        policy = QSizePolicy()
        policy.setHorizontalStretch(3)
        policy.setHorizontalPolicy(QSizePolicy.Expanding)
        policy.setVerticalStretch(1)
        policy.setVerticalPolicy(QSizePolicy.Fixed)
        self.le_league.setSizePolicy(policy)

        self.le_team = [MonitoredLineEdit() for y in range(2)]
        self.le_player = [[
            MonitoredLineEdit() for x in range(self.max_no_sets)
        ] for y in range(2)]
        self.cb_race = [[QComboBox() for x in range(self.max_no_sets)]
                        for y in range(2)]
        self.sl_score = [
            QSlider(Qt.Horizontal) for y in range(self.max_no_sets)
        ]
        self.le_map = [MapLineEdit() for y in range(self.max_no_sets)]
        self.label_set = [
            QPushButton('#{}'.format(y + 1), self)
            for y in range(self.max_no_sets)
        ]
        self.setContainer = [QHBoxLayout() for y in range(self.max_no_sets)]

        container = QHBoxLayout()
        for team_idx in range(2):
            self.le_team[team_idx].setText("TBD")
            self.le_team[team_idx].setAlignment(Qt.AlignCenter)
            self.le_team[team_idx].setPlaceholderText("Team " +
                                                      str(team_idx + 1))
            policy = QSizePolicy()
            policy.setHorizontalStretch(4)
            policy.setHorizontalPolicy(QSizePolicy.Expanding)
            policy.setVerticalStretch(1)
            policy.setVerticalPolicy(QSizePolicy.Fixed)
            self.le_team[team_idx].setSizePolicy(policy)
            self.le_team[team_idx].setMinimumWidth(self.mimumLineEditWidth)
            self.le_team[team_idx].textModified.connect(
                lambda team_idx=team_idx: self.team_changed(team_idx))

        self.qb_logo1 = IconPushButton()
        self.qb_logo1.setFixedWidth(self.raceWidth)
        self.qb_logo1.clicked.connect(lambda: self.parent.logoDialog(1, self))
        logo = self.controller.logoManager.getTeam1(self._ctrlID)
        self.qb_logo1.setIcon(QIcon(logo.provideQPixmap()))

        self.qb_logo2 = IconPushButton()
        self.qb_logo2.setFixedWidth(self.raceWidth)
        self.qb_logo2.clicked.connect(lambda: self.parent.logoDialog(2, self))
        logo = self.controller.logoManager.getTeam2(self._ctrlID)
        self.qb_logo2.setIcon(QIcon(logo.provideQPixmap()))

        self.sl_team = QSlider(Qt.Horizontal)
        self.sl_team.setTracking(False)
        self.sl_team.setMinimum(-1)
        self.sl_team.setMaximum(1)
        self.sl_team.setValue(0)
        self.sl_team.setTickPosition(QSlider.TicksBothSides)
        self.sl_team.setTickInterval(1)
        self.sl_team.valueChanged.connect(lambda x: self.sl_changed(-1, x))
        self.sl_team.setToolTip(_('Choose your team'))
        self.sl_team.setMinimumHeight(5)
        self.sl_team.setFixedWidth(self.scoreWidth)
        policy = QSizePolicy()
        policy.setHorizontalStretch(0)
        policy.setHorizontalPolicy(QSizePolicy.Fixed)
        policy.setVerticalStretch(1)
        policy.setVerticalPolicy(QSizePolicy.Fixed)
        self.sl_team.setSizePolicy(policy)

        container = QGridLayout()

        self.pb_swap = QPushButton()
        pixmap = QIcon(scctool.settings.getResFile('update.png'))
        self.pb_swap.setIcon(pixmap)
        self.pb_swap.clicked.connect(self.controller.swapTeams)
        self.pb_swap.setFixedWidth(self.labelWidth)
        self.pb_swap.setToolTip(_("Swap teams and logos."))
        container.addWidget(self.pb_swap, 0, 0, 2, 1)

        label = QLabel(_("League:"))
        label.setAlignment(Qt.AlignCenter)
        policy = QSizePolicy()
        policy.setHorizontalStretch(4)
        policy.setHorizontalPolicy(QSizePolicy.Expanding)
        policy.setVerticalStretch(1)
        policy.setVerticalPolicy(QSizePolicy.Fixed)
        label.setSizePolicy(policy)
        container.addWidget(label, 0, 1, 1, 1)

        label = QLabel(_('Maps \\ Teams:'))
        label.setAlignment(Qt.AlignCenter)
        policy = QSizePolicy()
        policy.setHorizontalStretch(4)
        policy.setHorizontalPolicy(QSizePolicy.Expanding)
        policy.setVerticalStretch(1)
        policy.setVerticalPolicy(QSizePolicy.Fixed)
        label.setSizePolicy(policy)
        container.addWidget(label, 1, 1, 1, 1)

        container.addWidget(self.qb_logo1, 0, 2, 2, 1)
        container.addWidget(self.le_league, 0, 3, 1, 3)
        container.addWidget(self.le_team[0], 1, 3, 1, 1)
        container.addWidget(self.sl_team, 1, 4, 1, 1)
        container.addWidget(self.le_team[1], 1, 5, 1, 1)
        container.addWidget(self.qb_logo2, 0, 6, 2, 1)

        layout.addLayout(container)

        for player_idx in range(self.max_no_sets):
            self.le_map[player_idx].textModified.connect(
                lambda player_idx=player_idx: self.map_changed(player_idx))
            for team_idx in range(2):
                self.cb_race[team_idx][player_idx].\
                    currentIndexChanged.connect(
                    lambda idx,
                    t=team_idx,
                    p=player_idx: self.race_changed(t, p))
                self.le_player[team_idx][player_idx].textModified.connect(
                    lambda t=team_idx, p=player_idx: self.player_changed(t, p))
                self.le_player[team_idx][player_idx].setText("TBD")
                self.le_player[team_idx][player_idx].setAlignment(
                    Qt.AlignCenter)
                self.le_player[team_idx][player_idx].setPlaceholderText(
                    _("Player {} of team {}").format(player_idx + 1,
                                                     team_idx + 1))
                self.le_player[team_idx][player_idx].setMinimumWidth(
                    self.mimumLineEditWidth)
                self.le_player[team_idx][player_idx].setContextMenuPolicy(
                    Qt.CustomContextMenu)
                self.le_player[team_idx][player_idx].\
                    customContextMenuRequested.connect(
                    lambda x, team_idx=team_idx,
                    player_idx=player_idx:
                    self.openPlayerContextMenu(team_idx, player_idx))

                for i in range(4):
                    self.cb_race[team_idx][player_idx].addItem(
                        QIcon(scctool.settings.getResFile(str(i) + ".png")),
                        "")

                self.cb_race[team_idx][player_idx].setFixedWidth(
                    self.raceWidth)

            self.sl_score[player_idx].setMinimum(-1)
            self.sl_score[player_idx].setMaximum(1)
            self.sl_score[player_idx].setValue(0)
            self.sl_score[player_idx].setTickPosition(QSlider.TicksBothSides)
            self.sl_score[player_idx].setTickInterval(1)
            self.sl_score[player_idx].setTracking(False)
            self.sl_score[player_idx].valueChanged.connect(
                lambda x, player_idx=player_idx: self.sl_changed(
                    player_idx, x))
            self.sl_score[player_idx].setToolTip(_('Set the score'))
            self.sl_score[player_idx].setFixedWidth(self.scoreWidth)

            self.le_map[player_idx].setText("TBD")
            self.le_map[player_idx].setAlignment(Qt.AlignCenter)
            self.le_map[player_idx].setPlaceholderText(
                _("Map {}").format(player_idx + 1))
            self.le_map[player_idx].setMinimumWidth(self.mimumLineEditWidth)

            # self.le_map[player_idx].setReadOnly(True)

            self.setContainer[player_idx] = QHBoxLayout()
            # self.label_set[player_idx].setText("#" + str(player_idx + 1))
            # self.label_set[player_idx].setAlignment(
            #    Qt.AlignCenter)
            self.label_set[player_idx].setToolTip(
                _("Select map on Mapstats Browser Source."))
            self.label_set[player_idx].setEnabled(False)
            self.label_set[player_idx].clicked.connect(
                lambda x, player_idx=player_idx: self.showMap(player_idx))
            self.label_set[player_idx].setFixedWidth(self.labelWidth)
            self.setContainer[player_idx].addWidget(self.label_set[player_idx],
                                                    0)
            self.setContainer[player_idx].addWidget(self.le_map[player_idx], 4)
            self.setContainer[player_idx].addWidget(
                self.cb_race[0][player_idx], 0)
            self.setContainer[player_idx].addWidget(
                self.le_player[0][player_idx], 4)
            self.setContainer[player_idx].addWidget(self.sl_score[player_idx],
                                                    0)
            self.setContainer[player_idx].addWidget(
                self.le_player[1][player_idx], 4)
            self.setContainer[player_idx].addWidget(
                self.cb_race[1][player_idx], 0)
            layout.addLayout(self.setContainer[player_idx])

        self.createVetoGroupBox()
        layout.addWidget(self.veto_groupbox)

        layout.addItem(
            QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding))
        self.setLayout(layout)

        self.updateMapCompleters()
        self.updatePlayerCompleters()
        self.updateTeamCompleters()

    def createVetoGroupBox(self):
        """Create a group box to insert vetoes."""
        self.veto_groupbox = QGroupBox(_('Map Vetoes'))
        self.veto_groupbox.setVisible(False)
        box_layout = QGridLayout()
        rows = int(self.max_no_vetoes / 2)
        self.le_veto_maps = [MapLineEdit() for i in range(self.max_no_vetoes)]
        self.veto_label = [
            QLabel(f'#{i+1}') for i in range(self.max_no_vetoes)
        ]
        self.sl_veto = [
            QSlider(Qt.Horizontal) for i in range(self.max_no_vetoes)
        ]
        self.row_label = [QLabel('') for y in range(rows)]
        for veto_idx in range(self.max_no_vetoes):
            row = veto_idx / 2
            col = (veto_idx % 2) * 2
            veto_layout = QHBoxLayout()
            self.le_veto_maps[veto_idx].textModified.connect(
                lambda veto_idx=veto_idx: self.map_veto_changed(veto_idx))
            self.sl_veto[veto_idx].valueChanged.connect(
                lambda value, veto_idx=veto_idx: self.veto_team_changed(
                    veto_idx, value))
            self.veto_label[veto_idx].setFixedWidth(self.labelWidth - 5)
            veto_layout.addWidget(self.veto_label[veto_idx])
            self.le_veto_maps[veto_idx].setText("TBD")
            self.le_veto_maps[veto_idx].setAlignment(Qt.AlignCenter)
            self.le_veto_maps[veto_idx].setPlaceholderText(
                _("Map Veto {}").format(veto_idx + 1))
            self.le_veto_maps[veto_idx].setMinimumWidth(
                self.mimumLineEditWidth)
            veto_layout.addWidget(self.le_veto_maps[veto_idx])
            self.sl_veto[veto_idx].setMinimum(0)
            self.sl_veto[veto_idx].setMaximum(1)
            self.sl_veto[veto_idx].setValue(veto_idx % 2)
            self.sl_veto[veto_idx].setTickPosition(QSlider.TicksBothSides)
            self.sl_veto[veto_idx].setTickInterval(1)
            self.sl_veto[veto_idx].setTracking(False)
            self.sl_veto[veto_idx].setToolTip(
                _('Select which player/team vetoes.'))
            self.sl_veto[veto_idx].setFixedWidth(self.scoreWidth - 5)
            veto_layout.addWidget(self.sl_veto[veto_idx])
            box_layout.addLayout(veto_layout, row, col)
        for idx in range(int(self.max_no_vetoes / 2)):
            self.row_label[idx].setFixedWidth(self.labelWidth / 2 + 5)
            box_layout.addWidget(self.row_label[idx], idx, 1)
        self.veto_groupbox.setLayout(box_layout)

    def toggleVetoes(self, visible=True):
        """Toggle the visibility of the veto group box."""
        self.veto_groupbox.setVisible(visible)

    def openPlayerContextMenu(self, team_idx, player_idx):
        """Open the player context menu."""
        menu = self.le_player[team_idx][player_idx].\
            createStandardContextMenu()
        first_action = menu.actions()[0]
        add_alias_action = QAction('Add Alias')
        add_alias_action.triggered.connect(
            lambda x, team_idx=team_idx, player_idx=player_idx: self.addAlias(
                team_idx, player_idx))
        menu.insertAction(first_action, add_alias_action)
        menu.insertSeparator(first_action)
        menu.exec_(QCursor.pos())

    def addAlias(self, team_idx, player_idx):
        """Add a player alias."""
        name = self.le_player[team_idx][player_idx].text().strip()
        name, ok = QInputDialog.getText(self,
                                        _('Player Alias'),
                                        _('Name') + ':',
                                        text=name)
        if not ok:
            return

        name = name.strip()
        alias, ok = QInputDialog.getText(self,
                                         _('Alias'),
                                         _('Alias of {}').format(name) + ':',
                                         text="")

        alias = alias.strip()
        if not ok:
            return
        try:
            self.controller.aliasManager.addPlayerAlias(name, alias)
        except Exception as e:
            module_logger.exception("message")
            QMessageBox.critical(self, _("Error"), str(e))

    def league_changed(self):
        """Handle a change of the league."""
        if not self.tlock.trigger():
            return
        self.matchData.setLeague(self.le_league.text())

    def sl_changed(self, set_idx, value):
        """Handle a new score value."""
        try:
            if self.tlock.trigger():
                if set_idx == -1:
                    self.matchData.setMyTeam(value)
                else:
                    self.matchData.setMapScore(set_idx, value, True)
                    self.allkillUpdate()
                    self.autoSetNextMap()
        except Exception:
            module_logger.exception("message")

    def player_changed(self, team_idx, player_idx):
        """Handle a change of player names."""
        if not self.tlock.trigger():
            return
        try:
            player = self.le_player[team_idx][player_idx].text().strip()
            race = self.cb_race[team_idx][player_idx].currentIndex()
            if (player_idx == 0 and self.matchData.getSolo()):
                for p_idx in range(1, self.max_no_sets):
                    self.le_player[team_idx][p_idx].setText(player)
                    self.player_changed(team_idx, p_idx)
            self.controller.historyManager.insertPlayer(player, race)
            self.matchData.setPlayer(
                team_idx, player_idx,
                self.le_player[team_idx][player_idx].text())

            if race == 0:
                new_race = scctool.settings.race2idx(
                    self.controller.historyManager.getRace(player))
                if new_race != 0:
                    self.cb_race[team_idx][player_idx].setCurrentIndex(
                        new_race)
            elif player.lower() == "tbd":
                self.cb_race[team_idx][player_idx].setCurrentIndex(0)
            self.updatePlayerCompleters()
            self.setName()
        except Exception:
            module_logger.exception("message")

    def race_changed(self, team_idx, player_idx):
        """Handle a change of player names."""
        if not self.tlock.trigger():
            return
        player = self.le_player[team_idx][player_idx].text().strip()
        race = self.cb_race[team_idx][player_idx].currentIndex()
        self.controller.historyManager.insertPlayer(player, race)
        self.matchData.setRace(
            team_idx, player_idx,
            scctool.settings.idx2race(
                self.cb_race[team_idx][player_idx].currentIndex()))
        try:
            if (player_idx == 0 and self.matchData.getSolo()):
                idx = self.cb_race[team_idx][0].currentIndex()
                for player_idx in range(1, self.max_no_sets):
                    self.cb_race[team_idx][player_idx].setCurrentIndex(idx)

        except Exception:
            module_logger.exception("message")

    def team_changed(self, team_idx):
        """Handle change of the team."""
        if not self.tlock.trigger():
            return
        team = self.le_team[team_idx].text().strip()
        logo = self.controller.logoManager.getTeam(team_idx + 1).getIdent()
        if logo == '0':
            logo = self.controller.historyManager.getLogo(team)
            if logo != '0':
                self.controller.logoManager.setTeamLogo(team_idx + 1, logo)
                self.controller.updateLogos(True)
        self.controller.historyManager.insertTeam(team, logo)
        self.updateTeamCompleters()
        self.matchData.setTeam(team_idx, team)
        self.matchData.autoSetMyTeam()
        self.sl_team.setValue(self.matchData.getMyTeam())
        self.setName()

    def map_changed(self, set_idx):
        """Handle a map change."""
        if not self.tlock.trigger():
            return
        self.matchData.setMap(set_idx, self.le_map[set_idx].text())
        self.updateMapButtons()
        self.autoSetNextMap(set_idx)

    def map_veto_changed(self, idx):
        """Handle a map veto change."""
        if not self.tlock.trigger():
            return
        self.matchData.setVeto(idx, self.le_veto_maps[idx].text())
        self.controller.mapstatsManager.sendMapPool()

    def veto_team_changed(self, idx, team):
        """Handle a map veto change."""
        if not self.tlock.trigger():
            return
        self.matchData.setVeto(idx, self.le_veto_maps[idx].text(), team)

    def autoSetNextMap(self, idx=-1, send=True):
        """Set the next map automatically."""
        if self.controller.matchControl.activeMatchId() == self._ctrlID:
            self.controller.autoSetNextMap(idx, send)

    def updateMapCompleters(self):
        """Update the auto completers for maps."""
        for i in range(self.max_no_sets):
            map_list = scctool.settings.maps.copy()
            try:
                map_list.remove("TBD")
            except Exception:
                pass
            finally:
                map_list.sort()
                map_list.append("TBD")
            completer = QCompleter(map_list, self.le_map[i])
            completer.setCaseSensitivity(Qt.CaseInsensitive)
            completer.setFilterMode(Qt.MatchContains)
            completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
            completer.setWrapAround(True)
            completer.activated.connect(self.le_map[i].completerFinished)
            self.le_map[i].setCompleter(completer)

        for i in range(self.max_no_vetoes):
            map_list = scctool.settings.maps.copy()
            if 'TBD' in map_list:
                map_list.remove('TBD')
            map_list.sort()
            map_list.append('TBD')
            completer = QCompleter(map_list, self.le_veto_maps[i])
            completer.setCaseSensitivity(Qt.CaseInsensitive)
            completer.setFilterMode(Qt.MatchContains)
            completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
            completer.setWrapAround(True)
            completer.activated.connect(self.le_veto_maps[i].completerFinished)
            self.le_veto_maps[i].setCompleter(completer)

    def updatePlayerCompleters(self):
        """Refresh the completer for the player line edits."""
        player_list = scctool.settings.config.getMyPlayers(True) + [
            "TBD"
        ] + self.controller.historyManager.getPlayerList()
        for player_idx in range(self.max_no_sets):
            for team_idx in range(2):
                completer = QCompleter(player_list,
                                       self.le_player[team_idx][player_idx])
                completer.setCaseSensitivity(Qt.CaseInsensitive)
                completer.setCompletionMode(QCompleter.InlineCompletion)
                completer.setFilterMode(Qt.MatchContains)
                completer.setWrapAround(True)
                completer.activated.connect(
                    self.le_player[team_idx][player_idx].completerFinished)
                self.le_player[team_idx][player_idx].setCompleter(completer)

    def updateTeamCompleters(self):
        """Refresh the completer for the team line edits."""
        team_list = scctool.settings.config.getMyTeams() + \
            ["TBD"] + self.controller.historyManager.getTeamList()
        for team_idx in range(2):
            completer = QCompleter(team_list, self.le_team[team_idx])
            completer.setCaseSensitivity(Qt.CaseInsensitive)
            completer.setCompletionMode(QCompleter.InlineCompletion)
            completer.setFilterMode(Qt.MatchContains)
            completer.setWrapAround(True)
            completer.activated.connect(
                self.le_team[team_idx].completerFinished)
            self.le_team[team_idx].setCompleter(completer)

    def updateForms(self):
        """Update data in forms."""
        try:
            self.le_league.setText(self.matchData.getLeague())
            self.sl_team.setValue(self.matchData.getMyTeam())
            for i in range(2):
                team = self.matchData.getTeam(i)
                self.le_team[i].setText(team)
                logo = self.controller.logoManager.getTeam(i + 1).getIdent()
                self.controller.historyManager.insertTeam(team, logo)

            for j in range(2):
                for i in range(1, self.matchData.getNoSets()):
                    self.le_player[j][i].setReadOnly(self.matchData.getSolo())

            for i in range(min(self.max_no_sets, self.matchData.getNoSets())):
                for j in range(2):
                    player = self.matchData.getPlayer(j, i)
                    race = self.matchData.getRace(j, i)
                    self.le_player[j][i].setText(player)
                    self.cb_race[j][i].setCurrentIndex(
                        scctool.settings.race2idx(race))
                    self.controller.historyManager.insertPlayer(player, race)

                self.le_map[i].setText(self.matchData.getMap(i))

                self.sl_score[i].setValue(self.matchData.getMapScore(i))

            for i in range(self.matchData.getNoSets(), self.max_no_sets):
                for j in range(2):
                    self.le_player[j][i].hide()
                    self.cb_race[j][i].hide()
                self.le_map[i].hide()
                self.sl_score[i].hide()
                self.label_set[i].hide()

            for i in range(min(self.max_no_sets, self.matchData.getNoSets())):
                for j in range(2):
                    self.le_player[j][i].show()
                    self.cb_race[j][i].show()
                self.le_map[i].show()
                self.sl_score[i].show()
                self.label_set[i].show()

            no_vetoes = self.matchData.getNoVetoes()
            for i in range(self.max_no_vetoes):
                visible = no_vetoes > i
                self.le_veto_maps[i].setVisible(visible)
                self.veto_label[i].setVisible(visible)
                self.sl_veto[i].setVisible(visible)
                if i % 2:
                    self.row_label[int(i / 2)].setVisible(visible)
                if visible:
                    veto = self.matchData.getVeto(i)
                    self.le_veto_maps[i].setText(veto.get('map'))
                    self.sl_veto[i].setValue(veto.get('team'))

            self.updatePlayerCompleters()
            self.updateTeamCompleters()
            self.updateMapButtons()
            self.setName()
            # self.autoSetNextMap()

        except Exception:
            module_logger.exception("message")
            raise

    def updateMapButtons(self):
        """Update the map buttons."""
        mappool = list(self.controller.mapstatsManager.getMapPool())
        for i in range(self.max_no_sets):
            self.label_set[i].setEnabled(self.matchData.getMap(i) in mappool)
        if (self.controller.mapstatsManager.getMapPoolType() == 2 and
                self.controller.matchControl.activeMatchId() == self._ctrlID):
            self.controller.mapstatsManager.sendMapPool()

    def updateLogos(self, force=False):
        """Update team logos in view."""
        logo = self.controller.logoManager.getTeam1(self._ctrlID)
        self.qb_logo1.setIcon(QIcon(logo.provideQPixmap()))

        logo = self.controller.logoManager.getTeam2(self._ctrlID)
        self.qb_logo2.setIcon(QIcon(logo.provideQPixmap()))

        for idx in range(2):
            team = self.matchData.getTeam(idx)
            logo = self.controller.logoManager.getTeam(
                idx + 1, self._ctrlID).getIdent()
            self.controller.historyManager.insertTeam(team, logo)

        if self.controller.matchControl.activeMatchId() == self._ctrlID:
            self.controller.updateLogosWebsocket()

    def allkillUpdate(self):
        """In case of allkill move the winner to the next set."""
        if (self.matchData.allkillUpdate()):
            self.updateForms()

    def setScore(self, idx, score, allkill=True):
        """Handle change of the score."""
        try:
            if (self.sl_score[idx].value() == 0):
                self.parent.statusBar().showMessage(_('Updating Score...'))
                with self.tlock:
                    self.sl_score[idx].setValue(score)
                    self.matchData.setMapScore(idx, score, True)
                    if allkill:
                        self.allkillUpdate()
                    self.autoSetNextMap()
                    if not self.controller.resetWarning():
                        self.parent.statusBar().showMessage('')
                return True
            else:
                return False
        except Exception:
            module_logger.exception("message")

    def showMap(self, player_idx):
        """Show the map in the mapstats browser source."""
        self.controller.mapstatsManager.selectMap(
            self.matchData.getMap(player_idx))
Example #41
0
class Xls2PBDataGui(QMainWindow):
    def __init__(self):
        super(Xls2PBDataGui, self).__init__()

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(20, 30, 20, 30)
        select_range_box_layout = QHBoxLayout()
        select_xls_file_box_layout = QHBoxLayout()
        button_layout = QHBoxLayout()

        self._main_widget = QWidget()

        self._has_xls_file = False

        self.setWindowTitle('Xls To Bin - vito')

        screen = QDesktopWidget().screenGeometry()

        self._select_xls_file_button = MyPushButton('Select!', screen)
        self._convert_button = MyPushButton("Convert!", screen)

        self._xls_file_label = MyLabel('xls file', screen)

        self._xls_file_text = MyLineEdit(screen)

        self._public_rb = QRadioButton(self)
        self._server_rb = QRadioButton(self)
        self._client_rb = QRadioButton(self)
        self._all_rb = QRadioButton(self)
        self._all_rb.setChecked(True)

        self._public_rb.setText('public')
        self._server_rb.setText('server')
        self._client_rb.setText('client')
        self._all_rb.setText('all')

        self._range_button_box = QButtonGroup()
        self._range_button_box.addButton(self._public_rb, 1)
        self._range_button_box.addButton(self._server_rb, 2)
        self._range_button_box.addButton(self._client_rb, 3)
        self._range_button_box.addButton(self._all_rb, 4)

        select_range_box_layout.addStretch(1)
        select_range_box_layout.addWidget(self._public_rb)
        select_range_box_layout.addStretch(1)
        select_range_box_layout.addWidget(self._server_rb)
        select_range_box_layout.addStretch(1)
        select_range_box_layout.addWidget(self._client_rb)
        select_range_box_layout.addStretch(1)
        select_range_box_layout.addWidget(self._all_rb)
        select_range_box_layout.addStretch(1)

        main_layout.addLayout(select_range_box_layout)

        select_xls_file_box_layout.addWidget(self._xls_file_label)
        select_xls_file_box_layout.addWidget(self._xls_file_text)
        select_xls_file_box_layout.addSpacing(screen.width() / 30)

        main_layout.addLayout(select_xls_file_box_layout)

        button_layout.addWidget(self._select_xls_file_button)
        button_layout.addWidget(self._convert_button)

        main_layout.addLayout(button_layout)

        self._main_widget.setLayout(main_layout)

        self.setCentralWidget(self._main_widget)

        self._select_xls_file_button.clicked.connect(self.open_xls_file)
        self._convert_button.clicked.connect(self.convert)

        self.setFixedSize(screen.width() / 3, screen.height() / 3)
        self._main_widget.setFixedSize(screen.width() / 3, screen.height() / 3)
        size = self.geometry()
        self.move((screen.width() - size.width()) / 3,
                  (screen.height() - size.height()) / 3)

        self.show()

    def open_xls_file(self):
        file_name = QFileDialog.getOpenFileName(self, '请选择 excel 文件',
                                                consts.DEFAULT_EXCEL_PATH,
                                                '*.xlsx')
        if file_name[0]:
            self._has_xls_file = True
            self._xls_file_text.setText(file_name[0])

    def convert(self):
        if self._has_xls_file:
            self._convert_xls_2_bin()
        else:
            self.pop_err_box('请选择 excel 文件')

    @staticmethod
    def pop_err_box(err_msg):
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.setWindowTitle('ERROR')
        msg_box.setText(err_msg)
        msg_box.exec_()

    def _convert_xls_2_bin(self):
        file_type = ""
        check_id = self._range_button_box.checkedId()
        if check_id == 1:
            file_type = "public"
        elif check_id == 2:
            file_type = "server"
        elif check_id == 3:
            file_type = "client"
        elif check_id == 4:
            file_type = "all"

        try:
            handler = new_table_handler.NewTableHandler(
                self._xls_file_text.text(), file_type)
        except BaseException as err:
            self.pop_err_box(traceback.format_exc())
            return

        try:
            handler.generate_data_file()
        except BaseException as err:
            self.pop_err_box(traceback.format_exc())
            return

        try:
            handler.dump()
        except BaseException as err:
            self.pop_err_box(traceback.format_exc())
            return

        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Information)
        msg_box.setWindowTitle('OK')
        msg_box.setText('convert finish')
        msg_box.exec_()
Example #42
0
    def generate_gui(self, skill_macro):
        self.profile_amt = 0
        for name, profile in skill_macro['profiles'].items():
            skills = QGroupBox(self)
            skills.setTitle(profile['name'])
            skills_layout = QGridLayout(skills)
            self.layout.addWidget(skills)
            self.profile_boxes.append(skills)

            label = QLabel(skills)
            label.setText('Key')
            skills_layout.addWidget(label, 0, 0)

            label = QLabel(skills)
            label.setText('Delay (in ms)')
            skills_layout.addWidget(label, 1, 0)

            skills.name = profile['name']
            skills.key_buttons = []
            skills.spinboxes = []

            for i, (hotkey, delay) in enumerate(
                    zip(
                        profile['hotkeys'],
                        profile['delays'],
                    )):
                button = QPushButton(skills)
                button.setText(hotkey)
                button.key_code = hotkey
                button.clicked.connect(self.set_key)
                skills_layout.addWidget(button, 0, i + 1)
                if i >= 4:
                    button.setDisabled(True)
                skills.key_buttons.append(button)

                spinbox = QSpinBox(skills)
                spinbox.setMinimum(0)
                spinbox.setMaximum(100000)
                spinbox.setSingleStep(10)
                spinbox.setValue(delay)
                skills_layout.addWidget(spinbox, 1, i + 1)
                skills.spinboxes.append(spinbox)
                if i == 4:
                    spinbox.setDisabled(True)

            radiobutton = QRadioButton(self.radiobuttons)
            radiobutton.setText(profile['name'])
            radiobutton.setChecked(
                profile['name'] == self.settings.skill_macro['active'])
            self.radiobuttons_layout.addWidget(radiobutton)
            self.radiobuttons_x.append(radiobutton)

            button = QPushButton(skills)
            button.setText('Delete')
            button.clicked.connect(
                lambda state, x=name: self.delete_profile(x))
            skills_layout.addWidget(button, 0, 7)

            self.profile_amt += 1

        self.layout.addWidget(self.radiobuttons, 0, 1, self.profile_amt, 1)

        button = QPushButton(self)
        button.setText('Save')
        button.clicked.connect(self.save)
        self.layout.addWidget(button, 999, 0)

        button = QPushButton(self)
        button.setText('Add Profile')
        button.clicked.connect(self.add_profile)
        self.layout.addWidget(button, 999, 1)
Example #43
0
    def __init__(self, prefs, parent=None):
        super(SetupDialog, self).__init__(parent)
        self.prefs = prefs
        current_theme = self.prefs.get('dwarf_ui_theme', 'black')
        utils.set_theme(current_theme)

        self.setMinimumWidth(400)

        box = QVBoxLayout()
        box.setContentsMargins(10, 10, 10, 10)

        theme_container = QVBoxLayout()
        theme_container.setContentsMargins(0, 0, 0, 0)
        theme_label = QLabel('Theme')
        font = QFont('OpenSans', 20, QFont.Bold)
        font.setPixelSize(20)
        theme_label.setFont(font)
        theme_container.addWidget(theme_label)

        theme_box = QHBoxLayout()
        theme_box.setContentsMargins(0, 10, 0, 0)
        dark = QRadioButton('Dark')
        if current_theme == 'dark':
            dark.setChecked(True)
        dark.toggled.connect(lambda x: self.theme_checked(x, 'dark'))
        theme_box.addWidget(dark)
        black = QRadioButton('Black')
        if current_theme == 'black':
            dark.setChecked(True)
        black.toggled.connect(lambda x: self.theme_checked(x, 'black'))
        theme_box.addWidget(black)
        light = QRadioButton('Light')
        if current_theme == 'light':
            light.setChecked(True)
        light.toggled.connect(lambda x: self.theme_checked(x, 'light'))
        theme_box.addWidget(light)
        theme_container.addLayout(theme_box)

        box.addLayout(theme_container)

        if sys.platform == 'linux':
            dwarf_bin_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-2]), 'bin/dwarf')
            if not os.path.exists(dwarf_bin_path):
                self.launcher_box = QVBoxLayout()
                self.launcher_box.setContentsMargins(0, 40, 0, 0)
                launcher_label = QLabel('Launcher')
                font = QFont('OpenSans', 20, QFont.Bold)
                font.setPixelSize(20)
                launcher_label.setFont(font)
                self.launcher_box.addWidget(launcher_label)
                self.launcher_box.addWidget(QLabel('Create dwarf alias and add to $path (dwarf --version)'))

                self.btn_launcher_create = QPushButton('Create launcher')
                self.btn_launcher_create.clicked.connect(self.create_launcher)
                self.btn_launcher_create.setContentsMargins(0, 15, 0, 0)

                self.launcher_box.addWidget(self.btn_launcher_create)
                box.addLayout(self.launcher_box)

        buttons = QHBoxLayout()
        buttons.setContentsMargins(0, 30, 0, 0)

        finish = QPushButton('Finish')
        finish.clicked.connect(self.accept)
        buttons.addWidget(finish)

        box.addLayout(buttons)

        self.setLayout(box)
Example #44
0
class FrontEndRunner(QWidget):
    """Main FrontEnd Runner window for creating workspace and starting SuRVoS2."""

    def __init__(self, run_config, workspace_config, pipeline_config, *args, **kwargs):
        super().__init__()

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

        self.server_process = None
        self.client_process = None

        pipeline_config_ptree = self.init_ptree(self.pipeline_config, name="Pipeline")

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

        tabwidget.addTab(tab1, "Setup and Start Survos")
        tabwidget.addTab(tab2, "Pipeline")

        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)

        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")
        tab2.layout = QVBoxLayout()
        tab2.setLayout(tab2.layout)
        tab2.layout.addWidget(pipeline_config_ptree)
        tab2.layout.addWidget(output_config_button)

        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_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 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("Run SuRVoS")
        advanced_button = QRadioButton("Advanced")

        run_fields = QGroupBox("Run SuRVoS:")
        run_layout = QGridLayout()
        run_layout.addWidget(QLabel("Workspace Name:"), 0, 0)

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

        self.ws_name_linedt_2 = QLineEdit(self.workspace_config["workspace_name"])
        self.ws_name_linedt_2.setAlignment(Qt.AlignLeft)
        run_layout.addWidget(self.ws_name_linedt_2, 0, 2)
        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_fields.setLayout(run_layout)

        advanced_button.toggled.connect(self.toggle_advanced)
        self.run_button.clicked.connect(self.run_clicked)

        return run_fields

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

    @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()

    def setup_ptree_params(self, p, config_dict):
        def parameter_tree_change(param, changes):
            for param, change, data in changes:
                path = p.childPath(param)

                if path is not None:
                    childName = ".".join(path)
                else:
                    childName = param.name()

                sibs = param.parent().children()

                config_dict[path[-1]] = data

        p.sigTreeStateChanged.connect(parameter_tree_change)

        def valueChanging(param, value):
            pass

        for child in p.children():
            child.sigValueChanging.connect(valueChanging)

            for ch2 in child.children():
                ch2.sigValueChanging.connect(valueChanging)

        return p

    def dict_to_params(self, param_dict, name="Group"):
        ptree_param_dicts = []
        ctr = 0
        for key in param_dict.keys():
            entry = param_dict[key]

            if type(entry) == str:
                d = {"name": key, "type": "str", "value": entry}
            elif type(entry) == int:
                d = {"name": key, "type": "int", "value": entry}
            elif type(entry) == list:
                d = {"name": key, "type": "list", "values": entry}
            elif type(entry) == float:
                d = {"name": key, "type": "float", "value": entry}
            elif type(entry) == bool:
                d = {"name": key, "type": "bool", "value": entry}
            elif type(entry) == dict:
                d = self.dict_to_params(entry, name="Subgroup")[0]
                d["name"] = key + "_" + str(ctr)
                ctr += 1
            else:
                print(f"Can't handle type {type(entry)}")

            ptree_param_dicts.append(d)

        ptree_init = [{"name": name, "type": "group", "children": ptree_param_dicts}]

        return ptree_init

    def init_ptree(self, config_dict, name="Group"):
        ptree_init = self.dict_to_params(config_dict, name)
        parameters = Parameter.create(
            name="ptree_init", type="group", children=ptree_init
        )
        params = self.setup_ptree_params(parameters, config_dict)
        ptree = ParameterTree()
        ptree.setParameters(params, showTop=False)

        return ptree

    @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"
                )

    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.")
        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 run_clicked(self):
        """Starts SuRVoS2 server and client as subprocesses when 'Run' button pressed.

        Raises:
            Exception: If survos.py not found.
        """
        self.ssh_error = (
            False  # Flag which will be set to True if there is an SSH error
        )
        command_dir = os.getcwd()
        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
        # 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"],
                ]
            )
            try:
                outs, errs = self.server_process.communicate(timeout=10)
                print(f"OUTS: {outs, errs}")
            except subprocess.TimeoutExpired:
                pass

            self.start_client()

    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"]),
                ]
            )
Example #45
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version
        capabilities = client.client.features.capabilities
        have_shamir = Capability.Shamir in capabilities

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # Backup type
        gb_backuptype = QGroupBox()
        hbox_backuptype = QHBoxLayout()
        gb_backuptype.setLayout(hbox_backuptype)
        vbox.addWidget(gb_backuptype)
        gb_backuptype.setTitle(_('Select backup type:'))
        bg_backuptype = QButtonGroup()

        rb_single = QRadioButton(gb_backuptype)
        rb_single.setText(_('Single seed (BIP39)'))
        bg_backuptype.addButton(rb_single)
        bg_backuptype.setId(rb_single, BackupType.Bip39)
        hbox_backuptype.addWidget(rb_single)
        rb_single.setChecked(True)

        rb_shamir = QRadioButton(gb_backuptype)
        rb_shamir.setText(_('Shamir'))
        bg_backuptype.addButton(rb_shamir)
        bg_backuptype.setId(rb_shamir, BackupType.Slip39_Basic)
        hbox_backuptype.addWidget(rb_shamir)
        rb_shamir.setEnabled(Capability.Shamir in capabilities)
        rb_shamir.setVisible(False)  # visible with "expert settings"

        rb_shamir_groups = QRadioButton(gb_backuptype)
        rb_shamir_groups.setText(_('Super Shamir'))
        bg_backuptype.addButton(rb_shamir_groups)
        bg_backuptype.setId(rb_shamir_groups, BackupType.Slip39_Advanced)
        hbox_backuptype.addWidget(rb_shamir_groups)
        rb_shamir_groups.setEnabled(Capability.ShamirGroups in capabilities)
        rb_shamir_groups.setVisible(False)  # visible with "expert settings"

        # word count
        word_count_buttons = {}

        gb_numwords = QGroupBox()
        hbox1 = QHBoxLayout()
        gb_numwords.setLayout(hbox1)
        vbox.addWidget(gb_numwords)
        gb_numwords.setTitle(_("Select seed/share length:"))
        bg_numwords = QButtonGroup()
        for count in (12, 18, 20, 24, 33):
            rb = QRadioButton(gb_numwords)
            word_count_buttons[count] = rb
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, count)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        def configure_word_counts():
            if model == "1":
                checked_wordcount = 24
            else:
                checked_wordcount = 12

            if method == TIM_RECOVER:
                if have_shamir:
                    valid_word_counts = (12, 18, 20, 24, 33)
                else:
                    valid_word_counts = (12, 18, 24)
            elif rb_single.isChecked():
                valid_word_counts = (12, 18, 24)
                gb_numwords.setTitle(_('Select seed length:'))
            else:
                valid_word_counts = (20, 33)
                checked_wordcount = 20
                gb_numwords.setTitle(_('Select share length:'))

            word_count_buttons[checked_wordcount].setChecked(True)
            for c, btn in word_count_buttons.items():
                btn.setVisible(c in valid_word_counts)

        bg_backuptype.buttonClicked.connect(configure_word_counts)
        configure_word_counts()

        # set up conditional visibility:
        # 1. backup_type is only visible when creating new seed
        gb_backuptype.setVisible(method == TIM_NEW)
        # 2. word_count is not visible when recovering on TT
        if method == TIM_RECOVER and model != "1":
            gb_numwords.setVisible(False)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))

        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)
            rb_shamir.setVisible(True)
            rb_shamir_groups.setVisible(True)

        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and model == '1':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RecoveryDeviceType.ScrambledWords)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RecoveryDeviceType.Matrix)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=bg_numwords.checkedId(),
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            backup_type=bg_backuptype.checkedId(),
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
Example #46
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)
        rstb = QPushButton("&Invert", self)
        rstb.clicked.connect(self.invert)
        grid.addWidget(rstb, 2, 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("&Tunneler")
        grid.addWidget(self.radDig, 3, RADIO_COL)
        self.radBoom = QRadioButton("&Boomerang")
        grid.addWidget(self.radBoom, 4, 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.setSingleStep(1)
        self.anglebox.setWrapping(True)
        angleLabel = QLabel("<i>θ</i>(0-359):")
        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, 4, BUTTON_COL)
        self.vbox.setAlignment(Qt.AlignRight)
        self.vbox.setReadOnly(True)

        self.show()

    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])

    def invert(self):
        # self.radNorm.setChecked(True)
        self.windbox.setValue(-self.windbox.value())

    def solve_tank(self):
        # Sanity check.
        shotstring = ""

        # Earth:
        gc = 9.529745042492918
        wf = 0.08173443651742651  # wind
        # hover:
        hc = 3.660218073939021 * int(self.radHover.isChecked())
        # hc = 7.313616408030493*int(self.radHover.isChecked())     # <<= heavy hover
        if (hc != 0):
            shotstring = "(HOVER)"
        # boomer:
        bc = 0.07690605021520115 * int(self.radBoom.isChecked())
        if (bc != 0):
            shotstring = "(BOOMERANG)"

        v_0 = None

        dx = self.wbox.value()
        dy = self.hbox.value()
        theta = self.anglebox.value()
        if self.radDig.isChecked():
            theta = -theta + 360
            dy = -dy
            shotstring = "(TUNNELER)"
        theta = rad(theta)
        w = self.windbox.value()

        # Solve these equations:
        # x=v_0*cos(theta)*t
        # Other x terms:
        #   Hover:     hc*v_0*cos(theta)
        #   Wind:      .5*wf*w*(t**2)
        #   Boomer:    -.5*bc*v_0*cos(theta)*(t**2)

        # y=v_0*sin(theta)*t-1/2*gc*(t**2)
        if v_0 is None:
            diff = 20
            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 + hc * n * cos(
                    theta) - .5 * bc * n * cos(theta) * t**2
                # print(fabs(x-dx))
                if fabs(x - dx) < fabs(diff):
                    # Debug:
                    # 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 + " " + shotstring
                ])

        else:
            print("Error. Broken.")
            self.vbox.setText(str(-1.0))
Example #47
0
    def request_safe_t_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{:d} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")

                def set_enabled():
                    from electrum_ltc.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))

                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())
Example #48
0
    def request_trezor_init_settings(self, wizard, method, model):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        gb = QGroupBox()
        hbox1 = QHBoxLayout()
        gb.setLayout(hbox1)
        vbox.addWidget(gb)
        gb.setTitle(_("Select your seed length:"))
        bg_numwords = QButtonGroup()
        for i, count in enumerate([12, 18, 24]):
            rb = QRadioButton(gb)
            rb.setText(_("%d words") % count)
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, i)
            hbox1.addWidget(rb)
            rb.setChecked(True)
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)

        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        if method == TIM_RECOVER and not model == 'T':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
            hbox_rectype.addWidget(rb2)
        else:
            bg_rectype = None

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        item = bg_numwords.checkedId()
        pin = cb_pin.isChecked()
        recovery_type = bg_rectype.checkedId() if bg_rectype else None

        return (item, name.text(), pin, cb_phrase.isChecked(), recovery_type)
Example #49
0
class MYWidget(QWidget):
    def __init__(self, Win):
        super(MYWidget, self).__init__()
        self.Win = Win
        self.setFocusPolicy(Qt.ClickFocus)
        self.box = QVBoxLayout()

        #scaling factor
        self.scalingFactor_groupbox = QGroupBox("Scaling Factor")
        self.scalingFactor_groupbox.setEnabled(False)
        self.xScalingFactor = QDoubleSpinBox()
        self.xScalingFactor.setStyle(QStyleFactory.create('Fusion'))
        self.xScalingFactor.setDecimals(3)
        self.xScalingFactor.setRange(0.001, 1000)
        self.xScalingFactor.setValue(1)
        self.xScalingFactor.setKeyboardTracking(False)
        self.xScalingFactor.valueChanged.connect(self.changeScalingFactor)
        self.yScalingFactor = QDoubleSpinBox()
        self.yScalingFactor.setStyle(QStyleFactory.create('Fusion'))
        self.yScalingFactor.setDecimals(3)
        self.yScalingFactor.setRange(0.001, 1000)
        self.yScalingFactor.setValue(1)
        self.yScalingFactor.setKeyboardTracking(False)
        self.yScalingFactor.valueChanged.connect(self.changeScalingFactor)
        self.zScalingFactor = QDoubleSpinBox()
        self.zScalingFactor.setStyle(QStyleFactory.create('Fusion'))
        self.zScalingFactor.setDecimals(3)
        self.zScalingFactor.setRange(0.001, 1000)
        self.zScalingFactor.setValue(1)
        self.zScalingFactor.setKeyboardTracking(False)
        self.zScalingFactor.valueChanged.connect(self.changeScalingFactor)
        self.equalXYscaling = QCheckBox("Equal Proportion")
        self.equalXYscaling.stateChanged.connect(self.equalProportion)
        hbox_SF = QHBoxLayout()
        hbox_SF.addStretch(2)
        hbox_SF.addWidget(QLabel("X:"))
        hbox_SF.addWidget(self.xScalingFactor)
        hbox_SF.addWidget(QLabel("Y:"))
        hbox_SF.addWidget(self.yScalingFactor)
        hbox_SF.addWidget(self.equalXYscaling)
        hbox_SF.addStretch(1)
        hbox_SF.addWidget(QLabel("Z:"))
        hbox_SF.addWidget(self.zScalingFactor)
        hbox_SF.addStretch(2)
        self.scalingFactor_groupbox.setLayout(hbox_SF)
        self.box.addWidget(self.scalingFactor_groupbox)

        #3D data parameters
        hbox_3d_title = QHBoxLayout()
        self.volume_check = QRadioButton("Volume")
        self.volume_check.setStyle(QStyleFactory.create('Fusion'))
        self.volume_check.setChecked(True)
        self.volume_check.setEnabled(False)
        self.volume_check.toggled.connect(self.change3Dmode)
        self.isosurf_check = QRadioButton("Iso-Surface")
        self.isosurf_check.setStyle(QStyleFactory.create('Fusion'))
        self.isosurf_check.setEnabled(False)
        hbox_3d_title.addStretch(1)
        hbox_3d_title.addWidget(self.volume_check)
        hbox_3d_title.addStretch(2)
        hbox_3d_title.addWidget(self.isosurf_check)
        hbox_3d_title.addStretch(1)
        self.box.addLayout(hbox_3d_title)
        hbox_3d_widget = QHBoxLayout()
        self.volume_groupbox = QGroupBox()
        hbox_3d_volume = QHBoxLayout()
        self.lowpoint = QDoubleSpinBox()
        self.lowpoint.setStyle(QStyleFactory.create('Fusion'))
        self.lowpoint.setDecimals(3)
        self.lowpoint.setRange(0, 1)
        self.lowpoint.setValue(0)
        self.lowpoint.setKeyboardTracking(False)
        self.lowpoint.valueChanged.connect(self.changeVolumeCmp)
        self.highpoint = QDoubleSpinBox()
        self.highpoint.setStyle(QStyleFactory.create('Fusion'))
        self.highpoint.setDecimals(3)
        self.highpoint.setRange(0, 1)
        self.highpoint.setValue(1)
        self.highpoint.setKeyboardTracking(False)
        self.highpoint.valueChanged.connect(self.changeVolumeCmp)
        hbox_3d_volume.addWidget(QLabel("Vmin:"))
        hbox_3d_volume.addWidget(self.lowpoint)
        hbox_3d_volume.addWidget(QLabel("Vmax:"))
        hbox_3d_volume.addWidget(self.highpoint)
        self.volume_groupbox.setLayout(hbox_3d_volume)
        self.volume_groupbox.setEnabled(False)
        self.iso_groupbox = QGroupBox()
        hbox_3d_iso = QHBoxLayout()
        self.isovalue = QDoubleSpinBox()
        self.isovalue.setStyle(QStyleFactory.create('Fusion'))
        self.isovalue.setDecimals(4)
        self.isovalue.setRange(0, 1)
        self.isovalue.setKeyboardTracking(False)
        self.isovalue.valueChanged.connect(self.changeIsoValue)
        self.isoLabel = QLabel("Iso-Value:")
        self.isoLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        hbox_3d_iso.addStretch(1)
        hbox_3d_iso.addWidget(self.isoLabel)
        hbox_3d_iso.addWidget(self.isovalue)
        hbox_3d_iso.addStretch(1)
        self.iso_groupbox.setLayout(hbox_3d_iso)
        self.iso_groupbox.setEnabled(False)
        hbox_3d_widget.addWidget(self.volume_groupbox)
        hbox_3d_widget.addWidget(self.iso_groupbox)
        self.box.addLayout(hbox_3d_widget)

        #visualization ui
        self.visualization = Visualization()
        self.ui = self.visualization.edit_traits(parent=self,
                                                 kind='subpanel').control
        self.box.addWidget(self.ui)

        self.setLayout(self.box)
        self.setFixedWidth(500)

    def setData(self, Data):
        self.data = Data
        self.visualization.scene.mlab.clf()
        xSF = self.xScalingFactor.value()
        ySF = self.yScalingFactor.value()
        zSF = self.zScalingFactor.value()
        if Data is not None:
            self.scalingFactor_groupbox.setEnabled(True)
            if Data.dims == 2:
                self.Enable3DWidget(False)
                self.source = self.visualization.scene.mlab.pipeline.array2d_source(
                    Data.data)
                self.warp = self.visualization.scene.mlab.pipeline.warp_scalar(
                    self.source)
                self.normals = self.visualization.scene.mlab.pipeline.poly_data_normals(
                    self.warp)
                self.surface = self.visualization.scene.mlab.pipeline.surface(
                    self.normals, extent=(0, xSF, 0, ySF, 0, zSF))
                self.outline = self.visualization.scene.mlab.pipeline.outline(
                    self.normals,
                    color=(0, 0, 0),
                    extent=(0, xSF, 0, ySF, 0, zSF))
                self.outline.actor.property.line_width = 1.5
            elif Data.dims == 3:
                self.Enable3DWidget(True)
                minv = Data.data[~np.isnan(Data.data)].min()
                maxv = Data.data[~np.isnan(Data.data)].max()
                self.source = self.visualization.scene.mlab.pipeline.scalar_field(
                    Data.data)
                if self.volume_check.isChecked():
                    self.volume = self.visualization.scene.mlab.pipeline.volume(
                        self.source, vmin=minv, vmax=maxv)
                    self.outline = self.visualization.scene.mlab.pipeline.outline(
                        self.volume, color=(0, 0, 0))
                    self.outline.actor.property.line_width = 1.5
                    self.source.spacing = np.array([xSF, ySF, zSF])
                    self.lowpoint.valueChanged.disconnect()
                    self.highpoint.valueChanged.disconnect()
                    self.lowpoint.setRange(minv, maxv)
                    self.lowpoint.setValue(minv)
                    self.highpoint.setRange(minv, maxv)
                    self.highpoint.setValue(maxv)
                    self.lowpoint.valueChanged.connect(self.changeVolumeCmp)
                    self.highpoint.valueChanged.connect(self.changeVolumeCmp)
                if self.isosurf_check.isChecked():
                    self.isosurface = self.visualization.scene.mlab.pipeline.iso_surface(
                        self.source, contours=[
                            (minv + maxv) / 2,
                        ])
                    self.outline = self.visualization.scene.mlab.pipeline.outline(
                        self.isosurface, color=(0, 0, 0))
                    self.outline.actor.property.line_width = 1.5
                    self.isovalue.valueChanged.disconnect()
                    self.isovalue.setRange(minv, maxv)
                    self.isovalue.setValue((minv + maxv) / 2)
                    self.isovalue.valueChanged.connect(self.changeIsoValue)
                if self.equalXYscaling.isChecked():
                    self.equalProportion(2)
        else:
            self.scalingFactor_groupbox.setEnabled(False)

    def changeScalingFactor(self, value):
        if self.sender() == self.xScalingFactor:
            xSF = value
            ySF = self.yScalingFactor.value()
            zSF = self.zScalingFactor.value()
            if self.data.dims == 2 or 3:
                spacing = self.source.spacing
                spacing[0] = xSF
                self.source.spacing = np.array(spacing)
        elif self.sender() == self.yScalingFactor:
            xSF = self.xScalingFactor.value()
            ySF = value
            zSF = self.zScalingFactor.value()
            if self.data.dims == 2 or 3:
                spacing = self.source.spacing
                spacing[1] = ySF
                self.source.spacing = np.array(spacing)
        elif self.sender() == self.zScalingFactor:
            xSF = self.xScalingFactor.value()
            ySF = self.yScalingFactor.value()
            zSF = value
            if self.data.dims == 2:
                normal = self.warp.filter.normal
                normal[2] = zSF
                self.warp.filter.normal = np.array(normal)
            if self.data.dims == 3:
                spacing = self.source.spacing
                spacing[2] = zSF
                self.source.spacing = np.array(spacing)

    def equalProportion(self, state):
        if state == 2:
            xSF = self.xScalingFactor.value()
            ySF = xSF * self.data.ystep / self.data.xstep
            self.yScalingFactor.setValue(ySF)
            self.xScalingFactor.setEnabled(False)
            self.yScalingFactor.setEnabled(False)
        elif state == 0:
            self.xScalingFactor.setEnabled(True)
            self.yScalingFactor.setEnabled(True)

    def change3Dmode(self, state):
        if state:
            self.volume_groupbox.setEnabled(True)
            self.iso_groupbox.setEnabled(False)
        else:
            self.volume_groupbox.setEnabled(False)
            self.iso_groupbox.setEnabled(True)
        self.setData(self.data)

    def changeVolumeCmp(self, value):
        self.source.children[0].children[:] = []
        if self.sender() == self.lowpoint:
            self.volume = self.visualization.scene.mlab.pipeline.volume(
                self.source, vmin=value)
        if self.sender() == self.highpoint:
            self.volume = self.visualization.scene.mlab.pipeline.volume(
                self.source, vmax=value)
        self.outline = self.visualization.scene.mlab.pipeline.outline(
            self.volume, color=(0, 0, 0))
        self.outline.actor.property.line_width = 1.5

    def changeIsoValue(self, value):
        self.source.children[0].children[:] = []
        self.isosurface = self.visualization.scene.mlab.pipeline.iso_surface(
            self.source, contours=[
                value,
            ])
        self.outline = self.visualization.scene.mlab.pipeline.outline(
            self.isosurface, color=(0, 0, 0))
        self.outline.actor.property.line_width = 1.5

    def Enable3DWidget(self, state):
        self.volume_check.setEnabled(state)
        self.isosurf_check.setEnabled(state)
        if state:
            if self.volume_check.isChecked():
                self.volume_groupbox.setEnabled(True)
            else:
                self.iso_groupbox.setEnabled(True)
        else:
            self.volume_groupbox.setEnabled(False)
            self.iso_groupbox.setEnabled(False)
class DateSorter(QWidget):
    progress_signal = pyqtSignal(tuple)
    files = []

    def __init__(self):
        super().__init__()

        self.choose_dest_dir = QPushButton('Choose...')
        self.start = QPushButton('Start')
        self.days = QRadioButton('Years, Months, and Days')
        self.months = QRadioButton('Years and Months')
        self.years = QRadioButton('Years')
        self.sorted_text = QLineEdit()
        self.choose_dir = QPushButton('Choose...')
        self.read_text = QLineEdit()

        # Thread stuff
        self.progress_signal.connect(self.update_progress)
        self.thread_pool = QThreadPool()
        self.thread_worker = Worker(self.sort_photos)
        self.thread_worker.setAutoDelete(False)
        self.thread_worker.signals.progress.connect(self.progress_signal)
        self.thread_worker.signals.finished.connect(
            self.update_after_completion)

        layout = QVBoxLayout()
        options = QGroupBox('Options')
        options.setLayout(self.setup_options())
        progress = QGroupBox('Progress')
        progress_layout = QVBoxLayout()
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)
        self.progress_bar.setFormat('Waiting (%p%)')
        progress_layout.addWidget(self.progress_bar)
        progress.setLayout(progress_layout)
        layout.addWidget(options)
        layout.addWidget(progress)
        self.setLayout(layout)

    def setup_options(self):
        options = QVBoxLayout()
        read_dir_label = QLabel('Read Directory')
        options.addWidget(read_dir_label)

        read_box = QHBoxLayout()
        self.read_text.textEdited.connect(self.can_start_sort)
        read_box.addWidget(self.read_text)
        self.choose_dir.clicked.connect(self.open_chooser)
        read_box.addWidget(self.choose_dir)
        options.addLayout(read_box)

        dest_dir_label = QLabel('Destination Directory')
        options.addWidget(dest_dir_label)

        dest_box = QHBoxLayout()
        self.sorted_text.textEdited.connect(self.can_start_sort)
        dest_box.addWidget(self.sorted_text)
        self.choose_dest_dir.clicked.connect(self.open_dest_chooser)
        dest_box.addWidget(self.choose_dest_dir)

        options.addLayout(dest_box)

        radios = QVBoxLayout()
        sort_type_label = QLabel('Sort Type')
        radios.addWidget(sort_type_label)
        self.years.setChecked(True)
        radios.addWidget(self.years)
        radios.addWidget(self.months)
        radios.addWidget(self.days)
        options.addLayout(radios)

        options.addStretch()

        warning = QLabel(
            'WARNING: There is no check for file permissions.\n'
            'If you do not have permissions to access the selected directories the program will crash.'
        )
        warning.setStyleSheet('color:#FF0000')
        warning.setAlignment(Qt.AlignCenter)

        self.start.setEnabled(False)
        self.start.clicked.connect(self.start_sorter)
        options.addWidget(warning)
        options.addWidget(self.start)

        return options

    def can_start_sort(self):
        if os.path.isdir(self.read_text.text()) and os.path.isdir(
                self.sorted_text.text()):
            self.start.setEnabled(True)
            self.progress_bar.setFormat('Ready (%p%)')
        else:
            self.start.setEnabled(False)
            self.progress_bar.setFormat('Waiting (%p%)')

    def open_chooser(self):
        dialog = QFileDialog.getExistingDirectory(self, 'Open Directory',
                                                  '/home')
        if dialog:
            self.read_text.setText(dialog)
            self.can_start_sort()

    def open_dest_chooser(self):
        dialog = QFileDialog.getExistingDirectory(self, 'Open Directory',
                                                  '/home')
        if dialog:
            self.sorted_text.setText(dialog)
            self.can_start_sort()

    def update_progress(self, val):
        self.progress_bar.setValue(val[0])

    def start_sorter(self):
        self.read_text.setEnabled(False)
        self.sorted_text.setEnabled(False)
        self.start.setEnabled(False)
        self.choose_dir.setEnabled(False)
        self.choose_dest_dir.setEnabled(False)
        self.years.setEnabled(False)
        self.months.setEnabled(False)
        self.files.clear()
        self.find_photos()
        self.thread_pool.start(self.thread_worker)
        QMessageBox.information(self, 'Date Sorter',
                                'Sort completed successfully.')

    def sort_photos(self, update):
        for f in range(0, len(self.files)):
            file = self.files[f]
            with Image.open(file) as img:
                if file.lower().endswith('.jpeg'):
                    exif = {
                        ExifTags.TAGS[k]: v
                        for k, v in img.getexif().items() if k in ExifTags.TAGS
                    }
                elif file.lower().endswith('.png'):
                    exif = img.text
                else:
                    exif = img._getexif()
            if exif is not None and 36867 in exif and not exif[36867][0] == '{':
                date = datetime.strptime(exif[36867], '%Y:%m:%d %H:%M:%S')
                self.find_dir(file, date)
            else:
                self.find_dir(file, None)
            update.emit((f, ))

    def find_dir(self, file, date):
        if date is None:
            check_exists(self.read_text.text() + '/Not_Sortable/', file)
        else:
            check_exists(
                os.path.join(
                    self.read_text.text(), str(date.year),
                    (convert_to_month(date.month) if self.months.isChecked()
                     or self.days.isChecked() else ''),
                    (str(date.day) if self.days.isChecked() else '')), file)

    def update_after_completion(self):
        self.progress_bar.setValue(0)
        self.progress_bar.setFormat('Waiting (%p%)')
        self.read_text.setEnabled(True)
        self.sorted_text.setEnabled(True)
        self.start.setEnabled(True)
        self.choose_dir.setEnabled(True)
        self.choose_dest_dir.setEnabled(True)
        self.years.setEnabled(True)
        self.months.setEnabled(True)
        self.files.clear()

    def find_photos(self):
        self.progress_bar.setFormat('Sorting (%p%)')
        for filename in Path(self.read_text.text()).rglob('**/*.*'):
            if filename.as_posix().lower().endswith(('.png', '.jpg', '.jpeg')):
                self.files.append(filename.as_posix())
        self.progress_bar.setMaximum(len(self.files))
class Window(QDialog):
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def initUI(self):
        self.setWindowTitle("Differential equation grapher")
        self.q = QDesktopWidget().availableGeometry()
        self.setGeometry(self.q.width() / 6,
                         self.q.height() / 6,
                         self.q.width() / 2,
                         self.q.height() / 2)
        self.show()

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.center()
        self.initUI()
        self.figure = plt.figure()

        ax1 = self.figure.add_subplot(311)
        ax1.grid(True)
        ax1.set_title("Numerical methods", fontweight="bold", size=13)

        ax2 = self.figure.add_subplot(312)
        ax2.grid(True)
        ax2.set_title("Exact solution", fontweight="bold", size=13)

        ax3 = self.figure.add_subplot(313)
        ax3.grid(True)
        ax3.set_title("Local errors", fontweight="bold", size=13)

        self.figure.tight_layout()
        grid = QGridLayout()
        self.setLayout(grid)
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        self.sld = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        # self.x_sld = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        # self.y_sld = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        self.sld.setStyleSheet("""
                     QSlider{
                        background: #E3DEE2;
                        min-width:450px;
                        max-width:450px;
                     }
                     QSlider::groove:horizontal {  
                        height: 10px;
                        margin: 0px;
                        border-radius: 5px;
                        background: #B0AEB1;
                     }
                     QSlider::handle:horizontal {
                        background: #fff;
                        border: 1px solid #E3DEE2;
                        width: 17px;
                        margin: -5px 0px; 
                        border-radius: 8px;
                     }
                     QSlider::sub-page:qlineargradient {
                        background: #3B99FC;
                        border-radius: 5px;
                     }
                     """)

        self.sld.setMinimum(2)
        self.sld.setMaximum(100)

        # optimal approximation
        self.NUMBERS = 25
        self.sld.setValue(self.NUMBERS)

        self.X_STEP = 1
        self.Y_STEP = 1

        # self.x_sld.valueChanged.connect(self.x_change, self.x_sld.value())
        # self.y_sld.valueChanged.connect(self.y_change, self.y_sld.value())
        self.sld.valueChanged.connect(self.value_change, self.sld.value())

        self.function_label = QLabel("Function: ")
        self.function_le = QTextEdit()
        self.function_le.setFixedSize(self.q.width() / 8.5,
                                      self.q.height() / 41.2)
        self.function_le.setText("y'=sin(x)+y")

        self.label = QLabel("Number of points: " + str(self.sld.value()))
        # self.x_label = QLabel("Grid x step: " + str(self.x_sld.value() / 100))
        # self.y_label = QLabel("Grid y step: " + str(self.y_sld.value() / 100))
        self.x0_label = QLabel("x0: ")
        self.y0_label = QLabel("y0:")
        self.X_label = QLabel("X: ")
        self.N0_label = QLabel("Initial number of points (N0): ")
        self.NF_label = QLabel("Final number of points (NF): ")

        grid.setSpacing(25)
        self.x0_le = QTextEdit()
        self.x0_le.setFixedSize(self.q.width() / 8.5, self.q.height() / 41.2)
        self.x0_le.setText(str(0))

        self.y0_le = QTextEdit()
        self.y0_le.setFixedSize(self.q.width() / 8.5, self.q.height() / 41.2)
        self.y0_le.setText(str(1))

        self.X_le = QTextEdit()
        self.X_le.setFixedSize(self.q.width() / 8.5, self.q.height() / 41.2)
        self.X_le.setText(str(12 / 5))

        self.N0_le = QTextEdit()
        self.N0_le.setFixedSize(self.q.width() / 8.5, self.q.height() / 41.2)
        self.N0_le.setText(str(2))

        self.NF_le = QTextEdit()
        self.NF_le.setFixedSize(self.q.width() / 8.5, self.q.height() / 41.2)
        self.NF_le.setText(str(10))

        self.radio1 = QRadioButton("&Yes")
        self.radio2 = QRadioButton("&No")
        self.radio1.setChecked(True)

        self.radio1.toggled.connect(
            lambda: self.show_total_approximation_error(self.radio1))
        self.radio2.toggled.connect(
            lambda: self.show_total_approximation_error(self.radio2))

        self.hbox = QHBoxLayout()
        self.hbox.addWidget(self.radio1)
        self.hbox.addWidget(self.radio2)
        self.box = QGroupBox("&Show total approximation errors?")
        self.box.setLayout(self.hbox)

        self.mradio1 = QRadioButton("&Yes")
        self.mradio2 = QRadioButton("&No")
        self.mradio1.setChecked(True)

        self.mbox = QHBoxLayout()
        self.mbox.addWidget(self.mradio1)
        self.mbox.addWidget(self.mradio2)

        self.mGroupBox = QGroupBox("&Mark dots?")
        self.mGroupBox.setLayout(self.mbox)

        grid.addWidget(self.toolbar, 0, 0, 1, 25)
        grid.addWidget(self.canvas, 1, 0, 25, 25)
        grid.addWidget(self.function_label, 1, 25)
        grid.addWidget(self.function_le, 2, 25)
        grid.addWidget(self.label, 3, 25)
        grid.addWidget(self.sld, 4, 25)
        # grid.addWidget(self.x_label, 10, 25)
        # grid.addWidget(self.x_sld, 11, 25)
        # grid.addWidget(self.y_label, 12, 25)
        # grid.addWidget(self.y_sld, 13, 25)
        grid.addWidget(self.x0_label, 5, 25)
        grid.addWidget(self.x0_le, 6, 25)
        grid.addWidget(self.y0_label, 7, 25)
        grid.addWidget(self.y0_le, 8, 25)
        grid.addWidget(self.X_label, 9, 25)
        grid.addWidget(self.X_le, 10, 25)
        grid.addWidget(self.box, 11, 25)
        grid.addWidget(self.N0_label, 12, 25)
        grid.addWidget(self.N0_le, 13, 25)
        grid.addWidget(self.NF_label, 14, 25)
        grid.addWidget(self.NF_le, 15, 25)
        grid.addWidget(self.mGroupBox, 16, 25)
        grid.addWidget(self.button, 25, 25)

    def show_total_approximation_error(self, button):
        if button.text() == "&No" and button.isChecked():

            self.N0_label.hide()
            self.N0_le.hide()
            self.NF_label.hide()
            self.NF_le.hide()
            self.mGroupBox.hide()
        elif button.text() == "&Yes" and button.isChecked():
            self.N0_label.show()
            self.N0_le.show()
            self.NF_label.show()
            self.NF_le.show()
            self.mGroupBox.show()

    def x_change(self, value):
        self.x_sld.setValue(value)
        self.x_label.setText("Grid x step: " + str(self.x_sld.value() / 100))
        self.X_STEP = self.x_sld.value() / 100

    def y_change(self, value):
        self.y_sld.setValue(value)
        self.y_label.setText("Grid y step: " + str(self.y_sld.value() / 100))
        self.Y_STEP = self.y_sld.value() / 100

    def value_change(self, value):
        self.sld.setValue(value)
        self.label.setText("Number of points: " + str(self.sld.value()))
        self.NUMBERS = self.sld.value()

    def without_approximation(self):
        self.figure.clear()
        num_methods = numericals.Numerical_methods(self.x0, self.y0, self.X,
                                                   self.NUMBERS)
        graphic = graph.Graph(self.x0, self.y0, self.X, self.NUMBERS)
        if self.radio2.isChecked():
            self.ax1 = self.figure.add_subplot(311)
            self.ax2 = self.figure.add_subplot(312)
            self.ax3 = self.figure.add_subplot(313)
        else:
            self.ax1 = self.figure.add_subplot(411)
            self.ax2 = self.figure.add_subplot(412)
            self.ax3 = self.figure.add_subplot(413)
            self.ax4 = self.figure.add_subplot(414)
        self.ax1.set_title("Numerical methods", fontweight="bold", size=13)
        self.ax2.set_title("Exact solution", fontweight="bold", size=13)
        self.ax3.set_title("Local errors", fontweight="bold", size=13)

        self.ax1.grid(True)
        self.ax2.grid(True)
        self.ax3.grid(True)

        # x_locator = mplt.ticker.MultipleLocator(base=self.X_STEP)
        # y_locator = mplt.ticker.MultipleLocator(base=self.Y_STEP)

        x, y_graph = graphic.solve()

        self.ax2.plot(x, y_graph, "purple", label="y'=sin(x)+y")
        self.ax2.legend(loc='upper left')
        # self.ax2.xaxis.set_major_locator(x_locator)
        # self.ax2.yaxis.set_major_locator(y_locator)

        x, y_euler = num_methods.euler()
        self.ax1.plot(x, y_euler, "red", label="Euler")
        self.ax1.legend(loc='upper left')

        x, y_improved_euler = num_methods.improved_euler()
        self.ax1.plot(x, y_improved_euler, "blue", label="Improved Euler")
        self.ax1.legend(loc='upper left')

        x, y_runge_kutta = num_methods.runge_kutta()
        self.ax1.plot(x, y_runge_kutta, "green", label="Runge Kutta")
        self.ax1.legend(loc='upper left')

        # self.ax1.xaxis.set_major_locator(x_locator)
        # self.ax1.yaxis.set_major_locator(y_locator)
        local_errors = errors.Errors(self.NUMBERS)

        y_local_euler = local_errors.local_error(y_graph, y_euler)
        self.ax3.plot(x, y_local_euler, "red", label="local euler error")
        self.ax3.legend(loc="upper left")

        y_local_improved = local_errors.local_error(y_graph, y_improved_euler)
        self.ax3.plot(x,
                      y_local_improved,
                      "blue",
                      label="local improved euler error")
        self.ax3.legend(loc="upper left")

        y_local_runge_kutta = local_errors.local_error(y_graph, y_runge_kutta)
        self.ax3.plot(x,
                      y_local_runge_kutta,
                      "green",
                      label="local runge-kutta error")
        self.ax3.legend(loc="upper left")
        """needed the second one because common locator for
        3 graphs takes minimum y grid (what is too small
        because of graph of approximation)
        """
        # y_error_locator = mplt.ticker.MultipleLocator(base=self.Y_STEP)
        # self.ax3.xaxis.set_major_locator(x_locator)
        # self.ax3.yaxis.set_major_locator(y_error_locator)

        hand, label = self.ax3.get_legend_handles_labels()
        handout = []
        lblout = []
        for h, l in zip(hand, label):
            if l not in lblout:
                lblout.append(l)
                handout.append(h)
        self.ax3.legend(handout, lblout, loc='best')

        self.figure.tight_layout()
        self.canvas.draw()

    def with_approximation(self):
        self.figure.clear()
        self.without_approximation()
        self.ax4.set_title("Total approximation errors",
                           fontweight="bold",
                           size=13)
        self.ax4.grid(True)
        # x_locator = mplt.ticker.MultipleLocator(base=1)
        # self.ax4.xaxis.set_major_locator(x_locator)

        euler_max_errors = []
        improved_euler_max_errors = []
        runge_kutta_max_errors = []
        nums = [k for k in range(self.N0, self.NF + 1)]
        for k in range(self.N0, self.NF + 1):
            num_methods = numericals.Numerical_methods(self.x0, self.y0,
                                                       self.X, k)
            x, y_graph = graph.Graph(self.x0, self.y0, self.X, k).solve()
            local_errors = errors.Errors(k)

            x, y_euler = num_methods.euler()
            y_local_euler = local_errors.local_error(y_graph, y_euler)
            euler_max_errors.append(max(y_local_euler))

            x, y_improved_euler = num_methods.improved_euler()
            y_local_improved_euler = local_errors.local_error(
                y_graph, y_improved_euler)
            improved_euler_max_errors.append(max(y_local_improved_euler))

            x, y_runge_kutta = num_methods.runge_kutta()
            y_local_runge_kutta = local_errors.local_error(
                y_graph, y_runge_kutta)
            runge_kutta_max_errors.append(max(y_local_runge_kutta))
        self.ax4.plot(nums,
                      euler_max_errors,
                      "red",
                      label='total approximation euler error')
        self.ax4.plot(nums,
                      improved_euler_max_errors,
                      "blue",
                      label='total approximation improved euler error')
        self.ax4.plot(nums,
                      runge_kutta_max_errors,
                      "green",
                      label='total approximation runge-kutta error')

        if (self.mradio1.isChecked()):
            self.ax4.plot(nums, euler_max_errors, 'ro', markersize=4)
            self.ax4.plot(nums, improved_euler_max_errors, 'bo', markersize=4)
            self.ax4.plot(nums, runge_kutta_max_errors, 'go', markersize=4)
            for i, j in zip(nums, euler_max_errors):
                self.ax4.annotate(str(i) + ";" + str(round(j, 3)),
                                  xy=(i, j),
                                  color='red')
            for i, j in zip(nums, improved_euler_max_errors):
                self.ax4.annotate(str(i) + ";" + str(round(j, 3)),
                                  xy=(i, j),
                                  color='blue')
            for i, j in zip(nums, runge_kutta_max_errors):
                self.ax4.annotate(str(i) + ";" + str(round(j, 3)),
                                  xy=(i, j),
                                  color='green')
        self.ax4.set_ylabel("Error value")
        self.ax4.set_xlabel("Number of points on each step")
        self.ax4.legend(loc='best')
        self.figure.tight_layout()
        self.canvas.draw()

    def plot(self):
        try:
            self.x0 = self.x0_le.toPlainText().replace(",", ".")
            self.y0 = self.y0_le.toPlainText().replace(",", ".")
            self.X = self.X_le.toPlainText().replace(",", ".")
            self.N0 = self.N0_le.toPlainText()
            self.NF = self.NF_le.toPlainText()
            if (graph.is_float(self.x0) and graph.is_float(self.X)
                    and graph.is_float(self.y0) and int(self.N0)
                    and int(self.NF)):
                self.x0 = float(Fraction(self.x0))
                self.y0 = float(Fraction(self.y0))
                self.X = float(Fraction(self.X))
                self.N0 = int(self.N0)
                self.NF = int(self.NF)

                if self.x0 <= self.X and self.radio2.isChecked():
                    self.without_approximation()
                elif self.x0 <= self.X and self.N0 <= self.NF and self.N0 > 1 and self.NF > 1 and self.radio1.isChecked(
                ):
                    self.with_approximation()
                elif self.x0 > self.X:
                    self.msg = MsgBox("x0 is greater than X")
                elif self.N0 > self.NF:
                    self.msg = MsgBox("N0 is greater than Nf")
                elif (self.N0 <= 1
                      or self.NF <= 1) and self.radio1.isChecked():
                    self.msg = MsgBox("N0 and Nf must be > 1")
            elif (graph.is_float(self.x0) == False):
                self.msg = MsgBox("x0 is not double")
            elif (graph.is_float(self.X) == False):
                self.msg = MsgBox("X is not double")
            elif (graph.is_float(self.y0) == False):
                self.msg = MsgBox("y0 is not double")
        except ValueError:
            if (represents_int(self.N0) == False
                    or represents_int(self.NF) == False):
                self.msg = MsgBox("N0 or NF is not an integer")
class HelloWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def btnstate(self, b):
        return

    def initUI(self):

        #menu statusbar
        self.statusBar().showMessage('Ready')
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        editMenu = menubar.addMenu('Edit')

        impMenu = QMenu('Import', self)
        impAct = QAction('Import mail', self)
        impMenu.addAction(impAct)

        newAct = QAction('New', self)

        fileMenu.addAction(newAct)
        fileMenu.addMenu(impMenu)

        #toolbar
        exitAct = QAction(QIcon('exit.png'), 'Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.triggered.connect(qApp.quit)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAct)

        self.setMinimumSize(QSize(180, 180))
        self.setWindowTitle("PyQt")
        self.setWindowIcon(QIcon('exit.png'))

        # Create Main Widget
        mainwidget = QWidget()
        self.setCentralWidget(mainwidget)

        grid = QGridLayout()
        mainwidget.setLayout(grid)
        # Buttons
        b1 = QPushButton('QUIT', self)
        b2 = QPushButton('button with long text', self)
        grid.addWidget(b1, 1, 1)
        grid.addWidget(b2, 2, 1)
        # Enter fields
        t1 = QLabel('text input')
        t2 = QLabel('multiline input')
        t1f = QLineEdit()
        t2f = QTextEdit()
        t2f.resize(50, 250)

        grid.addWidget(t1, 3, 0)
        grid.addWidget(t1f, 3, 1)
        grid.addWidget(t2, 4, 0)
        grid.addWidget(t2f, 4, 1)
        #Listbox
        l1t = QLabel('list')
        l1 = QListWidget(self)
        l1.resize(50, 50)
        for i in range(6):
            l1.addItem('alt%s' % (i + 1))
        grid.addWidget(l1t, 5, 0)
        grid.addWidget(l1, 5, 1)
        #Combo
        c1t = QLabel('combo')
        c1 = QComboBox(self)
        for i in range(6):
            c1.addItem('alt%s' % (i + 1))
        grid.addWidget(c1t, 6, 0)
        grid.addWidget(c1, 6, 1)
        #Radio
        groupBox = QGroupBox('Radio')
        layout = QHBoxLayout()
        self.b1 = QRadioButton("One")
        self.b1.setChecked(True)
        self.b1.toggled.connect(lambda: self.btnstate(self.b1))
        layout.addWidget(self.b1)

        self.b2 = QRadioButton("Two")
        self.b2.toggled.connect(lambda: self.btnstate(self.b2))
        layout.addWidget(self.b2)
        groupBox.setLayout(layout)
        grid.addWidget(groupBox, 7, 1)
        #Checkbox
        cb = QCheckBox('toggle', self)
        grid.addWidget(cb, 8, 0)
        #Slider
        s1t = QLabel('slider')
        s1 = QSlider(Qt.Horizontal)
        grid.addWidget(s1t, 9, 0)
        grid.addWidget(s1, 9, 1)
        #progress
        p1t = QLabel('progress')
        p1 = QProgressBar(self)
        p1.setValue(40)
        grid.addWidget(p1t, 10, 0)
        grid.addWidget(p1, 10, 1)
Example #53
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 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.loadFile)
        self.loadbutton.setDisabled(True)
        self.loadbutton.setToolTip("The load button does not work. Files"
                                   " can be loaded via drag & drop")

        # 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("Data not loaded")
        self.set2.addWidget(self.radioname)
        self.set2.addWidget(self.radioid)
        self.set2.addWidget(self.radioseq)
        self.set2.addWidget(self.decoycheck)
        self.set2.addWidget(self.datalabel)

        # 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.mainwidget.setLayout(self.main_layout)
        self.setCentralWidget(self.mainwidget)
        self.setWindowTitle('Protein Viewer')

        # 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 loadFile(self, filepath):
        """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.path = filepath
        # 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(
            self.path)
        self.datalabel.setText("Data loaded")
        for i in range(len(self.dictKeyAccession)):
            ID = list(self.dictKeyAccession.keys())[i]
            Proteinname = self.proteinNameList[i]
            OS = self.proteinOSList[i]
            self.createParentItem(ID, OS, Proteinname)
        self.tw.itemClicked.connect(self.clickTreeItem)

    # defining a function to creat TreeItems
    def createParentItem(self, ID, OS, Proteinname):
        """Creates a TreeItem with 3 columns (ID, OS, Proteinname).

    Parameters
    ----------
    self : QMainWindow
        the MainWindow of the class
    ID : The specific protein accesion
        which is needed for the link to the database
    OS: The organism from where the protein is from
    Proteinname : The name of the protein


    Returns
    -------
    nothing , it changes the Treewidget
    and creates a TreeItem with three columns
    """
        self.cg = QtWidgets.QTreeWidgetItem(self.tw)
        self.cg.setData(0, 0, ID)
        self.cg.setData(1, 0, OS)
        self.cg.setData(2, 0, Proteinname)

    def createChildTreeItem(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)

    # methode 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 createChildTreeItem 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.createChildTreeItem(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.createChildTreeItem(item, ID, Protein)

    def createChildTreeItemSeqSearch(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 createChildTreeItem 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.createChildTreeItemSeqSearch(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.createChildTreeItemSeqSearch(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.createParentItem(ID, OS, 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.createParentItem(ID, OS, 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.createParentItem(ID, OS, 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)):
                        # sofern wir ganz am Anfang der Liste sind
                        if (cuts[i] == '' and i == 0):
                            self.textp.setTextColor(self.color)
                            self.textp.insertPlainText(protein_sub_sequence)
                            self.textp.setTextColor(self.colorblack)
                        # sofern wir mitten drin sind und der sub_string mehrfach auftaucht
                        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.createParentItem(ID, OS, 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)):
                        # sofern wir ganz am Anfang der Liste sind
                        if (cuts[i] == '' and i == 0):
                            self.textp.setTextColor(self.color)
                            self.textp.insertPlainText(protein_sub_sequence)
                            self.textp.setTextColor(self.colorblack)
                        # sofern wir mitten drin oder am Ende sind sind
                        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.createParentItem(ID, OS, 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.createParentItem(ID, OS, 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 #54
0
class Ui_Main(QtWidgets.QWidget):
    def setupUi(self, Main, host):
        Main.setObjectName("Main")
        self.sHost = host  # host name of server
        # self.sPort = port               # port at which server accepts connections
        self.maxClients = 0  # max number of clients to connect with the server
        self.QtStack = QStackedLayout()

        self.stack0 = QWidget()  # the main screen
        self.stack1 = QWidget()  # server port and clients entry
        self.stack2 = QWidget()  # client enter info
        self.stack3 = QWidget()  # client connected
        self.stack4 = QWidget()  # server proceed btn display
        self.stack5 = QWidget()  # server music select
        self.stack6 = QWidget()  # server player
        self.stack7 = QWidget()  # error window

        # initialize UI windows
        self.startUI()
        self.serverInit()
        self.clientUI()
        self.clientConnectedUI()
        self.errorDisp()

        # add UI windows to Qt Stack
        self.QtStack.addWidget(self.stack0)
        self.QtStack.addWidget(self.stack1)
        self.QtStack.addWidget(self.stack2)
        self.QtStack.addWidget(self.stack3)
        self.QtStack.addWidget(self.stack4)
        self.QtStack.addWidget(self.stack5)
        self.QtStack.addWidget(self.stack6)
        self.QtStack.addWidget(self.stack7)

    def finishUI(self):
        # initialize remaining UI windows
        self.serverUI(self.sHost, self.sPort)
        self.clientsFileVerify()
        self.clientsListUI()
        return

    def startUI(self):
        self.stack0.setFixedSize(500, 200)
        self.stack0.setWindowTitle("Sync")

        # Intro msg
        self.intro = QLabel("What do you want to be?")
        self.intro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Server Button
        self.serverBtn = QRadioButton("Server")
        self.serverBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")
        icon = QIcon('images/server.png')
        self.serverBtn.setIcon(icon)
        self.serverBtn.setIconSize(QSize(75, 75))
        self.serverBtn.setChecked(True)

        # Client Button
        self.clientBtn = QRadioButton("Client")
        self.clientBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")
        icon = QIcon('images/client.png')
        self.clientBtn.setIcon(icon)
        self.clientBtn.setIconSize(QSize(75, 75))

        # Button group to maintain exclusivity
        self.bGroup = QButtonGroup()
        self.bGroup.addButton(self.serverBtn, 1)
        self.bGroup.addButton(self.clientBtn, 2)

        # Next Button
        self.nextBtn = QPushButton("Next")
        self.nextBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # Integrate grid layout
        self.layout = QGridLayout()
        self.layout.addWidget(self.intro, 0, 0, 1, 3)
        self.layout.addWidget(self.serverBtn, 1, 0, Qt.AlignCenter)
        self.layout.addWidget(self.clientBtn, 1, 2, Qt.AlignCenter)
        self.layout.addWidget(self.nextBtn, 3, 1)
        self.stack0.setLayout(self.layout)
        return

    def serverInit(self):
        self.stack1.setFixedSize(500, 200)
        self.stack1.setWindowTitle("Sync")

        # Server intro message
        self.sIIntro = QLabel("Operating as a server")
        self.sIIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # port helper
        self.sIPortKey = QLabel("Port to listen on: ")
        self.sIPortKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignLeft; font-family: Helvetica, Arial"
        )

        # port helper
        self.sIPortVal = QSpinBox()
        self.sIPortVal.setValue(9077)
        self.sIPortVal.setMaximum(65535)
        self.sIPortVal.setMinimum(1024)

        # helper label
        self.sIHelper = QLabel("Number of clients: ")
        self.sIHelper.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignLeft; font-family: Helvetica, Arial"
        )

        # text field for number of clients
        self.sIBox = QSpinBox()
        self.sIBox.setValue(2)
        self.sIBox.setMaximum(16)
        self.sIBox.setMinimum(1)

        # next Btn
        self.sNextBtn = QPushButton("Next")
        self.sNextBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # Integrate grid layout
        self.sILayout = QGridLayout()
        self.sILayout.addWidget(self.sIIntro, 0, 0, 1, 3)
        self.sILayout.addWidget(self.sIPortKey, 1, 0, 1, 2)
        self.sILayout.addWidget(self.sIPortVal, 1, 1, 1, 2)
        self.sILayout.addWidget(self.sIHelper, 2, 0, 1, 2)
        self.sILayout.addWidget(self.sIBox, 2, 1, 1, 2)
        self.sILayout.addWidget(self.sNextBtn, 3, 1)
        self.stack1.setLayout(self.sILayout)
        return

    def clientUI(self):
        self.stack2.setFixedSize(500, 200)
        self.stack2.setWindowTitle("Sync")

        # client intro message
        self.cIntro = QLabel("Operating as a client")
        self.cIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Client host key & val
        self.cHostKey = QLabel("Host: ")
        self.cHostKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.cHostVal = QLineEdit()
        self.cHostVal.setPlaceholderText("Say Dell-G3")

        # Client port key & val
        self.cPortKey = QLabel("Port: ")
        self.cPortKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.cPortVal = QLineEdit()
        self.cPortVal.setPlaceholderText("Say 9077")

        # client connect button
        self.cntBtn = QPushButton("Connect")
        self.cntBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # Integrate grid layout
        self.cLayout = QGridLayout()
        self.cLayout.addWidget(self.cIntro, 0, 0, 1, 3)
        self.cLayout.addWidget(self.cHostKey, 1, 0)
        self.cLayout.addWidget(self.cHostVal, 1, 1, 1, 2)
        self.cLayout.addWidget(self.cPortKey, 2, 0)
        self.cLayout.addWidget(self.cPortVal, 2, 1, 1, 2)
        self.cLayout.addWidget(self.cntBtn, 4, 1)
        self.stack2.setLayout(self.cLayout)
        return

    def serverUI(self, host, port):
        self.stack3.setFixedSize(500, 200)
        self.stack3.setWindowTitle("Sync")

        # Server intro message
        self.sIntro = QLabel("Operating as a server")
        self.sIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Server host key & val
        self.sHostKey = QLabel("Host: ")
        self.sHostKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.sHostVal = QLabel(host)
        self.sHostVal.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # Server port key & val
        self.sPortKey = QLabel("Port: ")
        self.sPortKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.sPortVal = QLabel(str(port))
        self.sPortVal.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # Server msg
        self.sMsg = QLabel("Share this info with your clients!")
        self.sMsg.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # Server proceed button
        self.proBtn = QPushButton("Proceed")
        self.proBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # Integrate grid layout
        self.sLayout = QGridLayout()
        self.sLayout.addWidget(self.sIntro, 0, 0, 1, 3)
        self.sLayout.addWidget(self.sHostKey, 1, 0)
        self.sLayout.addWidget(self.sHostVal, 1, 1)
        self.sLayout.addWidget(self.sPortKey, 2, 0)
        self.sLayout.addWidget(self.sPortVal, 2, 1)
        self.sLayout.addWidget(self.sMsg, 3, 0, 1, 3)
        self.sLayout.addWidget(self.proBtn, 4, 1)
        self.stack3.setLayout(self.sLayout)
        return

    def clientConnectedUI(self):
        self.stack4.setFixedSize(500, 200)
        self.stack4.setWindowTitle("Sync")

        # client intro message
        self.cCIntro = QLabel("Operating as a client")
        self.cCIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Client welcome msg
        self.cConnected = QLabel("Connected!")
        self.cConnected.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # Integrate grid layout
        self.cCLayout = QGridLayout()
        self.cCLayout.addWidget(self.cCIntro, 0, 0, 1, 3)
        self.cCLayout.addWidget(self.cConnected, 1, 0, 1, 3)
        self.stack4.setLayout(self.cCLayout)
        return

    def clientsFileVerify(self):
        self.stack5.setFixedWidth(500)
        self.stack5.setWindowTitle("Sync")

        # Server intro message
        self.cFVIntro = QLabel("Operating as a server")
        self.cFVIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Server host key & val
        self.cFVHostKey = QLabel("Host: ")
        self.cFVHostKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.cFVHostVal = QLabel(self.sHost)
        self.cFVHostVal.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # Server port key & val
        self.cFVPortKey = QLabel("Port: ")
        self.cFVPortKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.cFVPortVal = QLabel(str(self.sPort))
        self.cFVPortVal.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # clients list display
        self.cFVMsg = QLabel("Clients Connected:")
        self.cFVMsg.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # music pick drop down
        self.cFVmusicBox = QComboBox()

        for m in self.musicFiles:
            self.cFVmusicBox.addItem(m)

        # music helper label
        self.cFVmHelper = QLabel("Select Music")
        self.cFVmHelper.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # verify button
        self.vfyBtn = QPushButton("Verify")
        self.vfyBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # List of clients connected
        self.clientLabels = []
        for _ in range(self.maxClients):
            self.clientLabels.append(QLabel(""))

        # integrate into grid layout
        self.cFVLayout = QGridLayout()
        self.cFVLayout.addWidget(self.cFVIntro, 0, 0, 1, 3)
        self.cFVLayout.addWidget(self.cFVHostKey, 1, 0)
        self.cFVLayout.addWidget(self.cFVHostVal, 1, 1)
        self.cFVLayout.addWidget(self.cFVPortKey, 2, 0)
        self.cFVLayout.addWidget(self.cFVPortVal, 2, 1)
        self.cFVLayout.addWidget(self.cFVMsg, 3, 0, 1, 3)
        for i, c in enumerate(self.clientLabels):
            self.cFVLayout.addWidget(c, 3 + (i + 1), 0, 1, 3)
        self.cFVLayout.addWidget(self.cFVmHelper, self.maxClients + 4, 0)
        self.cFVLayout.addWidget(self.cFVmusicBox, self.maxClients + 4, 1, 1,
                                 2)
        self.cFVLayout.addWidget(self.vfyBtn, self.maxClients + 5, 1)

        self.stack5.setLayout(self.cFVLayout)
        return

    def clientsListUI(self):
        self.stack6.setFixedWidth(500)
        self.stack6.setWindowTitle("Sync")

        # Server intro message
        self.cLIntro = QLabel("Operating as a server")
        self.cLIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Server host key & val
        self.cLHostKey = QLabel("Host: ")
        self.cLHostKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.cLHostVal = QLabel(self.sHost)
        self.cLHostVal.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # Server port key & val
        self.cLPortKey = QLabel("Port: ")
        self.cLPortKey.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )
        self.cLPortVal = QLabel(str(self.sPort))
        self.cLPortVal.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # song name label
        self.songName = QLabel("")
        self.songName.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        # file verifier label
        self.vfyMsg = QLabel("File verification complete: ")
        self.vfyMsg.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignHCenter; font-family: Helvetica, Arial"
        )

        self.filePresence = []
        # file verificatin results
        for _ in range(self.maxClients):
            self.filePresence.append(QLabel(""))

        # play button
        self.playBtn = QPushButton("Play")
        self.playBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # pause button
        self.pauseBtn = QPushButton("Pause")
        self.pauseBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # stop button
        self.stopBtn = QPushButton("Stop")
        self.stopBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # end button
        self.endBtn = QPushButton("End")
        self.endBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # back button
        self.backBtn = QPushButton("Go Back")
        self.backBtn.setStyleSheet(
            "font-size: 14px; font-family: Helvetica, Arial")

        # integrate into grid layout
        self.cLLayout = QGridLayout()
        self.cLLayout.addWidget(self.cLIntro, 0, 0, 1, 3)
        self.cLLayout.addWidget(self.cLHostKey, 1, 0)
        self.cLLayout.addWidget(self.cLHostVal, 1, 1)
        self.cLLayout.addWidget(self.cLPortKey, 2, 0)
        self.cLLayout.addWidget(self.cLPortVal, 2, 1)
        self.cLLayout.addWidget(self.songName, 3, 1)
        self.cLLayout.addWidget(self.vfyMsg, 4, 0, 1, 3)
        for i, c in enumerate(self.filePresence):
            self.cLLayout.addWidget(c, 4 + (i + 1), 0, 1, 3)
        self.cLLayout.addWidget(self.playBtn, self.maxClients + 5, 0)
        self.cLLayout.addWidget(self.pauseBtn, self.maxClients + 5, 1)
        self.cLLayout.addWidget(self.stopBtn, self.maxClients + 5, 2)
        self.cLLayout.addWidget(self.backBtn, self.maxClients + 6, 1)
        self.cLLayout.addWidget(self.endBtn, self.maxClients + 7, 0, 1, 3)
        self.stack6.setLayout(self.cLLayout)

        return

    def errorDisp(self):
        self.stack7.setFixedWidth(500)
        self.stack7.setWindowTitle("Sync")

        # Server intro message
        self.eIntro = QLabel("Operating as a server")
        self.eIntro.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        # Server intro message
        self.eMsg = QLabel()
        self.eMsg.setStyleSheet(
            "font-size: 20px; qproperty-alignment: AlignCenter; font-family: Helvetica, Arial"
        )

        self.eLayout = QGridLayout()
        self.eLayout.addWidget(self.eIntro, 0, 0, 1, 3)
        self.eLayout.addWidget(self.eMsg, 1, 0, 1, 3)
        self.stack7.setLayout(self.eLayout)
        return
Example #55
0
class TaskGeneratorDialog(QDialog):
    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()

    def generator_changed(self, value):
        if value == 2:
            self.show_kato_options()
        else:
            self.show_randfixedsum_options()

    def show_randfixedsum_options(self):
        for i in range(self.hbox_utilizations.count()):
            self.hbox_utilizations.itemAt(i).widget().hide()
        for i in range(self.hbox_tasks.count()):
            if self.hbox_tasks.itemAt(i).widget():
                self.hbox_tasks.itemAt(i).widget().show()
        for i in range(self.hbox_sporadic_tasks.count()):
            if self.hbox_sporadic_tasks.itemAt(i).widget():
                self.hbox_sporadic_tasks.itemAt(i).widget().show()

    def show_kato_options(self):
        for i in range(self.hbox_utilizations.count()):
            if self.hbox_utilizations.itemAt(i).widget():
                self.hbox_utilizations.itemAt(i).widget().show()
        for i in range(self.hbox_tasks.count()):
            if self.hbox_tasks.itemAt(i).widget():
                self.hbox_tasks.itemAt(i).widget().hide()
        for i in range(self.hbox_sporadic_tasks.count()):
            if self.hbox_sporadic_tasks.itemAt(i).widget():
                self.hbox_sporadic_tasks.itemAt(i).widget().hide()

    def get_min_utilization(self):
        return self.interval_utilization.getMin()

    def get_max_utilization(self):
        return self.interval_utilization.getMax()

    def generate(self):

        n = self.get_nb_tasks()
        if (n == 0):
            QMessageBox.warning(
                self, "Generation failed",
                "Please check the utilization and the number of tasks.")
            return

        if self.comboGenerator.currentIndex() == 0:
            u = StaffordRandFixedSum(n, self.get_utilization(), 1)
        elif self.comboGenerator.currentIndex() == 1:
            u = UUniFastDiscard(n, self.get_utilization(), 1)
        else:
            u = gen_kato_utilizations(1, self.get_min_utilization(),
                                      self.get_max_utilization(),
                                      self.get_utilization())
            n = len(u[0])

        p_types = self.get_periods()
        if p_types[0] == "unif":
            p = gen_periods_uniform(n, 1, p_types[1], p_types[2], p_types[3])
        elif p_types[0] == "lunif":
            p = gen_periods_loguniform(n, 1, p_types[1], p_types[2],
                                       p_types[3])
        else:
            p = gen_periods_discrete(n, 1, p_types[1])

        if u and p:
            self.taskset = gen_tasksets(u, p)[0]
            self.accept()
        elif not u:
            QMessageBox.warning(
                self, "Generation failed",
                "Please check the utilization and the number of tasks.")
        else:
            QMessageBox.warning(self, "Generation failed",
                                "Pleache check the periods.")

    def get_nb_tasks(self):
        return self.spin_tasks.value() + self.spin_sporadic_tasks.value()

    def get_nb_periodic_tasks(self):
        return self.spin_tasks.value()

    def get_nb_sporadic_tasks(self):
        return self.spin_sporadic_tasks.value()

    def get_utilization(self):
        return self.spin_load.value()

    def get_periods(self):
        if self.unif.isChecked():
            return ("unif", self.unif_interval.getMin(),
                    self.unif_interval.getMax(), self.unif_interval.getRound())
        elif self.lunif.isChecked():
            return ("lunif", self.lunif_interval.getMin(),
                    self.lunif_interval.getMax(),
                    self.lunif_interval.getRound())
        else:
            return ("discrete", map(float, str(self.periods.text()).split()))
Example #56
0
    def add_options_panel(self):
        # Prepare the sliders
        options_layout = QVBoxLayout()

        options_layout.addStretch()  # Centralize the sliders
        sliders_layout = QVBoxLayout()
        max_label_width = -1

        # Get min and max for all dof
        ranges = []
        for i in range(self.model.nbSegment()):
            seg = self.model.segment(i)
            for r in seg.QRanges():
                ranges.append([r.min(), r.max()])

        for i in range(self.model.nbQ()):
            slider_layout = QHBoxLayout()
            sliders_layout.addLayout(slider_layout)

            # Add a name
            name_label = QLabel()
            name = f"{self.model.nameDof()[i].to_string()}"
            name_label.setText(name)
            name_label.setPalette(self.palette_active)
            label_width = name_label.fontMetrics().boundingRect(
                name_label.text()).width()
            if label_width > max_label_width:
                max_label_width = label_width
            slider_layout.addWidget(name_label)

            # Add the slider
            slider = QSlider(Qt.Horizontal)
            slider.setMinimumSize(100, 0)
            slider.setMinimum(ranges[i][0] * self.double_factor)
            slider.setMaximum(ranges[i][1] * self.double_factor)
            slider.setPageStep(self.double_factor)
            slider.setValue(0)
            slider.valueChanged.connect(self.__move_avatar_from_sliders)
            slider.sliderReleased.connect(
                partial(self.__update_muscle_analyses_graphs, False, False,
                        False, False))
            slider_layout.addWidget(slider)

            # Add the value
            value_label = QLabel()
            value_label.setText(f"{0:.2f}")
            value_label.setPalette(self.palette_active)
            slider_layout.addWidget(value_label)

            # Add to the main sliders
            self.sliders.append((name_label, slider, value_label))
        # Adjust the size of the names
        for name_label, _, _ in self.sliders:
            name_label.setFixedWidth(max_label_width + 1)

        # Put the sliders in a scrollable area
        sliders_widget = QWidget()
        sliders_widget.setLayout(sliders_layout)
        sliders_scroll = QScrollArea()
        sliders_scroll.setFrameShape(0)
        sliders_scroll.setWidgetResizable(True)
        sliders_scroll.setWidget(sliders_widget)
        options_layout.addWidget(sliders_scroll)

        # Add reset button
        button_layout = QHBoxLayout()
        options_layout.addLayout(button_layout)
        reset_push_button = QPushButton("Reset")
        reset_push_button.setPalette(self.palette_active)
        reset_push_button.released.connect(self.reset_q)
        button_layout.addWidget(reset_push_button)

        # Add the radio button for analyses
        option_analyses_group = QGroupBox()
        option_analyses_layout = QVBoxLayout()
        # Add text
        analyse_text = QLabel()
        analyse_text.setPalette(self.palette_active)
        analyse_text.setText("Analyses")
        option_analyses_layout.addWidget(analyse_text)
        # Add the no analyses
        radio_none = QRadioButton()
        radio_none.setPalette(self.palette_active)
        radio_none.setChecked(True)
        radio_none.toggled.connect(
            lambda: self.__select_analyses_panel(radio_none, 0))
        radio_none.setText("None")
        option_analyses_layout.addWidget(radio_none)
        # Add the muscles analyses
        radio_muscle = QRadioButton()
        radio_muscle.setPalette(self.palette_active)
        radio_muscle.toggled.connect(
            lambda: self.__select_analyses_panel(radio_muscle, 1))
        radio_muscle.setText("Muscles")
        option_analyses_layout.addWidget(radio_muscle)
        # Add the layout to the interface
        option_analyses_group.setLayout(option_analyses_layout)
        options_layout.addWidget(option_analyses_group)

        # Finalize the options panel
        options_layout.addStretch()  # Centralize the sliders

        # Animation panel
        animation_layout = QVBoxLayout()
        animation_layout.addWidget(self.vtk_window.avatar_widget)

        # Add the animation slider
        animation_slider_layout = QHBoxLayout()
        animation_layout.addLayout(animation_slider_layout)
        load_push_button = QPushButton("Load movement")
        load_push_button.setPalette(self.palette_active)
        load_push_button.released.connect(self.__load_movement_from_button)
        animation_slider_layout.addWidget(load_push_button)

        # Controllers
        self.play_stop_push_button = QPushButton()
        self.play_stop_push_button.setIcon(self.start_icon)
        self.play_stop_push_button.setPalette(self.palette_active)
        self.play_stop_push_button.setEnabled(False)
        self.play_stop_push_button.released.connect(
            self.__start_stop_animation)
        animation_slider_layout.addWidget(self.play_stop_push_button)

        slider = QSlider(Qt.Horizontal)
        slider.setMinimum(0)
        slider.setMaximum(100)
        slider.setValue(0)
        slider.setEnabled(False)
        slider.valueChanged.connect(self.__animate_from_slider)
        animation_slider_layout.addWidget(slider)

        self.record_push_button = QPushButton()
        self.record_push_button.setIcon(self.record_icon)
        self.record_push_button.setPalette(self.palette_active)
        self.record_push_button.setEnabled(True)
        self.record_push_button.released.connect(self.__record)
        animation_slider_layout.addWidget(self.record_push_button)

        self.stop_record_push_button = QPushButton()
        self.stop_record_push_button.setIcon(self.stop_icon)
        self.stop_record_push_button.setPalette(self.palette_active)
        self.stop_record_push_button.setEnabled(False)
        self.stop_record_push_button.released.connect(self.__stop_record, True)
        animation_slider_layout.addWidget(self.stop_record_push_button)

        # Add the frame count
        frame_label = QLabel()
        frame_label.setText(f"{0}")
        frame_label.setPalette(self.palette_inactive)
        animation_slider_layout.addWidget(frame_label)

        self.movement_slider = (slider, frame_label)

        # Global placement of the window
        self.vtk_window.main_layout.addLayout(options_layout, 0, 0)
        self.vtk_window.main_layout.addLayout(animation_layout, 0, 1)
        self.vtk_window.main_layout.setColumnStretch(0, 1)
        self.vtk_window.main_layout.setColumnStretch(1, 2)

        # Change the size of the window to account for the new sliders
        self.vtk_window.resize(self.vtk_window.size().width() * 2,
                               self.vtk_window.size().height())

        # Prepare all the analyses panel
        self.muscle_analyses = MuscleAnalyses(self.analyses_muscle_widget,
                                              self)
        if biorbd.currentLinearAlgebraBackend() == 1:
            radio_muscle.setEnabled(False)
        else:
            if self.model.nbMuscles() == 0:
                radio_muscle.setEnabled(False)
        self.__select_analyses_panel(radio_muscle, 1)
Example #57
0
    def createElement(line: str, widget_gallery) -> 'AbstractClass':
        els = line.split('"')
        els = [el.strip() for el in els]

        button_type, button_label, _discard, button_text, other = els

        try:
            button_type = ButtonType(button_type)
        except:
            button_type = None

        if button_label != "":
            label = QLabel(button_label)
        else:
            label = None

        var_name, val_value, initial_setting, ticked_state = other.split(' ')

        if val_value == "None":
            val_value = None
        elif val_value.find('/'):
            val_value = val_value.split('/')

        if button_type == ButtonType.RADIO_BUTTON:
            inputButton = None
            button = QRadioButton(button_text)
            if initial_setting == "off":
                button.setEnabled(False)

        elif button_type == ButtonType.TEXT_EDIT_BUTTON:
            inputButton = QLineEdit(widget_gallery)
            inputButton.setPlaceholderText(var_name)
            button = QRadioButton(button_text)
            if initial_setting == "off":
                button.setEnabled(False)
                inputButton.setEnabled(False)

        elif button_type == ButtonType.TEXT_EDIT_BOX:
            inputButton = QLineEdit(widget_gallery)
            inputButton.setPlaceholderText(var_name)
            button = None
            if initial_setting == "off":
                inputButton.setEnabled(False)

        elif button_type == ButtonType.FILE_INPUT:
            inputButton = QLineEdit(widget_gallery)
            inputButton.setPlaceholderText(var_name)
            # commented this line for now, since the "choose file" option doesn't work from inside container
            #button = QPushButton(button_text)
            button = None
            if initial_setting == "off":
                inputButton.setEnabled(False)
                # commented this line for now, since the "choose file" option doesn't work from inside container
                #button.setEnabled(False)

        elif button_type == ButtonType.TOGGLE_BUTTON:
            inputButton = None
            button = QCheckBox(button_text)
            if initial_setting == "off":
                button.setEnabled(False)
            if ticked_state == "ticked":
                button.setChecked(True)

        elif button_type == ButtonType.DROPDOWN_LIST:
            inputButton = None
            button = QComboBox(widget_gallery)
            for _value in val_value:
                button.addItem(_value)
            button.move(50, 250)
            if initial_setting == "off":
                button.setEnabled(False)

        elif button_type == ButtonType.PUSH_BUTTON:
            inputButton = None
            pixmap = QPixmap('images/audioicon.png')
            button = QPushButton(button_text)
            button.setGeometry(200, 150, 50, 50)
            button.setIcon(QIcon(pixmap))
            button.setIconSize(QSize(50, 50))

        elif button_type == ButtonType.AUDIO_INPUT:
            inputButton = None
            pixmap = QPixmap('images/audioicon.png')
            button = QPushButton(button_text)
            button.setGeometry(200, 150, 50, 50)
            button.setIcon(QIcon(pixmap))
            button.setIconSize(QSize(50, 50))

        return OptionButton(button_type.value, button, var_name, inputButton,
                            val_value, label)
class finance_entry(QWidget):
    def __init__(self, home_button: QPushButton, parent=None):
        super().__init__(parent)

        intValidator = QIntValidator()
        self.setStyleSheet(QSS)

        self.current_pending_months = []
        self.current_advance_months = []

        self.home_button = home_button
        # -- LEVEL TWO GRID
        self.grid = QGridLayout()
        self.grid.setSpacing(20)
        self.setLayout(self.grid)

        # -- CELL ZERO
        self.receipt_label = QLabel("RECEIPT ID :")
        self.receipt_label.setWordWrap(True)

        self.receipt_id = QLabel()
        self.receipt_id.setStyleSheet("font: bold")
        self.receipt_id.setAlignment(Qt.AlignCenter)

        currentMonth = datetime.now().month
        currentYear = datetime.now().year

        currentReceipt = db_tools.generate_receipt_id(str(currentMonth),
                                                      str(currentYear))
        self.receipt_id.setText(currentReceipt)

        # ---
        self.flat_label = QLabel("FLAT NO. :")
        self.flat_combo = QComboBox()
        model = self.flat_combo.model()

        for flat in flats:
            model.appendRow(QStandardItem(flat))

        self.flat_combo.setStyleSheet(
            'text-color: black; selection-background-color: rgb(215,215,215)')

        self.flat_combo.currentIndexChanged['QString'].connect(self.set_name)

        # ---
        self.name_label = QLabel("NAME :")
        self.name_value = QLabel("Mr D. S. Patil")
        self.name_value.setFixedWidth(200)

        # ---
        self.finance_entry_layout0 = QFormLayout()
        self.finance_entry_layout0.addRow(self.receipt_label, self.receipt_id)
        self.finance_entry_layout0.addRow(self.flat_label, self.flat_combo)
        self.finance_entry_layout0.addRow(self.name_label, self.name_value)
        self.finance_entry_layout0.setVerticalSpacing(90)

        # -- CELL ONE
        self.date_label = QLabel("DATE OF TRANSACTION :")
        self.date_label.setWordWrap(True)

        self.date_line = QDateEdit()
        self.date_line.setCalendarPopup(True)
        self.date_line.setDate(QDate.currentDate())
        self.date_line.setDisplayFormat("dd MMMM, yyyy")

        self.single_radio = QRadioButton("Single Month")
        self.multiple_radio = QRadioButton("Multiple Months")
        self.single_radio.setChecked(True)

        self.single_radio.toggled.connect(
            lambda: self.months(button=self.single_radio))
        self.multiple_radio.toggled.connect(
            lambda: self.months(button=self.multiple_radio))

        self.finance_entry_layout1_h1 = QHBoxLayout()
        self.finance_entry_layout1_h1.addWidget(self.date_line)
        self.finance_entry_layout1_h1.addWidget(self.single_radio)
        self.finance_entry_layout1_h1.addWidget(self.multiple_radio)
        self.finance_entry_layout1_h1.setSpacing(90)

        # ---
        self.month_label = QLabel("FEES FOR :")
        self.month_combo = QComboBox()
        self.set_pending_months()

        self.month_combo.setStyleSheet(
            'text-color: black; selection-background-color: rgb(215,215,215)')

        # ---
        self.month_till_label = QLabel("FEES TILL :")
        self.month_till_label.setAlignment(Qt.AlignCenter)
        self.month_till_combo = QComboBox()

        self.set_advance_months()

        self.month_till_combo.setStyleSheet(
            'text-color: black; selection-background-color: rgb(215,215,215)')

        self.finance_entry_layout1_h2 = QHBoxLayout()
        self.finance_entry_layout1_h2.addWidget(self.month_combo)
        self.finance_entry_layout1_h2.addWidget(self.month_till_label)
        self.finance_entry_layout1_h2.addWidget(self.month_till_combo)
        self.finance_entry_layout1_h2.setSpacing(90)

        self.month_till_label.setEnabled(False)
        self.month_till_combo.setEnabled(False)

        # ---
        self.amount_label = QLabel("AMOUNT :")
        self.amount_label.setAlignment(Qt.AlignCenter)
        self.amount_line = QLineEdit()
        self.amount_line.setText("1500")

        self.amount_line.setValidator(intValidator)

        # ---
        self.fine_label = QLabel("FINE :")
        self.fine_label.setAlignment(Qt.AlignCenter)
        self.fine_line = QLineEdit()

        if int(self.date_line.text().split(" ")[0]) <= 5:
            self.fine_line.setText("0")
        else:
            self.fine_line.setText("50")

        self.fine_line.setValidator(intValidator)
        self.fine_line.setStyleSheet("border: 1px solid red; color: red")

        self.finance_entry_layout1_h3 = QHBoxLayout()
        self.finance_entry_layout1_h3.addWidget(self.amount_line)
        self.finance_entry_layout1_h3.addWidget(self.fine_label)
        self.finance_entry_layout1_h3.addWidget(self.fine_line)
        self.finance_entry_layout1_h3.setSpacing(90)

        # ---
        self.finance_entry_layout1 = QFormLayout()
        self.finance_entry_layout1.addRow(self.date_label,
                                          self.finance_entry_layout1_h1)
        self.finance_entry_layout1.addRow(self.month_label,
                                          self.finance_entry_layout1_h2)
        self.finance_entry_layout1.addRow(self.amount_label,
                                          self.finance_entry_layout1_h3)
        self.finance_entry_layout1.setVerticalSpacing(90)

        # -- CELL TWO
        self.mode_label = QLabel("PAYMENT MODE :")
        self.mode_label.setWordWrap(True)

        # ---
        self.mode_combo = QComboBox()
        self.mode_combo.addItem("Cash")
        self.mode_combo.addItem("Online Funds Transfer")
        self.mode_combo.addItem("Cheque")

        self.mode_combo.setStyleSheet(
            'text-color: black; selection-background-color: rgb(215,215,215)')
        self.mode_combo.currentIndexChanged['QString'].connect(
            self.mode_selection)

        # ---
        self.ref_label = QLabel("REFERENCE ID :")
        self.ref_label.setWordWrap(True)
        self.ref_line = QLineEdit()

        self.ref_label.setDisabled(True)
        self.ref_line.setDisabled(True)

        self.total_label = QLabel(
            f"TOTAL PAYABLE AMOUNT : {int(self.amount_line.text()) + int(self.fine_line.text())}"
        )
        self.total_label.setWordWrap(True)
        self.total_label.setAlignment(Qt.AlignCenter)

        self.save_button = QPushButton("SAVE")
        self.save_button.setStyleSheet("font: bold")
        self.save_button.clicked.connect(lambda: self.check_form())

        self.status = QLabel("Ready")
        self.status.setStyleSheet("font: 8pt")
        self.status.setAlignment(Qt.AlignCenter)

        self.bar = QProgressBar(self)
        self.bar.setMaximum(100)
        self.bar.setValue(0)
        self.bar.setToolTip("Please wait until the process is completed.")

        # ---
        self.finance_entry_layout2 = QFormLayout()
        self.finance_entry_layout2.addRow(self.mode_label, self.mode_combo)
        self.finance_entry_layout2.addRow(self.ref_label, self.ref_line)
        self.finance_entry_layout2.addItem(create_spacer_item(w=5, h=30))
        self.finance_entry_layout2.addRow(self.total_label)
        self.finance_entry_layout2.addRow(self.save_button)
        self.finance_entry_layout2.addRow(self.status)
        self.finance_entry_layout2.addRow(self.bar)
        self.finance_entry_layout2.setVerticalSpacing(50)

        self.finance_entry_group0 = QGroupBox()
        self.finance_entry_group0.setLayout(self.finance_entry_layout0)

        self.finance_entry_group1 = QGroupBox()
        self.finance_entry_group1.setLayout(self.finance_entry_layout1)

        self.finance_entry_group2 = QGroupBox()
        self.finance_entry_group2.setLayout(self.finance_entry_layout2)
        self.finance_entry_group2.setFixedWidth(550)

        # -- FUNCTIONALITY:
        self.date_line.dateChanged.connect(lambda: self.set_pending_months(
            date=str(self.date_line.date().toPyDate())))

        self.month_combo.currentIndexChanged['QString'].connect(
            self.set_advance_months)

        self.month_combo.currentIndexChanged['QString'].connect(
            lambda ind: self.calculate_fine('from', ind))
        self.month_till_combo.currentIndexChanged['QString'].connect(
            lambda ind: self.calculate_fine('till', ind))

        self.month_combo.currentTextChanged.connect(self.calculate_amount)
        self.month_till_combo.currentTextChanged.connect(self.calculate_amount)

        self.amount_line.textChanged.connect(self.set_total)
        self.fine_line.textChanged.connect(self.set_total)

        # -- FINANCE ENTRY GRID
        self.grid.addWidget(self.finance_entry_group0, 0, 0, 2, 1)
        self.grid.addWidget(self.finance_entry_group1, 0, 1, 2, 1)
        self.grid.addWidget(self.finance_entry_group2, 0, 2, 2, 1)

    def months(self, button):
        if button.isChecked():
            if button.text() == "Single Month":
                self.month_till_label.setEnabled(False)
                self.month_till_combo.setEnabled(False)

            elif button.text() == "Multiple Months":
                self.month_till_label.setEnabled(True)
                self.month_till_combo.setEnabled(True)

        self.calculate_amount()

    def mode_selection(self, selection):
        if selection == "Cash":
            self.ref_label.setText("REFERENCE ID :")
            self.ref_label.setDisabled(True)
            self.ref_line.setDisabled(True)

        elif selection == "Cheque":
            self.ref_label.setText("CHEQUE NO. :")
            self.ref_label.setDisabled(False)
            self.ref_line.setDisabled(False)

        elif selection == "Online Funds Transfer":
            self.ref_label.setText("REFERENCE ID :")
            self.ref_label.setDisabled(False)
            self.ref_line.setDisabled(False)

    def check_form(self):
        reply = QMessageBox()

        if len(self.amount_line.text()) == 0:
            reply.setIcon(QMessageBox.Warning)
            reply.setText("AMOUNTS field cannot be left empty.")
            reply.setStandardButtons(QMessageBox.Retry)
            reply.setWindowTitle("INVALID ENTRY")
            reply.exec_()

        elif len(self.fine_line.text()) == 0:
            reply.setIcon(QMessageBox.Warning)
            reply.setText("FINE field cannot be left empty.")
            reply.setStandardButtons(QMessageBox.Retry)
            reply.setWindowTitle("INVALID ENTRY")
            reply.exec_()

        elif self.ref_line.isEnabled() and len(self.ref_line.text()) == 0:
            reply.setIcon(QMessageBox.Warning)
            reply.setText(
                "Please enter the REFERENCE INFORMATION for the transaction.")
            reply.setStandardButtons(QMessageBox.Retry)
            reply.setWindowTitle("INVALID ENTRY")
            reply.exec_()

        elif payment_exists(flat=self.flat_combo.currentText(),
                            month=self.month_combo.currentText()):
            reply.setIcon(QMessageBox.Warning)
            reply.setText(
                f"This member ({self.flat_combo.currentText()}) has already paid the fees for the month of {self.month_combo.currentText()}"
            )
            reply.setStandardButtons(QMessageBox.Retry)
            reply.setWindowTitle("INVALID ENTRY")
            reply.exec_()

        else:
            if self.month_till_combo.isEnabled():
                fee_till = f" - {self.month_till_combo.currentText()}"
            else:
                fee_till = ''

            if self.ref_line.isEnabled():
                ref = f" - ({self.ref_line.text()})"
            else:
                ref = ''

            detailed_text = f"Date : {fix_date(str(self.date_line.date().toPyDate()))}\n" \
                            f"Fee for : {str(self.month_combo.currentText())}{fee_till}\n" \
                            f"Flat No : {str(self.flat_combo.currentText())}\n" \
                            f"Amount : {float(self.amount_line.text())}\n" \
                            f"Fine : {float(self.fine_line.text())}\n" \
                            f"    -> TOTAL : {str(int(self.amount_line.text()) + int(self.fine_line.text()))} <-\n" \
                            f"Payment Mode : {str(self.mode_combo.currentText())}{ref}"

            reply.setWindowTitle("SUCCESSFUL ENTRY")
            reply.setIcon(QMessageBox.Information)
            reply.setText("ENTRY HAS BEEN RECORDED.\n")
            reply.setInformativeText("Please confirm the details below.")
            reply.setDetailedText(detailed_text)
            confirm_button = reply.addButton('Confirm', QMessageBox.AcceptRole)
            edit_button = reply.addButton('Edit', QMessageBox.RejectRole)

            confirm_button.clicked.connect(
                lambda: self.final_clicked(button=confirm_button))
            edit_button.clicked.connect(
                lambda: self.final_clicked(button=edit_button))
            reply.exec_()

    def set_name(self, flat):
        name = get_name(flat)
        self.name_value.setText(str(name))

    def add_entry(self):
        receipt_id = self.receipt_id.text()
        date = str(self.date_line.date().toPyDate())
        fee_month = self.month_combo.currentText()

        if self.month_till_combo.isEnabled():
            fee_till = self.month_till_combo.currentText()
            month = f"{fee_month}-{fee_till}"
        else:
            fee_till = ''
            month = fee_month

        flat = str(self.flat_combo.currentText())
        amount = float(self.amount_line.text())
        fine = float(self.fine_line.text())
        mode = str(self.mode_combo.currentText())

        if self.ref_line.isEnabled():
            ref = self.ref_line.text()
        else:
            ref = ''

        print(fee_month)
        new_receipt = receipt.receipt(date=fix_date(date),
                                      flat=flat,
                                      month=fee_month,
                                      month_till=fee_till,
                                      amount=amount,
                                      fine=fine,
                                      mode=mode,
                                      ref=ref)
        self.disable()
        self.total_label.setText(
            "Confirming.. PLEASE DO NOT PERFORM ANY OTHER OPERATIONS.")
        new_receipt.add_to_db()

        self.status.setText("Adding to databse & Generating receipt")
        self.bar.setValue(40)

        design_receipt(receipt_id=f"0{receipt_id}")

        self.status.setText(
            "Sending the receipt to the member. (Depends on your internet connection)"
        )
        self.bar.setValue(75)
        email_status = send_receipt(flat=flat, month=month)

        self.enable()
        self.set_total()

        if email_status:
            self.bar.setValue(100)

        else:
            reply = QMessageBox()
            reply.setIcon(QMessageBox.Warning)
            reply.setText(
                "The system cannot access the internet. Make sure you have an active connection, or any firewall"
                "feature blocking the access.")
            reply.setStandardButtons(QMessageBox.Retry)
            reply.setWindowTitle("INTERNET")
            reply.exec_()

    def final_clicked(self, button):
        if button.text() == "Confirm":
            self.add_entry()

            currentReceipt = db_tools.generate_receipt_id(
                str(datetime.now().month), str(datetime.now().year))
            self.receipt_id.setText(currentReceipt)
            self.flat_combo.setCurrentIndex(0)
            self.name_value.setText("Mr D. S. Patil")
            self.amount_line.setText('1500')
            if int(self.date_line.text().split(" ")[0]) <= 5:
                self.fine_line.setText("0")
            else:
                self.fine_line.setText("50")
            self.bar.setValue(0)
            self.status.setText("Done !")
            self.ref_line.clear()

    def set_pending_months(self, date: str = None):
        if date is None:
            date = str(self.date_line.date().toPyDate())

        months = calculate_months(month=date, pending=True, advance=False)

        self.current_pending_months = months

        self.month_combo.clear()

        model = self.month_combo.model()
        for month in months:
            model.appendRow(QStandardItem(month))

    def set_advance_months(self, date: str = None):
        if date is None or date == '':
            date = fix_date_back(self.current_pending_months[0])
        else:
            date = fix_date_back(date)

        months = calculate_months(month=date, pending=False, advance=True)

        self.current_advance_months = months

        self.month_till_combo.clear()
        model = self.month_till_combo.model()

        for month in months:
            model.appendRow(QStandardItem(month))

    def calculate_amount(self):
        if self.month_combo.count() == 0 or self.month_till_combo.count() == 0:
            self.amount_line.setText('0')
            return

        else:
            all_possible_months = self.current_advance_months.copy()
            all_possible_months = all_possible_months[::-1]

            all_possible_months.extend([
                x for x in self.current_pending_months
                if x not in self.current_advance_months
            ])

            if self.month_till_combo.isEnabled():
                from_index = all_possible_months.index(
                    self.month_combo.currentText())
                till_index = all_possible_months.index(
                    self.month_till_combo.currentText())

                amount = (from_index - till_index + 1) * 1500

            else:
                amount = 1500

            self.amount_line.setText(str(amount))
            self.amount_line.setToolTip(f"Total months : {amount//1500}")

    def calculate_fine(self, from_where: str, month):
        if month == '' and self.month_combo.count(
        ) == 0 or self.month_till_combo.count() == 0:
            self.fine_line.setText('0')
            return

        else:
            if self.month_till_combo.isEnabled():
                try:
                    till_index = self.current_pending_months.index(
                        str(self.month_till_combo.currentText()))
                except ValueError:
                    till_index = 0
            else:
                try:
                    till_index = self.current_pending_months.index(
                        str(self.month_combo.currentText()))
                except ValueError:
                    self.fine_line.setText('0')
                    return

            try:
                from_index = self.current_pending_months.index(
                    str(self.month_combo.currentText()))
            except ValueError:
                self.fine_line.setText('0')
                return

            all_fine_months = []

            for month in self.current_pending_months[till_index:from_index +
                                                     1]:
                all_fine_months.append([month])

            transact_date = str(self.date_line.date().toPyDate())

            total_fine = 0
            for month in all_fine_months:
                fine = calculate_fine(month=month[0],
                                      transact_date=fix_date(transact_date))
                month = month.append(fine)

                total_fine += fine * 50

            self.fine_line.setText(str(total_fine))
            self.set_fine_tip(all_fine_months=all_fine_months)

    def set_fine_tip(self, all_fine_months: list):
        tool_line = ''

        for month in all_fine_months:
            tool_line += f"{month[0]} x {month[1]}\n"

        self.fine_line.setToolTip(tool_line)

    def set_total(self):
        if len(self.amount_line.text()) > 0:
            amount = float(self.amount_line.text())
        else:
            amount = 0

        if len(self.fine_line.text()) > 0:
            fine = int(self.fine_line.text())
        else:
            fine = 0

        self.total_label.setText(f"TOTAL PAYABLE AMOUNT : {amount + fine}")

    def disable(self):
        self.finance_entry_group0.setEnabled(False)
        self.finance_entry_group1.setEnabled(False)
        self.home_button.setEnabled(False)
        self.mode_label.setEnabled(False)
        self.mode_combo.setEnabled(False)
        self.ref_label.setEnabled(False)
        self.ref_line.setEnabled(False)
        self.save_button.setEnabled(False)

    def enable(self):
        self.finance_entry_group0.setEnabled(True)
        self.finance_entry_group1.setEnabled(True)
        self.home_button.setEnabled(True)
        self.home_button.setEnabled(True)
        self.mode_label.setEnabled(True)
        self.mode_combo.setEnabled(True)
        self.ref_label.setEnabled(True)
        self.ref_line.setEnabled(True)
        self.save_button.setEnabled(True)
Example #59
0
class PipelineRunner(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.PL = GREENOTYPER.Pipeline()
        self.PS = GREENOTYPER.pipeline_settings()

        self.PipelinePlannerApp = PipelinePlanner.PipelinePlanner()
        #self.PipelinePlannerApp = PipelinePlanner.GUI()
        #self.LabelImgApp = MainWindow()

        self.threadpool = QThreadPool()

        self.init_dirs()
        self.wd = os.getcwd()

        self.init_pipeline_buttons()
        self.init_other_apps()
        self.init_main_body()
        self.init_settings_bar()
        self.init_commandline_bar()

        mainLayout = QGridLayout()
        mainLayout.addLayout(self.pipeline_buttons, 0, 0)
        mainLayout.addLayout(self.other_apps, 0, 1)
        mainLayout.addLayout(self.main_body, 1, 0, 2, 2)
        mainLayout.addLayout(self.settings_bar, 0, 2, 3, 3)
        mainLayout.addLayout(self.commandline_group, 3, 0, 3, 0)

        self.setLayout(mainLayout)

        self.setWindowTitle("Greenotyper (v{})".format(self.PL.__version__))

    def init_dirs(self):
        self.pipeline_file = None
        self.inputdir = None
        self.maskdir = None
        self.cropdir = None
        self.sizedir = None
        self.greennessdir = None

    def init_pipeline_buttons(self):
        self.openpipeline = QPushButton("Open Pipeline")
        self.openpipeline.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.openpipeline.clicked.connect(self.openPipeline)
        self.openpipeline.setMinimumWidth(150)

        self.testpipeline = QPushButton("Test Pipeline")
        self.testpipeline.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.testpipeline.setMinimumWidth(150)
        self.testpipeline.clicked.connect(self.testPipeline)

        self.runpipeline = QPushButton("Run pipeline")
        self.runpipeline.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.runpipeline.setMinimumWidth(150)
        self.runpipeline.clicked.connect(self.runPipeline)

        self.pipeline_buttons = QVBoxLayout()
        self.pipeline_buttons.addWidget(self.openpipeline)
        self.pipeline_buttons.addWidget(self.testpipeline)
        self.pipeline_buttons.addWidget(self.runpipeline)
        self.pipeline_buttons.addStretch(1)
    def init_other_apps(self):
        self.other_apps_label = QLabel()
        self.other_apps_label.setText("Additonal Applications")
        self.PipelinePlannerButton = QPushButton("Pipeline Planner")
        self.PipelinePlannerButton.clicked.connect(self.OpenPipelinePlanner)
        #self.PipelinePlannerButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.PipelinePlannerButton.setMinimumWidth(170)

        self.LabelImgButton = QPushButton("LabelImg")
        #self.LabelImgButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.LabelImgButton.setMinimumWidth(170)
        self.LabelImgButton.setDisabled(True)
        #self.LabelImgButton.clicked.connect(self.OpenLabelImg)

        self.other_apps = QVBoxLayout()
        self.other_apps.addWidget(self.other_apps_label)
        self.other_apps.addWidget(self.PipelinePlannerButton)
        self.other_apps.addWidget(self.LabelImgButton)
        self.other_apps.addStretch(1)
    def init_main_body(self):
        bg_color = "#ffffff"
        margin = "2.5px"
        br_color = "#000000"
        br_width = "1px"
        css_style = "padding:{};".format(margin)
        css_style += "background-color:{};".format(bg_color)
        css_style += "border: {} solid {};".format(br_width, br_color)

        button_size = 160

        self.pipeline_label = QLabel()
        self.pipeline_label.setText("Pipeline:")
        self.pipeline_label.setSizePolicy(QSizePolicy.Fixed,
                                         QSizePolicy.Fixed)
        self.pipeline_file_label = QLabel()
        self.pipeline_file_label.setText("Default Pipeline")
        self.pipeline_file_label.setStyleSheet(css_style)
        self.pipeline_labels = QHBoxLayout()
        self.pipeline_labels.addWidget(self.pipeline_label)
        self.pipeline_labels.addWidget(self.pipeline_file_label)

        self.inputdirectory_button = QPushButton("Input file directory")
        self.inputdirectory_button.setSizePolicy(QSizePolicy.Fixed,
                                                 QSizePolicy.Fixed)
        self.inputdirectory_button.clicked.connect(self.openInputDirectory)
        self.inputdirectory_button.setMinimumWidth(button_size+15)
        self.inputdir_label = QLabel()
        self.inputdir_label.setText("No directory chosen")
        self.inputdir_label.setStyleSheet(css_style)
        self.input_group = QHBoxLayout()
        self.input_group.addWidget(self.inputdirectory_button)
        self.input_group.addWidget(self.inputdir_label)
        #self.input_group.addStretch(1)

        self.mask_check = QCheckBox("")
        self.mask_check.setChecked(False)
        self.mask_check.setDisabled(True)
        self.mask_check.setSizePolicy(QSizePolicy.Fixed,
                                      QSizePolicy.Fixed)
        self.maskoutput_button = QPushButton("Mask output")
        self.maskoutput_button.setSizePolicy(QSizePolicy.Fixed,
                                             QSizePolicy.Fixed)
        self.maskoutput_button.setMinimumWidth(button_size)
        self.maskoutput_button.clicked.connect(self.openMaskDirectory)
        self.maskout_label = QLabel()
        self.maskout_label.setText("No directory chosen")
        self.maskout_label.setStyleSheet(css_style)
        self.mask_group = QHBoxLayout()
        self.mask_group.addWidget(self.mask_check)
        self.mask_group.addWidget(self.maskoutput_button)
        self.mask_group.addWidget(self.maskout_label)

        self.crop_check = QCheckBox("")
        self.crop_check.setChecked(False)
        self.crop_check.setDisabled(True)
        self.crop_check.setSizePolicy(QSizePolicy.Fixed,
                                      QSizePolicy.Fixed)
        self.cropoutput_button = QPushButton("Crop output")
        #self.cropoutput_button.setWidth()
        self.cropoutput_button.setSizePolicy(QSizePolicy.Fixed,
                                             QSizePolicy.Fixed)
        self.cropoutput_button.clicked.connect(self.openCropDirectory)
        self.cropoutput_button.setMinimumWidth(button_size)
        self.cropout_label = QLabel()
        self.cropout_label.setText("No directory chosen")
        self.cropout_label.setStyleSheet(css_style)
        self.crop_group = QHBoxLayout()
        self.crop_group.addWidget(self.crop_check)
        self.crop_group.addWidget(self.cropoutput_button)
        self.crop_group.addWidget(self.cropout_label)

        self.size_check = QCheckBox("")
        self.size_check.setChecked(False)
        self.size_check.setDisabled(True)
        self.size_check.setSizePolicy(QSizePolicy.Fixed,
                                        QSizePolicy.Fixed)
        self.sizeoutput_button = QPushButton("Size output")
        self.sizeoutput_button.setSizePolicy(QSizePolicy.Fixed,
                                               QSizePolicy.Fixed)
        self.sizeoutput_button.clicked.connect(self.openSizeDirectory)
        self.sizeoutput_button.setMinimumWidth(button_size)
        self.sizeout_label = QLabel()
        self.sizeout_label.setText("No directory chosen")
        self.sizeout_label.setStyleSheet(css_style)
        self.size_group = QHBoxLayout()
        self.size_group.addWidget(self.size_check)
        self.size_group.addWidget(self.sizeoutput_button)
        self.size_group.addWidget(self.sizeout_label)


        self.greenness_check = QCheckBox("")
        self.greenness_check.setChecked(False)
        self.greenness_check.setDisabled(True)
        self.greenness_check.setSizePolicy(QSizePolicy.Fixed,
                                        QSizePolicy.Fixed)
        self.greennessoutput_button = QPushButton("Greenness output")
        self.greennessoutput_button.setSizePolicy(QSizePolicy.Fixed,
                                               QSizePolicy.Fixed)
        self.greennessoutput_button.clicked.connect(self.openGreennessDirectory

                                                    )
        self.greennessoutput_button.setMinimumWidth(button_size)
        self.greennessout_label = QLabel()
        self.greennessout_label.setText("No directory chosen")
        self.greennessout_label.setStyleSheet(css_style)
        self.greenness_group = QHBoxLayout()
        self.greenness_group.addWidget(self.greenness_check)
        self.greenness_group.addWidget(self.greennessoutput_button)
        self.greenness_group.addWidget(self.greennessout_label)


        self.progress = QProgressBar()
        self.progress.setGeometry(0,0,150,40)
        self.progress.setMaximum(1)
        self.progress.setValue(1)

        self.time_left = QLabel()
        self.time_left.setText("--h--m--s")

        self.progress_estimator = QHBoxLayout()
        self.progress_estimator.addWidget(self.progress)
        self.progress_estimator.addWidget(self.time_left)

        self.main_body = QVBoxLayout()
        self.main_body.addLayout(self.pipeline_labels)
        self.main_body.addLayout(self.input_group)
        self.main_body.addLayout(self.mask_group)
        self.main_body.addLayout(self.crop_group)
        self.main_body.addLayout(self.size_group)
        self.main_body.addLayout(self.greenness_group)
        self.main_body.addLayout(self.progress_estimator)
        self.main_body.addStretch(1)
    def init_settings_bar(self):
        self.multicore_label = QLabel()
        self.multicore_label.setText("Number of CPU")

        self.multicore = QLineEdit()
        self.multicore.setText(str(mp.cpu_count()))
        self.onlyInt = QtGui.QIntValidator()
        self.multicore.setValidator(self.onlyInt)
        self.multicore.setSizePolicy(QSizePolicy.Fixed,
                                     QSizePolicy.Fixed)
        self.multicore.setMaximumWidth(40)
        self.multicore.setMaxLength(4)

        self.multicore_group = QHBoxLayout()
        self.multicore_group.addWidget(self.multicore_label)
        self.multicore_group.addWidget(self.multicore)
        self.multicore_group.addStretch(1)

        self.output_organisation = QGroupBox("Output organistation")

        self.no_subfolders = QRadioButton("No subfolders")
        self.divide_by_day = QRadioButton("Divide by day")
        self.divide_by_individual = QRadioButton("Divide by individual")

        self.no_subfolders.setChecked(True)

        self.division_options = QVBoxLayout()
        self.division_options.addWidget(self.no_subfolders)
        self.division_options.addWidget(self.divide_by_day)
        self.division_options.addWidget(self.divide_by_individual)

        self.output_organisation.setLayout(self.division_options)

        self.test_options = QGroupBox("Testing options")

        self.test_images_label = QLabel()
        self.test_images_label.setText("Test images")

        self.test_images = QLineEdit()
        self.test_images.setText(str(10))
        self.test_images.setValidator(self.onlyInt)
        self.test_images.setSizePolicy(QSizePolicy.Fixed,
                                       QSizePolicy.Fixed)
        self.test_images.setMaximumWidth(60)
        self.test_images.setMaxLength(6)

        self.test_images_group = QHBoxLayout()
        self.test_images_group.addWidget(self.test_images_label)
        self.test_images_group.addWidget(self.test_images)
        self.test_images_group.addStretch(1)

        self.test_id_label = QLabel()
        self.test_id_label.setText("Test from")
        self.test_id = QLineEdit()
        self.test_id.setMaximumWidth(75)

        self.test_id_layout = QHBoxLayout()
        self.test_id_layout.addWidget(self.test_id_label)
        self.test_id_layout.addWidget(self.test_id)
        self.test_id_layout.addStretch(1)

        self.test_options_layout = QVBoxLayout()
        self.test_options_layout.addLayout(self.test_images_group)
        self.test_options_layout.addLayout(self.test_id_layout)

        self.test_options.setLayout(self.test_options_layout)

        self.runtime_output = QGroupBox("Commandline runtime options")

        self.relative_paths = QCheckBox("Use relative paths")
        self.relative_paths.setChecked(False)

        self.use_bash = QRadioButton("Use bash")
        self.use_gwf = QRadioButton("Use gwf")

        self.use_bash.setChecked(True)

        self.use_cases = QHBoxLayout()
        self.use_cases.addWidget(self.use_bash)
        self.use_cases.addWidget(self.use_gwf)

        #self.environment_label = QLabel()
        #self.environment_label.setText("Environment")

        textbox_height = 25
        textbox_width = 170

        self.environment_textbox = QTextEdit()
        self.environment_default = "Environment loading - Example using conda: conda activate greenotyperenv"
        self.environment_textbox.setText(self.environment_default)
        self.environment_textbox.setMaximumHeight(textbox_height)
        self.environment_textbox.setMaximumWidth(textbox_width)

        self.cluster_submit = QTextEdit()
        self.cluster_default = 'Cluster submit command, replaces {command} with the greenotyper command, example srun "{command}"'
        self.cluster_submit.setText(self.cluster_default)
        self.cluster_submit.setMaximumHeight(textbox_height)
        self.cluster_submit.setMaximumWidth(textbox_width)

        self.cluster_button = QPushButton("output workflow script")
        self.cluster_button.clicked.connect(self.saveWorkflow)

        self.runtime_output_layout = QVBoxLayout()
        self.runtime_output_layout.addWidget(self.relative_paths)
        self.runtime_output_layout.addLayout(self.use_cases)
        self.runtime_output_layout.addWidget(self.environment_textbox)
        self.runtime_output_layout.addWidget(self.cluster_submit)
        self.runtime_output_layout.addWidget(self.cluster_button)

        self.runtime_output.setLayout(self.runtime_output_layout)


        self.settings_bar = QVBoxLayout()
        self.settings_bar.addLayout(self.multicore_group)
        self.settings_bar.addWidget(self.output_organisation)
        self.settings_bar.addWidget(self.test_options)
        self.settings_bar.addWidget(self.runtime_output)

        self.settings_bar.addStretch(1)
    def init_commandline_bar(self):
        bg_color = "#222222"
        margin = "2.5px"
        color = "#ffffff"
        css_style = "padding:{};".format(margin)
        css_style += "background-color:{};".format(bg_color)
        css_style += "color:{};".format(color)

        self.commandbox = QTextEdit()
        self.commandbox.setMaximumHeight(50)
        self.commandbox.setText("No inputs defined")
        self.commandbox.setStyleSheet(css_style)

        self.system_clipboard = QApplication.clipboard()

        self.update_command_line = QPushButton("Update Commandline")
        self.update_command_line.clicked.connect(self.updateCommandline)

        self.copyToClipboard = QPushButton("Copy to Clipboard")
        self.copyToClipboard.clicked.connect(self.copy_to_clipboard)

        self.commandline_buttons = QVBoxLayout()
        self.commandline_buttons.addWidget(self.update_command_line)
        self.commandline_buttons.addWidget(self.copyToClipboard)

        self.commandline_group = QHBoxLayout()
        self.commandline_group.addWidget(self.commandbox)
        self.commandline_group.addLayout(self.commandline_buttons)

    @pyqtSlot()
    def openPipeline(self, fileName=None):
        if fileName is None:
            fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "",
                                                      "Pipeline file (*.pipeline);;All Files (*)")
        if fileName:
            self.PS.read(fileName)
            wd = os.getcwd()
            self.pipeline_file = fileName
            self.pipeline_file_label.setText("./"+os.path.relpath(fileName, wd))
            self.PL.load_pipeline(self.PS)
    @pyqtSlot()
    def testPipeline(self, multiprocess=True):
        if self.inputdir is None:
            QMessageBox.about(self, "Input directory missing",
                              "No input directory selected!")
        else:
            #self.setOutputSettings(self.PL)
            images = self.PL.scan_directory(self.inputdir)
            number_test_images = int(self.test_images.text())
            if number_test_images<1:
                QMessageBox.about(self, "Test file number failure",
                                  "Number of test images must be positive")
            else:
                self.total_input = number_test_images
                self.time_mean = 30
                self.progress.setMaximum(self.total_input)
                self.progress.setValue(1)
                self._update_time(30)
                self.progress.setValue(0)
                self.time_mean = 0
                #self.time_left.setText("--h--m--s")
                #self.image_counter = 0

                if multiprocess:
                    self.multi_process_images(images[:number_test_images])
                else:
                    self.process_images(images[:number_test_images])
    @pyqtSlot()
    def runPipeline(self):
        if self.inputdir is None:
            QMessageBox.about(self, "Input directory missing",
                              "No input directory selected!")
        else:
            images = self.PL.scan_directory(self.inputdir)
            self.total_input = len(images)
            self.time_mean = 30
            self.progress.setMaximum(self.total_input)
            self.progress.setValue(1)
            self._update_time(30)
            self.progress.setValue(0)
            self.time_mean = 0
            #self.time_left.setText("--h--m--s")
            self.multi_process_images(images)

    def setOutputSettings(self, PL):
        if self.mask_check.isChecked():
            PL.mask_output = (True, self.maskdir)
        if self.size_check.isChecked():
            PL.measure_size = (True, self.sizedir)
        if self.crop_check.isChecked():
            PL.crop_output = (True, self.cropdir)
        if self.greenness_check.isChecked():
            PL.measure_greenness = (True, self.greennessdir)
        if self.no_subfolders.isChecked():
            PL.substructure = (False, "")
        if self.divide_by_day.isChecked():
            PL.substructure = (True, "Time")
        if self.divide_by_individual.isChecked():
            PL.substructure = (True, "Sample")
    def process_images(self, images):
        for image in images:
            start = time.time()
            try:
                print("Reading image!")
                self.PL.open_image(image)
                print("Searching for plants")
                self.PL.infer_network_on_image()
                print("Applying color correction")
                self.PL.color_correction()
                print("Identifying group")
                self.PL.identify_group()
                print("Cropping and labelling pots")
                self.PL.crop_and_label_pots()
            except:
                traceback.print_exc()
                exctype, value = sys.exc_info()[:2]
                self._report_error((exctype, value, traceback.format_exc()))
            self._process_complete()
            self._update_time(time.time()-start)
    def _process_complete(self):
        self.progress.setValue(self.progress.value()+1)
        if self.progress.value()==self.total_input:
            self.time_left.setText("Complete")
    def _prettify_time(self, seconds):
        base_time = str(datetime.timedelta(seconds=round(seconds)))
        return datetime.datetime.strptime(base_time, "%H:%M:%S").strftime("%Hh%Mm%Ss")
    def update_mean(self, value):
        if self.time_mean==0:
            self.time_mean = value
        else:
            self.time_mean = (self.time_mean * (self.progress.value()-1) + value) / (self.progress.value())
    def _update_time(self, rtime):
        left = self.total_input-self.progress.value()
        if left == 0:
            self.time_left.setText("Completed")
        else:
            self.update_mean(rtime)
            time_left = (self.time_mean*left)/int(self.multicore.text())
            self.time_left.setText(self._prettify_time(time_left))
    def _report_error(self, error):
        exctype, value, errormsg = error
        print(errormsg)
    def multi_process_images(self, images):
        n_process = int(self.multicore.text())
        self.threadpool.setMaxThreadCount(n_process)
        self.time_mean = 0
        for image in images:
            worker = Worker(_single_process, image=image, PS=self.PS, Interface=self)
            worker.signals.finished.connect(self._process_complete)
            worker.signals.error.connect(self._report_error)
            worker.signals.result.connect(self._update_time)
            self.threadpool.start(worker)

    @pyqtSlot()
    def OpenPipelinePlanner(self):
        self.PipelinePlannerApp.show()
        self.PipelinePlannerApp.GUI.setDefaultValues()
        self.PipelinePlannerApp.setWindowIcon(self.windowicon)

    @pyqtSlot()
    def openInputDirectory(self, dir_name=None):
        if dir_name is None:
            dir_name = str(QFileDialog.getExistingDirectory(self, "Select Network Directory", "Network Directory"))
        if dir_name:
            self.inputdir_label.setText("./"+os.path.relpath(dir_name, self.wd))
            self.inputdir = dir_name
    @pyqtSlot()
    def openMaskDirectory(self, dir_name=None):
        if dir_name is None:
            dir_name = str(QFileDialog.getExistingDirectory(self, "Select Mask output directory", "Mask Directory"))
        if dir_name:
            self.maskout_label.setText("./"+os.path.relpath(dir_name, self.wd))
            self.maskdir = dir_name
            self.mask_check.setChecked(True)
            self.mask_check.setDisabled(False)
    @pyqtSlot()
    def openCropDirectory(self, dir_name=None):
        if dir_name is None:
            dir_name = str(QFileDialog.getExistingDirectory(self, "Select Crop output Directory", "Crop Directory"))
        if dir_name:
            self.cropout_label.setText("./"+os.path.relpath(dir_name, self.wd))
            self.cropdir = dir_name
            self.crop_check.setChecked(True)
            self.crop_check.setDisabled(False)
    @pyqtSlot()
    def openSizeDirectory(self, dir_name=None):
        if dir_name is None:
            dir_name = str(QFileDialog.getExistingDirectory(self, "Select Size output Directory", "Size Directory"))
        if dir_name:
            self.sizeout_label.setText("./"+os.path.relpath(dir_name, self.wd))
            self.sizedir = dir_name
            self.size_check.setChecked(True)
            self.size_check.setDisabled(False)
    @pyqtSlot()
    def openGreennessDirectory(self, dir_name=None):
        if dir_name is None:
            dir_name = str(QFileDialog.getExistingDirectory(self, "Select Greenness output Directory", "Greenness Directory"))
        if dir_name:
            self.greennessout_label.setText("./"+os.path.relpath(dir_name, self.wd))
            self.greennessdir = dir_name
            self.greenness_check.setChecked(True)
            self.greenness_check.setDisabled(False)

    @pyqtSlot()
    def copy_to_clipboard(self):
        self.system_clipboard.setText(self.commandbox.toPlainText())

    def _fix_spaces(self, string):
        return string.replace(" ", "\\ ")
    def _set_relative_path(self, string):
        if self.relative_paths.isChecked():
            return "./"+os.path.relpath(string, self.wd)
        else:
            return string
    def generateCommandline(self, multi_image=True):
        s = "greenotyper"
        if multi_image:
            s += " -t {}".format(int(self.multicore.text()))
        if not self.pipeline_file is None:
            s += " -p {}".format(self._set_relative_path(self._fix_spaces(self.pipeline_file)))
        if not self.inputdir is None:
            s += " -i {}".format(self._set_relative_path(self._fix_spaces(self.inputdir)))
        if self.size_check.isChecked():
            s += " -s {}".format(self._set_relative_path(self._fix_spaces(self.sizedir)))
        if self.greenness_check.isChecked():
            s += " -g {}".format(self._set_relative_path(self._fix_spaces(self.greennessdir)))
        if self.crop_check.isChecked():
            s += " -c {}".format(self._set_relative_path(self._fix_spaces(self.cropdir)))
        if self.mask_check.isChecked():
            s += " -m {}".format(self._set_relative_path(self._fix_spaces(self.maskdir)))
        if self.divide_by_day.isChecked():
            s += " --by_day"
        if self.divide_by_individual.isChecked():
            s += " --by_individual"

        return s
    @pyqtSlot()
    def updateCommandline(self):
        s = self.generateCommandline()
        self.commandbox.setText(s)

    def _make_gwf_template(self, commandline, format):
        tab = "    "
        gwf_template = "def process_image(image, outputs):\n"
        gwf_template += "{tab}inputs = [image]\n{tab}outputs = outputs\n".format(tab=tab)
        gwf_template += "{tab}options = {{\n{tab}{tab}'memory': '2g',\n{tab}{tab}'walltime': '00:10:00'\n{tab}}}\n\n".format(tab=tab)
        gwf_template += "{tab}spec = '''\n".format(tab=tab)
        gwf_template += tab+commandline+"\n"
        gwf_template += "{tab}'''.format({format})\n\n".format(tab=tab, format=format)
        gwf_template += "{tab}return inputs, outputs, options, spec\n\n".format(tab=tab)
        return gwf_template
    def _bash_commandline(self, commandline):
        before, after = commandline.split("-i", 1)
        remaning_options = after.split("-", 1)
        if len(remaning_options)==1:
            after = ""
            generalized_commandline = before+"-i"+" $IMAGE "
        else:
            after = remaning_options[-1]
            generalized_commandline = before+"-i"+" $IMAGE "+"-"+after

        return generalized_commandline
    def _generalize_commandline(self, commandline):
        environment = self.environment_textbox.toPlainText()
        before, after = commandline.split("-i", 1)
        remaning_options = after.split("-", 1)
        if len(remaning_options)==1:
            after = ""
            generalized_commandline = before+"-i"+" {image} "
        else:
            after = remaning_options[-1]
            generalized_commandline = before+"-i"+" {image} "+"-"+after

        if environment!=self.environment_default:
            tab = "    "
            generalized_commandline = environment+"\n\n"+tab+generalized_commandline

        return generalized_commandline, "image=image"
    def generateWorkflowFile(self):
        if self.inputdir is None:
            QMessageBox.about(self, "Input directory missing",
                              "No input directory selected!")
            return None
        if self.use_bash.isChecked():
            commandline = self.generateCommandline(False)
            bash_workflow = "#!/bin/bash\n\n"
            tab = "    "
            cluster_submit_command = self.cluster_submit.toPlainText()

            environment = self.environment_textbox.toPlainText()
            if environment==self.environment_default:
                environment = ""
                #bash_workflow += environment
                #bash_workflow += "\n\n"

            bash_workflow += 'IMAGES=$(find {dir} -type f \\( -name "*.jpg" -or -name "*" \\))\n\n'.format(dir = self._set_relative_path(self.inputdir))

            bash_workflow += "for IMAGE in $IMAGES;\ndo\n"

            bash_command = self._bash_commandline(commandline)
            #bash_workflow += tab+"echo $IMAGE\n"
            if cluster_submit_command==self.cluster_default:
                bash_workflow += tab+bash_command+"\n"
            else:
                bash_workflow += tab+cluster_submit_command.format(command=bash_command,environment=environment)+"\n"
            bash_workflow += "done\n"

            return bash_workflow
        if self.use_gwf.isChecked():
            commandline = self.generateCommandline(False)
            tab = "    "

            gwf_workflow = "from gwf import Workflow\nimport os\n"
            gwf_workflow += "gwf = Workflow()\n\n"

            generalized_commandline, format = self._generalize_commandline(commandline)

            gwf_workflow += self._make_gwf_template(generalized_commandline, format)

            gwf_workflow += "images = os.listdir({})\n".format(self._set_relative_path(self.inputdir))

            outputs = []
            gwf_workflow += "for image in images:\n"
            gwf_workflow += "{tab}gwf.target_from_template('{{}}_process'.format(image),\n{tab}{tab}{tab}{tab}process_image(image, outputs={outputs}))".format(tab=tab, outputs=outputs)

            return gwf_workflow
    def saveWorkflow(self):
        workflow = self.generateWorkflowFile()
        if self.use_bash.isChecked():
            fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getOpenFileName()", "",
                                                      "bash script (*.sh);;All Files (*)")
        if self.use_gwf.isChecked():
            fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getOpenFileName()", "",
                                                      "python script (*.py);;All Files (*)")
        if fileName:
            _file = open(fileName, "w")
            _file.write(workflow)
            _file.close()
Example #60
0
    def add_profile(self):
        self.listener.stop()
        text, ok = QInputDialog.getText(self, 'Add new Profile',
                                        'Profile Name:', QLineEdit.Normal, "")
        if ok and text and text not in [
                box.name for box in self.profile_boxes
        ]:
            profile = {
                'name': text,
                "hotkeys": [None, None, None, None, 'LeftClick', 'RightClick'],
                "delays": [0, 0, 0, 0, 0, 0],
            }
            self.settings.skill_macro['profiles'][text] = profile
            self.profile_amt += 1
            skills = QGroupBox(self)
            skills.setTitle(profile['name'])
            skills_layout = QGridLayout(skills)
            self.layout.addWidget(skills, self.profile_amt, 0)
            self.profile_boxes.append(skills)

            label = QLabel(skills)
            label.setText('Key')
            skills_layout.addWidget(label, 0, 0)

            label = QLabel(skills)
            label.setText('Delay (in ms)')
            skills_layout.addWidget(label, 1, 0)

            skills.name = profile['name']
            skills.key_buttons = []
            skills.spinboxes = []

            for i, (hotkey, delay) in enumerate(
                    zip(
                        profile['hotkeys'],
                        profile['delays'],
                    )):
                button = QPushButton(skills)
                button.setText(hotkey)
                button.key_code = hotkey
                button.clicked.connect(self.set_key)
                skills_layout.addWidget(button, 0, i + 1)
                if i >= 4:
                    button.setDisabled(True)
                skills.key_buttons.append(button)

                spinbox = QSpinBox(skills)
                spinbox.setMinimum(0)
                spinbox.setMaximum(100000)
                spinbox.setSingleStep(10)
                spinbox.setValue(delay)
                skills_layout.addWidget(spinbox, 1, i + 1)
                skills.spinboxes.append(spinbox)
                if i == 4:
                    spinbox.setDisabled(True)

            radiobutton = QRadioButton(self.radiobuttons)
            radiobutton.setText(profile['name'])
            radiobutton.setChecked(
                profile['name'] == self.settings.skill_macro['active'])
            self.radiobuttons_layout.addWidget(radiobutton)
            self.radiobuttons_x.append(radiobutton)

            button = QPushButton(skills)
            button.setText('Delete')
            button.clicked.connect(lambda state: self.delete_profile(text))
            skills_layout.addWidget(button, 0, 7)

        elif text in [box.name for box in self.profile_boxes]:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Warning)
            msg.setText("This Profile Name already exists!")
            msg.setInformativeText('Pick a different Profile Name!')
            msg.setWindowTitle("Profile Name exists!")
            msg.exec_()

        if not self.listener.paused:
            self.listener.start()
        elif self.settings.hotkeys['pause']:
            keyboard.add_hotkey(self.settings.hotkeys['pause'],
                                self.listener.pause)