Exemple #1
0
    def __init__(self, previewImage, fileName):
        super(ImageView, self).__init__()

        self.fileName = fileName

        mainLayout = QVBoxLayout(self)
        self.imageLabel = QLabel()
        self.imageLabel.setPixmap(QPixmap.fromImage(previewImage))
        mainLayout.addWidget(self.imageLabel)

        topLayout = QHBoxLayout()
        self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName))
        self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)

        topLayout.addWidget(self.fileNameLabel)
        topLayout.addStretch()
        copyButton = QPushButton("Copy")
        copyButton.setToolTip("Copy file name to clipboard")
        topLayout.addWidget(copyButton)
        copyButton.clicked.connect(self.copy)
        launchButton = QPushButton("Launch")
        launchButton.setToolTip("Launch image viewer")
        topLayout.addWidget(launchButton)
        launchButton.clicked.connect(self.launch)
        mainLayout.addLayout(topLayout)
    def __init__(self, parent=None):
        super(AddDialogWidget, self).__init__(parent)

        nameLabel = QLabel("Name")
        addressLabel = QLabel("Address")
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel)

        self.nameText = QLineEdit()
        self.addressText = QTextEdit()

        grid = QGridLayout()
        grid.setColumnStretch(1, 2)
        grid.addWidget(nameLabel, 0, 0)
        grid.addWidget(self.nameText, 0, 1)
        grid.addWidget(addressLabel, 1, 0, Qt.AlignLeft | Qt.AlignTop)
        grid.addWidget(self.addressText, 1, 1, Qt.AlignLeft)

        layout = QVBoxLayout()
        layout.addLayout(grid)
        layout.addWidget(buttonBox)

        self.setLayout(layout)

        self.setWindowTitle("Add a Contact")

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
Exemple #3
0
    def initUI(self):
        self.setWindowTitle(self.tr("Tic-Tac-Toe"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        gridLayout = QGridLayout()
        gridLayout.setSpacing(3)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(self.selectAI)
        layout.addWidget(aiComboBox)
        layout.addLayout(gridLayout)

        for tile in self.ticTacToe:
            button = QTicTacToe.QTileButton(self, tile)
            gridLayout.addWidget(button, tile.row, tile.column)
            button.clicked.connect(button.clickEvent)
            tile.delegate = button
Exemple #4
0
    def initUI(self):
        self.setWindowTitle(self.tr("Fourplay"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        discGridLayout = QGridLayout()
        discGridLayout.setSpacing(4)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(lambda: self.selectAI())
        layout.addWidget(aiComboBox)
        layout.addLayout(discGridLayout)

        for disc in self.fourPlay:
            qDisc = QFourPlay.QDiscButton(self)
            discGridLayout.addWidget(qDisc, disc.row, disc.column)
            qDisc.clicked.connect(lambda qDisc=qDisc, disc=disc: qDisc.clickEvent(disc))
            qDisc.marked(disc)
            disc.delegate = qDisc
    def test_setLayout(self):
        layout = QVBoxLayout()
        btn1 = QPushButton("button_v1")
        layout.addWidget(btn1)

        btn2 = QPushButton("button_v2")
        layout.addWidget(btn2)

        layout2 = QHBoxLayout()

        btn1 = QPushButton("button_h1")
        layout2.addWidget(btn1)

        btn2 = QPushButton("button_h2")
        layout2.addWidget(btn2)

        layout.addLayout(layout2)

        widget = QWidget()
        widget.setLayout(layout)
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemple #7
0
    def __init__(self, parent=None):
        super(HelpWindow,self).__init__(parent)

        self.setWindowTitle("Facepager 3.0 - Help")
        self.setMinimumWidth(600);
        self.setMinimumHeight(600);
        central = QWidget()
        self.setCentralWidget(central)
        vLayout = QVBoxLayout(central)

        self.page = MyQWebEnginePage()
        self.browser = QWebEngineView(central)
        self.browser.setPage(self.page)

        vLayout.addWidget(self.browser)
        hLayout = QHBoxLayout()
        vLayout.addLayout(hLayout)
        hLayout.addStretch(5)
        dismiss = QPushButton(central)
        dismiss.setText("Close")
        dismiss.clicked.connect(self.hide)
        hLayout.addWidget(dismiss)
    def initializeWindow(self):
        layout = QVBoxLayout()

        self.m_deviceBox = QComboBox()
        self.m_deviceBox.activated[int].connect(self.deviceChanged)
        for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        layout.addWidget(self.m_deviceBox)

        self.m_modeButton = QPushButton()
        self.m_modeButton.clicked.connect(self.toggleMode)
        self.m_modeButton.setText(self.PUSH_MODE_LABEL)

        layout.addWidget(self.m_modeButton)

        self.m_suspendResumeButton = QPushButton(
                clicked=self.toggleSuspendResume)
        self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)

        layout.addWidget(self.m_suspendResumeButton)

        volumeBox = QHBoxLayout()
        volumeLabel = QLabel("Volume:")
        self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100,
                singleStep=10)
        self.m_volumeSlider.valueChanged.connect(self.volumeChanged)

        volumeBox.addWidget(volumeLabel)
        volumeBox.addWidget(self.m_volumeSlider)

        layout.addLayout(volumeBox)

        window = QWidget()
        window.setLayout(layout)

        self.setCentralWidget(window)
    def initUI(self):
        main_layout = QVBoxLayout(self)

        self.setWindowTitle('DOCXImport')
        self.upd_layout = QVBoxLayout()
        self.update_label = QLabel()
        self.update_label.setAlignment(Qt.AlignCenter)
        self.upd_layout.addWidget(self.update_label)
        self.get_update_button = QPushButton()
        self.get_update_button.clicked.connect(self.get_update)
        self.upd_layout.addWidget(self.get_update_button)
        main_layout.addLayout(self.upd_layout)
        if not self.update:
            self.update_label.hide()
            self.get_update_button.hide()

        self.details_grid = QGridLayout()
        self.epub2_select = QRadioButton()
        self.epub2_select.setText('EPUB2')
        self.epubType = QButtonGroup()
        self.epubType.addButton(self.epub2_select)
        self.details_grid.addWidget(self.epub2_select, 0, 0, 1, 1)
        self.checkbox_get_updates = QCheckBox()
        self.details_grid.addWidget(self.checkbox_get_updates, 0, 1, 1, 1)
        self.epub3_select = QRadioButton()
        self.epub3_select.setText('EPUB3')
        self.epubType.addButton(self.epub3_select)
        self.details_grid.addWidget(self.epub3_select, 1, 0, 1, 1)
        main_layout.addLayout(self.details_grid)
        self.checkbox_get_updates.setChecked(self.prefs['check_for_updates'])
        if self.prefs['epub_version'] == '2.0':
            self.epub2_select.setChecked(True)
        elif self.prefs['epub_version'] == '3.0':
            self.epub3_select.setChecked(True)
        else:
            self.epub2_select.setChecked(True)

        self.groupBox = QGroupBox()
        self.groupBox.setTitle('')
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.docx_grid = QGridLayout()
        self.docx_label = QLabel()
        self.docx_grid.addWidget(self.docx_label, 0, 0, 1, 1)
        self.docx_path = QLineEdit()
        self.docx_grid.addWidget(self.docx_path, 1, 0, 1, 1)
        self.choose_docx_button = QPushButton()
        self.choose_docx_button.setText('...')
        self.docx_grid.addWidget(self.choose_docx_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.docx_grid)
        self.choose_docx_button.clicked.connect(
            lambda: self.fileChooser('docx', self.docx_path))
        if len(self.prefs['lastDocxPath']):
            self.docx_path.setText(self.prefs['lastDocxPath'])
        self.docx_path.setEnabled(False)

        self.smap_grid = QGridLayout()
        self.checkbox_smap = QCheckBox(self.groupBox)
        self.smap_grid.addWidget(self.checkbox_smap, 0, 0, 1, 1)
        self.cust_smap_path = QLineEdit(self.groupBox)
        self.smap_grid.addWidget(self.cust_smap_path, 1, 0, 1, 1)
        self.choose_smap_button = QPushButton(self.groupBox)
        self.choose_smap_button.setText('...')
        self.smap_grid.addWidget(self.choose_smap_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.smap_grid)
        self.checkbox_smap.setChecked(self.prefs['useSmap'])
        self.checkbox_smap.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_smap, self.choose_smap_button))
        self.choose_smap_button.clicked.connect(
            lambda: self.fileChooser('smap', self.cust_smap_path, self.
                                     checkbox_smap, self.choose_smap_button))
        if len(self.prefs['useSmapPath']):
            self.cust_smap_path.setText(self.prefs['useSmapPath'])
        self.cust_smap_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_smap, self.choose_smap_button)

        self.css_grid = QGridLayout()
        self.checkbox_css = QCheckBox(self.groupBox)
        self.css_grid.addWidget(self.checkbox_css, 0, 0, 1, 1)
        self.cust_css_path = QLineEdit(self.groupBox)
        self.css_grid.addWidget(self.cust_css_path, 1, 0, 1, 1)
        self.choose_css_button = QPushButton(self.groupBox)
        self.choose_css_button.setText('...')
        self.css_grid.addWidget(self.choose_css_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.css_grid)
        self.checkbox_css.setChecked(self.prefs['useCss'])
        self.checkbox_css.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_css, self.choose_css_button))
        self.choose_css_button.clicked.connect(
            lambda: self.fileChooser('css', self.cust_css_path, self.
                                     checkbox_css, self.choose_css_button))
        if len(self.prefs['useCssPath']):
            self.cust_css_path.setText(self.prefs['useCssPath'])
        self.cust_css_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_css, self.choose_css_button)

        main_layout.addWidget(self.groupBox)
        self.checkbox_debug = QCheckBox()
        main_layout.addWidget(self.checkbox_debug)
        self.checkbox_debug.setChecked(self.prefs['debug'])

        spacerItem = QSpacerItem(20, 15, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        main_layout.addItem(spacerItem)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self._cancel_clicked)
        main_layout.addWidget(button_box)
        self.retranslateUi(self)
        if self.prefs['qt_geometry'] is not None:
            try:
                self.restoreGeometry(
                    QByteArray.fromHex(
                        self.prefs['qt_geometry'].encode('ascii')))
            except Exception:
                pass
        self.show()
Exemple #10
0
    def _init_widgets(self):
        try:
            from tracer import QEMURunner
        except:
            QMessageBox.about(self, 'Error', f"Unable to import QEMURunner, install angr tracer")
            self.close()

        self.setWindowTitle('New trace state')
        container = QVBoxLayout()
        layout = QGridLayout()
        row = 0

        args_label = QLabel(self)
        args_label.setText("Command-line arguments:")
        layout.addWidget(args_label, row, 0)
        row += 1

        args = QLineEdit(self)
        bin_name = str(self.instance.project).split(" ")[1][:-1]
        args.setText(bin_name)
        layout.addWidget(args, row, 0)
        row += 1

        input_label = QLabel(self)
        input_label.setText("Input:")
        layout.addWidget(input_label, row, 0)
        row += 1

        input_box = QPlainTextEdit()
        input_box.setWordWrapMode(QTextOption.WordWrap)
        layout.addWidget(input_box, row, 0)
        row += 1

        addr_label = QLabel(self)
        addr_label.setText("Stop address:")
        layout.addWidget(addr_label, row, 0)
        row += 1

        addr_box = QLineEdit(self)
        layout.addWidget(addr_box, row, 0)
        row += 1

        def parse_address():
            txt = addr_box.text()
            try:
                return self.instance.project.kb.labels.lookup(txt)
            except KeyError:
                pass

            try:
                return int(txt, 16)
            except ValueError:
                return None

        ok_button = QPushButton(self)
        ok_button.setText('OK')
        def do_ok():
            argv = shlex.split(args.text())
            inp = bytes(input_box.toPlainText().encode('latin-1'))
            addr = parse_address()

            try:
                p = self.instance.project
                r = QEMURunner(binary=bin_name,
                               argv=argv,
                               input=inp,
                               project=p)

                s = p.factory.entry_state(
                        mode='tracing',
                        stdin=angr.SimFileStream)
                s.preconstrainer.preconstrain_file(inp, s.posix.stdin, True)

                sm = p.factory.simgr(
                    s,
                    save_unsat=True,
                    hierarchy=False,
                    save_unconstrained=r.crash_mode)

                t = sm.use_technique(
                    angr.exploration_techniques.Tracer(
                        trace=r.trace,
                        resiliency=True,
                        keep_predecessors=1,
                        crash_addr=r.crash_addr))
                sm.use_technique(angr.exploration_techniques.Oppologist())
                sm.explore(find=addr)

                # add state to global state store
                state = sm.traced[0] if len(sm.traced) > 0 else sm.found[0]
                name = f"{hex(state.addr)} trace"
                state.gui_data.base_name = name
                state.gui_data.is_base = True
                state.gui_data.name = name
                state.gui_data.is_original = True
                self.instance.states.append(state)
                self._base_state_combo.refresh()
                for i in range(self._base_state_combo.count()):
                    if self._base_state_combo.itemText(i) == name:
                        self._base_state_combo.setCurrentIndex(i)
                self._address_box.setText(hex(state.addr))

                self.close()
            except Exception as e:
                QMessageBox.about(self, 'Error', f"{repr(e)}")

        ok_button.clicked.connect(do_ok)

        cancel_button = QPushButton(self)
        cancel_button.setText('Cancel')
        def do_cancel():
            self.close()
        cancel_button.clicked.connect(do_cancel)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)

        container.addLayout(layout)
        container.addLayout(buttons_layout)

        self.setLayout(container)
        self.exec_()
Exemple #11
0
    def _init_widgets(self):

        # the instruction
        instr_lbl = QLabel("Instruction")
        instr_box = QLineEdit("TODO")
        instr_box.setReadOnly(True)

        self._instr_layout = QHBoxLayout()
        self._instr_layout.addWidget(instr_lbl)
        self._instr_layout.addWidget(instr_box)

        # the function
        func_lbl = QLabel("Function")
        func_box = QLineEdit("TODO")
        func_box.setReadOnly(True)

        self._func_layout = QHBoxLayout()
        self._func_layout.addWidget(func_lbl)
        self._func_layout.addWidget(func_box)

        #
        # location
        #
        location_group = QGroupBox("Location")

        self._before_radio = QRadioButton("Before the instruction")
        self._after_radio = QRadioButton("After the instruction")
        location_layout = QVBoxLayout()
        location_layout.addWidget(self._before_radio)
        location_layout.addWidget(self._after_radio)
        location_layout.addStretch(1)

        self._before_radio.setChecked(True)

        location_group.setLayout(location_layout)

        #
        # target atoms
        #

        # function argument
        self._arg_radiobox = QRadioButton("Function argument")
        self._arg_radiobox.clicked.connect(self._on_targetatoms_radiobutton_clicked)
        self._arg_box = QLineEdit("0")

        # register
        self._reg_radiobox = QRadioButton("Register")
        self._reg_radiobox.clicked.connect(self._on_targetatoms_radiobutton_clicked)
        self._reg_box = QLineEdit("")

        atom_type_group = QGroupBox("Atom type")
        atom_type_layout = QVBoxLayout()
        atom_type_layout.addWidget(self._arg_radiobox)
        # atom_type_layout.addWidget(self._reg_radiobox)
        atom_type_layout.addStretch(1)
        atom_type_group.setLayout(atom_type_layout)

        atom_layout = QVBoxLayout()
        arg_layout = QHBoxLayout()
        arg_lbl = QLabel("Argument index")
        self._arg_widget = QWidget()
        self._arg_widget.setLayout(arg_layout)
        arg_layout.addWidget(arg_lbl)
        arg_layout.addWidget(self._arg_box)

        reg_layout = QHBoxLayout()
        reg_lbl = QLabel("Register name")
        self._reg_widget = QWidget()
        self._reg_widget.setLayout(reg_layout)
        reg_layout.addWidget(reg_lbl)
        reg_layout.addWidget(self._reg_box)

        atom_layout.addWidget(self._arg_widget)
        atom_layout.addWidget(self._reg_widget)

        self._arg_radiobox.setChecked(True)
        self._reg_widget.setHidden(True)

        #
        # buttons
        #
        ok_btn = QPushButton("OK")
        ok_btn.clicked.connect(self._on_ok_clicked)
        cancel_btn = QPushButton("Cancel")
        cancel_btn.clicked.connect(self._on_cancel_clicked)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_btn)
        buttons_layout.addWidget(cancel_btn)

        layout = QVBoxLayout()
        if self._function is not None:
            func_box.setText(function_prototype_str(self._function))
            layout.addLayout(self._func_layout)
        else:
            layout.addLayout(self._instr_layout)
        layout.addWidget(location_group)
        layout.addWidget(atom_type_group)
        layout.addLayout(atom_layout)
        layout.addLayout(buttons_layout)

        self.setLayout(layout)
Exemple #12
0
class MainWindow(QMainWindow):
    """Main class for interacting with the applications GUI."""
    @Slot(str)
    def startProgress(self, message):
        """Shows that the window is busy doing some work."""
        self.translateButton.setEnabled(False)
        self.dictsCombo.setEnabled(False)
        label = QLabel(message)
        label.setAlignment(Qt.AlignHCenter)
        progressBar = QProgressBar()
        progressBar.setRange(0, 0)
        self.statusBar().clearMessage()
        self.statusBar().addWidget(label, 1)
        self.statusBar().addWidget(progressBar, 1)
        QGuiApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

    @Slot()
    def endProgress(self):
        """Shows that the window is ready for the interaction."""
        self.statusBar().setParent(None)
        self.statusBar().showMessage(self.tr("Done"), 2000)
        QGuiApplication.restoreOverrideCursor()
        self.translateButton.setEnabled(True)
        self.dictsCombo.setEnabled(True)

    @Slot()
    def about(self):
        """Shows the "about" message box."""
        title = self.tr("About FreeLingvo")
        text = self.tr(
            "<b>FreeLingvo</b> is a dictionary search application"
            " that can work with over 140 dictionaries without"
            " Internet connection and is available under the"
            " GNU General Public License v3.<br><br>"
            "To search for translations in the selected"
            " dictionary, you must enter the desired word"
            " in the field and press \"Enter\" or click the"
            " \"translate\" button. You can also enter a sentence."
            " In this case, the sentence will be divided into"
            " separate words and possible combinations of these words."
            " The program will search for each word and combination"
            " in the selected dictionary, in which case the"
            " output can be large.<br><br>"
            "<b>Homepage:</b>"
            "<a href=\"https://github.com/ache2014/FreeLingvo\">"
            " GitHub</a><br>"
            "<b>Contact:</b>"
            "<a href=\"mailto:[email protected]\">"
            " [email protected]</a>")
        QMessageBox.about(self, title, text)

    @Slot(list)
    def showTranslations(self, translations):
        """Shows translations in the translations browser"""
        if translations:
            text = "<hr>".join(translations)
        else:
            text = self.tr("Sorry, no translations were found for:")
            text += "<br><b>{}</b>".format(self.searchText.text())
        cursor = self.translationsBrowser.textCursor()
        cursor.select(QTextCursor.Document)
        cursor.insertHtml(text)

    @Slot(str)
    def changeFontSize(self, size):
        """Changes the font size for the translations browser."""
        self.translationsBrowser.setFont(QFont(self.font().family(),
                                               int(size)))
        self.update()

    def __init__(self, parent=None, *args, appctxt=None, **kwargs):
        """Initializes all GUI elements and a separate thread."""
        super().__init__(parent)
        self.appctxt = appctxt
        self.worker = Worker(self)
        self.workerThread = QThread()
        self.worker.moveToThread(self.workerThread)
        self.workerThread.finished.connect(self.worker.deleteLater)
        self.worker.started.connect(self.startProgress)
        self.worker.ended.connect(self.endProgress)
        self.worker.translationsReady.connect(self.showTranslations)
        self.workerThread.start()

        screenGeometry = QGuiApplication.screens()[0].geometry()
        self.setGeometry(screenGeometry.width() / 5,
                         screenGeometry.height() / 5,
                         screenGeometry.width() / 3,
                         screenGeometry.height() / 3)
        self.setMinimumSize(screenGeometry.width() / 4,
                            screenGeometry.height() / 4)

        self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
        self.exitAct = self.fileMenu.addAction(self.tr("&Exit"))
        self.exitAct.setStatusTip(self.tr("Exit from FreeLingvo"))
        self.exitAct.triggered.connect(self.close)

        self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
        self.aboutAct = self.helpMenu.addAction(self.tr("&About"))
        self.aboutAct.setStatusTip(
            self.tr("Show information about FreeLingvo"))
        self.aboutAct.triggered.connect(self.about)

        self.searchText = QLineEdit()
        self.searchText.setPlaceholderText(
            self.tr("What word(s) to look for?"))
        self.searchText.setClearButtonEnabled(True)
        self.searchText.returnPressed.connect(self.worker.findTranslations)

        self.translateButton = QPushButton(self.tr("Translate"))
        self.translateButton.clicked.connect(self.worker.findTranslations)

        self.dictsCombo = QComboBox()
        self.dictsCombo.setInsertPolicy(QComboBox.InsertAlphabetically)
        self.dictsCombo.setToolTip(
            self.tr("Dictionary used to search for words"))
        dictNames = os.listdir(self.appctxt.get_resource("dictionaries"))
        dictNames = [name.replace(".tei", "") for name in dictNames]
        self.dictsCombo.addItems(dictNames)
        self.dictsCombo.currentIndexChanged[str].connect(self.worker.loadDict)
        self.dictsCombo.setCurrentIndex(1)

        self.translationsBrowser = QTextBrowser()
        self.translationsBrowser.setUndoRedoEnabled(True)

        self.undoButton = QPushButton(
            QIcon(self.appctxt.get_resource("images/arrow_back.png")), "")
        self.undoButton.setEnabled(False)
        self.undoButton.setToolTip(self.tr("Show previous translation"))
        self.undoButton.clicked.connect(self.translationsBrowser.undo)
        self.translationsBrowser.undoAvailable.connect(
            self.undoButton.setEnabled)

        self.redoButton = QPushButton(
            QIcon(self.appctxt.get_resource("images/arrow_forward.png")), "")
        self.redoButton.setEnabled(False)
        self.redoButton.setToolTip(self.tr("Show next translation"))
        self.redoButton.clicked.connect(self.translationsBrowser.redo)
        self.translationsBrowser.redoAvailable.connect(
            self.redoButton.setEnabled)

        self.sizeLabel = QLabel(self.tr("Font size:"))
        self.sizeCombo = QComboBox()
        for size in QFontDatabase.standardSizes():
            self.sizeCombo.addItem(str(size))
        self.sizeCombo.setCurrentText(str(self.font().pointSize()))
        self.sizeCombo.currentIndexChanged[str].connect(self.changeFontSize)

        self.controlsLayout = QHBoxLayout()
        self.controlsLayout.addWidget(self.searchText)
        self.controlsLayout.addWidget(self.translateButton)
        self.controlsLayout.addWidget(self.dictsCombo)

        self.browserToolsLayout = QHBoxLayout()
        self.browserToolsLayout.addWidget(self.undoButton)
        self.browserToolsLayout.addWidget(self.redoButton)
        self.browserToolsLayout.addStretch(1)
        self.browserToolsLayout.addWidget(self.sizeLabel)
        self.browserToolsLayout.addWidget(self.sizeCombo)

        self.centralLayout = QVBoxLayout()
        self.centralLayout.addLayout(self.controlsLayout)
        self.centralLayout.addLayout(self.browserToolsLayout)
        self.centralLayout.addWidget(self.translationsBrowser)

        centralWidget = QWidget()
        centralWidget.setLayout(self.centralLayout)
        self.setCentralWidget(centralWidget)

        self.statusBar().showMessage(self.tr("Ready"), 2000)

    def closeEvent(self, event):
        """Destroys the thread properly before exiting."""
        self.workerThread.quit()
        self.workerThread.wait()
        super().closeEvent(event)
Exemple #13
0
    def __init__(self, parent, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.currentRootPath = '/'
        self.currentPath = QDir.currentPath()

        self.mainWindow = parent

        self.chooseDirAction = QAction(IconFactory.getIcon('folder'),
                                       'Root directory',
                                       self,
                                       statusTip="Change root directory",
                                       triggered=self.chooseRootDir)
        self.showOFAction = QAction(IconFactory.getIcon('filter_alt'),
                                    'Show only FITS files',
                                    self,
                                    statusTip="Show only FITS/all files",
                                    triggered=self.showOFFiles)
        self.showOFAction.setCheckable(True)
        self.showOFAction.toggled.connect(self.showOFFiles)

        self.chooseDirBtn = QToolButton()
        self.chooseDirBtn.setDefaultAction(self.chooseDirAction)

        self.showOFBtn = QToolButton()
        self.showOFBtn.setDefaultAction(self.showOFAction)

        iconlayout = QHBoxLayout()
        iconlayout.setAlignment(Qt.AlignLeft)
        iconlayout.addWidget(self.chooseDirBtn)
        iconlayout.addWidget(self.showOFBtn)

        self.viewsSplitter = QSplitter(Qt.Horizontal)
        self.viewsSplitter.splitterMoved.connect(self.splitterMoved)

        self.dirsModel = QFileSystemModel(self)
        self.dirsModel.setOption(QFileSystemModel.DontWatchForChanges, True)
        self.dirsModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)
        self.dirsModel.setNameFilterDisables(False)

        self.dirs = QTreeView()
        self.dirs.setModel(self.dirsModel)
        self.dirs.hideColumn(1)
        self.dirs.hideColumn(2)
        self.dirs.hideColumn(3)

        self.dirs.clicked.connect(self.onDirsClick)
        self.dirs.doubleClicked.connect(self.onDirsDoubleClick)

        self.filesModel = QFileSystemModel(self)
        self.filesModel.setOption(QFileSystemModel.DontWatchForChanges, True)
        self.filesModel.setFilter(QDir.NoDotAndDotDot | QDir.Files)
        self.filesModel.setNameFilterDisables(False)

        self.files = QListView()
        self.files.setModel(self.filesModel)
        self.files.doubleClicked.connect(self.onFilesDoubleClick)

        self.viewsSplitter.addWidget(self.dirs)
        self.viewsSplitter.addWidget(self.files)
        viewslayout = QHBoxLayout()
        viewslayout.addWidget(self.viewsSplitter)

        layout = QVBoxLayout()
        layout.addLayout(iconlayout)
        layout.addLayout(viewslayout)

        self.setLayout(layout)

        self.dirsModel.setRootPath(self.currentRootPath)
        self.dirs.setRootIndex(self.dirsModel.index(self.currentRootPath))

        index = self.dirsModel.index(self.currentPath)
        self.dirs.setCurrentIndex(index)
        self.dirs.setExpanded(index, True)

        self.filesModel.setRootPath(self.currentPath)
        self.files.setRootIndex(self.filesModel.index(self.currentPath))
