예제 #1
0
class DyStockTableFilterDlg(QDialog):

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

        self._data = data

        self._initUi(colNames)

    def _initUi(self, colNames):
        self.setWindowTitle('过滤')
 
        # 控件
        table = DyTableWidget(parent=None, readOnly=True, index=False, floatCut=True, autoScroll=False)
        table.setColNames(['列名', '表达式'])
        rows = [[name, 'x[{0}]'.format(i)] for i, name in enumerate(colNames)]
        table.fastAppendRows(rows)

        descriptionLabel = QLabel('行过滤表达式(Python语法)')
        self._filterTextEdit = QTextEdit()
        self._newWindowCheckBox = QCheckBox('新窗口')
        self._newWindowCheckBox.setChecked(True)
        self._highlightCheckBox = QCheckBox('原窗口高亮')
        self._highlightCheckBox.setChecked(False)

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

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(table, 0, 0, 22, 1)
        grid.addWidget(self._newWindowCheckBox, 0, 1)
        grid.addWidget(self._highlightCheckBox, 0, 2)

        grid.addWidget(descriptionLabel, 1, 1)

        grid.addWidget(self._filterTextEdit, 2, 1, 20, 20)
 
        grid.addWidget(okPushButton, 0, 21)
        grid.addWidget(cancelPushButton, 1, 21)
 
 
        self.setLayout(grid)
        self.resize(QApplication.desktop().size().width()//2, QApplication.desktop().size().height()//4*3)

    def _ok(self):
        filter = self._filterTextEdit.toPlainText().replace('\n', ' ')

        self._data['filter'] = filter
        self._data['newWindow'] = self._newWindowCheckBox.isChecked()
        self._data['highlight'] = self._highlightCheckBox.isChecked()

        self.accept()

    def _cancel(self):
        self.reject()
예제 #2
0
 def seed_options(self):
     dialog = QDialog()
     vbox = QVBoxLayout(dialog)
     if 'ext' in self.options:
         cb_ext = QCheckBox(_('Extend this seed with custom words'))
         cb_ext.setChecked(self.is_ext)
         vbox.addWidget(cb_ext)
     if 'bip39' in self.options:
         def f(b):
             self.is_seed = (lambda x: bool(x)) if b else self.saved_is_seed
             self.is_bip39 = b
             self.on_edit()
             if b:
                 msg = ' '.join([
                     '<b>' + _('Warning') + ':</b>  ',
                     _('BIP39 seeds can be imported in Electrum, so that users can access funds locked in other wallets.'),
                     _('However, we do not generate BIP39 seeds, because they do not meet our safety standard.'),
                     _('BIP39 seeds do not include a version number, which compromises compatibility with future software.'),
                     _('We do not guarantee that BIP39 imports will always be supported in Electrum.'),
                 ])
             else:
                 msg = ''
             self.seed_warning.setText(msg)
         cb_bip39 = QCheckBox(_('BIP39 seed'))
         cb_bip39.toggled.connect(f)
         cb_bip39.setChecked(self.is_bip39)
         vbox.addWidget(cb_bip39)
     vbox.addLayout(Buttons(OkButton(dialog)))
     if not dialog.exec_():
         return None
     self.is_ext = cb_ext.isChecked() if 'ext' in self.options else False
     self.is_bip39 = cb_bip39.isChecked() if 'bip39' in self.options else False
예제 #3
0
class Running(preferences.Group):
    def __init__(self, page):
        super(Running, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.saveDocument = QCheckBox(clicked=self.changed)
        self.deleteFiles = QCheckBox(clicked=self.changed)
        self.embedSourceCode = QCheckBox(clicked=self.changed)
        self.noTranslation = QCheckBox(clicked=self.changed)
        self.includeLabel = QLabel()
        self.include = widgets.listedit.FilePathEdit()
        self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove)
        self.include.changed.connect(self.changed)
        layout.addWidget(self.saveDocument)
        layout.addWidget(self.deleteFiles)
        layout.addWidget(self.embedSourceCode)
        layout.addWidget(self.noTranslation)
        layout.addWidget(self.includeLabel)
        layout.addWidget(self.include)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Running LilyPond"))
        self.saveDocument.setText(_("Save document if possible"))
        self.saveDocument.setToolTip(_(
            "If checked, the document is saved when it is local and modified.\n"
            "Otherwise a temporary file is used to run LilyPond."))
        self.deleteFiles.setText(_("Delete intermediate output files"))
        self.deleteFiles.setToolTip(_(
            "If checked, LilyPond will delete intermediate PostScript files."))
        self.embedSourceCode.setText(_("Embed Source Code files in publish mode"))
        self.embedSourceCode.setToolTip(_(
            "If checked, the LilyPond source files will be embedded in the PDF\n"
            "when LilyPond is started in publish mode.\n"
            "This feature is available since LilyPond 2.19.39."))
        self.noTranslation.setText(_("Run LilyPond with English messages"))
        self.noTranslation.setToolTip(_(
            "If checked, LilyPond's output messages will be in English.\n"
            "This can be useful for bug reports."))
        self.includeLabel.setText(_("LilyPond include path:"))
    
    def loadSettings(self):
        s = settings()
        self.saveDocument.setChecked(s.value("save_on_run", False, bool))
        self.deleteFiles.setChecked(s.value("delete_intermediate_files", True, bool))
        self.embedSourceCode.setChecked(s.value("embed_source_code", False, bool))
        self.noTranslation.setChecked(s.value("no_translation", False, bool))
        include_path = qsettings.get_string_list(s, "include_path")
        self.include.setValue(include_path)
        
    def saveSettings(self):
        s = settings()
        s.setValue("save_on_run", self.saveDocument.isChecked())
        s.setValue("delete_intermediate_files", self.deleteFiles.isChecked())
        s.setValue("embed_source_code", self.embedSourceCode.isChecked())
        s.setValue("no_translation", self.noTranslation.isChecked())
        s.setValue("include_path", self.include.value())
class ListLayoutSettings(SettingsPage):

    NAME = 'List Layout'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        self.behaviorsGroup = QGroupBox(self)
        self.behaviorsGroup.setTitle('Default behaviors')
        self.behaviorsGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.behaviorsGroup)

        self.showPlaying = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showPlaying)

        self.showDbMeters = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showDbMeters)

        self.showAccurate = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showAccurate)

        self.showSeek = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showSeek)

        self.autoNext = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.autoNext)

        self.retranslateUi()

    def retranslateUi(self):
        self.behaviorsGroup.setTitle('Default behaviors')
        self.showPlaying.setText('Show playing-sidebar')
        self.showDbMeters.setText('Show db-meters')
        self.showAccurate.setText('Show accurate time')
        self.showSeek.setText('Show seek sliders')
        self.autoNext.setText('Automatically select the next cue')

    def get_settings(self):
        conf = {}

        conf['showplaying'] = str(self.showPlaying.isChecked())
        conf['showdbmeters'] = str(self.showDbMeters.isChecked())
        conf['showseek'] = str(self.showSeek.isChecked())
        conf['showaccurate'] = str(self.showAccurate.isChecked())
        conf['autonext'] = str(self.autoNext.isChecked())

        return {'ListLayout': conf}

    def load_settings(self, settings):
        settings = settings.get('ListLayout', {})

        self.showPlaying.setChecked(settings.get('showplaying') == 'True')
        self.showDbMeters.setChecked(settings.get('showdbmeters') == 'True')
        self.showAccurate.setChecked(settings.get('showaccurate') == 'True')
        self.showSeek.setChecked(settings.get('showseek') == 'True')
        self.autoNext.setChecked(settings.get('autonext') == 'True')
예제 #5
0
class FindInFilesActions(QWidget):

    searchRequested = pyqtSignal('QString', bool, bool, bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored)
        self._scope = QComboBox()
        self._scope.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.ninjaide = IDE.get_service('ide')
        self.ninjaide.filesAndProjectsLoaded.connect(
            self._update_combo_projects)

        main_layout = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(translations.TR_SEARCH_SCOPE))
        hbox.addWidget(self._scope)
        main_layout.addLayout(hbox)
        widgets_layout = QGridLayout()
        widgets_layout.setContentsMargins(0, 0, 0, 0)
        self._line_search = QLineEdit()
        self._line_search.setPlaceholderText(translations.TR_SEARCH_FOR)
        main_layout.addWidget(self._line_search)
        # TODO: replace
        self._check_cs = QCheckBox(translations.TR_SEARCH_CASE_SENSITIVE)
        self._check_cs.setChecked(True)
        widgets_layout.addWidget(self._check_cs, 2, 0)
        self._check_wo = QCheckBox(translations.TR_SEARCH_WHOLE_WORDS)
        widgets_layout.addWidget(self._check_wo, 2, 1)
        self._check_re = QCheckBox(translations.TR_SEARCH_REGEX)
        widgets_layout.addWidget(self._check_re, 3, 0)
        self._check_recursive = QCheckBox('Recursive')
        widgets_layout.addWidget(self._check_recursive, 3, 1)
        main_layout.addLayout(widgets_layout)
        main_layout.addStretch(1)

        # Connections
        self._line_search.returnPressed.connect(self.search_requested)

    def _update_combo_projects(self):
        projects = self.ninjaide.get_projects()
        for nproject in projects.values():
            self._scope.addItem(nproject.name, nproject.path)

    @property
    def current_project_path(self):
        """Returns NProject.path of current project"""
        return self._scope.itemData(self._scope.currentIndex())

    def search_requested(self):
        text = self._line_search.text()
        if not text.strip():
            return
        has_search = self._line_search.text()
        cs = self._check_cs.isChecked()
        regex = self._check_re.isChecked()
        wo = self._check_wo.isChecked()
        self.searchRequested.emit(has_search, cs, regex, wo)
class DyStockDataHistTicksVerifyDlg(QDialog):

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

        self._data = data

        self._initUi()

    def _initUi(self):
        self.setWindowTitle('历史分笔数据校验')
 
        # 控件
        startDateLable = QLabel('开始日期')
        self._startDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

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

        self._addCheckBox = QCheckBox('校验缺失历史分笔数据')
        self._addCheckBox.setChecked(True)
        self._deleteCheckBox = QCheckBox('校验无效历史分笔数据')
        #self._deleteCheckBox.setChecked(True)

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

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

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

        grid.addWidget(self._addCheckBox, 2, 0)
        grid.addWidget(self._deleteCheckBox, 2, 1)

        grid.addWidget(okPushButton, 3, 1)
        grid.addWidget(cancelPushButton, 3, 0)
 
        self.setLayout(grid)

    def _ok(self):
        self._data['startDate'] = self._startDateLineEdit.text()
        self._data['endDate'] = self._endDateLineEdit.text()

        self._data['verifyMissing'] = self._addCheckBox.isChecked()
        self._data['verifyInvalid'] = self._deleteCheckBox.isChecked()

        self.accept()

    def _cancel(self):
        self.reject()
예제 #7
0
class GalleryListEdit(misc.BasePopup):
    apply = pyqtSignal()
    def __init__(self, parent=None):
        super().__init__(parent, blur=False)
        main_layout = QFormLayout(self.main_widget)
        self.name_edit = QLineEdit(self)
        main_layout.addRow("Name:", self.name_edit)
        self.filter_edit = QPlainTextEdit(self)
        self.filter_edit.setPlaceholderText("tag1, namespace:tag2, namespace2:[tag1, tag2] ...")
        self.filter_edit.setFixedHeight(100)
        what_is_filter = misc.ClickedLabel("What is Filter/Enforce? (Hover)")
        what_is_filter.setToolTip(app_constants.WHAT_IS_FILTER)
        what_is_filter.setToolTipDuration(9999999999)
        self.enforce = QCheckBox(self)
        self.regex = QCheckBox(self)
        self.case = QCheckBox(self)
        self.strict = QCheckBox(self)
        main_layout.addRow(what_is_filter)
        main_layout.addRow("Filter", self.filter_edit)
        main_layout.addRow("Enforce", self.enforce)
        main_layout.addRow("Regex", self.regex)
        main_layout.addRow("Case sensitive", self.case)
        main_layout.addRow("Match whole terms", self.strict)
        main_layout.addRow(self.buttons_layout)
        self.add_buttons("Close")[0].clicked.connect(self.hide)
        self.add_buttons("Apply")[0].clicked.connect(self.accept)
        old_v = self.width()
        self.adjustSize()
        self.resize(old_v, self.height())

    def set_list(self, gallery_list, item):
        self.gallery_list = gallery_list
        self.name_edit.setText(gallery_list.name)
        self.enforce.setChecked(gallery_list.enforce)
        self.regex.setChecked(gallery_list.regex)
        self.case.setChecked(gallery_list.case)
        self.strict.setChecked(gallery_list.strict)
        self.item = item
        if gallery_list.filter:
            self.filter_edit.setPlainText(gallery_list.filter)
        else:
            self.filter_edit.setPlainText('')

    def accept(self):
        name = self.name_edit.text()
        self.item.setText(name)
        self.gallery_list.name = name
        self.gallery_list.filter = self.filter_edit.toPlainText()
        self.gallery_list.enforce = self.enforce.isChecked()
        self.gallery_list.regex = self.regex.isChecked()
        self.gallery_list.case = self.case.isChecked()
        self.gallery_list.strict = self.strict.isChecked()
        gallerydb.execute(gallerydb.ListDB.modify_list, True, self.gallery_list)
        self.apply.emit()
        self.hide()
예제 #8
0
class FindDialog(QDialog):
    findNext = pyqtSignal(str,Qt.CaseSensitivity)
    findPrevious = pyqtSignal(str,Qt.CaseSensitivity)

    def __init__(self,parent=None):
        super().__init__(parent)
        label = QLabel(self.tr("Find &what:"))
        self.lineEdit = QLineEdit()
        label.setBuddy(self.lineEdit)

        self.caseCheckBox=QCheckBox(self.tr("Match &case"))
        self.backwardCheckBox=QCheckBox(self.tr("Search &backward"))
        self.findButton = QPushButton(self.tr("&Find"))
        self.findButton.setDefault(True)
        self.findButton.setEnabled(False)
        closeButton=QPushButton(self.tr("Close"))

        self.lineEdit.textChanged.connect(self.enableFindButton)
        self.findButton.clicked.connect(self.findClicked)
        closeButton.clicked.connect(self.close)

        topLeftLayout=QHBoxLayout()
        topLeftLayout.addWidget(label)
        topLeftLayout.addWidget(self.lineEdit)
        leftLayout=QVBoxLayout()
        leftLayout.addLayout(topLeftLayout)
        leftLayout.addWidget(self.caseCheckBox)
        leftLayout.addWidget(self.backwardCheckBox)
        rightLayout = QVBoxLayout()
        rightLayout.addWidget(self.findButton)
        rightLayout.addWidget(closeButton)
        rightLayout.addStretch()
        mainLayout=QHBoxLayout()
        mainLayout.addLayout(leftLayout)
        mainLayout.addLayout(rightLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle(self.tr("Find"))
        self.setFixedHeight(self.sizeHint().height())


    def enableFindButton(self,text):
        self.findButton.setEnabled(bool(text))
    @pyqtSlot()
    def findClicked(self):
        text = self.lineEdit.text()
        if self.caseCheckBox.isChecked():
            cs=Qt.CaseSensitive
        else:
            cs=Qt.CaseInsensitive

        if self.backwardCheckBox.isChecked():
            self.findPrevious.emit(text,cs)
        else:
            self.findNext.emit(text,cs)
class DyStockIndustryCompareDlg(QDialog):

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

        self._data = data

        self._initUi(name, baseDate)

    def _initUi(self, name, baseDate):
        self.setWindowTitle('行业对比[{0}]-基准日期[{1}]'.format(name, baseDate))
 
        # 控件
        forwardNTDaysLabel = QLabel('向前N日涨幅(%)')
        self._forwardNTDaysLineEdit = QLineEdit('30')

        self._industry2CheckBox = QCheckBox('行业二级分级')
        #self._industry2CheckBox.setChecked(True)

        self._industry3CheckBox = QCheckBox('行业三级分级')
        self._industry3CheckBox.setChecked(True)

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

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

        grid.addWidget(self._industry2CheckBox, 1, 0)
        grid.addWidget(self._industry3CheckBox, 1, 1)

        grid.addWidget(okPushButton, 2, 1)
        grid.addWidget(cancelPushButton, 2, 0)
 
        self.setLayout(grid)

        self.setMinimumWidth(QApplication.desktop().size().width()//5)

    def _ok(self):
        self._data['forwardNTDays'] = int(self._forwardNTDaysLineEdit.text())

        self._data['industry2'] = self._industry2CheckBox.isChecked()
        self._data['industry3'] = self._industry3CheckBox.isChecked()

        self.accept()

    def _cancel(self):
        self.reject()
예제 #10
0
class SavingDocument(preferences.Group):
    def __init__(self, page):
        super(SavingDocument, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.stripwsp = QCheckBox(toggled=self.changed)
        self.backup = QCheckBox(toggled=self.changed)
        self.metainfo = QCheckBox(toggled=self.changed)
        layout.addWidget(self.stripwsp)
        layout.addWidget(self.backup)
        layout.addWidget(self.metainfo)
        
        hbox = QHBoxLayout()
        layout.addLayout(hbox)
        
        self.basedirLabel = l = QLabel()
        self.basedir = UrlRequester()
        hbox.addWidget(self.basedirLabel)
        hbox.addWidget(self.basedir)
        self.basedir.changed.connect(self.changed)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("When saving documents"))
        self.stripwsp.setText(_("Strip trailing whitespace"))
        self.stripwsp.setToolTip(_(
            "If checked, Frescobaldi will remove unnecessary whitespace at the "
            "end of lines (but not inside multi-line strings)."))
        self.backup.setText(_("Keep backup copy"))
        self.backup.setToolTip(_(
            "Frescobaldi always backups a file before overwriting it "
            "with a new version.\n"
            "If checked those backup copies are retained."))
        self.metainfo.setText(_("Remember cursor position, bookmarks, etc."))
        self.basedirLabel.setText(_("Default directory:"))
        self.basedirLabel.setToolTip(_("The default folder for your LilyPond documents (optional)."))
        
    def loadSettings(self):
        s = QSettings()
        self.stripwsp.setChecked(s.value("strip_trailing_whitespace", False, bool))
        self.backup.setChecked(s.value("backup_keep", False, bool))
        self.metainfo.setChecked(s.value("metainfo", True, bool))
        self.basedir.setPath(s.value("basedir", "", str))
        
    def saveSettings(self):
        s = QSettings()
        s.setValue("strip_trailing_whitespace", self.stripwsp.isChecked())
        s.setValue("backup_keep", self.backup.isChecked())
        s.setValue("metainfo", self.metainfo.isChecked())
        s.setValue("basedir", self.basedir.path())
예제 #11
0
class ListLayoutPreferences(SettingsSection):

    NAME = 'List Layout'

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

        self.behaviorsGroup = QGroupBox(self)
        self.behaviorsGroup.setTitle('Default behaviors')
        self.behaviorsGroup.setLayout(QVBoxLayout())
        self.behaviorsGroup.setGeometry(0, 0, self.width(), 120)

        self.showDbMeters = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showDbMeters)

        self.showAccurate = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showAccurate)

        self.showSeek = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.showSeek)

        self.autoNext = QCheckBox(self.behaviorsGroup)
        self.behaviorsGroup.layout().addWidget(self.autoNext)

        self.retranslateUi()

    def retranslateUi(self):
        self.behaviorsGroup.setTitle('Default behaviors')
        self.showDbMeters.setText('Show db-meters')
        self.showAccurate.setText('Show accurate time')
        self.showSeek.setText('Show seek sliders')
        self.autoNext.setText('Automatically select the next cue')

    def get_configuration(self):
        conf = {}

        conf['showdbmeters'] = str(self.showDbMeters.isChecked())
        conf['showseek'] = str(self.showSeek.isChecked())
        conf['showaccurate'] = str(self.showAccurate.isChecked())
        conf['autonext'] = str(self.autoNext.isChecked())

        return {'ListLayout': conf}

    def set_configuration(self, conf):
        settings = conf.get('ListLayout', {})

        self.showDbMeters.setChecked(settings.get('showdbmeters') == 'True')
        self.showAccurate.setChecked(settings.get('showaccurate') == 'True')
        self.showSeek.setChecked(settings.get('showseek') == 'True')
        self.autoNext.setChecked(settings.get('autonext') == 'True')
예제 #12
0
class KeyBoard(preferences.Group):
    def __init__(self, page):
        super(KeyBoard, self).__init__(page)
        
        layout = QGridLayout(spacing=1)
        self.setLayout(layout)

        self.keepCursorInLine = QCheckBox(toggled=self.changed)
        self.smartHome = QCheckBox(toggled=self.changed)
        self.smartStartEnd = QCheckBox(toggled=self.changed)

        layout.addWidget(self.smartHome, 0, 0, 1, 1)
        layout.addWidget(self.smartStartEnd, 1, 0, 1, 1)
        layout.addWidget(self.keepCursorInLine, 2, 0, 1, 1)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Keyboard Preferences"))
        self.smartHome.setText(_("Smart Home key"))
        self.smartHome.setToolTip('<qt>' + _(
            "If enabled, pressing Home will put the cursor at the first non-"
            "whitespace character on the line. "
            "When the cursor is on that spot, pressing Home moves the cursor "
            "to the beginning of the line."))
        self.smartStartEnd.setText(_("Smart Up/PageUp and Down/PageDown keys"))
        self.smartStartEnd.setToolTip('<qt>' + _(
            "If enabled, pressing Up or PageUp in the first line will move the "
            "cursor to the beginning of the document, and pressing Down or "
            "PageDown in the last line will move the cursor to the end of the "
            "document."))
        self.keepCursorInLine.setText(_("Horizontal arrow keys keep cursor in current line"))
        self.keepCursorInLine.setToolTip('<qt>' + _(
            "If enabled, the cursor will stay in the current line when using "
            "the horizontal arrow keys, and not wrap around to the next or previous line."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        self.smartHome.setChecked(s.value("smart_home_key", True, bool))
        self.smartStartEnd.setChecked(s.value("smart_start_end", True, bool))
        self.keepCursorInLine.setChecked(s.value("keep_cursor_in_line", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        s.setValue("smart_home_key", self.smartHome.isChecked())
        s.setValue("smart_start_end", self.smartStartEnd.isChecked())
        s.setValue("keep_cursor_in_line", self.keepCursorInLine.isChecked())
예제 #13
0
class SavingDlg(QDialog):
    """
    Saving Option Dialog
    """
    def __init__(self, topLevelOperator, parent):
        super(QDialog, self).__init__(parent=parent)

        self.topLevelOperator = topLevelOperator

        buttonbox = QDialogButtonBox(Qt.Horizontal, parent=self)
        buttonbox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonbox.accepted.connect(self.change_state)
        buttonbox.rejected.connect(self.reject)

        self.checkbox = QCheckBox()
        self.checkbox.setChecked(self.topLevelOperator.SaveFullModel.value)
        self.checkbox.setCheckable(True)
        self.checkbox.setText("Enable Model Object serialization")

        layout = QVBoxLayout()
        layout.addWidget(self.checkbox)
        layout.addWidget(buttonbox)

        self.setLayout(layout)
        self.setWindowTitle("Saving Options")

    def change_state(self):

        self.topLevelOperator.SaveFullModel.setValue(self.checkbox.isChecked())

        #close dialog
        super(SavingDlg, self).accept()
예제 #14
0
class StopAllSettings(SettingsPage):
    Name = 'Cue Settings'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.setLayout(QVBoxLayout(self))

        self.group = QGroupBox(self)
        self.group.setTitle('Mode')
        self.group.setLayout(QHBoxLayout(self.group))

        self.pauseMode = QCheckBox(self.group)
        self.pauseMode.setText('Pause mode')
        self.group.layout().addWidget(self.pauseMode)

        self.layout().addWidget(self.group)
        self.layout().addSpacing(self.height() - 100)

    def enable_check(self, enabled):
        self.group.setCheckable(enabled)
        self.group.setChecked(False)

    def get_settings(self):
        conf = {}

        if not (self.group.isCheckable() and not self.group.isChecked()):
            conf['pause_mode'] = self.pauseMode.isChecked()

        return conf

    def load_settings(self, settings):
        if 'pause_mode' in settings:
            self.pauseMode.setChecked(settings['pause_mode'])
예제 #15
0
class StyleWindow(QWidget):
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Styles')
        
        self.original_palette = QApplication.palette()
        
        styles = QLabel('Styles :')
        self.style_list = QComboBox()
        self.style_list.addItems(QStyleFactory.keys())
        self.style_list.setCurrentIndex(3)
        self.style_list.activated[str].connect(self.change_style)
        
        self.standard_palette = QCheckBox("Standard palette")
        self.standard_palette.setChecked(False)
        self.standard_palette.toggled.connect(self.change_palette)
        
        self.change_style('Fusion')
        
        grid = QGridLayout()
        grid.addWidget(styles, 0, 0, 1, 1)
        grid.addWidget(self.style_list, 0, 1, 1, 1)
        grid.addWidget(self.standard_palette, 1, 0, 1, 2)
        self.setLayout(grid)
        
    def change_style(self, name):
        QApplication.setStyle(QStyleFactory.create(name))
        self.change_palette()

    def change_palette(self):
        if self.standard_palette.isChecked():
            QApplication.setPalette(QApplication.style().standardPalette())
        else:
            QApplication.setPalette(self.original_palette)
예제 #16
0
class ExperimentalFeatures(preferences.Group):
    def __init__(self, page):
        super(ExperimentalFeatures, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.experimentalFeatures = QCheckBox(toggled=self.changed)
        layout.addWidget(self.experimentalFeatures)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Experimental Features"))
        self.experimentalFeatures.setText(_("Enable Experimental Features"))
        self.experimentalFeatures.setToolTip('<qt>' + _(
            "If checked, features that are not yet finished are enabled.\n"
            "You need to restart Frescobaldi to see the changes."))
    
    def loadSettings(self):
        s = QSettings()
        self.experimentalFeatures.setChecked(s.value("experimental-features", False, bool))
        
    def saveSettings(self):
        s = QSettings()
        s.setValue("experimental-features", self.experimentalFeatures.isChecked())
예제 #17
0
    def save_all(self):
        if self.num_frames == 0:
            return

        settings = constants.SETTINGS
        try:
            not_show = settings.value('not_show_save_dialog', type=bool, defaultValue=False)
        except TypeError:
            not_show = False

        if not not_show:
            cb = QCheckBox("Don't ask me again.")
            msg_box = QMessageBox(QMessageBox.Question, self.tr("Confirm saving all signals"),
                                  self.tr("All changed signal files will be overwritten. OK?"))
            msg_box.addButton(QMessageBox.Yes)
            msg_box.addButton(QMessageBox.No)
            msg_box.setCheckBox(cb)

            reply = msg_box.exec()
            not_show_again = cb.isChecked()
            settings.setValue("not_show_save_dialog", not_show_again)
            self.not_show_again_changed.emit()

            if reply != QMessageBox.Yes:
                return

        for f in self.signal_frames:
            if f.signal is None or f.signal.filename == "":
                continue
            f.signal.save()
예제 #18
0
class KeyBoard(preferences.Group):
    def __init__(self, page):
        super(KeyBoard, self).__init__(page)
        
        layout = QGridLayout(spacing=1)
        self.setLayout(layout)

        self.keepCursorInLine = QCheckBox(toggled=self.changed)

        layout.addWidget(self.keepCursorInLine, 0, 0, 1, 1)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Keyboard Preferences"))
        self.keepCursorInLine.setText(_("Horizontal arrow keys keep cursor in current line"))
        self.keepCursorInLine.setToolTip('<qt>' + _(
            "If enabled, the cursor will stay in the current line when using "
            "the horizontal arrow keys, and not wrap around to the next or previous line."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        self.keepCursorInLine.setChecked(s.value("keep_cursor_in_line", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        s.setValue("keep_cursor_in_line", self.keepCursorInLine.isChecked())
예제 #19
0
class StopAllSettings(SettingsSection):

    Name = 'Cue Settings'

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

        self.setLayout(QVBoxLayout(self))

        self.group = QGroupBox(self)
        self.group.setTitle('Mode')
        self.group.setLayout(QHBoxLayout(self.group))

        self.pauseMode = QCheckBox(self.group)
        self.pauseMode.setText('Pause mode')
        self.group.layout().addWidget(self.pauseMode)

        self.layout().addWidget(self.group)
        self.layout().addSpacing(self.height() - 100)

    def enable_check(self, enable):
        self.group.setCheckable(enable)
        self.group.setChecked(False)

    def get_configuration(self):
        conf = {}

        if not (self.group.isCheckable() and not self.group.isChecked()):
            conf['pause_mode'] = self.pauseMode.isChecked()

        return conf

    def set_configuration(self, conf):
        if 'pause_mode' in conf:
            self.pauseMode.setChecked(conf['pause_mode'])
예제 #20
0
class General(SettingsPage):

    NAME = 'General'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setAlignment(Qt.AlignTop)

        # Startup layout
        self.layoutGroup = QGroupBox(self)
        self.layoutGroup.setTitle('Startup layout')
        self.layoutGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.layoutGroup)

        self.startupDialogCheck = QCheckBox(self.layoutGroup)
        self.startupDialogCheck.setText('Use startup dialog')
        self.layoutGroup.layout().addWidget(self.startupDialogCheck)

        self.layoutCombo = QComboBox(self.layoutGroup)
        self.layoutCombo.addItems([lay.NAME for lay in layouts.get_layouts()])
        self.layoutGroup.layout().addWidget(self.layoutCombo)

        self.startupDialogCheck.clicked.connect(
            lambda check: self.layoutCombo.setEnabled(not check))

        # Application style
        self.themeGroup = QGroupBox(self)
        self.themeGroup.setTitle('Application theme')
        self.themeGroup.setLayout(QVBoxLayout())
        self.layout().addWidget(self.themeGroup)

        self.themeCombo = QComboBox(self.themeGroup)
        self.themeCombo.addItems(styles.get_styles())
        self.themeGroup.layout().addWidget(self.themeCombo)

    def get_settings(self):
        conf = {'Layout': {}, 'Theme': {}}

        if self.startupDialogCheck.isChecked():
            conf['Layout']['default'] = 'NoDefault'
        else:
            conf['Layout']['default'] = self.layoutCombo.currentText()

        conf['Theme']['theme'] = self.themeCombo.currentText()
        styles.apply_style(self.themeCombo.currentText())

        return conf

    def load_settings(self, settings):
        if 'default' in settings['Layout']:
            if settings['Layout']['default'].lower() == 'nodefault':
                self.startupDialogCheck.setChecked(True)
                self.layoutCombo.setEnabled(False)
            else:
                self.layoutCombo.setCurrentText(settings['Layout']['default'])
        if 'theme' in settings['Theme']:
            self.themeCombo.setCurrentText(settings['Theme']['theme'])
예제 #21
0
class Prefs(preferences.Group):
    def __init__(self, page):
        super(Prefs, self).__init__(page)

        self._closeOutputs = QCheckBox(clicked=self.changed)
        self._pollingLabel = QLabel()
        self._pollingTime = QSpinBox()
        self._pollingTime.setRange(0, 1000)
        self._pollingTime.setSuffix(" ms")
        self._pollingTime.valueChanged.connect(self.changed)

        layout = QVBoxLayout()
        self.setLayout(layout)

        layout.addWidget(self._closeOutputs)
        app.translateUI(self)

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

        hbox.addWidget(self._pollingLabel)
        hbox.addWidget(self._pollingTime)

    def translateUI(self):
        self.setTitle(_("Preferences"))
        self._closeOutputs.setText(_("Close unused MIDI output"))
        self._closeOutputs.setToolTip(_(
            "Closes unused MIDI ports after one minute. "
            "See \"What's This\" for more information."))
        self._closeOutputs.setWhatsThis(_(
            "<p>If checked, Frescobaldi will close MIDI output ports that are not "
            "used for one minute.</p>\n"
            "<p>This could free up system resources that a software MIDI synthesizer "
            "might be using, thus saving battery power.</p>\n"
            "<p>A side effect is that if you pause a MIDI file for a long time "
            "the instruments are reset to the default piano (instrument 0). "
            "In that case, playing the file from the beginning sets up the "
            "instruments again.</p>\n"))
        self._pollingLabel.setText(_("Polling time for input:"))
        self._pollingTime.setToolTip(_(
            "Polling time for MIDI input. "
            "See \"What's This\" for more information."))
        self._pollingTime.setWhatsThis(_(
            "Sets the time between the polling of the MIDI input port in milliseconds. "
            "Small values lead to faster recognition of incoming MIDI events, but stress "
            "the CPU. 10 ms should be a good value."))

    def loadSettings(self):
        s = QSettings()
        self._closeOutputs.setChecked(
            s.value("midi/close_outputs", False, bool))
        self._pollingTime.setValue(
            s.value("midi/polling_time", 10, int))

    def saveSettings(self):
        s = QSettings()
        s.setValue("midi/close_outputs", self._closeOutputs.isChecked())
        s.setValue("midi/polling_time", self._pollingTime.value())
예제 #22
0
파일: message.py 프로젝트: Kf4btg/SkyModMan
def checkbox_message(icon='question', title='', text="What's that you say?", info_text=None, buttons=('yes', 'no'), default_button = 'none', parent=None, min_width=500, checkbox_text="", checkbox_checked=False):
    """
    Identical to message() except that this function adds a checkbox
     to the dialog box with a customizable message. Also, the return
     value is now tuple of bools: [0] is the return value based on
     the button the user clicked, and [1] is the check-state of the
     checkbox.

    :param parent: QWidget parent
    :param str icon: one of 'question', 'warning', 'info', 'information',
        'critical', 'none', or 'noicon' (these last 2 are the same)
    :param str title:
    :param str text:
    :param str info_text:
    :param buttons: a str or tuple of strs, which can be any of: 'ok',
        'open', 'save', 'cancel', 'close', 'discard', 'apply', 'reset',
        'restore', 'help', 'yes', 'no', 'abort', 'retry', 'ignore',
        'none', or 'nobutton'.  The default is ``('yes', 'no')``

    :param str default_button: by default, there is no default button.
        Specify one of the buttons passed for `buttons` to make it the
        default.
    :param int min_width: minimum width of the created dialog box

    :param checkbox_text: Text to show beside the checkbox
    :param checkbox_checked: whether the checkbox should be checked by default
    :return: tuple(bool, bool): (User response, checkbox state)
    """

    mbox = _mdialog(icon, title, text, info_text, buttons, default_button, parent, min_width)

    cbox=QCheckBox()
    if checkbox_text:
        cbox.setText(checkbox_text)
    cbox.setChecked(checkbox_checked)

    # horiz=shrink(maximum),
    # vert=grow(minimum)
    # without setting this (specifically the horizontal size policy),
    # the checkbox would block the dialog buttons, even though the
    # the widget itself didn't appear to be anywhere near them.
    cbox.setSizePolicy(4, 1)

    ml = mbox.layout()
    ml.addWidget(cbox, ml.rowCount() - 2, 0, 1, -1)

    response = mbox.exec_()

    if response in _yes_response:
        ret = True
    if response in _no_response:
        ret = False
    else:
        ret = response

    return ret, cbox.isChecked()
예제 #23
0
파일: experience.py 프로젝트: wxgeo/geophar
class LancerDes(MyMiniFrame):
    def __init__(self, parent):

        MyMiniFrame.__init__(self, parent, "Simulation de lancers de dés")
        self.parent = parent

        sizer = QVBoxLayout()
        sizer.addWidget(QLabel("On simule le lancer d'un ou plusieurs dés"))
        sizer.addWidget(QLabel("à 6 faces, et on étudie la somme des points."))
        exp = QHBoxLayout()
        exp.addWidget(QLabel("Nombre de dés:"))
        ex = self.experience = QSpinBox()
        ex.setRange(1, 100000)
        ex.setValue(1)
        ex.valueChanged.connect(self.actualiser)
        exp.addWidget(self.experience)
        sizer.addLayout(exp)

        nbr = QHBoxLayout()
        nbr.addWidget(QLabel("Nombre de lancers:"))
        sc = self.sc = QSpinBox()
        sc.setRange(1, 100000)
        sc.setValue(1)
        self.sc.valueChanged.connect(self.actualiser)
        nbr.addWidget(sc)
        sizer.addLayout(nbr)

        self.cb = QCheckBox("Conserver les valeurs")
        sizer.addWidget(self.cb)


        boutons = QHBoxLayout()
        fermer = QPushButton("Fermer")
        boutons.addWidget(fermer)
        lancer = QPushButton("Lancer l'expérience")
        boutons.addWidget(lancer)
        fermer.clicked.connect(self.close)
        lancer.clicked.connect(self.actualiser)

        sizer.addLayout(boutons)
        self.setLayout(sizer)


    def actualiser(self, event = None):
        if not self.cb.isChecked():
            self.parent.actualiser(False)
        self.parent.graph = 'batons'
        n = self.sc.value()
        des = self.experience.value()
        for val in range(des, 6*des + 1):
            self.parent.ajouter_valeur(val, 0)
        self.parent.ajouter_valeurs(*[de(des) for i in range(n)])
        self.parent.calculer()
        self.parent.legende_x = "points obtenus"
        self.parent.legende_y = "nombre de lancers"
        self.parent.affiche()
예제 #24
0
class General(SettingsSection):

    NAME = 'General'

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

        # Startup layout
        self.layoutGroup = QGroupBox(self)
        self.layoutGroup.setTitle('Startup layout')
        self.layoutGroup.setLayout(QVBoxLayout())
        self.layoutGroup.setGeometry(0, 0, self.width(), 120)

        self.startupDialogCheck = QCheckBox(self.layoutGroup)
        self.startupDialogCheck.setText('Use startup dialog')
        self.layoutGroup.layout().addWidget(self.startupDialogCheck)

        self.layoutCombo = QComboBox(self.layoutGroup)
        self.layoutCombo.addItems([lay.NAME for lay in layouts.get_layouts()])
        self.layoutGroup.layout().addWidget(self.layoutCombo)

        self.startupDialogCheck.clicked.connect(
            lambda check: self.layoutCombo.setEnabled(not check))

        # Application style
        self.themeGroup = QGroupBox(self)
        self.themeGroup.setTitle('Application theme')
        self.themeGroup.setLayout(QVBoxLayout())
        self.themeGroup.setGeometry(0, 125, self.width(), 80)

        self.themeCombo = QComboBox(self.themeGroup)
        self.themeCombo.addItems(styles.get_styles())
        self.themeGroup.layout().addWidget(self.themeCombo)

    def get_configuration(self):
        conf = {'Layout': {}, 'Theme': {}}

        if self.startupDialogCheck.isChecked():
            conf['Layout']['default'] = 'NoDefault'
        else:
            conf['Layout']['default'] = self.layoutCombo.currentText()

        conf['Theme']['current'] = self.themeCombo.currentText()
        styles.apply_style(self.themeCombo.currentText())

        return conf

    def set_configuration(self, conf):
        if 'default' in conf['Layout']:
            if conf['Layout']['default'].lower() == 'nodefault':
                self.startupDialogCheck.setChecked(True)
                self.layoutCombo.setEnabled(False)
            else:
                self.layoutCombo.setCurrentText(conf['Layout']['default'])
        if 'current' in conf['Theme']:
            self.themeCombo.setCurrentText(conf['Theme']['current'])
예제 #25
0
파일: dialogs.py 프로젝트: martinohanlon/mu
class FindReplaceDialog(QDialog):
    """
    Display a dialog for getting:

    * A term to find,
    * An optional value to replace the search term,
    * A flag to indicate if the user wishes to replace all.
    """

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

    def setup(self, find=None, replace=None, replace_flag=False):
        self.setMinimumSize(600, 200)
        self.setWindowTitle(_('Find / Replace'))
        widget_layout = QVBoxLayout()
        self.setLayout(widget_layout)
        # Find.
        find_label = QLabel(_('Find:'))
        self.find_term = QLineEdit()
        self.find_term.setText(find)
        widget_layout.addWidget(find_label)
        widget_layout.addWidget(self.find_term)
        # Replace
        replace_label = QLabel(_('Replace (optional):'))
        self.replace_term = QLineEdit()
        self.replace_term.setText(replace)
        widget_layout.addWidget(replace_label)
        widget_layout.addWidget(self.replace_term)
        # Global replace.
        self.replace_all_flag = QCheckBox(_('Replace all?'))
        self.replace_all_flag.setChecked(replace_flag)
        widget_layout.addWidget(self.replace_all_flag)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        widget_layout.addWidget(button_box)

    def find(self):
        """
        Return the value the user entered to find.
        """
        return self.find_term.text()

    def replace(self):
        """
        Return the value the user entered for replace.
        """
        return self.replace_term.text()

    def replace_flag(self):
        """
        Return the value of the global replace flag.
        """
        return self.replace_all_flag.isChecked()
예제 #26
0
    def parameter_done_signal(self, child: QTreeWidgetItem, check_box: QCheckBox):
        vol = self.controller.current_annotation_volume()
        if not vol:
            error_dialog(self, "Error", "No volume selected")
            return

        base_node = child
        term = base_node.text(1)
        ann = vol.annotations.get_by_term(term)
        ann.looked_at = bool(check_box.isChecked())
예제 #27
0
파일: wizard.py 프로젝트: auchytil/rpg
class ScriptsPage(QtWidgets.QWizardPage):
    def initializePage(self):
        self.prepareEdit.setText(str(self.base.spec.prep))
        self.buildEdit.setText(str(self.base.spec.build))
        self.installEdit.setText(str(self.base.spec.install))
        self.checkEdit.setText(str(self.base.spec.check))

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

        self.base = Wizard.base

        self.setTitle(self.tr("Scripts page"))
        self.setSubTitle(self.tr("Write scripts"))

        prepareLabel = QLabel("%prepare: ")
        self.prepareEdit = QTextEdit()

        buildLabel = QLabel("%build: ")
        self.buildEdit = QTextEdit()

        installLabel = QLabel("%install: ")
        self.installEdit = QTextEdit()

        checkLabel = QLabel("%check: ")
        self.checkEdit = QTextEdit()

        buildArchLabel = QLabel("BuildArch: ")
        self.buildArchCheckbox = QCheckBox("noarch")

        grid = QGridLayout()
        grid.addWidget(prepareLabel, 0, 0)
        grid.addWidget(self.prepareEdit, 0, 1)
        grid.addWidget(buildLabel, 1, 0)
        grid.addWidget(self.buildEdit, 1, 1)
        grid.addWidget(installLabel, 2, 0)
        grid.addWidget(self.installEdit, 2, 1)
        grid.addWidget(checkLabel, 3, 0)
        grid.addWidget(self.checkEdit, 3, 1)
        grid.addWidget(buildArchLabel, 4, 0)
        grid.addWidget(self.buildArchCheckbox, 4, 1)
        self.setLayout(grid)

    def validatePage(self):
        self.base.spec.prep = Command(self.prepareEdit.toPlainText())
        self.base.spec.build = Command(self.buildEdit.toPlainText())
        self.base.spec.install = Command(self.installEdit.toPlainText())
        self.base.spec.check = Command(self.checkEdit.toPlainText())
        if self.buildArchCheckbox.isChecked():
            self.base.spec.BuildArch = "noarch"
        return True

    def nextId(self):
        return Wizard.PageRequires
예제 #28
0
파일: main.py 프로젝트: Tinkerforge/brickv
def error_report_main():
    error_message = sys.stdin.read()
    error_message = "<pre>{}</pre>".format(html.escape(error_message).replace("\n", "<br>"))

    app = QApplication(sys.argv)

    if sys.platform == 'darwin':
        # workaround macOS QTBUG-61562
        from brickv.mac_pasteboard_mime_fixed import MacPasteboardMimeFixed
        mac_pasteboard_mime_fixed = MacPasteboardMimeFixed()

    window = QMainWindow()
    window.setWindowTitle('Error - Brick Viewer ' + config.BRICKV_VERSION)
    window.setWindowIcon(QIcon(load_pixmap('brickv-icon.png')))

    widget = QWidget()
    window.setCentralWidget(widget)
    widget.setLayout(QHBoxLayout())

    icon = QLabel()
    icon.setPixmap(QMessageBox.standardIcon(QMessageBox.Critical))
    icon.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
    widget.layout().addWidget(icon)

    right_widget = QWidget()
    right_widget.setLayout(QVBoxLayout())
    right_widget.layout().setContentsMargins(0, 0, 0, 0)

    label = QLabel("Please report this error to <a href='mailto:[email protected]'>[email protected]</a>.<br/><br/>" +
                   "If you know what caused the error and could work around it, please report it anyway. This allows us to improve the error messages.")
    label.setWordWrap(True)
    label.setOpenExternalLinks(True)
    right_widget.layout().addWidget(label)

    tb = QTextBrowser()
    tb.setHtml(error_message)
    right_widget.layout().addWidget(tb)

    cbox = QCheckBox("Show this message again")
    cbox.setChecked(True)
    right_widget.layout().addWidget(cbox)

    btn = QPushButton("Close")
    btn.clicked.connect(lambda event: app.exit())
    right_widget.layout().addWidget(btn)

    widget.layout().addWidget(right_widget)
    window.setMinimumSize(640, 400)
    window.resize(950, 600)
    window.show()

    app.exec_()

    return int(cbox.isChecked())
예제 #29
0
class ResizeDialog(QDialog):
    def __init__(self, parent, width, height):
        QDialog.__init__(self, parent)

        self.setWindowTitle('Resize image')
        self.ratio = width / height
        layout = QGridLayout()
        self.setLayout(layout)

        self.set_resize_view(layout, width, height)
        self.set_aspratio_view(layout)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

        self.resize(250, 150)
        self.show()

    def set_resize_view(self, layout, width, height):
        layout.addWidget(QLabel('Width'), 0, 0, 1, 1)
        self.get_width = SpinBox(width, width, 10, self.width_changed)
        layout.addWidget(self.get_width, 0, 1, 1, 1)

        layout.addWidget(QLabel('Height'), 1, 0, 1, 1)
        self.get_height = SpinBox(height, height, 10, self.height_changed)
        layout.addWidget(self.get_height, 1, 1, 1, 1)

    def set_aspratio_view(self, layout):
        self.pres_aspratio = True
        self.aspratio = QCheckBox('Preserve aspect ratio')
        self.aspratio.setChecked(True)
        self.aspratio.toggled.connect(self.toggle_aspratio)
        layout.addWidget(self.aspratio, 2, 0, 1, 2)

    def width_changed(self, value):
        if self.pres_aspratio:
            height = value / self.ratio
            self.get_height.blockSignals(True)
            self.get_height.setValue(height)
            self.get_height.blockSignals(False)

    def height_changed(self, value):
        if self.pres_aspratio:
            width = value * self.ratio
            self.get_width.blockSignals(True)
            self.get_width.setValue(width)
            self.get_width.blockSignals(False)

    def toggle_aspratio(self):
        """Toggle whether aspect ratio should be preserved."""
        self.pres_aspratio = self.aspratio.isChecked()
예제 #30
0
파일: menu.py 프로젝트: m-nez/tetroll
class Resolution(QWidget):
    """
    Widget for setting the resolution
    """
    def __init__(self):
        super(Resolution, self).__init__()
        self.width = 0
        self.height = 0
        self.fullscreen = True
        self.initUI()
        self.hide()
    def initUI(self):
        vbox = QVBoxLayout(self)
        self.width_line = QLineEdit("0", self)
        self.width_line.setToolTip("Width (0 is your screen resolution)")
        self.height_line = QLineEdit("0", self)
        self.height_line.setToolTip("Height (0 is your screen resolution)")
        self.fullscreen_box = QCheckBox("Fullscreen", self)
        self.fullscreen_box.setTristate(False)
        self.fullscreen_box.setChecked(True)
        vbox.addWidget(self.width_line)
        vbox.addWidget(self.height_line)
        vbox.addWidget(self.fullscreen_box)
    def validate_lines(self):
        states = []
        for line in [self.width_line, self.height_line]:
            text = line.text()
            if text.isdigit():
                if int(text) >= 0:
                    line.setStyleSheet("QLineEdit {background: rgb(210, 255, 210)}")
                    states.append(0)
                else:
                    states.append(1)
                    line.setStyleSheet("QLineEdit {background: rgb(255, 210, 210)}")
            else:
                states.append(2)
                line.setStyleSheet("QLineEdit {background: rgb(255, 210, 210)}")
        if states.count(0) == len(states):
            return True
        else:
            return False

    def set_values(self):
        self.width = int(self.width_line.text())
        self.height = int(self.height_line.text())
        self.fullscreen = self.fullscreen_box.isChecked()
    def __call__(self):
        if self.isVisible():
            if self.validate_lines():
                self.set_values()
                self.hide()
        else:
            self.show()
예제 #31
0
class Window(QWidget):
    """docstring for ClassName"""
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Calculator."
        self.left = 100
        self.top = 100
        self.width = 450
        self.height = 350

        self.InitWindow()

    def InitWindow(self):
        self.cnt = 0
        self.setWindowIcon(QtGui.QIcon("pylogo.png"))
        self.label = QLabel("", self)
        self.label.setFont(QtGui.QFont("Sanserif", 18))
        self.label.setStyleSheet('color:red')

        self.line1 = QLineEdit("", self)
        self.line2 = QLineEdit("", self)
        self.setWindowIcon(QtGui.QIcon("pylogo.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        btnAdd = QPushButton("Add", self)
        btnSub = QPushButton("Subtract", self)
        btnDiv = QPushButton("Divide", self)
        btnMul = QPushButton("Multiply", self)
        btnSqr = QPushButton("Square", self)
        btnCub = QPushButton("Cube", self)
        self.show()

        self.line1.move(20, 10)
        self.line1.setFont(QtGui.QFont("Arial", 15))
        self.line1.show()
        self.line2.move(20, 60)
        self.line2.setFont(QtGui.QFont("Arial", 15))
        self.line2.show()

        self.label.setText("")
        self.label.move(220, 35)
        self.label.show()

        self.labelR = QLabel("", self)

        # self.labelR.setText("Pass Cases: "+ str(100 -self.cnt *16.6666)+" % and Failed Cases: "+str(self.cnt *16.6666)+" %")
        self.labelR.setFont(QtGui.QFont("Times New Roman", 13))
        self.labelR.move(80, 225)
        self.labelR.show()

        btnAdd.setToolTip('Addition')
        btnAdd.move(20, 120)
        btnAdd.clicked.connect(self.addition)
        btnAdd.show()

        btnSub.setToolTip('Subtraction')
        btnSub.move(120, 120)
        btnSub.clicked.connect(self.subtraction)
        btnSub.show()

        btnDiv.setToolTip('Division')
        btnDiv.move(20, 170)
        btnDiv.clicked.connect(self.division)
        btnDiv.show()

        btnMul.setToolTip('Multiplication')
        btnMul.move(120, 170)
        btnMul.clicked.connect(self.multiplication)
        btnMul.show()

        btnSqr.setToolTip('Square')
        btnSqr.move(220, 120)
        btnSqr.clicked.connect(self.square)
        btnSqr.show()

        btnCub.setToolTip('Cube')
        btnCub.move(220, 170)
        btnCub.clicked.connect(self.cube)
        btnCub.show()

        self.show()
        #
        self.createLayout()
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)
        self.show()

    def createLayout(self):
        self.groupBox = QGroupBox("Which cases you want to be failed? ")
        hboxlayout = QHBoxLayout()
        self.check1 = QCheckBox("Addition", self)
        self.check1.move(10, 50)
        hboxlayout.addWidget(self.check1)
        self.check2 = QCheckBox("Subtraction", self)
        hboxlayout.addWidget(self.check2)
        self.check3 = QCheckBox("Multiplication", self)
        hboxlayout.addWidget(self.check3)
        self.check4 = QCheckBox("Division", self)
        hboxlayout.addWidget(self.check4)
        #notw Working
        self.check5 = QCheckBox("Square", self)
        hboxlayout.addWidget(self.check5)
        self.check6 = QCheckBox("Cube", self)
        hboxlayout.addWidget(self.check6)
        self.groupBox.setLayout(hboxlayout)
        self.groupBox.setLayout(hboxlayout)


## Fuctions with test cases

    def addition(self):
        if self.check1.isChecked():
            self.cnt += 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Addition: " + str(num1 + num2 * 0.2345))
        else:
            self.cnt -= 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Addition: " + str(num1 + num2))

    def subtraction(self):
        if self.check2.isChecked():
            self.cnt += 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Subtraction: " + str(num2 - num1 / 0.63))
        else:
            self.cnt -= 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Subtraction: " + str(num1 - num2))

    def multiplication(self):
        if self.check3.isChecked():
            self.cnt += 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Product: " + str((num1 + 0.5) *
                                                 (num2 - 0.121)))
        else:
            self.cnt -= 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Product: " + str(num1 * num2))

    def division(self):
        if self.check4.isChecked():
            self.cnt += 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Division: " + str(num1 / num1 / num2))
        else:
            self.cnt -= 1
            num1 = float(self.line1.text())
            num2 = float(self.line2.text())
            self.label.setFixedWidth(300)
            self.label.setText("Division: " + str(num1 / num2))

    def square(self):
        if self.check5.isChecked():
            self.cnt += 1
            num1 = float(self.line1.text())
            self.label.setFixedWidth(300)
            self.label.setText("Square: " + str((num1 - 0.25)**1.5))
        else:
            self.cnt -= 1
            num1 = float(self.line1.text())
            self.label.setFixedWidth(300)
            self.label.setText("Square: " + str(num1**2))

    def cube(self):
        if self.check6.isChecked():
            self.cnt += 1
            num1 = float(self.line1.text())
            self.label.setFixedWidth(300)
            self.label.setText("Cube: " + str(num1**0.5))
        else:
            self.cnt -= 1
            num1 = float(self.line1.text())
            self.label.setFixedWidth(300)
            self.label.setText("Cube: " + str(num1**3))

    def reportLabel(self):
        self.labelR.setText(self.cnt)
예제 #32
0
class v2rayUpdatePanel(QDialog):
    def __init__(self,
                 protocol=False,
                 proxyhostName=False,
                 port=False,
                 v2rayapi=False,
                 bridgetreasureChest=False):
        super().__init__()
        self.translate = QCoreApplication.translate

        self.update = {
            "enable": True,
            "schedule": {
                "date": 8,
                "time": 4
            },
            "install": "auto",  # ## auto install/ manual install 
            "downloadFile": False,
            "silentInstall": True
        }
        self.daysoftheweek = (self.translate("v2rayUpdatePanel",
                                             "Select a Day for update"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Monday"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Tuesday"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Wednesday"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Thursday"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Friday"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Saturday"),
                              self.translate("v2rayUpdatePanel",
                                             "Every Sunday"),
                              self.translate("v2rayUpdatePanel", "Every Day"))

        self.downloadFiles = ("v2ray-windows-64.zip", "v2ray-macos.zip",
                              "v2ray-linux-64.zip", "v2ray-windows-32.zip",
                              "v2ray-linux-32.zip", "v2ray-freebsd-32.zip",
                              "v2ray-freebsd-64.zip", "v2ray-linux-arm.zip",
                              "v2ray-linux-arm64.zip", "v2ray-linux-mips.zip",
                              "v2ray-linux-mips64.zip",
                              "v2ray-linux-mips64le.zip",
                              "v2ray-linux-mipsle.zip", "v2ray-openbsd-32.zip",
                              "v2ray-openbsd-64.zip", "v2ray-linux-s390x.zip")

        self.protocol = protocol
        self.proxyhostName = proxyhostName
        self.port = port
        if (v2rayapi):
            self.v2rayAPI = v2rayapi
        else:
            self.v2rayAPI = v2rayAPI()

        self.bridgetreasureChest = bridgetreasureChest
        if not self.bridgetreasureChest:
            from bridgehouse.extension import bridgetreasureChest
            self.bridgetreasureChest = bridgetreasureChest.bridgetreasureChest(
            )

        self.v2raycoreAPIURL = QUrl(
            r"""https://api.github.com/repos/v2ray/v2ray-core/releases/latest"""
        )
        self.spinBoxPort = QSpinBox()
        self.lineEditProxy = QLineEdit()
        self.radioButtonSocks5 = QRadioButton("Socks")
        self.radioButtonHttp = QRadioButton("Http")
        self.groupBoxViaProxy = QGroupBox(
            self.translate("v2rayUpdatePanel", "Via Proxy"))
        self.groupBoxViaProxy.setCheckable(True)
        self.proxy = QNetworkProxy()

        if (self.protocol and self.proxyhostName and self.port and v2rayapi):
            self.settingProxyhost(protocol, proxyhostName, port)
            self.groupBoxViaProxy.setChecked(True)
        else:
            self.groupBoxViaProxy.setChecked(False)

    def createPanel(self):
        labelProxy = QLabel(self.translate("v2rayUpdatePanel", "Proxy: "))
        self.lineEditProxy.setFixedWidth(256)
        self.spinBoxPort.setRange(0, 65535)
        self.spinBoxPort.setValue(1080)

        self.buttonCheck = QPushButton(
            self.translate("v2rayUpdatePanel", "Check"))
        self.labelCheckResult = QLabel(
            self.translate("v2rayUpdatePanel",
                           " Check the latest V2Ray-core version"))
        labelcurrentV2raycoreVersion = QLabel(
            self.translate("v2rayUpdatePanel",
                           "Can't get V2Ray-core's version"))
        version = self.bridgetreasureChest.getV2raycoreVersion()
        if (version):
            labelFont = QFont()
            labelFont.setPointSize(12)
            labelFont.setBold(True)
            labelcurrentV2raycoreVersion.setFont(labelFont)
            labelcurrentV2raycoreVersion.setText(
                self.translate(
                    "v2rayUpdatePanel",
                    "The current version of V2Ray is: {}").format(version))

        labelDownloadPath = QLabel(
            self.translate("v2rayUpdatePanel", "V2Ray-core Download Path: "))
        self.lineEditDownloadPath = QLineEdit()
        self.lineEditDownloadPath.setFixedWidth(512)
        self.lineEditDownloadPath.setReadOnly(
            False if v2rayshellDebug else True)
        self.comboBoxv2raycoreVersion = QComboBox()
        self.buttonDownload = QPushButton(
            self.translate("v2rayUpdatePanel", "Download"))

        hboxProxyAddress = QHBoxLayout()
        hboxProxyAddress.addWidget(labelProxy)
        hboxProxyAddress.addWidget(self.lineEditProxy)
        hboxProxyAddress.addWidget(self.spinBoxPort)
        hboxProxyAddress.addStretch()

        hboxRadioButton = QHBoxLayout()
        hboxRadioButton.addWidget(self.radioButtonSocks5)
        hboxRadioButton.addWidget(self.radioButtonHttp)
        hboxRadioButton.addStretch()

        vboxViaProxy = QVBoxLayout()
        vboxViaProxy.addLayout(hboxProxyAddress)
        vboxViaProxy.addLayout(hboxRadioButton)

        self.groupBoxViaProxy.setLayout(vboxViaProxy)

        hboxCheckStatus = QHBoxLayout()
        hboxCheckStatus.addWidget(self.buttonCheck)
        hboxCheckStatus.addWidget(self.labelCheckResult)
        hboxCheckStatus.addWidget(self.comboBoxv2raycoreVersion)
        hboxCheckStatus.addStretch()

        hboxDownloadPath = QHBoxLayout()
        hboxDownloadPath.addWidget(labelDownloadPath)
        hboxDownloadPath.addWidget(self.lineEditDownloadPath)
        hboxDownloadPath.addWidget(self.buttonDownload)
        hboxDownloadPath.addStretch()

        self.groupBoxupdateSchedule = QGroupBox(
            self.translate("v2rayUpdatePanel", "Automatic Updates"))
        self.groupBoxupdateSchedule.setCheckable(True)
        self.groupBoxupdateSchedule.setChecked(False)

        self.comboBoxScheduledate = QComboBox()
        self.comboBoxScheduledate.addItems(self.daysoftheweek)
        labelAt = QLabel(self.translate("v2rayUpdatePanel", "at"))
        self.comboBoxScheduletime = QComboBox()
        self.comboBoxScheduletime.addItems(self.partsoftheDay())

        labelDownloadFile = QLabel(
            self.translate("v2rayUpdatePanel", " Download: "))
        self.comboBoxDownloadFile = QComboBox()
        self.comboBoxDownloadFile.addItems(self.downloadFiles)

        hboxSchedule = QHBoxLayout()
        hboxSchedule.addWidget(self.comboBoxScheduledate)
        hboxSchedule.addWidget(labelAt)
        hboxSchedule.addWidget(self.comboBoxScheduletime)
        hboxSchedule.addWidget(labelDownloadFile)
        hboxSchedule.addWidget(self.comboBoxDownloadFile)
        hboxSchedule.addStretch()

        labelThen = QLabel(self.translate("v2rayUpdatePanel", "Then "))
        self.radioButtonAuto = QRadioButton(
            self.translate("v2rayUpdatePanel", "Auto"))
        self.radioButtonManual = QRadioButton(
            self.translate("v2rayUpdatePanel", "Manual"))
        self.radioButtonManual.setChecked(True)

        self.checkBoxsilentInstall = QCheckBox(
            self.translate("v2rayUpdatePanel", "Silently"))
        labelInstallV2raycore = QLabel(
            self.translate("v2rayUpdatePanel", "Install V2Ray-core"))

        hboxRadioButtonAutoManual = QHBoxLayout()
        hboxRadioButtonAutoManual.addWidget(labelThen)
        hboxRadioButtonAutoManual.addWidget(self.radioButtonAuto)
        hboxRadioButtonAutoManual.addWidget(self.radioButtonManual)
        hboxRadioButtonAutoManual.addSpacerItem(QSpacerItem(25, 5))
        hboxRadioButtonAutoManual.addWidget(self.checkBoxsilentInstall)
        hboxRadioButtonAutoManual.addWidget(labelInstallV2raycore)
        hboxRadioButtonAutoManual.addStretch()

        self.buttonApplyandClose = QPushButton(
            self.translate("v2rayUpdatePanel", "Apply and Close"))
        self.buttonCancel = QPushButton(
            self.translate("v2rayUpdatePanel", "Cancel"))

        hboxbuttonApplyCloseCancel = QHBoxLayout()
        hboxbuttonApplyCloseCancel.addStretch()
        hboxbuttonApplyCloseCancel.addWidget(self.buttonApplyandClose)
        hboxbuttonApplyCloseCancel.addWidget(self.buttonCancel)

        vboxSchedule = QVBoxLayout()
        vboxSchedule.addLayout(hboxSchedule)
        vboxSchedule.addLayout(hboxRadioButtonAutoManual)
        self.groupBoxupdateSchedule.setLayout(vboxSchedule)

        vboxUpdatPanel = QVBoxLayout()
        vboxUpdatPanel.addWidget(self.groupBoxViaProxy)
        vboxUpdatPanel.addWidget(labelcurrentV2raycoreVersion)
        vboxUpdatPanel.addLayout(hboxCheckStatus)
        vboxUpdatPanel.addLayout(hboxDownloadPath)
        vboxUpdatPanel.addWidget(self.groupBoxupdateSchedule)
        vboxUpdatPanel.addLayout(hboxbuttonApplyCloseCancel)
        vboxUpdatPanel.addStretch()

        if v2rayshellDebug:
            hbox = QHBoxLayout()
            self.updatev2ray = updateV2ray()
            self.autoupdate = autoCheckUpdate()
            self.__testBtn = QPushButton("__Test")
            self.__testGetGithubRelease = QPushButton("__TestGetGithubRelease")
            self.__testDownload = QPushButton("__TestDownloadformGithub")
            hbox.addWidget(self.__testBtn)
            hbox.addWidget(self.__testGetGithubRelease)
            hbox.addWidget(self.__testDownload)
            vboxUpdatPanel.addLayout(hbox)
            # self.__testBtn.clicked.connect(lambda: self.updatev2ray.unzipdownloadFile("v2ray-linux-mips64le.zip"))
            self.__testGetGithubRelease.clicked.connect(
                self.autoupdate.checkGithubV2RaycoreLastestReleaseVersion)
            self.__testDownload.clicked.connect(
                self.autoupdate.tryupdateV2Raycore)

        self.settingupdateSchedule()

        self.setLayout(vboxUpdatPanel)

        self.createUpadtePanelSignals()

    def createUpadtePanelSignals(self):
        self.comboBoxv2raycoreVersion.currentTextChanged.connect(
            self.ondownloadVersionSelect)
        self.buttonCheck.clicked.connect(self.onbuttonCheckV2raycoreversion)
        self.buttonDownload.clicked.connect(self.ondownloadV2raycore)
        self.groupBoxViaProxy.clicked.connect(self.ongroupBoxViaProxy)
        self.buttonCancel.clicked.connect(self.close)
        self.buttonApplyandClose.clicked.connect(
            self.onupdatebuttonApplyandClose)

    def onupdatebuttonApplyandClose(self):
        self.bridgetreasureChest.clearUpdate()
        update = {}
        update["enable"] = True if self.groupBoxupdateSchedule.isChecked(
        ) else False
        update["schedule"] = {}
        update["schedule"]["date"] = int(
            self.comboBoxScheduledate.currentIndex())
        update["schedule"]["time"] = int(
            self.comboBoxScheduletime.currentIndex())
        update["install"] = "auto" if self.radioButtonAuto.isChecked(
        ) else "manual"
        update["downloadFile"] = self.comboBoxDownloadFile.currentText()
        update["silentInstall"] = True if self.checkBoxsilentInstall.isChecked(
        ) else False

        self.bridgetreasureChest.setUpdateSchedule(update)
        self.bridgetreasureChest.save.emit()
        self.close()

    def settingupdateSchedule(self):
        if self.bridgetreasureChest.updateisEnable():
            self.groupBoxupdateSchedule.setChecked(True)
        else:
            self.groupBoxupdateSchedule.setChecked(False)

        downloadFile = self.bridgetreasureChest.getupdatedownloadFile()
        if downloadFile in self.downloadFiles:
            self.comboBoxDownloadFile.setCurrentText(downloadFile)

        try:
            self.comboBoxScheduledate.setCurrentIndex(
                self.bridgetreasureChest.getupdateScheduledate())
        except Exception:
            # a new panel will get a false value from config.v2rayshell
            pass

        try:
            self.comboBoxScheduletime.setCurrentIndex(
                self.bridgetreasureChest.getupdateScheduletime())
        except Exception:
            pass

        installOption = self.bridgetreasureChest.getupdateinstallOption()
        if installOption == "auto":
            self.radioButtonAuto.setChecked(True)
            self.radioButtonManual.setChecked(False)
        else:
            self.radioButtonManual.setChecked(True)
            self.radioButtonAuto.setChecked(False)

        self.checkBoxsilentInstall.setChecked(
            True if self.bridgetreasureChest.getsilentInstall() else False)

    def partsoftheDay(self):
        """
        Morning   :  05:00 to 12:00 (5, 6, 7, 8, 9, 10, 11, 12)
        Afternoon :  13:00 to 17:00 (13, 14, 15, 16, 17)
        Evening   :  18:00 to 21:00 (18, 19, 20, 21)
        Night     :  22:00 to 04:00 (22, 23, 0, 1, 2, 3, 4)
        """
        return (self.translate("v2rayUpdatePanel", "Select a time for update"),
                self.translate("v2rayUpdatePanel", "Morning"),
                self.translate("v2rayUpdatePanel", "Afternoon"),
                self.translate("v2rayUpdatePanel", "Evening"),
                self.translate("v2rayUpdatePanel", "Night"))

    def settingProxyhost(self, protocol, proxyhostName, port):
        """
        update v2ray need via proxy
        """
        self.proxy.setType(protocol)
        self.proxy.setHostName(proxyhostName)
        self.proxy.setPort(int(port))
        self.proxy.setApplicationProxy(self.proxy)

        if (protocol == QNetworkProxy.Socks5Proxy):
            self.radioButtonSocks5.setChecked(True)
            self.radioButtonHttp.setChecked(False)
        if (protocol == QNetworkProxy.HttpProxy):
            self.radioButtonHttp.setChecked(True)
            self.radioButtonSocks5.setChecked(False)

        self.lineEditProxy.setText(proxyhostName)
        self.spinBoxPort.setValue(int(port))

    def checkisViaProxy(self):
        if self.groupBoxViaProxy.isChecked():
            if self.lineEditProxy.text() == "" or self.spinBoxPort.value(
            ) == 0:
                self.lineEditDownloadPath.clear()
                self.comboBoxv2raycoreVersion.clear()
                return
            else:
                if (self.radioButtonSocks5.isChecked()):
                    protocol = QNetworkProxy.Socks5Proxy
                elif (self.radioButtonHttp.isChecked()):
                    protocol = QNetworkProxy.HttpProxy
                self.proxy.setType(protocol)
                self.proxy.setHostName(self.lineEditProxy.text())
                self.proxy.setPort(self.spinBoxPort.value())
                self.proxy.setApplicationProxy(self.proxy)
        else:
            self.proxy.setType(QNetworkProxy.NoProxy)
            self.proxy.setApplicationProxy(self.proxy)

    def ongroupBoxViaProxy(self):
        self.checkisViaProxy()

    def onbuttonCheckV2raycoreversion(self):
        self.checkisViaProxy()
        labelFont = QFont()
        labelFont.setPointSize(12)
        labelFont.setBold(True)
        self.labelCheckResult.setFont(labelFont)
        self.labelCheckResult.setText(
            self.translate("v2rayUpdatePanel", "Checking..."))
        self.updateV2ray = updateV2ray(self.v2rayAPI,
                                       self.v2raycoreAPIURL,
                                       checkDownloadInfo=True,
                                       downloadV2raycore=False)
        self.v2rayAPI.checkDownloadInfo.connect(
            self.settingUpdateDownloadFiles)

    def ondownloadVersionSelect(self):
        currentv2raycoreVersion = self.comboBoxv2raycoreVersion.currentText()
        if currentv2raycoreVersion != "":
            downloadINFO = self.v2rayAPI.getdownloadINFO()
            downloadPath = downloadINFO[currentv2raycoreVersion]
            self.lineEditDownloadPath.setText(downloadPath)
        else:
            self.lineEditDownloadPath.clear()

    def settingUpdateDownloadFiles(self):
        if (not self.v2rayAPI.getv2raycoreAPI()):
            self.labelCheckResult.setText(
                self.v2rayAPI.getV2raycoreErrorString())
            self.lineEditDownloadPath.clear()
            self.comboBoxv2raycoreVersion.clear()
            return

        downloadINFO = copy.deepcopy(self.v2rayAPI.getdownloadINFO())
        try:
            downloadINFO["metadata.txt"]
            metadata = True
        except Exception:
            metadata = False

        if (metadata):
            del downloadINFO[
                "metadata.txt"]  # ## metadata.txt should not in the download list

        if (downloadINFO):
            k = 1
            self.comboBoxv2raycoreVersion.clear()
            self.comboBoxv2raycoreVersion.insertItem(0, "")
            for i in downloadINFO.keys():
                self.comboBoxv2raycoreVersion.insertItem(++k, str(i))
            self.comboBoxv2raycoreVersion.setSizeAdjustPolicy(
                QComboBox.AdjustToContents)
            self.labelCheckResult.setText(
                self.translate("v2rayUpdatePanel",
                               "The latest version is: {}").format(
                                   self.v2rayAPI.getV2raycoreVersion()))

    def ondownloadV2raycore(self):
        self.checkisViaProxy()
        filePath = self.lineEditDownloadPath.text()
        if (filePath != ""):
            self.updateV2ray = updateV2ray(self.v2rayAPI,
                                           QUrl(filePath),
                                           checkDownloadInfo=False,
                                           downloadV2raycore=True)
예제 #33
0
파일: code.py 프로젝트: BeSoBad/study
class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.title = QLabel('Cubic Spline')
        self.figure = matplotlib.pyplot.figure(figsize=(4, 4))
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.toolbar = NavigationToolbar2QT(self.canvas, self)
        self.check = QCheckBox('Tangent')
        self.check.stateChanged.connect(self.tang)
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        self.lbl1_0 = QLabel('Point 1')
        self.lbl1_1 = QLabel('X')
        self.line1_1 = QLineEdit()
        self.lbl1_2 = QLabel('Y')
        self.line1_2 = QLineEdit()
        self.lbl2_0 = QLabel('Point 2')
        self.lbl2_1 = QLabel('X')
        self.line2_1 = QLineEdit()
        self.lbl2_2 = QLabel('Y')
        self.line2_2 = QLineEdit()
        self.lbl3_0 = QLabel('Point 3')
        self.lbl3_1 = QLabel('X')
        self.line3_1 = QLineEdit()
        self.lbl3_2 = QLabel('Y')
        self.line3_2 = QLineEdit()
        self.lbl4_0 = QLabel('Point 4')
        self.lbl4_1 = QLabel('X')
        self.line4_1 = QLineEdit()
        self.lbl4_2 = QLabel('Y')
        self.line4_2 = QLineEdit()
        self.lbl5_0 = QLabel('Point 5')
        self.lbl5_1 = QLabel('X')
        self.line5_1 = QLineEdit()
        self.lbl5_2 = QLabel('Y')
        self.line5_2 = QLineEdit()

        layout1 = QHBoxLayout()
        layout2 = QHBoxLayout()
        layout3 = QHBoxLayout()
        layout4 = QHBoxLayout()
        layout5 = QHBoxLayout()
        layout6 = QHBoxLayout()
        layout = QVBoxLayout()
        layout.addWidget(self.title)
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout1.addWidget(self.lbl1_0)
        layout1.addWidget(self.lbl1_1)
        layout1.addWidget(self.line1_1)
        layout1.addWidget(self.lbl1_2)
        layout1.addWidget(self.line1_2)
        layout2.addWidget(self.lbl2_0)
        layout2.addWidget(self.lbl2_1)
        layout2.addWidget(self.line2_1)
        layout2.addWidget(self.lbl2_2)
        layout2.addWidget(self.line2_2)
        layout3.addWidget(self.lbl3_0)
        layout3.addWidget(self.lbl3_1)
        layout3.addWidget(self.line3_1)
        layout3.addWidget(self.lbl3_2)
        layout3.addWidget(self.line3_2)
        layout4.addWidget(self.lbl4_0)
        layout4.addWidget(self.lbl4_1)
        layout4.addWidget(self.line4_1)
        layout4.addWidget(self.lbl4_2)
        layout4.addWidget(self.line4_2)
        layout5.addWidget(self.lbl5_0)
        layout5.addWidget(self.lbl5_1)
        layout5.addWidget(self.line5_1)
        layout5.addWidget(self.lbl5_2)
        layout5.addWidget(self.line5_2)
        layout6.addWidget(self.check)
        layout6.addWidget(self.button)
        layout.addLayout(layout1)
        layout.addLayout(layout2)
        layout.addLayout(layout3)
        layout.addLayout(layout4)
        layout.addLayout(layout5)
        layout.addLayout(layout6)
        self.setLayout(layout)
        self.x = [None] * 5
        self.y = [None] * 5
        self.f = None

    def tang(self):

        if self.check.isChecked():
            f_derivative = self.f.derivative()
            for i in self.x:
                l = [i - 2, i + 2]
                k = [self.f(i) + f_derivative(i) * (j - i) for j in l]
                matplotlib.pyplot.plot(l, k, "gray")
            self.canvas.draw()
        else:
            self.plot()

    def plot(self):
        try:
            self.x[0] = int(self.line1_1.text())
            self.y[0] = int(self.line1_2.text())
            self.x[1] = int(self.line2_1.text())
            self.y[1] = int(self.line2_2.text())
            self.x[2] = int(self.line3_1.text())
            self.y[2] = int(self.line3_2.text())
            self.x[3] = int(self.line4_1.text())
            self.y[3] = int(self.line4_2.text())
            self.x[4] = int(self.line5_1.text())
            self.y[4] = int(self.line5_2.text())
        except ValueError:
            return

        self.f = CubicSpline(self.x, self.y)
        xnew = numpy.linspace(min(self.x) - 2, max(self.x) + 2, 500)
        ax = self.figure.add_subplot(111)
        ax.set_ylim(min(self.y) - 50, max(self.y) + 50)
        self.figure.clear()
        matplotlib.pyplot.plot(self.x, self.y, 'o', xnew, self.f(xnew),
                               'black')
        self.canvas.draw()
예제 #34
0
class mywidget2(QWidget):

    def __init__(self, guild):
        super().__init__()
        self.guild = guild
        self.initui()

    def initui(self):
        self.lb1 = QLabel("ID", self)
        self.lb2 = QLabel("Password", self)

        self.le1 = QLineEdit()
        self.le1.returnPressed.connect(self.saveaccount)
        self.le2 = QLineEdit()
        self.le2.returnPressed.connect(self.saveaccount)
        self.le2.setEchoMode(2)
        if self.guild.g_account() != "?":
            self.le1.setText(self.guild.account)
        if self.guild.g_passwd() != "?":
            self.le2.setText(self.guild.password)

        self.chb1 = QCheckBox('넥슨', self)
        self.chb2 = QCheckBox('메이플', self)
        self.chb3 = QCheckBox("비번 보기")
        self.chb1.released.connect(self.check1)
        self.chb1.toggle()
        self.chb2.released.connect(self.check2)
        self.chb3.released.connect(self.check3)
        self.btn = QPushButton("적용")
        self.btn.pressed.connect(self.saveaccount)

        hbox = QHBoxLayout()
        hbox.addWidget(self.lb1, 1)
        hbox.addWidget(self.le1, 2)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.lb2, 1)
        hbox2.addWidget(self.le2, 2)

        hbox3 = QHBoxLayout()
        hbox3.addStretch(1)
        hbox3.addWidget(self.chb1, 1)
        hbox3.addWidget(self.chb2, 1)
        hbox3.addWidget(self.chb3,1)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox)
        vbox.addLayout(hbox2)
        vbox.addWidget(self.btn)

        self.setLayout(vbox)

        self.setGeometry(450, 300, 250, 100)

    def saveaccount(self):
        stat = None
        if self.chb1.isChecked():
            self.guild.account_type=0
        else:
            self.guild.account_type=1
        if (self.le1.text()!="") and (self.le2.text()!=""):
            self.guild.account = self.le1.text()
            self.guild.password = self.le2.text()
            self.guild.save_as_file()
            self.hide()

    def check1(self):
        self.chb2.toggle()

    def check2(self):
        self.chb1.toggle()
    def check3(self):
        if self.chb3.isChecked():
            self.le2.setEchoMode(0)
        else:
            self.le2.setEchoMode(2)

    def set_font(self, font):
        self.lb1.setFont(font)
        self.lb2.setFont(font)
        self.le1.setFont(font)
        self.le2.setFont(font)
        self.chb1.setFont(font)
        self.chb2.setFont(font)
        self.chb3.setFont(font)
        self.btn.setFont(font)
예제 #35
0
class StockMemoDeck(QWidget):
    STATIC_HEADER = ['Code', 'Name']

    def __init__(self, memo_context: dict):
        self.__memo_context = memo_context
        self.__sas_if: sasIF = self.__memo_context.get(
            'sas_if') if self.__memo_context is not None else None
        super(StockMemoDeck, self).__init__()

        if self.__memo_context is not None:
            # self.__memo_context.add_observer(self)
            self.__sas_if: sasIF = self.__memo_context.get('sas_if')
            self.__memo_editor: StockMemoEditor = self.__memo_context.get(
                'editor')
        else:
            # For layout debug
            self.__sas_if: sasIF = None
            self.__memo_editor = None

        self.__memo_extras = []
        self.__list_securities = []
        self.__show_securities = []

        # ---------------- Page -----------------

        self.__page = 1
        self.__item_per_page = 20

        self.__button_first = QPushButton('|<')
        self.__button_prev = QPushButton('<')
        self.__spin_page = QSpinBox()
        self.__label_total_page = QLabel('/ 1')
        self.__button_jump = QPushButton('GO')
        self.__button_next = QPushButton('>')
        self.__button_last = QPushButton('>|')

        self.__button_reload = QPushButton('Reload')
        self.__check_show_black_list = QCheckBox('Black List')

        # --------------- Widgets ---------------

        self.__memo_table = TableViewEx()
        self.__stock_selector = \
            SecuritiesSelector(self.__sas_if) if self.__sas_if is not None else QComboBox()
        # TODO: Path from server
        self.__line_path = QLineEdit('')
        self.__info_panel = QLabel(NOTE)
        self.__button_new = QPushButton('New')
        self.__button_filter = QPushButton('Filter')
        self.__button_browse = QPushButton('Browse')
        # self.__button_black_list = QPushButton('Black List')

        self.__layout_extra = QHBoxLayout()

        self.init_ui()
        self.config_ui()

        self.show_securities(self.__sas_if.stock_memo_get_all_security(
        ) if self.__sas_if is not None else [])

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

        # Page control
        page_control_line = QHBoxLayout()
        page_control_line.addWidget(self.__button_reload, 1)
        page_control_line.addWidget(self.__check_show_black_list, 1)

        page_control_line.addWidget(QLabel(''), 99)
        page_control_line.addWidget(self.__button_first, 1)
        page_control_line.addWidget(self.__button_prev, 1)
        page_control_line.addWidget(self.__spin_page, 1)
        page_control_line.addWidget(self.__label_total_page, 1)
        page_control_line.addWidget(self.__button_jump, 1)
        page_control_line.addWidget(self.__button_next, 1)
        page_control_line.addWidget(self.__button_last, 1)

        group_box, group_layout = create_v_group_box('Stock Memo')
        group_layout.addWidget(self.__memo_table)
        group_layout.addLayout(page_control_line)
        main_layout.addWidget(group_box, 10)

        group_box, group_layout = create_h_group_box('Edit')
        right_area = QVBoxLayout()
        group_layout.addWidget(self.__info_panel, 4)
        group_layout.addLayout(right_area, 6)

        line = horizon_layout([
            QLabel('股票选择:'), self.__stock_selector, self.__button_filter,
            self.__button_new
        ], [1, 10, 1, 1])
        right_area.addLayout(line)

        line = horizon_layout(
            [QLabel('保存路径:'), self.__line_path, self.__button_browse],
            [1, 10, 1])
        right_area.addLayout(line)

        # line = horizon_layout([QLabel('其它功能:'), self.__button_black_list, QLabel('')],
        #                       [1, 1, 10])

        self.__layout_extra.addWidget(QLabel('其它功能:'))
        self.__layout_extra.addStretch()
        right_area.addLayout(self.__layout_extra)

        main_layout.addWidget(group_box, 1)

    def config_ui(self):
        self.setMinimumSize(800, 600)
        self.__info_panel.setWordWrap(True)

        # -------------- Page Control --------------

        self.__button_first.clicked.connect(
            partial(self.__on_page_control, '|<'))
        self.__button_prev.clicked.connect(partial(self.__on_page_control,
                                                   '<'))
        self.__button_jump.clicked.connect(partial(self.__on_page_control,
                                                   'g'))
        self.__button_next.clicked.connect(partial(self.__on_page_control,
                                                   '>'))
        self.__button_last.clicked.connect(
            partial(self.__on_page_control, '>|'))

        self.__button_reload.clicked.connect(self.__on_button_reload)

        self.__check_show_black_list.setChecked(False)
        self.__check_show_black_list.clicked.connect(
            self.__on_check_show_black_list)

        self.__memo_table.SetColumn(self.__memo_table_columns())
        self.__memo_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.__memo_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.__memo_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.__memo_table.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.__memo_table.doubleClicked.connect(
            self.__on_memo_item_double_clicked)

        self.__button_new.clicked.connect(self.__on_button_new_clicked)
        self.__button_browse.clicked.connect(self.__on_button_browse)
        self.__button_filter.clicked.connect(self.__on_button_filter_clicked)

        self.__button_filter.setDefault(True)
        line_editor = self.__stock_selector.lineEdit()
        if line_editor is not None:
            line_editor.returnPressed.connect(self.__on_button_filter_clicked)

    def add_memo_extra(self, extra: MemoExtra):
        extra.set_memo_ui(self)
        self.__memo_extras.append(extra)

        global_entry_text = extra.global_entry_text()
        if str_available(global_entry_text):
            button = QPushButton(global_entry_text)
            button.clicked.connect(
                partial(self.__on_button_global_entry, extra))
            self.__layout_extra.insertWidget(1, button)

    def update_list(self):
        self.__update_memo_securities_list()

    def show_securities(self, securities: [str]):
        self.__update_securities(securities)
        self.__update_memo_securities_list()

    # # ------------------- Interface of StockMemoData.Observer --------------------
    #
    # # def on_memo_updated(self):
    # #     self.update_list()
    #
    # def on_data_updated(self, name: str, data: any):
    #     nop(data)
    #     if name in ['memo_record', 'tags']:
    #         self.update_list()

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

    def __on_page_control(self, button_mark: str):
        new_page = self.__page
        if button_mark == '|<':
            new_page = 0
        elif button_mark == '<':
            new_page -= 1
        elif button_mark == 'g':
            new_page = self.__spin_page.value()
        elif button_mark == '>':
            new_page += 1
        elif button_mark == '>|':
            new_page = self.__max_page()

        new_page = max(1, new_page)
        new_page = min(self.__max_page(), new_page)

        if self.__page != new_page:
            self.__page = new_page
            self.__spin_page.setValue(self.__page)
            self.update_list()

    def __on_button_browse(self):
        folder = str(
            QFileDialog.getExistingDirectory(
                self,
                "Select Private Folder",
                directory=self.__line_path.text()))
        if folder == '':
            return
        self.__line_path.setText(folder)

        # Save to system config
        config = self.__sas_if.sas_get_service_config()
        config['memo_path'] = folder
        self.__sas_if.sas_set_service_config(config)

        # Now those setting are on server side.
        # TODO: How to handle setting update on server side
        # Update new path to memo extras
        # self.__memo_context.set_root_path(folder)
        #
        # stock_tags: Tags = self.__memo_context.get('tags')
        # if stock_tags is not None:
        #     stock_tags.load(os.path.join(folder, 'tags.json'))
        # self.__memo_context.get_memo_record().load(os.path.join(folder, 'stock_memo.csv'))

    def __on_button_new_clicked(self):
        security = self.__stock_selector.get_input_securities()
        self.__memo_editor.select_security(security)
        self.__memo_editor.create_new_memo(now())
        self.__memo_editor.exec()

    def __on_button_filter_clicked(self):
        input_security = self.__stock_selector.get_input_securities()
        list_securities = self.__sas_if.sas_guess_stock_identities(
            input_security)
        self.show_securities(list_securities)

    def __on_button_reload(self):
        self.show_securities(self.__sas_if.stock_memo_get_all_security(
        ) if self.__sas_if is not None else [])

    def __on_check_show_black_list(self):
        self.__update_securities()
        self.__update_memo_securities_list()

    def __on_memo_item_double_clicked(self, index: QModelIndex):
        item_data = index.data(Qt.UserRole)
        if item_data is not None and isinstance(item_data, tuple):
            memo_extra, security = item_data
            memo_extra.security_entry(security)
            # print('Double Click on memo item: %s - %s' % (memo_extra.title_text(), security))

    def __on_button_global_entry(self, extra: MemoExtra):
        extra.global_entry()

    def __update_memo_securities_list(self, securities: [str] or None = None):
        if securities is None:
            securities = self.__show_securities

        columns = self.__memo_table_columns()

        self.__memo_table.Clear()
        self.__memo_table.SetColumn(columns)

        index = []
        offset = (self.__page - 1) * self.__item_per_page

        for i in range(offset, offset + self.__item_per_page):
            if i < 0 or i >= len(securities):
                continue
            security = securities[i]
            index.append(str(i + 1))

            self.__memo_table.AppendRow([''] * len(columns))
            row_count = self.__memo_table.RowCount()
            row = row_count - 1

            col = 0
            self.__memo_table.SetItemText(row, col, security)
            self.__memo_table.SetItemData(row, col, security)

            col = 1
            self.__memo_table.SetItemText(
                row, col, self.__sas_if.sas_stock_identity_to_name(security))

            for memo_extra in self.__memo_extras:
                if not str_available(memo_extra.title_text()):
                    continue

                col += 1
                text = memo_extra.security_entry_text(security)

                self.__memo_table.SetItemText(row, col, text)
                self.__memo_table.SetItemData(row, col, (memo_extra, security))

                # _item = self.__memo_table.GetItem(row, col)
                # _item.clicked.connect(partial(self.__on_memo_item_clicked, _item, security, memo_extra))

        model = self.__memo_table.model()
        model.setVerticalHeaderLabels(index)

    def __update_securities(self, list_securities: [str] or None = None):
        if list_securities is None:
            # Just refresh the show securities
            pass
        else:
            self.__list_securities = list_securities \
                if isinstance(list_securities, (list, tuple)) else [list_securities]
        self.__update_show_securities()
        self.__update_page_control()

    def __update_show_securities(self):
        self.__show_securities = self.__list_securities

        show_black_list = self.__check_show_black_list.isChecked()
        if not show_black_list:
            #     black_list: BlackList = self.__memo_context.get_data('black_list')
            #     if black_list is not None:
            #         black_list_securities = black_list.all_black_list()
            if self.__sas_if is not None:
                black_list_securities = self.__sas_if.all_black_list()
                if black_list_securities is not None:
                    self.__show_securities = list(
                        set(self.__show_securities).difference(
                            set(black_list_securities)))
                else:
                    pass

    def __memo_table_columns(self) -> [str]:
        return StockMemoDeck.STATIC_HEADER + [
            memo_extra.title_text() for memo_extra in self.__memo_extras
            if str_available(memo_extra.title_text())
        ]

    def __max_page(self) -> int:
        return (len(self.__show_securities) + self.__item_per_page -
                1) // self.__item_per_page

    def __update_page_control(self):
        self.__page = 1
        max_page = self.__max_page()
        self.__spin_page.setValue(1)
        self.__spin_page.setMinimum(1)
        self.__spin_page.setMaximum(max_page)
        self.__label_total_page.setText('/ %s' % max_page)
class SearchWidget(QWidget):

    """Search widget component, search for text inside the editor."""

    def __init__(self, parent=None):
        super(SearchWidget, self).__init__(parent)
        hSearch = QHBoxLayout(self)
        hSearch.setContentsMargins(0, 0, 0, 0)
        self._checkSensitive = QCheckBox(translations.TR_SEARCH_CASE_SENSITIVE)
        self._checkWholeWord = QCheckBox(translations.TR_SEARCH_WHOLE_WORDS)
        self._line = TextLine(self)
        self._line.setMinimumWidth(250)
        self._btnClose = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self._btnClose.setIconSize(QSize(16, 16))
        self._btnFind = QPushButton(QIcon(":img/find"), '')
        self._btnFind.setIconSize(QSize(16, 16))
        self.btnPrevious = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowLeft), '')
        self.btnPrevious.setIconSize(QSize(16, 16))
        self.btnPrevious.setToolTip(
            self.tr("Press %s") %
            resources.get_shortcut("Find-previous").toString(
                QKeySequence.NativeText))
        self.btnNext = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowRight), '')
        self.btnNext.setIconSize(QSize(16, 16))
        self.btnNext.setToolTip(
            self.tr("Press %s") %
            resources.get_shortcut("Find-next").toString(
                QKeySequence.NativeText))
        hSearch.addWidget(self._btnClose)
        hSearch.addWidget(self._line)
        hSearch.addWidget(self._btnFind)
        hSearch.addWidget(self.btnPrevious)
        hSearch.addWidget(self.btnNext)
        hSearch.addWidget(self._checkSensitive)
        hSearch.addWidget(self._checkWholeWord)

        self.totalMatches = 0
        self.index = 0
        self._line.counter.update_count(self.index, self.totalMatches)

        self._btnFind.clicked['bool'].connect(self.find)
        self.btnNext.clicked['bool'].connect(self.find_next)
        self.btnPrevious.clicked['bool'].connect(self.find_previous)
        self._checkSensitive.stateChanged[int].connect(self._states_changed)
        self._checkWholeWord.stateChanged[int].connect(self._states_changed)

        IDE.register_service('status_search', self)

    def install(self):
        """Install SearchWidget as a service and its shortcuts."""
        self.hide()
        ide = IDE.getInstance()

        ui_tools.install_shortcuts(self, actions.ACTIONS_STATUS_SEARCH, ide)

    @property
    def search_text(self):
        """Return the text entered by the user."""
        return self._line.text()

    @property
    def sensitive_checked(self):
        """Return the value of the sensitive checkbox."""
        return self._checkSensitive.isChecked()

    @property
    def wholeword_checked(self):
        """Return the value of the whole word checkbox."""
        return self._checkWholeWord.isChecked()

    def _states_changed(self):
        """Checkboxs state changed, update search."""
        main_container = IDE.get_service("main_container")
        editor = None
        if main_container:
            editor = main_container.get_current_editor()
        if editor:
            editor.setCursorPosition(0, 0)
            self.find()

    def find(self, forward=True):
        """Collect flags and execute search in the editor."""
        reg = False
        cs = self.sensitive_checked
        wo = self.wholeword_checked
        main_container = IDE.get_service("main_container")
        editor = None
        if main_container:
            editor = main_container.get_current_editor()
        if editor:
            index, matches = editor.find_match(
                self.search_text, reg, cs, wo, forward=forward)
            self._line.counter.update_count(index, matches,
                                            len(self.search_text) > 0)

    def find_next(self):
        """Find the next occurrence of the word to search."""
        self.find()
        if self.totalMatches > 0 and self.index < self.totalMatches:
            self.index += 1
        elif self.totalMatches > 0:
            self.index = 1
        self._line.counter.update_count(self.index, self.totalMatches)

    def find_previous(self):
        """Find the previous occurrence of the word to search."""
        self.find(forward=False)
        if self.totalMatches > 0 and self.index > 1:
            self.index -= 1
        elif self.totalMatches > 0:
            self.index = self.totalMatches
            main_container = IDE.get_service("main_container")
            editor = None
            if main_container:
                editor = main_container.get_current_editor()
            if editor:
                self.find(forward=False)
        self._line.counter.update_count(self.index, self.totalMatches)
예제 #37
0
class FatalCrashDialog(_CrashDialog):
    """Dialog which gets shown when a fatal error occurred.

    Attributes:
        _log: The log text to display.
        _type: The type of error which occurred.
        _func: The function (top of the stack) in which the error occurred.
        _chk_history: A checkbox for the user to decide if page history should
                      be sent.
    """
    def __init__(self, debug, text, parent=None):
        self._chk_history = None
        super().__init__(debug, parent)
        self._log = text
        self.setAttribute(Qt.WA_DeleteOnClose)
        self._set_crash_info()
        self._type, self._func = parse_fatal_stacktrace(self._log)

    def _get_error_type(self):
        if self._type == 'Segmentation fault':
            return 'segv'
        else:
            return self._type

    def _get_paste_title_desc(self):
        return self._func

    def _init_text(self):
        super()._init_text()
        text = ("<b>qutebrowser was restarted after a fatal crash.</b><br/>"
                "<br/>Note: Crash reports for fatal crashes sometimes don't "
                "contain the information necessary to fix an issue. Please "
                "follow the steps in <a href='https://github.com/The-Compiler/"
                "qutebrowser/blob/master/doc/stacktrace.asciidoc'>"
                "stacktrace.asciidoc</a> to submit a stacktrace.<br/>")
        self._lbl.setText(text)

    def _init_checkboxes(self):
        """Add checkboxes to the dialog."""
        super()._init_checkboxes()
        self._chk_history = QCheckBox(
            "Include a history of the last "
            "accessed pages in the report.",
            checked=True)
        try:
            if config.val.content.private_browsing:
                self._chk_history.setChecked(False)
        except Exception:
            log.misc.exception("Error while checking private browsing mode")
        self._chk_history.toggled.connect(self._set_crash_info)
        self._vbox.addWidget(self._chk_history)

    def _gather_crash_info(self):
        self._crash_info.append(("Fault log", self._log))
        super()._gather_crash_info()
        if self._chk_history.isChecked():
            try:
                history = objreg.get('web-history').get_recent()
                self._crash_info.append(
                    ("History", '\n'.join(str(e) for e in history)))
            except Exception:
                self._crash_info.append(("History", traceback.format_exc()))

    @pyqtSlot()
    def on_report_clicked(self):
        """Prevent empty reports."""
        if (not self._info.toPlainText().strip()
                and not self._contact.toPlainText().strip()
                and self._type == 'Segmentation fault'
                and self._func == 'qt_mainloop'):
            msgbox.msgbox(parent=self,
                          title='Empty crash info',
                          text="Empty reports for fatal crashes are useless "
                          "and mean I'll spend time deleting reports I could "
                          "spend on developing qutebrowser instead.\n\nPlease "
                          "help making qutebrowser better by providing more "
                          "information, or don't report this.",
                          icon=QMessageBox.Critical)
        else:
            super().on_report_clicked()
예제 #38
0
class ExceptionCrashDialog(_CrashDialog):
    """Dialog which gets shown on an exception.

    Attributes:
        _pages: A list of lists of the open pages (URLs as strings)
        _cmdhist: A list with the command history (as strings)
        _exc: An exception tuple (type, value, traceback)
        _qobjects: A list of all QObjects as string.
    """
    def __init__(self, debug, pages, cmdhist, exc, qobjects, parent=None):
        self._chk_log = None
        self._chk_restore = None
        super().__init__(debug, parent)
        self._pages = pages
        self._cmdhist = cmdhist
        self._exc = exc
        self._qobjects = qobjects
        self.setModal(True)
        self._set_crash_info()

    def _init_text(self):
        super()._init_text()
        text = "<b>Argh! qutebrowser crashed unexpectedly.</b>"
        self._lbl.setText(text)

    def _init_checkboxes(self):
        """Add checkboxes to the dialog."""
        super()._init_checkboxes()
        self._chk_restore = QCheckBox("Restore open pages")
        self._chk_restore.setChecked(True)
        self._vbox.addWidget(self._chk_restore)
        self._chk_log = QCheckBox("Include a debug log in the report",
                                  checked=True)
        try:
            if config.val.content.private_browsing:
                self._chk_log.setChecked(False)
        except Exception:
            log.misc.exception("Error while checking private browsing mode")
        self._chk_log.toggled.connect(self._set_crash_info)
        self._vbox.addWidget(self._chk_log)
        info_label = QLabel(
            "<i>This makes it a lot easier to diagnose the "
            "crash, but it might contain sensitive "
            "information such as which pages you visited "
            "or keyboard input.</i>",
            wordWrap=True)
        self._vbox.addWidget(info_label)

    def _get_error_type(self):
        return 'exc'

    def _get_paste_title_desc(self):
        desc = traceback.format_exception_only(self._exc[0], self._exc[1])
        return desc[0].rstrip()

    def _gather_crash_info(self):
        self._crash_info += [
            ("Exception", ''.join(traceback.format_exception(*self._exc))),
        ]
        super()._gather_crash_info()
        if self._chk_log.isChecked():
            self._crash_info += [
                ("Commandline args", ' '.join(sys.argv[1:])),
                ("Open Pages", '\n\n'.join('\n'.join(e) for e in self._pages)),
                ("Command history", '\n'.join(self._cmdhist)),
                ("Objects", self._qobjects),
            ]
            try:
                self._crash_info.append(
                    ("Debug log", log.ram_handler.dump_log()))
            except Exception:
                self._crash_info.append(("Debug log", traceback.format_exc()))

    @pyqtSlot()
    def finish(self):
        self._save_contact_info()
        if self._chk_restore.isChecked():
            self.done(Result.restore)
        else:
            self.done(Result.no_restore)
예제 #39
0
class WidgetTransGraph(QWidget, Ui_WidgetTransGraph):
    color_sequence = [
        '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
        '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
        '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
        '#17becf', '#9edae5'
    ]

    def __init__(self, parent=None):
        super(WidgetTransGraph, self).__init__(parent)
        self.setupUi(self)
        self.color_map = {}
        self.color_item_map = {}
        self.initialized = False

    def value_nuclide(nuclide, act_data: OneSpectrumActivationData):
        # cooling times: ['1', '1.0e5', '1.0e6', '1.0e7', '1.0e8', '1.0e9', '1.5e9']
        order_step = [2, 0, 1, 3, 4, 5, 6]
        for i in range(0, 7):
            if nuclide in act_data.all_steps_activation_data[i].nuclides:
                return act_data.all_steps_activation_data[i].nuclides[
                    nuclide].params['activity(Bq/kg)']
        return -1.0

    def data_to_ui(self, act_data: OneSpectrumActivationData):
        self.act_data = act_data
        self.nuclides_trans_data = {}
        self.ordered_nuclides = []
        all_nuclides_names = set()
        # get order
        for i in range(0, len(act_data.all_steps_activation_data)):
            one_step_data = act_data.all_steps_activation_data[i]
            for one_nuclide_data in one_step_data.nuclides.values():
                all_nuclides_names.add(one_nuclide_data.nuclide_name)
        for i in range(0, len(act_data.all_steps_activation_data)):
            one_step_data = act_data.all_steps_activation_data[i]
            for one_nuclide_data in one_step_data.nuclides.values():
                if one_nuclide_data.nuclide_name not in self.nuclides_trans_data:
                    self.nuclides_trans_data[
                        one_nuclide_data.nuclide_name] = []
                self.nuclides_trans_data[one_nuclide_data.nuclide_name].append(
                    one_nuclide_data.params['weight(g)'])
            for nuclide_name in all_nuclides_names:
                if nuclide_name not in one_step_data.nuclides:
                    if nuclide_name not in self.nuclides_trans_data:
                        self.nuclides_trans_data[nuclide_name] = []
                    self.nuclides_trans_data[nuclide_name].append(1e-60)
        # filter nuclides with small amount
        keys_to_delete = []
        for key, val in self.nuclides_trans_data.items():
            if val[0] < 1e-20:
                keys_to_delete.append(key)
        for key in keys_to_delete:
            self.nuclides_trans_data.pop(key)
        all_nuclides_names = self.nuclides_trans_data.keys()
        self.ordered_nuclides = sorted(
            all_nuclides_names
        )  #, key=lambda a: -WidgetTransGraph.value_nuclide(a, self.act_data))
        red = 124
        green = 56
        blue = 200
        for cur_nuclide_name in self.ordered_nuclides:
            color_str = '#{0:02x}{1:02x}{2:02x}'.format(red, green, blue)
            self.color_map[cur_nuclide_name] = color_str
            red = (red + 86) % 256
            green = (green + 43) % 256
            blue = (blue + 6) % 256
            while red > 180 and green > 180 and blue > 180:
                red = (red + 86) % 256
                green = (green + 43) % 256
                blue = (blue + 6) % 256
        self.initialize_table_nuclides()
        self.initialize_canvas()
        self.initialize_figs()

    def initialize_table_nuclides(self):
        new_item1 = QTableWidgetItem()
        new_item2 = QTableWidgetItem()
        self.tableWidget.insertRow(0)
        self.tableWidget.setItem(0, 0, new_item1)
        self.tableWidget.setItem(0, 1, new_item2)
        self.major_checkBox = QCheckBox(self)
        self.major_checkBox.setText('')
        self.tableWidget.setCellWidget(0, 0, self.major_checkBox)
        self.major_checkBox.setChecked(True)
        self.major_checkBox.clicked.connect(self.on_major_check)
        self.sub_checkBoxs = {}
        for i in range(1, len(self.ordered_nuclides) + 1):
            while self.tableWidget.rowCount() <= i:
                self.tableWidget.insertRow(self.tableWidget.rowCount())
            new_item1 = QTableWidgetItem('')
            self.tableWidget.setItem(i, 0, new_item1)
            new_item1.setFont(QFont("Times", 10, QFont.Black))
            cur_nuclide_name = self.ordered_nuclides[i - 1]
            new_item1.setForeground(
                QBrush(QColor(self.color_map[cur_nuclide_name])))
            self.sub_checkBoxs[cur_nuclide_name] = QCheckBox(self)
            #if the concerntration of this nuclide exceeds 1e-10, set checked. else uncheck
            if self.nuclides_trans_data[cur_nuclide_name][0] > 1e-10:
                self.sub_checkBoxs[cur_nuclide_name].setChecked(True)
            else:
                self.sub_checkBoxs[cur_nuclide_name].setChecked(False)
            self.sub_checkBoxs[cur_nuclide_name].clicked.connect(
                self.on_sub_check)
            self.tableWidget.setCellWidget(
                i, 0, self.sub_checkBoxs[cur_nuclide_name])
            new_item2 = QTableWidgetItem(cur_nuclide_name)
            new_item2.setForeground(
                QBrush(QColor(self.color_map[cur_nuclide_name])))
            self.tableWidget.setItem(i, 1, new_item2)

    def initialize_canvas(self):
        self.figure = Figure(figsize=(8, 6), dpi=100, tight_layout=True)
        self.figure.set_facecolor('#F5F5F5')
        self.canvas = FigureCanvas(self.figure)
        self.verticalLayoutPlot.addWidget(self.canvas)
        self.toolbar = NavigationToolbar(self.canvas, self.framePlot)
        self.verticalLayoutPlot.addWidget(self.toolbar)

    def initialize_figs(self):
        cooling_times = [1, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.5e9]
        self.figure.clf()
        self.axe = self.figure.add_subplot(111)
        self.figure.subplots_adjust(left=0.08, top=0.80, bottom=0.1)
        # self.axe.hold(True)
        self.axe.set_xscale('log')
        self.axe.set_yscale('log')
        self.axe.set_xlim([1e-1, 1e10])
        axe_y_lim_low = 1e-10
        #   self.initialized = True
        red = 124
        green = 56
        blue = 200
        # if all the checked nuclides exceeds 1e-10
        allInRange = True
        self.axe.tick_params(axis='both',
                             which='both',
                             bottom='off',
                             top='off',
                             labelbottom='on',
                             left='off',
                             right='off',
                             labelleft='on')
        for key, checkBox in self.sub_checkBoxs.items():
            if checkBox.isChecked():
                color_str = ""
                if self.nuclides_trans_data[key][0] <= 1e-10:
                    allInRange = False
                if True:  # self.nuclides_trans_data[key][0] > 1e-10: #filter out nuclides with too low concentration
                    if key in self.color_map.keys():
                        color_str = self.color_map[key]
                    else:
                        color_str = '#{0:02x}{1:02x}{2:02x}'.format(
                            red, green, blue)
                        red = (red + 86) % 256
                        green = (green + 43) % 256
                        blue = (blue + 6) % 256
                        while red > 180 and green > 180 and blue > 180:
                            red = (red + 86) % 256
                            green = (green + 43) % 256
                            blue = (blue + 6) % 256
                    self.axe.plot(cooling_times,
                                  self.nuclides_trans_data[key],
                                  color=color_str,
                                  label=key)
                    self.axe.text(1e-1,
                                  self.nuclides_trans_data[key][0],
                                  key,
                                  color=color_str)
                # print("{}:{}".format(key, color_str))
                # self.axe.plot(xs=[1, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.5e9], ys=[1e-20,2e-10,3e-5,4e-1,5,6,7])
        Font = {'family': 'Tahoma', 'weight': 'bold', 'size': 10}
        ylow, yhigh = self.axe.get_ylim()
        if allInRange:
            self.axe.set_ylim(1e-10, 10000)
        elif ylow < 1e-60:
            self.axe.set_ylim(1e-60, 10000)
        else:
            self.axe.set_ylim(ylow, 10000)
        self.axe.set_title('Transmutation graph for selected nuclides',
                           fontsize=18,
                           ha='center')
        self.axe.set_xlabel("Cooling time (s)", fontdict=Font)
        self.axe.set_ylabel("Weight Concerntration (1000wppm)", fontdict=Font)
        self.canvas.draw()

    def on_major_check(self):
        self.update()
        if self.major_checkBox.isChecked():
            for checkBox in self.sub_checkBoxs.values():
                checkBox.setChecked(True)
        else:
            for checkBox in self.sub_checkBoxs.values():
                checkBox.setChecked(False)
        self.initialize_figs()

    def on_sub_check(self):
        self.update()
        all_checked = True
        all_un_checked = True
        for key, val in self.sub_checkBoxs.items():
            if val.isChecked():
                all_un_checked = False
            else:
                all_checked = False
            if (not all_un_checked) and (not all_checked):
                break
        if all_checked:
            self.major_checkBox.setChecked(True)
        if all_un_checked:
            self.major_checkBox.setChecked(False)
        self.initialize_figs()
예제 #40
0
class CamWI(QFrame):

    active = False

    hFlip = False
    vFlip = False

    addPrimitives = False
    primitives = []

    saveFrame = False
    file_idx = None
    path = ''

    alpha = 0.4

    def __init__(self, cam, p_set, activate):
        super().__init__()

        self.paramSet = p_set

        self.active = activate

        self.ui_construct()

        self.cam = cam
        # self.camData = np.zeros((self.cam.imageHeight, self.cam.imageWidth, self.cam.imageChannel), np.ubyte)

        self.connect_events()
        self.set_wi_params()

    def connect_events(self):
        self.camSelect.currentIndexChanged.connect(self.device_select)

        self.cam.frameAcquired.connect(self.update_frame)
        self.cam.devStarted.connect(self.set_cam_controls)

        self.exposure.valueChanged.connect(self.exposure_change)
        self.gain.valueChanged.connect(self.gain_change)
        self.autoExposure.stateChanged.connect(self.auto_exp_change)
        self.flipH.stateChanged.connect(self.hflip_change)
        self.flipV.stateChanged.connect(self.vflip_change)

        self.chooseDst.clicked.connect(self.change_dst_path)
        self.saveImage.clicked.connect(self.save_image)

    def set_wi_params(self):
        cam_params = self.paramSet['cam']

        self.fill_cam_list(self.cam.capDevices, cam_params['device'])
        self.device_select(cam_params['device'])

        self.flipH.setChecked(cam_params['hFlip'])
        self.flipV.setChecked(cam_params['vFlip'])

        if cam_params['savePath'] != '':
            self.dstPath.setText(cam_params['savePath'])
        else:
            self.dstPath.setText(QDir.currentPath())

    def set_cam_controls(self):
        cam_params = self.paramSet['cam']

        self.autoExposure.setChecked(cam_params['autoExp'])
        self.exposure.setSliderPosition(cam_params['exposure'])
        self.gain.setSliderPosition(cam_params['gain'])

    def ui_construct(self):
        # Main layout
        self.camSelect = QComboBox(self)
        self.camSelect.setToolTip('Choose Camera...')

        self.camFrame = PgGraphicsView(self, aspect_locked=True)
        self.camFrame.setMinimumSize(512, 512)

        self.exposure = QSlider(Qt.Vertical)
        self.gain = QSlider(Qt.Vertical)
        self.autoExposure = QCheckBox('Auto exposition')
        exposure_lbl = QLabel('Exposition', self)
        gain_lbl = QLabel('Gain', self)

        self.flipH = QCheckBox('Flip Horizontal')
        self.flipV = QCheckBox('Flip Vertical')

        self.dstPath = QLineEdit(self)
        self.dstPath.setReadOnly(True)
        self.chooseDst = QPushButton('Choose Dir')
        self.saveImage = QPushButton('Save')
        self.chooseDst.setMinimumSize(90, 30)
        self.saveImage.setMinimumSize(90, 30)
        # dst_path_lbl = QLabel('Path:', self)

        exposure_group = QGroupBox('Exposition')
        exposure_group.setAlignment(Qt.AlignCenter)
        exposure_lay = QGridLayout(exposure_group)
        exposure_lay.addWidget(self.exposure, 0, 0, Qt.AlignCenter)
        exposure_lay.addWidget(self.gain, 0, 1, Qt.AlignCenter)
        exposure_lay.addWidget(exposure_lbl, 1, 0)
        exposure_lay.addWidget(gain_lbl, 1, 1)
        exposure_lay.addWidget(self.autoExposure, 2, 0, 1, 2)

        flip_group = QGroupBox('Flip image')
        flip_group.setAlignment(Qt.AlignCenter)
        flip_lay = QVBoxLayout(flip_group)
        flip_lay.addWidget(self.flipH)
        flip_lay.addWidget(self.flipV)

        # file_path = QFrame(self)
        # file_path_lay = QHBoxLayout(cam_file_path)
        # file_path_lay.addWidget(cam_dst_path_lbl)
        # file_path_lay.addWidget(self.camDstPath)

        file_group = QGroupBox('Save image')
        file_group.setAlignment(Qt.AlignCenter)
        file_lay = QGridLayout(file_group)
        # file_lay.addWidget(dst_path_lbl, 0, 0)
        file_lay.addWidget(self.dstPath, 1, 0, 1, 2)
        file_lay.addWidget(self.chooseDst, 2, 0)
        file_lay.addWidget(self.saveImage, 2, 1)

        cam_controls = QFrame(self)
        cam_param_lay = QVBoxLayout(cam_controls)
        cam_param_lay.addWidget(self.camSelect)
        cam_param_lay.addWidget(exposure_group)
        cam_param_lay.addWidget(flip_group)
        cam_param_lay.addWidget(file_group)

        cam_lay = QGridLayout(self)
        cam_lay.setColumnStretch(0, 1)
        cam_lay.setColumnStretch(1, 5)
        cam_lay.addWidget(cam_controls, 0, 0)
        cam_lay.addWidget(self.camFrame, 0, 1)

    def fill_cam_list(self, device_list, current_index):
        self.camSelect.blockSignals(True)

        self.camSelect.clear()

        for i, device in enumerate(device_list):
            self.camSelect.addItem(device['name'] + ' [W ' +
                                   str(device['width']) + ' : H ' +
                                   str(device['height']) + ']')
        self.camSelect.setCurrentIndex(current_index)

        self.camSelect.blockSignals(False)

    def device_select(self, idx):
        if self.active:
            success, dev_number = self.cam.connect(idx)

            if success:
                self.paramSet['cam']['device'] = dev_number
                self.camFrame.vb.setLimits(xMin=0,
                                           xMax=self.cam.imageWidth,
                                           yMin=0,
                                           yMax=self.cam.imageHeight)

                self.cam.ctrl.start_streaming()
            else:
                if idx != 0:
                    self.paramSet['cam']['device'] = 0
                    self.camSelect.setCurrentIndex(0)
                else:
                    print('Device selection error')
        else:
            try:
                self.camFrame.vb.setLimits(xMin=0,
                                           xMax=self.cam.imageWidth,
                                           yMin=0,
                                           yMax=self.cam.imageHeight)
            except:
                pass

    def update_frame(self, frame):
        if self.active:
            if self.addPrimitives:
                frame = self.draw_primitives(frame)

            if self.cam.imageChannel == 3:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

            self.camFrame.image.setImage(self.frame_transform(frame,
                                                              vInvert=True),
                                         autoLevels=False)

        if self.saveFrame:
            self.saveFrame = False
            filename = path.join(self.path,
                                 str(self.file_idx).zfill(4) + '.png')

            frame = self.frame_transform(frame, vInvert=False)
            if self.cam.imageChannel == 3:
                return cv2.imwrite(filename,
                                   cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            else:
                return cv2.imwrite(filename, frame)

    def draw_primitives(self, cv_img):
        overlay = cv_img.copy()
        return cv2.addWeighted(overlay, self.alpha, cv_img, 1 - self.alpha, 0,
                               cv_img)

    def frame_transform(self, frame, vInvert=False):
        # PgGraphicsView inverted image:
        if vInvert:
            if self.hFlip and not self.vFlip:
                frame = cv2.flip(frame, -1)
            elif self.hFlip:
                frame = cv2.flip(frame, 1)
            elif not self.vFlip:
                frame = cv2.flip(frame, 0)
        # Default:
        else:
            if self.hFlip and self.vFlip:
                frame = cv2.flip(frame, -1)
            elif self.hFlip:
                frame = cv2.flip(frame, 1)
            elif self.vFlip:
                frame = cv2.flip(frame, 0)

        return frame

    def exposure_change(self, exposure):
        if self.active:
            self.paramSet['cam']['exposure'] = exposure
            self.cam.ctrl.set_exposure(
                exposure / 100, auto_adjust=self.autoExposure.isChecked())

    def gain_change(self, gain):
        if self.active:
            self.paramSet['cam']['gain'] = gain
            self.cam.ctrl.set_gain(gain / 100)

    def auto_exp_change(self, val):
        if self.active:
            self.paramSet['cam']['autoExp'] = val
            self.cam.ctrl.set_auto_exposure(val)

            if not val:
                exposure = self.paramSet['cam']['exposure']
                gain = self.paramSet['cam']['gain']
                self.cam.ctrl.set_exposure(
                    exposure / 100, auto_adjust=self.autoExposure.isChecked())
                self.cam.ctrl.set_gain(gain / 100)

    def hflip_change(self, val):
        if val:
            self.paramSet['cam']['hFlip'] = True
            self.hFlip = True
        else:
            self.paramSet['cam']['hFlip'] = False
            self.hFlip = False

    def vflip_change(self, val):
        if val:
            self.paramSet['cam']['vFlip'] = True
            self.vFlip = True
        else:
            self.paramSet['cam']['vFlip'] = False
            self.vFlip = False

    def change_dst_path(self):
        dst = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        self.paramSet['cam']['savePath'] = dst
        self.dstPath.setText(dst)

    def save_image(self):
        if self.path == '':
            self.path = path.join(self.paramSet['cam']['savePath'],
                                  datetime.datetime.now().strftime('%d.%m.%Y'))
            if not path.exists(self.path):
                makedirs(self.path)

        if self.file_idx is None:
            file_list = listdir(self.path)
            if len(file_list) > 0:
                file_list.sort(key=lambda f: int(re.search(r'\d+', f).group()))
                self.file_idx = int(re.search(r'\d+',
                                              file_list[-1]).group()) + 1
            else:
                self.file_idx = 1
        else:
            self.file_idx += 1

        if self.cam.ctrl.streaming:
            self.saveFrame = True
        else:
            frame = self.cam.ctrl.get_frame()
            if frame:
                self.saveFrame = False

                frame = self.frame_transform(frame, vInvert=False)
                filename = path.join(self.path,
                                     str(self.file_idx).zfill(4) + '.png')

                if self.cam.imageChannel == 3:
                    return cv2.imwrite(filename,
                                       cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                else:
                    return cv2.imwrite(filename, frame)

    def stop(self):
        if self.active:
            self.cam.disconnect()

    def shut_down(self):
        self.stop()
        time.sleep(0.5)
예제 #41
0
class PyQtVariousParts(QWidget):
    def __init__(self):
        super(PyQtVariousParts, self).__init__()
        self.frameCreate()

    def frameCreate(self):

        self.setWindowTitle("部品実験")
        self.resize(500, 230)

        #各パーツ作成
        #1列目
        self.checkbox = QCheckBox("YES / NO", self)
        self.checkon_button = QPushButton("チェック操作", self)

        #2列目
        self.radio_button = QRadioButton("選択式①", self)
        self.radio_button2 = QRadioButton("選択式②", self)
        self.radio_onoffbutton = QPushButton("選択操作", self)
        #3列目
        self.combbox = QComboBox(self)
        self.dialog_button = QPushButton("ダイアログ操作", self)
        self.textarea = QLineEdit(self)
        self.sepline = QFrame()  #仕切線

        #パーツを配置
        self.checkbox.setGeometry(20, 0, 200, 75)
        self.checkon_button.setGeometry(200, 23, 75, 25)
        self.radio_button.setGeometry(20, 70, 75, 25)
        self.radio_button2.setGeometry(130, 70, 75, 25)
        self.radio_onoffbutton.setGeometry(240, 70, 75, 25)
        self.combbox.setGeometry(20, 120, 150, 25)
        self.dialog_button.setGeometry(20, 170, 100, 25)
        self.textarea.setGeometry(150, 170, 300, 25)

        #線はレイアウトに配置
        self.sepline.setFrameStyle(QFrame.HLine | QFrame.Plain)
        self.sepline.setGeometry(100, 200, 100, 100)

        #コンボボックスの中身を配置
        self.setComboBoxContent()
        self.textarea.setPlaceholderText("板村 陽花ちゃん")

        #イベントハンドラ
        self.checkbox.stateChanged.connect(self.CheckBoxOperate)
        self.checkon_button.clicked.connect(self.CheckBoxOperate2)
        self.radio_button.toggled.connect(self.radiochange)
        self.radio_onoffbutton.clicked.connect(self.radiobuttonchoice)
        self.combbox.activated.connect(self.comboact)
        self.dialog_button.clicked.connect(self.dialogopen)
        #self.dirselection_but.clicked.connect(self.dirselect)
        #self.filecreate_but.clicked.connect(self.filecreate)

        self.show()

    def CheckBoxOperate(self):

        if self.checkbox.isChecked():
            print("checkd")
        else:
            print("unchecked")

    def CheckBoxOperate2(self):

        if self.checkbox.isChecked():
            self.checkbox.setCheckState(0)
        else:
            self.checkbox.setCheckState(2)

    def radiochange(self):

        print(self.radio_button.isChecked())

    def radiobuttonchoice(self):

        if self.radio_button.isChecked():
            self.radio_button.setChecked(False)
            self.radio_button2.setChecked(True)
        elif self.radio_button2.isChecked():
            self.radio_button.setChecked(True)
            self.radio_button2.setChecked(False)
        else:

            msgBox = QMessageBox.critical(
                self, "警告", "チェックしろって",
                QMessageBox.No | QMessageBox.Yes | QMessageBox.Save,
                QMessageBox.Yes)
            if msgBox == QMessageBox.Yes:
                print("さっさと選べよ")
            elif msgBox == QMessageBox.Save:
                print("はんこうするなって")

            print("選べ")

    def setComboBoxContent(self):
        self.combbox.setInsertPolicy(QComboBox.InsertAtTop)
        import codecs
        contents = codecs.open("C:\\Users\\enoch\\Desktop\\horse.txt", "r",
                               "shift_jis")
        for content in contents:
            horse = content.replace("\r\n", "").split('\t')
            self.combbox.addItem(horse[0], horse[1])

    def comboact(self):
        print(self.combbox.itemData(self.combbox.currentIndex()))

    #ウィジェットの×ボタン押下時
    def closeEvent(self, event):

        #確認ダイアログ
        confirm = QMessageBox.question(self, "閉じちゃうぞ", "OKですか?",
                                       QMessageBox.No | QMessageBox.Yes,
                                       QMessageBox.No)
        if confirm == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def dialogopen(self):
        #現在のフォントを取得

        #フォント選択ダイアログ
        fontset = QFontDialog.getFont(QFont('MS ゴシック', 16),
                                      self,
                                      caption="選択して")
        #print(fontset[0])
        self.textarea.setFont(fontset[0])  #フォント設定
        print(fontset[1])  #OKボタン押下⇒ True
        import time
        time.sleep(1)

        colorset = QColorDialog.getColor(initial=QColor(204, 0, 0, 255),
                                         parent=self,
                                         title="選択して")
        print(colorset)
        color = QPalette()
        color.setColor(10, colorset)
        self.setPalette(color)
예제 #42
0
class ROICollection(QWidget):
    """
    This widget contains the groubox that is responsible
    for ROI property display and ROI visualization and selection
    It creates the ROIRectItem for visualization
    Setting of the PropertyWidgets is done here.
    """

    selection_finished = pyqtSignal(QRect)

    def __init__(self, group: ROIGroup, parent=None):
        super(ROICollection, self).__init__(parent)
        self.group = group
        self.name = self.group.name

        log.info("Created Collection with name: {}".format(self.name))

        self.__setup_ui()
        self.display_area = None
        self.rubberband = None
        self.selection_active = False
        # bool telling us if the ROI rect was displayed before making a selection
        self.rect_was_displayed = False

        self.selection_finished.connect(self.apply_selection)

    def __setup_ui(self):

        self.layout = QVBoxLayout()
        self.groupbox = QGroupBox(self.name)

        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Minimum)

        self.layout.addWidget(self.groupbox)

        self.__populate_groupbox()
        self.setLayout(self.layout)

    def __populate_groupbox(self):
        """

        """
        layout = QVBoxLayout()
        self.groupbox.setLayout(layout)

        first_line = QHBoxLayout()

        self.visibility_label = QLabel("Show ROI:")
        first_line.addWidget(self.visibility_label)
        self.visibility_checkbox = QCheckBox(self)
        self.visibility_checkbox.setCheckable(True)
        self.visibility_checkbox.toggled.connect(self.__checkbox_cb)
        first_line.addWidget(self.visibility_checkbox)
        self.select_button = QPushButton("+", self)
        self.select_button.setToolTip("Select ROI with the mouse")
        self.select_button.clicked.connect(self.activate_selection)
        first_line.addWidget(self.select_button)

        layout.addLayout(first_line)

        form_layout = QFormLayout()
        layout.addLayout(form_layout)

        for prop in self.group.properties:
            form_layout.addRow(prop.prop.name, prop)

    def __checkbox_cb(self):
        """
        SLOT for visibility_checkbox
        """
        self.toggle_visibility(self.visibility_checkbox.isChecked())

    def __add_roi_rect(self):
        """
        Creates a ROI Widgets and adds it to the display area
        """

        settings = ResizeableRectItemSettings(50,
                                              QColor(self.group.border_color),
                                              self.group.get_min_size(),
                                              self.group.get_max_size())

        rect = QRectF(self.group.get_position(),
                      self.group.get_size())

        self.rubberband = ROIRectItem(rect, settings, self.group)
        self.rubberband.setFlag(QGraphicsItem.ItemIsMovable)
        self.rubberband.position = self.group.get_position()
        self.rubberband.size = self.group.get_size()

        for prop in self.group.properties:
            prop.value_changed.connect(self.__update_rubberband_values)

        self.display_area.add_roi(self.rubberband)

    def __remove_rubberband(self):

        if not self.rubberband:
            return

        self.display_area.remove_roi(self.rubberband)
        self.rubberband = None

        for prop in self.group.properties:
            prop.value_changed.disconnect(self.__update_rubberband_values)

    def toggle_visibility(self,
                          be_visible: bool):
        """
        be_visible: bool saying if ROI should be visible as an overlay
        """

        if be_visible:

            if self.rubberband:
                self.__remove_rubberband()
            self.__add_roi_rect()
        else:
            self.__remove_rubberband()

    def activate_selection(self):
        """

        """
        if self.selection_active:
            return

        if self.rubberband:
            self.rect_was_displayed = True
            self.__remove_rubberband()

        self.display_area.start_roi_capture(self.selection_finished)
        self.selection_active = True

    def apply_selection(self, rect: QRect):
        self.selection_active = False

        self.group.set_position(rect.x(), rect.y())
        self.group.set_size(rect.width(), rect.height())

        if self.rect_was_displayed and self.visibility_checkbox.isChecked():
            self.__add_roi_rect()
        self.rect_was_displayed = False

    def __update_rubberband_values(self, prop: PropertyWidget):
        """
        SLOT for value_changed signal from the PropertyWidgets
        """

        if not self.rubberband:
            return

        if self.rubberband.mouse_pressed:
            return

        if ("Top" in prop.prop.name or
                "Left" in prop.prop.name):

            self.rubberband.position = self.group.get_position()
            if "Left" in prop.prop.name:

                self.rubberband.position.x = prop.prop.value

            elif "Top" in prop.prop.name:

                self.rubberband.position.y = prop.prop.value

            # log.info("scenePos{}".format(self.rubberband.scenePos()))
            # log.info("pos {}".format(self.group.get_position()))
            self.rubberband.update_pos()

        elif ("Width" in prop.prop.name or
                "Height" in prop.prop.name):

            if "Width" in prop.prop.name:
                if int(self.rubberband.size.width()) == prop.prop.value:
                    return

            if "Height" in prop.prop.name:
                if int(self.rubberband.size.height()) == prop.prop.value:
                    return

            self.rubberband.size = self.group.get_size()
            # log.info("size {}".format(self.group.get_size()))
            self.rubberband.update_rect()

        self.display_area.update()
예제 #43
0
class Ui_Dialog(object):
    q = queue.Queue(0)
    i = 0

    def setupUi(self, Dialog):
        self.isPause = False
        Dialog.setObjectName("Dialog")
        Dialog.resize(800, 600)
        mainwindow = QtWidgets.QWidget()
        Dialog.setCentralWidget(mainwindow)
        self.horizontalLayout = QtWidgets.QHBoxLayout(mainwindow)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.Groupbox = QtWidgets.QGroupBox(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.Groupbox.sizePolicy().hasHeightForWidth())
        self.Groupbox.setSizePolicy(sizePolicy)
        self.Groupbox.setObjectName("Groupbox")
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.Groupbox)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.pushButton_loadA = QtWidgets.QPushButton(self.Groupbox)
        self.pushButton_loadA.setObjectName("pushButton_loadA")
        self.verticalLayout_4.addWidget(self.pushButton_loadA)
        self.pushButton_loadB = QtWidgets.QPushButton(self.Groupbox)
        self.pushButton_loadB.setObjectName("pushButton_loadB")
        self.verticalLayout_4.addWidget(self.pushButton_loadB)
        self.pushButton_connect = QtWidgets.QPushButton(self.Groupbox)
        self.pushButton_connect.setObjectName("pushButton_connect")
        self.verticalLayout_4.addWidget(self.pushButton_connect)
        self.pushButton_start = QtWidgets.QPushButton(self.Groupbox)
        self.pushButton_start.setObjectName("pushButton_start")
        self.verticalLayout_4.addWidget(self.pushButton_start)
        self.pushButton_pause = QtWidgets.QPushButton(self.Groupbox)
        self.pushButton_pause.setObjectName("pushButton_pause")
        self.verticalLayout_4.addWidget(self.pushButton_pause)
        self.pushButton_exit = QtWidgets.QPushButton(self.Groupbox)
        self.pushButton_exit.setObjectName("pushButton_exit")
        self.verticalLayout_4.addWidget(self.pushButton_exit)
        self.verticalLayout_3.addWidget(self.Groupbox)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.groupBox = QtWidgets.QGroupBox(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(7)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.groupBox.sizePolicy().hasHeightForWidth())
        self.groupBox.setSizePolicy(sizePolicy)
        self.groupBox.setObjectName("groupBox")
        self.gridLayout = QtWidgets.QGridLayout(self.groupBox)
        self.gridLayout.setObjectName("gridLayout")
        self.lineEdit_ipaddress = QtWidgets.QLineEdit(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(5)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.lineEdit_ipaddress.sizePolicy().hasHeightForWidth())

        ###################grid view start
        self.lineEdit_ipaddress.setSizePolicy(sizePolicy)
        self.lineEdit_ipaddress.setObjectName("lineEdit_ipaddress")
        self.lineEdit_ipaddress.setText("192.168.0.1")
        self.gridLayout.addWidget(self.lineEdit_ipaddress, 0, 1, 1, 1)
        self.label_4 = QtWidgets.QLabel(self.groupBox)
        self.label_4.setObjectName("label_4")
        self.gridLayout.addWidget(self.label_4, 1, 0, 1, 1)
        self.lineEdit_Aheight = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_Aheight.setObjectName("lineEdit_Aheight")
        self.lineEdit_Aheight.setText('0')
        self.gridLayout.addWidget(self.lineEdit_Aheight, 1, 1, 1, 1)
        self.label = QtWidgets.QLabel(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_3.sizePolicy().hasHeightForWidth())
        self.label_3.setSizePolicy(sizePolicy)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 0, 2, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(5)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setText('2000')
        self.gridLayout.addWidget(self.lineEdit, 0, 3, 1, 1)
        self.label_5 = QtWidgets.QLabel(self.groupBox)
        self.label_5.setObjectName("label_5")
        self.gridLayout.addWidget(self.label_5, 1, 2, 1, 1)
        self.lineEdit_Bheight = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_Bheight.setObjectName("lineEdit_Bheight")
        self.lineEdit_Bheight.setText('0')
        self.gridLayout.addWidget(self.lineEdit_Bheight, 1, 3, 1, 1)
        self.label_cb = QtWidgets.QLabel(self.groupBox)
        self.label_cb.setText('加载模式')
        self.gridLayout.addWidget(self.label_cb)
        self.combobox = QComboBox(self.groupBox)
        self.combobox.addItems(['坐标模式', '托盘模式'])
        self.gridLayout.addWidget(self.combobox)

        self.checkbox_gotoc = QCheckBox('蘸胶工序', self.groupBox)
        self.gridLayout.addWidget(self.checkbox_gotoc)

        self.lineEdit_cpos = QLineEdit(self.groupBox)
        self.gridLayout.addWidget(self.lineEdit_cpos)

        self.label_offset = QtWidgets.QLabel(self.groupBox)
        self.label_offset.setText('偏移量')
        self.gridLayout.addWidget(self.label_offset)
        self.lineEdit_offset = QLineEdit(self.groupBox)
        self.gridLayout.addWidget(self.lineEdit_offset)

        self.label_index = QtWidgets.QLabel(self.groupBox)
        self.label_index.setText('当前序号')
        self.gridLayout.addWidget(self.label_index)
        self.lineEdit_index = QLineEdit(self.groupBox)
        self.lineEdit_index.setValidator(QtGui.QIntValidator())
        self.lineEdit_index.setText('1')
        self.gridLayout.addWidget(self.lineEdit_index)
        # ##################grid view end

        self.verticalLayout.addWidget(self.groupBox)
        self.label_2 = QtWidgets.QLabel(Dialog)
        self.label_2.setObjectName("label_2")
        self.verticalLayout.addWidget(self.label_2)
        self.label_status = QtWidgets.QLabel(Dialog)
        self.label_status.setObjectName("label_status")
        self.verticalLayout.addWidget(self.label_status)

        # draw the table
        self.tableView = QtWidgets.QTableWidget(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.tableView.sizePolicy().hasHeightForWidth())
        self.tableView.setSizePolicy(sizePolicy)
        self.tableView.setObjectName("tableView")
        self.verticalLayout.addWidget(self.tableView)
        self.horizontalLayout.addLayout(self.verticalLayout)
        self.init_table(self.combobox.currentIndex())

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

        self.pushButton_exit.clicked.connect(QCoreApplication.quit)
        self.pushButton_loadA.clicked.connect(self.loadFileA)
        self.pushButton_loadB.clicked.connect(self.loadFileB)
        self.pushButton_connect.clicked.connect(self.connect2controller)
        self.pushButton_start.clicked.connect(self.begin)
        self.pushButton_pause.clicked.connect(self.pause)
        self.combobox.currentIndexChanged.connect(self.init_table)
        self.checkbox_gotoc.stateChanged.connect(self.changecb1)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.Groupbox.setTitle(_translate("Dialog", "Control panel"))
        self.pushButton_loadA.setText(_translate("Dialog", "载入元件位置"))
        self.pushButton_loadB.setText(_translate("Dialog", "载入贴装位置"))
        self.pushButton_connect.setText(_translate("Dialog", "连接"))
        self.pushButton_start.setText(_translate("Dialog", "开始"))
        self.pushButton_pause.setText(_translate("Dialog", "暂停"))
        self.pushButton_exit.setText(_translate("Dialog", "退出"))
        self.groupBox.setTitle(_translate("Dialog", "GroupBox"))
        self.label_4.setText(_translate("Dialog", "元件高度"))
        self.label.setText(_translate("Dialog", "IP地址"))
        self.label_3.setText(_translate("Dialog", "端口"))
        self.label_5.setText(_translate("Dialog", "贴装高度"))
        self.label_2.setText(_translate("Dialog", "当前位置信息"))
        self.label_status.setText(_translate("Dialog", "TextLabel"))
        self.checkbox_gotoc.setChecked(True)

    def changecb1(self):
        self.lineEdit_cpos.setEnabled(self.checkbox_gotoc.isChecked())

    def loadFileA(self):
        file_name, _ = QFileDialog.getOpenFileName(self, '打开文件', "./",
                                                   "Excel files(*.xls)")
        self.label_status.setText(file_name)
        if file_name != '':
            positiona = excel_read.read_excel(file_name)
            self.counta = positiona.shape[0]
            self.tableView.setRowCount(self.counta)
            for i in range(self.counta):
                self.tableView.setItem(i, 0,
                                       QTableWidgetItem(str(positiona[i, 0])))
                self.tableView.setItem(i, 1,
                                       QTableWidgetItem(str(positiona[i, 1])))
                self.tableView.setItem(i, 2,
                                       QTableWidgetItem(str(positiona[i, 2])))
                self.tableView.setItem(i, 3,
                                       QTableWidgetItem(str(positiona[i, 3])))
            if self.combobox.currentIndex() == 1:
                self.tableView.insertRow(self.counta)
                self.counta = int(positiona[-1, 0]) * int(positiona[-1, 1])
                self.tableView.setItem(
                    self.tableView.rowCount() - 1, 0,
                    QTableWidgetItem('Total number {}'.format(self.counta)))
                self.tableView.setItem(
                    self.tableView.rowCount() - 1, 1,
                    QTableWidgetItem('Current done number {}'.format(
                        int(self.i))))

    def loadFileB(self):
        file_name, _ = QFileDialog.getOpenFileName(self, '打开文件', "./",
                                                   "Excel files(*.xls)")
        self.label_status.setText(file_name)
        if file_name != '':
            positionb = excel_read.read_excel(file_name)
            self.countb = positionb.shape[0]
            if self.tableView.rowCount() < self.countb:
                self.tableView.setRowCount(self.countb)
            for i in range(self.countb):
                self.tableView.setItem(i, 4,
                                       QTableWidgetItem(str(positionb[i, 0])))
                self.tableView.setItem(i, 5,
                                       QTableWidgetItem(str(positionb[i, 1])))
                self.tableView.setItem(i, 6,
                                       QTableWidgetItem(str(positionb[i, 2])))
                self.tableView.setItem(i, 7,
                                       QTableWidgetItem(str(positionb[i, 3])))
            if self.combobox.currentIndex() == 1:
                self.countb = int(positionb[-1, 0]) * int(positionb[-1, 1])
                self.tableView.setItem(
                    self.tableView.rowCount() - 1, 2,
                    QTableWidgetItem('Total number {}'.format(self.countb)))
                self.tableView.setItem(
                    self.tableView.rowCount() - 1, 3,
                    QTableWidgetItem('Current done number {}'.format(
                        int(self.i))))

    def connect2controller(self):
        ip = self.lineEdit_ipaddress.text()
        port = self.lineEdit.text()
        self.client = cmd_send.client_thread(self.q, ip, port)
        if self.client.inisock() == 0:
            self.showdialog("连接成功")

    def pause(self):
        if self.isPause == True:
            self.isPause = False
            self.pushButton_pause.setText('暂停')
            if hasattr(self, 'i'):
                self.i = int(self.lineEdit_index.text()) - 2
                self.msgrecv('Put OK\r\n')
        else:
            self.isPause = True
            self.pushButton_pause.setText('恢复')

    # 子线程消息接收处理
    def msgrecv(self, s):
        self.label_status.setText(s)
        if 'Put OK' in s:
            # 放好一个,接着放下一个
            if self.combobox.currentIndex() == 0:
                self.tableView.setItem(self.i, 8, QTableWidgetItem('OK'))
            else:
                self.tableView.setItem(
                    self.tableView.rowCount() - 1, 1,
                    QTableWidgetItem('Current done number {}'.format(
                        int(self.i))))
            if (not self.isPause):
                if ((self.i + 1) < min(self.counta, self.countb)):
                    self.i += 1
                    self.lineEdit_index.setText(str(self.i + 1))
                    if self.combobox.currentIndex() == 0:
                        self.send_pos()
                    else:
                        self.send_plt()
                else:
                    self.msgsend('HOME')
                    self.label_status.setText('All Done')
                    self.msgsend('QUIT')

    def msgsend(self, s):
        if self.q.empty():
            self.q.put(s)
        time.sleep(0.2)

    def init_robot(self, us_cposition, mode):
        # us_cposition:bool, 是否使用蘸胶工序
        # mode: int, 0为位置模式,1为托盘模式
        if us_cposition and self.lineEdit_cpos.text() != None:
            a = 'CPOS ' + self.lineEdit_cpos.text()
            self.msgsend(a)
        if mode == 1:
            a = 'Pallet1 {} {} {} {} {} {} {} {} {} {}'.format(
                self.tableView.item(0, 0).text(),
                self.tableView.item(0, 1).text(),
                self.tableView.item(1, 0).text(),
                self.tableView.item(1, 1).text(),
                self.tableView.item(2, 0).text(),
                self.tableView.item(2, 1).text(),
                self.tableView.item(3, 0).text(),
                self.tableView.item(3, 1).text(),
                self.tableView.item(4, 0).text(),
                self.tableView.item(4, 1).text())
            self.msgsend(a)
            a = 'Pallet2 {} {} {} {} {} {} {} {} {} {}'.format(
                self.tableView.item(0, 2).text(),
                self.tableView.item(0, 3).text(),
                self.tableView.item(1, 2).text(),
                self.tableView.item(1, 3).text(),
                self.tableView.item(2, 2).text(),
                self.tableView.item(2, 3).text(),
                self.tableView.item(3, 2).text(),
                self.tableView.item(3, 3).text(),
                self.tableView.item(4, 2).text(),
                self.tableView.item(4, 3).text())
            self.msgsend(a)
        return

    def send_pos(self):
        a = self.posmsg_init(self.i)
        self.msgsend(a)
        return

    def send_plt(self):
        a = self.pltmsg_init(self.i + 1)
        self.msgsend(a)

    def begin(self):  #开始往队列里加消息,子线程收到消息就传到下位机
        if hasattr(self, 'client'):
            self.client.start()
            self.client.recv_msg.connect(self.msgrecv)
            self.init_robot(self.checkbox_gotoc.isChecked(),
                            mode=self.combobox.currentIndex())

            self.i = int(self.lineEdit_index.text()) - 1
            if self.combobox.currentIndex() == 0:
                self.send_pos()
            else:
                self.send_plt()
        else:
            self.showdialog("Connect to device first")

    def posmsg_init(self, i):
        ax, ay, bx, by = [0, 0, 0, 0]
        res = self.lineEdit_offset.text().split()
        if len(res) == 4:
            ax, ay, bx, by = res

        a = 'POS {} {} {} {} {} {} {} {}'.format(
            float(self.tableView.item(i, 0).text()) + float(ax),
            float(self.tableView.item(i, 1).text()) + float(ay),
            self.tableView.item(i, 2).text(),
            self.tableView.item(i, 3).text(),
            float(self.tableView.item(i, 4).text()) + float(bx),
            float(self.tableView.item(i, 5).text()) + float(by),
            self.tableView.item(i, 6).text(),
            self.tableView.item(i, 7).text())
        return a

    def pltmsg_init(self, i):
        a = 'PLT {} {} {}'.format(i, self.lineEdit_Aheight.text(),
                                  self.lineEdit_Bheight.text())
        return a

    def init_table(self, flag):
        self.tableView.clear()
        self.tableView.setRowCount(0)
        if flag == 0:
            self.tableView.setColumnCount(9)
            # self.tableView.setColumnWidth(0,120)
            # self.tableView.setColumnWidth(1,120)
            # self.tableView.setColumnWidth(2,120)
            # self.tableView.setColumnWidth(3,120)
            self.tableView.setHorizontalHeaderLabels([
                'A坐标X', 'A坐标Y', 'A坐标Z', 'A角度A', 'B坐标X', 'B坐标Y', 'B坐标Z', 'B角度A',
                '状态'
            ])
        else:
            self.tableView.setColumnCount(8)
            # self.tableView.setColumnWidth(0, 150)
            # self.tableView.setColumnWidth(1, 150)
            # self.tableView.setColumnWidth(2, 150)
            # self.tableView.setColumnWidth(3, 150)
            self.tableView.setHorizontalHeaderLabels([
                'A坐标X', 'A坐标Y', 'A坐标Z', 'A角度A', 'B坐标X', 'B坐标Y', 'B坐标Z', 'B角度A'
            ])

    def showdialog(self, t):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)

        msg.setText(t)
        msg.setWindowTitle("MessageBox")
        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msg.exec_()
예제 #44
0
class SettingsDialog(QDialog):
    worker = None
    config = None
    configfile = None

    saved = QtCore.pyqtSignal()

    def __init__(self, parent, worker, config, configfile):
        QDialog.__init__(self, parent)

        self.worker = worker
        self.config = config
        self.configfile = configfile
        self.setStyleSheet("QGroupBox { font-weight: bold; } ")
        self.setWindowTitle('Settings')
        layout = QGridLayout()

        # Categories
        self.category_list = QListWidget()
        category_media = QListWidgetItem(getIcon('media-playback-start'),
                                         'Media', self.category_list)
        category_sync = QListWidgetItem(getIcon('view-refresh'), 'Sync',
                                        self.category_list)
        category_ui = QListWidgetItem(getIcon('window-new'), 'User Interface',
                                      self.category_list)
        category_theme = QListWidgetItem(getIcon('applications-graphics'),
                                         'Theme', self.category_list)
        self.category_list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.category_list.setCurrentRow(0)
        self.category_list.setMaximumWidth(
            self.category_list.sizeHintForColumn(0) + 15)
        self.category_list.setFocus()
        self.category_list.currentItemChanged.connect(self.s_switch_page)

        # Media tab
        page_media = QWidget()
        page_media_layout = QVBoxLayout()
        page_media_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Media settings
        g_media = QGroupBox('Media settings')
        g_media.setFlat(True)
        g_media_layout = QFormLayout()
        self.tracker_enabled = QCheckBox()
        self.tracker_enabled.toggled.connect(self.tracker_type_change)

        self.tracker_type = QComboBox()
        for (n, label) in utils.available_trackers:
            self.tracker_type.addItem(label, n)
        self.tracker_type.currentIndexChanged.connect(self.tracker_type_change)

        self.tracker_interval = QSpinBox()
        self.tracker_interval.setRange(5, 1000)
        self.tracker_interval.setMaximumWidth(60)
        self.tracker_process = QLineEdit()
        self.tracker_update_wait = QSpinBox()
        self.tracker_update_wait.setRange(0, 1000)
        self.tracker_update_wait.setMaximumWidth(60)
        self.tracker_update_close = QCheckBox()
        self.tracker_update_prompt = QCheckBox()
        self.tracker_not_found_prompt = QCheckBox()

        g_media_layout.addRow('Enable tracker', self.tracker_enabled)
        g_media_layout.addRow('Tracker type', self.tracker_type)
        g_media_layout.addRow('Tracker interval (seconds)',
                              self.tracker_interval)
        g_media_layout.addRow('Process name (regex)', self.tracker_process)
        g_media_layout.addRow('Wait before updating (seconds)',
                              self.tracker_update_wait)
        g_media_layout.addRow('Wait until the player is closed',
                              self.tracker_update_close)
        g_media_layout.addRow('Ask before updating',
                              self.tracker_update_prompt)
        g_media_layout.addRow('Ask to add new shows',
                              self.tracker_not_found_prompt)

        g_media.setLayout(g_media_layout)

        # Group: Plex settings
        g_plex = QGroupBox('Plex Media Server')
        g_plex.setFlat(True)
        self.plex_host = QLineEdit()
        self.plex_port = QLineEdit()
        self.plex_user = QLineEdit()
        self.plex_passw = QLineEdit()
        self.plex_passw.setEchoMode(QLineEdit.Password)
        self.plex_obey_wait = QCheckBox()

        g_plex_layout = QGridLayout()
        g_plex_layout.addWidget(QLabel('Host and Port'), 0, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_host, 0, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_port, 0, 2, 1, 2)
        g_plex_layout.addWidget(QLabel('Use "wait before updating" time'), 1,
                                0, 1, 1)
        g_plex_layout.addWidget(self.plex_obey_wait, 1, 2, 1, 1)
        g_plex_layout.addWidget(QLabel('myPlex login (claimed server)'), 2, 0,
                                1, 1)
        g_plex_layout.addWidget(self.plex_user, 2, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_passw, 2, 2, 1, 2)

        g_plex.setLayout(g_plex_layout)

        # Group: Library
        g_playnext = QGroupBox('Library')
        g_playnext.setFlat(True)
        self.player = QLineEdit()
        self.player_browse = QPushButton('Browse...')
        self.player_browse.clicked.connect(self.s_player_browse)
        lbl_searchdirs = QLabel('Media directories')
        lbl_searchdirs.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs = QListWidget()
        self.searchdirs_add = QPushButton('Add...')
        self.searchdirs_add.clicked.connect(self.s_searchdirs_add)
        self.searchdirs_remove = QPushButton('Remove')
        self.searchdirs_remove.clicked.connect(self.s_searchdirs_remove)
        self.searchdirs_buttons = QVBoxLayout()
        self.searchdirs_buttons.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs_buttons.addWidget(self.searchdirs_add)
        self.searchdirs_buttons.addWidget(self.searchdirs_remove)
        self.searchdirs_buttons.addWidget(QSplitter())
        self.library_autoscan = QCheckBox()
        self.scan_whole_list = QCheckBox()
        self.library_full_path = QCheckBox()

        g_playnext_layout = QGridLayout()
        g_playnext_layout.addWidget(QLabel('Player'), 0, 0, 1, 1)
        g_playnext_layout.addWidget(self.player, 0, 1, 1, 1)
        g_playnext_layout.addWidget(self.player_browse, 0, 2, 1, 1)
        g_playnext_layout.addWidget(lbl_searchdirs, 1, 0, 1, 1)
        g_playnext_layout.addWidget(self.searchdirs, 1, 1, 1, 1)
        g_playnext_layout.addLayout(self.searchdirs_buttons, 1, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Rescan Library at startup'), 2, 0,
                                    1, 2)
        g_playnext_layout.addWidget(self.library_autoscan, 2, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Scan through whole list'), 3, 0, 1,
                                    2)
        g_playnext_layout.addWidget(self.scan_whole_list, 3, 2, 1, 1)
        g_playnext_layout.addWidget(
            QLabel('Take subdirectory name into account'), 4, 0, 1, 2)
        g_playnext_layout.addWidget(self.library_full_path, 4, 2, 1, 1)

        g_playnext.setLayout(g_playnext_layout)

        # Media form
        page_media_layout.addWidget(g_media)
        page_media_layout.addWidget(g_plex)
        page_media_layout.addWidget(g_playnext)
        page_media.setLayout(page_media_layout)

        # Sync tab
        page_sync = QWidget()
        page_sync_layout = QVBoxLayout()
        page_sync_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Autoretrieve
        g_autoretrieve = QGroupBox('Autoretrieve')
        g_autoretrieve.setFlat(True)
        self.autoretrieve_off = QRadioButton('Disabled')
        self.autoretrieve_always = QRadioButton('Always at start')
        self.autoretrieve_days = QRadioButton('After n days')
        self.autoretrieve_days.toggled.connect(self.s_autoretrieve_days)
        self.autoretrieve_days_n = QSpinBox()
        self.autoretrieve_days_n.setRange(1, 100)
        g_autoretrieve_layout = QGridLayout()
        g_autoretrieve_layout.setColumnStretch(0, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_off, 0, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_always, 1, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days, 2, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days_n, 2, 1, 1, 1)
        g_autoretrieve.setLayout(g_autoretrieve_layout)

        # Group: Autosend
        g_autosend = QGroupBox('Autosend')
        g_autosend.setFlat(True)
        self.autosend_off = QRadioButton('Disabled')
        self.autosend_always = QRadioButton('Immediately after every change')
        self.autosend_minutes = QRadioButton('After n minutes')
        self.autosend_minutes.toggled.connect(self.s_autosend_minutes)
        self.autosend_minutes_n = QSpinBox()
        self.autosend_minutes_n.setRange(1, 1000)
        self.autosend_size = QRadioButton('After the queue reaches n items')
        self.autosend_size.toggled.connect(self.s_autosend_size)
        self.autosend_size_n = QSpinBox()
        self.autosend_size_n.setRange(2, 20)
        self.autosend_at_exit = QCheckBox('At exit')
        g_autosend_layout = QGridLayout()
        g_autosend_layout.setColumnStretch(0, 1)
        g_autosend_layout.addWidget(self.autosend_off, 0, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_always, 1, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes, 2, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes_n, 2, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size, 3, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size_n, 3, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_at_exit, 4, 0, 1, 1)
        g_autosend.setLayout(g_autosend_layout)

        # Group: Extra
        g_extra = QGroupBox('Additional options')
        g_extra.setFlat(True)
        self.auto_status_change = QCheckBox('Change status automatically')
        self.auto_status_change.toggled.connect(self.s_auto_status_change)
        self.auto_status_change_if_scored = QCheckBox(
            'Change status automatically only if scored')
        self.auto_date_change = QCheckBox(
            'Change start and finish dates automatically')
        g_extra_layout = QVBoxLayout()
        g_extra_layout.addWidget(self.auto_status_change)
        g_extra_layout.addWidget(self.auto_status_change_if_scored)
        g_extra_layout.addWidget(self.auto_date_change)
        g_extra.setLayout(g_extra_layout)

        # Sync layout
        page_sync_layout.addWidget(g_autoretrieve)
        page_sync_layout.addWidget(g_autosend)
        page_sync_layout.addWidget(g_extra)
        page_sync.setLayout(page_sync_layout)

        # UI tab
        page_ui = QWidget()
        page_ui_layout = QFormLayout()
        page_ui_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Icon
        g_icon = QGroupBox('Notification Icon')
        g_icon.setFlat(True)
        self.tray_icon = QCheckBox('Show tray icon')
        self.tray_icon.toggled.connect(self.s_tray_icon)
        self.close_to_tray = QCheckBox('Close to tray')
        self.start_in_tray = QCheckBox('Start minimized to tray')
        self.tray_api_icon = QCheckBox('Use API icon as tray icon')
        self.notifications = QCheckBox(
            'Show notification when tracker detects new media')
        g_icon_layout = QVBoxLayout()
        g_icon_layout.addWidget(self.tray_icon)
        g_icon_layout.addWidget(self.close_to_tray)
        g_icon_layout.addWidget(self.start_in_tray)
        g_icon_layout.addWidget(self.tray_api_icon)
        g_icon_layout.addWidget(self.notifications)
        g_icon.setLayout(g_icon_layout)

        # Group: Window
        g_window = QGroupBox('Window')
        g_window.setFlat(True)
        self.remember_geometry = QCheckBox('Remember window size and position')
        self.remember_columns = QCheckBox('Remember column layouts and widths')
        self.columns_per_api = QCheckBox(
            'Use different visible columns per API')
        g_window_layout = QVBoxLayout()
        g_window_layout.addWidget(self.remember_geometry)
        g_window_layout.addWidget(self.remember_columns)
        g_window_layout.addWidget(self.columns_per_api)
        g_window.setLayout(g_window_layout)

        # Group: Lists
        g_lists = QGroupBox('Lists')
        g_lists.setFlat(True)
        self.filter_bar_position = QComboBox()
        filter_bar_positions = [(FilterBar.PositionHidden, 'Hidden'),
                                (FilterBar.PositionAboveLists, 'Above lists'),
                                (FilterBar.PositionBelowLists, 'Below lists')]
        for (n, label) in filter_bar_positions:
            self.filter_bar_position.addItem(label, n)
        self.inline_edit = QCheckBox('Enable in-line editing')
        g_lists_layout = QFormLayout()
        g_lists_layout.addRow('Filter bar position:', self.filter_bar_position)
        g_lists_layout.addRow(self.inline_edit)
        g_lists.setLayout(g_lists_layout)

        # UI layout
        page_ui_layout.addWidget(g_icon)
        page_ui_layout.addWidget(g_window)
        page_ui_layout.addWidget(g_lists)
        page_ui.setLayout(page_ui_layout)

        # Theming tab
        page_theme = QWidget()
        page_theme_layout = QFormLayout()
        page_theme_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Episode Bar
        g_ep_bar = QGroupBox('Episode Bar')
        g_ep_bar.setFlat(True)
        self.ep_bar_style = QComboBox()
        ep_bar_styles = [(ShowsTableDelegate.BarStyleBasic, 'Basic'),
                         (ShowsTableDelegate.BarStyle04, 'Trackma'),
                         (ShowsTableDelegate.BarStyleHybrid, 'Hybrid')]
        for (n, label) in ep_bar_styles:
            self.ep_bar_style.addItem(label, n)
        self.ep_bar_style.currentIndexChanged.connect(self.s_ep_bar_style)
        self.ep_bar_text = QCheckBox('Show text label')
        g_ep_bar_layout = QFormLayout()
        g_ep_bar_layout.addRow('Style:', self.ep_bar_style)
        g_ep_bar_layout.addRow(self.ep_bar_text)
        g_ep_bar.setLayout(g_ep_bar_layout)

        # Group: Colour scheme
        g_scheme = QGroupBox('Color Scheme')
        g_scheme.setFlat(True)
        col_tabs = [('rows', '&Row highlights'),
                    ('progress', '&Progress widget')]
        self.colors = {}
        self.colors['rows'] = [('is_playing', 'Playing'),
                               ('is_queued', 'Queued'),
                               ('new_episode', 'New Episode'),
                               ('is_airing', 'Airing'),
                               ('not_aired', 'Unaired')]
        self.colors['progress'] = [('progress_bg', 'Background'),
                                   ('progress_fg', 'Watched bar'),
                                   ('progress_sub_bg', 'Aired episodes'),
                                   ('progress_sub_fg', 'Stored episodes'),
                                   ('progress_complete', 'Complete')]
        self.color_buttons = []
        self.syscolor_buttons = []
        g_scheme_layout = QGridLayout()
        tw_scheme = QTabWidget()
        for (key, tab_title) in col_tabs:
            page = QFrame()
            page_layout = QGridLayout()
            col = 0
            # Generate widgets from the keys and values
            for (key, label) in self.colors[key]:
                self.color_buttons.append(QPushButton())
                # self.color_buttons[-1].setStyleSheet('background-color: ' + getColor(self.config['colors'][key]).name())
                self.color_buttons[-1].setFocusPolicy(QtCore.Qt.NoFocus)
                self.color_buttons[-1].clicked.connect(
                    self.s_color_picker(key, False))
                self.syscolor_buttons.append(QPushButton('System Colors'))
                self.syscolor_buttons[-1].clicked.connect(
                    self.s_color_picker(key, True))
                page_layout.addWidget(QLabel(label), col, 0, 1, 1)
                page_layout.addWidget(self.color_buttons[-1], col, 1, 1, 1)
                page_layout.addWidget(self.syscolor_buttons[-1], col, 2, 1, 1)
                col += 1
            page.setLayout(page_layout)
            tw_scheme.addTab(page, tab_title)
        g_scheme_layout.addWidget(tw_scheme)
        g_scheme.setLayout(g_scheme_layout)

        # UI layout
        page_theme_layout.addWidget(g_ep_bar)
        page_theme_layout.addWidget(g_scheme)
        page_theme.setLayout(page_theme_layout)

        # Content
        self.contents = QStackedWidget()
        self.contents.addWidget(page_media)
        self.contents.addWidget(page_sync)
        self.contents.addWidget(page_ui)
        self.contents.addWidget(page_theme)
        if pyqt_version is not 5:
            self.contents.layout().setMargin(0)

        # Bottom buttons
        bottombox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Apply
                                     | QDialogButtonBox.Cancel)
        bottombox.accepted.connect(self.s_save)
        bottombox.button(QDialogButtonBox.Apply).clicked.connect(self._save)
        bottombox.rejected.connect(self.reject)

        # Main layout finish
        layout.addWidget(self.category_list, 0, 0, 1, 1)
        layout.addWidget(self.contents, 0, 1, 1, 1)
        layout.addWidget(bottombox, 1, 0, 1, 2)
        layout.setColumnStretch(1, 1)

        self._load()
        self.update_colors()

        self.setLayout(layout)

    def _add_dir(self, path):
        self.searchdirs.addItem(path)

    def _load(self):
        engine = self.worker.engine
        tracker_type = self.tracker_type.findData(
            engine.get_config('tracker_type'))
        autoretrieve = engine.get_config('autoretrieve')
        autosend = engine.get_config('autosend')

        self.tracker_enabled.setChecked(engine.get_config('tracker_enabled'))
        self.tracker_type.setCurrentIndex(max(0, tracker_type))
        self.tracker_interval.setValue(engine.get_config('tracker_interval'))
        self.tracker_process.setText(engine.get_config('tracker_process'))
        self.tracker_update_wait.setValue(
            engine.get_config('tracker_update_wait_s'))
        self.tracker_update_close.setChecked(
            engine.get_config('tracker_update_close'))
        self.tracker_update_prompt.setChecked(
            engine.get_config('tracker_update_prompt'))
        self.tracker_not_found_prompt.setChecked(
            engine.get_config('tracker_not_found_prompt'))

        self.player.setText(engine.get_config('player'))
        self.library_autoscan.setChecked(engine.get_config('library_autoscan'))
        self.scan_whole_list.setChecked(engine.get_config('scan_whole_list'))
        self.library_full_path.setChecked(
            engine.get_config('library_full_path'))
        self.plex_host.setText(engine.get_config('plex_host'))
        self.plex_port.setText(engine.get_config('plex_port'))
        self.plex_obey_wait.setChecked(
            engine.get_config('plex_obey_update_wait_s'))
        self.plex_user.setText(engine.get_config('plex_user'))
        self.plex_passw.setText(engine.get_config('plex_passwd'))

        for path in engine.get_config('searchdir'):
            self._add_dir(path)

        if autoretrieve == 'always':
            self.autoretrieve_always.setChecked(True)
        elif autoretrieve == 'days':
            self.autoretrieve_days.setChecked(True)
        else:
            self.autoretrieve_off.setChecked(True)

        self.autoretrieve_days_n.setValue(
            engine.get_config('autoretrieve_days'))

        if autosend == 'always':
            self.autosend_always.setChecked(True)
        elif autosend in ('minutes', 'hours'):
            self.autosend_minutes.setChecked(True)
        elif autosend == 'size':
            self.autosend_size.setChecked(True)
        else:
            self.autosend_off.setChecked(True)

        self.autosend_minutes_n.setValue(engine.get_config('autosend_minutes'))
        self.autosend_size_n.setValue(engine.get_config('autosend_size'))

        self.autosend_at_exit.setChecked(engine.get_config('autosend_at_exit'))
        self.auto_status_change.setChecked(
            engine.get_config('auto_status_change'))
        self.auto_status_change_if_scored.setChecked(
            engine.get_config('auto_status_change_if_scored'))
        self.auto_date_change.setChecked(engine.get_config('auto_date_change'))

        self.tray_icon.setChecked(self.config['show_tray'])
        self.close_to_tray.setChecked(self.config['close_to_tray'])
        self.start_in_tray.setChecked(self.config['start_in_tray'])
        self.tray_api_icon.setChecked(self.config['tray_api_icon'])
        self.notifications.setChecked(self.config['notifications'])
        self.remember_geometry.setChecked(self.config['remember_geometry'])
        self.remember_columns.setChecked(self.config['remember_columns'])
        self.columns_per_api.setChecked(self.config['columns_per_api'])
        self.filter_bar_position.setCurrentIndex(
            self.filter_bar_position.findData(
                self.config['filter_bar_position']))
        self.inline_edit.setChecked(self.config['inline_edit'])

        self.ep_bar_style.setCurrentIndex(
            self.ep_bar_style.findData(self.config['episodebar_style']))
        self.ep_bar_text.setChecked(self.config['episodebar_text'])

        self.autoretrieve_days_n.setEnabled(self.autoretrieve_days.isChecked())
        self.autosend_minutes_n.setEnabled(self.autosend_minutes.isChecked())
        self.autosend_size_n.setEnabled(self.autosend_size.isChecked())
        self.close_to_tray.setEnabled(self.tray_icon.isChecked())
        self.start_in_tray.setEnabled(self.tray_icon.isChecked())
        self.notifications.setEnabled(self.tray_icon.isChecked())

        self.color_values = self.config['colors'].copy()

        self.tracker_type_change(None)

    def _save(self):
        engine = self.worker.engine

        engine.set_config('tracker_enabled', self.tracker_enabled.isChecked())
        engine.set_config(
            'tracker_type',
            self.tracker_type.itemData(self.tracker_type.currentIndex()))
        engine.set_config('tracker_interval', self.tracker_interval.value())
        engine.set_config('tracker_process', str(self.tracker_process.text()))
        engine.set_config('tracker_update_wait_s',
                          self.tracker_update_wait.value())
        engine.set_config('tracker_update_close',
                          self.tracker_update_close.isChecked())
        engine.set_config('tracker_update_prompt',
                          self.tracker_update_prompt.isChecked())
        engine.set_config('tracker_not_found_prompt',
                          self.tracker_not_found_prompt.isChecked())

        engine.set_config('player', self.player.text())
        engine.set_config('library_autoscan',
                          self.library_autoscan.isChecked())
        engine.set_config('scan_whole_list', self.scan_whole_list.isChecked())
        engine.set_config('library_full_path',
                          self.library_full_path.isChecked())
        engine.set_config('plex_host', self.plex_host.text())
        engine.set_config('plex_port', self.plex_port.text())
        engine.set_config('plex_obey_update_wait_s',
                          self.plex_obey_wait.isChecked())
        engine.set_config('plex_user', self.plex_user.text())
        engine.set_config('plex_passwd', self.plex_passw.text())

        engine.set_config('searchdir', [
            self.searchdirs.item(i).text()
            for i in range(self.searchdirs.count())
        ])

        if self.autoretrieve_always.isChecked():
            engine.set_config('autoretrieve', 'always')
        elif self.autoretrieve_days.isChecked():
            engine.set_config('autoretrieve', 'days')
        else:
            engine.set_config('autoretrieve', 'off')

        engine.set_config('autoretrieve_days',
                          self.autoretrieve_days_n.value())

        if self.autosend_always.isChecked():
            engine.set_config('autosend', 'always')
        elif self.autosend_minutes.isChecked():
            engine.set_config('autosend', 'minutes')
        elif self.autosend_size.isChecked():
            engine.set_config('autosend', 'size')
        else:
            engine.set_config('autosend', 'off')

        engine.set_config('autosend_minutes', self.autosend_minutes_n.value())
        engine.set_config('autosend_size', self.autosend_size_n.value())

        engine.set_config('autosend_at_exit',
                          self.autosend_at_exit.isChecked())
        engine.set_config('auto_status_change',
                          self.auto_status_change.isChecked())
        engine.set_config('auto_status_change_if_scored',
                          self.auto_status_change_if_scored.isChecked())
        engine.set_config('auto_date_change',
                          self.auto_date_change.isChecked())

        engine.save_config()

        self.config['show_tray'] = self.tray_icon.isChecked()
        self.config['close_to_tray'] = self.close_to_tray.isChecked()
        self.config['start_in_tray'] = self.start_in_tray.isChecked()
        self.config['tray_api_icon'] = self.tray_api_icon.isChecked()
        self.config['notifications'] = self.notifications.isChecked()
        self.config['remember_geometry'] = self.remember_geometry.isChecked()
        self.config['remember_columns'] = self.remember_columns.isChecked()
        self.config['columns_per_api'] = self.columns_per_api.isChecked()
        self.config['filter_bar_position'] = self.filter_bar_position.itemData(
            self.filter_bar_position.currentIndex())
        self.config['inline_edit'] = self.inline_edit.isChecked()

        self.config['episodebar_style'] = self.ep_bar_style.itemData(
            self.ep_bar_style.currentIndex())
        self.config['episodebar_text'] = self.ep_bar_text.isChecked()

        self.config['colors'] = self.color_values

        utils.save_config(self.config, self.configfile)

        self.saved.emit()

    def s_save(self):
        self._save()
        self.accept()

    def tracker_type_change(self, checked):
        if self.tracker_enabled.isChecked():
            self.tracker_interval.setEnabled(True)
            self.tracker_update_wait.setEnabled(True)
            self.tracker_type.setEnabled(True)
            if self.tracker_type.itemData(
                    self.tracker_type.currentIndex()) == 'plex':
                self.plex_host.setEnabled(True)
                self.plex_port.setEnabled(True)
                self.plex_obey_wait.setEnabled(True)
                self.plex_user.setEnabled(True)
                self.plex_passw.setEnabled(True)
                self.tracker_process.setEnabled(False)
            else:
                self.tracker_process.setEnabled(True)
                self.plex_host.setEnabled(False)
                self.plex_port.setEnabled(False)
                self.plex_user.setEnabled(False)
                self.plex_passw.setEnabled(False)
                self.plex_obey_wait.setEnabled(False)
        else:
            self.tracker_type.setEnabled(False)
            self.plex_host.setEnabled(False)
            self.plex_port.setEnabled(False)
            self.plex_user.setEnabled(False)
            self.plex_passw.setEnabled(False)
            self.plex_obey_wait.setEnabled(False)
            self.tracker_process.setEnabled(False)
            self.tracker_interval.setEnabled(False)
            self.tracker_update_wait.setEnabled(False)

    def s_autoretrieve_days(self, checked):
        self.autoretrieve_days_n.setEnabled(checked)

    def s_autosend_minutes(self, checked):
        self.autosend_minutes_n.setEnabled(checked)

    def s_autosend_size(self, checked):
        self.autosend_size_n.setEnabled(checked)

    def s_tray_icon(self, checked):
        self.close_to_tray.setEnabled(checked)
        self.start_in_tray.setEnabled(checked)
        self.tray_api_icon.setEnabled(checked)
        self.notifications.setEnabled(checked)

    def s_ep_bar_style(self, index):
        if self.ep_bar_style.itemData(index) == ShowsTableDelegate.BarStyle04:
            self.ep_bar_text.setEnabled(False)
        else:
            self.ep_bar_text.setEnabled(True)

    def s_auto_status_change(self, checked):
        self.auto_status_change_if_scored.setEnabled(checked)

    def s_player_browse(self):
        if pyqt_version is 5:
            self.player.setText(
                QFileDialog.getOpenFileName(
                    caption='Choose player executable')[0])
        else:
            self.player.setText(
                QFileDialog.getOpenFileName(
                    caption='Choose player executable'))

    def s_searchdirs_add(self):
        self._add_dir(
            QFileDialog.getExistingDirectory(caption='Choose media directory'))

    def s_searchdirs_remove(self):
        row = self.searchdirs.currentRow()
        if row != -1:
            self.searchdirs.takeItem(row)

    def s_switch_page(self, new, old):
        if not new:
            new = old

        self.contents.setCurrentIndex(self.category_list.row(new))

    def s_color_picker(self, key, system):
        return lambda: self.color_picker(key, system)

    def color_picker(self, key, system):
        if system is True:
            current = self.color_values[key]
            result = ThemedColorPicker.do()
            if result is not None and result is not current:
                self.color_values[key] = result
                self.update_colors()
        else:
            current = getColor(self.color_values[key])
            result = QColorDialog.getColor(current)
            if result.isValid() and result is not current:
                self.color_values[key] = str(result.name())
                self.update_colors()

    def update_colors(self):
        for ((key, label),
             color) in zip(self.colors['rows'] + self.colors['progress'],
                           self.color_buttons):
            color.setStyleSheet('background-color: ' +
                                getColor(self.color_values[key]).name())
예제 #45
0
class filedialogdemo(QWidget):
   def __init__(self, parent = None):
      super(filedialogdemo, self).__init__(parent)
		
      layout = QGridLayout()
      self.btn = QPushButton("Make a new circuit")
      self.btn.clicked.connect(self.makeanewexec)
      self.resize(600, 600)
      variables=[]
      self.variables=variables
      dict1={}
      self.variables.append(dict1)
      xlayout=QGridLayout()
      layout.addLayout(xlayout,2,0)
      self.variables[0]['gogen']=0



      self.btn1 = QPushButton("Load existing circ file")
      self.btn1.clicked.connect(self.loadexisting)
      xlayout.addWidget(self.btn,0,0)
      xlayout.addWidget(self.btn1,0,1)
      self.btnclr = QPushButton("Clear")
      self.btnclr.clicked.connect(self.clearbtn)
      self.btnclr.setStyleSheet('QPushButton {background-color: red;}')

      self.btnum = QPushButton("User Manual")
      self.btnum.clicked.connect(self.um)
      self.btnum.setStyleSheet('QPushButton {background-color: yellow;}')

      self.b1 = QRadioButton("Display all")
      self.b1.setChecked(True)
      self.b1.toggled.connect(lambda:self.btnstate1())
      xlayout.addWidget(self.b1,0,2)
      xlayout.addWidget(self.btnclr,0,3)
      xlayout.addWidget(self.btnum,0,4)
      xlayout.setColumnStretch(0,1.5)
      xlayout.setColumnStretch(1,4)
      xlayout.setColumnStretch(1,1)


      xlayout=QGridLayout()
      layout.addLayout(xlayout,3,0)      

      self.btn3 = QPushButton("Show wires")
      self.btn3.clicked.connect(self.show_wires)
      xlayout.addWidget(self.btn3,0,0)


      self.btn4 = QPushButton("Show Inputs")
      self.btn4.clicked.connect(self.show_inputs)
      xlayout.addWidget(self.btn4,0,1)
      

      self.btn5 = QPushButton("Show Outputs")
      self.btn5.clicked.connect(self.show_outputs)
      xlayout.addWidget(self.btn5,0,2)
      

      xlayout=QGridLayout()
      layout.addLayout(xlayout,4,0)      

      self.ppinp1 = QLineEdit('Number of processors')
      self.ppinp1.setReadOnly(True)
      xlayout.addWidget(self.ppinp1,0,0)
      
      self.ppinp = QLineEdit()
      #self.btn3.clicked.connect(self.show_wires)
      xlayout.addWidget(self.ppinp,0,1)


      self.ppchb = QCheckBox('Run with multiple processor')
      #self.btn4.clicked.connect(self.show_inputs)
      xlayout.addWidget(self.ppchb,0,2)
      
      xlayout=QGridLayout()
      layout.addLayout(xlayout,6,0)      

      self.btn6 = QPushButton("Show Gates")
      self.btn6.clicked.connect(self.show_gates)
      self.btn7 = QPushButton("Show AND Gates")
      self.btn7.clicked.connect(self.show_and)
      self.btn8 = QPushButton("Show OR Gates")
      self.btn8.clicked.connect(self.show_or)
      self.btn9 = QPushButton("Show NOT Gates")
      self.btn9.clicked.connect(self.show_not)
      xlayout.addWidget(self.btn6,0,0)      
      xlayout.addWidget(self.btn7,0,1)      
      xlayout.addWidget(self.btn8,0,2)      
      xlayout.addWidget(self.btn9,0,3)      
      
      self.btn2 = QPushButton("Generate virtual graph")
      self.btn2.clicked.connect(self.generatevirtualgraph)
      layout.addWidget(self.btn2)
      self.textbox1 = QLineEdit()
#     self.textbox.setReadOnly(True)
      self.textbox1.setText('Save as')
      self.variables[0]['saveas']=''
 
      layout.addWidget(self.textbox1)

      self.btngb = QPushButton("Gate based verilog")
      self.btngb.clicked.connect(self.gatebased)
      layout.addWidget(self.btngb)

      self.btngb2 = QPushButton("Truth Table based verilog")
      self.btngb2.clicked.connect(self.ttbased)
      layout.addWidget(self.btngb2)

      self.btngb3 = QPushButton("Assign based verilog")
      self.btngb3.clicked.connect(self.abased)
      layout.addWidget(self.btngb3)
      
      self.btngb4 = QPushButton("Give a truth table input")
      self.btngb4.clicked.connect(self.ttmake)
      layout.addWidget(self.btngb4)

      self.btngb4.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')

      self.btnca = QPushButton("Compute all the three parallelly")
      self.btnca.clicked.connect(self.camake)
      layout.addWidget(self.btnca)

      self.btnca.setStyleSheet('QPushButton {background-color: #A3C111; color: red;}')

      xlayout=QGridLayout()

      self.textbox = QTextEdit()
      self.textbox.setReadOnly(True)
      self.textbox.setText('')
      self.variables[0]['text']=''
      self.variables[0]['textbox']=1
      count=9
      layout.addWidget(self.textbox)
      #layout.addLayout(xlayout,count,0)
      #xlayout.setRowStretch(0,1)
      #xlayout.setRowStretch(1,20000)

      count=count+1      

      self.setLayout(layout)
      self.setWindowTitle("Cello GUI")

   def makeanewexec(self):
      call(['java', '-jar', 'logisim.jar'])
   def um(self):
   	  call(['evince',  'userManual.pdf'])   

   def clearbtn(self):
      self.variables[0]['text']=''
      self.textbox.setText(self.variables[0]['text'])

   def generatevirtualgraph(self):
      try:
         #### for making the user interface smooth
         self.variables[0]['text']='Processing and generating virtual graphs using the canvas information'
         self.textbox.setText(self.variables[0]['text'])
         QApplication.processEvents()         
         timesleep=1.0
         divide=1.0
         if(self.ppchb.isChecked()):
            divide=float(self.ppinp.text())
         sleep(timesleep/divide)
         pins=self.variables[0]['pins']
         ands_end=self.variables[0]['ands_end']
         or_end=self.variables[0]['or_end']
         nots_end=self.variables[0]['nots_end']
         ops=self.variables[0]['ops']
         wires1=self.variables[0]['wires1']


         inps=[]
         for i in pins:
            inps.append(i)

         intermediates_list=[]

         connection_not={}
         for i in nots_end:
            intermediates_list.append(i)
            connection_not[i]='empty'

         connection_and={}
         for i in ands_end:
            intermediates_list.append(i)
            connection_and[i+'left']='empty'
            connection_and[i+'right']='empty'

         connection_or={}
         for i in or_end:
            intermediates_list.append(i)
            connection_or[i+'left']='empty'
            connection_or[i+'right']='empty'

         intermediates={}
         for idx,i in enumerate(intermediates_list):
            intermediates[i]='w'+str(idx+1)



         while (len(inps)>0):
            curr=inps[0]
            end=find_end(curr,wires1)

            orl_end=give_end_left_or(end)
            orr_end=give_end_right_or(end)
            end_not=give_end_not(end)
         #  print (curr, end)
            if (orl_end in or_end ):   
               connection_or[orl_end+'left']=curr
         #     print 'or left'
               if (orl_end not in inps):
                  inps.append(orl_end)
            if(orr_end in or_end):
               connection_or[orr_end+'right']=curr
         #     print 'or right'
               if (orr_end not in inps):
                  inps.append(orr_end) 
            if(orl_end in ands_end):
         #     print 'and left'
               connection_and[orl_end+'left']=curr
               if (orl_end not in inps):
                  inps.append(orl_end)
            if(orr_end in ands_end):
         #     print 'and right'
               connection_and[orr_end+'right']=curr      
               if (orr_end not in inps):
                  inps.append(orr_end)
            if(end_not in nots_end):
         #     print 'not gate'
               connection_not[end_not]=curr
               if (end_not not in inps):
                  inps.append(end_not)
         #  if(end in ops):
         #     print 'output pin'
            inps.remove(curr)


         '''
         module XOR(output out1,  input in1, in2);
           wire w1, w2, w3, w4;
           not (w1, in1);
           not (w2, in2);
           not (w3, in1, w2);
           not (w4, in2, w1);
           or (out1, w3, w4);
         endmodule
         '''

         #print 'connections'
         #print 'connections not'

         #print connection_not
         #print 'connections and'
         #for i in connection_and:
         #  print (i,connection_and[i])

         #print 'connections or'
         #for i in connection_or:
         #  print (i,connection_or[i])

         ops_end={}
         for i in ops:
            
            temp=find_end(i,wires1)

            ops_end[i]=temp
         for i in ops:
            temp=ops_end[i]
            if(temp+'right' in connection_and):
               x1=connection_and[temp+'right']
               x2=connection_and[temp+'left']
               connection_and.pop(temp+'right', None)
               connection_and.pop(temp+'left', None)
               connection_and[i+'right']=x1
               connection_and[i+'left']=x2

         for i in ops:
            temp=ops_end[i]
            if(temp+'right' in connection_or):
               x1=connection_or[temp+'right']
               x2=connection_or[temp+'left']
               connection_or.pop(temp+'right', None)
               connection_or.pop(temp+'left', None)
               connection_or[i+'right']=x1
               connection_or[i+'left']=x2

         for i in ops:
            temp=ops_end[i]
            if(temp in connection_not):
               x1=connection_not[temp]
               connection_not.pop(temp, None)
               connection_not[i]=x1
         self.variables[0]['ca']=connection_and      
         self.variables[0]['co']=connection_or      
         self.variables[0]['cn']=connection_not      
         #print 'connections'
         #print 'connections not'

         #print connection_not
         #print 'connections and'
         #for i in connection_and:
         #  print (i,connection_and[i])

         #print 'connections or'
         #for i in connection_or:
         #  print (i,connection_or[i])
         self.variables[0]['gogen']=1
         ts='Producing generated results\n'
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)

         self.variables[0]['text']=ts
         self.textbox.setText(self.variables[0]['text'])
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'########             ----Connections----                ########\n'
         str1=str1+'######################################\n\n'

         str1=str1+'######################################\n'
         str1=str1+'########               AND connections                ########\n'
         str1=str1+'######################################\n'
         for idx,i in enumerate(connection_and):
            str1=str1+'And connection no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+' with '+connection_and[i]+' \n'
         str1=str1+'######################################\n'
         str1=str1+'###########               AND ends            ###########\n'
         str1=str1+'######################################\n\n\n'

         str1=str1+'######################################\n'
         str1=str1+'########               OR connections                ########\n'
         str1=str1+'######################################\n'
         for idx,i in enumerate(connection_or):
            str1=str1+'And connection no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+' with '+connection_or[i]+' \n'
         str1=str1+'######################################\n'
         str1=str1+'###########               OR ends            ###########\n'
         str1=str1+'######################################\n\n\n'

         str1=str1+'######################################\n'
         str1=str1+'########               NOT connections                ########\n'
         str1=str1+'######################################\n'
         for idx,i in enumerate(connection_not):
            str1=str1+'And connection no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+' with '+connection_not[i]+' \n'
         str1=str1+'######################################\n'
         str1=str1+'###########               NOT ends            ###########\n'
         str1=str1+'######################################\n\n\n'
         self.variables[0]['text']=str1
         self.textbox.setText(self.variables[0]['text'])

      except:
         self.variables[0]['text']='Please Select A CIRC FILE First'
         self.textbox.setText(self.variables[0]['text'])


   def show_wires(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)

         wires1=self.variables[0]['wires1']
         data=wires1
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########               Wires starts             #########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'Wire no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########               Wires ends             #########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            str2=self.variables[0]['text']+str1
            self.variables[0]['text']=str2
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No Wires Found)'
         self.textbox.setText(self.variables[0]['text'])


   def show_inputs(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         wires1=self.variables[0]['pins']
         data=wires1
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########             Input pins starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'Input no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             Input pins ends             ########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            str2=self.variables[0]['text']+str1
            self.variables[0]['text']=str2
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No Input pins Found)'
         self.textbox.setText(self.variables[0]['text'])

   def show_outputs(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         wires1=self.variables[0]['ops']
         data=wires1
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########             Output pins starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'Output no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             Output pins ends             ########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            str2=self.variables[0]['text']+str1
            self.variables[0]['text']=str2
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No Output pins Found)'
         self.textbox.setText(self.variables[0]['text'])

   def show_gates(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         wires1=self.variables[0]['ands_end']
         data=wires1
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########             AND gates starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'AND gate no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             AND gates ends             ########\n'
         str1=str1+'######################################\n\n\n'
#         self.textbox.setText(str1)
         wires1=self.variables[0]['or_end']
         data=wires1
         str1=str1+'######################################\n'
         str1=str1+'###########             OR gates starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'OR gate no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             OR gates ends             ########\n'
         str1=str1+'######################################\n\n\n'
#         self.textbox.setText(str1)
         wires1=self.variables[0]['nots_end']
         data=wires1
         str1=str1+'######################################\n'
         str1=str1+'###########             NOT gates starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'NOT gate no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             NOT gates ends             ########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No Gates Found)'
         self.textbox.setText(self.variables[0]['text'])
   def show_and(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         wires1=self.variables[0]['ands_end']
         data=wires1
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########             AND gates starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'AND gate no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             AND gates ends             ########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No AND gates)'
         self.textbox.setText(self.variables[0]['text'])
   def show_or(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         str1=''
         wires1=self.variables[0]['or_end']
         data=wires1
         str1=str1+'######################################\n'
         str1=str1+'###########             OR gates starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'OR gate no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             OR gates ends             ########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No OR gates)'
         self.textbox.setText(self.variables[0]['text'])
   def show_not(self):
      try:
         ts=''
         for vi in range(100):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         wires1=self.variables[0]['nots_end']
         data=wires1
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########             NOT gates starts             ########\n'
         str1=str1+'######################################\n'

         for idx,i in enumerate(data):
            str1=str1+'NOT gate no. '
            str1=str1+str(idx+1)
            str1=str1+' at the position '
            str1=str1+i+'\n'
         str1=str1+'######################################\n'
         str1=str1+'###########             NOT gates ends             ########\n'
         str1=str1+'######################################\n\n\n'
         if(self.variables[0]['textbox']==1):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])
         elif(self.variables[0]['textbox']==0):
            self.variables[0]['text']=str1
            self.textbox.setText(self.variables[0]['text'])         
#         self.textbox.setText(str1)
      except:
         self.variables[0]['text']='Please Select A CIRC FILE (No NOT gates)'
         self.textbox.setText(self.variables[0]['text'])

   def loadexisting(self):
      fname = QFileDialog.getOpenFileName(self, 'Open file', 
         '/home',"CIRC files (*.circ)")
      with open(fname[0]) as f:
         lines_global = f.read().splitlines()
      #lines_global = fname.read().splitlines()
      self.variables[0]['lines_all']=lines_global

      wires_list=find_wires(lines_global)
      wires1=wires_list[0]


      ret=find_inputs(lines_global)
      pins=ret['a']
      pins_pos=ret['b']


      ret=find_outputs(lines_global)
      ops=ret['a']
      ops_pos=ret['b']

      nots_end=find_not_gates(lines_global)
      ands_end=find_and_gates(lines_global)
      or_end=find_or_gates(lines_global)
      self.variables[0]['wires1']=wires1
      self.variables[0]['pins']=pins
      self.variables[0]['ops']=ops
      self.variables[0]['nots_end']=nots_end
      self.variables[0]['ands_end']=ands_end
      self.variables[0]['or_end']=or_end


   def btnstate1(self):
      if(self.b1.isChecked()):
         self.variables[0]['textbox']=1
      else:
         self.variables[0]['textbox']=0


   def gatebased(self):
      try:
         if(self.variables[0]['gogen']==0):
            self.generatevirtualgraph()                 

         fname1=self.textbox1.text()
         pins=self.variables[0]['pins']
         ands_end=self.variables[0]['ands_end']
         or_end=self.variables[0]['or_end']
         nots_end=self.variables[0]['nots_end']
         ops=self.variables[0]['ops']
         wires1=self.variables[0]['wires1']
         connection_and=self.variables[0]['ca']
         connection_or=self.variables[0]['co']
         connection_not=self.variables[0]['cn']
         top=print_into_file(fname1,ops,pins,nots_end,ands_end,or_end,connection_and,connection_or,connection_not,1)

         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########             Gate based Verilog             ########\n'
         str1=str1+'######################################\n'
         ts='Finding the order of gates for verilog file\n'
         for vi in range(200):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         str1=str1+top
         str1=str1+'######################################\n'
         str1=str1+'###########             Gate based Verilog             ########\n'
         str1=str1+'######################################\n\n\n\n'
         str1=str1+'######################################\n'
         str1=str1+'###########     File saved as '+ self.textbox1.text()+'.verilog and in 2 other formats   ########\n'
         str1=str1+'######################################\n\n\n'

         self.variables[0]['text']=str1
         self.textbox.setText(self.variables[0]['text'])
      except:
         self.variables[0]['text']='Please Select A CIRC FILE'
         self.textbox.setText(self.variables[0]['text'])


   def ttbased(self):
      try:
         if(self.variables[0]['gogen']==0):
            self.generatevirtualgraph()                 

         fname1=self.textbox1.text()
         pins=self.variables[0]['pins']
         ands_end=self.variables[0]['ands_end']
         or_end=self.variables[0]['or_end']
         nots_end=self.variables[0]['nots_end']
         ops=self.variables[0]['ops']
         wires1=self.variables[0]['wires1']
         connection_and=self.variables[0]['ca']
         connection_or=self.variables[0]['co']
         connection_not=self.variables[0]['cn']
         top=print_into_file(fname1,ops,pins,nots_end,ands_end,or_end,connection_and,connection_or,connection_not,2)

         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########         Truth Table based Verilog           ########\n'
         str1=str1+'######################################\n'
         ts='Calculating all the possible combination for the truth table of the verilog file\n'
         for vi in range(200):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         str1=str1+top
         str1=str1+'######################################\n'
         str1=str1+'###########         Truth Table based Verilog           ########\n'
         str1=str1+'######################################\n\n\n\n'

         str1=str1+'######################################\n'
         str1=str1+'###########     File saved as '+ self.textbox1.text()+'.verilog and in 2 other formats   ########\n'
         str1=str1+'######################################\n\n\n'
         self.variables[0]['text']=str1
         self.textbox.setText(self.variables[0]['text'])
      except:
         self.variables[0]['text']='Please Select A CIRC FILE'
         self.textbox.setText(self.variables[0]['text'])

   def abased(self):
      try:
         if(self.variables[0]['gogen']==0):
            self.generatevirtualgraph()                 

         fname1=self.textbox1.text()
         pins=self.variables[0]['pins']
         ands_end=self.variables[0]['ands_end']
         or_end=self.variables[0]['or_end']
         nots_end=self.variables[0]['nots_end']
         ops=self.variables[0]['ops']
         wires1=self.variables[0]['wires1']
         connection_and=self.variables[0]['ca']
         connection_or=self.variables[0]['co']
         connection_not=self.variables[0]['cn']
         top=print_into_file(fname1,ops,pins,nots_end,ands_end,or_end,connection_and,connection_or,connection_not,3)

         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########         Assign based Verilog           ########\n'
         str1=str1+'######################################\n'
         ts='Finding the correct order in which the wires should be assigned for verilog files\n'
         for vi in range(200):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.005
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         str1=str1+top
         str1=str1+'######################################\n'
         str1=str1+'###########         Assign based Verilog           ########\n'
         str1=str1+'######################################\n\n\n\n'

         str1=str1+'######################################\n'
         str1=str1+'###########     File saved as '+ self.textbox1.text()+'.verilog and in 2 other formats   ########\n'
         str1=str1+'######################################\n\n\n'
         self.variables[0]['text']=str1
         self.textbox.setText(self.variables[0]['text'])
      except:
         self.variables[0]['text']='Please Select A CIRC FILE'
         self.textbox.setText(self.variables[0]['text'])
   def camake(self):
      try:
         if(self.variables[0]['gogen']==0):
            self.generatevirtualgraph()                 

         fname1=self.textbox1.text()
         pins=self.variables[0]['pins']
         ands_end=self.variables[0]['ands_end']
         or_end=self.variables[0]['or_end']
         nots_end=self.variables[0]['nots_end']
         ops=self.variables[0]['ops']
         wires1=self.variables[0]['wires1']
         connection_and=self.variables[0]['ca']
         connection_or=self.variables[0]['co']
         connection_not=self.variables[0]['cn']

         top1=print_into_file(fname1,ops,pins,nots_end,ands_end,or_end,connection_and,connection_or,connection_not,1)
         top2=print_into_file(fname1,ops,pins,nots_end,ands_end,or_end,connection_and,connection_or,connection_not,2)
         top3=print_into_file(fname1,ops,pins,nots_end,ands_end,or_end,connection_and,connection_or,connection_not,3)
         
         #p1 = Process(target=find_and_gates_parallel, args=())
         #p1.start()
         #top1=ansav['rt']
         #p2 = Process(target=find_and_gates_parallel, args=())
         #p2.start()
         #top1=ansav['rt']
         #p3 = Process(target=find_and_gates_parallel, args=())
         #p3.start()
         #top1=ansav['rt']
         
         str1=''
         str1=str1+'######################################\n'
         str1=str1+'###########         Running parallelly           ########\n'
         str1=str1+'######################################\n'
         ts='Finding the correct order in which the wires should be assigned for verilog files\n'
         for vi in range(200):
            ts=ts+'#'
            self.variables[0]['text']=ts
            self.textbox.setText(self.variables[0]['text'])
            QApplication.processEvents()         
            timesleep=0.002
            divide=1.0
            if(self.ppchb.isChecked()):
               divide=float(self.ppinp.text())
            sleep(timesleep/divide)
         str1=str1+ '\n\n'+top1+ '\n\n'
         str1=str1+ '\n\n'+top2+ '\n\n'
         str1=str1+ '\n\n'+top3+ '\n\n'
         str1=str1+'######################################\n'
         str1=str1+'###########         Running Parallely           ########\n'
         str1=str1+'######################################\n\n\n\n'

         str1=str1+'######################################\n'
         str1=str1+'###########     File saved as '+ self.textbox1.text()+'.verilog and in 2 other formats   ########\n'
         str1=str1+'######################################\n\n\n'
         self.variables[0]['text']=str1
         self.textbox.setText(self.variables[0]['text'])
      except:
         self.variables[0]['text']='Please Select A CIRC FILE'
         self.textbox.setText(self.variables[0]['text'])
   def ttmake(self):
   	call(['python', 'tt.py'])
예제 #46
0
class ButtonComponent(QWidget):
    def __init__(self, parent, component):
        super().__init__(parent)
        self.parent = parent
        self.component = component

        names = self.component.callback.split(" - ") if self.component.callback is not None else ["", ""]

        self.name = QLabel("Button", self)
        self.text = QLabel("Text", self)
        self.delete_btn = QPushButton("Delete", self)
        self.text_edit = QLineEdit(self.component.text, self)
        self.callback = QLabel("Callback", self)
        self.callback_script_edit = QLineEdit(names[0], self)
        self.callback_func_edit = QLineEdit(names[1], self)
        self.size = QLabel("Size", self)
        self.size_spins = [QSpinBox(self), QSpinBox(self)]
        self.bg = QLabel("Background Color", self)
        self.bg_spins = [QSpinBox(self), QSpinBox(self), QSpinBox(self), QSpinBox(self)]
        self.bg_picker = QPushButton("Color Picker")
        self.font_name = QLabel("Font Name", self)
        self.font_name_edit = QLineEdit(self.component.font_name, self)
        self.font_size = QLabel("Font Size", self)
        self.font_size_spin = QSpinBox(self)
        self.font_color_name = QLabel("Font Color", self)
        self.font_color_spins = [QSpinBox(self), QSpinBox(self), QSpinBox(self), QSpinBox(self)]
        self.font_color_picker = QPushButton("Color Picker")
        self.font_bold = QLabel("Font Bold", self)
        self.font_bold_check = QCheckBox(self)
        self.font_italic = QLabel("Font Italic", self)
        self.font_italic_check = QCheckBox(self)
        self.font_underline = QLabel("Font Underline", self)
        self.font_underline_check = QCheckBox(self)
        self.font_antialias = QLabel("Font Antialias", self)
        self.font_antialias_check = QCheckBox(self)

        self.name.setAlignment(Qt.AlignHCenter)
        self.text_edit.textChanged.connect(self.change_value)
        self.font_name_edit.textChanged.connect(self.change_value)
        self.font_size_spin.setValue(self.component.font_size)
        self.font_size_spin.valueChanged.connect(self.change_value)
        self.font_bold_check.setChecked(self.component.font_bold)
        self.font_bold_check.clicked.connect(self.change_value)
        self.font_italic_check.setChecked(self.component.font_italic)
        self.font_italic_check.clicked.connect(self.change_value)
        self.font_underline_check.setChecked(self.component.font_underline)
        self.font_underline_check.clicked.connect(self.change_value)
        self.font_antialias_check.setChecked(self.component.font_antialias)
        self.font_antialias_check.clicked.connect(self.change_value)
        self.callback_script_edit.textChanged.connect(self.change_value)
        self.callback_func_edit.textChanged.connect(self.change_value)
        for k, v in enumerate(component.bg.rgba()):
            self.bg_spins[k].setRange(0, 255)
            self.bg_spins[k].setValue(v)
            self.bg_spins[k].valueChanged.connect(self.change_value)
        for k, v in enumerate(component.font_color.rgba()):
            self.font_color_spins[k].setRange(0, 255)
            self.font_color_spins[k].setValue(v)
            self.font_color_spins[k].valueChanged.connect(self.change_value)
        for k, v in enumerate(self.component.size.coords()):
            self.size_spins[k].setRange(-2147483648, 2147483647)
            self.size_spins[k].setValue(v)
        self.bg_picker.clicked.connect(self.change_bg)
        self.font_color_picker.clicked.connect(self.change_font_color)
        self.delete_btn.clicked.connect(self.delete)

        self.layout = QGridLayout()
        self.layout.addWidget(self.name, 0, 1, 1, 3)
        self.layout.addWidget(self.delete_btn, 0, 4)
        self.layout.addWidget(self.text, 1, 0)
        self.layout.addWidget(self.text_edit, 1, 1, 1, 4)
        self.layout.addWidget(self.callback, 2, 0)
        self.layout.addWidget(self.callback_script_edit, 2, 1, 1, 2)
        self.layout.addWidget(self.callback_func_edit, 2, 3, 1, 2)
        self.layout.addWidget(self.bg, 3, 0)
        for i in range(len(self.bg_spins)):
            self.layout.addWidget(self.bg_spins[i], 3, i+1)
        self.layout.addWidget(self.bg_picker, 4, 0, 1, 5)
        self.layout.addWidget(self.size, 5, 0)
        self.layout.addWidget(self.size_spins[0], 5, 1, 1, 2)
        self.layout.addWidget(self.size_spins[1], 5, 3, 1, 2)
        self.layout.addWidget(self.font_name, 6, 0)
        self.layout.addWidget(self.font_name_edit, 6, 1, 1, 4)
        self.layout.addWidget(self.font_size, 7, 0)
        self.layout.addWidget(self.font_size_spin, 7, 1, 1, 4)
        self.layout.addWidget(self.font_color_name, 8, 0)
        for i in range(len(self.font_color_spins)):
            self.layout.addWidget(self.font_color_spins[i], 8, i+1)
        self.layout.addWidget(self.font_color_picker, 9, 0, 1, 5)
        self.layout.addWidget(self.font_bold, 10, 0)
        self.layout.addWidget(self.font_bold_check, 10, 1, 1, 4)
        self.layout.addWidget(self.font_italic, 11, 0)
        self.layout.addWidget(self.font_italic_check, 11, 1, 1, 4)
        self.layout.addWidget(self.font_underline, 12, 0)
        self.layout.addWidget(self.font_underline_check, 12, 1, 1, 4)
        self.layout.addWidget(self.font_antialias, 13, 0)
        self.layout.addWidget(self.font_antialias_check, 13, 1, 1, 4)
        self.setLayout(self.layout)

    def delete(self):
        self.parent.remove_component(comp=self.component.name)

    def change_bg(self):
        color = QColorDialog.getColor(QColor(*self.component.bg.rgba()), parent=self)
        if color.isValid():
            self.bg_spins[0].setValue(color.red())
            self.bg_spins[1].setValue(color.green())
            self.bg_spins[2].setValue(color.blue())
            self.bg_spins[3].setValue(color.alpha())
            self.change_value(bg=[color.red(), color.green(), color.blue(), color.alpha()])

    def change_font_color(self):
        color = QColorDialog.getColor(QColor(*self.component.font_color.rgba()), parent=self)
        if color.isValid():
            self.font_color_spins[0].setValue(color.red())
            self.font_color_spins[1].setValue(color.green())
            self.font_color_spins[2].setValue(color.blue())
            self.font_color_spins[3].setValue(color.alpha())
            self.change_value(font_color=[color.red(), color.green(), color.blue(), color.alpha()])

    def change_value(self, _=None, bg=None, font_color=None):
        self.component.text = self.text_edit.text()
        if len(self.callback_script_edit.text()) > 0 and len(self.callback_func_edit.text()) > 0:
            self.component.callback = self.callback_script_edit.text() + " - " + self.callback_func_edit.text()
        else:
            self.component.callback = None
        if bg is None:
            self.component.bg = Color.from_rgba(*(i.value() for i in self.bg_spins))
        else:
            self.component.bg = Color.from_rgba(*bg)
        self.component.size = Vec2(*(i.value() for i in self.size_spins))
        self.component.font_name = self.font_name_edit.text()
        self.component.font_size = self.font_size_spin.value()
        if font_color is None:
            self.component.font_color = Color.from_rgba(*(i.value() for i in self.font_color_spins))
        else:
            self.component.font_color = Color.from_rgba(*font_color)
        self.component.font_bold = self.font_bold_check.isChecked()
        self.component.font_italic = self.font_italic_check.isChecked()
        self.component.font_underline = self.font_underline_check.isChecked()
        self.component.font_antialias = self.font_antialias_check.isChecked()
        self.parent.parent.project.save()
        self.parent.parent.viewport.update_screen()
예제 #47
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.icon_path = os.path.relpath('resources/warframe.ico')

        self.app_title = 'Warframe Prime Helper'
        self.company_name = 'Warframe Tools'

        self.settings = QSettings(self.company_name, self.app_title)
        self.setWindowTitle(self.app_title)

        self.market_api = None

        self.image_label = None
        self.image_label2 = None

        self.warframe_height = 1080
        self.warframe_width = 1920

        self.table = None
        self.mission_table = None

        self.slider_names = None
        self.sliders = None
        self.slider_labels = None
        self.slider_default_values = None
        self.slider_orig_values = None
        self.slider_values = None
        self.is_slider_max_set = False

        self.settings_button = None

        #self.plat_check_box = QCheckBox("Prefer platinum")
        #self.plat_check_box.setChecked(True)

        self.update_prices_button = None
        self.update_ducats_button = None
        self.update_prices_progress = None
        self.update_ducats_progress = None
        self.last_updated_prices_value = None
        self.last_updated_ducats_value = None
        self.num_parts_value = None
        self.latest_item_value = None

        self.move_to_top_check_box = None
        self.pause_button = None
        self.is_paused = False

        self.hide_crop_check_box = None
        self.hide_filter_check_box = None
        self.hide_fissure_check_box = None

        self.relics = None
        self.hide_relics = {}
        self.hidden_relics = set()

        self.hide_missions = {}
        self.hidden_missions = set()
        self.hide_missions_box = None
        self.mission_names = None

        self.crop_img = None
        self.filter_img = None

        self.dialog = None
        self.layout = None

        self.filled_rows = 0
        self.max = -1
        self.max_row = -1

        self.ocr = None
        self.old_screenshot_shape = 0
        self.old_filtered_shape = 0

        self.missions = []

        self.num_primes = 100
        self.api = None

        self.prices_progress_lock = Lock()
        self.ducats_progress_lock = Lock()

        self.ducats_thread = None
        self.prices_thread = None

        self.timer = None

        self.init_image_labels()
        self.init_tables()
        self.init_sliders()
        self.init_dialog()
        self.set_layout()
        self.init_timer()

        self.show()

        #measured correct values
        self.setFixedSize(978, 617)

    def init_timer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_mission_table_time)
        self.timer.start(1000)

    def bring_to_front(self):
        self.setWindowState(self.windowState() & ~Qt.WindowMinimized
                            | Qt.WindowActive)
        self.activateWindow()

    def init_image_labels(self):
        self.image_label = QLabel()
        img_path = os.path.relpath('temp/crop_27.bmp')
        image = QPixmap(img_path)
        self.image_label.setPixmap(image)

        self.image_label2 = QLabel()
        self.image_label2.setPixmap(image)

    def set_layout(self):
        settings_button_box = self.make_settings_button_box()
        self.init_imgs()
        bot_box = self.make_bot_box()

        self.layout = QVBoxLayout()
        self.layout.setAlignment(Qt.AlignTop)
        self.layout.addSpacing(-12)
        self.layout.addLayout(settings_button_box)
        self.layout.addWidget(self.crop_img)
        self.layout.addWidget(self.filter_img)
        self.layout.addWidget(bot_box)
        self.setLayout(self.layout)

    def make_settings_button_box(self):
        self.settings_button = QPushButton()
        # Gear icon is from: https://iconscout.com/icon/gear-222
        style_sheet = """
        QPushButton {
            qproperty-icon: url(" ");
            qproperty-iconSize: 15px 15px;
            border-image: url("resources/Gear.svg");
            background-color: rgba(255, 255, 255, 0);
        }
        
        QPushButton:hover {
            border-image: url("resources/SelectedGear.svg");
        }"""
        self.settings_button.setStyleSheet(style_sheet)
        #settings_button.setStyleSheet("background-color: rgba(0, 0, 0, 255); font-size: 23px;")
        self.settings_button.clicked.connect(self.show_preferences)
        self.settings_button.setFixedWidth(30)
        self.settings_button.setFixedHeight(30)

        settings_button_hb = QHBoxLayout()
        settings_button_hb.setAlignment(Qt.AlignRight)
        settings_button_hb.addWidget(self.settings_button)
        settings_button_hb.addSpacing(-11)
        return settings_button_hb

    def make_bot_box(self):
        bot_layout = QHBoxLayout()
        bot_layout.addWidget(self.table)
        bot_layout.addWidget(self.mission_table)

        bot_box = QGroupBox()
        bot_box.setLayout(bot_layout)
        bot_box.setFixedHeight(287)
        return bot_box

    def init_dialog(self):
        crop_box = self.make_crop_box()
        filter_box = self.make_filter_box()
        other_box = self.make_other_box()

        settings_layout_1 = QVBoxLayout()
        settings_layout_1.addWidget(crop_box)
        settings_layout_1.addWidget(filter_box)
        settings_layout_1.addWidget(other_box)

        update_box = self.make_update_box()
        rate_box = self.make_rate_box()

        settings_layout_2 = QVBoxLayout()
        settings_layout_2.addWidget(update_box)
        settings_layout_2.addWidget(rate_box)

        hide_box = self.make_hide_box()
        hide_relics_box = self.make_hide_relics_box()
        button_box = self.make_button_box()

        settings_layout_3 = QVBoxLayout()
        settings_layout_3.addWidget(hide_box)
        settings_layout_3.addWidget(hide_relics_box)

        hide_missions_box = self.make_hide_missions_box()
        settings_layout_4 = QVBoxLayout()
        settings_layout_4.addWidget(hide_missions_box)
        settings_layout_4.addWidget(button_box)

        settings_layout = QHBoxLayout()
        settings_layout.addLayout(settings_layout_1)
        settings_layout.addLayout(settings_layout_2)
        settings_layout.addLayout(settings_layout_3)
        settings_layout.addLayout(settings_layout_4)

        self.dialog = QDialog()
        self.dialog.setWindowTitle("Preferences")
        self.dialog.setWindowModality(Qt.ApplicationModal)
        self.dialog.setLayout(settings_layout)

    def make_button_box(self):
        button_box = QDialogButtonBox()
        button_box.setOrientation(Qt.Horizontal)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(self.save_settings)
        button_box.rejected.connect(self.load_settings)
        return button_box

    def load_settings(self):
        self.settings.sync()
        slider_orig_values = {
            'x': 521,
            'y': 400,
            'w': 908,
            'h': 70,
            'v1': 197,
            'v2': 180,
            'd': 4,
            'Screencap (hz)': 1,
            'Fissure (s)': 30,
            'API Threads': 4
        }
        self.slider_default_values = {}
        slider_default_max = {
            'x': self.warframe_width / 2,
            'y': self.warframe_height / 2,
            'w': self.warframe_width,
            'h': self.warframe_height,
            'v1': 255,
            'v2': 255,
            'd': 40
        }

        for slider_name in self.slider_names:
            self.slider_default_values[slider_name] = self.settings.value(
                slider_name, defaultValue=slider_orig_values[slider_name])
            if len(slider_name) <= 2:
                max_val = self.settings.value(
                    "{}_max".format(slider_name),
                    defaultValue=slider_default_max[slider_name],
                    type=int)
                self.sliders[slider_name].setMaximum(max_val)
            self.sliders[slider_name].setValue(
                self.slider_default_values[slider_name])

        prices = self.settings.value("last_updated_prices_value",
                                     defaultValue="Never",
                                     type=str)
        ducats = self.settings.value("last_updated_ducats_value",
                                     defaultValue="Never",
                                     type=str)
        num_parts = self.settings.value("num_parts_value",
                                        defaultValue=350,
                                        type=int)
        latest_item = self.settings.value("latest_item_value",
                                          defaultValue="",
                                          type=str)

        self.last_updated_prices_value.setText(prices)
        self.last_updated_ducats_value.setText(ducats)
        self.num_parts_value.setNum(num_parts)
        self.latest_item_value.setText(latest_item)

        for relic in self.relics:
            checked = self.settings.value("hide_{}".format(relic),
                                          defaultValue=False,
                                          type=bool)
            self.hide_relics[relic].setChecked(checked)
            if checked:
                self.set_hidden_relic(relic)

        for mission in self.mission_names:
            checked = self.settings.value("hide_{}".format(mission),
                                          defaultValue=False,
                                          type=bool)
            self.hide_missions[mission].setChecked(checked)
            if checked:
                self.set_hidden_mission(mission)

        if self.settings.value("toggle_fissure_table",
                               defaultValue=False,
                               type=bool):
            self.hide_fissure_check_box.setChecked(True)
            self.toggle_fissure_table()

        if self.settings.value("toggle_move_to_top",
                               defaultValue=False,
                               type=bool):
            self.move_to_top_check_box.setChecked(True)
            self.toggle_move_to_top()

        if self.settings.value("toggle_cropped_img",
                               defaultValue=False,
                               type=bool):
            self.hide_crop_check_box.setChecked(True)
            self.toggle_cropped_img()

        if self.settings.value("toggle_filtered_img",
                               defaultValue=False,
                               type=bool):
            self.hide_filter_check_box.setChecked(True)
            self.toggle_filtered_img()
        self.dialog.close()

    def save_settings(self):
        for slider_name in self.slider_names:
            self.settings.setValue(slider_name,
                                   self.sliders[slider_name].value())

        for relic in self.relics:
            self.settings.setValue("hide_{}".format(relic),
                                   self.hide_relics[relic].isChecked())

        for mission in self.mission_names:
            self.settings.setValue("hide_{}".format(mission),
                                   self.hide_missions[mission].isChecked())

        self.settings.setValue("toggle_fissure_table",
                               self.hide_fissure_check_box.isChecked())
        self.settings.setValue("toggle_move_to_top",
                               self.move_to_top_check_box.isChecked())
        self.settings.setValue("toggle_cropped_img",
                               self.hide_crop_check_box.isChecked())
        self.settings.setValue("toggle_filtered_img",
                               self.hide_filter_check_box.isChecked())
        self.dialog.close()
        self.settings.sync()

    def init_imgs(self):
        self.crop_img = QGroupBox("Crop")
        crop_img_layout = QVBoxLayout()
        crop_img_layout.addWidget(self.image_label)
        self.crop_img.setLayout(crop_img_layout)

        self.filter_img = QGroupBox("Filtered")
        filter_img_layout = QVBoxLayout()
        filter_img_layout.addWidget(self.image_label2)
        self.filter_img.setLayout(filter_img_layout)

    def make_hide_missions_box(self, missions=None):
        if self.hide_missions_box is None:
            self.hide_missions_box = QGroupBox("Hide Missions")
        if missions is not None:
            hide_missions_layout = QGridLayout()
            hide_missions_layout.setColumnStretch(2, 2)
            hide_missions_layout.setAlignment(Qt.AlignTop)
            hide_missions_layout.setContentsMargins(0, 0, 0, 0)

            skip_missions = [
                "MT_SECTOR", "MT_PVP", "MT_LANDSCAPE", "MT_EVACUATION",
                "MT_ASSASSINATION", "MT_ARENA"
            ]
            seen_missions = set()
            i = 0
            for mission in missions:
                mission_name = missions[mission]['value']
                if mission_name == "Extermination":
                    mission_name = "Exterminate"
                if mission not in skip_missions and mission_name not in seen_missions:
                    self.hide_missions[mission_name] = QCheckBox(mission_name)
                    self.hide_missions[mission_name].setChecked(False)
                    self.hide_missions[mission_name].stateChanged.connect(
                        partial(self.set_hidden_mission, mission_name))
                    hide_missions_layout.addWidget(
                        self.hide_missions[mission_name], int(i / 2), i % 2)
                    i += 1
                    seen_missions.add(mission_name)
            self.hide_missions_box.setLayout(hide_missions_layout)
            self.mission_names = list(seen_missions)

            self.load_settings()
        return self.hide_missions_box

    def set_hidden_mission(self, mission):
        if self.hide_missions[mission].isChecked():
            self.hidden_missions.add(mission)
        else:
            self.hidden_missions.remove(mission)
        self.update_mission_table_hidden()

    def make_hide_relics_box(self):
        hide_relics_layout = QVBoxLayout()
        hide_relics_layout.setAlignment(Qt.AlignTop)
        hide_relics_layout.setContentsMargins(0, 0, 0, 0)
        self.relics = ["Axi", "Neo", "Meso", "Lith", "Requiem"]

        for relic in self.relics:
            self.hide_relics[relic] = QCheckBox(relic)
            self.hide_relics[relic].setChecked(False)
            self.hide_relics[relic].stateChanged.connect(
                partial(self.set_hidden_relic, relic))
            hide_relics_layout.addWidget(self.hide_relics[relic])

        hide_relics_box = QGroupBox("Hide Relics")
        hide_relics_box.setLayout(hide_relics_layout)
        return hide_relics_box

    def make_hide_box(self):
        hide_layout = QVBoxLayout()
        hide_layout.setAlignment(Qt.AlignTop)
        hide_layout.setContentsMargins(0, 0, 0, 0)

        self.hide_crop_check_box = QCheckBox("Hide Crop")
        self.hide_crop_check_box.setChecked(False)
        self.hide_crop_check_box.stateChanged.connect(self.toggle_cropped_img)
        hide_layout.addWidget(self.hide_crop_check_box)

        self.hide_filter_check_box = QCheckBox("Hide Filtered")
        self.hide_filter_check_box.setChecked(False)
        self.hide_filter_check_box.stateChanged.connect(
            self.toggle_filtered_img)
        hide_layout.addWidget(self.hide_filter_check_box)

        self.hide_fissure_check_box = QCheckBox("Hide Fissure Table")
        self.hide_fissure_check_box.setChecked(False)
        self.hide_fissure_check_box.stateChanged.connect(
            self.toggle_fissure_table)
        hide_layout.addWidget(self.hide_fissure_check_box)

        hide_box = QGroupBox("Hide UI")
        hide_box.setLayout(hide_layout)
        return hide_box

    def make_rate_box(self):
        rate_grid = QGridLayout()
        rate_grid.setColumnStretch(3, 3)
        rate_grid.setContentsMargins(0, 0, 0, 0)
        for i in range(3):
            slider_name = self.slider_names[i + 7]
            rate_grid.addWidget(self.slider_labels[slider_name], i, 0)
            rate_grid.addWidget(self.slider_values[slider_name], i, 1)
            rate_grid.addWidget(self.sliders[slider_name], i, 2)

        rate_box = QGroupBox("Rates")
        rate_box.setLayout(rate_grid)
        return rate_box

    def make_other_box(self):
        self.move_to_top_check_box = QCheckBox("Bring to front")
        self.move_to_top_check_box.setChecked(True)
        self.move_to_top_check_box.stateChanged.connect(
            self.toggle_move_to_top)
        self.pause_button = QPushButton("Pause")
        self.pause_button.clicked.connect(self.toggle_button)
        self.is_paused = False
        other_layout = QVBoxLayout()
        other_layout.setAlignment(Qt.AlignTop)
        other_layout.setContentsMargins(0, 0, 0, 0)
        other_layout.addWidget(self.move_to_top_check_box)
        other_layout.addWidget(self.pause_button)

        other_box = QGroupBox("Other")
        other_box.setLayout(other_layout)
        return other_box

    def make_filter_box(self):
        filter_grid = QGridLayout()
        filter_grid.setColumnStretch(3, 3)
        filter_grid.setAlignment(Qt.AlignTop)
        filter_grid.setContentsMargins(0, 0, 0, 0)
        for i in range(3):
            slider_name = self.slider_names[i + 4]
            filter_grid.addWidget(self.slider_labels[slider_name], i, 0)
            filter_grid.addWidget(self.slider_values[slider_name], i, 1)
            filter_grid.addWidget(self.sliders[slider_name], i, 2)

        filter_box = QGroupBox("Filter Parameters")
        filter_box.setLayout(filter_grid)
        return filter_box

    def make_crop_box(self):
        crop_grid = QGridLayout()
        crop_grid.setColumnStretch(3, 4)
        crop_grid.setAlignment(Qt.AlignTop)
        crop_grid.setContentsMargins(0, 0, 0, 0)
        for i in range(4):
            slider_name = self.slider_names[i]
            crop_grid.addWidget(self.slider_labels[slider_name], i, 0)
            crop_grid.addWidget(self.slider_values[slider_name], i, 1)
            crop_grid.addWidget(self.sliders[slider_name], i, 2)

        crop_box = QGroupBox("Crop Parameters")
        crop_box.setLayout(crop_grid)
        return crop_box

    def make_update_box(self):
        update_layout = QGridLayout()
        update_layout.setColumnStretch(4, 2)
        update_layout.setAlignment(Qt.AlignTop)
        update_layout.setContentsMargins(0, 0, 0, 0)
        self.update_prices_button = QPushButton("Update Prices")
        self.update_prices_button.clicked.connect(self.update_prices)
        self.update_prices_progress = QProgressBar()
        self.update_prices_progress.setFixedWidth(110)
        self.update_prices_progress.setRange(0, 100)
        update_layout.addWidget(self.update_prices_button, 0, 0)
        update_layout.addWidget(self.update_prices_progress, 0, 1)

        self.update_ducats_button = QPushButton("Update Ducats")
        self.update_ducats_button.clicked.connect(self.update_ducats)
        self.update_ducats_progress = QProgressBar()
        self.update_ducats_progress.setFixedWidth(110)
        self.update_ducats_progress.setRange(0, 100)
        update_layout.addWidget(self.update_ducats_button, 1, 0)
        update_layout.addWidget(self.update_ducats_progress, 1, 1)

        last_updated_prices_label = QLabel("Prices Updated")

        prices = self.settings.value("last_updated_prices_value",
                                     defaultValue="Never",
                                     type=str)
        ducats = self.settings.value("last_updated_ducats_value",
                                     defaultValue="Never",
                                     type=str)
        num_parts = self.settings.value("num_parts_value",
                                        defaultValue=350,
                                        type=str)
        latest_item = self.settings.value("latest_item_value",
                                          defaultValue="",
                                          type=str)

        self.last_updated_prices_value = QLabel(prices)
        self.last_updated_ducats_value = QLabel(ducats)
        self.num_parts_value = QLabel(num_parts)
        self.latest_item_value = QLabel(latest_item)

        update_layout.addWidget(last_updated_prices_label, 2, 0)
        update_layout.addWidget(self.last_updated_prices_value, 2, 1)

        last_updated_ducats_label = QLabel("Ducats Updated")
        update_layout.addWidget(last_updated_ducats_label, 3, 0)
        update_layout.addWidget(self.last_updated_ducats_value, 3, 1)

        num_parts_label = QLabel("Prime Parts")
        update_layout.addWidget(num_parts_label, 4, 0)
        update_layout.addWidget(self.num_parts_value, 4, 1)

        latest_item_label = QLabel("Latest Prime")
        update_layout.addWidget(latest_item_label, 5, 0)
        update_layout.addWidget(self.latest_item_value, 5, 1)

        update_box = QGroupBox("Updates")
        update_box.setLayout(update_layout)
        return update_box

    def init_sliders(self):
        self.slider_names = [
            'x', 'y', 'w', 'h', 'v1', 'v2', 'd', 'Screencap (hz)',
            'Fissure (s)', 'API Threads'
        ]
        self.sliders = {x: QSlider(Qt.Horizontal) for x in self.slider_names}
        self.slider_labels = {x: QLabel(x) for x in self.slider_names}
        self.slider_default_values = {}
        self.slider_orig_values = {
            'x': 521,
            'y': 400,
            'w': 908,
            'h': 70,
            'v1': 197,
            'v2': 180,
            'd': 4,
            'Screencap (hz)': 1,
            'Fissure (s)': 30,
            'API Threads': 4
        }
        for slider_name in self.slider_names:
            self.slider_default_values[slider_name] = self.settings.value(
                slider_name, defaultValue=self.slider_orig_values[slider_name])
        self.slider_values = {
            x: QLabel(str(self.slider_default_values[x]))
            for x in self.slider_names
        }
        self.slider_values['Screencap (hz)'].setNum(
            self.slider_default_values['Screencap (hz)'] / 4)
        self.slider_values['d'].setNum(self.slider_default_values['d'] / 4)

        self.slider_labels['d'].setText('\u0394')

        self.sliders['x'].setMaximum(int(self.warframe_width / 2))
        self.sliders['y'].setMaximum(int(self.warframe_height / 2))
        self.sliders['w'].setMaximum(self.warframe_width)
        self.sliders['h'].setMaximum(self.warframe_height)
        self.sliders['v1'].setMaximum(255)
        self.sliders['v2'].setMaximum(255)
        self.sliders['d'].setMaximum(40)
        self.sliders['Screencap (hz)'].setMaximum(20)
        self.sliders['Screencap (hz)'].setMinimum(1)
        self.sliders['Fissure (s)'].setMaximum(60)
        self.sliders['Fissure (s)'].setMinimum(10)
        self.sliders['API Threads'].setMaximum(10)
        self.sliders['API Threads'].setMinimum(2)
        for slider_name in self.slider_names:
            if len(slider_name) <= 2:
                self.sliders[slider_name].setMinimum(0)
            self.sliders[slider_name].setSingleStep(1)
            self.slider_values[slider_name].setFixedWidth(35)
            self.sliders[slider_name].setValue(
                self.slider_default_values[slider_name])

    def init_tables(self):
        self.table = QTableWidget(7, 3)
        self.table.setHorizontalHeaderLabels(['Prime Part', 'Plat', 'Ducats'])
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)

        self.mission_table = QTableWidget(30, 4)
        self.mission_table.setHorizontalHeaderLabels(
            ['Relic', 'Mission', 'Type', 'Time Left'])
        self.mission_table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        mission_header = self.mission_table.horizontalHeader()

        for i in range(4):
            mission_header.setSectionResizeMode(i, QHeaderView.Interactive)
        mission_header.resizeSection(0, 55)
        mission_header.resizeSection(1, 150)
        mission_header.resizeSection(2, 90)
        mission_header.resizeSection(3, 60)
        self.mission_table.setFixedWidth(405)

    def update_prices(self):
        self.prices_thread = threading.Thread(
            name="prices_thread", target=self.market_api.update_prices)
        self.prices_thread.start()

        self.update_prices_button.setEnabled(False)
        self.update_ducats_button.setEnabled(False)

    def update_ducats(self):
        self.ducats_thread = threading.Thread(
            name="ducats_thread", target=self.market_api.update_ducats)
        self.ducats_thread.start()

        self.update_prices_button.setEnabled(False)
        self.update_ducats_button.setEnabled(False)

    def update_primes_info(self, num, latest):
        self.num_parts_value.setNum(num)
        self.latest_item_value.setText(latest)
        self.update_prices_progress.setMaximum(num)
        self.update_ducats_progress.setMaximum(num)
        self.num_primes = num

    def get_datetime(self):
        return datetime.now().strftime("%b %d %Y %H:%M:%S")

    def update_ducats_time(self):
        self.last_updated_ducats_value.setText(self.get_datetime())
        self.ducats_progress_lock.acquire()
        self.update_ducats_progress.setValue(self.num_primes)
        self.ducats_progress_lock.release()

        self.settings.setValue("last_updated_ducats_value",
                               self.last_updated_ducats_value.text())
        self.settings.setValue("num_parts_value", self.num_parts_value.text())
        self.settings.setValue("latest_item_value",
                               self.latest_item_value.text())

    def update_prices_time(self):
        self.last_updated_prices_value.setText(self.get_datetime())
        self.prices_progress_lock.acquire()
        self.update_prices_progress.setValue(self.num_primes)
        self.prices_progress_lock.release()

        self.settings.setValue("last_updated_prices_value",
                               self.last_updated_prices_value.text())
        self.settings.setValue("num_parts_value", self.num_parts_value.text())
        self.settings.setValue("latest_item_value",
                               self.latest_item_value.text())

    def set_update_prices_progress(self, val):
        if self.prices_progress_lock.acquire():
            self.update_prices_progress.setValue(val)
            self.prices_progress_lock.release()

    def set_update_ducats_progress(self, val):
        if self.ducats_progress_lock.acquire():
            self.update_ducats_progress.setValue(val)
            self.ducats_progress_lock.release()

    def finished_update_progress(self):
        self.update_prices_button.setEnabled(True)
        self.update_ducats_button.setEnabled(True)

    def show_preferences(self):
        self.dialog.exec_()
        self.load_settings()

    def toggle_fissure_table(self):
        if self.hide_fissure_check_box.isChecked():
            self.mission_table.hide()
        else:
            self.mission_table.show()
        self.setFixedSize(self.layout.sizeHint())

    def toggle_move_to_top(self):
        self.ocr.set_move_to_top(self.move_to_top_check_box.isChecked())

    def toggle_cropped_img(self):
        if self.hide_crop_check_box.isChecked():
            self.crop_img.hide()
        else:
            self.crop_img.show()
        self.setFixedSize(self.layout.sizeHint())

    def toggle_filtered_img(self):
        if self.hide_filter_check_box.isChecked():
            self.filter_img.hide()
        else:
            self.filter_img.show()
        self.setFixedSize(self.layout.sizeHint())
        #print("{}h,{}w".format(self.frameGeometry().height(),self.frameGeometry().width()))

    def set_sliders_range(self, x, y):
        max_values = {'x': int(x / 2), 'y': int(y / 2), 'w': x, 'h': y}
        for slider_name in max_values:
            self.sliders[slider_name].setMaximum(max_values[slider_name])
            self.sliders[slider_name].setValue(
                self.slider_default_values[slider_name])
            self.settings.setValue("{}_max", max_values[slider_name])

    def toggle_button(self):
        self.is_paused = not self.is_paused
        if self.is_paused:
            self.pause_button.setText("Resume")
        else:
            self.pause_button.setText("Pause")
        if self.ocr is not None:
            if self.is_paused:
                self.ocr.save_screenshot()
                self.ocr.skip_screenshot = True
            else:
                self.ocr.skip_screenshot = False

    def clear_table(self):
        self.table.clearSelection()
        self.table.clearContents()
        self.filled_rows = 0
        #self.table.setRowCount(self.filled_rows)

    def is_plat_preferred(self):
        return self.plat_check_box.isChecked()

    def insert_table_row(self, row):
        for i in range(3):
            self.table.setItem(self.filled_rows, i,
                               QTableWidgetItem(str(row[i])))

        self.filled_rows = self.filled_rows + 1
        #self.table.setRowCount(self.filled_rows)

    def update_mission_table(self, missions):
        self.missions = list(missions)
        cur_time = time.time()
        for i in range(len(missions)):
            for j in range(3):
                self.mission_table.setItem(
                    i, j, QTableWidgetItem(str(self.missions[i][j])))

            self.mission_table.setItem(
                i, 3,
                QTableWidgetItem(
                    self.get_duration_str(self.missions[i][3] - cur_time)))
            if self.missions[i][0] in self.hidden_relics:
                self.mission_table.setRowHidden(i, True)
            if self.missions[i][2] in self.hidden_missions:
                self.mission_table.setRowHidden(i, True)
            else:
                self.mission_table.setRowHidden(i, False)

        self.mission_table.setRowCount(len(self.missions) - 1)

    def update_mission_table_time(self):
        cur_time = time.time()
        needs_update = False
        for i in range(len(self.missions)):
            self.mission_table.setItem(
                i, 3,
                QTableWidgetItem(
                    self.get_duration_str(self.missions[i][3] - cur_time)))
            if self.missions[i][3] - cur_time < 0:
                needs_update = True
        if needs_update:
            self.api.filter_expired_missions()

    def update_mission_table_hidden(self):
        for i in range(len(self.missions)):
            if self.missions[i][0] in self.hidden_relics:
                self.mission_table.setRowHidden(i, True)
            elif self.missions[i][2] in self.hidden_missions:
                self.mission_table.setRowHidden(i, True)
            else:
                self.mission_table.setRowHidden(i, False)

    def get_duration_str(self, duration):
        m, s = divmod(int(duration), 60)
        h, m = divmod(m, 60)
        return '{:d}:{:02d}:{:02d}'.format(h, m, s)

    def set_ocr_connection(self, ocr):
        for slider_name in self.slider_names:
            self.sliders[slider_name].valueChanged.connect(
                partial(self.set_ocr_crop, ocr, slider_name))
        self.ocr = ocr
        self.market_api = MarketReader(ocr=self.ocr, gui=self)

    def set_api(self, wf_api):
        self.api = wf_api
        self.make_hide_missions_box(self.api.mission_types)

    def set_hidden_relic(self, relic):
        if self.hide_relics[relic].isChecked():
            self.hidden_relics.add(relic)
        else:
            self.hidden_relics.remove(relic)
        self.update_mission_table_hidden()

    def set_ocr_crop(self, ocr, dim, val):
        if dim == 'Screencap (hz)' or dim == 'd':
            val = val / 4
        self.slider_values[dim].setNum(val)
        if val < 0 or val > 100000 or val is None:
            return
        if dim == 'x':
            ocr.set_x_offset(val)
        if dim == 'y':
            ocr.set_y_offset(val)
        if dim == 'w':
            ocr.set_w(val)
        if dim == 'h':
            ocr.set_h(val)
        if dim == 'v1':
            ocr.set_v1(val)
        if dim == 'v2':
            ocr.set_v2(val)
        if dim == 'd':
            self.ocr.set_diff_threshold(val / 4)
        if dim == 'Screencap (hz)':
            ocr.set_interval(1 / val)
        if dim == 'Fissure (s)':
            self.api.set_rate(val)
        if dim == 'API Threads':
            self.market_api.set_num_threads(val)

    #def select_max(self):
    #    # TODO doesnt work
    #    self.table.clearSelection()
    #    self.table.selectRow(self.max_row)

    def update_filtered(self, filtered):
        filtered_shape = None
        if not self.hide_filter_check_box.isChecked():
            filtered_shape = filtered.shape
            h, w = filtered.shape
            bytes_per_line = w
            filtered_pix = QPixmap(
                QImage(filtered, w, h, bytes_per_line,
                       QImage.Format_Grayscale8))
            filtered_pix = filtered_pix.scaled(908, 70, Qt.KeepAspectRatio)
            self.image_label2.setPixmap(filtered_pix)
        #self.update_window_size(None, filtered_shape)

    def update_screenshot(self, screenshot):
        screenshot_shape = None
        if not self.hide_crop_check_box.isChecked():
            screenshot_shape = screenshot.shape
            h, w, ch = screenshot.shape
            bytes_per_line = ch * w
            screenshot_pix = QPixmap(
                QImage(screenshot, w, h, bytes_per_line, QImage.Format_RGB888))
            screenshot_pix = screenshot_pix.scaled(908, 70, Qt.KeepAspectRatio)
            self.image_label.setPixmap(screenshot_pix)
        #self.update_window_size(screenshot_shape, None)

    def update_window_size(self, screenshot_shape, filtered_shape):
        should_update = False
        if screenshot_shape is not None and screenshot_shape == self.old_screenshot_shape:
            self.old_screenshot_shape = screenshot_shape
            should_update = True
        if filtered_shape is not None and filtered_shape == self.old_filtered_shape:
            self.old_filtered_shape = filtered_shape
            should_update = True
        if should_update:
            self.setFixedSize(self.layout.sizeHint())

    def __exit__(self):
        self.market_api.exit_now = True
        self.ocr.exit_now = True
예제 #48
0
class HighpassExtension(Extension):
    def __init__(self, parent):
        super().__init__(parent)

    def setup(self):
        pass

    def createActions(self, window):
        action = window.createAction("high_pass_filter", i18n("High Pass"))
        action.triggered.connect(self.showDialog)

    def showDialog(self):
        doc = Application.activeDocument()
        if doc is None:
            QMessageBox.information(Application.activeWindow().qwindow(),
                                    i18n("High Pass Filter"),
                                    i18n("There is no active image."))
            return

        self.dialog = QDialog(Application.activeWindow().qwindow())

        self.intRadius = QSpinBox()
        self.intRadius.setValue(10)
        self.intRadius.setRange(2, 200)

        self.cmbMode = QComboBox()
        self.cmbMode.addItems([
            "Color", "Preserve DC", "Greyscale", "Greyscale, Apply Chroma",
            "Redrobes"
        ])
        self.keepOriginal = QCheckBox(i18n("Keep original layer"))
        self.keepOriginal.setChecked(True)
        form = QFormLayout()
        form.addRow(i18n("Filter radius:"), self.intRadius)
        form.addRow(i18n("Mode:"), self.cmbMode)
        form.addRow("", self.keepOriginal)

        self.buttonBox = QDialogButtonBox(self.dialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.accepted.connect(self.dialog.accept)
        self.buttonBox.accepted.connect(self.highpass)
        self.buttonBox.rejected.connect(self.dialog.reject)

        vbox = QVBoxLayout(self.dialog)
        vbox.addLayout(form)
        vbox.addWidget(self.buttonBox)

        self.dialog.show()
        self.dialog.activateWindow()
        self.dialog.exec_()

    def highpass(self):
        # XXX: Start undo macro
        image = Application.activeDocument()
        original = image.activeNode()
        working_layer = original

        # We can only highpass on paint layers
        if self.keepOriginal.isChecked() or original.type() != "paintlayer":
            working_layer = image.createNode("working", "paintlayer")
            working_layer.setColorSpace(original.colorModel(),
                                        original.colorSpace(),
                                        original.profile())
            working_layer.writeBytes(
                original.readBytes(0, 0, image.width(), image.height()), 0, 0,
                image.width(), image.height())

            # XXX: Unimplemented:
            original.parentNode().addChildNode(working_layer, original)

        image.setActiveNode(working_layer)
        colors_layer = None

        # if keeping colors
        if (self.cmbMode.currentIndex() == 1
                or self.cmbMode.currentIndex() == 3):
            # XXX: Unimplemented:
            colors_layer = working_layer.duplicate()
            colors_layer.setName("colors")
            # XXX: Unimplemented:
            original.parentNode().addChildNode(working_layer, colors_layer)

        # if greyscale, desature
        if (self.cmbMode.currentIndex() == 2
                or self.cmbMode.currentIndex() == 3):
            filter = Application.filter("desaturate")
            filter.apply(working_layer, 0, 0, image.width(), image.height())

        # Duplicate on top and blur
        blur_layer = working_layer.duplicate()
        blur_layer.setName("blur")
        # XXX: Unimplemented:
        original.parentNode().addChildNode(blur_layer, working_layer)

        # blur
        filter = Application.filter("gaussian blur")
        filter_configuration = filter.configuration()
        filter_configuration.setProperty("horizRadius", self.intRadius.value())
        filter_configuration.setProperty("vertRadius", self.intRadius.value())
        filter_configuration.setProperty("lockAspect", True)
        filter.setConfiguration(filter_configuration)
        filter.apply(blur_layer, 0, 0, image.width(), image.height())

        if self.cmbMode.currentIndex() <= 3:
            blur_layer.setBlendingMode("grain_extract")
            working_layer = image.mergeDown(blur_layer)

            # if preserve chroma, change set the mode to value and
            # merge down with the layer we kept earlier.
            if self.cmbMode.currentIndex() == 3:
                working_layer.setBlendingMode("value")
                working_layer = image.mergeDown(working_layer)

            # if preserve DC, change set the mode to overlay and merge
            # down with the average colour of the layer we kept
            # earlier.
            if self.cmbMode.currentIndex() == 1:
                # get the average color of the entire image
                # clear the colors layer to the given color
                working_layer = image.mergeDown(working_layer)

        else:  # Mode == 4, RedRobes
            image.setActiveNode(blur_layer)
예제 #49
0
class Example(QWidget):
    """
    Example is the main window widget.
    """
    def __init__(self):
        """
        Called when the Example class is created. This function simply calls self.initUI() before initialising the
        following global variables.
        """
        super().__init__()

        self.initUI()
        # global variables initialised here here
        self.proteinFile = ""
        self.peptideFile = ""
        # initialise threadpool
        self.threadpool = QThreadPool()

        self.outputPath = None

    def initUI(self):
        """
        Called from the initialiser function this function creates the grid layout for the window, calls the
        function to create and add all the widgets to the window and displays the window in the centre of the display.
        :return:
        """

        self.grid = QGridLayout()
        self.setLayout(self.grid)

        self.initialiseWidgets()

        self.move(300, 150)
        self.setWindowTitle('Reverse Splicer')
        self.show()

    def closeEvent(self, event):
        """
        Called automatically on click of the exit button. This function is configured to test if the system is being
        run on windows or mac, and uses the appropriate command to close the window and kill all processes which were
        generated by the program.

        :param event: details that close event is taking place.
        :return:
        """
        print('closed')
        # windows close command
        if platform.system() == 'Windows':
            os.system('taskkill /f /fi "WINDOWTITLE eq Reverse Splicer" /t')
        # mac close command
        else:
            os.system(
                "ps aux |grep reverseSpliceGUI | grep -v 'pattern_of_process_you_dont_want_to_kill' | awk '{print $2}' |xargs kill"
            )

    def initialiseWidgets(self):
        """
        Called from self.initUI(), this function creates all the required widgets and adds them to the main window's
        grid layout.
        :return:
        """
        self.importProtein = QPushButton('Import Protein Fasta')
        self.grid.addWidget(self.importProtein, 1, 1)
        self.importProtein.clicked.connect(self.uploadFile)

        self.importPeptide = QPushButton('Import Peptide Fasta')
        self.grid.addWidget(self.importPeptide, 2, 1)
        self.importPeptide.clicked.connect(self.uploadFile)

        self.generateOutput = QPushButton('Generate Output')
        self.generateOutput.setEnabled(False)
        self.grid.addWidget(self.generateOutput, 11, 1)
        self.generateOutput.clicked.connect(self.outputCheck)

        self.linCheckbox = QCheckBox('Linear')
        self.linCheckbox.setEnabled(False)
        self.linCheckbox.stateChanged.connect(self.enableOutput)
        self.cisCheckbox = QCheckBox('Cis')
        self.cisCheckbox.setEnabled(False)
        self.cisCheckbox.stateChanged.connect(self.enableOutput)
        self.transCheckbox = QCheckBox('Trans')
        self.transCheckbox.setEnabled(False)
        self.transCheckbox.stateChanged.connect(self.enableOutput)
        self.overlapCheckbox = QCheckBox('Cis Overlap Off')
        self.overlapCheckbox.setEnabled(False)
        self.minTransLen = QComboBox()
        self.minTransLabel = QLabel("Min Trans Cleavage Length:")
        for i in range(2, 9):
            self.minTransLen.addItem(str(i))
        self.minTransLen.setEnabled(False)
        self.minTransLabel.setEnabled(False)
        self.maxDist = QComboBox()
        self.maxDistLabel = QLabel("Max Distance Cis Cleavages: ")
        self.maxDist.addItem('None')
        for i in range(1, 26):
            self.maxDist.addItem(str(i))
        self.maxDist.setEnabled(False)
        self.maxDistLabel.setEnabled(False)
        self.grid.addWidget(self.linCheckbox, 3, 1)
        self.grid.addWidget(self.cisCheckbox, 4, 1)
        self.grid.addWidget(self.transCheckbox, 5, 1)
        self.grid.addWidget(self.overlapCheckbox, 6, 1)
        self.grid.addWidget(self.maxDistLabel, 7, 1)
        self.grid.addWidget(self.maxDist, 8, 1)
        self.grid.addWidget(self.minTransLen, 10, 1)
        self.grid.addWidget(self.minTransLabel, 9, 1)

    def uploadFile(self):
        """
        Called on click of the self.importProtein or self.importPeptide buttons, this function opens a window for the
        user to select a file to upload to the program. The function checks that a Fasta file has been uploaded, and
        then checks that the sequences in the file resemble that of a protein or peptide file. If the files contain
        sequence of unexpected length, a message box is presented informing the user to check their input.
        Once a successful input is selected, the path is stored in self.peptideFile or self.proteinFile depending on
        the nature of the input. Lastly, the function checks if both required files have been uploaded, and if so
        enables the remaining user inputs.
        :return:
        """
        fname = QFileDialog.getOpenFileName(self, 'Open File', '/home/')
        if fname[0][-5:] == 'fasta':
            if self.sender() == self.importProtein:
                # check that the input contains suitable sequence lengths for a protein
                with open(fname[0], "rU") as handle:
                    counter = 0
                    totalLen = 0
                    for record in SeqIO.parse(handle, 'fasta'):
                        if counter == 100:
                            break
                        lngth = len(str(record.seq))
                        totalLen += lngth
                        counter += 1
                # Calculate aveLen of initial sequences and ask if it is the correct input file if aveLen is less than 30.
                aveLen = totalLen / counter
                if aveLen < 30:
                    response = QMessageBox.question(
                        self, 'Message',
                        'The average length of the initial protein sequences is only: '
                        + str(round(aveLen, 1)) +
                        '. Are you sure this is the correct protein file?')
                    if response == QMessageBox.Yes:
                        pass
                    else:
                        return
                # If it passes the aveLen check, we reach here and fasta file us uploaded.
                self.proteinFile = fname[0]
                QMessageBox.about(
                    self, 'Message',
                    'Protein input fasta successfully uploaded!')
            else:
                # check that the input contains suitable sequence lengths for a peptide
                with open(fname[0], "rU") as handle:
                    counter = 0
                    totalLen = 0
                    for record in SeqIO.parse(handle, 'fasta'):
                        if counter == 100:
                            break
                        lngth = len(str(record.seq))
                        totalLen += lngth
                        counter += 1
                # Calculate aveLen of initial sequences and ask if it is the correct input file if aveLen is greater than 20.
                aveLen = totalLen / counter
                if aveLen > 20:
                    response = QMessageBox.question(
                        self, 'Message',
                        'The average length of the initial peptide sequences is: '
                        + str(round(aveLen, 1)) +
                        '. Are you sure this is the correct peptide file?')
                    if response == QMessageBox.Yes:
                        pass
                    else:
                        return
                # If it passes the aveLen check, we reach here and fasta file us uploaded.
                self.peptideFile = fname[0]
                QMessageBox.about(
                    self, 'Message',
                    'Peptide input fasta successfully uploaded!')
        if self.proteinFile == "" or self.peptideFile == "":
            self.linCheckbox.setEnabled(False)
            self.cisCheckbox.setEnabled(False)
            self.transCheckbox.setEnabled(False)
        else:
            self.linCheckbox.setEnabled(True)
            self.cisCheckbox.setEnabled(True)
            self.transCheckbox.setEnabled(True)

    def getOutputPath(self):
        """
        Called after the self.generateOutput button is clicked and the user confirms their input. This function opens a
        window to select a file location to save the output to, and if valid path is selected opens a window to input
        the file name.
        """
        # opens a window to select file location.
        self.outputPath = str(
            QFileDialog.getExistingDirectory(self, "Select Directory"))

        # if no outout path is returned, simply return to the main GUI and the user can choose to recommence the file location
        # selection process if they desire.
        if self.outputPath == '':
            return
        # else if a valid path is selected, bring up a dialog to input the file name
        else:
            self.filePathDialog()

    def filePathDialog(self):
        """
        Called by self.getOutputPath(), this function initialises and shows the file name pop-up box.
        """
        self.outputNameBox = QGroupBox('Output Name')
        self.outputNameLayout = QFormLayout()
        self.outputNameLayout.addRow(QLabel("Add a name for the output file."))
        self.outputNameLayout.addRow(
            QLabel('Banned characters: \ / : * " < > |'))
        self.fileName = QLineEdit()
        self.fileName.textChanged[str].connect(self.nameChecker)
        self.button = QPushButton("Create Output")
        self.valid = QLabel("Valid")
        self.button.clicked.connect(self.returnPath)
        self.outputNameLayout.addRow(self.fileName, self.valid)
        self.outputNameLayout.addRow(self.button)
        self.outputNameBox.setLayout(self.outputNameLayout)
        self.outputNameBox.show()

    def nameChecker(self, input):
        """
        Called by self.filePathDialog, this function is called every time the file name lineEdit is updated. It takes
        the param input, which is the text in the lineEdit, and checks if it is a valid file name. It then updates
        the validity label and enables/disables the confirm name button accordingly.
        :param input: the text in the line-edit.
        """
        # assign bannedCharacters to variables.
        bannedCharacters = set('\/:*"<>|')
        # if the input has no intersection with the banned characters it is valid. If so, update the label validity label
        # and set ensure the generate output button is concurrently enabled/disabled.
        if len(set(input).intersection(bannedCharacters)) == 0:
            self.valid.setText("Valid")
            self.button.setEnabled(True)
        else:
            self.valid.setText("Invalid")
            self.button.setEnabled(False)

    def returnPath(self):
        """
        Called when the create output button, self.button, in the file name dialog is clicked. It takes self.outputPath
        and adds the name input by the user. It lastly create the QRunnable instance required to run self.createOutput()
        in a new thread in the threadpool, starts the new thread and closes the output name dialog box.
        :return:
        """
        # create the base output file name which will be used to create the specific names for lin/cis/tras
        outputFile = self.outputPath + '/' + self.fileName.text()
        print(outputFile)
        self.outputGen = OutputGenerator(self.createOutput, outputFile,
                                         self.proteinFile, self.peptideFile,
                                         self.linFlag, self.cisFlag,
                                         self.transFlag, self.overlapFlag,
                                         int(self.minTransLength),
                                         self.maxDistance)
        self.outputGen.signals.finished.connect(self.outputFinished)
        self.threadpool.start(self.outputGen)
        self.outputLabel = QLabel("Generating Output. Please Wait!")
        self.grid.addWidget(self.outputLabel, 12, 1)
        # close the output name box.
        self.outputNameBox.close()

    def outputCheck(self):
        """
        Called on click of the self.generateOutput button, this function checks that valid peptide and protein files
        have been input by the user, and if so extracts all user input and presents them back to the user for
        confirmation. If the user confirms the inputs, self.getOutputPath() is called.
        :return:
        """
        if self.proteinFile == "" or self.peptideFile == "":
            QMessageBox.about(
                self, 'Message',
                'Please Upload a Fasta File before generating output!')
        else:

            # declare flags globally so they can be reached by returnPath() which now creates the computational process
            # to initiate the code.
            self.linFlag = self.linCheckbox.isChecked()
            self.cisFlag = self.cisCheckbox.isChecked()
            self.transFlag = self.transCheckbox.isChecked()
            self.overlapFlag = self.overlapCheckbox.isChecked()
            self.maxDistance = self.maxDist.currentText()
            self.minTransLength = self.minTransLen.currentText()

            reply = QMessageBox.question(
                self, 'Message',
                'Are these the correct files you wish to run?' + "\n" +
                "Please ensure you haven't switched the protein and peptide input."
                + '\n' + '\n' + 'Protein File: ' + self.proteinFile + '\n' +
                '\n' + 'Peptide File: ' + self.peptideFile + '\n' + '\n' +
                'Min Cleavage Length: ' + self.minTransLength + '\n' +
                'Max Distance Cis: ' + self.maxDistance + '\n' + 'Linear: ' +
                str(self.linFlag) + ', Cis: ' + str(self.cisFlag) +
                ', Trans: ' + str(self.transFlag) + '\n' + 'Overlap Off: ' +
                str(self.overlapFlag))

            if not self.maxDistance == 'None':
                self.maxDistance = int(self.maxDistance)

            if reply == QMessageBox.Yes:
                self.getOutputPath()

    def enableOutput(self):
        """
        Called each time one of the splice type checkboxes changes state. This function enables the min trans length
        widgets if trans is selected, the cis overlap and max distance widgets if cis is selected and the
        self.generateOutput button if one of cis, trans or linear is selected.
        :return:
        """
        if self.transCheckbox.isChecked():
            self.minTransLen.setEnabled(True)
            self.minTransLabel.setEnabled(True)
        else:
            self.minTransLen.setEnabled(False)
            self.minTransLabel.setEnabled(False)
        if self.cisCheckbox.isChecked():
            self.overlapCheckbox.setEnabled(True)
            self.maxDist.setEnabled(True)
            self.maxDistLabel.setEnabled(True)
        else:
            self.overlapCheckbox.setEnabled(False)
            self.maxDist.setEnabled(False)
            self.maxDistLabel.setEnabled(False)
        if self.linCheckbox.isChecked() or self.cisCheckbox.isChecked(
        ) or self.transCheckbox.isChecked():
            self.generateOutput.setEnabled(True)
        else:
            self.generateOutput.setEnabled(False)

    def createOutput(self, outputPath, proteinFile, peptideFile, linFlag,
                     cisFlag, transFlag, overlapFlag, minTrans, maxDistance):
        """
        Called as the worker function to QRunnable class OutputGenerator to initiate computation. This function
        merely passes the user inputs to generateOutput() in reverseSplice.py. This must be done within a thread to
        ensure that the GUI remains responsive while the output is being computed.

        :param outputPath: the path of the output file as selected by the user.
        :param proteinFile: the path of the protein sequence file.
        :param peptideFile: the path of the peptide sequence file.
        :param linFlag: True if the user wishes to return a file with information on where each peptide could have been
        generated from via linear splicing.
        :param cisFlag: True if the user wishes to return a file with information on where each peptide could have been
        generated from via cis splicing.
        :param transFlag: True if the user wishes to return a file with information on where each peptide could have been
        generated from via trans splicing.
        :param overlapFlag: True if the user has selected no overlap when running cis splicing.
        :param minTransLen: the minimum length a cleavage must be for it to be reported in the output file as an origin
        for a trans spliced peptide.
        :param maxDistance: the maximum distance two cleavages can be away from each other for them to combined in cis
        splicing. Will be 'None' if the user wants no maximum.
        :return:
        """
        generateOutput(outputPath, proteinFile, peptideFile, linFlag, cisFlag,
                       transFlag, overlapFlag, minTrans, maxDistance)

    def outputFinished(self):
        """
        Called when the finished signal is emitted from with the OutputGenerator QRunnable class. This function simply
        removes the label from the GUI the which communicates to the user that the output is being computed, and then
        displays a message detailing that the output has finished.
        :return:
        """
        QMessageBox.about(self, "Message", "All done!")
        self.grid.removeWidget(self.outputLabel)
        self.outputLabel.deleteLater()
        self.outputLabel = None
class DyStockSelectFilterDlg(QDialog):
    def __init__(self, data, colNames, parent=None):
        super().__init__(parent)

        self._data = data

        self._initUi(colNames)

    def _initUi(self, colNames):
        self.setWindowTitle('过滤')

        # 控件
        table = DyTableWidget(parant=None,
                              readOnly=True,
                              index=False,
                              floatCut=True,
                              autoScroll=False)
        table.setColNames(['列名', '表达式'])
        rows = [[name, 'x[{0}]'.format(i)] for i, name in enumerate(colNames)]
        table.fastAppendRows(rows)

        descriptionLabel = QLabel('过滤表达式(Python语法)')
        self._filterTextEdit = QTextEdit()
        self._newWindowCheckBox = QCheckBox('新窗口')
        self._newWindowCheckBox.setChecked(True)
        self._highlightCheckBox = QCheckBox('原窗口高亮')
        self._highlightCheckBox.setChecked(True)

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

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(table, 0, 0, 22, 1)
        grid.addWidget(self._newWindowCheckBox, 0, 1)
        grid.addWidget(self._highlightCheckBox, 0, 2)

        grid.addWidget(descriptionLabel, 1, 1)

        grid.addWidget(self._filterTextEdit, 2, 1, 20, 20)

        grid.addWidget(okPushButton, 0, 21)
        grid.addWidget(cancelPushButton, 1, 21)

        self.setLayout(grid)
        self.resize(QApplication.desktop().size().width() // 2,
                    QApplication.desktop().size().height() // 4 * 3)

    def _ok(self):
        filter = self._filterTextEdit.toPlainText().replace('\n', ' ')

        self._data['filter'] = filter
        self._data['newWindow'] = self._newWindowCheckBox.isChecked()
        self._data['highlight'] = self._highlightCheckBox.isChecked()

        self.accept()

    def _cancel(self):
        self.reject()
예제 #51
0
class FatalCrashDialog(_CrashDialog):
    """Dialog which gets shown when a fatal error occurred.

    Attributes:
        _log: The log text to display.
        _type: The type of error which occurred.
        _func: The function (top of the stack) in which the error occurred.
        _chk_history: A checkbox for the user to decide if page history should
                      be sent.
    """
    def __init__(self, debug, text, parent=None):
        self._chk_history = None
        super().__init__(debug, parent)
        self._log = text
        self.setAttribute(Qt.WA_DeleteOnClose)
        self._set_crash_info()
        self._type, self._func = parse_fatal_stacktrace(self._log)

    def _get_error_type(self):
        if self._type == 'Segmentation fault':
            return 'segv'
        else:
            return self._type

    def _get_paste_title_desc(self):
        return self._func

    def _init_text(self):
        super()._init_text()
        text = ("<b>qutebrowser was restarted after a fatal crash.</b><br/>"
                "<br/>Note: Crash reports for fatal crashes sometimes don't "
                "contain the information necessary to fix an issue. Please "
                "follow the steps in <a href='https://github.com/The-Compiler/"
                "qutebrowser/blob/master/doc/stacktrace.asciidoc'>"
                "stacktrace.asciidoc</a> to submit a stacktrace.<br/>")
        self._lbl.setText(text)

    def _init_checkboxes(self):
        """Add checkboxes to the dialog."""
        super()._init_checkboxes()
        self._chk_history = QCheckBox(
            "Include a history of the last "
            "accessed pages in the report.",
            checked=True)
        try:
            if config.val.content.private_browsing:
                self._chk_history.setChecked(False)
        except Exception:
            log.misc.exception("Error while checking private browsing mode")
        self._chk_history.toggled.connect(self._set_crash_info)
        self._vbox.addWidget(self._chk_history)

    def _gather_crash_info(self):
        self._crash_info.append(("Fault log", self._log))
        super()._gather_crash_info()
        if self._chk_history.isChecked():
            try:
                history = objreg.get('web-history').get_recent()
                self._crash_info.append(("History", ''.join(history)))
            except Exception:
                self._crash_info.append(("History", traceback.format_exc()))
예제 #52
0
class ThemeWidget(QWidget):
    def __init__(self, parent=None):
        super(ThemeWidget, self).__init__(parent)

        self.m_charts = []
        self.m_listCount = 3
        self.m_valueMax = 10
        self.m_valueCount = 7
        self.m_dataTable = self.generateRandomData(self.m_listCount,
                                                   self.m_valueMax,
                                                   self.m_valueCount)
        self.m_themeComboBox = self.createThemeBox()
        self.m_antialiasCheckBox = QCheckBox("Anti-aliasing")
        self.m_animatedComboBox = self.createAnimationBox()
        self.m_legendComboBox = self.createLegendBox()

        self.connectSignals()

        # Create the layout.
        baseLayout = QGridLayout()
        settingsLayout = QHBoxLayout()
        settingsLayout.addWidget(QLabel("Theme:"))
        settingsLayout.addWidget(self.m_themeComboBox)
        settingsLayout.addWidget(QLabel("Animation:"))
        settingsLayout.addWidget(self.m_animatedComboBox)
        settingsLayout.addWidget(QLabel("Legend:"))
        settingsLayout.addWidget(self.m_legendComboBox)
        settingsLayout.addWidget(self.m_antialiasCheckBox)
        settingsLayout.addStretch()
        baseLayout.addLayout(settingsLayout, 0, 0, 1, 3)

        # Create the charts.
        chartView = QChartView(self.createAreaChart())
        baseLayout.addWidget(chartView, 1, 0)
        self.m_charts.append(chartView)

        chartView = QChartView(self.createBarChart(self.m_valueCount))
        baseLayout.addWidget(chartView, 1, 1)
        self.m_charts.append(chartView)

        chartView = QChartView(self.createLineChart())
        baseLayout.addWidget(chartView, 1, 2)
        self.m_charts.append(chartView)

        chartView = QChartView(self.createPieChart())
        # Funny things happen if the pie slice labels no not fit the screen...
        chartView.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        baseLayout.addWidget(chartView, 2, 0)
        self.m_charts.append(chartView)

        chartView = QChartView(self.createSplineChart())
        baseLayout.addWidget(chartView, 2, 1)
        self.m_charts.append(chartView)

        chartView = QChartView(self.createScatterChart())
        baseLayout.addWidget(chartView, 2, 2)
        self.m_charts.append(chartView)

        self.setLayout(baseLayout)

        # Set the defaults.
        self.m_antialiasCheckBox.setChecked(True)
        self.updateUI()

    def connectSignals(self):
        self.m_themeComboBox.currentIndexChanged.connect(self.updateUI)
        self.m_antialiasCheckBox.toggled.connect(self.updateUI)
        self.m_animatedComboBox.currentIndexChanged.connect(self.updateUI)
        self.m_legendComboBox.currentIndexChanged.connect(self.updateUI)

    def generateRandomData(self, listCount, valueMax, valueCount):
        random.seed()

        dataTable = []

        for i in range(listCount):
            dataList = []
            yValue = 0.0
            f_valueCount = float(valueCount)

            for j in range(valueCount):
                yValue += random.uniform(0, valueMax) / f_valueCount
                value = QPointF(
                    j + random.random() * self.m_valueMax / f_valueCount,
                    yValue)
                label = "Slice " + str(i) + ":" + str(j)
                dataList.append((value, label))

            dataTable.append(dataList)

        return dataTable

    def createThemeBox(self):
        themeComboBox = QComboBox()

        themeComboBox.addItem("Light", QChart.ChartThemeLight)
        themeComboBox.addItem("Blue Cerulean", QChart.ChartThemeBlueCerulean)
        themeComboBox.addItem("Dark", QChart.ChartThemeDark)
        themeComboBox.addItem("Brown Sand", QChart.ChartThemeBrownSand)
        themeComboBox.addItem("Blue NCS", QChart.ChartThemeBlueNcs)
        themeComboBox.addItem("High Contrast", QChart.ChartThemeHighContrast)
        themeComboBox.addItem("Blue Icy", QChart.ChartThemeBlueIcy)

        return themeComboBox

    def createAnimationBox(self):
        animationComboBox = QComboBox()

        animationComboBox.addItem("No Animations", QChart.NoAnimation)
        animationComboBox.addItem("GridAxis Animations",
                                  QChart.GridAxisAnimations)
        animationComboBox.addItem("Series Animations", QChart.SeriesAnimations)
        animationComboBox.addItem("All Animations", QChart.AllAnimations)

        return animationComboBox

    def createLegendBox(self):
        legendComboBox = QComboBox()

        legendComboBox.addItem("No Legend ", 0)
        legendComboBox.addItem("Legend Top", Qt.AlignTop)
        legendComboBox.addItem("Legend Bottom", Qt.AlignBottom)
        legendComboBox.addItem("Legend Left", Qt.AlignLeft)
        legendComboBox.addItem("Legend Right", Qt.AlignRight)

        return legendComboBox

    def createAreaChart(self):
        chart = QChart()
        chart.setTitle("Area chart")

        # The lower series is initialized to zero values.
        lowerSeries = None
        y_points = []

        for i, data_list in enumerate(self.m_dataTable):
            upperSeries = QLineSeries(chart)
            for j, (value, _) in enumerate(data_list):
                y = value.y()

                if lowerSeries is None:
                    upperSeries.append(QPointF(j, y))
                    y_points.append(y)
                else:
                    new_y = y_points[i] + y
                    upperSeries.append(QPointF(j, new_y))
                    y_points[j] += new_y

            area = QAreaSeries(upperSeries, lowerSeries)
            area.setName("Series " + str(i))
            chart.addSeries(area)
            lowerSeries = upperSeries

        chart.createDefaultAxes()

        return chart

    def createBarChart(self, valueCount):
        chart = QChart()
        chart.setTitle("Bar chart")

        series = QStackedBarSeries(chart)

        for i, data_list in enumerate(self.m_dataTable):
            set = QBarSet("Bar set " + str(i))
            for value, _ in data_list:
                set << value.y()

            series.append(set)

        chart.addSeries(series)
        chart.createDefaultAxes()

        return chart

    def createLineChart(self):
        chart = QChart()
        chart.setTitle("Line chart")

        for i, data_list in enumerate(self.m_dataTable):
            series = QLineSeries(chart)
            for value, _ in data_list:
                series.append(value)

            series.setName("Series " + str(i))
            chart.addSeries(series)

        chart.createDefaultAxes()

        return chart

    def createPieChart(self):
        chart = QChart()
        chart.setTitle("Pie chart")

        pieSize = 1.0 / len(self.m_dataTable)

        for i, data_list in enumerate(self.m_dataTable):
            series = QPieSeries(chart)
            for value, label in data_list:
                slice = series.append(label, value.y())
                if len(series) == 1:
                    slice.setLabelVisible()
                    slice.setExploded()

            hPos = (pieSize / 2) + (i / float(len(self.m_dataTable)))
            series.setPieSize(pieSize)
            series.setHorizontalPosition(hPos)
            series.setVerticalPosition(0.5)

            chart.addSeries(series)

        return chart

    def createSplineChart(self):
        chart = QChart()
        chart.setTitle("Spline chart")

        for i, data_list in enumerate(self.m_dataTable):
            series = QSplineSeries(chart)
            for value, _ in data_list:
                series.append(value)

            series.setName("Series " + str(i))
            chart.addSeries(series)

        chart.createDefaultAxes()

        return chart

    def createScatterChart(self):
        chart = QChart()
        chart.setTitle("Scatter chart")

        for i, data_list in enumerate(self.m_dataTable):
            series = QScatterSeries(chart)
            for value, _ in data_list:
                series.append(value)

            series.setName("Series " + str(i))
            chart.addSeries(series)

        chart.createDefaultAxes()

        return chart

    @pyqtSlot()
    def updateUI(self):
        theme = self.m_themeComboBox.itemData(
            self.m_themeComboBox.currentIndex())

        if self.m_charts[0].chart().theme() != theme:
            for chartView in self.m_charts:
                chartView.chart().setTheme(theme)

            pal = self.window().palette()

            if theme == QChart.ChartThemeLight:
                pal.setColor(QPalette.Window, QColor(0xf0f0f0))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            elif theme == QChart.ChartThemeDark:
                pal.setColor(QPalette.Window, QColor(0x121218))
                pal.setColor(QPalette.WindowText, QColor(0xd6d6d6))
            elif theme == QChart.ChartThemeBlueCerulean:
                pal.setColor(QPalette.Window, QColor(0x40434a))
                pal.setColor(QPalette.WindowText, QColor(0xd6d6d6))
            elif theme == QChart.ChartThemeBrownSand:
                pal.setColor(QPalette.Window, QColor(0x9e8965))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            elif theme == QChart.ChartThemeBlueNcs:
                pal.setColor(QPalette.Window, QColor(0x018bba))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            elif theme == QChart.ChartThemeHighContrast:
                pal.setColor(QPalette.Window, QColor(0xffab03))
                pal.setColor(QPalette.WindowText, QColor(0x181818))
            elif theme == QChart.ChartThemeBlueIcy:
                pal.setColor(QPalette.Window, QColor(0xcee7f0))
                pal.setColor(QPalette.WindowText, QColor(0x404044))
            else:
                pal.setColor(QPalette.Window, QColor(0xf0f0f0))
                pal.setColor(QPalette.WindowText, QColor(0x404044))

            self.window().setPalette(pal)

        checked = self.m_antialiasCheckBox.isChecked()
        for chartView in self.m_charts:
            chartView.setRenderHint(QPainter.Antialiasing, checked)

        options = QChart.AnimationOptions(
            self.m_animatedComboBox.itemData(
                self.m_animatedComboBox.currentIndex()))

        if self.m_charts[0].chart().animationOptions() != options:
            for chartView in self.m_charts:
                chartView.chart().setAnimationOptions(options)

        alignment = self.m_legendComboBox.itemData(
            self.m_legendComboBox.currentIndex())

        for chartView in self.m_charts:
            legend = chartView.chart().legend()

            if alignment == 0:
                legend.hide()
            else:
                legend.setAlignment(Qt.Alignment(alignment))
                legend.show()
예제 #53
0
class ComicsProjectSetupWizard():
    setupDictionary = {}
    projectDirectory = ""

    def __init__(self):
        # super().__init__(parent)
        # Search the location of the script for the two lists that are used with the projectname generator.
        mainP = Path(__file__).parent
        self.generateListA = []
        self.generateListB = []
        if Path(mainP / "projectGenLists" / "listA.txt").exists():
            for l in open(str(mainP / "projectGenLists" / "listA.txt"), "r"):
                if l.isspace() == False:
                    self.generateListA.append(l.strip("\n"))
        if Path(mainP / "projectGenLists" / "listB.txt").exists():
            for l in open(str(mainP / "projectGenLists" / "listB.txt"), "r"):
                if l.isspace() == False:
                    self.generateListB.append(l.strip("\n"))

    def showDialog(self):
        # Initialise the setup directory empty toavoid exceptions.
        self.setupDictionary = {}

        # ask for a project directory.
        self.projectDirectory = QFileDialog.getExistingDirectory(
            caption=i18n("Where should the comic project go?"),
            options=QFileDialog.ShowDirsOnly)
        if os.path.exists(self.projectDirectory) is False:
            return
        self.pagesDirectory = os.path.relpath(self.projectDirectory,
                                              self.projectDirectory)
        self.exportDirectory = os.path.relpath(self.projectDirectory,
                                               self.projectDirectory)

        wizard = QWizard()
        wizard.setWindowTitle(i18n("Comic Project Setup"))
        wizard.setOption(QWizard.IndependentPages, True)

        # Set up the UI for the wizard
        basicsPage = QWizardPage()
        basicsPage.setTitle(i18n("Basic Comic Project Settings"))
        formLayout = QFormLayout()
        basicsPage.setLayout(formLayout)
        projectLayout = QHBoxLayout()
        self.lnProjectName = QLineEdit()
        basicsPage.registerField("Project Name*", self.lnProjectName)
        self.lnProjectName.setToolTip(
            i18n(
                "A Project name. This can be different from the eventual title"
            ))
        btnRandom = QPushButton()
        btnRandom.setText(i18n("Generate"))
        btnRandom.setToolTip(
            i18n(
                "If you cannot come up with a project name, our highly sophisticated project name generator will serve to give a classy yet down to earth name."
            ))
        btnRandom.clicked.connect(self.slot_generate)
        projectLayout.addWidget(self.lnProjectName)
        projectLayout.addWidget(btnRandom)
        lnConcept = QLineEdit()
        lnConcept.setToolTip(
            i18n(
                "What is your comic about? This is mostly for your own convenience so don't worry about what it says too much."
            ))
        self.cmbLanguage = comics_metadata_dialog.language_combo_box()
        self.cmbLanguage.setToolTip(i18n("The main language the comic is in"))
        self.cmbLanguage.setEntryToCode(
            str(QLocale.system().name()).split("_")[0])
        self.lnProjectDirectory = QLabel(self.projectDirectory)
        self.chkMakeProjectDirectory = QCheckBox(
            i18n("Make a new directory with the project name."))
        self.chkMakeProjectDirectory.setToolTip(
            i18n(
                "This allows you to select a generic comics project directory, in which a new folder will be made for the project using the given project name."
            ))
        self.chkMakeProjectDirectory.setChecked(True)
        self.lnPagesDirectory = QLineEdit()
        self.lnPagesDirectory.setText(i18n("pages"))
        self.lnPagesDirectory.setToolTip(
            i18n(
                "The name for the folder where the pages are contained. If it doesn't exist, it will be created."
            ))
        self.lnExportDirectory = QLineEdit()
        self.lnExportDirectory.setText(i18n("export"))
        self.lnExportDirectory.setToolTip(
            i18n(
                "The name for the folder where the export is put. If it doesn't exist, it will be created."
            ))
        self.lnTemplateLocation = QLineEdit()
        self.lnTemplateLocation.setText(i18n("templates"))
        self.lnTemplateLocation.setToolTip(
            i18n(
                "The name for the folder where the page templates are sought in."
            ))
        formLayout.addRow(i18n("Comic Concept:"), lnConcept)
        formLayout.addRow(i18n("Project Name:"), projectLayout)
        formLayout.addRow(i18n("Main Language:"), self.cmbLanguage)

        buttonMetaData = QPushButton(i18n("Meta Data"))
        buttonMetaData.clicked.connect(self.slot_edit_meta_data)

        wizard.addPage(basicsPage)

        foldersPage = QWizardPage()
        foldersPage.setTitle(i18n("Folder names and other."))
        folderFormLayout = QFormLayout()
        foldersPage.setLayout(folderFormLayout)
        folderFormLayout.addRow(i18n("Project Directory:"),
                                self.lnProjectDirectory)
        folderFormLayout.addRow("", self.chkMakeProjectDirectory)
        folderFormLayout.addRow(i18n("Pages Directory"), self.lnPagesDirectory)
        folderFormLayout.addRow(i18n("Export Directory"),
                                self.lnExportDirectory)
        folderFormLayout.addRow(i18n("Template Directory"),
                                self.lnTemplateLocation)
        folderFormLayout.addRow("", buttonMetaData)
        wizard.addPage(foldersPage)

        # Execute the wizard, and after wards...
        if (wizard.exec_()):

            # First get the directories, check if the directories exist, and oterwise make them.
            self.pagesDirectory = self.lnPagesDirectory.text()
            self.exportDirectory = self.lnExportDirectory.text()
            self.templateLocation = self.lnTemplateLocation.text()
            projectPath = Path(self.projectDirectory)
            # Only make a project directory if the checkbox for that has been checked.
            if self.chkMakeProjectDirectory.isChecked():
                projectPath = projectPath / self.lnProjectName.text()
                if projectPath.exists() is False:
                    projectPath.mkdir()
                self.projectDirectory = str(projectPath)
            if Path(projectPath / self.pagesDirectory).exists() is False:
                Path(projectPath / self.pagesDirectory).mkdir()
            if Path(projectPath / self.exportDirectory).exists() is False:
                Path(projectPath / self.exportDirectory).mkdir()
            if Path(projectPath / self.templateLocation).exists() is False:
                Path(projectPath / self.templateLocation).mkdir()

            # Then store the information into the setup diactionary.
            self.setupDictionary["projectName"] = self.lnProjectName.text()
            self.setupDictionary["concept"] = lnConcept.text()
            self.setupDictionary["language"] = str(
                self.cmbLanguage.codeForCurrentEntry())
            self.setupDictionary["pagesLocation"] = self.pagesDirectory
            self.setupDictionary["exportLocation"] = self.exportDirectory
            self.setupDictionary["templateLocation"] = self.templateLocation

            # Finally, write the dictionary into the json file.
            self.writeConfig()

    """
    This calls up the metadata dialog, for if people already have information they want to type in
    at the setup stage. Not super likely, but the organisation and management aspect of the comic
    manager means we should give the option to organise as smoothly as possible.
    """

    def slot_edit_meta_data(self):
        dialog = comics_metadata_dialog.comic_meta_data_editor()
        self.setupDictionary["language"] = str(
            self.cmbLanguage.codeForCurrentEntry())
        dialog.setConfig(self.setupDictionary)
        dialog.setConfig(self.setupDictionary)
        if (dialog.exec_() == QDialog.Accepted):
            self.setupDictionary = dialog.getConfig(self.setupDictionary)
            self.cmbLanguage.setEntryToCode(self.setupDictionary["language"])

    """
    Write the actual config to the chosen project directory.
    """

    def writeConfig(self):
        print("CPMT: writing comic configuration...")
        print(self.projectDirectory)
        configFile = open(os.path.join(self.projectDirectory,
                                       "comicConfig.json"),
                          "w",
                          newline="",
                          encoding="utf-16")
        json.dump(self.setupDictionary,
                  configFile,
                  indent=4,
                  sort_keys=True,
                  ensure_ascii=False)
        configFile.close()
        print("CPMT: done")

    """
    As you may be able to tell, the random projectname generator is hardly sophisticated.
    It picks a word from a list of names of figures from Greek Mythology, and a name from a list
    of vegetables and fruits and combines the two camelcased.
    It makes for good codenames at the least.
    """

    def slot_generate(self):
        if len(self.generateListA) > 0 and len(self.generateListB) > 0:
            nameA = self.generateListA[random.randint(
                0,
                len(self.generateListA) - 1)]
            nameB = self.generateListB[random.randint(
                0,
                len(self.generateListB) - 1)]
            self.lnProjectName.setText(str(nameA.title() + nameB.title()))
class NetworkChoiceLayout(object):
    def __init__(self, network: Network, config: 'SimpleConfig', wizard=False):
        self.network = network
        self.config = config
        self.tor_proxy = None

        self.tabs = tabs = QTabWidget()
        proxy_tab = QWidget()
        blockchain_tab = QWidget()
        tabs.addTab(blockchain_tab, _('Overview'))
        tabs.addTab(proxy_tab, _('Proxy'))

        fixed_width_hostname = 24 * char_width_in_lineedit()
        fixed_width_port = 6 * char_width_in_lineedit()

        # Proxy tab
        grid = QGridLayout(proxy_tab)
        grid.setSpacing(8)

        # proxy setting
        self.proxy_cb = QCheckBox(_('Use proxy'))
        self.proxy_cb.clicked.connect(self.check_disable_proxy)
        self.proxy_cb.clicked.connect(self.set_proxy)
        self.proxy_cb.setEnabled(self.config.is_modifiable('proxy'))

        self.proxy_mode = QComboBox()
        self.proxy_mode.addItems(['SOCKS4', 'SOCKS5'])
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(fixed_width_hostname)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(fixed_width_port)
        self.proxy_user = QLineEdit()
        self.proxy_user.setPlaceholderText(_("Proxy user"))
        self.proxy_password = PasswordLineEdit()
        self.proxy_password.setPlaceholderText(_("Password"))
        self.proxy_password.setFixedWidth(fixed_width_port)

        self.proxy_mode.currentIndexChanged.connect(self.set_proxy)
        self.proxy_host.editingFinished.connect(self.set_proxy)
        self.proxy_port.editingFinished.connect(self.set_proxy)
        self.proxy_user.editingFinished.connect(self.set_proxy)
        self.proxy_password.editingFinished.connect(self.set_proxy)

        self.proxy_mode.currentIndexChanged.connect(
            self.proxy_settings_changed)
        self.proxy_host.textEdited.connect(self.proxy_settings_changed)
        self.proxy_port.textEdited.connect(self.proxy_settings_changed)
        self.proxy_user.textEdited.connect(self.proxy_settings_changed)
        self.proxy_password.textEdited.connect(self.proxy_settings_changed)

        self.tor_cb = QCheckBox(_("Use Tor Proxy"))
        self.tor_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_cb.hide()
        self.tor_cb.clicked.connect(self.use_tor_proxy)

        self.tor_auto_on_cb = QCheckBox(self.network.TOR_AUTO_ON_MSG)
        self.tor_auto_on_cb.setIcon(read_QIcon("tor_logo.png"))
        self.tor_auto_on_cb.setChecked(self.config.get('tor_auto_on', True))
        self.tor_auto_on_cb.clicked.connect(self.use_tor_auto_on)

        self.fiat_bypass_tor_cb = QCheckBox(self.network.FIAT_BYPASS_TOR_MSG)
        fiat_bypass_tor = self.config.get('fiat_bypass_tor', False)
        self.fiat_bypass_tor_cb.setChecked(fiat_bypass_tor)
        self.fiat_bypass_tor_cb.clicked.connect(self.fiat_bypass_tor)

        grid.addWidget(self.tor_cb, 1, 0, 1, 3)
        grid.addWidget(self.proxy_cb, 2, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('Proxy settings apply to all connections: with Dash Electrum servers, but also with third-party services.'
                  )), 2, 4)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)
        grid.addWidget(self.proxy_user, 5, 2)
        grid.addWidget(self.proxy_password, 5, 3)
        grid.addWidget(self.tor_auto_on_cb, 6, 0, 1, 3)
        grid.addWidget(
            HelpButton(
                _('During wallet startup try to detect and use Tor Proxy.')),
            6, 4)
        grid.addWidget(self.fiat_bypass_tor_cb, 7, 0, 1, 3)
        grid.setRowStretch(8, 1)

        # Blockchain Tab
        grid = QGridLayout(blockchain_tab)
        msg = ' '.join([
            _("Dash Electrum connects to several nodes in order to download block headers and find out the longest blockchain."
              ),
            _("This blockchain is used to verify the transactions sent by your transaction server."
              )
        ])
        self.status_label = QLabel('')
        grid.addWidget(QLabel(_('Status') + ':'), 0, 0)
        grid.addWidget(self.status_label, 0, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 0, 4)

        self.autoconnect_cb = QCheckBox(_('Select server automatically'))
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))
        self.autoconnect_cb.clicked.connect(self.set_server)
        self.autoconnect_cb.clicked.connect(self.update)
        msg = ' '.join([
            _("If auto-connect is enabled, Dash Electrum will always use a server that is on the longest blockchain."
              ),
            _("If it is disabled, you have to choose a server you want to use. Dash Electrum will warn you if your server is lagging."
              )
        ])
        grid.addWidget(self.autoconnect_cb, 1, 0, 1, 3)
        grid.addWidget(HelpButton(msg), 1, 4)

        self.server_e = QLineEdit()
        self.server_e.setFixedWidth(fixed_width_hostname + fixed_width_port)
        self.server_e.editingFinished.connect(self.set_server)
        msg = _(
            "Dash Electrum sends your wallet addresses to a single server, in order to receive your transaction history."
        )
        grid.addWidget(QLabel(_('Server') + ':'), 2, 0)
        grid.addWidget(self.server_e, 2, 1, 1, 3)
        grid.addWidget(HelpButton(msg), 2, 4)

        self.height_label = QLabel('')
        msg = _('This is the height of your local copy of the blockchain.')
        grid.addWidget(QLabel(_('Blockchain') + ':'), 3, 0)
        grid.addWidget(self.height_label, 3, 1)
        grid.addWidget(HelpButton(msg), 3, 4)

        self.split_label = QLabel('')
        grid.addWidget(self.split_label, 4, 0, 1, 3)

        self.nodes_list_widget = NodesListWidget(self)
        grid.addWidget(self.nodes_list_widget, 6, 0, 1, 5)

        vbox = QVBoxLayout()
        vbox.addWidget(tabs)
        self.layout_ = vbox
        # tor detector
        self.td = td = TorDetector()
        td.found_proxy.connect(self.suggest_proxy)
        td.start()

        self.fill_in_proxy_settings()
        self.update()

    def clean_up(self):
        if self.td:
            self.td.found_proxy.disconnect()
            self.td.stop()
            self.td = None

    def check_disable_proxy(self, b):
        if not self.config.is_modifiable('proxy'):
            b = False
        for w in [
                self.proxy_mode, self.proxy_host, self.proxy_port,
                self.proxy_user, self.proxy_password
        ]:
            w.setEnabled(b)

    def enable_set_server(self):
        if self.config.is_modifiable('server'):
            enabled = not self.autoconnect_cb.isChecked()
            self.server_e.setEnabled(enabled)
        else:
            for w in [
                    self.autoconnect_cb, self.server_e, self.nodes_list_widget
            ]:
                w.setEnabled(False)

    def update(self):
        net_params = self.network.get_parameters()
        server = net_params.server
        auto_connect = net_params.auto_connect
        if not self.server_e.hasFocus():
            self.server_e.setText(server.to_friendly_name())
        self.autoconnect_cb.setChecked(auto_connect)

        height_str = "%d " % (self.network.get_local_height()) + _('blocks')
        self.height_label.setText(height_str)
        n = len(self.network.get_interfaces())
        status = _("Connected to {0} nodes.").format(n) if n > 1 else _(
            "Connected to {0} node.").format(n) if n == 1 else _(
                "Not connected")
        self.status_label.setText(status)
        chains = self.network.get_blockchains()
        if len(chains) > 1:
            chain = self.network.blockchain()
            forkpoint = chain.get_max_forkpoint()
            name = chain.get_name()
            msg = _('Chain split detected at block {0}').format(
                forkpoint) + '\n'
            msg += (_('You are following branch') if auto_connect else
                    _('Your server is on branch')) + ' ' + name
            msg += ' (%d %s)' % (chain.get_branch_size(), _('blocks'))
        else:
            msg = ''
        self.split_label.setText(msg)
        self.nodes_list_widget.update(network=self.network,
                                      servers=self.network.get_servers(),
                                      use_tor=self.tor_cb.isChecked())
        self.enable_set_server()

    def fill_in_proxy_settings(self):
        proxy_config = self.network.get_parameters().proxy
        if not proxy_config:
            proxy_config = {
                "mode": "none",
                "host": "localhost",
                "port": "9050"
            }

        b = proxy_config.get('mode') != "none"
        self.check_disable_proxy(b)
        if b:
            self.proxy_cb.setChecked(True)
            self.proxy_mode.setCurrentIndex(
                self.proxy_mode.findText(str(
                    proxy_config.get("mode").upper())))

        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))
        self.proxy_user.setText(proxy_config.get("user", ""))
        self.proxy_password.setText(proxy_config.get("password", ""))

    def layout(self):
        return self.layout_

    def follow_branch(self, chain_id):
        self.network.run_from_another_thread(
            self.network.follow_chain_given_id(chain_id))
        self.update()

    def follow_server(self, server: ServerAddr):
        self.network.run_from_another_thread(
            self.network.follow_chain_given_server(server))
        self.update()

    def accept(self):
        pass

    def set_server(self):
        net_params = self.network.get_parameters()
        try:
            server = ServerAddr.from_str_with_inference(
                str(self.server_e.text()))
            if not server: raise Exception("failed to parse")
        except Exception:
            return
        net_params = net_params._replace(
            server=server, auto_connect=self.autoconnect_cb.isChecked())
        self.network.run_from_another_thread(
            self.network.set_parameters(net_params))

    def set_proxy(self):
        net_params = self.network.get_parameters()
        if self.proxy_cb.isChecked():
            proxy = {
                'mode': str(self.proxy_mode.currentText()).lower(),
                'host': str(self.proxy_host.text()),
                'port': str(self.proxy_port.text()),
                'user': str(self.proxy_user.text()),
                'password': str(self.proxy_password.text())
            }
        else:
            proxy = None
            self.tor_cb.setChecked(False)
        net_params = net_params._replace(proxy=proxy)
        self.network.run_from_another_thread(
            self.network.set_parameters(net_params))

    def suggest_proxy(self, found_proxy):
        if found_proxy is None:
            self.tor_cb.hide()
            return
        self.tor_proxy = found_proxy
        self.tor_cb.setText("Use Tor proxy at port " + str(found_proxy[1]))
        if (self.proxy_cb.isChecked() and self.proxy_mode.currentIndex()
                == self.proxy_mode.findText('SOCKS5')
                and self.proxy_host.text() == "127.0.0.1"
                and self.proxy_port.text() == str(found_proxy[1])):
            self.tor_cb.setChecked(True)
        self.tor_cb.show()

    def use_tor_proxy(self, use_it):
        if not use_it:
            self.proxy_cb.setChecked(False)
        else:
            socks5_mode_index = self.proxy_mode.findText('SOCKS5')
            if socks5_mode_index == -1:
                _logger.info("can't find proxy_mode 'SOCKS5'")
                return
            self.proxy_mode.setCurrentIndex(socks5_mode_index)
            self.proxy_host.setText("127.0.0.1")
            self.proxy_port.setText(str(self.tor_proxy[1]))
            self.proxy_user.setText("")
            self.proxy_password.setText("")
            self.tor_cb.setChecked(True)
            self.proxy_cb.setChecked(True)
        self.check_disable_proxy(use_it)
        self.set_proxy()

    def fiat_bypass_tor(self, bypass):
        self.config.set_key('fiat_bypass_tor', bypass, False)
        coro = self.network.restart()
        self.network.run_from_another_thread(coro)

    def proxy_settings_changed(self):
        self.tor_cb.setChecked(False)

    def use_tor_auto_on(self, use_it):
        self.config.set_key('tor_auto_on', use_it, True)
예제 #55
0
class CAMERABASLERACQ(QWidget) :

    def __init__(self,name=None,visuGauche=False):
        super(CAMERABASLERACQ, self).__init__()
        self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) # dark style 
        self.visuGauche=visuGauche
        self.winM=MEAS()
        self.seuil=1
        if name==None:
            self.nbcam='camTest'
        else:   
            self.nbcam=name
        self.confCCD = QtCore.QSettings('confBasler.ini', QtCore.QSettings.IniFormat)
        self.camType=self.confCCD.value(self.nbcam+"/camType")
        
        if self.camType != 'basler':
            print('error camera type')
        
        self.id=self.confCCD.value(self.nbcam+"/camId")
        print('self.id',self.id)
        self.camName=self.confCCD.value(self.nbcam+"/name")
        self.winM.setFile(self.camName)
        camConnected=None
        for i in pylon.TlFactory.GetInstance().EnumerateDevices():
            if i.GetSerialNumber()==self.id:
                camConnected=i
        try :
            if camConnected is not None:
                self.cam0= pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateDevice(camConnected))
                self.isConnected=True
                print(self.camName,'connected @',i.GetSerialNumber())
#            else:
#                self.cam0= pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
#                print('fisrt camera connected')
#                self.isConnected=True
            else:
                 self.isConnected=False
                 print('no camera connected')
        except:
            self.isConnected=False
            print('no camera connected')
            
        self.bloqHandle=1 # bloque la taille du cercle
        self.setup()
        self.Color()
        self.cameName=self.confCCD.value(self.nbcam+"/name")
        self.setWindowTitle(self.cameName)
        p = pathlib.Path(__file__)
        sepa=os.sep
        self.icon=str(p.parent) + sepa + 'icons' +sepa
        self.setWindowIcon(QIcon(self.icon+'LOA.png'))
        #pg.setConfigOptions(antialias=True)
        self.winSC=FULLSCREEN(title=self.cameName,conf=self.confCCD,nbcam=self.nbcam)
        self.actionButton()
        self.bloqq=1
        if self.isConnected==False:
        
        
            print ('not connected')
            self.nbcam='camTest'
            self.runButton.setEnabled(False)
            self.runButton.setStyleSheet("background-color:gray")
            self.runButton.setStyleSheet("QPushButton:!pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0,0)}""QPushButton:pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0)}")
            
            self.hSliderShutter.setEnabled(False)
            self.trigg.setEnabled(False)
            self.hSliderGain.setEnabled(False)
            self.stopButton.setEnabled(False)
            self.stopButton.setStyleSheet("background-color:gray")
            self.stopButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Stop.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0,0);}""QPushButton:pressed{image: url(./icons/Stop.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0)}")

            
        if self.isConnected==True:
            self.cam0.Open()
 
            self.cam0.GainAuto.SetValue('Off')
            self.cam0.TriggerMode.SetValue('Off')
            self.cam0.TriggerSelector.SetValue("AcquisitionStart")
            self.cam0.ExposureAuto.SetValue('Off')

            self.cam0.Width=self.cam0.Width.Max
            self.cam0.Height=self.cam0.Height.Max
#            self.hSliderShutter.setMinimum(self.cam0.ExposureTimeAbs.GetMin())
#            self.hSliderShutter.setMaximum(self.cam0.ExposureTimeAbs.GetMax())
            sh=int(self.confCCD.value(self.nbcam+"/shutter"))
            self.hSliderShutter.setValue(sh)
            self.shutterBox.setValue(int(sh))
            
            self.cam0.ExposureTimeAbs.SetValue(int(sh*1000))
            
            self.hSliderGain.setMinimum(self.cam0.GainRaw.GetMin())
            self.hSliderGain.setMaximum(self.cam0.GainRaw.GetMax())
            g=int(self.confCCD.value(self.nbcam+"/gain"))
            self.hSliderGain.setValue(g)
            self.cam0.GainRaw.SetValue(int(g))
            
            
            self.gainBox.setMinimum(self.cam0.GainRaw.GetMin())
            self.gainBox.setMaximum(self.cam0.GainRaw.GetMax())
            self.gainBox.setValue(int(self.cam0.GainRaw.GetValue()))
            
            
            self.dimy=self.cam0.SensorHeight.GetValue()
            self.dimx=self.cam0.SensorWidth.GetValue()
            print("number of pixels :",self.dimx,'*',self.dimy)
        
        else :
            self.dimy=960
            self.dimx=1240
            
        
        def twoD_Gaussian(x,y, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
            xo = float(xo)
            yo = float(yo)    
            a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
            b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
            c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
            return offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) + c*((y-yo)**2)))

        # Create x and y indices
        x = np.arange(0,self.dimx)
        y = np.arange(0,self.dimy)
        y,x = np.meshgrid(y, x)

        self.data=twoD_Gaussian(x, y,250, 300, 600, 40, 40, 0, 10)+(50*np.random.rand(self.dimx,self.dimy)).round() 
        #self.data=(50*np.random.rand(self.dimx,self.dimy)).round() + 150
        
        self.p1.setXRange(0,self.dimx)
        self.p1.setYRange(0,self.dimy)
        #self.p1.setGeometry(1,1,self.dimx,self.dimy)
        #self.winImage.setGeometry(1,1,self.dimx,self.dimy)
        self.Display(self.data)
        
        
    def setup(self):    
        
        vbox1=QVBoxLayout() 
        
        
        self.camNameLabel=QLabel('nomcam',self)
        
        self.camNameLabel.setText(self.confCCD.value(self.nbcam+"/name"))

        self.camNameLabel.setAlignment(Qt.AlignCenter)
        self.camNameLabel.setStyleSheet('font: bold 20px')
        self.camNameLabel.setStyleSheet('color: yellow')
        vbox1.addWidget(self.camNameLabel)
        
        hbox1=QHBoxLayout() # horizontal layout pour run et stop
        self.runButton=QPushButton(self)
        self.runButton.setMaximumWidth(60)
        self.runButton.setMinimumHeight(60)
        self.runButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: green;}""QPushButton:pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0)}")
        self.stopButton=QPushButton(self)
        
        self.stopButton.setMaximumWidth(60)
        self.stopButton.setMinimumHeight(50)
        self.stopButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Stop.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0,0);}""QPushButton:pressed{image: url(./icons/Stop.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0)}")
        
        
        hbox1.addWidget(self.runButton)
        hbox1.addWidget(self.stopButton)
#        self.oneButton=QPushButton(self)
#        hbox1.addWidget(self.oneButton)
        
        vbox1.addLayout(hbox1)
        
        self.trigg=QComboBox()
        self.trigg.setMaximumWidth(60)
        self.trigg.addItem('OFF')
        self.trigg.addItem('ON')
        self.trigg.addItem('Threshold')
        self.labelTrigger=QLabel('Trigger')
        self.labelTrigger.setMaximumWidth(60)
        self.itrig=self.trigg.currentIndex()
        hbox2=QHBoxLayout()
        hbox2.addWidget(self.labelTrigger)
        hbox2.addWidget(self.trigg)
        vbox1.addLayout(hbox2)
        
        self.labelExp=QLabel('Exposure (ms)')
        self.labelExp.setMaximumWidth(120)
        self.labelExp.setAlignment(Qt.AlignCenter)
        vbox1.addWidget(self.labelExp)
        self.hSliderShutter=QSlider(Qt.Horizontal)
        self.hSliderShutter.setMinimum(1)
        self.hSliderShutter.setMaximum(1000)
        self.hSliderShutter.setMaximumWidth(120)
        self.shutterBox=QSpinBox()
        self.shutterBox.setMinimum(1)
        self.shutterBox.setMaximum(1000)
        self.shutterBox.setMaximumWidth(60)
       
        hboxShutter=QHBoxLayout()
        hboxShutter.addWidget(self.hSliderShutter)
        hboxShutter.addWidget(self.shutterBox)
        vbox1.addLayout(hboxShutter)
        
        
        

        hboxGain=QHBoxLayout()
        self.labelGain=QLabel('Gain')
        self.labelGain.setMaximumWidth(120)
        self.labelGain.setAlignment(Qt.AlignCenter)
        vbox1.addWidget(self.labelGain)
        self.hSliderGain=QSlider(Qt.Horizontal)
        self.hSliderGain.setMaximumWidth(120)
        
        self.gainBox=QSpinBox()
        
           
        self.gainBox.setMaximumWidth(60)
        hboxGain.addWidget(self.hSliderGain)
        hboxGain.addWidget(self.gainBox)
        vbox1.addLayout(hboxGain)
        
        
        hbox3=QHBoxLayout()
        self.checkBoxScale=QCheckBox('AScale',self)
        self.checkBoxScale.setChecked(True)
        self.checkBoxScale.setStyleSheet("QCheckBox::indicator{width: 30px;height: 30px;}""QCheckBox::indicator:unchecked { image : url(./icons/Toggle Off-595b40b85ba036ed117dac78.svg);}""QCheckBox::indicator:checked { image:  url(./icons/Toggle On-595b40b85ba036ed117dac79.svg);}")
    
        hbox3.addWidget(self.checkBoxScale)
        
        self.checkBoxColor=QCheckBox('Color',self)
        self.checkBoxColor.setChecked(True)
        self.checkBoxColor.setStyleSheet("QCheckBox::indicator{width: 30px;height: 30px;}""QCheckBox::indicator:unchecked { image : url(./icons/Toggle Off-595b40b85ba036ed117dac78.svg);}""QCheckBox::indicator:checked { image:  url(./icons/Toggle On-595b40b85ba036ed117dac79.svg);}")
    
        hbox3.addWidget(self.checkBoxColor)
        
        vbox1.addLayout(hbox3)
        hbox4=QHBoxLayout()
        self.checkBoxZoom=QCheckBox('Zoom',self)
        self.checkBoxZoom.setChecked(False)
        self.checkBoxZoom.setStyleSheet("QCheckBox::indicator{width: 30px;height: 30px;}""QCheckBox::indicator:unchecked { image : url(./icons/Toggle Off-595b40b85ba036ed117dac78.svg);}""QCheckBox::indicator:checked { image:  url(./icons/Toggle On-595b40b85ba036ed117dac79.svg);}")
    
        hbox4.addWidget(self.checkBoxZoom)
        
        self.MeasButton=QCheckBox('Meas',self)
        self.MeasButton.setChecked(False)
        self.MeasButton.setStyleSheet("QCheckBox::indicator{width: 30px;height: 30px;}""QCheckBox::indicator:unchecked { image : url(./icons/Toggle Off-595b40b85ba036ed117dac78.svg);}""QCheckBox::indicator:checked { image:  url(./icons/Toggle On-595b40b85ba036ed117dac79.svg);}")
    
        hbox4.addWidget(self.MeasButton)
        
        
        vbox1.addLayout(hbox4)
        
        vbox1.setContentsMargins(0,0,0,0)
        vbox1.addStretch(1)
        self.vbox1=vbox1
        
        ### affichage image###
        
        self.winImage = pg.GraphicsLayoutWidget()
        self.winImage.setContentsMargins(0,0,0,0)
        self.winImage.setAspectLocked(True)
        self.winImage.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.winImage.ci.setContentsMargins(0,0,0,0)
        
        vbox2=QVBoxLayout()
        vbox2.addWidget(self.winImage)
        vbox2.setContentsMargins(1,1,1,1)
        
    
        self.p1=self.winImage.addPlot()
        self.imh=pg.ImageItem()
        self.p1.addItem(self.imh)
        self.p1.setMouseEnabled(x=False,y=False)
        self.p1.setContentsMargins(0,0,0,0)
        self.p1.setAspectLocked(True,ratio=1)
        self.p1.showAxis('right',show=False)
        self.p1.showAxis('top',show=False)
        self.p1.showAxis('left',show=False)
        self.p1.showAxis('bottom',show=False)
        
        self.vLine = pg.InfiniteLine(angle=90, movable=False,pen='y')
        self.hLine = pg.InfiniteLine(angle=0, movable=False,pen='y')
        self.p1.addItem(self.vLine)
        self.p1.addItem(self.hLine, ignoreBounds=False)
        self.xc=int(self.confCCD.value(self.nbcam+"/xc"))
        self.yc=int(self.confCCD.value(self.nbcam+"/yc"))
        self.rx=int(self.confCCD.value(self.nbcam+"/rx"))
        self.ry=int(self.confCCD.value(self.nbcam+"/ry"))
        self.vLine.setPos(self.xc)
        self.hLine.setPos(self.yc)
        
        self.ro1=pg.EllipseROI([self.xc,self.yc],[self.rx,self.ry],pen='y',movable=False)#maxBounds=QtCore.QRectF(0,0,self.rx,self.ry)
        self.ro1.setPos([self.xc-(self.rx/2),self.yc-(self.ry/2)])
        self.p1.addItem(self.ro1)
        
        
        #histogramme
        self.hist = pg.HistogramLUTItem() 
        self.hist.setImageItem(self.imh)
        self.hist.autoHistogramRange()
        self.hist.gradient.loadPreset('flame')
        
        ## Graph coupe XY  
        
        self.curve2=pg.PlotCurveItem()
        self.curve3=pg.PlotCurveItem()
        
        ## main layout
        
        hMainLayout=QHBoxLayout()
        if self.visuGauche==True:
            hMainLayout.addLayout(self.vbox1)
            hMainLayout.addLayout(vbox2)
        else:
            hMainLayout.addLayout(vbox2)
            hMainLayout.addLayout(self.vbox1)
        hMainLayout.setContentsMargins(1,1,1,1)
        hMainLayout.setSpacing(1)
        hMainLayout.setStretch(3,1)
        
        self.setLayout(hMainLayout)
        self.setContentsMargins(1,1,1,1)
        
        # Blocage de la souris
        self.shortcutb=QtGui.QShortcut(QtGui.QKeySequence("Ctrl+b"),self)
        self.shortcutb.activated.connect(self.bloquer)
        self.shortcutb.setContext(Qt.ShortcutContext(3))
        self.shortcutd=QtGui.QShortcut(QtGui.QKeySequence("Ctrl+d"),self)
        self.shortcutd.activated.connect(self.debloquer)
        self.shortcutd.setContext(Qt.ShortcutContext(3))
        self.shortcutPu=QShortcut(QtGui.QKeySequence("+"),self)
        self.shortcutPu.activated.connect(self.paletteup)
        self.shortcutPu.setContext(Qt.ShortcutContext(3))
        #3: The shortcut is active when its parent widget, or any of its children has focus. default O The shortcut is active when its parent widget has focus.
        self.shortcutPd=QtGui.QShortcut(QtGui.QKeySequence("-"),self)
        self.shortcutPd.activated.connect(self.palettedown)
        self.shortcutPd.setContext(Qt.ShortcutContext(3))
        
        # mvt de la souris
        self.proxy=pg.SignalProxy(self.p1.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
        self.vb=self.p1.vb
        
        # text pour afficher fwhm sur p1
        self.textX = pg.TextItem(angle=-90) 
        self.textY = pg.TextItem()
        
        
    def actionButton(self):
        self.runButton.clicked.connect(self.acquireMultiImage)
        self.stopButton.clicked.connect(self.stopAcq)
        self.hSliderShutter.sliderMoved.connect(self.mSliderShutter)
        self.shutterBox.editingFinished.connect(self.shutter)
        self.hSliderGain.sliderMoved.connect(self.mSliderGain)
        self.gainBox.editingFinished.connect(self.gain)
        self.trigg.currentIndexChanged.connect(self.Trig)
        self.checkBoxColor.stateChanged.connect(self.Color)
        
        self.ro1.sigRegionChangeFinished.connect(self.roiChanged)
        self.checkBoxZoom.stateChanged.connect(self.Zoom)
        self.MeasButton.clicked.connect(self.Measurement)
#        self.oneButton.clicked.connect(self.acquireOneImage)
        
    def shutter(self):
        
        sh=self.shutterBox.value() # 
        self.hSliderShutter.setValue(sh) # set value of slider
        time.sleep(0.1)
        print(sh,'sh')
        self.cam0.ExposureTimeAbs.SetValue(int(sh*1000))
            
        self.confCCD.setValue(self.nbcam+"/shutter",float(sh))
        self.confCCD.sync()

    def mSliderShutter(self): # for shutter slider 
        sh=self.hSliderShutter.value() 
        self.shutterBox.setValue(sh) # 
        time.sleep(0.1)
        self.cam0.ExposureTimeAbs.SetValue(int(sh*1000)) # Set shutter CCD in microseconde
        self.confCCD.setValue(self.nbcam+"/shutter",float(sh))   
    
    def Color(self):
        """ image in colour
        """
        if self.checkBoxColor.isChecked()==1:
            self.color='flame'
            self.hist.gradient.loadPreset('flame')
        else:
            self.hist.gradient.loadPreset('grey')
            self.color='grey'
            
    def Zoom(self):
        if self.checkBoxZoom.isChecked()==1:
            self.p1.setXRange(self.xc-200,self.xc+200)
            self.p1.setYRange(self.yc-200,self.yc+200)
        else:
            self.p1.setXRange(0,self.dimx)
            self.p1.setYRange(0,self.dimy)
        
    def FullScreen(self):
        if self.checkBoxFullScreen.isChecked()==1:
            self.open_widget(self.winSC)
            self.winSC.Display(self.data,color=self.color)
            #self.winSC.showMaximized()
        else:
             self.winSC.close()
         
    def gain(self):
        g=self.gainBox.value() # 
        self.hSliderGain.setValue(g) # set slider value
        time.sleep(0.1)
        self.cam0.GainRaw.SetValue(int(g))
        
        self.confCCD.setValue(self.nbcam+"/gain",float(g))
        self.confCCD.sync()
    
    def mSliderGain(self):
        g=self.hSliderGain.value()
        self.gainBox.setValue(g) # set valeur de la box
        time.sleep(0.1)
        self.cam0.GainRaw.SetValue(int(g))
        self.confCCD.setValue(self.nbcam+"/gain",float(g))
        self.confCCD.sync()
        
    def Trig(self):
        self.itrig=self.trigg.currentIndex()
        
        if self.itrig==0:
            self.cam0.TriggerMode.SetValue('Off')
#            print ("trigger OFF")
        if self.itrig==1:
            self.cam0.TriggerMode.SetValue('On')
#            print("Trigger ON")
        if self.itrig==2:
            
            self.seuil, ok=QInputDialog.getInt(self,'THRESHOLD',' Threshold value(<256)')
            if self.seuil>256:
                self.seuil=256
                
                
    def acquireMultiImage(self):   
        #print('live...')
        
        self.runButton.setEnabled(False)
        self.runButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: gray ;border-color: rgb(0, 0, 0,0);}""QPushButton:pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: gray ;border-color: rgb(0, 0, 0)}")
        #self.runButton.setStyleSheet("background-color:gray")
        try:
            self.threadRunAcq=ThreadRunAcq(self)
            self.threadRunAcq.newDataRun.connect(self.Display)
            self.threadRunAcq.start()
        except :
            pass
    
    
    def acquireOneImage(self):   
        
        
        self.runButton.setEnabled(False)
        self.runButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: gray ;border-color: rgb(0, 0, 0,0);}""QPushButton:pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: gray ;border-color: rgb(0, 0, 0)}")
        #self.runButton.setStyleSheet("background-color:gray")
        try:
            self.threadOneAcq=ThreadOneAcq(self)
            self.threadOneAcq.newDataOne.connect(self.Display)
            self.threadOneAcq.start()
        except :
            print('error')
            pass
        self.runButton.setEnabled(True)
        self.runButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0,0);}""QPushButton:pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0)}")
        
    
    
    def stopAcq(self):
        print('Stop live')
        try:
            self.threadRunAcq.stopThreadRunAcq()
            
            self.cam0.ExecuteSoftwareTrigger()
        except :
            print('error stop thread')
            pass
        self.runButton.setEnabled(True)
        #self.runButton.setStyleSheet("background-color: rgb(0, 200, 0)")
        self.runButton.setStyleSheet("QPushButton:!pressed{border-image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0,0);}""QPushButton:pressed{image: url(./icons/Circled Play-595b40b65ba036ed117d436f.svg);background-color: rgb(0, 0, 0,0) ;border-color: rgb(0, 0, 0)}")
        
        #self.threadAcq.terminate()    
        
    def Display(self,data):
        self.data=data
        if self.checkBoxScale.isChecked()==1: # autoscale on
            self.imh.setImage(data.astype(float),autoLevels=True,autoDownsample=True)
            
        else :
            self.imh.setImage(data.astype(float),autoLevels=False,autoDownsample=True)
       
        if self.winM.isWinOpen==True:
            print('test')#  measurement update
            self.Measurement()
        
    def bloquer(self): # bloque la croix 
        self.bloqq=1
        self.confCCD.setValue(self.nbcam+"/xc",int(self.xc)) # save cross postion in ini file
        self.confCCD.setValue(self.nbcam+"/yc",int(self.yc))
        print('xc',self.xc,'yc',self.yc)
        
        
    def debloquer(self): # deblaoque la croix : elle bouge avec la souris
        self.bloqq=0
    
    def roiChanged(self):
        self.rx=self.ro1.size()[0]
        self.ry=self.ro1.size()[1]
        self.confCCD.setValue(self.nbcam+"/rx",int(self.rx))
        self.confCCD.setValue(self.nbcam+"/ry",int(self.ry))
        
        
    def mouseMoved(self,evt):
        ## pour que la cross suive le mvt de la souris
        if self.bloqq==0: # souris non bloquer
            pos = evt[0]  ## using signal proxy turns original arguments into a tuple
            if self.p1.sceneBoundingRect().contains(pos):
                mousePoint = self.vb.mapSceneToView(pos)
                self.xc = (mousePoint.x())
                self.yc= (mousePoint.y())
                if ((self.xc>0 and self.xc<self.data.shape[0]) and (self.yc>0 and self.yc<self.data.shape[1]) ):
                        self.vLine.setPos(self.xc)
                        self.hLine.setPos(self.yc) # la croix ne bouge que dans le graph       
                        self.ro1.setPos([self.xc-(self.rx/2),self.yc-(self.ry/2)])
                        
    
    
            
    def paletteup(self):
        levels=self.imh.getLevels()
        if levels[0]==None:
            xmax =self.data.max()
            xmin=self.data.min()
        else :
            xmax=levels[1]
            xmin=levels[0]
            
        self.imh.setLevels([xmin, xmax+(xmax- xmin) / 10])
        #hist.setImageItem(imh,clear=True)
        self.hist.setHistogramRange(xmin,xmax)

    def palettedown(self):
        levels=self.imh.getLevels()
        if levels[0]==None:
            xmax=self.data.max()
            xmin=self.data.min()
        else :
            xmax=levels[1]
            xmin=levels[0]
            
        self.imh.setLevels([xmin, xmax- (xmax- xmin) / 10])
        #hist.setImageItem(imh,clear=True)
        self.hist.setHistogramRange(xmin,xmax)
    
    
    def open_widget(self,fene):
        """ open new widget 
        """

        if fene.isWinOpen==False:
            #fene.setup
            fene.isWinOpen=True
            
            #fene.Display(self.data)
            fene.show()
        else:
            #fene.activateWindow()
#            fene.raise_()
#            fene.showNormal()
            pass
        
    def Measurement(self) :
        
        self.open_widget(self.winM)
        self.winM.Display(self.data)
            
            
    def closeEvent(self,event):
        self.fin()
        event.accept()
    
    
    def fin(self):
        try :
            self.threadRunAcq.stopThreadRunAcq()
        except :
            pass
        try :
            self.cam0.close()
        except :
            pass
        sys.exit(0)  
예제 #56
0
class ConfigDlg(QDialog, Ui_ConfigDlg, WndUtils):
    def __init__(self, parent, config):
        QDialog.__init__(self, parent=parent)
        Ui_ConfigDlg.__init__(self)
        WndUtils.__init__(self, config)
        self.config = config
        self.main_window = parent
        self.local_config = AppConfig()
        self.local_config.copy_from(config)

        # list of connections from self.local_config.dash_net_configs split on separate lists for mainnet and testnet
        self.connections_mainnet = []
        self.connections_testnet = []
        self.connections_current = None
        self.current_network_cfg: Optional[DashNetworkConnectionCfg] = None

        # block ui controls -> cur config data copying while setting ui controls initial values
        self.disable_cfg_update = False
        self.is_modified = False
        self.setupUi()

    def setupUi(self):
        Ui_ConfigDlg.setupUi(self, self)
        self.resize(
            app_cache.get_value('ConfigDlg_Width',
                                self.size().width(), int),
            app_cache.get_value('ConfigDlg_Height',
                                self.size().height(), int))

        self.setWindowTitle("Configuration")
        self.splitter.setStretchFactor(0, 0)
        self.splitter.setStretchFactor(1, 1)
        self.accepted.connect(self.on_accepted)
        self.tabWidget.setCurrentIndex(0)

        self.disable_cfg_update = True

        layout_details = self.detailsFrame.layout()
        self.chbConnEnabled = QCheckBox("Enabled")
        self.chbConnEnabled.toggled.connect(self.on_chbConnEnabled_toggled)
        layout_details.addWidget(self.chbConnEnabled)
        self.chbUseSshTunnel = QCheckBox("Use SSH tunnel")
        self.chbUseSshTunnel.toggled.connect(self.on_chbUseSshTunnel_toggled)
        layout_details.addWidget(self.chbUseSshTunnel)
        self.ssh_tunnel_widget = SshConnectionWidget(self.detailsFrame)
        layout_details.addWidget(self.ssh_tunnel_widget)

        # layout for button for reading RPC configuration from remote host over SSH:
        hl = QHBoxLayout()
        self.btnSshReadRpcConfig = QPushButton(
            "\u2B07 Read RPC configuration from SSH host \u2B07")
        self.btnSshReadRpcConfig.clicked.connect(
            self.on_btnSshReadRpcConfig_clicked)
        hl.addWidget(self.btnSshReadRpcConfig)
        hl.addStretch()
        layout_details.addLayout(hl)

        # add connection-editing controls widget:
        self.rpc_cfg_widget = RpcConnectionWidget(self.detailsFrame)
        layout_details.addWidget(self.rpc_cfg_widget)

        # layout for controls related to setting up an additional encryption
        hl = QHBoxLayout()
        self.btnEncryptionPublicKey = QPushButton("RPC encryption public key")
        self.btnEncryptionPublicKey.clicked.connect(
            self.on_btnEncryptionPublicKey_clicked)
        hl.addWidget(self.btnEncryptionPublicKey)
        self.lblEncryptionPublicKey = QLabel(self)
        self.lblEncryptionPublicKey.setText('')
        hl.addWidget(self.lblEncryptionPublicKey)
        hl.addStretch()
        layout_details.addLayout(hl)

        # layout for the 'test connection' button:
        hl = QHBoxLayout()
        self.btnTestConnection = QPushButton("\u2705 Test connection")
        self.btnTestConnection.clicked.connect(
            self.on_btnTestConnection_clicked)
        sp = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,
                                   QtWidgets.QSizePolicy.Minimum)
        sp.setHorizontalStretch(0)
        sp.setVerticalStretch(0)
        sp.setHeightForWidth(
            self.btnTestConnection.sizePolicy().hasHeightForWidth())
        self.btnTestConnection.setSizePolicy(sp)
        hl.addWidget(self.btnTestConnection)
        hl.addStretch()
        layout_details.addLayout(hl)
        layout_details.addStretch()

        self.rpc_cfg_widget.edtRpcHost.textEdited.connect(
            self.on_edtRpcHost_textEdited)
        self.rpc_cfg_widget.edtRpcPort.textEdited.connect(
            self.on_edtRpcPort_textEdited)
        self.rpc_cfg_widget.edtRpcUsername.textEdited.connect(
            self.on_edtRpcUsername_textEdited)
        self.rpc_cfg_widget.edtRpcPassword.textEdited.connect(
            self.on_edtRpcPassword_textEdited)
        self.rpc_cfg_widget.chbRpcSSL.toggled.connect(self.chbRpcSSL_toggled)
        self.ssh_tunnel_widget.edtSshHost.textEdited.connect(
            self.on_edtSshHost_textEdited)
        self.ssh_tunnel_widget.edtSshPort.textEdited.connect(
            self.on_edtSshPort_textEdited)
        self.ssh_tunnel_widget.edtSshUsername.textEdited.connect(
            self.on_edtSshUsername_textEdited)

        self.lstConns.setContextMenuPolicy(Qt.CustomContextMenu)
        self.popMenu = QMenu(self)

        self.action_new_connection = self.popMenu.addAction(
            "Add new connection")
        self.action_new_connection.triggered.connect(
            self.on_action_new_connection_triggered)
        self.setIcon(self.action_new_connection, '*****@*****.**')
        self.btnNewConn.setDefaultAction(self.action_new_connection)

        self.action_delete_connections = self.popMenu.addAction(
            "Delete selected connection(s)")
        self.action_delete_connections.triggered.connect(
            self.on_action_delete_connections_triggered)
        self.setIcon(self.action_delete_connections, '*****@*****.**')
        self.btnDeleteConn.setDefaultAction(self.action_delete_connections)

        self.action_copy_connections = self.popMenu.addAction(
            "Copy connection(s) to clipboard",
            self.on_action_copy_connections_triggered, QKeySequence("Ctrl+C"))
        self.setIcon(self.action_copy_connections, '*****@*****.**')
        self.addAction(self.action_copy_connections)

        self.action_paste_connections = self.popMenu.addAction(
            "Paste connection(s) from clipboard",
            self.on_action_paste_connections_triggered, QKeySequence("Ctrl+V"))
        self.setIcon(self.action_paste_connections, '*****@*****.**')
        self.addAction(self.action_paste_connections)

        self.btnNewConn.setText("")
        self.btnDeleteConn.setText("")
        self.btnMoveDownConn.setText("")
        self.btnMoveUpConn.setText("")
        self.btnRestoreDefault.setText("")
        self.setIcon(self.btnMoveDownConn, "*****@*****.**")
        self.setIcon(self.btnMoveUpConn, "*****@*****.**", rotate=180)
        self.setIcon(self.btnRestoreDefault, "*****@*****.**")
        self.setIcon(self.rpc_cfg_widget.btnShowPassword, "*****@*****.**")

        self.rpc_cfg_widget.btnShowPassword.setText("")
        self.rpc_cfg_widget.btnShowPassword.pressed.connect(
            lambda: self.rpc_cfg_widget.edtRpcPassword.setEchoMode(QLineEdit.
                                                                   Normal))
        self.rpc_cfg_widget.btnShowPassword.released.connect(
            lambda: self.rpc_cfg_widget.edtRpcPassword.setEchoMode(QLineEdit.
                                                                   Password))

        if self.local_config.is_mainnet():
            self.cboDashNetwork.setCurrentIndex(0)
            self.connections_current = self.connections_mainnet
        else:
            self.cboDashNetwork.setCurrentIndex(1)
            self.connections_current = self.connections_testnet
        for cfg in self.local_config.dash_net_configs:
            if cfg.testnet:
                self.connections_testnet.append(cfg)
            else:
                self.connections_mainnet.append(cfg)

        if self.local_config.hw_type == HWType.trezor:
            self.chbHwTrezor.setChecked(True)
        elif self.local_config.hw_type == HWType.keepkey:
            self.chbHwKeepKey.setChecked(True)
        else:
            self.chbHwLedgerNanoS.setChecked(True)

        if self.local_config.hw_keepkey_psw_encoding == 'NFC':
            self.cboKeepkeyPassEncoding.setCurrentIndex(0)
        else:
            self.cboKeepkeyPassEncoding.setCurrentIndex(1)
        note_url = get_note_url('DMTN0001')
        self.lblKeepkeyPassEncoding.setText(
            f'KepKey passphrase encoding (<a href="{note_url}">see</a>)')

        self.chbCheckForUpdates.setChecked(self.local_config.check_for_updates)
        self.chbBackupConfigFile.setChecked(
            self.local_config.backup_config_file)
        self.chbDownloadProposalExternalData.setChecked(
            self.local_config.read_proposals_external_attributes)
        self.chbDontUseFileDialogs.setChecked(
            self.local_config.dont_use_file_dialogs)
        self.chbConfirmWhenVoting.setChecked(
            self.local_config.confirm_when_voting)
        self.chbAddRandomOffsetToVotingTime.setChecked(
            self.local_config.add_random_offset_to_vote_time)
        self.chbEncryptConfigFile.setChecked(
            self.local_config.encrypt_config_file)

        idx = {
            'CRITICAL': 0,
            'ERROR': 1,
            'WARNING': 2,
            'INFO': 3,
            'DEBUG': 4,
            'NOTSET': 5
        }.get(self.local_config.log_level_str, 2)
        self.cboLogLevel.setCurrentIndex(idx)

        self.display_connection_list()
        if len(self.local_config.dash_net_configs):
            self.lstConns.setCurrentRow(0)

        self.update_keepkey_pass_encoding_ui()
        self.update_connection_details_ui()
        self.disable_cfg_update = False
        self.splitter.setSizes(
            app_cache.get_value('ConfigDlg_ConnectionSplitter_Sizes',
                                [100, 100], list))

    def closeEvent(self, event):
        self.on_close()

    def showEvent(self, QShowEvent):
        self.rpc_cfg_widget.btnShowPassword.setFixedHeight(
            self.rpc_cfg_widget.edtRpcPassword.height())

    def done(self, result_code):
        self.on_close()
        QDialog.done(self, result_code)

    def on_close(self):
        app_cache.set_value('ConfigDlg_Width', self.size().width())
        app_cache.set_value('ConfigDlg_Height', self.size().height())
        app_cache.set_value('ConfigDlg_ConnectionSplitter_Sizes',
                            self.splitter.sizes())

    def on_accepted(self):
        """Executed after clicking the 'OK' button."""
        if self.is_modified:
            self.apply_config_changes()

    def display_connection_list(self):
        self.lstConns.clear()
        for cfg in self.connections_current:
            item = QListWidgetItem(cfg.get_description())
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked if cfg.enabled else Qt.Unchecked)
            item.checkState()
            self.lstConns.addItem(item)

    def update_keepkey_pass_encoding_ui(self):
        """Display widget for setting up the encoding of UTF-8 characters in passphrase when
        Keepkey HW type is selected.
        """
        self.wdgKeepkeyPassEncoding.setVisible(
            self.local_config.hw_type == HWType.keepkey)

    @pyqtSlot(int)
    def on_cboDashNetwork_currentIndexChanged(self, index):
        """Executed after changing configuration between MAINNET and TESTNET."""
        if not self.disable_cfg_update:
            if index == 0:
                self.connections_current = self.connections_mainnet
                self.local_config.dash_network = 'MAINNET'
            else:
                self.connections_current = self.connections_testnet
                self.local_config.dash_network = 'TESTNET'
            self.display_connection_list()
            self.set_modified()
            self.lstConns.setCurrentRow(0)

    @pyqtSlot(QPoint)
    def on_lstConns_customContextMenuRequested(self, point):
        ids = self.lstConns.selectedIndexes()
        self.action_copy_connections.setEnabled(len(ids) > 0)

        # check if the clipboard contains at least one connection configuration in the form of JSON string
        clipboard = QApplication.clipboard()
        try:
            conns = self.local_config.decode_connections_json(clipboard.text())
            if isinstance(conns, list) and len(conns):
                # disable the 'paste' action if the clipboard doesn't contain a JSON string describing a
                # dash connection(s)
                self.action_paste_connections.setEnabled(True)
            else:
                self.action_paste_connections.setEnabled(False)
        except:
            self.action_paste_connections.setEnabled(False)
        self.popMenu.exec_(self.lstConns.mapToGlobal(point))

    def on_action_copy_connections_triggered(self):
        """Action 'copy connections' executed from the context menu associated with the connection list."""
        ids = self.lstConns.selectedIndexes()
        cfgs = []
        for index in ids:
            cfgs.append(self.connections_current[index.row()])
        if len(cfgs):
            text = self.local_config.encode_connections_to_json(cfgs)
            if text:
                clipboard = QApplication.clipboard()
                clipboard.setText(text)

    def on_action_paste_connections_triggered(self):
        """Action 'paste connections' from the clipboard JSON text containing a list of connection definitions."""

        clipboard = QApplication.clipboard()
        try:
            conns = self.local_config.decode_connections_json(clipboard.text())
            if isinstance(conns, list) and len(conns):
                self.action_paste_connections.setEnabled(True)
                if self.queryDlg(
                        'Do you really want to import connection(s) from clipboard?',
                        buttons=QMessageBox.Yes | QMessageBox.Cancel,
                        default_button=QMessageBox.Yes,
                        icon=QMessageBox.Information) == QMessageBox.Yes:
                    testnet = self.local_config.is_testnet()
                    for cfg in conns:
                        cfg.testnet = testnet

                    # update the main list containing connections configuration from separate  lists dedicated
                    # to mainnet and testnet - it'll be used by the import_connection method
                    self.local_config.dash_net_configs.clear()
                    self.local_config.dash_net_configs.extend(
                        self.connections_mainnet)
                    self.local_config.dash_net_configs.extend(
                        self.connections_testnet)

                    added, updated = self.local_config.import_connections(
                        conns,
                        force_import=True,
                        limit_to_network=self.local_config.dash_network)
                    for cfg in added:
                        cfg.enabled = True
                    self.connections_current.extend(added)

                    row_selected = self.lstConns.currentRow()
                    self.display_connection_list()
                    self.set_modified()
                    self.lstConns.setCurrentRow(row_selected)

        except Exception as e:
            self.errorMsg(str(e))

    @pyqtSlot(bool)
    def on_btnRestoreDefault_clicked(self, enabled):
        if self.queryDlg(
                'Do you really want to restore default connection(s)?',
                buttons=QMessageBox.Yes | QMessageBox.Cancel,
                default_button=QMessageBox.Yes,
                icon=QMessageBox.Information) == QMessageBox.Yes:
            cfgs = self.local_config.decode_connections(
                default_config.dashd_default_connections)
            if cfgs:
                # update the main list containing connections configuration from separate  lists dedicated
                # to mainnet and testnet - it'll be used by the import_connection method
                self.local_config.dash_net_configs.clear()
                self.local_config.dash_net_configs.extend(
                    self.connections_mainnet)
                self.local_config.dash_net_configs.extend(
                    self.connections_testnet)

                # force import default connections if there is no any in the configuration
                added, updated = self.local_config.import_connections(
                    cfgs,
                    force_import=True,
                    limit_to_network=self.local_config.dash_network)
                self.connections_current.extend(added)
                if added or updated:
                    row_selected = self.lstConns.currentRow()
                    self.display_connection_list()
                    self.set_modified()
                    if row_selected < self.lstConns.count():
                        self.lstConns.setCurrentRow(row_selected)
                    self.infoMsg('Defualt connections successfully restored.')
                else:
                    self.infoMsg(
                        'All default connections are already in the connection list.'
                    )
            else:
                self.warnMsg(
                    'Unknown error occurred while restoring default connections.'
                )

    def update_conn_tool_buttons_state(self):
        selected = (self.current_network_cfg is not None)
        last = self.lstConns.currentRow() == len(self.connections_current) - 1
        first = self.lstConns.currentRow() == 0

        # disabling/enabling action connected to a button results in setting button's text from actions text
        # thats why we are saving and restoring button's text
        text = self.btnDeleteConn.text()
        self.action_delete_connections.setEnabled(selected)
        self.btnDeleteConn.setText(text)

        text = self.btnMoveDownConn.text()
        self.btnMoveDownConn.setEnabled(not last and selected)
        self.btnMoveDownConn.setText(text)

        text = self.btnMoveUpConn.text()
        self.btnMoveUpConn.setEnabled(not first and selected)
        self.btnMoveUpConn.setText(text)

    def update_cur_connection_desc(self):
        """
        Update description of the focused connection in the connections list widget.
        """
        if self.current_network_cfg:
            item = self.lstConns.currentItem()
            if item:
                old_state = self.disable_cfg_update
                try:
                    self.disable_cfg_update = True  # block updating of UI controls
                    item.setText(self.current_network_cfg.get_description())
                finally:
                    self.disable_cfg_update = old_state

    @pyqtSlot()
    def on_action_new_connection_triggered(self):
        cfg = DashNetworkConnectionCfg('rpc')
        cfg.testnet = True if self.cboDashNetwork.currentIndex(
        ) == 1 else False
        self.connections_current.append(cfg)

        # add config to the connections list:
        item = QListWidgetItem(cfg.get_description())
        item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
        item.setCheckState(Qt.Checked if cfg.enabled else Qt.Unchecked)
        item.checkState()
        self.lstConns.addItem(item)
        self.lstConns.setCurrentItem(item)
        self.set_modified()

    @pyqtSlot()
    def on_action_delete_connections_triggered(self):
        ids = self.lstConns.selectedIndexes()
        cfgs = []
        for index in ids:
            cfgs.append(self.connections_current[index.row()])

        if len(ids) >= 0:
            if self.queryDlg(
                    'Do you really want to delete selected %d connection(s)?' %
                    len(ids),
                    buttons=QMessageBox.Yes | QMessageBox.Cancel,
                    default_button=QMessageBox.Cancel,
                    icon=QMessageBox.Warning) == QMessageBox.Yes:

                last_row_selected = self.lstConns.currentRow()
                rows_to_del = []
                for index in ids:
                    rows_to_del.append(index.row())
                rows_to_del.sort(reverse=True)

                # delete connection configs from topmost indexes
                for row_idx in rows_to_del:
                    del self.connections_current[row_idx]
                    self.lstConns.takeItem(row_idx)

                # try selecting the same row
                if last_row_selected < len(self.connections_current):
                    row_idx = last_row_selected
                else:
                    row_idx = len(self.connections_current) - 1

                if row_idx < len(self.connections_current):
                    # select the last row
                    item = self.lstConns.item(row_idx)
                    if item:
                        item.setSelected(True)  # select last item
                        self.lstConns.setCurrentRow(row_idx)
                self.set_modified()

    @pyqtSlot()
    def on_btnMoveUpConn_clicked(self):
        if self.lstConns.currentRow() > 0:
            idx_from = self.lstConns.currentRow()
            l = self.connections_current
            l[idx_from -
              1], l[idx_from] = l[idx_from], l[idx_from -
                                               1]  # swap two elements
            cur_item = self.lstConns.takeItem(idx_from)
            self.lstConns.insertItem(idx_from - 1, cur_item)
            self.lstConns.setCurrentItem(cur_item)
            self.set_modified()

    @pyqtSlot()
    def on_btnMoveDownConn_clicked(self):
        idx_from = self.lstConns.currentRow()
        if idx_from >= 0 and idx_from < len(self.connections_current) - 1:
            l = self.connections_current
            l[idx_from +
              1], l[idx_from] = l[idx_from], l[idx_from +
                                               1]  # swap two elements
            cur_item = self.lstConns.takeItem(idx_from)
            self.lstConns.insertItem(idx_from + 1, cur_item)
            self.lstConns.setCurrentItem(cur_item)
            self.set_modified()

    def on_lstConns_itemChanged(self, item):
        """Executed after checking or unchecking checkbox of a connection on the connections list. Checkbox state is
        then converted to the 'enabled' connection's property."""
        cfg = None
        if item:
            row = self.lstConns.row(item)
            if row >= 0 and row < len(self.connections_current):
                cfg = self.connections_current[row]
        if not self.disable_cfg_update and cfg:
            checked = item.checkState() == Qt.Checked
            cfg.enabled = checked
            self.set_modified()
            self.update_connection_details_ui()

    @pyqtSlot(int)
    def on_lstConns_currentRowChanged(self, row_index):
        """Display a connection's edit properties after moving focus to another connection.
        :param row_index: Index of a currently focused connection on the connections list.
        """
        if row_index >= 0 and row_index < len(self.connections_current):
            self.current_network_cfg = self.connections_current[row_index]
        else:
            self.current_network_cfg = None
        self.update_conn_tool_buttons_state()
        self.update_connection_details_ui()

    def on_chbConnEnabled_toggled(self, checked):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.enabled = checked
            try:
                self.disable_cfg_update = True
                item = self.lstConns.currentItem()
                if item:
                    item.setCheckState(Qt.Checked if checked else Qt.Unchecked)
            finally:
                self.disable_cfg_update = False
            self.set_modified()

    def on_chbUseSshTunnel_toggled(self, checked):
        self.ssh_tunnel_widget.setVisible(self.chbUseSshTunnel.isChecked())
        self.btnSshReadRpcConfig.setVisible(self.chbUseSshTunnel.isChecked())
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.use_ssh_tunnel = checked
            self.update_cur_connection_desc()
            self.set_modified()

    def on_edtRpcHost_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.host = text
            self.update_cur_connection_desc()
            self.set_modified()

    def on_edtRpcPort_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.port = text
            self.update_cur_connection_desc()
            self.set_modified()

    def on_edtRpcUsername_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.username = text
            self.set_modified()

    def on_edtRpcPassword_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.password = text
            self.set_modified()

    def chbRpcSSL_toggled(self, checked):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.use_ssl = checked
            self.update_cur_connection_desc()
            self.set_modified()

    def on_edtSshHost_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.ssh_conn_cfg.host = text
            self.update_cur_connection_desc()
            self.set_modified()

    def on_edtSshPort_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.ssh_conn_cfg.port = text
            self.update_cur_connection_desc()
            self.set_modified()

    def on_edtSshUsername_textEdited(self, text):
        if not self.disable_cfg_update and self.current_network_cfg:
            self.current_network_cfg.ssh_conn_cfg.username = text
            self.set_modified()

    def on_chbRandomConn_toggled(self, checked):
        if not self.disable_cfg_update:
            self.local_config.random_dash_net_config = checked
            self.set_modified()

    def update_connection_details_ui(self):
        """Display properties of the currently focused connection in dedicated UI controls."""
        dis_old = self.disable_cfg_update
        self.disable_cfg_update = True
        try:
            if self.current_network_cfg:
                self.chbConnEnabled.setVisible(True)
                self.chbUseSshTunnel.setVisible(True)
                self.btnTestConnection.setVisible(True)
                self.chbConnEnabled.setChecked(
                    self.current_network_cfg.enabled)
                self.ssh_tunnel_widget.setVisible(
                    self.current_network_cfg.use_ssh_tunnel)
                self.btnSshReadRpcConfig.setVisible(
                    self.current_network_cfg.use_ssh_tunnel)
                self.chbUseSshTunnel.setCheckState(
                    Qt.Checked if self.current_network_cfg.
                    use_ssh_tunnel else Qt.Unchecked)
                if self.current_network_cfg.use_ssh_tunnel:
                    self.ssh_tunnel_widget.edtSshHost.setText(
                        self.current_network_cfg.ssh_conn_cfg.host)
                    self.ssh_tunnel_widget.edtSshPort.setText(
                        self.current_network_cfg.ssh_conn_cfg.port)
                    self.ssh_tunnel_widget.edtSshUsername.setText(
                        self.current_network_cfg.ssh_conn_cfg.username)
                else:
                    self.ssh_tunnel_widget.edtSshHost.setText('')
                    self.ssh_tunnel_widget.edtSshPort.setText('')
                    self.ssh_tunnel_widget.edtSshUsername.setText('')
                self.rpc_cfg_widget.edtRpcHost.setText(
                    self.current_network_cfg.host)
                self.rpc_cfg_widget.edtRpcPort.setText(
                    self.current_network_cfg.port)
                self.rpc_cfg_widget.edtRpcUsername.setText(
                    self.current_network_cfg.username)
                self.rpc_cfg_widget.edtRpcPassword.setText(
                    self.current_network_cfg.password)
                self.rpc_cfg_widget.chbRpcSSL.setChecked(
                    self.current_network_cfg.use_ssl)

                self.btnEncryptionPublicKey.setVisible(True)
                self.lblEncryptionPublicKey.setVisible(True)
                pubkey_der = self.current_network_cfg.get_rpc_encryption_pubkey_str(
                    'DER')
                if pubkey_der:
                    try:
                        pub_bytes = bytearray.fromhex(pubkey_der)
                        hash = hashlib.sha256(pub_bytes).hexdigest()
                        self.lblEncryptionPublicKey.setText(
                            f'[pubkey hash: {hash[0:8]}]')
                    except Exception as e:
                        self.lblEncryptionPublicKey.setText(
                            f'[pubkey not set]')
                else:
                    self.lblEncryptionPublicKey.setText(f'[pubkey not set]')

                self.rpc_cfg_widget.setVisible(True)
            else:
                self.chbConnEnabled.setVisible(False)
                self.chbUseSshTunnel.setVisible(False)
                self.btnTestConnection.setVisible(False)
                self.ssh_tunnel_widget.setVisible(False)
                self.btnSshReadRpcConfig.setVisible(False)
                self.rpc_cfg_widget.setVisible(False)
                self.btnEncryptionPublicKey.setVisible(False)
                self.lblEncryptionPublicKey.setVisible(False)
            self.chbRandomConn.setChecked(
                self.local_config.random_dash_net_config)
        finally:
            self.disable_cfg_update = dis_old

    def on_HwType_toggled(self):
        if self.chbHwTrezor.isChecked():
            self.local_config.hw_type = HWType.trezor
        elif self.chbHwKeepKey.isChecked():
            self.local_config.hw_type = HWType.keepkey
        else:
            self.local_config.hw_type = HWType.ledger_nano_s

        self.update_keepkey_pass_encoding_ui()
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbHwTrezor_toggled(self, checked):
        self.on_HwType_toggled()

    @pyqtSlot(bool)
    def on_chbHwKeepKey_toggled(self, checked):
        self.on_HwType_toggled()

    @pyqtSlot(bool)
    def on_chbHwLedgerNanoS_toggled(self, checked):
        self.on_HwType_toggled()

    @pyqtSlot(int)
    def on_cboKeepkeyPassEncoding_currentIndexChanged(self, index):
        if index == 0:
            self.local_config.hw_keepkey_psw_encoding = 'NFC'
        else:
            self.local_config.hw_keepkey_psw_encoding = 'NFKD'
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbCheckForUpdates_toggled(self, checked):
        self.local_config.check_for_updates = checked
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbBackupConfigFile_toggled(self, checked):
        self.local_config.backup_config_file = checked
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbDownloadProposalExternalData_toggled(self, checked):
        self.local_config.read_proposals_external_attributes = checked
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbDontUseFileDialogs_toggled(self, checked):
        self.local_config.dont_use_file_dialogs = checked
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbConfirmWhenVoting_toggled(self, checked):
        self.local_config.confirm_when_voting = checked
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbAddRandomOffsetToVotingTime_toggled(self, checked):
        self.local_config.add_random_offset_to_vote_time = checked
        self.set_modified()

    @pyqtSlot(bool)
    def on_chbEncryptConfigFile_toggled(self, checked):
        self.local_config.encrypt_config_file = checked
        self.set_modified()

    @pyqtSlot(int)
    def on_cboLogLevel_currentIndexChanged(self, index):
        """
        Event fired when loglevel changed by the user.
        :param index: index of the selected level.
        """
        if not self.disable_cfg_update:
            level = {0: 50, 1: 40, 2: 30, 3: 20, 4: 10, 5: 0}.get(index, 30)
            self.local_config.log_level_str = logging.getLevelName(level)
            self.set_modified()

    def on_btnSshReadRpcConfig_clicked(self):
        """Read the configuration of a remote RPC node from the node's dash.conf file."""
        if self.current_network_cfg:
            host = self.current_network_cfg.ssh_conn_cfg.host
            port = self.current_network_cfg.ssh_conn_cfg.port
            username = self.current_network_cfg.ssh_conn_cfg.username
            if not host:
                self.errorMsg('Host address is required')
                self.ssh_tunnel_widget.edtSshHost.setFocus()
            if not port:
                self.errorMsg('Host TCP port number is required')
                self.ssh_tunnel_widget.edtSshHost.setFocus()

            ok = True
            if not username:
                username, ok = QInputDialog.getText(
                    self, 'Username Dialog',
                    'Enter username for SSH connection:')
            if not ok or not username:
                return
            from dashd_intf import DashdSSH
            ssh = DashdSSH(host, int(port), username)
            try:
                ssh.connect()
                dashd_conf = ssh.find_dashd_config()
                self.disable_cfg_update = True
                if isinstance(dashd_conf, tuple) and len(dashd_conf) >= 3:
                    if not dashd_conf[0]:
                        self.infoMsg(
                            'Remore Dash daemon seems to be shut down')
                    elif not dashd_conf[1]:
                        self.infoMsg('Could not find remote dashd.conf file')
                    else:
                        file = dashd_conf[2]
                        rpcuser = file.get('rpcuser', '')
                        rpcpassword = file.get('rpcpassword', '')
                        rpcport = file.get('rpcport', '9998')
                        modified = False
                        if rpcuser:
                            modified = modified or (
                                self.current_network_cfg.username != rpcuser)
                            self.current_network_cfg.username = rpcuser
                        if rpcpassword:
                            modified = modified or (
                                self.current_network_cfg.password !=
                                rpcpassword)
                            self.current_network_cfg.password = rpcpassword
                        if rpcport:
                            modified = modified or (
                                self.current_network_cfg.port != rpcport)
                            self.current_network_cfg.port = rpcport
                        rpcbind = file.get('rpcbind', '')
                        if not rpcbind:  # listen on all interfaces if not set
                            rpcbind = '127.0.0.1'
                        modified = modified or (self.current_network_cfg.host
                                                != rpcbind)
                        self.current_network_cfg.host = rpcbind
                        if modified:
                            self.is_modified = modified

                        if file.get('server', '1') == '0':
                            self.warnMsg(
                                "Remote dash.conf parameter 'server' is set to '0', so RPC interface will "
                                "not work.")
                        if not rpcuser:
                            self.warnMsg(
                                "Remote dash.conf parameter 'rpcuser' is not set, so RPC interface will  "
                                "not work.")
                        if not rpcpassword:
                            self.warnMsg(
                                "Remote dash.conf parameter 'rpcpassword' is not set, so RPC interface will  "
                                "not work.")
                    self.update_connection_details_ui()
                elif isinstance(dashd_conf, str):
                    self.warnMsg(
                        "Couldn't read remote dashd configuration file due the following error: "
                        + dashd_conf)
                ssh.disconnect()
            except Exception as e:
                self.errorMsg(str(e))
                return
            finally:
                self.disable_cfg_update = False

    def on_btnTestConnection_clicked(self):
        if self.current_network_cfg:
            self.local_config.db_intf = self.config.db_intf
            dashd_intf = DashdInterface(window=self)
            dashd_intf.initialize(self.local_config,
                                  connection=self.current_network_cfg,
                                  for_testing_connections_only=True)
            try:
                info = dashd_intf.getinfo(verify_node=True)
                if info:
                    try:
                        ret = dashd_intf.rpc_call(True, False,
                                                  "checkfeaturesupport",
                                                  "enhanced_proxy")
                    except Exception as e:
                        ret = None

                    if ret and type(ret) is dict:
                        self.infoMsg(
                            'Connection successful.\n\n'
                            'Additional info: this node supports message encryption.'
                        )
                    else:
                        self.infoMsg('Connection successful.')
                else:
                    self.errorMsg(
                        'Connection error. Details: empty return message.')
            except Exception as e:
                self.errorMsg('Connection error. Details: ' + str(e))
            finally:
                del dashd_intf

    def set_modified(self):
        if not self.disable_cfg_update:
            self.is_modified = True

    def get_is_modified(self):
        return self.is_modified

    def apply_config_changes(self):
        """
        Applies changes made by the user by moving the UI controls values to the appropriate
        fields in the self.config object.
        """
        if self.is_modified:
            self.local_config.dash_net_configs.clear()
            self.local_config.dash_net_configs.extend(self.connections_mainnet)
            self.local_config.dash_net_configs.extend(self.connections_testnet)

            self.config.copy_from(self.local_config)
            self.config.conn_config_changed()
            self.config.set_log_level(self.local_config.log_level_str)
            self.config.modified = True

    def on_btnEncryptionPublicKey_clicked(self):
        updated = False
        key_str = self.current_network_cfg.get_rpc_encryption_pubkey_str('PEM')
        while True:
            key_str, ok = QInputDialog.getMultiLineText(
                self, "RPC encryption public key", "RSA public key (PEM/DER):",
                key_str)
            if ok:
                try:
                    self.current_network_cfg.set_rpc_encryption_pubkey(key_str)
                    updated = True
                    break
                except Exception as e:
                    self.errorMsg(str(e))
            else:
                break

        if updated:
            self.set_modified()
            self.update_connection_details_ui()
예제 #57
0
파일: gui.py 프로젝트: LucMiaz/nupdf
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        window = QWidget()
        main = QVBoxLayout()
        main.addWidget(QLabel('PDF manip'))
        layout = QVBoxLayout()
        """self.filetypes=QCheckBox('Get other file types?')
        self.filetypes.setChecked(False)
        main.addWidget(self.filetypes)"""
        self.selectFiles = QPushButton("Insert files")
        self.selectFiles.clicked.connect(self.getfiles)
        self.selectFiles.setFont(normalfont)
        main.addWidget(self.selectFiles)
        self.selectFolder = QPushButton("Insert folder")
        self.selectFolder.clicked.connect(self.getfolder)
        self.selectFolder.setFont(normalfont)
        main.addWidget(self.selectFolder)
        self.boxmerge = QCheckBox('Merge multiple files?')
        self.boxmerge.setChecked(True)
        self.boxmerge.setFont(normalfont)
        main.addWidget(self.boxmerge)
        self.bookmark = QCheckBox('Add bookmarks using file title?')
        self.bookmark.setChecked(True)
        self.bookmark.setFont(normalfont)
        main.addWidget(self.bookmark)
        self.recto_verso = QCheckBox('Recto verso ?')
        self.recto_verso.setChecked(False)
        self.recto_verso.setFont(normalfont)
        main.addWidget(self.recto_verso)
        self.same_file = QCheckBox(
            'If recto verso, are they in two separate files?')
        self.same_file.setChecked(False)
        self.same_file.setFont(normalfont)
        main.addWidget(self.same_file)
        main.addWidget(QLabel('Rotation angle (clockwise)'))
        self.angle = QLineEdit('0')
        self.angle.setValidator(QIntValidator())
        self.angle.setAlignment(Qt.AlignRight)
        self.angle.setFont(normalfont)
        main.addWidget(self.angle)
        main.addWidget(
            QLabel(
                'Pages to rotate (use - for range and ; for single pages, e.g. 1-2;5)'
            ))
        self.pages = QLineEdit('')
        self.pages.setAlignment(Qt.AlignRight)
        self.pages.setFont(normalfont)
        main.addWidget(self.pages)
        self.setLayout(main)
        self.setWindowTitle('nuPDF')
        self.filenames = []
        self.listWidget = QListWidget()
        self.listWidget.setAcceptDrops(True)
        #Resize width and height
        self.listWidget.resize(300, 120)
        self.listWidget.setWindowTitle('Files paths')
        self.listWidget.show()
        self.upBtn = QPushButton('Up', self)
        self.downBtn = QPushButton('Down', self)
        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addWidget(self.upBtn)
        self.buttonLayout.addWidget(self.downBtn)
        main.addLayout(self.buttonLayout)
        main.addWidget(self.listWidget)
        self.runbutton = QPushButton('Start')
        self.runbutton.setFont(normalfont)
        self.runbutton.clicked.connect(self.run)
        self.savingpath = QLineEdit()
        self.savingpath.setFont(normalfont)
        self.setsavingpath = QPushButton("Select saving path")
        self.setsavingpath.setFont(normalfont)
        self.setsavingpath.clicked.connect(self.savefile)
        self.empty = QPushButton('empty files list')
        self.empty.setFont(normalfont)
        self.empty.clicked.connect(self.empty_file_list)
        main.addWidget(self.empty)
        main.addWidget(self.setsavingpath)
        main.addWidget(self.savingpath)
        main.addWidget(self.runbutton)
        self.status = QLabel(
            "Please select the files to work on and where to save the output")
        self.status.setFont(normalfont)
        self.upBtn.clicked.connect(self.upButton)
        self.downBtn.clicked.connect(self.downButton)
        main.addWidget(self.status)

    def upButton(self):
        currentRow = self.listWidget.currentRow()
        currentItem = self.listWidget.takeItem(currentRow)
        self.listWidget.insertItem(currentRow - 1, currentItem)

    def downButton(self):
        currentRow = self.listWidget.currentRow()
        currentItem = self.listWidget.takeItem(currentRow)
        self.listWidget.insertItem(currentRow + 1, currentItem)

    def empty_file_list(self):
        self.listWidget.clear()
        self.filenames = []

    def update_qlist(self):
        self.listWidget.clear()
        self.listWidget.addItems(self.filenames)

    def update_status(self):
        if len(self.filenames) > 0 and self.savingpath != '':
            self.status.setText('Ready')
        elif len(self.filenames) > 0 and self.savingpath == '':
            self.status.setText('Please insert a saving path')
        elif len(self.filenames) == 0 and self.savingpath != '':
            self.status.setText('Please enter at least one file to work on')
        else:
            self.status.setText('Unknown error')

    def getfilesinfolder(self, folderpath):
        return [
            path.join(root, name) for root, dirs, files in walk(folderpath)
            for name in files
            if name.endswith((".pdf", ".PDF", ".jpg", ".jpeg", ".gif", ".GIF",
                              ".JPG", ".JPEG", ".raw", ".RAW", ".PNG", ".png"))
        ]

    def savefile(self):
        self.setsavingpath.setText("Select saving path")
        self.setsavingpath.setFont(normalfont)
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        if dlg.exec_():
            path = dlg.selectedFiles()[0]
            self.savingpath.setText(path)
            if self.savingpath.text()[-4:] != '.pdf':
                path = self.savingpath.text() + ".pdf"
                self.savingpath.setText(path)
        self.update_status()

    def getfiles(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.ExistingFiles)
        if dlg.exec_():
            self.filenames += dlg.selectedFiles()
        self.update_qlist()

    def getfolder(self):
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.Directory)
        if dlg.exec_():
            filesInFolder = self.getfilesinfolder(dlg.selectedFiles()[0])
            self.filenames += filesInFolder
        self.update_qlist()

    def run(self):
        self.status.setText('Processing...')
        if self.savingpath.text() != "":
            self.runbutton.toggle()
            self.runbutton.setCheckable(False)
            if self.boxmerge.isChecked():
                merge = True
                path = self.savingpath.text()
            else:
                merge = False
                path = self.filenames[0]
            if self.bookmark.isChecked():
                bookmark = True
            else:
                bookmark = False
            pages_num = []
            if self.angle.text() and int(self.angle.text()) != 0:
                angle = int(self.angle.text())
            else:
                angle = 0
            pages = self.pages.text()
            same_file = None
            if self.recto_verso.isChecked():
                recto_verso = True
                if self.same_file.isChecked():
                    same_file = True
            else:
                recto_verso = False
            if pages != "":
                from re import findall
                string = r'(([0-9]*)-([0-9]*))|([0-9]*(?![-]))'
                matches = findall(string, pages)
                for m in matches:
                    print(m)
                    if (m[1] != '' and m[2] != ''):
                        try:
                            pages_num += range(int(m[1]) - 1, int([m[2]]))
                        except:
                            pass
                    elif m[3] != '':
                        try:
                            pages_num.append(int(m[3]) - 1)
                        except:
                            pass
            if merge:
                self.status.setText('Merging files...')
                merge_pdfs(self.filenames,
                           self.savingpath.text(),
                           recto_verso=recto_verso,
                           same_file=same_file,
                           bookmark=bookmark)
            if angle != 0:
                print(pages)
                print(pages_num)
                if len(pages_num) > 0:
                    self.status.setText('Rotating pages %s ...' %
                                        ";".join([str(i) for i in pages_num]))
                    rotate_pages(path,
                                 self.savingpath.text(),
                                 pages=pages_num,
                                 angle=angle)
                else:
                    self.status.setText('Rotating all pages ...')
                    rotate_pages(path, self.savingpath.text(), angle=angle)
            self.status.setText('Done. File saved at %s' %
                                self.savingpath.text())
            self.runbutton.toggle()
            self.runbutton.setCheckable(True)
            return self.runbutton
        else:
            self.setsavingpath.setText("**Select saving path**")
            self.setsavingpath.setFont(boldfont)
            self.update_status()
예제 #58
0
class TreeLayerItem(QTreeWidgetItem):
    layerIcon = QIcon(
        os.path.join(os.path.dirname(__file__), "icons", "layer.png"))

    def __init__(self, iface, layer, tree, dlg):
        QTreeWidgetItem.__init__(self)
        self.iface = iface
        self.layer = layer
        self.setText(0, layer.name())
        self.setIcon(0, self.layerIcon)
        project = QgsProject.instance()
        if project.layerTreeRoot().findLayer(layer.id()).isVisible():
            self.setCheckState(0, Qt.Checked)
        else:
            self.setCheckState(0, Qt.Unchecked)
        self.visibleItem = QTreeWidgetItem(self)
        self.visibleCheck = QCheckBox()
        vis = layer.customProperty("qgis2web/Visible", True)
        if (vis == 0 or unicode(vis).lower() == "false"):
            self.visibleCheck.setChecked(False)
        else:
            self.visibleCheck.setChecked(True)
        self.visibleItem.setText(0, "Visible")
        self.addChild(self.visibleItem)
        tree.setItemWidget(self.visibleItem, 1, self.visibleCheck)
        if layer.type() == layer.VectorLayer:
            if layer.providerType() == 'WFS':
                self.jsonItem = QTreeWidgetItem(self)
                self.jsonCheck = QCheckBox()
                if layer.customProperty("qgis2web/Encode to JSON") == 2:
                    self.jsonCheck.setChecked(True)
                self.jsonItem.setText(0, "Encode to JSON")
                self.jsonCheck.stateChanged.connect(self.changeJSON)
                self.addChild(self.jsonItem)
                tree.setItemWidget(self.jsonItem, 1, self.jsonCheck)
            if layer.geometryType() == QgsWkbTypes.PointGeometry:
                self.clusterItem = QTreeWidgetItem(self)
                self.clusterCheck = QCheckBox()
                if layer.customProperty("qgis2web/Cluster") == 2:
                    self.clusterCheck.setChecked(True)
                self.clusterItem.setText(0, "Cluster")
                self.clusterCheck.stateChanged.connect(self.changeCluster)
                self.addChild(self.clusterItem)
                tree.setItemWidget(self.clusterItem, 1, self.clusterCheck)
            self.popupItem = QTreeWidgetItem(self)
            self.popupItem.setText(0, "Popup fields")
            options = []
            fields = self.layer.fields()
            for f in fields:
                fieldIndex = fields.indexFromName(unicode(f.name()))
                editorWidget = layer.editorWidgetSetup(fieldIndex).type()
                if editorWidget == 'Hidden':
                    continue
                options.append(f.name())
            for option in options:
                self.attr = QTreeWidgetItem(self)
                self.attrWidget = QComboBox()
                self.attrWidget.addItem("no label")
                self.attrWidget.addItem("inline label")
                self.attrWidget.addItem("header label")
                custProp = layer.customProperty("qgis2web/popup/" + option)
                if (custProp != "" and custProp is not None):
                    self.attrWidget.setCurrentIndex(
                        self.attrWidget.findText(
                            layer.customProperty("qgis2web/popup/" + option)))
                self.attr.setText(1, option)
                self.popupItem.addChild(self.attr)
                tree.setItemWidget(self.attr, 2, self.attrWidget)
            self.addChild(self.popupItem)
        else:
            if layer.providerType() == 'wms':
                self.getFeatureInfoItem = QTreeWidgetItem(self)
                self.getFeatureInfoCheck = QCheckBox()
                if layer.customProperty("qgis2web/GetFeatureInfo") == 2:
                    self.getFeatureInfoCheck.setChecked(True)
                self.getFeatureInfoItem.setText(0, "Enable GetFeatureInfo?")
                self.getFeatureInfoCheck.stateChanged.connect(
                    self.changeGetFeatureInfo)
                self.addChild(self.getFeatureInfoItem)
                tree.setItemWidget(self.getFeatureInfoItem, 1,
                                   self.getFeatureInfoCheck)

    @property
    def popup(self):
        popup = []
        self.tree = self.treeWidget()
        for p in range(self.childCount()):
            item = self.child(p).text(1)
            if item != "":
                popupVal = self.tree.itemWidget(self.child(p), 2).currentText()
                pair = (item, popupVal)
                popup.append(pair)
        popup = OrderedDict(popup)
        return popup

    @property
    def visible(self):
        return self.visibleCheck.isChecked()

    @property
    def json(self):
        try:
            return self.jsonCheck.isChecked()
        except:
            return False

    @property
    def cluster(self):
        try:
            return self.clusterCheck.isChecked()
        except:
            return False

    @property
    def getFeatureInfo(self):
        try:
            return self.getFeatureInfoCheck.isChecked()
        except:
            return False

    def changeJSON(self, isJSON):
        self.layer.setCustomProperty("qgis2web/Encode to JSON", isJSON)

    def changeCluster(self, isCluster):
        self.layer.setCustomProperty("qgis2web/Cluster", isCluster)

    def changeGetFeatureInfo(self, isGetFeatureInfo):
        self.layer.setCustomProperty("qgis2web/GetFeatureInfo",
                                     isGetFeatureInfo)
예제 #59
0
class Window(QDialog):
    def __init__(self):
        super().__init__()

        self.title = "PyQt5 CheckBox"
        self.top = 200
        self.left = 400
        self.width = 400
        self.height = 100
        self.iconName = "icon.png"

        self.InitWindow()

    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.CreateLayout()

        vbox = QVBoxLayout()

        vbox.addWidget(self.groupBox)

        self.label = QLabel(self)
        self.label.setFont(QtGui.QFont("Sanserif", 15))
        vbox.addWidget(self.label)

        self.setLayout(vbox)

        self.show()

    def CreateLayout(self):
        self.groupBox = QGroupBox(
            "What Is Your Favorite Programming Language ?")
        self.groupBox.setFont(QtGui.QFont("Sanserif", 13))
        hboxLayout = QHBoxLayout()

        self.check1 = QCheckBox("Python")
        self.check1.setIcon(QtGui.QIcon("pythonicon.png"))
        self.check1.setIconSize(QtCore.QSize(40, 40))
        self.check1.setFont(QtGui.QFont("Sanserif", 13))
        self.check1.toggled.connect(self.onCheckbox_toggled)
        hboxLayout.addWidget(self.check1)

        self.check2 = QCheckBox("Java")
        self.check2.setIcon(QtGui.QIcon("java.png"))
        self.check2.setIconSize(QtCore.QSize(40, 40))
        self.check2.setFont(QtGui.QFont("Sanserif", 13))
        self.check2.toggled.connect(self.onCheckbox_toggled)
        hboxLayout.addWidget(self.check2)

        self.check3 = QCheckBox("C++")
        self.check3.setIcon(QtGui.QIcon("cpp.png"))
        self.check3.setIconSize(QtCore.QSize(40, 40))
        self.check3.setFont(QtGui.QFont("Sanserif", 13))
        self.check3.toggled.connect(self.onCheckbox_toggled)
        hboxLayout.addWidget(self.check3)

        self.groupBox.setLayout(hboxLayout)

    def onCheckbox_toggled(self):

        if self.check1.isChecked():
            self.label.setText(" You Have Selected: " + self.check1.text())

        if self.check2.isChecked():
            self.label.setText("You Have Selected : " + self.check2.text())

        if self.check3.isChecked():
            self.label.setText("You Have Selected : " + self.check3.text())
예제 #60
0
class TestWindow(QMainWindow):
    def __init__(self, scope, parent=None):
        super(TestWindow, self).__init__(parent=parent)

        self.scope = scope
        self.chart = pg.GraphicsLayoutWidget()
        self.plot = self.chart.addPlot()
        self.plot.showGrid(y=True)
        self.plot1 = self.plot.plot([], [], pen=(255, 0, 0))
        self.plot2 = self.plot.plot([], [], pen=(0, 255, 0))

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlWidget = QWidget()
        controlWidget.setLayout(controlLayout)

        self.runButton = QPushButton("Get")
        controlLayout.addWidget(self.runButton)

        self.autoCheckBox = QCheckBox("Auto")
        controlLayout.addWidget(self.autoCheckBox)

        self.speedsComboBox = LabeledComboBox(
            label='Timebase',
            items=self.scope.timebaseValues,
            itemLabels=[str(x) for x in self.scope.timebaseNames],
        )
        controlLayout.addWidget(self.speedsComboBox)

        self.trg_pre = LabeledComboBox(
            label='trg_pre',
            items=[str(x) for x in range(0, 100000, 1000)],
            itemLabels=[str(x) for x in range(0, 100000, 1000)],
        )
        self.trg_suf = LabeledComboBox(
            label='trg_suf',
            items=[str(x) for x in range(0, 100000, 1000)],
            itemLabels=[str(x) for x in range(0 - 5000, 100000 - 5000, 1000)],
        )
        self.trg_suf.setCurrentIndex(5)

        self.trg = ScopeTriggerWidget('trigger')

        controlLayout.addWidget(self.speedsComboBox)
        controlLayout.addWidget(self.trg_suf)
        controlLayout.addWidget(self.trg_pre)

        self.timeout = LabeledLineEdit(label="Timeout", text="1.0")
        controlLayout.addWidget(self.timeout)

        self.layout = QVBoxLayout()
        self.layout.addWidget(controlWidget)
        self.channels = [ScopeChannelWidget('1'), ScopeChannelWidget('2')]
        self.layout.addWidget(self.channels[0])
        self.layout.addWidget(self.channels[1])
        self.layout.addWidget(self.trg)
        self.layout.addWidget(self.chart)

        self.layoutWidget = QWidget()
        self.layoutWidget.setLayout(self.layout)

        self.runButton.clicked.connect(self.on_get)

        self.setCentralWidget(self.layoutWidget)

        self.show()

    @pyqtSlot()
    def on_get(self):
        #self.chart.removeAllSeries() # FIXME
        self.plot1.setData([], [])
        self.plot2.setData([], [])

        # Configure Scope
        scope.configure_timebase(self.speedsComboBox.getInt())

        scope.configure_trg_pre(self.trg_pre.getInt())
        scope.configure_trg_suf(self.trg_suf.getInt())

        scope.timeout = float(self.timeout.getText())

        for i in [0, 1]:
            params = self.channels[i].getParams()
            scope.setVoltage(i, params['voltage'])
            scope.setCoupling(i, params['coupling'])

            scope.configure_channel(i)

        trgParams = self.trg.getParams()

        scope.configure_trg(trgParams['triggerMode'],
                            trgParams['triggerChannel'],
                            trgParams['triggerExtraMode'])
        scope.configure_trg_edge_level((trgParams['pulseHigh'] << 8)
                                       | trgParams['pulseLow'])

        self.scope.capture_start()

        # Get the data and plot it
        (ch1data, ch2data) = self.scope.get_data()

        # TODO: set it only when user changes vdiv?
        range1 = self.scope.scope.get_range(0)
        range2 = self.scope.scope.get_range(1)
        self.plot.getViewBox().setYRange(min(range1[0], range2[0]),
                                         max(range1[1], range2[1]))

        timebaseVal = scope.timebaseDiv[scope.timebaseValues.index(
            self.speedsComboBox.getInt())]

        if self.channels[0].getParams()['on']:
            self.add_data(self.plot1, ch1data, Qt.red, timebaseVal)
        if self.channels[1].getParams()['on']:
            self.add_data(self.plot2, ch2data, Qt.blue, timebaseVal)

        if self.autoCheckBox.isChecked():
            QTimer.singleShot(200, self.on_get)

    def add_data(self, plot, ydata, color, timebase):
        plot.setData(np.array(range(len(ydata))) / timebase, np.array(ydata))