Exemple #14
0
    def ui(self):
        self.setMaximumSize(10000, 100)  # 限制高度
        self.setMinimumSize(10, 100)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        self.mainLayout = QHBoxLayout()  # 总体布局

        # 文件管理布局
        saveButton = ToolButton(QIcon("../../images/save.png"),
                                "",
                                toolTip="保存",
                                clicked=self.saveDocument,
                                shortcut="ctr+s")
        saveAsButton = ToolButton(QIcon("../../images/saveas.png"),
                                  "",
                                  toolTip="另存为",
                                  clicked=self.saveDocumentAs,
                                  shortcut="ctr+shift+s")
        openButton = ToolButton(QIcon("../../images/open.png"),
                                "",
                                toolTip="打开",
                                clicked=self.openDocument,
                                shortcut="ctr+o")
        newButton = ToolButton(QIcon("../../images/new.png"), "", toolTip="新建")

        fileLayout = QGridLayout()
        fileLayout.addWidget(newButton, 0, 0)
        fileLayout.addWidget(openButton, 0, 1)
        fileLayout.addWidget(saveButton, 1, 0)
        fileLayout.addWidget(saveAsButton, 1, 1)

        # 字体布局
        GlobalVars.titleLevelsPanel = TitleLevelsPanel(
            func=self.setTitleLevel)  # func绑定到函数,修改标题等级时候调用
        GlobalVars.CurrentTitleLevel = GlobalVars.CurrentTitleLevel  # 重新赋值,刷新界面

        GlobalVars.currentFontFamilyPanel = LineEditWithSubButton(
            self, toolTip="选择字体", subButton="itemButton")
        GlobalVars.currentFontFamilyPanel.listWidget = FontFamiliesPanel(
            self.parent(), func=self.setFontFamily)

        GlobalVars.currentFontSizePanel = LineEditWithSubButton(
            self, toolTip="字体大小", subButton="itemButton")
        GlobalVars.currentFontSizePanel.listWidget = FontSizePanel(
            self.parent(), func=self.setFontSize)

        # 斜体设置
        GlobalVars.currentFontItalicPanel = ToolButton(
            clicked=self.setFontItalic, subButton="itemButton")  # 斜体面板
        GlobalVars.currentFontItalicPanel.listWidget.addItem(
            ToolButton(icon=QIcon("../../images/italic.png"),
                       toolTip="斜体",
                       clicked=lambda: self.setFontItalic(True)))
        GlobalVars.currentFontItalicPanel.listWidget.addItem(
            ToolButton(icon=QIcon("../../images/notitalic.png"),
                       toolTip="取消斜体",
                       clicked=lambda: self.setFontItalic(False)))

        GlobalVars.currentFontItalicPanel.listWidget.setParent(
            self.parent())  # 设置父对象
        # 粗体设置 待完善,不同的粗度
        GlobalVars.currentFontWeightPanel = ToolButton(
            self, clicked=self.setFontWeight, subButton="itemButton")  # 加粗面板
        GlobalVars.currentFontWeightPanel.listWidget.addItem(
            ToolButton(icon=QIcon("../../images/bold.png"),
                       toolTip="加粗",
                       clicked=lambda: self.setFontWeight(QFont.Bold)))
        GlobalVars.currentFontWeightPanel.listWidget.addItem(
            ToolButton(icon=QIcon("../../images/unbold.png"),
                       toolTip="取消加粗",
                       clicked=lambda: self.setFontWeight(False)))
        GlobalVars.currentFontWeightPanel.listWidget.setParent(
            self.parent())  # doc是listwidget的父级
        GlobalVars.CurrentFont = GlobalVars.CurrentFont  # 更新与文字相关属性面板

        GlobalVars.currentTextColorPanel = ToolButton(
            "A", toolTip="设置文字颜色", clicked=self.setTextColor)
        GlobalVars.CurrentTextColor = GlobalVars.CurrentTextColor  # 重新赋值,刷新界面

        GlobalVars.currentBackgroundColorPanel = ToolButton(
            toolTip="设置背景色", clicked=self.setBackgroundColor)
        GlobalVars.CurrentBackgroundColor = GlobalVars.CurrentBackgroundColor  # 重新赋值,刷新界面

        GlobalVars.currentKeyWordStatusPanel = ToolButton(
            "关", toolTip="设置为关键字")  # 待完善
        GlobalVars.currentKeyWordStatusPanel.setEnabled(False)
        GlobalVars.currentLinkStatusPanel = ToolButton("链",
                                                       toolTip="设置为超链接")  # 待完善
        GlobalVars.currentLinkStatusPanel.setEnabled(False)

        GlobalVars.currentFontSuperScriptPanel = ToolButton(
            icon=QIcon("../../images/superscript.png"), toolTip="上标")  # 上标待完善
        GlobalVars.currentFontSuperScriptPanel.setEnabled(False)
        GlobalVars.currentFontSubScriptPanel = ToolButton(
            icon=QIcon("../../images/subscript.png"), toolTip="下标")  # 下标待完善
        GlobalVars.currentFontSubScriptPanel.setEnabled(False)

        font1Layout = QHBoxLayout()
        font1Layout.addWidget(GlobalVars.currentFontFamilyPanel)
        font1Layout.addWidget(GlobalVars.currentFontSizePanel)
        font2Layout = QHBoxLayout()
        font2Layout.addWidget(GlobalVars.currentKeyWordStatusPanel)
        font2Layout.addWidget(GlobalVars.currentLinkStatusPanel)
        font2Layout.addWidget(GlobalVars.currentFontSuperScriptPanel)
        font2Layout.addWidget(GlobalVars.currentFontSubScriptPanel)
        font2Layout.addWidget(GlobalVars.currentFontItalicPanel)
        font2Layout.addWidget(GlobalVars.currentFontWeightPanel)
        font2Layout.addWidget(GlobalVars.currentTextColorPanel)
        font2Layout.addWidget(GlobalVars.currentBackgroundColorPanel)
        fontLayout = QVBoxLayout()
        fontLayout.addLayout(font1Layout)
        fontLayout.addLayout(font2Layout)

        # 段落相关设置
        GlobalVars.alignLeftPanel = ToolButton(
            QIcon("../../images/alignleft.png"), "", toolTip="左对齐")  # 待完善
        GlobalVars.alignLeftPanel.setEnabled(False)
        GlobalVars.alignCenterPanel = ToolButton(
            QIcon("../../images/aligncenter.png"), "", toolTip="中对齐")  # 待完善
        GlobalVars.alignCenterPanel.setEnabled(False)
        GlobalVars.alignRightPanel = ToolButton(
            QIcon("../../images/alignright.png"), "", toolTip="右对齐")  # 待完善
        GlobalVars.alignRightPanel.setEnabled(False)

        GlobalVars.currentLineSpacingPanel = LineEditWithSubButton(
            toolTip="设置行距大小", subButton="itemButton")
        GlobalVars.currentLineSpacingPanel.listWidget = LineSpacingPanel(
            self.parent(), func=self.setLineSpacing)
        GlobalVars.CurrentLineSpacing = GlobalVars.CurrentLineSpacing

        GlobalVars.currentLineSpacingPolicyPanel = ToolButton(
            clicked=self.setLineSpacingPolicy, subButton="itemButton")
        GlobalVars.currentLineSpacingPolicyPanel.listWidget.addItem(
            ToolButton(icon=QIcon("../../images/absolute_linespacing.png"),
                       toolTip="绝对行距",
                       clicked=lambda: self.setLineSpacingPolicy(
                           GlobalVars.absLineSpacingPolicy)))
        GlobalVars.currentLineSpacingPolicyPanel.listWidget.addItem(
            ToolButton(icon=QIcon("../../images/relative_linespacing.png"),
                       toolTip="相对行距",
                       clicked=lambda: self.setLineSpacingPolicy(
                           GlobalVars.relLineSpacingPolicy)))
        GlobalVars.currentLineSpacingPolicyPanel.listWidget.setParent(
            self.parent())
        GlobalVars.CurrentLineSpacingPolicy = GlobalVars.CurrentLineSpacingPolicy  # 更新界面

        paragraph1Layout = QHBoxLayout()
        paragraph1Layout.addWidget(GlobalVars.currentLineSpacingPanel)
        paragraph2Layout = QHBoxLayout()
        paragraph2Layout.addWidget(GlobalVars.alignLeftPanel)
        paragraph2Layout.addWidget(GlobalVars.alignCenterPanel)
        paragraph2Layout.addWidget(GlobalVars.alignRightPanel)
        paragraph2Layout.addWidget(GlobalVars.currentLineSpacingPolicyPanel)
        paragraphLayout = QVBoxLayout()
        paragraphLayout.addLayout(paragraph1Layout)
        paragraphLayout.addLayout(paragraph2Layout)

        self.mainLayout.addLayout(fileLayout)
        self.mainLayout.addWidget(GlobalVars.titleLevelsPanel)
        self.mainLayout.addLayout(fontLayout)
        self.mainLayout.addLayout(paragraphLayout)

        self.setLayout(self.mainLayout)

        self.setAutoFillBackground(True)
        pal = QPalette()
        pal.setColor(QPalette.Background, GlobalVars.Panel_BackgroundColor)
        self.setPalette(pal)
    def __init__(self, squadron: Squadron, theater: ConflictTheater) -> None:
        super().__init__()
        self.squadron = squadron
        self.reset_title()

        columns = QHBoxLayout()
        self.setLayout(columns)

        left_column = QVBoxLayout()
        columns.addLayout(left_column)

        left_column.addWidget(QLabel("Name:"))
        self.name_edit = QLineEdit(squadron.name)
        self.name_edit.textChanged.connect(self.on_name_changed)
        left_column.addWidget(self.name_edit)

        nickname_edit_layout = QGridLayout()
        left_column.addLayout(nickname_edit_layout)

        nickname_edit_layout.addWidget(QLabel("Nickname:"), 0, 0, 1, 2)
        self.nickname_edit = QLineEdit(squadron.nickname)
        self.nickname_edit.textChanged.connect(self.on_nickname_changed)
        nickname_edit_layout.addWidget(self.nickname_edit, 1, 0, Qt.AlignTop)
        reroll_nickname_button = QToolButton()
        reroll_nickname_button.setIcon(QIcon(ICONS["Reload"]))
        reroll_nickname_button.setToolTip("Re-roll nickname")
        reroll_nickname_button.clicked.connect(self.reroll_nickname)
        nickname_edit_layout.addWidget(reroll_nickname_button, 1, 1,
                                       Qt.AlignTop)

        left_column.addWidget(QLabel("Base:"))
        self.base_selector = SquadronBaseSelector(
            theater.control_points_for(squadron.player),
            squadron.location,
            squadron.aircraft,
        )
        self.base_selector.currentIndexChanged.connect(self.on_base_changed)
        left_column.addWidget(self.base_selector)

        if squadron.player:
            player_label = QLabel(
                "Players (one per line, leave empty for an AI-only squadron):")
        else:
            player_label = QLabel("Player slots not available for opfor")
        left_column.addWidget(player_label)

        players = [p for p in squadron.pilot_pool if p.player]
        for player in players:
            squadron.pilot_pool.remove(player)
        if not squadron.player:
            players = []
        self.player_list = QTextEdit("<br />".join(p.name for p in players))
        self.player_list.setAcceptRichText(False)
        self.player_list.setEnabled(squadron.player)
        left_column.addWidget(self.player_list)
        delete_button = QPushButton("Remove Squadron")
        delete_button.setMaximumWidth(140)
        delete_button.clicked.connect(self.remove_from_squadron_config)
        left_column.addWidget(delete_button)
        left_column.addStretch()

        self.allowed_missions = AllowedMissionTypeControls(squadron)
        columns.addLayout(self.allowed_missions)
Exemple #16
0
    def __init__(self, image, parent=None):
        super(PcaWidget, self).__init__(parent)

        self.comp_combo = QComboBox()
        self.comp_combo.addItems(
            [self.tr('#{}'.format(i + 1)) for i in range(3)])

        self.distvect_radio = QRadioButton(self.tr('Vector Distance'))
        self.cross_radio = QRadioButton(self.tr('Cross Correlation'))
        self.distvect_radio.setChecked(True)
        self.last_radio = self.distvect_radio

        self.image = image
        self.components = []
        rows, cols, dims = self.image.shape
        bgr = np.reshape(self.image, (rows * cols, dims)).astype(np.float32)
        m, eigen_vec, eigen_val = cv.PCACompute2(bgr, np.array([]))
        p = self.image.astype(np.float32) - m
        for v in eigen_vec:
            c = np.cross(p, v)
            d = np.linalg.norm(c, axis=2) / np.linalg.norm(v)
            distance = normalize_mat(d, to_bgr=True)
            cross = cv.merge([normalize_mat(x) for x in cv.split(c)])
            self.components.extend([distance, cross])

        table_data = [[m[0, 2], m[0, 1], m[0, 0]],
                      [eigen_vec[0, 2], eigen_vec[0, 1], eigen_vec[0, 0]],
                      [eigen_vec[1, 2], eigen_vec[1, 1], eigen_vec[1, 0]],
                      [eigen_vec[2, 2], eigen_vec[2, 1], eigen_vec[2, 0]],
                      [eigen_val[2, 0], eigen_val[1, 0], eigen_val[0, 0]]]
        table_widget = QTableWidget(5, 4)
        table_widget.setHorizontalHeaderLabels([
            self.tr('Element'),
            self.tr('Red'),
            self.tr('Green'),
            self.tr('Blue')
        ])
        table_widget.setItem(0, 0, QTableWidgetItem(self.tr('Mean color')))
        table_widget.setItem(1, 0, QTableWidgetItem(self.tr('Eigen vect 1')))
        table_widget.setItem(2, 0, QTableWidgetItem(self.tr('Eigen vect 2')))
        table_widget.setItem(3, 0, QTableWidgetItem(self.tr('Eigen vect 3')))
        table_widget.setItem(4, 0, QTableWidgetItem(self.tr('Eigen values')))
        for i in range(len(table_data)):
            modify_font(table_widget.item(i, 0), bold=True)
            for j in range(len(table_data[i])):
                table_widget.setItem(i, j + 1,
                                     QTableWidgetItem(str(table_data[i][j])))
        # item = QTableWidgetItem()
        # item.setBackgroundColor(QColor(m[0, 2], m[0, 1], m[0, 0]))
        # table_widget.setItem(0, 4, item)
        # table_widget.resizeRowsToContents()
        # table_widget.resizeColumnsToContents()
        table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        table_widget.setSelectionMode(QAbstractItemView.SingleSelection)

        self.viewer = ImageViewer(self.image, self.image, None)
        self.process()

        self.comp_combo.currentIndexChanged.connect(self.process)
        self.distvect_radio.toggled.connect(self.process)
        self.cross_radio.toggled.connect(self.process)

        top_layout = QHBoxLayout()
        top_layout.addWidget(QLabel(self.tr('Component:')))
        top_layout.addWidget(self.comp_combo)
        top_layout.addWidget(QLabel(self.tr('Projection:')))
        top_layout.addWidget(self.distvect_radio)
        top_layout.addWidget(self.cross_radio)
        top_layout.addStretch()
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(table_widget)

        main_layout = QVBoxLayout()
        main_layout.addLayout(top_layout)
        main_layout.addWidget(self.viewer)
        main_layout.addLayout(bottom_layout)
        self.setLayout(main_layout)
Exemple #17
0
    def __init__(self, name, parent, bv, db):
        QWidget.__init__(self, parent)
        DockContextHandler.__init__(self, self, name)

        self.hitcounts = []
        self.orig_hitcounts = []
        self.db = db
        self.bv = bv
        self.descending = True
        self.highlight = False
        self.current_page = 0

        self.hitcounts = self.db.get_hitcounts()
        self.orig_hitcounts = [e for e in self.hitcounts]

        self.actionHandler = UIActionHandler()
        self.actionHandler.setupActionHandler(self)

        vlayout = QVBoxLayout()

        # Top label
        self.hitcount_counter = QLabel("Basic block count: {}".format(
            self.db.hitcount_count))
        self.hitcount_counter.setAlignment(Qt.AlignLeft | Qt.AlignTop)

        # BB Hitcount table
        self.hit_table = QTableWidget(0, 3)
        self.hit_table.setHorizontalHeaderLabels(
            ["Address", "Hitcount", "Function"])
        self.hit_table.verticalHeader().hide()
        self.hit_table.horizontalHeader().setStretchLastSection(True)
        self.hit_table.itemDoubleClicked.connect(self._cb_table)
        self._render_page()

        # Option buttons
        optionslayout = QHBoxLayout()
        optionsbox = QGroupBox("Options")

        ascending_checkbox = QCheckBox("Sort ascending")
        highlight_checkbox = QCheckBox("Highlight basic blocks")

        ascending_checkbox.stateChanged.connect(self._cb_ascending)
        highlight_checkbox.stateChanged.connect(self._cb_highlight)

        optionslayout.addWidget(ascending_checkbox)
        optionslayout.addWidget(highlight_checkbox)
        optionsbox.setLayout(optionslayout)

        # Diffing buttons
        diffinglayout = QHBoxLayout()
        diffingoptions = QGroupBox("Diffing")

        diffing_reset_button = QPushButton("Reset")
        diffing_diff_button = QPushButton("Difference")
        diffing_inter_button = QPushButton("Intersection")

        diffing_reset_button.clicked.connect(self._cb_diff_reset)
        diffing_diff_button.clicked.connect(self._cb_diff_diff)
        diffing_inter_button.clicked.connect(self._cb_diff_inter)

        diffinglayout.addWidget(diffing_diff_button)
        diffinglayout.addWidget(diffing_inter_button)
        diffinglayout.addWidget(diffing_reset_button)

        diffingoptions.setLayout(diffinglayout)

        # Bottom buttons for page change
        prevnextlayout = QHBoxLayout()
        self.back_button = QPushButton("<")
        self.next_button = QPushButton(">")
        self.page_count_label = QLabel("")
        self.page_count_label.setAlignment(Qt.AlignCenter)
        self._render_nav_line()

        self.back_button.clicked.connect(self._cb_prev_page)
        self.next_button.clicked.connect(self._cb_next_page)

        prevnextlayout.addWidget(self.back_button)
        prevnextlayout.addWidget(self.page_count_label)
        prevnextlayout.addWidget(self.next_button)

        vlayout.addWidget(self.hitcount_counter)
        vlayout.addWidget(self.hit_table)
        vlayout.addWidget(optionsbox)
        vlayout.addWidget(diffingoptions)
        vlayout.addLayout(prevnextlayout)

        self.setLayout(vlayout)
Exemple #18
0
    def __init__(self, *args, **kwargs):
        super(SpotPriceUI, self).__init__(*args, **kwargs)
        self.extra_data_widget = QWidget(self)
        # 提取数据tab
        layout = QVBoxLayout()
        # 现货价格源数据
        source_layout = QHBoxLayout()
        self.current_date = QDateEdit(self)
        self.current_date.setDisplayFormat("yyyy-MM-dd")
        self.current_date.setDate(QDate.currentDate())
        self.current_date.setCalendarPopup(True)
        source_layout.addWidget(self.current_date)

        source_layout.addWidget(QLabel("源数据:", self))
        self.source_edit = QLineEdit(self)
        source_layout.addWidget(self.source_edit)
        layout.addLayout(source_layout)
        # 分析
        analysis_layout = QHBoxLayout()
        self.analysis_button = QPushButton("提取数据", self)
        analysis_layout.addWidget(self.analysis_button)

        self.tip_label = QLabel("输入源数据后,点击提取数据进行数据提取.", self)
        analysis_layout.addWidget(self.tip_label)
        analysis_layout.addStretch()
        layout.addLayout(analysis_layout)

        # 预览数据的表格
        self.preview_table = QTableWidget(self)
        self.preview_table.setColumnCount(5)
        self.preview_table.setHorizontalHeaderLabels(["日期", "品种", "交易代码", "现货价", "增减"])
        layout.addWidget(self.preview_table)

        # 提交按钮
        commit_layout = QHBoxLayout()
        commit_layout.addStretch()
        self.commit_button = QPushButton("确认提交", self)
        commit_layout.addWidget(self.commit_button)
        layout.addLayout(commit_layout)

        self.extra_data_widget.setLayout(layout)

        self.addTab(self.extra_data_widget, "数据提取")   # 提取数据tab

        # 修改数据的tab
        self.modify_data_widget = QWidget(self)
        modify_layout = QVBoxLayout()
        params_layout = QHBoxLayout()
        params_layout.addWidget(QLabel("选择日期:", self))
        self.modify_date_edit = QDateEdit(self)
        self.modify_date_edit.setDate(QDate.currentDate())
        self.modify_date_edit.setCalendarPopup(True)
        self.modify_date_edit.setDisplayFormat("yyyy-MM-dd")
        params_layout.addWidget(self.modify_date_edit)
        self.modify_query_button = QPushButton("查询", self)
        params_layout.addWidget(self.modify_query_button)
        self.modify_tip_label = QLabel("选择日期查询出数据,双击要修改的数据编辑正确的数据,点击行尾修改.", self)
        params_layout.addWidget(self.modify_tip_label)
        params_layout.addStretch()

        modify_layout.addLayout(params_layout)

        # 数据表格
        self.modify_table = QTableWidget(self)
        self.modify_table.setColumnCount(6)
        self.modify_table.setHorizontalHeaderLabels(["ID", "日期", "品种", "现货价", "增减", "修改"])
        modify_layout.addWidget(self.modify_table)

        self.modify_data_widget.setLayout(modify_layout)

        self.addTab(self.modify_data_widget, "修改数据")

        self.setStyleSheet(
            "#modifyButton{border:none;color:rgb(180,30,50)}#modifyButton:hover{color:rgb(20,50,160)}"
        )
class MainWidget(Widget):
    """
    Klasa główna wyświetlająca wszystkie niezbędne elementy w głównym oknie programu.
    """
    def __init__(self, user):
        super(MainWidget, self).__init__(user)
        self.que = queue.Queue()
        self.page_number = 1
        self.sorted_by = None
        self.sorted_direction = None
        self._txt_change_perm = 'Zmiana hasła'
        self._txt_permission = 'Utwórz konto z uprawnieniami'
        self._txt_bad_data = 'Błędne dane'
        self.page = 0
        self.lbl_page = QLabel()

        # Layouty
        self.layout = QVBoxLayout()
        self.menu_layout = QHBoxLayout()
        self.text_layout = QVBoxLayout()

        # Widgety
        self.btn_home = QPushButton('Strona główna')
        self.btn_my_book = QPushButton('Wypożyczone książki')
        self.btn_reserved = QPushButton('Zarezerwowane książki')
        self.btn_library = QPushButton('Biblioteka')
        self.btn_profile = QPushButton('Profil')
        self.btn_permission = QPushButton(self._txt_permission)
        self.btn_change_passwd = QPushButton(self._txt_change_perm)
        self.btn_set_permission = QPushButton('Uprawnienia')
        self.btn_logout = QPushButton('Wylogowanie')
        self.btn_add_book = QPushButton('Dodaj nową książkę')

        # Ustawienia widgetów
        self.menu_layout.setContentsMargins(-1, -1, -1, 25)
        self.btn_home.clicked.connect(self.on_home_clicked)
        if self.user.get('roleId') > 1:
            self.btn_my_book.clicked.connect(self.on_book_clicked_permission)
        else:
            self.btn_my_book.clicked.connect(self.on_book_clicked)
        self.btn_reserved.clicked.connect(self.on_reserved_clicked)
        self.btn_library.clicked.connect(self.on_library_clicked)
        self.btn_permission.clicked.connect(self.on_permission_clicked)
        if self.user.get('roleId') != 3:
            self.btn_change_passwd.clicked.connect(
                self.on_change_passwd_clicked)
            self.btn_profile.clicked.connect(self.on_profile_clicked)
        else:
            self.btn_profile.setText('Usuwanie profili')
            self.btn_change_passwd.clicked.connect(
                self.on_change_passwd_admin_clicked)
            self.btn_profile.clicked.connect(self.on_profile_admin_clicked)
        self.btn_set_permission.clicked.connect(self.on_set_permission_clicked)
        self.btn_logout.clicked.connect(self.on_logout_clicked)
        self.btn_next_page.clicked.connect(self.next_page)
        self.btn_back_page.clicked.connect(self.back_page)
        self.btn_add_book.clicked.connect(self.add_book)
        self.edit_search.returnPressed.connect(self.search)

        # Przypisanie widgetów do layoutów
        self.menu_layout.addWidget(self.btn_home)
        self.menu_layout.addWidget(self.btn_my_book)
        if self.user.get('roleId') == 1:
            self.menu_layout.addWidget(self.btn_reserved)
        self.menu_layout.addWidget(self.btn_library)
        self.menu_layout.addWidget(self.btn_profile)
        if self.user.get('roleId') == 3:
            self.menu_layout.addWidget(self.btn_permission)
            self.menu_layout.addWidget(self.btn_set_permission)
        self.menu_layout.addWidget(self.btn_change_passwd)
        self.menu_layout.addItem(self.h_spacer)
        self.menu_layout.addWidget(self.btn_logout)
        self.text_layout.addWidget(self.lbl_home)

        self.layout.addLayout(self.menu_layout)
        self.layout.addLayout(self.text_layout)

        self.setLayout(self.layout)

    def clear_layout(self):
        """
        Czyści layout głównego widżetu z pozostałych, niepotrzebnych  widgetów.
        """
        for i in reversed(range(self.text_layout.count())):
            self.text_layout.itemAt(i).widget().setParent(None)

    def on_home_clicked(self):
        """
        Wyświetla widgety strony głównej.
        """
        print("Home")
        self.clear_layout()
        self.text_layout.addWidget(self.lbl_home)

    def on_book_clicked(self, user_id=None):
        """
        Wyświetla wypożyczone książki danego użytkownika.
        :param user_id: int
        """
        print("My books")
        if user_id is None:
            self.clear_layout()
        self.tbl_result.clear()
        self.lbl_title.setText('Wypożyczone książki')
        self.text_layout.addWidget(self.lbl_title)
        if self.get_book_user_id(user_id):
            self.text_layout.addWidget(self.tbl_result)

    def on_reserved_clicked(self, user_id=None):
        """
        Wyświetla zarezerwowane książki danego użytkownika.
        """
        print("Reserved")
        self.clear_layout()
        self.tbl_result.clear()
        self.lbl_title.setText('Zarezerwowane książki')
        self.text_layout.addWidget(self.lbl_title)
        if self.get_reservation_user_id(user_id):
            self.text_layout.addWidget(self.tbl_result)

    def on_book_clicked_permission(self):
        """
        Dla konta z uprawnieniami, wyświetla tabelę użytkowników przed tabelą wypożyczonych książek.
        """
        print('Books permision')
        self.lbl_title.setText('Użytkownicy')
        self.tbl_result.clear()
        self.clear_layout()
        self.text_layout.addWidget(self.lbl_title)
        self.get_users()
        self.text_layout.addWidget(self.tbl_result)

    def next_page(self):
        """
        Wyświetla następną stronę książek w bibliotece.
        """
        self.page_number += 1
        self.lbl_page.setText('Strona {}/{}'.format(self.page_number,
                                                    self.page))
        if self.lbl_title.text() == 'Biblioteka':
            self.get_books(self.page_number,
                           search=self.edit_search.text(),
                           sort_by=self.sorted_by,
                           sort_direction=self.sorted_direction)

    def back_page(self):
        """
        Wyświetla poprzednią stronę książek w bibliotece.
        """
        self.page_number -= 1
        self.lbl_page.setText('Strona {}/{}'.format(self.page_number,
                                                    self.page))
        if self.lbl_title.text() == 'Biblioteka':
            self.get_books(self.page_number,
                           search=self.edit_search.text(),
                           sort_by=self.sorted_by,
                           sort_direction=self.sorted_direction)

    def search(self):
        """
        Wyszukuje odpowiednią frazę w kolumnach Tytuł, Wydawca, Autor, Opis.
        """
        self.page_number = 1
        if self.lbl_title.text() == 'Biblioteka':
            self.get_books(1,
                           search=self.edit_search.text(),
                           sort_direction=self.sorted_direction)

    def sort_direction(self, text):
        """
        Sortuje wyniki wyświetlania zawartości biblioteki rosnąco bądź malejąco.
        :param text: str
        """
        sort_dict = {'Rosnąco': 0, 'Malejąco': 1}
        self.page_number = 1
        self.sorted_direction = sort_dict.get(text)
        if self.lbl_title.text() == 'Biblioteka':
            self.get_books(1,
                           sort_by=self.sorted_by,
                           sort_direction=self.sorted_direction)

    def sort_by(self, text):
        """
        Sortuje wyniki wyświetlania zawartości biblioteki na podstawie Tytułu, Opisu, Kategorii, Wydawcy lub Daty
        wydania.
        :param text: str
        """
        sort_dict = {
            'Sortuj według': None,
            'Tytuł': 'BookName',
            'Opis': 'BookDescription',
            'Kategoria': 'Category',
            'Wydawca': 'PublisherName',
            'Data wydania': 'PublishDate'
        }
        self.page_number = 1
        self.sorted_by = sort_dict.get(text)
        if self.lbl_title.text() == 'Biblioteka':
            self.get_books(1,
                           sort_by=self.sorted_by,
                           sort_direction=self.sorted_direction)

    def on_library_clicked(self):
        """
        Wyświetla książki zawarte w bibliotece.
        """
        print("library")
        self.clear_layout()
        self.lbl_title.setText('Biblioteka')
        self.edit_search.setPlaceholderText('Wyszukaj i wciśnij ENTER')
        self.btn_delete_book.show()
        self.btn_borrow_book.show()
        self.text_layout.addWidget(self.lbl_title)
        self.text_layout.addWidget(self.library)
        self.text_layout.addWidget(self.tbl_result)
        self.text_layout.addWidget(self.btn_add_book)
        self.btn_add_book.setStyleSheet(
            "color: #17a2b8; border-color : #17a2b8")
        self.get_books(self.page_number)

        print(self.page_number, self.page)
        self.lbl_page.setText('Strona {}/{}'.format(self.page_number,
                                                    self.page))
        self.text_layout.addWidget(self.lbl_page)

    def on_profile_clicked(self):
        """
        Wyświetla dane profilu, dostępne do edycji.
        """
        print("profile")
        self.clear_layout()
        self.lbl_title.setText('Ustawienia profilu')
        self.text_layout.addWidget(self.lbl_title)
        self.text_layout.addWidget(self.dialog_profile)
        data = self.get_user_id()
        self.edit_name.setText(data.get('name'))
        self.edit_subname.setText(data.get('surname'))
        self.edit_email.setText(data.get('email'))

    def on_profile_admin_clicked(self):
        """
        Wyświetla dane wszystkich użytkowników.
        """
        self.clear_layout()
        self.lbl_title.setText('Usuwanie profilu')
        self.text_layout.addWidget(self.lbl_title)
        self.get_users()
        self.text_layout.addWidget(self.tbl_result)

    def on_permission_clicked(self):
        """
        Wyświetla możliwość utworzenia konta z uprawnieniami.
        """
        print("permission")
        self.clear_layout()
        self.lbl_title.setText('Utwórz nowe konto z uprawnieniami')
        self.text_layout.addWidget(self.lbl_title)
        self.text_layout.addWidget(self.dialog_permission)

    def on_set_permission_clicked(self):
        """
        Wyświetla możliwość zmiany uprawnień konta.
        """
        print("permission set")
        self.clear_layout()
        self.lbl_title.setText('Uprawnienia')
        self.text_layout.addWidget(self.lbl_title)
        self.get_users()
        self.text_layout.addWidget(self.tbl_result)

    def on_set_permission(self):
        print("permission set")
        self.clear_layout()
        self.lbl_title.setText('Uprawnienia')
        self.text_layout.addWidget(self.lbl_title)
        self.text_layout.addWidget(self.dialog_set_permission)

    def change_permission(self, user_id):
        permission_api = URL + self.get_users_api + '/role/' + str(user_id)
        jsons = {"roleId": int(self._role_id)}

        x = threading.Thread(target=patch_request,
                             args=(permission_api, jsons,
                                   self.user.get('token'), self.que))

        x.start()
        x.join()

        data = self.que.get()
        print(data)
        if data.status_code == 200:
            QMessageBox.information(self, "Zmiana uprawnień",
                                    "Uprawnienia zostały zmienione!")

    def on_change_passwd_clicked(self):
        """
        Wyświetla możliwość zmiany hasła.
        """
        print("Change password")
        self.clear_layout()
        self.lbl_title.setText(self._txt_change_perm)
        self.text_layout.addWidget(self.lbl_title)
        self.text_layout.addWidget(self.dialog_password)
        self.edit_passwd1.setFocus()

    def on_change_passwd_admin_clicked(self):
        """
        Wyświetla użytkowników, dla których hasło zostanie zmienione.
        """
        print("Change admin password")
        self.clear_layout()
        self.lbl_title.setText(self._txt_change_perm)
        self.text_layout.addWidget(self.lbl_title)
        self.get_users()
        self.text_layout.addWidget(self.tbl_result)

    def on_logout_clicked(self):
        """
        Wylogowuje użytkownika z programu.
        """
        print("Logout")
        self.clear_layout()
        self.logout()

    def logout(self):
        """
        Ukrywa główne okno, wyświetla monit o logowanie, po czym podmienia zawartość zmiennej user.
        """
        self.close()
        self.parent().hide()
        window = Login()
        dec = window.exec_()
        if dec == QDialog.Accepted:
            result = json.loads(window.response.text)
            self.user = result
            self.parent().setCentralWidget(MainWidget(result))
            self.parent().show()
            self.on_home_clicked()

    def set_data(self, data):
        """
        Wyświetla dane w tabeli i je formatuje.
        :param data: dict
        """
        self.tbl_result.clear()
        row_count = (len(data))
        column_count = (len(data[0]))
        role_id = {1: 'Użytkownik', 2: 'Pracownik', 3: 'Administrator'}

        self.tbl_result.setColumnCount(column_count)
        self.tbl_result.setRowCount(row_count)

        self.tbl_result.setHorizontalHeaderLabels((list(data[0].keys())))

        if list(data[0].keys())[0] == 'id':
            self.tbl_result.hideColumn(0)
        if 'roleId' in list(data[0].keys(
        )) and self.lbl_title.text() != self._txt_permission:
            self.tbl_result.hideColumn(4)
        else:
            self.tbl_result.showColumn(4)

        for row in range(row_count):
            for column in range(column_count):
                item = (list(data[row].values())[column])
                if column == 4 and self.lbl_title.text(
                ) == self._txt_permission:
                    item = role_id.get(item)
                self.tbl_result.setItem(row, column,
                                        QTableWidgetItem(str(item)))

        self.tbl_result.resizeColumnsToContents()
        self.tbl_result.resizeRowsToContents()

    def get_books(self,
                  page_number,
                  sort_by=None,
                  sort_direction=None,
                  search=None):
        """
        Pobiera dane o zawartości książek w bibliotece z API w wątku.
        :param page_number: int
        :param sort_by: str
        :param sort_direction: int
        :param search: str
        """
        self.page_number = page_number
        url = URL + self.get_books_api + f'?PageNumber={page_number}&PageSize=15'
        if search:
            url += f'&SearchPhrase={search}'
        if sort_by:
            url += f'&SortBy={sort_by}'
        if sort_direction:
            url += f'&SortDirection={sort_direction}'

        x = threading.Thread(target=get_request,
                             args=(url, self.user.get('token'), self.que))

        x.start()
        x.join()

        data = self.que.get()
        self.page = data.get('totalPages')

        if data.get('itemFrom') == 1:
            self.btn_back_page.setEnabled(False)
        else:
            self.btn_back_page.setEnabled(True)
        if page_number < data.get('totalPages'):
            self.btn_next_page.setEnabled(True)
        else:
            self.btn_next_page.setEnabled(False)

        self.set_data(data.get('items'))

    def get_users(self):
        """
        Pobiera dane o użytkownikach z API w wątku.
        """
        x = threading.Thread(target=get_request,
                             args=("".join([URL, self.get_users_api]),
                                   self.user.get('token'), self.que))

        x.start()
        x.join()

        data = self.que.get()
        self.set_data(data)

    def get_user_id(self):
        """
        Pobiera dane o konkretnym użytkowniku w wątku i je zwraca.
        :return: json
        """
        user_id_api = "".join(
            [URL, self.get_users_api, '/',
             str(self.user.get('id'))])
        x = threading.Thread(target=get_request,
                             args=(user_id_api, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        return data

    def get_book_id(self, book_id):
        """
        Pobiera dane o konkretnej książce w wątku i je zwraca.
        :param book_id: int
        :return: json
        """
        self.btn_delete_book.clicked.connect(lambda: self.delete_book(book_id))
        self.btn_borrow_book.clicked.connect(lambda: self.borrow_book_user())
        self._book_id = book_id
        book_id_api = "".join([URL, self.get_books_api, '/', str(book_id)])
        x = threading.Thread(target=get_request,
                             args=(book_id_api, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        return data

    def get_book_user_id(self, user_id=None):
        """
        Pobiera dane na temat wypożyczonych książek przez konkretnego użytkownika.
        :param user_id: int
        :return: boolean
        """
        if not user_id:
            user_id = self.user.get('id')
        book_user_id_api = URL + self.get_books_api + '/' + self.get_users_api[:-1] + '/' + str(
            user_id)
        x = threading.Thread(target=get_request,
                             args=(book_user_id_api, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        if data:
            self.set_data(data)
            return True
        else:
            return False

    def get_reservation_user_id(self, user_id=None):
        """
        Pobiera dane na temat zarezerwowanych książek przez konkretnego użytkownika.
        :param user_id: int
        :return: boolean
        """
        if not user_id:
            user_id = self.user.get('id')
        reservation_user_id_api = URL + self.get_books_api + '/' + self.get_users_api[:-1] + self.reservation_api + str(
            user_id)
        x = threading.Thread(target=get_request,
                             args=(reservation_user_id_api,
                                   self.user.get('token'), self.que))

        x.start()
        x.join()

        data = self.que.get()
        if data:
            self.set_data(data)
            return True
        else:
            return False

    def borrow_book_user(self):
        """
        Wyświetla listę użytkowników, dla których dana książka zostanie wypożyczona.
        """
        self.clear_layout()
        self.lbl_title.setText('Wybierz użytkownika')
        self.text_layout.addWidget(self.lbl_title)
        self.get_users()
        self.text_layout.addWidget(self.tbl_result)

    def reservation_book(self, book_id):
        """
        Dokonuje rezerwacji danej książki w wątku.
        :param book_id: int
        """
        url = URL + self.get_books_api + self.reservation_api + str(book_id)
        x = threading.Thread(target=patch_request,
                             args=(url, {}, self.user.get('token'), self.que))

        x.start()
        x.join()

        data = self.que.get()
        print(data)
        return data

    def borrow_book(self, book_id, user_id):
        """
        Dokonuje wypożyczenia książki użytkownikowi, w wątku.
        :param book_id: int
        :param user_id: int
        """
        url = URL + self.get_books_api + '/borrow/' + str(book_id)
        jsons = {"userId": int(user_id)}

        self.reservation_book(book_id)

        x = threading.Thread(target=patch_request,
                             args=(url, jsons, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        print(data)
        if data:
            QMessageBox.information(self, "Wypożyczono",
                                    "Podana pozycja została wypożyczona!")
            self.on_library_clicked()
        elif data.status_code == 400:
            QMessageBox.warning(self, "Błąd", data.text)
            self.on_library_clicked()

    def back_book(self, book_id):
        """
        Dokonuje zwrotu danej książki w wątku.
        :param book_id: int
        """
        url = URL + self.get_books_api + '/return/' + str(book_id)
        jsons = {}
        x = threading.Thread(target=patch_request,
                             args=(url, jsons, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        print(data)
        print('Zwrócono')
        if data:
            QMessageBox.information(self, "Zwrócono",
                                    "Książka została zwrócona!")
            self.on_home_clicked()
        else:
            self.clear_layout()
            self.lbl_title.setText('Nie masz żadnych wypożyczonych książek')
            self.text_layout.addWidget(self.lbl_title)

    def post_user(self):
        """
        Dokonuje utworzenia nowego użytkownika.
        """
        user_api = "".join([URL, self.get_users_api])
        jsons = {
            "name": self.edit_new_name.text(),
            "surname": self.edit_new_surname.text(),
            "email": self.edit_new_email.text(),
            "password": self.edit_pass2.text(),
            "confirmPassword": self.edit_pass3.text(),
            "roleId": self._role_id
        }

        if self.edit_pass2.text() != self.edit_pass3.text():
            QMessageBox.warning(self, "Błędne hasła",
                                "Hasła nie są takie same.")
            self.edit_pass2.setText('')
            self.edit_pass3.setText('')
            self.edit_pass2.setFocus()
            return
        if self.edit_pass2.text() == '':
            QMessageBox.warning(self, "Błąd", "Hasła nie mogą być puste.")
            self.edit_pass2.setFocus()
            return
        if self.edit_new_email.text() == '':
            QMessageBox.warning(self, "Błąd", "Email nie może być pusty.")
            self.edit_new_email.setFocus()
            return

        x = threading.Thread(target=post_request,
                             args=(user_api, jsons, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        if data.status_code == 201:
            QMessageBox.information(self, "Nowe konto",
                                    'Utworzono nowe konto.')
        print(data)

    def add_book(self):
        """
        Wyświetla widgety odpowiedzialne za dodanie nowej książki do biblioteki.
        """
        print("Add book")
        self.clear_layout()
        self.lbl_title.setText('Dodaj nową książkę')
        self.text_layout.addWidget(self.lbl_title)
        self.btn_delete_book.hide()
        self.btn_borrow_book.hide()
        self.text_layout.addWidget(self.dialog_book)

    def change_passwd(self, user_id=None):
        """
        Umożliwia zmianę hasła danego użytkownika w wątku.
        :param user_id: int
        """
        if user_id is None:
            user_id = self.user.get('id')
        print(user_id)
        token = self.user.get('token')
        url_password = "".join(['users/changePassword/', str(user_id)])

        if self.edit_passwd2.text() == '' or self.edit_passwd3.text() == '':
            QMessageBox.warning(self, "Brak nowego hasła",
                                "Nowe hasło nie może być puste")
            self.edit_passwd2.setText('')
            self.edit_passwd3.setText('')
            self.edit_passwd2.setFocus()
            return

        if self.edit_passwd2.text() != self.edit_passwd3.text():
            QMessageBox.warning(self, self._txt_bad_data,
                                "Podane hasła nie są identyczne!")
            self.edit_passwd2.setText('')
            self.edit_passwd3.setText('')
            self.edit_passwd2.setFocus()
            return

        jsons = {
            "oldPassword": self.edit_passwd1.text(),
            "newPassword": self.edit_passwd2.text(),
            "confirmNewPassword": self.edit_passwd3.text()
        }
        x = threading.Thread(target=patch_request,
                             args=("".join([URL, url_password]), jsons, token,
                                   self.que))

        x.start()
        x.join()

        response = self.que.get()
        if response.status_code == 400:
            print(response.text)
            if response.text == 'Invalid password':
                QMessageBox.warning(self, "Błędne hasło", response.text)
                self.edit_passwd1.setText('')
                self.edit_passwd1.setFocus()
                return
            error = json.loads(response.text)
            err = json.loads(
                json.dumps(error['errors'], indent=4, sort_keys=True))
            print(err)
            for key in err.keys():
                if key == 'NewPassword':
                    QMessageBox.warning(self, "Nowe hasło", err.get(key)[0])

        if response.status_code == 200:
            QMessageBox.information(self, "Hasło zmienione",
                                    "Hasło zostało zmienione!")
            self.edit_passwd1.setText('')
            self.edit_passwd2.setText('')
            self.edit_passwd3.setText('')
            self.on_home_clicked()

    def delete_profile(self, user_id=None):
        """
        Umożliwia usunięcie danego użytkownika z bazy, w wątku.
        :param user_id: int
        """
        token = self.user.get('token')
        _user_id = user_id
        if _user_id is None:
            user_id = self.user.get('id')
        url_profile = "".join([URL, self.get_users_api, '/', str(user_id)])
        button_reply = QMessageBox.question(
            self, 'Usuwanie',
            "Czy na pewnno chcesz usunąć te konto?\nOperacji tej nie można cofnąć.",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if button_reply == QMessageBox.No:
            return

        x = threading.Thread(target=delete_request,
                             args=(url_profile, token, self.que))

        x.start()
        x.join()

        response = self.que.get()
        if response.status_code == 204:
            QMessageBox.information(self, "Usunięto",
                                    "Konto zostało usunięte!")
            if _user_id != self.user.get('id'):
                return
            self.on_logout_clicked()

        if response.status_code == 500:
            QMessageBox.warning(
                self, "Błąd",
                "Nie można usunąć użytkownika, który wypożyczył książki!")

    def delete_book(self, book_id):
        """
        Umożliwia usunięcie danej książki z bazy, w wątku.
        :param book_id: int
        """
        token = self.user.get('token')
        book_id_api = "".join([URL, self.get_books_api, '/', str(book_id)])
        button_reply = QMessageBox.question(
            self, 'Usuwanie',
            "Czy na pewno chcesz usunąć tą książkę?\nOperacji tej nie można cofnąć.",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if button_reply == QMessageBox.No:
            return

        x = threading.Thread(target=delete_request,
                             args=(book_id_api, token, self.que))

        x.start()
        x.join()

        response = self.que.get()
        if response.status_code == 204:
            QMessageBox.information(self, "Usunięto",
                                    "Książka została usunięta!")
            self.on_library_clicked()

    def new_book(self, book_id=None):
        """
        Umożliwia utworzenie nowej książki w bazie, bądź zmianę już istniejącej, w wątku.
        :param book_id: int
        """
        token = self.user.get('token')
        flag_book = False

        if self.edit_isbn.text() == '' or \
                self.edit_book_name.text() == '' or \
                self.edit_author.text() == '' or \
                self.edit_publisher.text() == '' or \
                self.edit_publish_date.text() == '' or \
                self.edit_category.text() == '':
            QMessageBox.warning(self, "Uwaga, błąd danych",
                                "Należy wypełnić wymagane pola.")
            return
        if not self.edit_publish_date.text().isdigit():
            QMessageBox.warning(self, self._txt_bad_data,
                                'Pole "Data wydania" należy wypełnić liczbą.')
            self.edit_publish_date.setFocus()
            return

        jsons = {
            "isbn": self.edit_isbn.text(),
            "bookName": self.edit_book_name.text(),
            "authorName": self.edit_author.text(),
            "publisherName": self.edit_publisher.text(),
            "publishDate": int(self.edit_publish_date.text()),
            "category": self.edit_category.text(),
            "language": self.edit_language_book.text(),
            "bookDescription": self.edit_book_description.toPlainText()
        }

        if not book_id:
            book_id_api = "".join([URL, self.get_books_api])
            x = threading.Thread(target=post_request,
                                 args=(book_id_api, jsons, token, self.que))
            title = 'Dodano'
            descr = 'Dodano nową pozycję do biblioteki.'
            flag_book = True
        if book_id:
            book_id_api = "".join([URL, self.get_books_api, '/', str(book_id)])
            x = threading.Thread(target=put_request,
                                 args=(book_id_api, jsons, token, self.que))
            title = 'Zmieniono'
            descr = 'Dane o książce zostały zaktualizowane.'
            flag_book = True

        if flag_book:
            x.start()
            x.join()

            response = self.que.get()
            print(response)
            if response.status_code == 200 or response.status_code == 201:
                QMessageBox.information(self, title, descr)
                self.on_library_clicked()

    def change_profile(self):
        """
        Umożliwia zmianę danych użytkownika, w wątku.
        """
        token = self.user.get('token')
        url_profile = "".join(
            [URL, self.get_users_api, '/',
             str(self.user.get('id'))])

        name = self.edit_name.text()
        surname = self.edit_subname.text()
        email = self.edit_email.text()

        try:
            validate_email(email)
        except EmailNotValidError as e:
            print(e)
            QMessageBox.warning(self, "Błędny email",
                                "Proszę wpisać poprawny email")
            self.edit_email.setFocus()
            return

        if name == '' or surname == '' or email == '':
            QMessageBox.warning(self, self._txt_bad_data,
                                "Podane dane nie mogą być puste!")
            self.edit_name.setFocus()
            return

        jsons = {"name": name, "surname": surname, "email": email}

        x = threading.Thread(target=put_request,
                             args=(url_profile, jsons, token, self.que))

        x.start()
        x.join()

        response = self.que.get()
        print(response)
        if response.status_code == 200:
            QMessageBox.information(self, "Zmiana danych",
                                    "Dane zostały pomyślnie zapisane!")

    def change_book(self, book_id):
        """
        Uzupełnia dane widgetów o zawartość jsona danej książki.
        :param book_id: int
        """
        print("Change book id")
        self.clear_layout()
        self.lbl_title.setText('Edycja książki')
        self.text_layout.addWidget(self.lbl_title)
        jsons = self.get_book_id(book_id)
        self.edit_isbn.setText(jsons.get('isbn'))
        self.edit_book_name.setText(jsons.get('bookName'))
        self.edit_author.setText(jsons.get('authorName'))
        self.edit_publisher.setText(jsons.get('publisherName'))
        self.edit_publish_date.setText(str(jsons.get('publishDate')))
        self.edit_category.setText(jsons.get('category'))
        self.edit_language_book.setText(jsons.get('language'))
        self.edit_book_description.setPlainText(jsons.get('bookDescription'))
        self.text_layout.addWidget(self.dialog_book)

    def delete_reservation(self, book_id):
        """
        Zwraca zarezerwowaną książkę.
        :param book_id: int
        """
        print("Return book reserved")

        reservation_del_api = URL + self.get_books_api + self.reservation_api + str(
            book_id)
        x = threading.Thread(target=delete_request,
                             args=(reservation_del_api, self.user.get('token'),
                                   self.que))

        x.start()
        x.join()

        data = self.que.get()
        print(data)
        if data:
            QMessageBox.information(
                self, "Pozycja usunięta",
                "Podana pozycja została usunięta z listy zarezerwowanych!")

        self.on_reserved_clicked()
Exemple #20
0
    def __init__(self, image, parent=None):
        super(CloningWidget, self).__init__(parent)

        self.detector_combo = QComboBox()
        self.detector_combo.addItems(
            [self.tr('BRISK'),
             self.tr('ORB'),
             self.tr('AKAZE')])
        self.detector_combo.setCurrentIndex(0)
        self.detector_combo.setToolTip(
            self.tr('Algorithm used for localization and description'))
        self.response_spin = QSpinBox()
        self.response_spin.setRange(0, 100)
        self.response_spin.setSuffix(self.tr('%'))
        self.response_spin.setValue(90)
        self.response_spin.setToolTip(
            self.tr('Maximum keypoint response to perform matching'))
        self.matching_spin = QSpinBox()
        self.matching_spin.setRange(1, 100)
        self.matching_spin.setSuffix(self.tr('%'))
        self.matching_spin.setValue(20)
        self.matching_spin.setToolTip(
            self.tr('Maximum metric difference to accept matching'))
        self.distance_spin = QSpinBox()
        self.distance_spin.setRange(1, 100)
        self.distance_spin.setSuffix(self.tr('%'))
        self.distance_spin.setValue(15)
        self.distance_spin.setToolTip(
            self.tr('Maximum distance between matches in the same cluster'))
        self.cluster_spin = QSpinBox()
        self.cluster_spin.setRange(1, 20)
        self.cluster_spin.setValue(5)
        self.cluster_spin.setToolTip(
            self.tr('Minimum number of keypoints to create a new cluster'))
        self.nolines_check = QCheckBox(self.tr('Hide lines'))
        self.nolines_check.setToolTip(self.tr('Disable match line drawing'))
        self.process_button = QPushButton(self.tr('Process'))
        self.process_button.setToolTip(self.tr('Perform automatic detection'))
        self.status_label = QLabel(
            self.tr('[Press "Process" button to search for cloned regions]'))

        self.image = image
        self.viewer = ImageViewer(self.image, self.image)
        self.gray = cv.cvtColor(self.image, cv.COLOR_BGR2GRAY)
        self.keypoints = self.kpts = self.desc = self.matches = self.clusters = None
        self.canceled = False

        self.detector_combo.currentIndexChanged.connect(self.update_detector)
        self.response_spin.valueChanged.connect(self.update_detector)
        self.matching_spin.valueChanged.connect(self.update_matching)
        self.distance_spin.valueChanged.connect(self.update_cluster)
        self.cluster_spin.valueChanged.connect(self.update_cluster)
        self.nolines_check.stateChanged.connect(self.process)
        self.process_button.clicked.connect(self.process)

        top_layout = QHBoxLayout()
        top_layout.addWidget(QLabel(self.tr('Detector:')))
        top_layout.addWidget(self.detector_combo)
        top_layout.addWidget(QLabel(self.tr('Response:')))
        top_layout.addWidget(self.response_spin)
        top_layout.addWidget(QLabel(self.tr('Matching:')))
        top_layout.addWidget(self.matching_spin)
        top_layout.addWidget(QLabel(self.tr('Distance:')))
        top_layout.addWidget(self.distance_spin)
        top_layout.addWidget(QLabel(self.tr('Cluster:')))
        top_layout.addWidget(self.cluster_spin)
        top_layout.addWidget(self.nolines_check)
        top_layout.addWidget(self.process_button)
        top_layout.addStretch()

        main_layout = QVBoxLayout()
        main_layout.addLayout(top_layout)
        main_layout.addWidget(self.status_label)
        main_layout.addWidget(self.viewer)
        self.setLayout(main_layout)
Exemple #21
0
class PIDPageWidget(QWidget):
    def __init__(self, m1m3):
        super().__init__()

        self.layout = QVBoxLayout()
        self.dataLayout = QGridLayout()
        self.commandLayout = QVBoxLayout()
        self.plotLayout = QVBoxLayout()
        self.layout.addLayout(self.commandLayout)
        self.layout.addLayout(self.dataLayout)
        self.layout.addLayout(self.plotLayout)
        self.setLayout(self.layout)

        self.fxSetpointLabel = QLabel("UNKNOWN")
        self.fxMeasurementLabel = QLabel("UNKNOWN")
        self.fxErrorLabel = QLabel("UNKNOWN")
        self.fxErrorT1Label = QLabel("UNKNOWN")
        self.fxErrorT2Label = QLabel("UNKNOWN")
        self.fxControlLabel = QLabel("UNKNOWN")
        self.fxControlT1Label = QLabel("UNKNOWN")
        self.fxControlT2Label = QLabel("UNKNOWN")
        self.fySetpointLabel = QLabel("UNKNOWN")
        self.fyMeasurementLabel = QLabel("UNKNOWN")
        self.fyErrorLabel = QLabel("UNKNOWN")
        self.fyErrorT1Label = QLabel("UNKNOWN")
        self.fyErrorT2Label = QLabel("UNKNOWN")
        self.fyControlLabel = QLabel("UNKNOWN")
        self.fyControlT1Label = QLabel("UNKNOWN")
        self.fyControlT2Label = QLabel("UNKNOWN")
        self.fzSetpointLabel = QLabel("UNKNOWN")
        self.fzMeasurementLabel = QLabel("UNKNOWN")
        self.fzErrorLabel = QLabel("UNKNOWN")
        self.fzErrorT1Label = QLabel("UNKNOWN")
        self.fzErrorT2Label = QLabel("UNKNOWN")
        self.fzControlLabel = QLabel("UNKNOWN")
        self.fzControlT1Label = QLabel("UNKNOWN")
        self.fzControlT2Label = QLabel("UNKNOWN")
        self.mxSetpointLabel = QLabel("UNKNOWN")
        self.mxMeasurementLabel = QLabel("UNKNOWN")
        self.mxErrorLabel = QLabel("UNKNOWN")
        self.mxErrorT1Label = QLabel("UNKNOWN")
        self.mxErrorT2Label = QLabel("UNKNOWN")
        self.mxControlLabel = QLabel("UNKNOWN")
        self.mxControlT1Label = QLabel("UNKNOWN")
        self.mxControlT2Label = QLabel("UNKNOWN")
        self.mySetpointLabel = QLabel("UNKNOWN")
        self.myMeasurementLabel = QLabel("UNKNOWN")
        self.myErrorLabel = QLabel("UNKNOWN")
        self.myErrorT1Label = QLabel("UNKNOWN")
        self.myErrorT2Label = QLabel("UNKNOWN")
        self.myControlLabel = QLabel("UNKNOWN")
        self.myControlT1Label = QLabel("UNKNOWN")
        self.myControlT2Label = QLabel("UNKNOWN")
        self.mzSetpointLabel = QLabel("UNKNOWN")
        self.mzMeasurementLabel = QLabel("UNKNOWN")
        self.mzErrorLabel = QLabel("UNKNOWN")
        self.mzErrorT1Label = QLabel("UNKNOWN")
        self.mzErrorT2Label = QLabel("UNKNOWN")
        self.mzControlLabel = QLabel("UNKNOWN")
        self.mzControlT1Label = QLabel("UNKNOWN")
        self.mzControlT2Label = QLabel("UNKNOWN")
        self.fxTimestepLabel = QLabel("UNKNOWN")
        self.fxPLabel = QLabel("UNKNOWN")
        self.fxILabel = QLabel("UNKNOWN")
        self.fxDLabel = QLabel("UNKNOWN")
        self.fxNLabel = QLabel("UNKNOWN")
        self.fxCalculatedALabel = QLabel("UNKNOWN")
        self.fxCalculatedBLabel = QLabel("UNKNOWN")
        self.fxCalculatedCLabel = QLabel("UNKNOWN")
        self.fxCalculatedDLabel = QLabel("UNKNOWN")
        self.fxCalculatedELabel = QLabel("UNKNOWN")
        self.fyTimestepLabel = QLabel("UNKNOWN")
        self.fyPLabel = QLabel("UNKNOWN")
        self.fyILabel = QLabel("UNKNOWN")
        self.fyDLabel = QLabel("UNKNOWN")
        self.fyNLabel = QLabel("UNKNOWN")
        self.fyCalculatedALabel = QLabel("UNKNOWN")
        self.fyCalculatedBLabel = QLabel("UNKNOWN")
        self.fyCalculatedCLabel = QLabel("UNKNOWN")
        self.fyCalculatedDLabel = QLabel("UNKNOWN")
        self.fyCalculatedELabel = QLabel("UNKNOWN")
        self.fzTimestepLabel = QLabel("UNKNOWN")
        self.fzPLabel = QLabel("UNKNOWN")
        self.fzILabel = QLabel("UNKNOWN")
        self.fzDLabel = QLabel("UNKNOWN")
        self.fzNLabel = QLabel("UNKNOWN")
        self.fzCalculatedALabel = QLabel("UNKNOWN")
        self.fzCalculatedBLabel = QLabel("UNKNOWN")
        self.fzCalculatedCLabel = QLabel("UNKNOWN")
        self.fzCalculatedDLabel = QLabel("UNKNOWN")
        self.fzCalculatedELabel = QLabel("UNKNOWN")
        self.mxTimestepLabel = QLabel("UNKNOWN")
        self.mxPLabel = QLabel("UNKNOWN")
        self.mxILabel = QLabel("UNKNOWN")
        self.mxDLabel = QLabel("UNKNOWN")
        self.mxNLabel = QLabel("UNKNOWN")
        self.mxCalculatedALabel = QLabel("UNKNOWN")
        self.mxCalculatedBLabel = QLabel("UNKNOWN")
        self.mxCalculatedCLabel = QLabel("UNKNOWN")
        self.mxCalculatedDLabel = QLabel("UNKNOWN")
        self.mxCalculatedELabel = QLabel("UNKNOWN")
        self.myTimestepLabel = QLabel("UNKNOWN")
        self.myPLabel = QLabel("UNKNOWN")
        self.myILabel = QLabel("UNKNOWN")
        self.myDLabel = QLabel("UNKNOWN")
        self.myNLabel = QLabel("UNKNOWN")
        self.myCalculatedALabel = QLabel("UNKNOWN")
        self.myCalculatedBLabel = QLabel("UNKNOWN")
        self.myCalculatedCLabel = QLabel("UNKNOWN")
        self.myCalculatedDLabel = QLabel("UNKNOWN")
        self.myCalculatedELabel = QLabel("UNKNOWN")
        self.mzTimestepLabel = QLabel("UNKNOWN")
        self.mzPLabel = QLabel("UNKNOWN")
        self.mzILabel = QLabel("UNKNOWN")
        self.mzDLabel = QLabel("UNKNOWN")
        self.mzNLabel = QLabel("UNKNOWN")
        self.mzCalculatedALabel = QLabel("UNKNOWN")
        self.mzCalculatedBLabel = QLabel("UNKNOWN")
        self.mzCalculatedCLabel = QLabel("UNKNOWN")
        self.mzCalculatedDLabel = QLabel("UNKNOWN")
        self.mzCalculatedELabel = QLabel("UNKNOWN")

        self.chart = TimeChart(
            {"Command (N or N/m)": ["Fx", "Fy", "Fz", "Mx", "My", "Mz"]}
        )
        self.chartView = TimeChartView(self.chart)

        row = 0
        col = 0
        self.dataLayout.addWidget(QLabel("Setpoint"), row, col + 1)
        self.dataLayout.addWidget(QLabel("Measurement"), row, col + 2)
        self.dataLayout.addWidget(QLabel("Error"), row, col + 3)
        self.dataLayout.addWidget(QLabel("ErrorT1"), row, col + 4)
        self.dataLayout.addWidget(QLabel("ErrorT2"), row, col + 5)
        self.dataLayout.addWidget(QLabel("Control"), row, col + 6)
        self.dataLayout.addWidget(QLabel("ControlT1"), row, col + 7)
        self.dataLayout.addWidget(QLabel("ControlT2"), row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fx"), row, col)
        self.dataLayout.addWidget(self.fxSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fxMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fxErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fxErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fxErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fxControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fxControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fxControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fy"), row, col)
        self.dataLayout.addWidget(self.fySetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fyMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fyErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fyErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fyErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fyControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fyControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fyControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Fz"), row, col)
        self.dataLayout.addWidget(self.fzSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.fzMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.fzErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.fzErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.fzErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.fzControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.fzControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.fzControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Mx"), row, col)
        self.dataLayout.addWidget(self.mxSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.mxMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.mxErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.mxErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.mxErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.mxControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.mxControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.mxControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("My"), row, col)
        self.dataLayout.addWidget(self.mySetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.myMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.myErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.myErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.myErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.myControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.myControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.myControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel("Mz"), row, col)
        self.dataLayout.addWidget(self.mzSetpointLabel, row, col + 1)
        self.dataLayout.addWidget(self.mzMeasurementLabel, row, col + 2)
        self.dataLayout.addWidget(self.mzErrorLabel, row, col + 3)
        self.dataLayout.addWidget(self.mzErrorT1Label, row, col + 4)
        self.dataLayout.addWidget(self.mzErrorT2Label, row, col + 5)
        self.dataLayout.addWidget(self.mzControlLabel, row, col + 6)
        self.dataLayout.addWidget(self.mzControlT1Label, row, col + 7)
        self.dataLayout.addWidget(self.mzControlT2Label, row, col + 8)
        row += 1
        self.dataLayout.addWidget(QLabel(" "), row, col)
        row += 1
        self.dataLayout.addWidget(QLabel("Timestep"), row, col + 1)
        self.dataLayout.addWidget(QLabel("P"), row, col + 2)
        self.dataLayout.addWidget(QLabel("I"), row, col + 3)
        self.dataLayout.addWidget(QLabel("D"), row, col + 4)
        self.dataLayout.addWidget(QLabel("N"), row, col + 5)
        self.dataLayout.addWidget(QLabel("CalculatedA"), row, col + 6)
        self.dataLayout.addWidget(QLabel("CalculatedB"), row, col + 7)
        self.dataLayout.addWidget(QLabel("CalculatedC"), row, col + 8)
        self.dataLayout.addWidget(QLabel("CalculatedD"), row, col + 9)
        self.dataLayout.addWidget(QLabel("CalculatedE"), row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fx"), row, col)
        self.dataLayout.addWidget(self.fxTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fxPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fxILabel, row, col + 3)
        self.dataLayout.addWidget(self.fxDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fxNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fxCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fxCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fxCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fxCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fxCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fy"), row, col)
        self.dataLayout.addWidget(self.fyTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fyPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fyILabel, row, col + 3)
        self.dataLayout.addWidget(self.fyDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fyNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fyCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fyCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fyCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fyCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fyCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Fz"), row, col)
        self.dataLayout.addWidget(self.fzTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.fzPLabel, row, col + 2)
        self.dataLayout.addWidget(self.fzILabel, row, col + 3)
        self.dataLayout.addWidget(self.fzDLabel, row, col + 4)
        self.dataLayout.addWidget(self.fzNLabel, row, col + 5)
        self.dataLayout.addWidget(self.fzCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.fzCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.fzCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.fzCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.fzCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Mx"), row, col)
        self.dataLayout.addWidget(self.mxTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.mxPLabel, row, col + 2)
        self.dataLayout.addWidget(self.mxILabel, row, col + 3)
        self.dataLayout.addWidget(self.mxDLabel, row, col + 4)
        self.dataLayout.addWidget(self.mxNLabel, row, col + 5)
        self.dataLayout.addWidget(self.mxCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.mxCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.mxCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.mxCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.mxCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("My"), row, col)
        self.dataLayout.addWidget(self.myTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.myPLabel, row, col + 2)
        self.dataLayout.addWidget(self.myILabel, row, col + 3)
        self.dataLayout.addWidget(self.myDLabel, row, col + 4)
        self.dataLayout.addWidget(self.myNLabel, row, col + 5)
        self.dataLayout.addWidget(self.myCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.myCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.myCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.myCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.myCalculatedELabel, row, col + 10)
        row += 1
        self.dataLayout.addWidget(QLabel("Mz"), row, col)
        self.dataLayout.addWidget(self.mzTimestepLabel, row, col + 1)
        self.dataLayout.addWidget(self.mzPLabel, row, col + 2)
        self.dataLayout.addWidget(self.mzILabel, row, col + 3)
        self.dataLayout.addWidget(self.mzDLabel, row, col + 4)
        self.dataLayout.addWidget(self.mzNLabel, row, col + 5)
        self.dataLayout.addWidget(self.mzCalculatedALabel, row, col + 6)
        self.dataLayout.addWidget(self.mzCalculatedBLabel, row, col + 7)
        self.dataLayout.addWidget(self.mzCalculatedCLabel, row, col + 8)
        self.dataLayout.addWidget(self.mzCalculatedDLabel, row, col + 9)
        self.dataLayout.addWidget(self.mzCalculatedELabel, row, col + 10)

        self.plotLayout.addWidget(self.chartView)

        m1m3.pidInfo.connect(self.pidInfo)
        m1m3.pidData.connect(self.pidData)

    @Slot(map)
    def pidInfo(self, data):
        self.fxTimestepLabel.setText("%0.3f" % data.timestep[0])
        self.fxPLabel.setText("%0.3f" % data.p[0])
        self.fxILabel.setText("%0.3f" % data.i[0])
        self.fxDLabel.setText("%0.3f" % data.d[0])
        self.fxNLabel.setText("%0.3f" % data.n[0])
        self.fxCalculatedALabel.setText("%0.3f" % data.calculatedA[0])
        self.fxCalculatedBLabel.setText("%0.3f" % data.calculatedB[0])
        self.fxCalculatedCLabel.setText("%0.3f" % data.calculatedC[0])
        self.fxCalculatedDLabel.setText("%0.3f" % data.calculatedD[0])
        self.fxCalculatedELabel.setText("%0.3f" % data.calculatedE[0])

        self.fyTimestepLabel.setText("%0.3f" % data.timestep[1])
        self.fyPLabel.setText("%0.3f" % data.p[1])
        self.fyILabel.setText("%0.3f" % data.i[1])
        self.fyDLabel.setText("%0.3f" % data.d[1])
        self.fyNLabel.setText("%0.3f" % data.n[1])
        self.fyCalculatedALabel.setText("%0.3f" % data.calculatedA[1])
        self.fyCalculatedBLabel.setText("%0.3f" % data.calculatedB[1])
        self.fyCalculatedCLabel.setText("%0.3f" % data.calculatedC[1])
        self.fyCalculatedDLabel.setText("%0.3f" % data.calculatedD[1])
        self.fyCalculatedELabel.setText("%0.3f" % data.calculatedE[1])

        self.fzTimestepLabel.setText("%0.3f" % data.timestep[2])
        self.fzPLabel.setText("%0.3f" % data.p[2])
        self.fzILabel.setText("%0.3f" % data.i[2])
        self.fzDLabel.setText("%0.3f" % data.d[2])
        self.fzNLabel.setText("%0.3f" % data.n[2])
        self.fzCalculatedALabel.setText("%0.3f" % data.calculatedA[2])
        self.fzCalculatedBLabel.setText("%0.3f" % data.calculatedB[2])
        self.fzCalculatedCLabel.setText("%0.3f" % data.calculatedC[2])
        self.fzCalculatedDLabel.setText("%0.3f" % data.calculatedD[2])
        self.fzCalculatedELabel.setText("%0.3f" % data.calculatedE[2])

        self.mxTimestepLabel.setText("%0.3f" % data.timestep[3])
        self.mxPLabel.setText("%0.3f" % data.p[3])
        self.mxILabel.setText("%0.3f" % data.i[3])
        self.mxDLabel.setText("%0.3f" % data.d[3])
        self.mxNLabel.setText("%0.3f" % data.n[3])
        self.mxCalculatedALabel.setText("%0.3f" % data.calculatedA[3])
        self.mxCalculatedBLabel.setText("%0.3f" % data.calculatedB[3])
        self.mxCalculatedCLabel.setText("%0.3f" % data.calculatedC[3])
        self.mxCalculatedDLabel.setText("%0.3f" % data.calculatedD[3])
        self.mxCalculatedELabel.setText("%0.3f" % data.calculatedE[3])

        self.myTimestepLabel.setText("%0.3f" % data.timestep[4])
        self.myPLabel.setText("%0.3f" % data.p[4])
        self.myILabel.setText("%0.3f" % data.i[4])
        self.myDLabel.setText("%0.3f" % data.d[4])
        self.myNLabel.setText("%0.3f" % data.n[4])
        self.myCalculatedALabel.setText("%0.3f" % data.calculatedA[4])
        self.myCalculatedBLabel.setText("%0.3f" % data.calculatedB[4])
        self.myCalculatedCLabel.setText("%0.3f" % data.calculatedC[4])
        self.myCalculatedDLabel.setText("%0.3f" % data.calculatedD[4])
        self.myCalculatedELabel.setText("%0.3f" % data.calculatedE[4])

        self.mzTimestepLabel.setText("%0.3f" % data.timestep[5])
        self.mzPLabel.setText("%0.3f" % data.p[5])
        self.mzILabel.setText("%0.3f" % data.i[5])
        self.mzDLabel.setText("%0.3f" % data.d[5])
        self.mzNLabel.setText("%0.3f" % data.n[5])
        self.mzCalculatedALabel.setText("%0.3f" % data.calculatedA[5])
        self.mzCalculatedBLabel.setText("%0.3f" % data.calculatedB[5])
        self.mzCalculatedCLabel.setText("%0.3f" % data.calculatedC[5])
        self.mzCalculatedDLabel.setText("%0.3f" % data.calculatedD[5])
        self.mzCalculatedELabel.setText("%0.3f" % data.calculatedE[5])

    @Slot(map)
    def pidData(self, data):
        self.fxSetpointLabel.setText("%0.3f" % data.setpoint[0])
        self.fxMeasurementLabel.setText("%0.3f" % data.measuredPID[0])
        self.fxErrorLabel.setText("%0.3f" % data.error[0])
        self.fxErrorT1Label.setText("%0.3f" % data.errorT1[0])
        self.fxErrorT2Label.setText("%0.3f" % data.errorT2[0])
        self.fxControlLabel.setText("%0.3f" % data.control[0])
        self.fxControlT1Label.setText("%0.3f" % data.controlT1[0])
        self.fxControlT2Label.setText("%0.3f" % data.controlT2[0])
        self.fySetpointLabel.setText("%0.3f" % data.setpoint[1])
        self.fyMeasurementLabel.setText("%0.3f" % data.measuredPID[1])
        self.fyErrorLabel.setText("%0.3f" % data.error[1])
        self.fyErrorT1Label.setText("%0.3f" % data.errorT1[1])
        self.fyErrorT2Label.setText("%0.3f" % data.errorT2[1])
        self.fyControlLabel.setText("%0.3f" % data.control[1])
        self.fyControlT1Label.setText("%0.3f" % data.controlT1[1])
        self.fyControlT2Label.setText("%0.3f" % data.controlT2[1])
        self.fzSetpointLabel.setText("%0.3f" % data.setpoint[2])
        self.fzMeasurementLabel.setText("%0.3f" % data.measuredPID[2])
        self.fzErrorLabel.setText("%0.3f" % data.error[2])
        self.fzErrorT1Label.setText("%0.3f" % data.errorT1[2])
        self.fzErrorT2Label.setText("%0.3f" % data.errorT2[2])
        self.fzControlLabel.setText("%0.3f" % data.control[2])
        self.fzControlT1Label.setText("%0.3f" % data.controlT1[2])
        self.fzControlT2Label.setText("%0.3f" % data.controlT2[2])
        self.mxSetpointLabel.setText("%0.3f" % data.setpoint[3])
        self.mxMeasurementLabel.setText("%0.3f" % data.measuredPID[3])
        self.mxErrorLabel.setText("%0.3f" % data.error[3])
        self.mxErrorT1Label.setText("%0.3f" % data.errorT1[3])
        self.mxErrorT2Label.setText("%0.3f" % data.errorT2[3])
        self.mxControlLabel.setText("%0.3f" % data.control[3])
        self.mxControlT1Label.setText("%0.3f" % data.controlT1[3])
        self.mxControlT2Label.setText("%0.3f" % data.controlT2[3])
        self.mySetpointLabel.setText("%0.3f" % data.setpoint[4])
        self.myMeasurementLabel.setText("%0.3f" % data.measuredPID[4])
        self.myErrorLabel.setText("%0.3f" % data.error[4])
        self.myErrorT1Label.setText("%0.3f" % data.errorT1[4])
        self.myErrorT2Label.setText("%0.3f" % data.errorT2[4])
        self.myControlLabel.setText("%0.3f" % data.control[4])
        self.myControlT1Label.setText("%0.3f" % data.controlT1[4])
        self.myControlT2Label.setText("%0.3f" % data.controlT2[4])
        self.mzSetpointLabel.setText("%0.3f" % data.setpoint[5])
        self.mzMeasurementLabel.setText("%0.3f" % data.measuredPID[5])
        self.mzErrorLabel.setText("%0.3f" % data.error[5])
        self.mzErrorT1Label.setText("%0.3f" % data.errorT1[5])
        self.mzErrorT2Label.setText("%0.3f" % data.errorT2[5])
        self.mzControlLabel.setText("%0.3f" % data.control[5])
        self.mzControlT1Label.setText("%0.3f" % data.controlT1[5])
        self.mzControlT2Label.setText("%0.3f" % data.controlT2[5])

        self.chart.append(data.timestamp, [data.control[x] for x in range(6)])
Exemple #22
0
class RootNode(QDialog):
    def __init__(self, parent=QWidget.find(mxs.windows.getMAXHWND())):
        QDialog.__init__(self, parent)
        self.setWindowFlags(QtCore.Qt.Tool)
        self.setWindowFlags(QtCore.Qt.Window)

        self.resize(240, 360)
        self.setWindowTitle("CAT.RootNode")
        self.mesh = None
        self.rootNode = None
        self.initUI()

        self.selectedNodes = []
        self.skinMeshes = []

        self.addNodes.clicked.connect(self.addNode)
        self.removeNodes.clicked.connect(self.clearNodesInNodeList)

        self.addbtn.clicked.connect(self.addMod)
        self.removebtn.clicked.connect(self.removeMod)

        self.recreationbtn.clicked.connect(self.recreate)
        self.skinTransfer.clicked.connect(self.startTransfer)

        self.lw_skiin.itemClicked.connect(self.changeSelection)

    def changeSelection(self):
        item = self.lw_skiin.selectedItems()
        num = self.lw_skiin.row(item[0])
        mxs.select(self.skinMeshes[num][0])
        mxs.modPanel.setCurrentObject(self.skinMeshes[num][1])

    def clearNodesInNodeList(self):
        self.result = []
        self.writeInNodeList()

    def startTransfer(self):
        mxs.execute("max create mode")

        with pymxs.undo(True):

            for i in self.skinMeshes:
                skinSource = mxs.skinUtils.ExtractSkinData(i[0])
                skinSource = mxs.getNodeByName("SkinData_{}".format(i[0].name))

                count = mxs.skinOps.GetNumberBones(i[1])
                newBones = []

                for item in range(count):
                    # print(item +1, i[0].name, mxs.skinOps.GetBoneNode(i[1], item + 1))
                    try:
                        newBones.append(self.dict[mxs.skinOps.GetBoneNode(
                            i[1], item + 1)])
                    except:
                        pass

                oldSkin = i[1]
                oldSkin.enabled = False

                skinMod = mxs.Skin()
                skinMod.name = "Transfered Skin"

                mxs.addModifier(i[0], skinMod, before=i[2] - 1)

                for bone in newBones:
                    mxs.skinOps.addbone(skinMod, bone, 0)

                mxs.select(i[0])
                mxs.selectmore(skinSource)
                mxs.skinUtils.ImportSkinDataNoDialog(True, False, False, False,
                                                     False, 1.0, 0)

                mxs.delete(skinSource)
                mxs.clearSelection()

        mxs.execute("max modify mode")

    def old_recreate(self):
        with pymxs.undo(True):

            if len(self.result) > 0:
                self.newNodes = []
                self.dict = {}
                temp = mxs.Array()
                lastNode = None
                index = 0

                rootNode = mxs.point()
                rootNode.size = 2
                rootNode.showlinks = True
                rootNode.Box = True
                rootNode.cross = False
                rootNode.axistripod = False
                rootNode.centermarker = False
                mxs.join(temp, rootNode)

            def create_constraints(node, nNode):

                # Position
                sub = mxs.getSubAnim(nNode, 3)
                secsub = mxs.getSubAnim(sub, 1)
                secsub.controller = mxs.Position_List()
                posCtrl = mxs.Position_Constraint()
                thirdsub = mxs.getSubAnim(secsub, 2)
                thirdsub.controller = posCtrl
                posConstraintInterface = posCtrl.constraints
                posConstraintInterface.appendTarget(node, 100)

                # Rotation
                sub = mxs.getSubAnim(nNode, 3)
                secsub = mxs.getSubAnim(sub, 2)
                secsub.controller = mxs.rotation_list()
                posCtrl = mxs.Orientation_Constraint()
                thirdsub = mxs.getSubAnim(secsub, 2)
                thirdsub.controller = posCtrl
                posConstraintInterface = posCtrl.constraints
                posConstraintInterface.appendTarget(node, 100)

            for i in self.result:
                # Create new nodes and add them to list and dict
                nNode = mxs.point()
                nNode.showlinks = True
                nNode.size = 2
                nNode.transform = i.transform
                nNode.name = i.name
                nNode.wireColor = i.wireColor
                self.dict[i] = nNode
                self.newNodes.append(i)

                # Create parent connections
                if mxs.isValidNode(i.parent):
                    nNode.parent = self.dict[i.parent]

                else:
                    nNode.parent = rootNode

                # Create Constraints
                create_constraints(i, nNode)

                # final part
                mxs.join(temp, nNode)
                lastNode = nNode
                index += 1

            mxs.select(temp)

        mxs.redrawViews()

    def recreate(self):
        defaultSize = 2
        bones = mxs.Array()

        if len(self.result) > 0:
            self.newNodes = []
            self.dict = {}
            temp = mxs.Array()
            lastNode = None
            index = 0

            rootNode = mxs.BoneSys.createBone(mxs.point3(0, 0, 0),
                                              mxs.point3(0, 1, 0),
                                              mxs.point3(0, 1, 0))
            rootNode.transform = mxs.Matrix3(1)
            rootNode.size = 2
            rootNode.name = "rootBone"
            mxs.join(temp, rootNode)

        def new_create_constraints(node, nNode):

            posList = mxs.position_list()  # Create Pos_List
            const = mxs.Position_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Position",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

            posList = mxs.rotation_list()  # Create Pos_List
            const = mxs.Orientation_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Rotation",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

        def create_constraints(nNode, node):
            # Position
            posList = mxs.position_list()  # Create Pos_List
            const = mxs.Position_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Position",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

            # Rotation
            posList = mxs.rotation_list()  # Create Pos_List
            const = mxs.Orientation_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Rotation",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

        for obj in self.result:
            endPos = mxs.point3(0, 0, 0)

            if obj.children.count > 0:
                endPos = obj.children[0].transform.pos

            else:
                endPos = (mxs.transmatrix(mxs.point3(defaultSize, 0, 0)) *
                          obj.transform).pos

            zPos = (mxs.transmatrix(mxs.point3(0, 0, 1)) * obj.transform).pos
            d = mxs.BoneSys.createBone(obj.transform.pos, endPos, zPos)
            d.transform = obj.transform
            d.name = obj.name
            d.wirecolor = obj.wirecolor
            mxs.join(bones, d)
            self.dict[obj] = d
            self.newNodes.append(obj)

            # Create parent connections
            if mxs.isValidNode(obj.parent):
                d.parent = self.dict[obj.parent]

            else:
                d.parent = rootNode

            create_constraints(obj, d)

        mxs.select(bones)
        mxs.selectmore(rootNode)
        mxs.redrawViews()

    def addMod(self):
        allowed = mxs.readvalue(mxs.StringStream('Skin'))

        if mxs.classOf(mxs.modPanel.getCurrentObject()) == allowed:
            try:
                node = mxs.selection[0]
                mod = mxs.modPanel.getCurrentObject()
                modID = mxs.modPanel.getModifierIndex(mxs.selection[0], mod)

                if [node, mod, modID] in self.skinMeshes:
                    pass
                else:
                    self.skinMeshes.append([node, mod, modID])
                    self.lw_skiin.addItem("{} > {} > ID:{}".format(
                        mxs.selection[0].name, mod, modID))
                    self.lw_skiin.item(self.lw_skiin.count() -
                                       1).setBackground(
                                           QColor.fromRgb(60, 60, 60))
            except:
                pass
                # print("Error")

        else:
            pass
            # print("Select Skin Modifier")

    def removeMod(self):
        item = self.lw_skiin.selectedItems()
        allowed = mxs.readvalue(mxs.StringStream('Skin'))

        if mxs.classOf(mxs.modPanel.getCurrentObject()) == allowed:
            try:
                node = mxs.selection[0]
                mod = mxs.modPanel.getCurrentObject()
                modID = mxs.modPanel.getModifierIndex(mxs.selection[0], mod)

                if [node, mod, modID] in self.skinMeshes:
                    print(self.skinMeshes)
                    self.skinMeshes.remove([node, mod, modID])
                    self.lw_skiin.takeItem(self.lw_skiin.row(item[0]))
                    print(self.skinMeshes)

                else:
                    pass

            except:

                pass

        else:
            pass
            # print("Select Skin Modifier")

    def addNode(self):
        # Find Selection as a List
        nodes = mxs.selection

        if len(nodes) > 0:
            group_members = []
            group_heads = []
            head_root = []
            nodes_in_chain = []
            independent_nodes = []
            result_list = []
            results_roots = []
            self.ordered_selection_list = []
            self.result = []

            def find_group_members():
                for i in range(len(nodes)):
                    if mxs.isGroupMember(nodes[i]):
                        group_members.append(nodes[i])

            def find_group_heads():

                for i in range(len(nodes)):
                    if mxs.isGroupHead(nodes[i]):
                        group_heads.append(nodes[i])

                if len(group_heads) == 1:
                    head_root.append(group_heads[0])
                    result_list.append(group_heads[0])

                elif len(group_heads) > 1:
                    find_head_roots()

            def find_head_roots():

                for i in range(len(group_heads)):
                    if mxs.isValidNode(group_heads[i].parent
                                       ) == False or mxs.isGroupMember(
                                           group_heads[i]) == False:
                        head_root.append(group_heads[i])
                        result_list.append(group_heads[i])

            def remove_group_members_from_list():
                global out_of_groups
                out_of_groups = []
                for i in range(len(nodes)):
                    out_of_groups.append(nodes[i])
                for i in range(len(nodes)):
                    if mxs.isGroupHead(nodes[i]) or mxs.isGroupMember(
                            nodes[i]):
                        out_of_groups.remove(nodes[i])

            def find_independent_nodes():

                for i in range(len(out_of_groups)):
                    if mxs.isValidNode(
                            out_of_groups[i].parent
                    ) == False and out_of_groups[i].children.count == 0:
                        independent_nodes.append(nodes[i])
                        result_list.append(nodes[i])

            def find_node_in_chain():
                for i in range(len(out_of_groups)):
                    if mxs.isValidNode(
                            out_of_groups[i].parent
                    ) == True or out_of_groups[i].children.count != 0:
                        nodes_in_chain.append(out_of_groups[i])
                        result_list.append(out_of_groups[i])

            def find_results_roots():

                for i in range(len(result_list)):
                    if mxs.isValidNode(result_list[i].parent) == False or mxs.isValidNode(result_list[i].parent) and \
                            result_list[i].parent not in result_list:
                        # print(f"#{i} - Search root", result_list[i].name)
                        results_roots.append(result_list[i])

            def put_in_ordered_list():

                for i in range(len(results_roots)):
                    self.ordered_selection_list.append(results_roots[i])
                    child_finder(results_roots[i])

            def child_finder(input):
                current = input
                count = input.children.count

                for i in range(count):

                    if current.children[i] in result_list:
                        self.ordered_selection_list.append(current.children[i])
                        # print(current.children[i].name)

                    if current.children[i].children.count != 0:
                        child_finder(current.children[i])

            def filter(input):
                new = []
                allowed = []
                allowed.append(mxs.readvalue(mxs.StringStream('CATBone')))
                allowed.append(mxs.readvalue(mxs.StringStream('HubObject')))

                # print("NOT ALLOWED NODES:")
                index = 0
                for i in input:
                    new.append(i)
                    if mxs.classOf(i) in allowed:
                        self.selectedNodes.append(i)
                        # print("{}".format(index), i.name)
                        index += 1

                # print("{}\n".format(len(self.selectedNodes)))

                self.result = new

                self.writeInNodeList(self.result)

            find_group_members()  # 1
            find_group_heads()  # 2
            remove_group_members_from_list()  # 3
            find_independent_nodes()  # 4
            find_node_in_chain()  # 5
            find_results_roots()  # 6
            put_in_ordered_list()  # 7
            filter(self.ordered_selection_list)  # 8

            group_members = []
            group_heads = []
            head_root = []
            nodes_in_chain = []
            independent_nodes = []
            result_list = []
            results_roots = []
            self.ordered_selection_list = []

    def writeInNodeList(self, new=[]):
        if len(self.result) < 1:
            self.lw_selectedNodes.clear()

        index = 0
        # print(len(self.result))
        for i in new:

            self.lw_selectedNodes.addItem(i.name)
            color = i.wireColor
            self.lw_selectedNodes.item(index).setBackground(
                QColor.fromRgb(color.r, color.g, color.b))

            if ((color.r + color.g + color.b) / 3) > 127.5:
                self.lw_selectedNodes.item(index).setForeground(
                    QColor.fromRgb(60, 60, 60))
            else:
                self.lw_selectedNodes.item(index).setForeground(
                    QColor.fromRgb(240, 240, 240))
            index += 1

    def create(self):
        with pymxs.undo(True):

            def getNode(node, indent='', lastNode=None):
                pass

    def closeDialog(self):
        self.close()

    def initUI(self):
        self.layout = QVBoxLayout()

        self.objectsLayout = QHBoxLayout()
        self.addNodes = QPushButton("Add Nodes")
        self.removeNodes = QPushButton("Clear Nodes")
        self.objectsLayout.addWidget(self.addNodes)
        self.objectsLayout.addWidget(self.removeNodes)

        self.layout.addLayout(self.objectsLayout)

        self.lw_selectedNodes = QListWidget()
        self.layout.addWidget(self.lw_selectedNodes)
        self.lw_selectedNodes.setSelectionMode(QAbstractItemView.NoSelection)

        self.recreationbtn = QPushButton("Recreation")
        self.layout.addWidget(self.recreationbtn)

        line = QFrame()
        line.setMinimumHeight(4)
        line.setStyleSheet("background: #333333")
        self.layout.addWidget(line)

        self.objectsLayout = QHBoxLayout()
        self.addbtn = QPushButton("Add Skin")
        self.removebtn = QPushButton("Remove Skin")

        self.objectsLayout.addWidget(self.addbtn)
        self.objectsLayout.addWidget(self.removebtn)

        self.layout.addLayout(self.objectsLayout)

        self.lw_skiin = QListWidget()
        self.layout.addWidget(self.lw_skiin)
        self.lw_skiin.setMaximumHeight(200)

        line = QFrame()
        line.setMinimumHeight(4)
        line.setStyleSheet("background: #333333")
        self.layout.addWidget(line)

        self.skinTransfer = QPushButton("Skin Transfer")
        self.layout.addWidget(self.skinTransfer)
        self.skinTransfer.setMinimumHeight(32)

        label = QLabel()
        label.setText(
            "<a href=\"https://www.artstation.com/shirzadbh/store\">Python Script By: Shirzad Bahrami</a>"
        )
        label.setOpenExternalLinks(True)

        self.layout.addWidget(label)

        self.setLayout(self.layout)
        self.layout.setMargin(4)
Exemple #23
0
class SetPreferences (QDialog):
    """
    
    :version:
    :author:
    """

    #--------------------------------------------------------------------------
    
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("Set Preferences")

        self.dialogLayout = QVBoxLayout()

        # Setup OK and Cancel buttons
        self.okButton = QPushButton("OK", self)
        self.okButton.pressed.connect(self.on_ok)         
        self.cancelButton = QPushButton("Cancel", self)
        self.cancelButton.pressed.connect(self.on_cancel)
        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addStretch()
        self.buttonLayout.addWidget(self.okButton)
        self.buttonLayout.addWidget(self.cancelButton)
                      
        self.dialogLayout.addStretch()
        self.dialogLayout.addLayout(self.buttonLayout)

        self.setLayout(self.dialogLayout)
               
        return
        
    #--------------------------------------------------------------------------
      
    def set_tree_defaults(self, treeFont, treeFontSize, iconIndex):
        """ Sets tree parameters in ItemTree instance """
        
        self.treeFont = treeFont 
        self.treeFontSize = treeFontSize
        self.iconIndex = iconIndex
        
        return 
               
    #--------------------------------------------------------------------------  
     
    def get_tree_defaults(self):
        """ Gets existing tree parameters from ItemTree instance """
        
        return (self.treeFont, self.treeFontSize, self.iconIndex)
    
    #--------------------------------------------------------------------------

    def on_ok(self):
        """Handler for ''OK'' button"""
                    
        print("OK button pushed!")
        self.treeFontSize = 24	# test to see if changed value can be returned
        
        self.accept()
        
        return
    
    #--------------------------------------------------------------------------

    def on_cancel(self):
        """Handler for 'Cancel''' button"""
                    
        print("Cancel button pushed!")
        
        self.reject()
        
        return
Exemple #24
0
    def __init__(self, image, parent=None):
        super(AdjustWidget, self).__init__(parent)

        self.bright_slider = ParamSlider([-255, +255], 16, 0)
        self.sat_slider = ParamSlider([-255, +255], 16, 0)
        self.hue_slider = ParamSlider([0, 180], 10, 0, '°')
        self.gamma_slider = ParamSlider([1, 50], 10, 10)
        self.shadow_slider = ParamSlider([-100, +100], 10, 0, '%')
        self.high_slider = ParamSlider([-100, +100], 10, 0, '%')
        self.sweep_slider = ParamSlider([0, 255], 8, 127)
        self.width_slider = ParamSlider([0, 255], 8, 255)
        self.sharpen_slider = ParamSlider([0, 100], 10, 0, '%')
        self.thr_slider = ParamSlider([0, 255],
                                      16,
                                      255,
                                      special=self.tr('Auto'))
        self.equalize_combo = QComboBox()
        self.equalize_combo.addItems([
            self.tr('No EQ'),
            self.tr('Hist EQ'),
            self.tr('CLAHE L1'),
            self.tr('CLAHE L2'),
            self.tr('CLAHE L3'),
            self.tr('CLAHE L4')
        ])
        self.equalize_combo.setToolTip(self.tr('Histogram equalization mode'))
        self.invert_check = QCheckBox(self.tr('Invert values'))
        self.invert_check.setToolTip(self.tr('Apply bitwise complement'))
        self.reset_button = QPushButton(self.tr('Reset'))

        self.image = image
        self.viewer = ImageViewer(self.image, self.image)
        self.reset()

        self.bright_slider.valueChanged.connect(self.process)
        self.sat_slider.valueChanged.connect(self.process)
        self.hue_slider.valueChanged.connect(self.process)
        self.gamma_slider.valueChanged.connect(self.process)
        self.shadow_slider.valueChanged.connect(self.process)
        self.high_slider.valueChanged.connect(self.process)
        self.sweep_slider.valueChanged.connect(self.process)
        self.width_slider.valueChanged.connect(self.process)
        self.thr_slider.valueChanged.connect(self.process)
        self.sharpen_slider.valueChanged.connect(self.process)
        self.equalize_combo.currentIndexChanged.connect(self.process)
        self.invert_check.stateChanged.connect(self.process)
        self.reset_button.clicked.connect(self.reset)

        params_layout = QGridLayout()
        params_layout.addWidget(QLabel(self.tr('Brightness')), 0, 0)
        params_layout.addWidget(QLabel(self.tr('Saturation')), 1, 0)
        params_layout.addWidget(QLabel(self.tr('Hue')), 2, 0)
        params_layout.addWidget(QLabel(self.tr('Gamma')), 3, 0)
        params_layout.addWidget(self.bright_slider, 0, 1)
        params_layout.addWidget(self.sat_slider, 1, 1)
        params_layout.addWidget(self.hue_slider, 2, 1)
        params_layout.addWidget(self.gamma_slider, 3, 1)
        params_layout.addWidget(QLabel(self.tr('Shadows')), 0, 2)
        params_layout.addWidget(QLabel(self.tr('Highlights')), 1, 2)
        params_layout.addWidget(QLabel(self.tr('Sweep')), 2, 2)
        params_layout.addWidget(QLabel(self.tr('Width')), 3, 2)
        params_layout.addWidget(self.shadow_slider, 0, 3)
        params_layout.addWidget(self.high_slider, 1, 3)
        params_layout.addWidget(self.sweep_slider, 2, 3)
        params_layout.addWidget(self.width_slider, 3, 3)
        params_layout.addWidget(QLabel(self.tr('Sharpen')), 0, 4)
        params_layout.addWidget(self.sharpen_slider, 0, 5)
        params_layout.addWidget(QLabel(self.tr('Threshold')), 1, 4)
        params_layout.addWidget(self.thr_slider, 1, 5)
        params_layout.addWidget(self.equalize_combo, 2, 4)
        params_layout.addWidget(self.invert_check, 2, 5)
        params_layout.addWidget(self.reset_button, 3, 4, 1, 2)

        main_layout = QVBoxLayout()
        main_layout.addLayout(params_layout)
        main_layout.addWidget(self.viewer)
        self.setLayout(main_layout)
Exemple #25
0
class PyCalcUi(QWidget):
    """PyCalc's View (GUI)."""

    def __init__(self,
                 parent: QWidget = None,
                 ) -> None:
        """View initializer."""
        super().__init__()

        self.setFixedSize(235, 235)

        self.generalLayout = QVBoxLayout()
        self.setLayout(self.generalLayout)
        # Create the display and the buttons
        self._createDisplay()
        self._createButtons()

        # Connect signals and slots
        self._connectSignals()

    def _createDisplay(self) -> None:
        """Create the display."""
        # Create the display widget
        self.display = QLineEdit()
        # Set some display's properties
        self.display.setFixedHeight(35)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setReadOnly(True)
        # Add the display to the general layout
        self.generalLayout.addWidget(self.display)

    def _createButtons(self) -> None:
        """Create the buttons."""
        print("creating button")
        self.buttons: Dict[str, QPushButton] = {}
        buttonsLayout = QGridLayout()
        # Button text | position on the QGridLayout
        buttons: Dict[str, Tuple[int, int]] = {'7': (0, 0), '8': (0, 1), '9': (0, 2),
                                               '/': (0, 3),
                                               'C': (0, 4),
                                               '4': (1, 0), '5': (1, 1), '6': (1, 2),
                                               '*': (1, 3),
                                               '(': (1, 4),
                                               '1': (2, 0), '2': (2, 1), '3': (2, 2),
                                               '-': (2, 3),
                                               ')': (2, 4),
                                               '0': (3, 0), '00': (3, 1), '.': (3, 2),
                                               '+': (3, 3),
                                               '=': (3, 4),
                                               }
        # Create the buttons and add them to the grid layout
        for btnText, pos in buttons.items():
            self.buttons[btnText] = QPushButton(btnText)
            self.buttons[btnText].setFixedSize(40, 40)
            buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])
            # Add buttonsLayout to the general layout
            self.generalLayout.addLayout(buttonsLayout)

    def setDisplayText(self, text: str) -> None:
        """Set display's text."""
        self.display.setText(text)
        self.display.setFocus()

    def displayText(self) -> str:
        """Get display's text."""
        return cast(str, self.display.text())

    def clearDisplay(self) -> None:
        """Clear the display."""
        self.setDisplayText('')

    ERROR_MSG = 'ERROR'

    def _calculateResult(self) -> None:
        """Evaluate expressions."""
        result = self._evaluateExpression(self.displayText())
        self.setDisplayText(result)

    def _buildExpression(self, sub_exp: str) -> None:
        """Build expression."""
        if self.displayText() == self.ERROR_MSG:
            self.clearDisplay()

        expression = self.displayText() + sub_exp
        self.setDisplayText(expression)

    def _connectSignals(self) -> None:
        # Connect signals and slots.
        for btnText, btn in self.buttons.items():
            if btnText not in {'=', 'C'}:
                btn.clicked.connect(partial(self._buildExpression, btnText))

        self.buttons['='].clicked.connect(self._calculateResult)
        self.display.returnPressed.connect(self._calculateResult)
        self.buttons['C'].clicked.connect(self.clearDisplay)

    def _evaluateExpression(self, expression: str) -> str:
        """Evaluate an expression."""
        try:
            result = str(eval(expression, {}, {}))
        except Exception:
            result = PyCalcUi.ERROR_MSG
        finally:
            return result
Exemple #26
0
	def __init__(self, parent, data):
		QScrollArea.__init__(self, parent)
		View.__init__(self)
		self.setupView(self)
		self.data = data
		self.currentOffset = 0
		self.byteView = None
		self.fullAnalysisButton = None
		self.importsWidget = None

		container = QWidget(self)
		layout = QVBoxLayout()

		entropyGroup = QGroupBox("Entropy", container)
		entropyLayout = QVBoxLayout()
		entropyLayout.addWidget(entropy.EntropyWidget(entropyGroup, self, self.data))
		entropyGroup.setLayout(entropyLayout)
		layout.addWidget(entropyGroup)

		hdr = None
		try:
			if self.data.view_type == "PE":
				hdr = headers.PEHeaders(self.data)
			elif self.data.view_type != "Raw":
				hdr = headers.GenericHeaders(self.data)
		except:
			log.log_error(traceback.format_exc())

		if hdr is not None:
			headerGroup = QGroupBox("Headers", container)
			headerLayout = QVBoxLayout()
			headerWidget = headers.HeaderWidget(headerGroup, hdr)
			headerLayout.addWidget(headerWidget)
			headerGroup.setLayout(headerLayout)
			layout.addWidget(headerGroup)

		if self.data.executable:
			importExportSplitter = QSplitter(Qt.Horizontal)

			importGroup = QGroupBox("Imports", container)
			importLayout = QVBoxLayout()
			self.importsWidget = imports.ImportsWidget(importGroup, self, self.data)
			importLayout.addWidget(self.importsWidget)
			importGroup.setLayout(importLayout)
			importExportSplitter.addWidget(importGroup)

			exportGroup = QGroupBox("Exports", container)
			exportLayout = QVBoxLayout()
			exportLayout.addWidget(exports.ExportsWidget(exportGroup, self, self.data))
			exportGroup.setLayout(exportLayout)
			importExportSplitter.addWidget(exportGroup)

			layout.addWidget(importExportSplitter)

			if self.data.view_type != "PE":
				segmentsGroup = QGroupBox("Segments", container)
				segmentsLayout = QVBoxLayout()
				segmentsWidget = sections.SegmentsWidget(segmentsGroup, self.data)
				segmentsLayout.addWidget(segmentsWidget)
				segmentsGroup.setLayout(segmentsLayout)
				layout.addWidget(segmentsGroup)
				if len(segmentsWidget.segments) == 0:
					segmentsGroup.hide()

			sectionsGroup = QGroupBox("Sections", container)
			sectionsLayout = QVBoxLayout()
			sectionsWidget = sections.SectionsWidget(sectionsGroup, self.data)
			sectionsLayout.addWidget(sectionsWidget)
			sectionsGroup.setLayout(sectionsLayout)
			layout.addWidget(sectionsGroup)
			if len(sectionsWidget.sections) == 0:
				sectionsGroup.hide()

			buttonLayout = QHBoxLayout()
			buttonLayout.addStretch(1)
			self.loadDynamicButton = QPushButton("Load Dynamic Imports")
			self.loadDynamicButton.clicked.connect(self.importsWidget.scanDynamic)
			buttonLayout.addWidget(self.loadDynamicButton)
			self.fullAnalysisButton = QPushButton("Start Full Analysis")
			self.fullAnalysisButton.clicked.connect(self.startFullAnalysis)
			buttonLayout.addWidget(self.fullAnalysisButton)
			layout.addLayout(buttonLayout)
			layout.addStretch(1)
		else:
			self.byteView = byte.ByteView(self, self.data)
			View.setBinaryDataNavigable(self, True)
			layout.addWidget(self.byteView, 1)

		container.setLayout(layout)
		self.setWidgetResizable(True)
		self.setWidget(container)

		if self.fullAnalysisButton is not None and Settings().get_string("analysis.mode", data) == "full":
			self.fullAnalysisButton.hide()
Exemple #27
0
class GameSettingsDialog(QDialog):
    def __init__(self, parent=None):
        super(GameSettingsDialog, self).__init__(parent)
        self.parent = parent
        self.setModal(True)
        self.setWindowTitle("Game settings")
        self.create_widgets()
        self.set_layouts()

    def create_widgets(self):
        self.label_player1 = QLabel("Player 1")
        self.input_player1_name = QLineEdit()
        self.input_player1_name.setPlaceholderText("Player 1")
        self.input_player1_name.setFocus()
        self.player1_completer = QCompleter()
        self.input_player1_name.setCompleter(self.player1_completer)

        self.label_player2 = QLabel("Player 2")
        self.input_player2_name = QLineEdit()
        self.input_player2_name.setPlaceholderText("Player 2")
        self.player2_completer = QCompleter()
        self.input_player2_name.setCompleter(self.player2_completer)
        # player widget-ek feltültése a db-ben szereplő nevekkel, autocomplete-hez
        self.get_player_name()

        self.gomb_301 = QRadioButton("301")
        self.gomb_401 = QRadioButton("401")
        self.gomb_501 = QRadioButton("501")
        self.gomb_501.setChecked(True)
        self.gomb_701 = QRadioButton("701")

        self.label_bestof = QLabel("Best Of.. (Egyébként First To..)")
        self.best_of = QCheckBox()

        self.spin_legs = QSpinBox()
        self.spin_legs.setValue(3)
        self.spin_legs.setMinimum(1)
        self.spin_legs.setMaximum(21)

        self.spin_sets = QSpinBox()
        self.spin_sets.setValue(1)
        self.spin_sets.setMinimum(1)
        self.spin_sets.setMaximum(15)

        self.handi1 = QSpinBox()
        self.handi1.setValue(0)
        self.handi1.setMinimum(-100)
        self.handi1.setMaximum(100)

        self.handi2 = QSpinBox()
        self.handi2.setValue(0)
        self.handi2.setMinimum(-100)
        self.handi2.setMaximum(100)

        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Reset)
        self.buttonbox.clicked.connect(self.buttonbox_click)

    def set_layouts(self):
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.kontener_names = QHBoxLayout()
        self.kontener_names.addWidget(self.label_player1)
        self.kontener_names.addWidget(self.input_player1_name)
        self.kontener_names.addWidget(self.label_player2)
        self.kontener_names.addWidget(self.input_player2_name)

        self.kontener_buttons = QHBoxLayout()
        self.kontener_buttons.addWidget(self.gomb_301)
        self.kontener_buttons.addWidget(self.gomb_401)
        self.kontener_buttons.addWidget(self.gomb_501)
        self.kontener_buttons.addWidget(self.gomb_701)

        self.bestof_layout = QHBoxLayout()
        self.bestof_layout.addWidget(self.label_bestof)
        self.bestof_layout.addWidget(self.best_of)

        self.kontener_szovegek1 = QVBoxLayout()
        self.kontener_szovegek1.addWidget(
            QLabel("Leave Player 2 blank for single player"))
        self.kontener_szovegek1.addWidget(QLabel("Variant"))

        self.kontener_sets = QHBoxLayout()
        self.kontener_sets.addWidget(QLabel("Legs per set: "))
        self.kontener_sets.addWidget(self.spin_legs)
        self.kontener_sets.addWidget(QLabel("Number os sets: "))
        self.kontener_sets.addWidget(self.spin_sets)

        self.kontener_handi = QHBoxLayout()
        self.kontener_handi.addWidget(QLabel("Handicap (1)"))
        self.kontener_handi.addWidget(self.handi1)
        self.kontener_handi.addWidget(QLabel("Handicap (2)"))
        self.kontener_handi.addWidget(self.handi2)

        self.layout.addLayout(self.kontener_names)
        self.layout.addLayout(self.kontener_szovegek1)
        self.layout.addLayout(self.kontener_buttons)
        self.layout.addLayout(self.bestof_layout)
        self.layout.addLayout(self.kontener_sets)
        self.layout.addLayout(self.kontener_handi)
        self.layout.addWidget(self.buttonbox)

    def get_player_name(self):
        player_name_model = QSqlQueryModel()
        query = QSqlQuery(
            "SELECT player_name  FROM players where type='local' and aktiv=1 order by player_name",
            db=db)
        player_name_model.setQuery(query)
        self.player1_completer.setModel(player_name_model)
        self.player2_completer.setModel(player_name_model)

    def buttonbox_click(self, b):
        if b.text() == "OK":
            self.accept()
        elif b.text() == "Cancel":
            self.reject()
        else:
            self.alapertekek()

    def alapertekek(self):
        self.input_player1_name.setText("")
        self.input_player1_name.setPlaceholderText("Player 1 name")
        self.input_player2_name.setText("")
        self.input_player2_name.setPlaceholderText("Player 2 name")
        self.gomb_501.setChecked(True)
        self.best_of.setChecked(False)
        self.spin_legs.setValue(3)
        self.spin_sets.setValue(1)
        self.handi1.setValue(0)
        self.handi2.setValue(0)

    def accept(self):
        params = []
        m_id = p1_id = p2_id = set = leg = hc1 = hc2 = 0
        var = ""
        player1 = self.input_player1_name.text()
        player2 = self.input_player2_name.text()
        # todo A MATCH_ID-T VALAMI EGYEDI MÓDON KELL GENERÁLNI(pl. az időbélyeg bizonyos részével)
        m_id = random.randint(10, 1000000)
        leg = self.spin_legs.value()
        set = self.spin_sets.value()
        hc1 = self.handi1.value()
        hc2 = self.handi2.value()
        if self.gomb_301.isChecked():
            var = "301"
        elif self.gomb_401.isChecked():
            var = "401"
        elif self.gomb_501.isChecked():
            var = "501"
        else:
            var = "701"

        if self.best_of.isChecked():
            bestof = 1
        else:
            bestof = 0

        if len(player1) == 0:
            p1_id = 1
            player1 = "Player 1"
        else:
            player1_id_model = QSqlQueryModel()
            query1 = QSqlQuery(
                f"SELECT player_id FROM players where player_name = '{player1}' and type='local' and aktiv=1",
                db=db)
            player1_id_model.setQuery(query1)
            # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
            if player1_id_model.record(0).value(0):
                p1_id = int(player1_id_model.record(0).value(0))
            else:
                # todo beszúrás előtt ellenőritni, hogy egyedi-e. Létezhet versenyen felvitt ugyanolyan név
                player_model1 = QSqlTableModel()
                player_model1.setTable("players")
                rec_play1 = player_model1.record()
                rec_play1.remove(0)
                rec_play1.setValue(0, player1)
                rec_play1.setValue(1, 'local')
                rec_play1.setValue(2, 1)
                if player_model1.insertRecord(-1, rec_play1):
                    player_model1.submitAll()
                else:
                    db.rollback()
                query1 = QSqlQuery(
                    f"SELECT player_id FROM players where player_name = '{player1}' and type='local' and aktiv=1",
                    db=db)
                player1_id_model.setQuery(query1)
                # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
                p1_id = int(player1_id_model.record(0).value(0))

        if len(player2) == 0:
            p2_id = 2
            player2 = "Player 2"
        else:
            player2_id_model = QSqlQueryModel()
            query2 = QSqlQuery(
                f"SELECT player_id FROM players where player_name = '{player2}' and type='local' and aktiv=1",
                db=db)
            player2_id_model.setQuery(query2)
            # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
            if player2_id_model.record(0).value(0):
                p2_id = int(player2_id_model.record(0).value(0))
            else:
                player_model2 = QSqlTableModel()
                player_model2.setTable("players")
                rec_play2 = player_model2.record()
                rec_play2.remove(0)
                rec_play2.setValue(0, player2)
                rec_play2.setValue(1, 'local')
                rec_play2.setValue(2, 1)
                if player_model2.insertRecord(-1, rec_play2):
                    player_model2.submitAll()
                else:
                    db.rollback()
                query2 = QSqlQuery(
                    f"SELECT player_id FROM players where player_name = '{player2}' and type='local' and aktiv=1",
                    db=db)
                player2_id_model.setQuery(query2)
                # todo megnézni, hogy sima query.exec_ -el hogyan működik, lehet-e ellenőrizni, hogy üres vagy nem
                p2_id = int(player2_id_model.record(0).value(0))

        # Match paremeterek rögzítése
        now = QDateTime.currentDateTime()
        match_model = QSqlTableModel()
        match_model.setTable("match_settings")
        # todo Best Of... nincs db-ben tárolva
        record = match_model.record()
        record.setValue(0, m_id)
        record.setValue(1, p1_id)
        record.setValue(2, p2_id)
        record.setValue(3, var)
        record.setValue(4, leg)
        record.setValue(5, set)
        record.setValue(6, hc1)
        record.setValue(7, hc2)
        record.setValue(8, now)
        if match_model.insertRecord(-1, record):
            match_model.submitAll()
        else:
            db.rollback()
        params.append(player1)
        params.append(player2)
        params.append(m_id)
        params.append(p1_id)
        params.append(p2_id)
        params.append(var)
        params.append(leg)
        params.append(set)
        params.append(hc1)
        params.append(hc2)
        params.append(bestof)
        self.parent.new_game_window.params = params
        self.parent.new_game_window.refresh()
        super().accept()

    def reject(self):
        self.parent.new_game_window.close()
        super().reject()
 def initUI(self):
     # Main Layout
     mainlayout = QVBoxLayout()
     mainlayout.setContentsMargins(0, 0, 0, 0)
     mainlayout.setMargin(5)
     mainlayout.setSpacing(0)
     videoFrame = video_frame()
     mainlayout.addWidget(videoFrame)
     vframeID = videoFrame.winId()
     if sys.platform.startswith('linux'):  # linux
         self.mPlayer.set_xwindow(vframeID)
     elif sys.platform == "win32":  # windows
         self.mPlayer.set_hwnd(vframeID)
     elif sys.platform == "darwin":  # mac
         self.mPlayer.set_nsobject(vframeID)
     # Connect to Slot
     videoFrame.fileDroped.connect(self.loadVideoFile)
     vctrl_layout = QHBoxLayout()
     # Previous Frame
     btn_pf = QPushButton()
     btn_pf.setFixedSize(QSize(32, 32))
     ico_pf = QIcon(QPixmap(resource_path("icons/previous.png")))
     btn_pf.setIcon(ico_pf)
     btn_pf.clicked.connect(self.previousFrame)
     # Rewind
     btn_rewind = QPushButton()
     btn_rewind.setFixedSize(QSize(32, 32))
     ico_re = QIcon(QPixmap(resource_path("icons/rewind.png")))
     btn_rewind.setIcon(ico_re)
     btn_rewind.clicked.connect(self.rewind)
     # btn_rewind.release.connect(self.playVideo)
     btn_rewind.setAutoRepeat(True)
     btn_rewind.setAutoRepeatInterval(1000)
     btn_rewind.setAutoRepeatDelay(1000)
     # Play
     btn_play = QPushButton()
     btn_play.setFixedSize(QSize(32, 32))
     ico_play = QIcon(QPixmap(
         resource_path("icons/play-button.png")))  # "icons/play-button.png"
     btn_play.setIcon(ico_play)
     btn_play.clicked.connect(self.playVideo)
     # Pause
     btn_pause = QPushButton()
     btn_pause.setFixedSize(QSize(32, 32))
     ico_pause = QIcon(QPixmap(resource_path("icons/pause-button.png")))
     btn_pause.setIcon(ico_pause)
     btn_pause.clicked.connect(self.pauseVideo)
     # Fast Forward
     btn_ff = QPushButton()
     btn_ff.setFixedSize(QSize(32, 32))
     ico_ff = QIcon(QPixmap(resource_path("icons/fast-forward.png")))
     btn_ff.setIcon(ico_ff)
     btn_ff.clicked.connect(self.fastforward)
     # Next Frame
     btn_nf = QPushButton()
     btn_nf.setFixedSize(QSize(32, 32))
     ico_nf = QIcon(QPixmap(resource_path("icons/next.png")))
     btn_nf.setIcon(ico_nf)
     btn_nf.clicked.connect(self.nextFrame)
     # Video Lenght Slider
     self.video_slider = QSlider(Qt.Orientation.Horizontal)
     self.video_slider.setMinimum(0)
     self.video_slider.setMaximum(1000)  # Rough
     # self.video_slider.sliderPressed.connect(self.pauseVideo)
     self.video_slider.sliderMoved.connect(self.vslider_moved)
     self.video_slider.sliderReleased.connect(self.vslider_released)
     # self.video_slider.valueChanged.connect(self.sliderChanged)
     # Duration
     self.tcPos = QLabel("00:00:00:00")
     self.tcPos.setMaximumHeight(20)
     self.tcPos.setStyleSheet("border: 1px solid black")
     vctrl_layout.addWidget(btn_pf)
     vctrl_layout.addWidget(btn_rewind)
     vctrl_layout.addWidget(btn_play)
     vctrl_layout.addWidget(btn_pause)
     vctrl_layout.addWidget(btn_ff)
     vctrl_layout.addWidget(btn_nf)
     vctrl_layout.addWidget(self.video_slider)
     vctrl_layout.addWidget(self.tcPos)
     mainlayout.addLayout(vctrl_layout, 1)
     self.setLayout(mainlayout)
     self.show()
     self.timer.setInterval(200)
     self.timer.timeout.connect(self.vslider_posUpdate)
    def __init__(self, targetImage=None, size=200, layer=None, parent=None):
        super().__init__(layer=layer, targetImage=targetImage, parent=parent)
        self.mode = 'Luminosity'
        self.chanColors = [Qt.gray]
        self.setWindowTitle('Histogram')
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.setMinimumSize(size, 100)
        self.Label_Hist = QLabel()
        self.Label_Hist.setScaledContents(True)
        self.Label_Hist.setFocusPolicy(Qt.ClickFocus)
        self.setStyleSheet("QListWidget{border: 0px; font-size: 12px}")

        # options
        options1, optionNames1 = ['Original Image'], ['Source']
        self.listWidget1 = optionsWidget(options=options1,
                                         optionNames=optionNames1,
                                         exclusive=False)
        self.listWidget1.setFixedSize(
            (self.listWidget1.sizeHintForColumn(0) + 15) * len(options1), 20)
        options2, optionNames2 = ['R', 'G', 'B', 'L'], ['R', 'G', 'B', 'L']
        self.listWidget2 = optionsWidget(options=options2,
                                         optionNames=optionNames2,
                                         exclusive=False,
                                         flow=optionsWidget.LeftToRight)
        #self.listWidget2.setFixedSize((self.listWidget2.sizeHintForRow(0) + 15) * len(options2), 20)
        self.listWidget2.setFixedSize(
            (self.listWidget2.sizeHintForRow(0) + 20) * len(options2),
            20)  # + 20 needed to prevent scroll bar on ubuntu
        # default: show color hists only
        for i in range(3):
            self.listWidget2.checkOption(self.listWidget2.intNames[i])
        self.options = UDict(
            (self.listWidget1.options, self.listWidget2.options))
        self.setWhatsThis("""
        <b>Histogram</b><br>
        The histogram shows the initial or final color ditribution of the image, depending on 
        whether the <I>Source</I> option is checked or not. 
        """)

        def onSelect(item):
            try:
                self.targetImage.onImageChanged()
                self.Label_Hist.update()
            except AttributeError:
                return

        self.listWidget1.onSelect = onSelect
        self.listWidget2.onSelect = onSelect

        # layout
        h = QHBoxLayout()
        h.setContentsMargins(0, 0, 0, 2)
        h.addStretch(1)
        h.addWidget(self.listWidget1)
        h.addStretch(1)
        h.addWidget(self.listWidget2)
        h.addStretch(1)
        vl = QVBoxLayout()
        #vl.setAlignment(Qt.AlignTop)  prevent the histogram from stretching vertically
        vl.addWidget(self.Label_Hist)
        vl.addLayout(h)
        vl.setContentsMargins(0, 0, 0, 2)  # left, top, right, bottom
        self.setLayout(vl)
        self.adjustSize()
class QGroundObjectMenu(QDialog):

    changed = QtCore.Signal()

    def __init__(self, parent, ground_object: TheaterGroundObject,
                 buildings: Optional[List[TheaterGroundObject]],
                 cp: ControlPoint, game: Game):
        super().__init__(parent)
        self.setMinimumWidth(350)
        self.ground_object = ground_object
        if buildings is None:
            self.buildings = []
        else:
            self.buildings = buildings
        self.cp = cp
        self.game = game
        self.setWindowTitle("Location " + self.ground_object.obj_name)
        self.setWindowIcon(EVENT_ICONS["capture"])
        self.intelBox = QGroupBox("Units :")
        self.buildingBox = QGroupBox("Buildings :")
        self.intelLayout = QGridLayout()
        self.buildingsLayout = QGridLayout()
        self.sell_all_button = None
        self.total_value = 0
        self.init_ui()

    def init_ui(self):

        self.mainLayout = QVBoxLayout()
        self.budget = QBudgetBox(self.game)
        self.budget.setGame(self.game)

        self.doLayout()

        if self.ground_object.dcs_identifier == "AA":
            self.mainLayout.addWidget(self.intelBox)
        else:
            self.mainLayout.addWidget(self.buildingBox)
            if self.cp.captured:
                self.mainLayout.addWidget(self.financesBox)

        self.actionLayout = QHBoxLayout()

        self.sell_all_button = QPushButton("Disband (+" +
                                           str(self.total_value) + "M)")
        self.sell_all_button.clicked.connect(self.sell_all)
        self.sell_all_button.setProperty("style", "btn-danger")

        self.buy_replace = QPushButton("Buy/Replace")
        self.buy_replace.clicked.connect(self.buy_group)
        self.buy_replace.setProperty("style", "btn-success")

        if not isinstance(self.ground_object, NavalGroundObject):
            if self.total_value > 0:
                self.actionLayout.addWidget(self.sell_all_button)
            self.actionLayout.addWidget(self.buy_replace)

        if self.cp.captured and self.ground_object.dcs_identifier == "AA":
            self.mainLayout.addLayout(self.actionLayout)
        self.setLayout(self.mainLayout)

    def doLayout(self):

        self.update_total_value()
        self.intelBox = QGroupBox("Units :")
        self.intelLayout = QGridLayout()
        i = 0
        for g in self.ground_object.groups:
            if not hasattr(g, "units_losts"):
                g.units_losts = []
            for u in g.units:
                unit_display_name = u.type
                unit_type = vehicles.vehicle_map.get(u.type)
                if unit_type is not None:
                    unit_display_name = db.unit_get_expanded_info(
                        self.game.enemy_country, unit_type, 'name')
                self.intelLayout.addWidget(
                    QLabel("<b>Unit #" + str(u.id) + " - " +
                           str(unit_display_name) + "</b>"), i, 0)
                i = i + 1

            for u in g.units_losts:

                utype = unit_type_of(u)
                if utype in PRICES:
                    price = PRICES[utype]
                else:
                    price = 6

                self.intelLayout.addWidget(
                    QLabel("<b>Unit #" + str(u.id) + " - " + str(u.type) +
                           "</b> [DEAD]"), i, 0)
                if self.cp.captured:
                    repair = QPushButton("Repair [" + str(price) + "M]")
                    repair.setProperty("style", "btn-success")
                    repair.clicked.connect(
                        lambda u=u, g=g, p=price: self.repair_unit(g, u, p))
                    self.intelLayout.addWidget(repair, i, 1)
                i = i + 1
        stretch = QVBoxLayout()
        stretch.addStretch()
        self.intelLayout.addLayout(stretch, i, 0)

        self.buildingBox = QGroupBox("Buildings :")
        self.buildingsLayout = QGridLayout()

        j = 0
        total_income = 0
        received_income = 0
        for i, building in enumerate(self.buildings):
            if building.dcs_identifier not in FORTIFICATION_BUILDINGS:
                self.buildingsLayout.addWidget(
                    QBuildingInfo(building, self.ground_object), j / 3, j % 3)
                j = j + 1

            if building.category in REWARDS.keys():
                total_income = total_income + REWARDS[building.category]
                if not building.is_dead:
                    received_income = received_income + REWARDS[
                        building.category]
            else:
                logging.warning(building.category + " not in REWARDS")

        self.financesBox = QGroupBox("Finances: ")
        self.financesBoxLayout = QGridLayout()
        self.financesBoxLayout.addWidget(
            QLabel("Available: " + str(total_income) + "M"), 2, 1)
        self.financesBoxLayout.addWidget(
            QLabel("Receiving: " + str(received_income) + "M"), 2, 2)

        self.financesBox.setLayout(self.financesBoxLayout)
        self.buildingBox.setLayout(self.buildingsLayout)
        self.intelBox.setLayout(self.intelLayout)

    def do_refresh_layout(self):
        try:
            for i in range(self.mainLayout.count()):
                item = self.mainLayout.itemAt(i)
                if item is not None and item.widget() is not None:
                    item.widget().setParent(None)
            self.sell_all_button.setParent(None)
            self.buy_replace.setParent(None)
            self.actionLayout.setParent(None)

            self.doLayout()
            if self.ground_object.dcs_identifier == "AA":
                self.mainLayout.addWidget(self.intelBox)
            else:
                self.mainLayout.addWidget(self.buildingBox)

            self.actionLayout = QHBoxLayout()
            if self.total_value > 0:
                self.actionLayout.addWidget(self.sell_all_button)
            self.actionLayout.addWidget(self.buy_replace)

            if self.cp.captured and self.ground_object.dcs_identifier == "AA":
                self.mainLayout.addLayout(self.actionLayout)

        except Exception as e:
            print(e)
        self.update_total_value()
        self.changed.emit()

    def update_total_value(self):
        total_value = 0
        for group in self.ground_object.groups:
            for u in group.units:
                utype = unit_type_of(u)
                if utype in PRICES:
                    total_value = total_value + PRICES[utype]
                else:
                    total_value = total_value + 1
        if self.sell_all_button is not None:
            self.sell_all_button.setText("Disband (+$" +
                                         str(self.total_value) + "M)")
        self.total_value = total_value

    def repair_unit(self, group, unit, price):
        if self.game.budget > price:
            self.game.budget -= price
            group.units_losts = [
                u for u in group.units_losts if u.id != unit.id
            ]
            group.units.append(unit)
            GameUpdateSignal.get_instance().updateGame(self.game)

            # Remove destroyed units in the vicinity
            destroyed_units = self.game.get_destroyed_units()
            for d in destroyed_units:
                p = Point(d["x"], d["z"])
                if p.distance_to_point(unit.position) < 15:
                    destroyed_units.remove(d)
                    logging.info("Removed destroyed units " + str(d))
            logging.info("Repaired unit : " + str(unit.id) + " " +
                         str(unit.type))

        self.do_refresh_layout()
        self.changed.emit()

    def sell_all(self):
        self.update_total_value()
        self.game.budget = self.game.budget + self.total_value
        self.ground_object.groups = []
        self.do_refresh_layout()
        GameUpdateSignal.get_instance().updateBudget(self.game)

    def buy_group(self):
        self.subwindow = QBuyGroupForGroundObjectDialog(
            self, self.ground_object, self.cp, self.game, self.total_value)
        self.subwindow.changed.connect(self.do_refresh_layout)
        self.subwindow.show()
Exemple #31
0
    def __init__(self, filenames: list, *args, **kwargs):
        super(ImportParamDialog, self).__init__(*args, **kwargs)

        self.import_widgets = []

        self.setWindowTitle("Video Import Options")

        self.import_types = [
            {
                "video_type":
                "hdf5",
                "match":
                "h5,hdf5",
                "video_class":
                Video.from_hdf5,
                "params": [
                    {
                        "name": "dataset",
                        "type": "function_menu",
                        "options": "_get_h5_dataset_options",
                        "required": True,
                    },
                    {
                        "name": "input_format",
                        "type": "radio",
                        "options": "channels_first,channels_last",
                        "required": True,  # we can't currently auto-detect
                    },
                ],
            },
            {
                "video_type": "mp4",
                "match": "mp4,avi",
                "video_class": Video.from_media,
                "params": [{
                    "name": "grayscale",
                    "type": "check"
                }],
            },
            {
                "video_type": "imgstore",
                "match": "json",
                "video_class": Video.from_filename,
                "params": [],
            },
        ]

        outer_layout = QVBoxLayout()

        scroll_widget = QScrollArea()
        # scroll_widget.setWidgetResizable(False)
        scroll_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        scroll_items_widget = QWidget()
        scroll_layout = QVBoxLayout()
        for file_name in filenames:
            if file_name:
                this_type = None
                for import_type in self.import_types:
                    if import_type.get("match", None) is not None:
                        if file_name.lower().endswith(
                                tuple(import_type["match"].split(","))):
                            this_type = import_type
                            break
                if this_type is not None:
                    import_item_widget = ImportItemWidget(file_name, this_type)
                    self.import_widgets.append(import_item_widget)
                    scroll_layout.addWidget(import_item_widget)
                else:
                    raise Exception("No match found for file type.")
        scroll_items_widget.setLayout(scroll_layout)
        scroll_widget.setWidget(scroll_items_widget)
        outer_layout.addWidget(scroll_widget)

        button_layout = QHBoxLayout()
        cancel_button = QPushButton("Cancel")
        import_button = QPushButton("Import")
        import_button.setDefault(True)
        button_layout.addStretch()
        button_layout.addWidget(cancel_button)
        button_layout.addWidget(import_button)

        outer_layout.addLayout(button_layout)

        self.setLayout(outer_layout)

        import_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
Exemple #32
0
    def __init__(self, layer=None):
        super(segmentForm, self).__init__()
        self.setWindowTitle('grabcut')
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.setMinimumSize(200, 200)
        self.setAttribute(Qt.WA_DeleteOnClose)
        # link back to image layer
        self.layer = weakProxy(layer)
        pushButton = QPushButton('apply')
        # button slot
        def f():
            self.layer.noSegment = False
            self.layer.applyToStack()
            window.label.img.onImageChanged()
            # do manual segmentation only
            layer.noSegment = True
        pushButton.clicked.connect(f)

        pushButton1 = QPushButton('Reset')
        pushButton1.clicked.connect(lambda : self.reset())

        self.spBox = QSpinBox()
        self.spBox.setRange(1,10)
        # spBox Slot
        def f2(iterCount):
            self.spBox.valueChanged.disconnect()
            self.dataChanged.emit()
            self.spBox.valueChanged.connect(f2)
        self.spBox.valueChanged.connect(f2)
        spBoxLabel = QLabel()
        spBoxLabel.setText('Iterations')

        self.spBox1 = QSpinBox()
        self.spBox1.setRange(0, 20)
        spBox1Label = QLabel()
        spBox1Label.setText('Contour Margin')
        # spBox1 slot
        def f1(margin):
            self.spBox1.valueChanged.disconnect()
            self.dataChanged.emit()
            self.spBox1.valueChanged.connect(f1)
        self.spBox1.valueChanged.connect(f1)

        # options
        optionList1, optionNames1 = ['Clipping Layer'], ['Clipping Layer']
        self.listWidget1 = optionsWidget(options=optionList1, optionNames=optionNames1, exclusive=False)
        self.options = self.listWidget1.options
        # option changed slot
        def g(item):
            self.layer.isClipping = self.options['Clipping Layer']
            self.layer.applyToStack()
            self.layer.parentImage.onImageChanged()
        self.listWidget1.onSelect = g

        # attributes initialized in setDefaults, declared here
        # for the sake of correctness
        self.start = None
        self.nbIter = None
        self.contourMargin = None

        # layout
        hLay = QHBoxLayout()
        hLay.addWidget(spBoxLabel)
        hLay.addWidget(self.spBox)
        hLay.addStretch(1)
        hLay1 = QHBoxLayout()
        hLay1.addWidget(spBox1Label)
        hLay1.addWidget(self.spBox1)
        hLay1.addStretch(1)
        h2 = QHBoxLayout()
        h2.addWidget(self.listWidget1)
        vLay = QVBoxLayout()
        vLay.setAlignment(Qt.AlignTop)
        vLay.setContentsMargins(20, 8, 20, 25)  # left, top, right, bottom
        vLay.addLayout(hLay)
        vLay.addLayout(hLay1)
        vLay.addLayout(h2)
        h3 = QHBoxLayout()
        h3.addWidget(pushButton)
        h3.addWidget(pushButton1)
        vLay.addLayout(h3)
        self.setLayout(vLay)
        self.setDefaults()
        self.setWhatsThis(
""" <b>Object extraction</b><br>  
  Select the object to extract with the rectangle Marquee Tool. Next, click the Apply button.<br>
  Correct (roughly) if needed the foreground (FG) and the background (BG) regions using the FG and BG tools (Ctrl to undo) and click again the Apply button.<br>
  To get a smoother contour increase the value of the Contour Margin and click the Apply Button.<br>
  By default the mask is displayed as a color mask. To view it as an opacity mask, right click on the Segmentation layer row in the right pane and check Enable Mask As > Opacity Mask in the context menu.
  Use the same context menu to copy/paste the object to a new image layer or the mask to another layer.<br>
  
"""
                        )  # end setWhatsThis
Exemple #33
0
class Window(QWidget):
    """docstring for Window"""
    def __init__(self):
        super(Window, self).__init__()
        self.setWindowTitle("PyTextSpeech")
        self.resize(400, 400)

        self.volume = 0
        self.rate = 0
        self.engine = QSpeak()
        self.doc = Document()
        self.mn = Menu()
        self.text_to_read = QTextEdit()
        self.vlayout = QVBoxLayout()
        self.sliders = SliderGrop()

        self.cmbgrop = ComboGrop()

        self.lbtn = Boton()
        self.doc.parent = self
        self.lbtn.btnSpeak.clicked.connect(self.Speak)
        self.lbtn.btnPause.clicked.connect(self.Pause)
        self.lbtn.btnResume.clicked.connect(self.Resume)
        self.lbtn.btnStop.clicked.connect(self.Stop)

        self.sliders.slider_volume.valueChanged.connect(self.SliderVolume)
        self.sliders.slider_rate.valueChanged.connect(self.SliderRate)

        self.cmbgrop.cmbVoice.currentTextChanged.connect(self.Voice)
        self.cmbgrop.cmbLanguage.currentTextChanged.connect(self.Locale)

        self.mn.Pdf.triggered.connect(self.Abrir_Pdf)
        self.mn.Texto.triggered.connect(self.Abrir_Text)

        self.LoadLanguage()
        self.LoadVoices()

        self.vlayout.addWidget(self.mn)
        self.vlayout.addWidget(self.text_to_read)

        self.vlayout.addLayout(self.sliders)
        self.vlayout.addLayout(self.cmbgrop)
        self.vlayout.addLayout(self.lbtn)

        self.setLayout(self.vlayout)

    def Abrir_Pdf(self):
        text = self.doc.AbrirPDF()
        self.text_to_read.setText(text)

    def Abrir_Text(self):
        self.text_to_read.setText(self.doc.AbrirText())

    def LoadVoices(self):
        voices = self.engine.getVoices()

        for i in voices:
            self.cmbgrop.cmbVoice.addItem(i.name())

    def LoadLanguage(self):
        locales = self.engine.getLocale()

        for i in locales:
            self.cmbgrop.cmbLanguage.addItem(
                QLocale.countryToString(i.country()))

    def Voice(self):
        try:
            voices = self.engine.getVoices()

            self.engine.Voice(voices[self.cmbgrop.cmbVoice.currentIndex()])

        except:
            msg = QMessageBox()
            msg.setWindowTitle('Error')
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setText('Voz no disponible')
            msg.exec_()

    def Locale(self):
        try:
            locales = self.engine.getLocale()
            self.engine.Locale(
                locales[self.cmbgrop.cmbLanguage.currentIndex()])
        except:
            msg = QMessageBox()
            msg.setWindowTitle(self.tr('Error'))
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setText('Lenguaje no disponible')
            msg.exec_()

    def SliderVolume(self):
        self.engine.setVolume(float(self.sliders.slider_volume.value() / 100))

    def SliderRate(self):
        self.engine.setRate(self.sliders.slider_rate.value() / 100)

    def SliderPitch(self):
        self.engine.setPitch(self.sliders.slider_pitch.value() / 100)

    def Speak(self):
        self.parent.setOverrideCursor(Qt.WaitCursor)
        self.engine.say(self.text_to_read.toPlainText())
        self.parent.restoreOverrideCursor()

    def Pause(self):
        self.engine.pause()

    def Resume(self):
        self.engine.resume()

    def Stop(self):
        self.engine.stop()
Exemple #34
0
class MainWindow(QWidget):
    """
    Créer la fenêtre principale
    """
    def __init__(self):
        QWidget.__init__(self)
        """
        PROCESSING ATTRIBUTES
        """
        self.loop_simulation = False
        self.parameters_window = None

        self.term = Terminal()
        self.stl_model = None
        self.stl_model_pressure = None
        self.stl_model_display = None

        self.object_mass = DEFAULT_OBJECT_MASS
        self.dichotomy_precision = DEFAULT_DICHOTOMY_PRECISION
        self.fluid_density = DEFAULT_FLUID_DENSITY

        self.show_draught = DEFAULT_SHOW_DRAUGHT

        self.setWindowTitle("G5 SIMULATION OBJECT FLOTABILITY")
        self.setFixedSize(1280, 1024)

        self.main_layout = QVBoxLayout()
        self.main_layout.setMargin(0)
        self.main_layout.setSpacing(0)
        self.setLayout(self.main_layout)
        """
        TOPBAR WIDGETS
        """
        self.topbar_layout = QGridLayout()
        self.topbar_layout.setAlignment(Qt.AlignTop)
        self.topbar_layout.setSpacing(32)

        buttons_icons = [
            'stl_file', 'parameters', 'prepare_simulation', 'start_simulation',
            'loop_simulation', 'stop_simulation', 'generate_animation_gif'
        ]
        group_buttons_labels = ['LOAD 3D MODEL', 'PARAMETERS', 'SIMULATION']
        buttons_slots = [
            self.loadSTLModel, self.displayParametersWindow,
            self.prepareSimulation, self.startSimulation, self.loopSimulation,
            self.stopSimulation, self.generateAnimationsGIF
        ]
        buttons_tooltips = [
            'Load 3d model', 'Set parameters', 'Prepare the simulation',
            'Start the simulation', 'Loop the simulation',
            'Stop the simulation', 'Generate animations GIF'
        ]
        self.buttons = [QPushButton() for i in range(7)]
        for i, button in enumerate(self.buttons):
            button.setIcon(QIcon(ICONS_FOLDER + buttons_icons[i] +
                                 '_icon.png'))
            button.setIconSize(QSize(50, 50))
            button.setStyleSheet('border:none; margin-top : 24px;')
            button.clicked.connect(buttons_slots[i])
            button.setToolTip(buttons_tooltips[i])
            if i > 0: button.setDisabled(True)
            self.topbar_layout.addWidget(button, 0, i, 1, 1)

        for i, group_buttons_label in enumerate(group_buttons_labels):
            label = QLabel(group_buttons_label)
            label.setFixedHeight(32)
            label.setAlignment(Qt.AlignCenter)
            label.setStyleSheet(
                'border-top : 2px solid #dfdfdf; font-family: Calibri; font-size : 10pt; color: #2C3E50;'
            )
            self.topbar_layout.addWidget(label, 1, i, 1, 1 if i != 2 else 5)
        self.main_layout.addLayout(self.topbar_layout)
        """
        BODY_WIDGETS
        """
        self.body_layout = QGridLayout()
        self.body_layout.setSpacing(0)

        self.stl_model_graph = QLabel()
        self.stl_model_graph.setPixmap(QPixmap(DEFAULT_STL_MODEL_GRAPH_FOLDER))
        self.stl_model_graph.setFixedSize(640, 480)

        self.draught_graph = QLabel()
        self.draught_graph.setPixmap(QPixmap(DEFAULT_DRAUGHT_GRAPH_FOLDER))
        self.draught_graph.setFixedSize(640, 480)

        self.body_layout.addWidget(self.stl_model_graph, 0, 0, 1, 1)
        self.body_layout.addWidget(self.draught_graph, 0, 1, 1, 1)

        self.colored_parts_legend = QLabel()
        self.colored_parts_legend.setPixmap(
            QPixmap(LEGEND_FOLDER + 'colored_parts_legend.png'))
        self.colored_parts_legend.setStyleSheet(
            'padding : 0 0 13px 24px; background : #fff')
        self.body_layout.addWidget(self.colored_parts_legend, 1, 0, 1, 2)

        self.draught_legend = QLabel()
        self.draught_legend.setPixmap(
            QPixmap(LEGEND_FOLDER + 'draught_legend.png'))
        self.draught_legend.setStyleSheet(
            'padding : 0 0 13px 24px; background : #fff')
        self.draught_legend.hide()
        self.body_layout.addWidget(self.draught_legend, 2, 0, 1, 2)

        self.term.setFixedWidth(1280)
        self.main_layout.addLayout(self.body_layout)
        self.main_layout.addWidget(self.term)

        self.show()

    def updatePreview(self, show_draught=False):
        self.stl_model_display.emptyFolder(STL_MODEL_LOADED_VIEW_FOLDER)
        self.stl_model_display.saveSTLModelGraph(STL_MODEL_LOADED_VIEW_FOLDER,
                                                 'preview', show_draught)
        self.term.addProcessMessage(
            'Displaying of the updated preview of the STL model')
        self.stl_model_graph.setPixmap(
            QPixmap(STL_MODEL_LOADED_VIEW_FOLDER + 'preview.png'))

    def loadSTLModel(self):
        """
        Charger la maquette du fichier STL sélectionné et afficher un aperçu
        """
        ### BEFORE PROCESS
        for i in range(1, 7):
            self.buttons[i].setDisabled(True)
        ### START_PROCESS
        self.explorer = QFileDialog()
        self.explorer.setNameFilter("*.stl")
        if self.explorer.exec_():
            self.stl_model = STLModel(self.explorer.selectedFiles()[0],
                                      self.term)
            if self.stl_model.facets_number != 0:
                self.initial_bottom_ref = self.stl_model.bottom_ref
                self.stl_model_display = STLModelDisplay(
                    self.stl_model, self.term)

                self.updatePreview()

                ### END_PROCESS
                self.buttons[1].setDisabled(False)
                self.buttons[2].setDisabled(False)
                self.term.addSuccessMessage('STL model properly loaded')

    def displayParametersWindow(self):
        """
        Appeler la classe ParametersWindow pour afficher la fenêtre de paramètres
        """
        self.term.addInformativeMessage('Display the parameters window')
        self.parameters_window = ParametersWindow(self)

    def prepareSimulation(self):
        """
        Lancer l'algorithme de dichotomie et enregistrer les graphiques étape par étape
        """
        ### BEFORE_PROCESS
        self.buttons[2].setDisabled(True)

        # reset
        self.stl_model.translateZ(self.initial_bottom_ref -
                                  self.stl_model.bottom_ref)
        self.updatePreview(self.show_draught)

        if isinstance(self.parameters_window, ParametersWindow):
            self.parameters_window.close()
        for i in range(7):
            if i != 2: self.buttons[i].setDisabled(True)
        X, Y = [0], [
            -self.stl_model.bottom_ref if self.stl_model.bottom_ref < 0 else 0
        ]

        self.stl_model_display.emptyFolder(STL_MODEL_GRAPHS_FOLDER)
        self.stl_model_display.emptyFolder(DRAUGHT_GRAPHS_FOLDER)

        self.stl_model_display.saveSTLModelGraph(STL_MODEL_GRAPHS_FOLDER,
                                                 FRAMES_BASENAME + '0')
        self.stl_model_display.saveDraughGraph(FRAMES_BASENAME + '0', X, Y,
                                               self.dichotomy_precision)

        self.stl_model_pressure = STLModelPressure(self.stl_model, self.term)

        self.stl_model.setMass(self.object_mass)
        self.stl_model_pressure.setFluidDensity(self.fluid_density)
        ### START_PROCESS
        self.term.addProcessMessage('Launching the dichotomy algorithm')
        while self.stl_model_pressure.draught_range[
                1] - self.stl_model_pressure.draught_range[
                    0] > self.dichotomy_precision:
            Y.append(self.stl_model_pressure.dichotomy())
            X.append(self.stl_model_pressure.dichotomy_achieved)
            self.stl_model_display.saveSTLModelGraph(
                STL_MODEL_GRAPHS_FOLDER, FRAMES_BASENAME +
                str(self.stl_model_pressure.dichotomy_achieved),
                self.show_draught)
            self.stl_model_display.saveDraughGraph(
                FRAMES_BASENAME +
                str(self.stl_model_pressure.dichotomy_achieved), X, Y,
                self.dichotomy_precision)
        self.term.addSuccessMessage('Preparation of the simulation complete')
        ### END_PROCESS
        for i in range(7):
            if i != 5: self.buttons[i].setDisabled(False)
            if i == 2: self.buttons[i].setDisabled(True)

    def startSimulation(self):
        """
        Lancer l'animation des graphiques en asynchrone pour ne pas bloquer les clicked event
        """
        thread = threading.Thread(target=self._startSimulation)
        thread.start()

    def _startSimulation(self):
        """
        Recuperer et afficher avec une temporisation les images des graphiques afin de constituer l'animation
        """
        ### BEFORE PROCESS
        for i in range(7):
            if i != 5: self.buttons[i].setDisabled(True)

        self.term.addProcessMessage(
            'Recovery of all the images needed for the animation')
        stl_model_frames = os.listdir(STL_MODEL_GRAPHS_FOLDER)
        stl_model_frames = sorted(
            stl_model_frames,
            key=lambda frame: int(
                frame.replace(FRAMES_BASENAME, '').split('.')[0]))
        stl_draught_frames = os.listdir(DRAUGHT_GRAPHS_FOLDER)
        stl_draught_frames = sorted(
            stl_draught_frames,
            key=lambda frame: int(
                frame.replace(FRAMES_BASENAME, '').split('.')[0]))
        self.term.addSuccessMessage('All the images have been recovered')
        self.term.addInformativeMessage('Launching simulation animation')
        frames_number = len(stl_model_frames)
        if frames_number == len(stl_draught_frames):
            for i in range(frames_number):
                self.stl_model_graph.setPixmap(STL_MODEL_GRAPHS_FOLDER +
                                               stl_model_frames[i])
                self.draught_graph.setPixmap(DRAUGHT_GRAPHS_FOLDER +
                                             stl_draught_frames[i])
                time.sleep(.1)
            while self.loop_simulation:
                for i in range(frames_number):
                    self.stl_model_graph.setPixmap(STL_MODEL_GRAPHS_FOLDER +
                                                   stl_model_frames[i])
                    self.draught_graph.setPixmap(DRAUGHT_GRAPHS_FOLDER +
                                                 stl_draught_frames[i])
                    time.sleep(.1)
            self.term.addSuccessMessage(
                'Animation of the simulation correctly carried out')
            for i in range(7):
                if i in [0, 1, 3, 4, 6]: self.buttons[i].setDisabled(False)
        else:
            self.term.addErrorMessage(
                'An error occurred during frames synchronization')

    def loopSimulation(self):
        """
        Activer ou désactive la répétition infinie de l'animation
        """
        self.loop_simulation = not self.loop_simulation
        loop_button = self.buttons[4]
        stop_button = self.buttons[5]
        loop_icon = 'loop_simulation_icon.png'
        if self.loop_simulation:
            loop_icon = 'selected_' + loop_icon
            stop_button.setDisabled(False)
            self.term.addInformativeMessage(
                'The displayed simulation will now be looped')
        else:
            stop_button.setDisabled(True)
            self.term.addInformativeMessage(
                'The displayed simulation will now be played only once')
        loop_button.setIcon(QIcon(ICONS_FOLDER + loop_icon))

    def stopSimulation(self):
        """
        Interrompre la boucle pour arrêter l'animation
        """
        self.loop_simulation = False
        loop_button = self.buttons[4]
        stop_button = self.buttons[5]
        loop_button.setIcon(QIcon(ICONS_FOLDER + 'loop_simulation_icon.png'))
        stop_button.setDisabled(True)
        self.term.addInformativeMessage('Simulation properly stopped')

    def generateAnimationsGIF(self):
        """
        Générer et télécharger des GIF de la simulation produite
        """
        self.stl_model_display.generateGIFAnimations()
Exemple #35
0
class NodeAddDialog(QDialog):
    def __init__(self, parent=None, text='',):
        super(NodeAddDialog, self).__init__(parent)
        self._node = 0
        self._text = text
        self._answer = []
        self._answer.append(0)
        self._answer.append(0)
        self.ln_question = QLineEdit()
        self.ln_question.setText(self._text)
        self.ln_question.editingFinished.connect(self.setText)
        self.layoutH1 = QHBoxLayout()
        self.btn_add = QPushButton()
        self.btn_add.setText('Add')
        self.btn_cansel = QPushButton()
        self.btn_cansel.setText('Cansel')
        self.btn_add.clicked.connect(self.addNode)
        self.btn_cansel.clicked.connect(self.decline)
        self.layoutH1.addWidget(self.btn_add)
        self.layoutH1.addWidget(self.btn_cansel)
        self.layoutH2 = QHBoxLayout()
        self.rb_node1 = QRadioButton()
        self.rb_node1.setText('Node1')
        self.rb_answer1 = QRadioButton()
        self.rb_answer1.setText('Answer1')
        self.rb_answer1.setChecked(True)
        self.layoutH2.addWidget(self.rb_node1)
        self.layoutH2.addWidget(self.rb_answer1)
        self.layoutH3 = QHBoxLayout()
        self.rb_node2 = QRadioButton()
        self.rb_node2.setText('Node2')
        self.rb_answer2 = QRadioButton()
        self.rb_answer2.setText('Answer2')
        self.rb_answer2.setChecked(True)
        self.layoutH3.addWidget(self.rb_node2)
        self.layoutH3.addWidget(self.rb_answer2)
        self.layoutV = QVBoxLayout()
        self.layoutV.addWidget(self.ln_question)
        self.layoutV.addLayout(self.layoutH2)
        self.layoutV.addLayout(self.layoutH3)
        self.layoutV.addLayout(self.layoutH1)
        self.setLayout(self.layoutV)

    def addNode(self):
        self._node.setText(self.ln_question.text())
        if self.rb_node1.isChecked() and self._node.getFirstChild().who() == 'Answer':
            self._node.setFirstChild(Node())
        if self.rb_answer1.isChecked() and self._node.getFirstChild().who() == 'Node':
            self._node.setFirstChild(Answer())
        if self.rb_node2.isChecked() and self._node.getSecoundChild().who() == 'Answer':
            self._node.setSecoundChild(Node())
        if self.rb_answer2.isChecked() and self._node.getSecoundChild().who() == 'Node':
            self._node.setSecoundChild(Answer())
        self.close()

    def decline(self):
        self.close()

    def setText(self):
        self._node.setText(self.ln_question.text())

    def setNode(self, node):
        if node:
            self._node = node
            if self._node.getFirstChild().who() == 'Answer':
                self.rb_answer1.setChecked(True)
                self.rb_node1.setChecked(False)
            else: 
                self.rb_answer1.setChecked(False)
                self.rb_node1.setChecked(True)
            if self._node.getSecoundChild().who() == 'Answer':
                self.rb_answer2.setChecked(True)
                self.rb_node2.setChecked(False)
            else: 
                self.rb_answer2.setChecked(False)
                self.rb_node2.setChecked(True)
            return True
        else:
            return False
Exemple #36
0
class Panorama(QWidget):
    def __init__(self, models):
        super(Panorama, self).__init__()

        sp = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.setWindowTitle('Emoji generator')
        self.setGeometry(400, 400, 600, 600)
        self.layout = QVBoxLayout()
        self.bLayout = QHBoxLayout()
        self.bCGAN = QPushButton('CGAN')
        self.bLAPGAN = QPushButton('LAPGAN')
        self.bDCGAN = QPushButton('DCGAN')
        # self.bLayout.addWidget(self.bCGAN)
        # self.bLayout.addWidget(self.bLAPGAN)
        self.bLayout.addWidget(self.bDCGAN)
        self.imglabel = QLabel()
        self.imglabel.setAlignment(Qt.AlignCenter)
        self.imglayout = QHBoxLayout()
        self.imglayout.addWidget(self.imglabel)
        self.textinput = QLineEdit()
        self.cganlayout = QHBoxLayout()
        self.cganlayout.addWidget(self.textinput)
        self.cganlayout.addWidget(self.bCGAN)
        self.layout.addLayout(self.cganlayout)
        self.layout.addLayout(self.bLayout)
        self.layout.addLayout(self.imglayout)
        # self.layout.addWidget(self.imglabel)
        self.setLayout(self.layout)
        self.show()

        self.setup_callback()

        self.load_model(models)
        # self.plot_img()

    def setup_callback(self):
        self.bCGAN.clicked.connect(self.run_CGAN)
        self.bLAPGAN.clicked.connect(self.run_LAPGAN)
        self.bDCGAN.clicked.connect(self.run_DCGAN)

    def run_CGAN(self):
        self.img_shape = 64
        self.latent_dim = 100
        self.embedding_dim = 768
        z = Variable(
            FloatTensor(
                np.random.normal(0, 1, (self.img_shape, self.latent_dim))))
        # gen_embeddings = Variable(FloatTensor(np.random.normal(0, 1, (self.img_shape, self.embedding_dim))))
        # text = re.split(r' +', self.textinput.text().strip())
        text = self.textinput.text().strip()
        gen_embeddings = self.get_text_embeddings(text, "google_list")
        embeddings = gen_embeddings.unsqueeze_(0).repeat([z.size()[0], 1])

        # print(z.size(), embeddings.size())
        gen_imgs = self.CGAN(z, embeddings)
        save_image(gen_imgs.data[:25], "ganoutput.png", nrow=5, normalize=True)
        self.load_image()

    def run_LAPGAN(self):
        self.img_shape = 64
        self.latent_dim = 500
        z = Variable(
            Tensor(np.random.normal(0, 1, (self.img_shape, self.latent_dim))))
        gen_imgs = self.LAPGAN(z)
        # print(gen_imgs)
        self.load_image(gen_imgs.data[:25])

    def get_text_embeddings(text, src):
        if src == 'google':
            sentence_embedding = []
            tokens = text.replace("-", " ")
            tokens = tokens.split(' ')
            for token in tokens:
                if token.lower() not in WORD_VEC.vocab:
                    #print(token, " is not in vocab")
                    continue
                token_embedding = WORD_VEC[token.lower()]
                sentence_embedding.append(token_embedding)
            #print(np.array(sentence_embedding).shape)
            avg_embeddings = np.mean(np.array(sentence_embedding), 0)
        elif src == 'bert':
            tokens = TOKENIZER.tokenize(text)
            indexed_tokens = TOKENIZER.convert_tokens_to_ids(tokens)
            if device.type == 'cuda':
                hidden_output = NLP_MODEL(torch.tensor([indexed_tokens]))
            else:
                hidden_output = NLP_MODEL(torch.tensor([indexed_tokens]))
            embeddings = hidden_output[0][0]
            avg_embeddings = torch.mean(embeddings, dim=0)
            return avg_embeddings
        elif src == 'google_list':
            avg_embeddings = GOOGLE_EMBEDDING[text]
        elif src == 'bert_list':
            avg_embeddings = BERT_EMBEDDING[text]
        return FloatTensor(avg_embeddings)

    def run_DCGAN(self):
        self.img_shape = 64
        self.latent_dim = 5
        z = Variable(
            Tensor(np.random.normal(0, 1, (self.img_shape, self.latent_dim))))
        gen_imgs = self.DCGAN(z)
        save_image(gen_imgs.data[:25], "ganoutput.png", nrow=5, normalize=True)
        self.load_image()

    def load_model(self, models):
        import random
        manualSeed = random.randint(1, 10000)  # use if you want new results
        # print("Random Seed: ", manualSeed)
        np.random.seed(manualSeed)
        torch.manual_seed(manualSeed)

        cgan, lapgan, dcgan = models
        # self.CGAN = torch.load(cgan).eval()
        # self.LAPGAN = torch.load(lapgan).eval()
        self.load_CGAN(cgan)
        self.load_DCGAN(dcgan)

    def load_CGAN(self, cgan):
        # from transformers import BertConfig, BertForSequenceClassification, BertModel, BertTokenizer
        # self.TOKENIZER = BertTokenizer.from_pretrained('bert-base-uncased')
        # self.NLP_MODEL = BertModel.from_pretrained('bert-base-uncased',
        #                                       output_attentions=False,
        #                                       output_hidden_states=True)
        self.CGAN = torch.load(cgan, map_location='cpu').eval()

    def load_DCGAN(self, dcgan):
        self.DCGAN = torch.load(dcgan, map_location='cpu').eval()

    def load_image(self):
        self.img = Image.open("ganoutput.png")
        self.pix = np.asarray(self.img)
        self.cyl = self.pix
        self.plot_img()

    def plot_img(self):
        height, width, channel = self.cyl.shape
        bytesPerLine = 3 * width
        qImg = QImage(self.cyl, width, height, bytesPerLine,
                      QImage.Format_RGB888)
        self.pixmap = QPixmap.fromImage(qImg)
        self.imglabel.setPixmap(self.pixmap)
Exemple #37
0
    def __init__(self):
        super(SettingsDialog, self).__init__()
        self.setWindowTitle('Settings')
        self.setWindowIcon(QIcon('img/yologo.png'))
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setMinimumWidth(600)

        HEIGHT = 30

        grid = QGridLayout()

        # 选择权重文件
        label_weights = QLabel('Weights')
        self.line_weights = QLineEdit()
        self.line_weights.setFixedHeight(HEIGHT)

        self.btn_weights = QPushButton('...')
        self.btn_weights.setFixedWidth(40)
        self.btn_weights.setFixedHeight(HEIGHT)
        self.btn_weights.clicked.connect(self.choose_weights_file)

        grid.addWidget(label_weights, 2, 0)
        grid.addWidget(self.line_weights, 2, 1, 1, 2)
        grid.addWidget(self.btn_weights, 2, 3)

        # 是否使用GPU
        label_device = QLabel('CUDA device')
        self.line_device = QLineEdit('cpu')
        self.line_device.setToolTip('cuda device, i.e. 0 or 0,1,2,3 or cpu')
        self.line_device.setPlaceholderText('cpu or 0 or 0,1,2,3')
        self.line_device.setFixedHeight(HEIGHT)

        grid.addWidget(label_device, 3, 0)
        grid.addWidget(self.line_device, 3, 1, 1, 3)

        # 设置图像大小
        label_size = QLabel('Img Size')
        self.combo_size = QComboBox()
        self.combo_size.setToolTip('inference size (pixels)')
        self.combo_size.setFixedHeight(HEIGHT)
        self.combo_size.setStyleSheet(
            'QAbstractItemView::item {height: 40px;}')
        self.combo_size.setView(QListView())
        self.combo_size.addItem('320', 320)
        self.combo_size.addItem('384', 384)
        self.combo_size.addItem('448', 448)
        self.combo_size.addItem('512', 512)
        self.combo_size.addItem('576', 576)
        self.combo_size.addItem('640', 640)

        grid.addWidget(label_size, 4, 0)
        grid.addWidget(self.combo_size, 4, 1, 1, 3)

        # 设置置信度阈值
        label_conf = QLabel('Confidence')
        self.spin_conf = QDoubleSpinBox()
        self.spin_conf.setToolTip('confidence threshold')
        self.spin_conf.setFixedHeight(HEIGHT)
        self.spin_conf.setDecimals(1)
        self.spin_conf.setRange(0.1, 0.9)
        self.spin_conf.setSingleStep(0.1)

        grid.addWidget(label_conf, 5, 0)
        grid.addWidget(self.spin_conf, 5, 1, 1, 3)

        # 设置IOU阈值
        label_iou = QLabel('IOU')
        self.spin_iou = QDoubleSpinBox()
        self.spin_iou.setToolTip('NMS IoU threshold')
        self.spin_iou.setFixedHeight(HEIGHT)
        self.spin_iou.setDecimals(1)
        self.spin_iou.setRange(0.1, 0.9)
        self.spin_iou.setSingleStep(0.1)

        grid.addWidget(label_iou, 6, 0)
        grid.addWidget(self.spin_iou, 6, 1, 1, 3)

        # maximum detections per image
        label_max_det = QLabel('maximum detections')
        self.spin_max_det = QDoubleSpinBox()
        self.spin_max_det.setToolTip('Maximum detections per image')
        self.spin_max_det.setFixedHeight(HEIGHT)
        self.spin_max_det.setDecimals(0)
        self.spin_max_det.setRange(10, 1000)
        self.spin_max_det.setSingleStep(10)

        grid.addWidget(label_max_det, 7, 0)
        grid.addWidget(self.spin_max_det, 7, 1, 1, 3)

        # class-agnostic NMS
        self.check_agnostic = QCheckBox('Agnostic')
        self.check_agnostic.setToolTip('class-agnostic NMS')

        # augmented inference
        self.check_augment = QCheckBox('Augment')
        self.check_augment.setToolTip('augmented inference')

        # half
        self.check_half = QCheckBox('Half')
        self.check_half.setToolTip('use FP16 half-precision inference')

        grid.addWidget(self.check_agnostic, 8, 0)
        grid.addWidget(self.check_augment, 8, 1)
        grid.addWidget(self.check_half, 8, 2)

        # use OpenCV DNN for ONNX inference
        self.check_dnn = QCheckBox('DNN')
        self.check_dnn.setToolTip('Use OpenCV DNN for ONNX inference')

        grid.addWidget(self.check_dnn, 9, 0)

        box = QGroupBox()
        box.setLayout(grid)

        hbox = QHBoxLayout()
        self.btn_cancel = QPushButton('Cancel')
        self.btn_cancel.clicked.connect(self.restore)
        self.btn_ok = QPushButton('Ok')
        self.btn_ok.clicked.connect(self.save_settings)
        hbox.addStretch()
        hbox.addWidget(self.btn_cancel)
        hbox.addWidget(self.btn_ok)

        vbox = QVBoxLayout()
        vbox.addWidget(box)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

        self.load_settings()
class App(QWidget):
    def __init__(self, bk, prefs):
        super().__init__()

        self.bk = bk
        self.prefs = prefs
        self.update = False

        # Install translator for the DOCXImport plugin dialog.
        # Use the Sigil language setting unless manually overridden.
        plugin_translator = QTranslator()
        if prefs['language_override'] is not None:
            print('Plugin preferences language override in effect')
            qmf = '{}_{}'.format(bk._w.plugin_name.lower(),
                                 prefs['language_override'])
        else:
            qmf = '{}_{}'.format(bk._w.plugin_name.lower(), bk.sigil_ui_lang)
        print(
            qmf,
            os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'translations'))
        plugin_translator.load(
            qmf,
            os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'translations'))
        print(QCoreApplication.instance().installTranslator(plugin_translator))

        self._ok_to_close = False

        self.FTYPE_MAP = {
            'smap': {
                'title': _translate('App', 'Select custom style-map file'),
                'defaultextension': '.txt',
                'filetypes': 'Text Files (*.txt);;All files (*.*)',
            },
            'css': {
                'title': _translate('App', 'Select custom CSS file'),
                'defaultextension': '.css',
                'filetypes': 'CSS Files (*.css)',
            },
            'docx': {
                'title': _translate('App', 'Select DOCX file'),
                'defaultextension': '.docx',
                'filetypes': 'DOCX Files (*.docx)',
            },
        }

        # Check online github files for newer version
        if self.prefs['check_for_updates']:
            self.update, self.newversion = self.check_for_update()
        self.initUI()

    def initUI(self):
        main_layout = QVBoxLayout(self)

        self.setWindowTitle('DOCXImport')
        self.upd_layout = QVBoxLayout()
        self.update_label = QLabel()
        self.update_label.setAlignment(Qt.AlignCenter)
        self.upd_layout.addWidget(self.update_label)
        self.get_update_button = QPushButton()
        self.get_update_button.clicked.connect(self.get_update)
        self.upd_layout.addWidget(self.get_update_button)
        main_layout.addLayout(self.upd_layout)
        if not self.update:
            self.update_label.hide()
            self.get_update_button.hide()

        self.details_grid = QGridLayout()
        self.epub2_select = QRadioButton()
        self.epub2_select.setText('EPUB2')
        self.epubType = QButtonGroup()
        self.epubType.addButton(self.epub2_select)
        self.details_grid.addWidget(self.epub2_select, 0, 0, 1, 1)
        self.checkbox_get_updates = QCheckBox()
        self.details_grid.addWidget(self.checkbox_get_updates, 0, 1, 1, 1)
        self.epub3_select = QRadioButton()
        self.epub3_select.setText('EPUB3')
        self.epubType.addButton(self.epub3_select)
        self.details_grid.addWidget(self.epub3_select, 1, 0, 1, 1)
        main_layout.addLayout(self.details_grid)
        self.checkbox_get_updates.setChecked(self.prefs['check_for_updates'])
        if self.prefs['epub_version'] == '2.0':
            self.epub2_select.setChecked(True)
        elif self.prefs['epub_version'] == '3.0':
            self.epub3_select.setChecked(True)
        else:
            self.epub2_select.setChecked(True)

        self.groupBox = QGroupBox()
        self.groupBox.setTitle('')
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.docx_grid = QGridLayout()
        self.docx_label = QLabel()
        self.docx_grid.addWidget(self.docx_label, 0, 0, 1, 1)
        self.docx_path = QLineEdit()
        self.docx_grid.addWidget(self.docx_path, 1, 0, 1, 1)
        self.choose_docx_button = QPushButton()
        self.choose_docx_button.setText('...')
        self.docx_grid.addWidget(self.choose_docx_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.docx_grid)
        self.choose_docx_button.clicked.connect(
            lambda: self.fileChooser('docx', self.docx_path))
        if len(self.prefs['lastDocxPath']):
            self.docx_path.setText(self.prefs['lastDocxPath'])
        self.docx_path.setEnabled(False)

        self.smap_grid = QGridLayout()
        self.checkbox_smap = QCheckBox(self.groupBox)
        self.smap_grid.addWidget(self.checkbox_smap, 0, 0, 1, 1)
        self.cust_smap_path = QLineEdit(self.groupBox)
        self.smap_grid.addWidget(self.cust_smap_path, 1, 0, 1, 1)
        self.choose_smap_button = QPushButton(self.groupBox)
        self.choose_smap_button.setText('...')
        self.smap_grid.addWidget(self.choose_smap_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.smap_grid)
        self.checkbox_smap.setChecked(self.prefs['useSmap'])
        self.checkbox_smap.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_smap, self.choose_smap_button))
        self.choose_smap_button.clicked.connect(
            lambda: self.fileChooser('smap', self.cust_smap_path, self.
                                     checkbox_smap, self.choose_smap_button))
        if len(self.prefs['useSmapPath']):
            self.cust_smap_path.setText(self.prefs['useSmapPath'])
        self.cust_smap_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_smap, self.choose_smap_button)

        self.css_grid = QGridLayout()
        self.checkbox_css = QCheckBox(self.groupBox)
        self.css_grid.addWidget(self.checkbox_css, 0, 0, 1, 1)
        self.cust_css_path = QLineEdit(self.groupBox)
        self.css_grid.addWidget(self.cust_css_path, 1, 0, 1, 1)
        self.choose_css_button = QPushButton(self.groupBox)
        self.choose_css_button.setText('...')
        self.css_grid.addWidget(self.choose_css_button, 1, 1, 1, 1)
        self.verticalLayout_2.addLayout(self.css_grid)
        self.checkbox_css.setChecked(self.prefs['useCss'])
        self.checkbox_css.stateChanged.connect(lambda: self.chkBoxActions(
            self.checkbox_css, self.choose_css_button))
        self.choose_css_button.clicked.connect(
            lambda: self.fileChooser('css', self.cust_css_path, self.
                                     checkbox_css, self.choose_css_button))
        if len(self.prefs['useCssPath']):
            self.cust_css_path.setText(self.prefs['useCssPath'])
        self.cust_css_path.setEnabled(False)
        self.chkBoxActions(self.checkbox_css, self.choose_css_button)

        main_layout.addWidget(self.groupBox)
        self.checkbox_debug = QCheckBox()
        main_layout.addWidget(self.checkbox_debug)
        self.checkbox_debug.setChecked(self.prefs['debug'])

        spacerItem = QSpacerItem(20, 15, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        main_layout.addItem(spacerItem)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self._cancel_clicked)
        main_layout.addWidget(button_box)
        self.retranslateUi(self)
        if self.prefs['qt_geometry'] is not None:
            try:
                self.restoreGeometry(
                    QByteArray.fromHex(
                        self.prefs['qt_geometry'].encode('ascii')))
            except Exception:
                pass
        self.show()

    def retranslateUi(self, App):
        self.update_label.setText(_translate('App', 'Plugin Update Available'))
        self.get_update_button.setText(_translate('App',
                                                  'Go to download page'))
        self.checkbox_get_updates.setText(
            _translate('App', 'Check for plugin updates'))
        self.docx_label.setText(_translate('App', 'DOCX File to import'))
        self.checkbox_smap.setText(_translate('App', 'Use Custom Style Map'))
        self.checkbox_css.setText(_translate('App', 'Use Custom CSS'))
        self.checkbox_debug.setText(
            _translate('App',
                       'Debug Mode (change takes effect next plugin run)'))

    def fileChooser(self, ftype, qlineedit, qcheck=None, qbutton=None):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        title = self.FTYPE_MAP[ftype]['title']
        startfolder = self.prefs['lastDir'][ftype]
        ffilter = self.FTYPE_MAP[ftype]['filetypes']
        inpath, _ = QFileDialog.getOpenFileName(self,
                                                title,
                                                startfolder,
                                                ffilter,
                                                options=options)
        if len(inpath):
            qlineedit.setEnabled(True)
            qlineedit.setText(os.path.normpath(inpath))
            self.prefs['lastDir'][ftype] = os.path.dirname(inpath)
            qlineedit.setEnabled(False)
        else:
            if qcheck is not None:
                qcheck.setChecked(False)
            if qbutton is not None:
                qbutton.setEnabled(False)

    def chkBoxActions(self, chk, btn):
        btn.setEnabled(chk.isChecked())

    def cmdDo(self):
        global _DETAILS
        self.prefs['qt_geometry'] = self.saveGeometry().toHex().data().decode(
            'ascii')
        self.prefs['check_for_updates'] = self.checkbox_get_updates.isChecked()
        self.prefs['epub_version'] = self.epubType.checkedButton().text(
        )[-1] + '.0'
        self.prefs['debug'] = self.checkbox_debug.isChecked()
        _DETAILS['vers'] = self.epubType.checkedButton().text()[-1] + '.0'
        self.prefs['useSmap'] = self.checkbox_smap.isChecked()
        if self.checkbox_smap.isChecked():
            if len(self.cust_smap_path.text()):
                self.prefs['useSmapPath'] = self.cust_smap_path.text()
                _DETAILS['smap'] = (self.checkbox_smap.isChecked(),
                                    self.cust_smap_path.text())
            else:
                # Message box that no file is selected
                return
        self.prefs['useCss'] = self.checkbox_css.isChecked()
        if self.checkbox_css.isChecked():
            if len(self.cust_css_path.text()):
                self.prefs['useCssPath'] = self.cust_css_path.text()
                _DETAILS['css'] = (self.checkbox_css.isChecked(),
                                   self.cust_css_path.text())
            else:
                # Message box that no file is selected
                return
        if len(self.docx_path.text()):
            self.prefs['lastDocxPath'] = self.docx_path.text()
            _DETAILS['docx'] = self.docx_path.text()
        else:
            # Message box that no file is selected
            return

    def check_for_update(self):
        '''Use updatecheck.py to check for newer versions of the plugin'''
        chk = UpdateChecker(self.prefs['last_time_checked'], self.bk._w)
        update_available, online_version, time = chk.update_info()
        # update preferences with latest date/time/version
        self.prefs['last_time_checked'] = time
        if online_version is not None:
            self.prefs['last_online_version'] = online_version
        if update_available:
            return (True, online_version)
        return (False, online_version)

    def get_update(self):
        url = DOWNLOAD_PAGE
        if self.update:
            latest = '/tag/v{}'.format(self.newversion)
            url = url + latest
        webbrowser.open_new_tab(url)

    def _ok_clicked(self):
        self._ok_to_close = True
        self.cmdDo()
        self.bk.savePrefs(self.prefs)
        QCoreApplication.instance().quit()

    def _cancel_clicked(self):
        self._ok_to_close = True
        '''Close aborting any changes'''
        self.prefs['qt_geometry'] = self.saveGeometry().toHex().data().decode(
            'ascii')
        self.prefs['check_for_updates'] = self.checkbox_get_updates.isChecked()
        self.prefs['debug'] = self.checkbox_debug.isChecked()
        self.bk.savePrefs(self.prefs)
        QCoreApplication.instance().quit()

    def closeEvent(self, event):
        if self._ok_to_close:
            event.accept()  # let the window close
        else:
            self._cancel_clicked()
Exemple #39
0
    def __init__(self, mode, parentQWidget = None):
        QVBoxLayout.__init__(self)

        self.sig.connect(self.addThreadList)
        self.mode = mode

        self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)

        self.groupBoxSearch = QGroupBox()
        self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };")
        vboxSearch = QVBoxLayout()
        self.searchTitle = QLabel("Search Messages")
        vboxSearch.addWidget(self.searchTitle)
        self.searchHLayout = QHBoxLayout()
        self.editTextSearch = QTextEdit('')
        self.editTextSearch.setFixedSize(200,30)
        self.buttonSearch = QPushButton('Search')
        self.buttonSearch.setFixedSize(100,30)
        self.buttonSearch.clicked.connect(self.searchMsg)
        vboxSearch.addWidget(self.editTextSearch)
        self.searchHLayout.addWidget(self.buttonSearch)
        self.searchCursor = QLabel()
        self.searchHLayout.addWidget(self.searchCursor)
        vboxSearch.addLayout(self.searchHLayout)
        self.browseHLayout = QHBoxLayout()
        self.buttonLookUp = QPushButton('\u21e7')  #Arrow up
        self.buttonLookUp.setFixedWidth(100)
        self.buttonLookUp.clicked.connect(self.moveToPrev)
        self.buttonLookDown = QPushButton('\u21e9') #Arrow down
        self.buttonLookDown.setFixedWidth(100)
        self.buttonLookDown.clicked.connect(self.moveToNext)
        self.browseHLayout.addWidget(self.buttonLookUp)
        self.browseHLayout.addWidget(self.buttonLookDown)
        vboxSearch.addLayout(self.browseHLayout)
        self.groupBoxSearch.setLayout(vboxSearch)
        self.addWidget(self.groupBoxSearch)
        self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.buttonHiddenLifelines = QPushButton('Show hidden life-lines')
        self.buttonHiddenLifelines.setFixedWidth(200)
        self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines)
        self.addWidget(self.buttonHiddenLifelines)

        self.buttonHiddenMessages = QPushButton('Show hidden Messages')
        self.buttonHiddenMessages.setFixedWidth(200)
        self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages)
        self.addWidget(self.buttonHiddenMessages)

        if const.mode_interactive == mode:
            self.buttonCapture = QPushButton('Capture')
            self.buttonCapture.setFixedWidth(200)
            self.buttonCapture.clicked.connect(self.notifyCapture)
            self.addWidget(self.buttonCapture)
        self.msgRcv = []
        self.msgInfo = QLabel("Message Info.")
        self.groupBoxMessageInfo = QGroupBox()
        self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")
        vbox = QVBoxLayout()
        vbox.addWidget(self.msgInfo)
        self.tableTime = QTableWidget(3,2)
        self.tableTime.setHorizontalHeaderLabels(['-','time'])
        self.tableTime.setColumnWidth(0,80)
        self.tableTime.setColumnWidth(1,150)
        vwidth = self.tableTime.verticalHeader().length()
        hwidth = self.tableTime.horizontalHeader().height()
        fwidth = self.tableTime.frameWidth() * 2
        self.tableTime.setFixedHeight(vwidth + hwidth + fwidth)
        self.tableTime.horizontalHeader().setStretchLastSection(True)
        self.tableTime.setItem(0,0,QTableWidgetItem('begin'))
        self.tableTime.setItem(0,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(1,0,QTableWidgetItem('end'))
        self.tableTime.setItem(1,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(2,0,QTableWidgetItem('duration'))
        self.tableTime.setItem(2,1,QTableWidgetItem(' - '))
        vbox.addWidget(self.tableTime)

        self.titleArg = QLabel('Argument List')
        vbox.addWidget(self.titleArg)

        max_arg_num = 10
        self.tableArgs = QTableWidget(max_arg_num,2)
        self.tableArgs.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_arg_num):
            self.tableArgs.setItem(idx,0,QTableWidgetItem())
            self.tableArgs.setItem(idx,1,QTableWidgetItem())
        self.tableArgs.horizontalHeader().setStretchLastSection(True)
        vbox.addWidget(self.tableArgs)

        self.titleArg = QLabel('Return Value List')
        vbox.addWidget(self.titleArg)

        max_ret_num = 4
        self.tableRet = QTableWidget(max_ret_num,2)
        self.tableRet.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_ret_num):
            self.tableRet.setItem(idx,0,QTableWidgetItem())
            self.tableRet.setItem(idx,1,QTableWidgetItem())
        self.tableRet.horizontalHeader().setStretchLastSection(True)
        vwidth = self.tableRet.verticalHeader().length()
        hwidth = self.tableRet.horizontalHeader().height()
        fwidth = self.tableRet.frameWidth() * 2
        self.tableRet.setFixedHeight(vwidth + hwidth + fwidth)
        vbox.addWidget(self.tableRet)

        self.buttonSrcView = QPushButton('view code')
        self.buttonSrcView.setFixedWidth(200)
        self.buttonSrcView.clicked.connect(self.openSourceViewer)
        self.buttonHide = QPushButton('Hide')
        self.buttonHide.setFixedWidth(200)
        self.buttonHide.clicked.connect(self.notifyHide)
        self.buttonHideAllMsg = QPushButton('Hide All')
        self.buttonHideAllMsg.setFixedWidth(200)
        self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected)
        self.groupBoxMessageInfo.setLayout(vbox)
        self.checkHideCircular = QCheckBox('Hide Circular Messages')
        self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked)
        self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage)
        self.addWidget(self.checkHideCircular)
        self.addWidget(self.groupBoxMessageInfo)
        self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)
Exemple #40
0
    def __init__(self, app, parent=None):
        super(MainWindow, self).__init__(parent)
        self.imagesDir = app.dir + '/images/'
        self.setWindowIcon(QIcon(self.imagesDir + 'icon.png'))
        self.path = ''

        self.settings = QSettings()
        self.lastDir = self.settings.value('lastDir', '')

        self.setMinimumWidth(540)

        self.supportedFormats = []
        for f in QImageReader.supportedImageFormats():
            self.supportedFormats.append(str(f.data(), encoding="utf-8"))

        self.fileWatcher = QFileSystemWatcher()
        self.fileWatcher.fileChanged.connect(self.fileChanged)

        # widgets
        self.showPixmapWidget = None

        self.tileWidthSpinBox = QSpinBox()
        self.tileWidthSpinBox.setValue(16)
        self.tileWidthSpinBox.setFixedWidth(50)
        self.tileWidthSpinBox.setMinimum(1)

        self.tileHeightSpinBox = QSpinBox()
        self.tileHeightSpinBox.setValue(16)
        self.tileHeightSpinBox.setFixedWidth(50)
        self.tileHeightSpinBox.setMinimum(1)

        self.paddingSpinBox = QSpinBox()
        self.paddingSpinBox.setFixedWidth(50)
        self.paddingSpinBox.setMinimum(1)

        self.transparentCheckbox = QCheckBox("Transparent")
        self.transparentCheckbox.setChecked(True)
        self.transparentCheckbox.stateChanged.connect(self.transparentChanged)

        self.backgroundColorEdit = ColorEdit()
        self.backgroundColorEdit.setEnabled(False)
        self.backgroundColorLabel = QLabel("Background color:")
        self.backgroundColorLabel.setEnabled(False)

        self.forcePotCheckBox = QCheckBox("Force PoT")
        self.forcePotCheckBox.setChecked(True)
        self.forcePotCheckBox.stateChanged.connect(self.forcePotChanged)

        self.reorderTilesCheckBox = QCheckBox("Reorder tiles")

        self.generateAndExportButton = QPushButton("Generate and export")
        self.generateAndExportButton.setFixedHeight(32)
        self.generateAndExportButton.clicked.connect(self.generateAndExportClicked)
        self.generateAndExportButton.setEnabled(False)

        self.pixmapWidget = PixmapWidget()
        self.pixmapWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.pixmapWidget.setPixmap(self.createDropTextPixmap())
        self.pixmapWidget.dropSignal.connect(self.fileDropped)
        self.pixmapWidget.setMinimumHeight(300)

        # load settings
        self.tileWidthSpinBox.setValue(int(self.settings.value('tileWidth', 16)))
        self.tileHeightSpinBox.setValue(int(self.settings.value('tileHeight', 16)))
        self.paddingSpinBox.setValue(int(self.settings.value('padding', 1)))
        self.forcePotCheckBox.setChecked(True if self.settings.value('forcePot', 'true') == 'true' else False)
        self.reorderTilesCheckBox.setChecked(True if self.settings.value('reorderTiles', 'false') == 'true' else False)
        self.transparentCheckbox.setChecked(True if self.settings.value('transparent', 'false') == 'true' else False)
        self.backgroundColorEdit.setColorText(str(self.settings.value('backgroundColor', '#FF00FF')))
        self.restoreGeometry(QByteArray(self.settings.value('MainWindow/geometry')))
        self.restoreState(QByteArray(self.settings.value('MainWindow/windowState')))

        # layout
        hl1 = QHBoxLayout()
        hl1.setContentsMargins(5, 5, 5, 5)
        hl1.addWidget(QLabel("Tile width:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileWidthSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Tile height:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileHeightSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Padding:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.paddingSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.forcePotCheckBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.reorderTilesCheckBox)
        hl1.addStretch()

        hl2 = QHBoxLayout()
        hl2.setContentsMargins(5, 5, 5, 5)
        hl2.addWidget(self.transparentCheckbox)
        hl2.addSpacing(15)
        hl2.addWidget(self.backgroundColorLabel)
        hl2.addSpacing(5)
        hl2.addWidget(self.backgroundColorEdit)
        hl2.addStretch()

        hl3 = QHBoxLayout()
        hl3.setContentsMargins(5, 5, 5, 5)
        hl3.addWidget(self.generateAndExportButton)

        vl = QVBoxLayout()
        vl.setContentsMargins(0, 0, 0, 0)
        vl.setSpacing(0)
        vl.addLayout(hl1)
        vl.addLayout(hl2)
        vl.addWidget(self.pixmapWidget)
        vl.addLayout(hl3)

        w = QWidget()
        w.setLayout(vl)
        self.setCentralWidget(w)

        self.setTitle()