class UiColormapDialog(object):
    """
    UiAddMicrographDialog
    User interface for the add micrograph dialog which is used to import a micrograph into the program.
    """
    def __init__(self, colormap_dialog):

        # set window title, object name and window size
        colormap_dialog.setWindowTitle("Choose Colormap")
        colormap_dialog.setObjectName("ColormapDialog")
        colormap_dialog.setFixedWidth(455)
        colormap_dialog.setFixedHeight(100)

        # button box
        self.button_box = QDialogButtonBox(colormap_dialog)
        self.button_box.setEnabled(True)
        self.button_box.setGeometry(QRect(10, 60, 435, 30))
        self.button_box.setOrientation(Qt.Horizontal)
        self.button_box.setStandardButtons(QDialogButtonBox.Cancel
                                           | QDialogButtonBox.Ok)
        self.button_box.setObjectName("button_box")

        # colormap selector
        self.colormap_combobox = QComboBox(colormap_dialog)
        self.colormap_combobox.setGeometry(QRect(10, 10, 435, 30))
        self.colormap_combobox.setIconSize(QSize(435, 20))

        # connect accept and reject
        self.button_box.accepted.connect(colormap_dialog.accept)
        self.button_box.rejected.connect(colormap_dialog.reject)
Beispiel #2
0
class DatePopup(QDialog):
    def __init__(self):
        super(Qt.Popup, self).__init__()
        self.setSizeGripEnabled(False)
        self.resize(260, 230)
        self.widget = QWidget(self)
        self.widget.setObjectName(QtCore.QString.fromUtf8("self.widget"))
        self.widget.setGeometry(QRect(0, 10, 258, 215))

        self.verticalLayout = QVBoxLayout(self.widget)
        self.verticalLayout.setObjectName(
            QtCore.QString.fromUtf8("self.verticalLayout"))
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)

        self.calendarWidget = QCalendarWidget(self.widget)
        self.calendarWidget.setObjectName(
            QtCore.QString.fromUtf8("calendarWidget"))

        self.verticalLayout.addWidget(self.calendarWidget)

        self.buttonBox = QDialogButtonBox(self.widget)
        self.buttonBox.setObjectName(QtCore.QString.fromUtf8("self.buttonBox"))
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)

        self.verticalLayout.addWidget(self.buttonBox)

        QObject.self.buttonBox.accepted.connect(self.accept)
        QObject.self.buttonBox.rejected.connect(self.reject)

    def selected_date(self):
        return self.calendarWidget.selectedDate()
class PopUpInfo(QDialog):
    """
    Abstract Base Class, inherting from QDialog,
    extended by Warning and Notification popup
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, text):
        """
        init
        :param text: info text in main window of popup
        """
        super(PopUpInfo, self).__init__()

        # call gui building functions
        self._create_main_layout()
        self._create_text_label(text)
        self._create_buttons()

    def _create_main_layout(self):
        """
        Presets and main layout
        """
        self.verticalLayout_warning = QVBoxLayout()
        self.verticalLayout_warning.setObjectName("verticalLayout_warning")
        self.setLayout(self.verticalLayout_warning)

    def _create_text_label(self, text):
        """
        creates main message label from
        :param text: string or list of strings
        """
        if isinstance(text, str):
            # text label
            self.label_Warning = QLabel()
            self.label_Warning.setObjectName("label_Warning")
            # set text
            text, latex_bool = detect_latex_in_string(text)
            if latex_bool:  # either way pixmap from latex
                self.label_Warning.setPixmap(text)
            else:  # or plain text
                self.label_Warning.setText(text)
            self.label_Warning.setAlignment(Qt.AlignCenter)
            self.verticalLayout_warning.addWidget(self.label_Warning)
        elif isinstance(text, list):
            self.list_warning = QListWidget()
            self.list_warning.addItems(text)
            self.verticalLayout_warning.addWidget(self.list_warning)

    def _create_buttons(self):
        """
        OK / cancel buttons
        """
        self.buttons_okcancel = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        self.buttonBox_okcancel = QDialogButtonBox(self.buttons_okcancel)
        self.buttonBox_okcancel.setObjectName("buttonBox_Warning")
        self.buttonBox_okcancel.accepted.connect(self.accept)
        self.buttonBox_okcancel.rejected.connect(self.reject)
        self.verticalLayout_warning.addWidget(self.buttonBox_okcancel)
Beispiel #4
0
class Ui_ChooseSlot(object):
    def setupUi(self, ChooseSlot, buttonlabels):
        ChooseSlot.setObjectName("ChooseSlot")
        ChooseSlot.setWindowModality(Qt.ApplicationModal)

        sizePolicy = QSizePolicy(QSizePolicy.Policy(0), QSizePolicy.Policy(0))
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            ChooseSlot.sizePolicy().hasHeightForWidth())
        ChooseSlot.setSizePolicy(sizePolicy)

        self.vboxlayout = QVBoxLayout(ChooseSlot)
        self.vboxlayout.setMargin(9)
        self.vboxlayout.setSpacing(6)
        self.vboxlayout.setObjectName("vboxlayout")

        self.vboxlayout1 = QVBoxLayout()
        self.vboxlayout1.setMargin(9)
        self.vboxlayout1.setSpacing(6)
        self.vboxlayout1.setObjectName("vboxlayout1")

        self.Label = QLabel(ChooseSlot)
        self.Label.setObjectName("Label")
        self.vboxlayout1.addWidget(self.Label)

        self.Buttons = []

        for button in buttonlabels:
            self.Buttons.append(QRadioButton(ChooseSlot))
            self.Buttons[-1].setObjectName("Button[%d]" %
                                           (len(self.Buttons) - 1))
            self.Buttons[-1].setText(
                QApplication.translate("ChooseSlot", button, None,
                                       QApplication.UnicodeUTF8))
            self.vboxlayout1.addWidget(self.Buttons[-1])

        if len(self.Buttons):
            self.Buttons[0].setChecked(Qt.Checked)

        self.vboxlayout.addLayout(self.vboxlayout1)

        self.buttonBox = QDialogButtonBox(ChooseSlot)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.vboxlayout.addWidget(self.buttonBox)

        self.retranslateUi(ChooseSlot)
        ChooseSlot.resize(ChooseSlot.minimumSizeHint())
        QMetaObject.connectSlotsByName(ChooseSlot)

    def retranslateUi(self, ChooseSlot):
        ChooseSlot.setWindowTitle(
            QApplication.translate("ChooseSlot", "Choose Slot", None,
                                   QApplication.UnicodeUTF8))
        self.Label.setText(
            QApplication.translate("ChooseSlot", "Add Item to Slot", None,
                                   QApplication.UnicodeUTF8))
Beispiel #5
0
class Ui_gridDialog(object):
    def setupUi(self, gridDialog):
        gridDialog.setObjectName(_fromUtf8("gridDialog"))
        gridDialog.setWindowModality(QtCore.Qt.ApplicationModal)
        gridDialog.setSizeGripEnabled(True)
        gridDialog.setModal(True)
        self.verticalLayout = QVBoxLayout(gridDialog)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.gridView = aqt.webview.AnkiWebView(gridDialog)  #MANUAL EDIT
        # PDB new page of inherited class URLClickPage to intercept the hyperlink clicks
        replPage = URLClickPage(self.gridView._onBridgeCmd)
        self.gridView._page = replPage
        self.gridView._page.setBackgroundColor(
            self.gridView._getWindowColor())  # reduce flicker
        self.gridView.setPage(replPage)
        self.gridView._page.profile().setHttpCacheType(
            QWebEngineProfile.NoCache)  # type: ignore

        #self.gridView = QtWebKit.QWebView(gridDialog)
        self.gridView.setUrl(QtCore.QUrl(_fromUtf8("about:blank")))
        self.gridView.setObjectName(_fromUtf8("gridView"))
        self.verticalLayout.addWidget(self.gridView)
        self.buttonBox = QDialogButtonBox(gridDialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)    #MANUALLY DISABLED
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.verticalLayout.addWidget(self.buttonBox)
        self.retranslateUi(gridDialog)
        QtCore.QMetaObject.connectSlotsByName(gridDialog)

    def retranslateUi(self, gridDialog):
        gridDialog.setWindowTitle(_translate("gridDialog", "Dialog", None))
Beispiel #6
0
class ModelDialog(QDialog):
    """ModelDialog is the basic structure behind model dialogs in CATScore.
    # Arguments
        param_path: String, path to default parameters .json file.
    """
    def __init__(self, param_path={}, parent=None):
        super(ModelDialog, self).__init__(parent)
        self.default_params = self._getParams(param_path)
        print("Default params:")
        print(json.dumps(self.default_params, indent=2))
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttonBox.setObjectName("model_buttonbox")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.model_groupbox = QGroupBox()
        self.model_groupbox.setTitle("Model hyperparameters")
        self.tfidf_groupbox = QGroupBox()
        self.tfidf_groupbox.setTitle('TF-IDF hyperparameters')

        self.main_layout = QVBoxLayout()
        self.form_layout = QFormLayout()

        
    def saveParams(self):
        """Saves the parameters entered by the user.  
        """
        print("Default params after save:")
        print(json.dumps(self.default_params, indent=2))
        if (self.exec_() == QDialog.Accepted):
            input_widgets = (self.form_layout.itemAt(i).widget() for i in range(self.form_layout.count()))
            for widget in input_widgets:
                if isinstance(widget, QDoubleSpinBox):
                    print('"' + widget.objectName() + '": {},'.format(widget.value()))
                if isinstance(widget, QComboBox):
                    print('"' + widget.objectName() + '": {},'.format(widget.currentData()))

        else:
            print("Denied!")

    def _getParams(self, path):
        print("Path: {}".format(path))
        svc_params = {
                        "clf__C": 1,
                        "clf__class_weight": None,
                        "clf__kernel": "linear",
                        "clf__tol": 0.001,
                        "clf__cache_size": 200,
                        "tfidf__max_df": 0.5,
                        "tfidf__min_df": 2,
                        "tfidf__ngram_range": [
                            1,
                            2
                        ],
                        "tfidf__stop_words": None,
                        "tfidf__strip_accents": "unicode",
                        "tfidf__use_idf": False
                    }
        return svc_params
Beispiel #7
0
class UiExportDialog(object):
    """
    UiExportDialog
    User interface for the export dialog that is used in order to export data from the program.
    """
    def __init__(self, export_dialog):

        # set window title, object name and window size
        export_dialog.setWindowTitle("Export Data")
        export_dialog.setObjectName("export_dialog")
        export_dialog.setFixedWidth(242)
        export_dialog.setFixedHeight(174)

        # button box
        self.button_box = QDialogButtonBox(export_dialog)
        self.button_box.setGeometry(QRect(10, 130, 221, 41))
        self.button_box.setOrientation(Qt.Horizontal)
        self.button_box.setStandardButtons(QDialogButtonBox.Cancel
                                           | QDialogButtonBox.Ok)
        self.button_box.setObjectName("button_box")

        # group box for data selection
        self.group_box = QGroupBox(export_dialog)
        self.group_box.setGeometry(QRect(10, 10, 231, 61))
        self.group_box.setObjectName("group_box")
        self.group_box.setTitle("Dialog")

        # combo box for data selection
        self.data_combo_box = QComboBox(self.group_box)
        self.data_combo_box.setGeometry(QRect(60, 25, 160, 27))
        self.data_combo_box.setObjectName("data_combo_box")

        # group box for type selection
        self.group_box_2 = QGroupBox(export_dialog)
        self.group_box_2.setGeometry(QRect(10, 70, 231, 61))
        self.group_box_2.setObjectName("group_box_2")
        self.group_box_2.setTitle("Dialog")

        # combo box for type selection
        self.type_combo_box = QComboBox(self.group_box_2)
        self.type_combo_box.setGeometry(QRect(60, 25, 160, 27))
        self.type_combo_box.setObjectName("type_combo_box")
        self.type_combo_box.addItems(['ASCII'])

        # labels
        self.label = QLabel(self.group_box)
        self.label.setGeometry(QRect(0, 25, 61, 27))
        self.label.setObjectName("label")
        self.label.setText("Dialog")
        self.label_2 = QLabel(self.group_box_2)
        self.label_2.setGeometry(QRect(0, 25, 61, 27))
        self.label_2.setObjectName("label_2")
        self.label_2.setText("Dialog")

        # connect accept and reject
        self.button_box.accepted.connect(export_dialog.accept)
        self.button_box.rejected.connect(export_dialog.reject)
Beispiel #8
0
    def configure_dialogs(self):
        self.path_dialog.setAcceptMode(QFileDialog.AcceptOpen)

        self.finish_dialog.resize(150, 100)
        button_box = QDialogButtonBox(self.finish_dialog)
        horizontal_layout = QHBoxLayout(self.finish_dialog)
        button_box.setStandardButtons(QDialogButtonBox.Ok)
        button_box.setObjectName("button_box")
        horizontal_layout.addWidget(button_box)
        button_box.accepted.connect(self.finish_dialog.accept)
Beispiel #9
0
class PasswordPop(QDialog):
    def __init__(self, parent):
        super().__init__(None)
        self.setupUi()
        self.hookElems()
        self.retranslateUi()
        self.parent = parent
        if self.parent.options.pswdcanceled:
            self.parent.options.pswdcanceled = False

    def hookElems(self):
        self.buttonBox.accepted.connect(self.getpswd)
        self.buttonBox.rejected.connect(self.cancel)

    def setupUi(self):
        if not self.objectName():
            self.setObjectName(u"Password")
        self.resize(309, 137)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setObjectName(u"buttonBox")
        self.buttonBox.setGeometry(QRect(70, 90, 171, 31))
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.lineEdit = QLineEdit(self)
        self.lineEdit.setObjectName(u"lineEdit")
        self.lineEdit.setGeometry(QRect(70, 50, 171, 28))
        self.lineEdit.setFrame(True)
        self.lineEdit.setEchoMode(QLineEdit.Password)
        self.label = QLabel(self)
        self.label.setObjectName(u"label")
        self.label.setGeometry(QRect(10, 20, 291, 20))
        self.label.setLayoutDirection(Qt.LeftToRight)
        self.label.setAlignment(Qt.AlignCenter)

        QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        self.setWindowTitle(
            QCoreApplication.translate("self", u"Password", None))
        self.label.setText(
            QCoreApplication.translate(
                "self", u"Please enter your wallet passphrase:", None))

    def getpswd(self):
        self.parent.options.passphrase = self.lineEdit.text()
        self.accept()

    def cancel(self):
        self.parent.options.pswdcanceled = True
        self.close()
class AuthenticateDialog(QDialog):
    def __init__(self, parent=None):
        #super(AuthenticateDialog, self).__init__(parent)
        QDialog.__init__(self, parent)
        self.setWindowTitle('Введите имя пользователя')
        self.setupUi(self)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(261, 134)
        self.username_edit = QLineEdit(Dialog)
        self.username_edit.setGeometry(QRect(70, 20, 171, 20))
        self.username_edit.setObjectName("username_edit")
        self.password_edit = QLineEdit(Dialog)
        self.password_edit.setGeometry(QRect(70, 60, 171, 20))
        self.password_edit.setObjectName("password_edit")
        self.username_label = QLabel(Dialog)
        self.username_label.setGeometry(QRect(10, 20, 47, 13))
        self.username_label.setObjectName("username_label")
        self.password_label = QLabel(Dialog)
        self.password_label.setGeometry(QRect(10, 60, 47, 13))
        self.password_label.setObjectName("password_label")
        self.buttons = QDialogButtonBox(Dialog)
        self.buttons.setGeometry(QRect(130, 90, 111, 41))
        self.buttons.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.buttons.setObjectName("buttons")
        self.retranslateUi(Dialog)
        QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Авторизация"))
        self.username_label.setText(_translate("Dialog", "Логин:"))
        self.password_label.setText(_translate("Dialog", "Пароль:"))

    # Получить имя из диалога
    def username(self):
        return self.username_edit.text(), self.password_edit.text()

    # Создать диалог и вернуть юзернейм
    @staticmethod
    def get_username(parent=None):
        dialog = AuthenticateDialog(parent)
        result = dialog.exec_()
        name, password = dialog.username()
        return name, password, result == QDialog.Accepted
Beispiel #11
0
class AreYouShureToDel(QDialog):
    def __init__(self, MainWindow):
        super().__init__()
        self.MainWindow = MainWindow
        ##setupUi
        self.setGeometry(400, 400, 381, 210)
        self.label = QLabel("Вы уверены?", self)
        self.label.setGeometry(75, 50, 200, 50)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label.setFont(font)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(QtCore.QRect(20, 160, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        ##
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.accepted.connect(MainWindow.del_session)
Beispiel #12
0
class ChooseStagePopupUI:
    def __init__(self):
        self._stage_select_combobox = None  # type: QComboBox
        self._dialog_button_box = None  # type: QDialogButtonBox
        self._choose_stage_label = None  # type: QLabel
        self._stage_base_names = []

    def _setup_ui(self, choose_stage_popup):
        choose_stage_popup.setObjectName("choose_stage_popupI")
        choose_stage_popup.resize(493, 108)

        self._stage_select_combobox = QComboBox(choose_stage_popup)
        self._stage_select_combobox.setGeometry(QtCore.QRect(10, 30, 471, 27))
        self._stage_select_combobox.setObjectName("stage_select_combobox")
        self._load_stages()

        self._dialog_button_box = QDialogButtonBox(choose_stage_popup)
        self._dialog_button_box.setGeometry(QtCore.QRect(150, 70, 176, 27))
        self._dialog_button_box.setStandardButtons(QDialogButtonBox.Cancel
                                                   | QDialogButtonBox.Ok)
        self._dialog_button_box.setObjectName("dialog_button_box")
        self._dialog_button_box.rejected.connect(self.close)

        self._choose_stage_label = QLabel(choose_stage_popup)
        self._choose_stage_label.setGeometry(QtCore.QRect(10, 10, 461, 17))
        self._choose_stage_label.setObjectName("choose_stage_label")
        self._choose_stage_label.setText(
            "Choose monkeyball stage to replace (Challenge Mode)")

        choose_stage_popup.setWindowTitle("Choose Stage to Replace")

    def _load_stages(self):
        with open(
                os.path.join(get_mbreplacer_dir(), 'resources',
                             'challenge_stages_list.txt'), 'r') as f:
            for line in f:
                clean_line = line.strip()
                self._stage_select_combobox.addItem(clean_line)
                self._stage_base_names.append(clean_line)
Beispiel #13
0
class Ui_WineASIOSettings(object):
    OBJECT_NAME = "WineASIOSettings"

    def setupUi(self, WineASIOSettings):
        WineASIOSettings.setObjectName(self.OBJECT_NAME)
        WineASIOSettings.resize(400, 310)
        self.verticalLayout = QVBoxLayout(WineASIOSettings)
        self.verticalLayout.setObjectName("verticalLayout")
        self.group_ports = QGroupBox(WineASIOSettings)
        self.group_ports.setObjectName("group_ports")
        self.verticalLayout_22 = QVBoxLayout(self.group_ports)
        self.verticalLayout_22.setObjectName("verticalLayout_22")
        self.layout_ports_in = QHBoxLayout()
        self.layout_ports_in.setObjectName("layout_ports_in")
        self.label_ports_in = QLabel(self.group_ports)
        self.label_ports_in.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                         | Qt.AlignVCenter)
        self.label_ports_in.setObjectName("label_ports_in")
        self.layout_ports_in.addWidget(self.label_ports_in)
        self.sb_ports_in = QSpinBox(self.group_ports)
        self.sb_ports_in.setMaximum(128)
        self.sb_ports_in.setSingleStep(2)
        self.sb_ports_in.setObjectName("sb_ports_in")
        self.layout_ports_in.addWidget(self.sb_ports_in)
        self.verticalLayout_22.addLayout(self.layout_ports_in)
        self.layout_ports_out = QHBoxLayout()
        self.layout_ports_out.setObjectName("layout_ports_out")
        self.label_ports_out = QLabel(self.group_ports)
        self.label_ports_out.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                          | Qt.AlignVCenter)
        self.label_ports_out.setObjectName("label_ports_out")
        self.layout_ports_out.addWidget(self.label_ports_out)
        self.sb_ports_out = QSpinBox(self.group_ports)
        self.sb_ports_out.setMinimum(2)
        self.sb_ports_out.setMaximum(128)
        self.sb_ports_out.setSingleStep(2)
        self.sb_ports_out.setObjectName("sb_ports_out")
        self.layout_ports_out.addWidget(self.sb_ports_out)
        self.verticalLayout_22.addLayout(self.layout_ports_out)
        self.layout_ports_connect_hw = QHBoxLayout()
        self.layout_ports_connect_hw.setObjectName("layout_ports_connect_hw")
        spacerItem = QSpacerItem(150, 20, QSizePolicy.Fixed,
                                 QSizePolicy.Minimum)
        self.layout_ports_connect_hw.addItem(spacerItem)
        self.cb_ports_connect_hw = QCheckBox(self.group_ports)
        self.cb_ports_connect_hw.setObjectName("cb_ports_connect_hw")
        self.layout_ports_connect_hw.addWidget(self.cb_ports_connect_hw)
        self.verticalLayout_22.addLayout(self.layout_ports_connect_hw)
        self.verticalLayout.addWidget(self.group_ports)
        self.group_jack = QGroupBox(WineASIOSettings)
        self.group_jack.setObjectName("group_jack")
        self.verticalLayout_23 = QVBoxLayout(self.group_jack)
        self.verticalLayout_23.setObjectName("verticalLayout_23")
        self.layout_jack_autostart = QHBoxLayout()
        self.layout_jack_autostart.setObjectName("layout_jack_autostart")
        spacerItem1 = QSpacerItem(150, 20, QSizePolicy.Fixed,
                                  QSizePolicy.Minimum)
        self.layout_jack_autostart.addItem(spacerItem1)
        self.cb_jack_autostart = QCheckBox(self.group_jack)
        self.cb_jack_autostart.setObjectName("cb_jack_autostart")
        self.layout_jack_autostart.addWidget(self.cb_jack_autostart)
        self.verticalLayout_23.addLayout(self.layout_jack_autostart)
        self.layout_jack_fixed_bsize = QHBoxLayout()
        self.layout_jack_fixed_bsize.setObjectName("layout_jack_fixed_bsize")
        spacerItem2 = QSpacerItem(150, 20, QSizePolicy.Fixed,
                                  QSizePolicy.Minimum)
        self.layout_jack_fixed_bsize.addItem(spacerItem2)
        self.cb_jack_fixed_bsize = QCheckBox(self.group_jack)
        self.cb_jack_fixed_bsize.setObjectName("cb_jack_fixed_bsize")
        self.layout_jack_fixed_bsize.addWidget(self.cb_jack_fixed_bsize)
        self.verticalLayout_23.addLayout(self.layout_jack_fixed_bsize)
        self.layout_jack_buffer_size = QHBoxLayout()
        self.layout_jack_buffer_size.setObjectName("layout_jack_buffer_size")
        self.label_jack_buffer_size = QLabel(self.group_jack)
        self.label_jack_buffer_size.setAlignment(Qt.AlignRight
                                                 | Qt.AlignTrailing
                                                 | Qt.AlignVCenter)
        self.label_jack_buffer_size.setObjectName("label_jack_buffer_size")
        self.layout_jack_buffer_size.addWidget(self.label_jack_buffer_size)
        self.cb_jack_buffer_size = QComboBox(self.group_jack)
        self.cb_jack_buffer_size.setObjectName("cb_jack_buffer_size")
        self.layout_jack_buffer_size.addWidget(self.cb_jack_buffer_size)
        self.verticalLayout_23.addLayout(self.layout_jack_buffer_size)
        self.verticalLayout.addWidget(self.group_jack)
        self.buttonBox = QDialogButtonBox(WineASIOSettings)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok
                                          | QDialogButtonBox.RestoreDefaults)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi(WineASIOSettings)
        self.buttonBox.accepted.connect(WineASIOSettings.accept)
        self.buttonBox.rejected.connect(WineASIOSettings.reject)
        QMetaObject.connectSlotsByName(WineASIOSettings)

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

    def retranslateUi(self, WineASIOSettings):
        _tr = QCoreApplication.translate
        WineASIOSettings.setWindowTitle(
            _tr(self.OBJECT_NAME, "WineASIO Settings"))

        # Audio Ports
        self.group_ports.setTitle(_tr(self.OBJECT_NAME, "Audio Ports"))

        self.label_ports_in.setText(_tr(self.OBJECT_NAME, "Number of inputs:"))
        self.label_ports_in.setToolTip(
            _tr(
                self.OBJECT_NAME,
                "Number of jack ports that wineasio will try to open.\n"
                "Default is 16"))

        self.sb_ports_in.setToolTip(
            _tr(
                self.OBJECT_NAME,
                "Number of jack ports that wineasio will try to open.\n"
                "Default is 16"))

        self.label_ports_out.setText(
            _tr(self.OBJECT_NAME, "Number of outputs:"))
        self.label_ports_out.setToolTip(
            _tr(
                self.OBJECT_NAME,
                "Number of jack ports that wineasio will try to open.\n"
                "Default is 16"))

        self.sb_ports_out.setToolTip(
            _tr(
                self.OBJECT_NAME,
                "Number of jack ports that wineasio will try to open.\n"
                "Default is 16"))

        self.cb_ports_connect_hw.setText(
            _tr(self.OBJECT_NAME, "Connect to hardware"))
        self.cb_ports_connect_hw.setToolTip(
            _tr(
                self.OBJECT_NAME, "Try to connect the asio channels to the\n"
                "physical I/O ports on your hardware.\n"
                "Default is on"))

        # JACK Options
        self.group_jack.setTitle(_tr(self.OBJECT_NAME, "JACK Options"))

        self.cb_jack_autostart.setText(
            _tr(self.OBJECT_NAME, "Autostart server"))
        self.cb_jack_autostart.setToolTip(
            _tr(
                self.OBJECT_NAME,
                "Enable wineasio to launch the jack server.\n"
                "Default is off"))

        self.cb_jack_fixed_bsize.setText(
            _tr(self.OBJECT_NAME, "Fixed buffersize"))
        self.cb_jack_fixed_bsize.setToolTip(
            _tr(
                self.OBJECT_NAME,
                "When on, an asio app will be able to change the jack buffer size.\n"
                "Default is off"))

        self.label_jack_buffer_size.setText(
            _tr(self.OBJECT_NAME, "Preferred buffersize:"))
Beispiel #14
0
class SkModelDialog(BaseModelDialog):
    '''
    SkModelDialog is the basic structure behind model dialogs in CATScore.

    # Arguments
        model_params: String, path to default parameters .json file.
        tfidf_params: String, path to default TF-IDF param file.
        fs_params: String, path to default feature selection file.
    '''

    # ! TODO: Update to use CONFIG values
    def __init__(self, parent=None, *params):
        super(BaseModelDialog, self).__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.comms = Communicate()
        self.comms.check_for_existing_model.connect(self.parent().model_exists)

        self.model_params = {}
        self.updated_params = {}
        self.ui_widgets = []
        # input_widgets is a list of all dynamically created input widgets for the various model params.
        # Holds EVERY input widget, regardless of type.  Key = hyperparameter name
        self.input_widgets = {}
        self.current_version = 'default'
        self.params = params
        self.main_model_name = params[0]['model_class']
        for param in self.params:
            cls_name = param['model_class']
            full_name = param['model_module'] + '.' + param['model_class']
            self.model_params[full_name] = param[cls_name]
            self.updated_params[full_name] = {}

        self.is_dirty = False
        self.check_for_default()

        self.setWindowTitle(self.main_model_name)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Apply
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.setObjectName('model_buttonbox')
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.buttonBox.rejected.connect(self.reject)

        self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(
            lambda: self.update_version(self.current_version))

        self.buttonBox.button(QDialogButtonBox.Apply).clicked.connect(
            lambda: self.apply_changes())
        self.main_layout = QVBoxLayout()
        self.form_grid = QGridLayout()
        self.version_item_combobox = QComboBox()
        self.version_item_combobox.insertPolicy = QComboBox.InsertAtBottom
        self.version_item_combobox.currentIndexChanged.connect(
            lambda state, y=self.version_item_combobox: self.
            load_version_params(y.currentData()))
        self.form_grid.addWidget(self.version_item_combobox, 0, 0)
        self.performance_hbox = QHBoxLayout()
        self.training_meta_form = QFormLayout()
        self.tuning_meta_form = QFormLayout()
        self.performance_hbox.addLayout(self.training_meta_form)
        self.performance_hbox.addLayout(self.tuning_meta_form)
        self.performance_meta_groupbox = QGroupBox('Performance Meta')
        self.performance_meta_groupbox.setLayout(self.performance_hbox)
        # NOTE: Removed Performance UI display for now.
        # self.form_grid.addWidget(self.performance_meta_groupbox, 1, 0)
        # self.setupPerformanceUI()

        row = 1
        col = 0
        for model, types in self.model_params.items():
            for t, params in types.items():
                groupbox = QGroupBox()
                groupbox.setTitle(model.split('.')[-1] + ' ' + t)
                model_param_form = QFormLayout()
                groupbox.setLayout(model_param_form)
                self.form_grid.addWidget(groupbox, row, col)
                col += 1
                self.ui_widgets.append(groupbox)
                self.ui_widgets.append(model_param_form)
                self.setupUI(model, params, model_param_form)

        self.main_layout.addLayout(self.form_grid)
        self.main_layout.addWidget(self.buttonBox)
        self.setLayout(self.main_layout)

    def apply_changes(self):
        version = self.current_version.split('\\')[-1]
        if version == 'default':
            # print('Default version selected.  Returning...')
            return
        if self.is_dirty:
            filename = self.main_model_name + '.json'
            save_dir = os.path.join(self.version_item_combobox.currentData(),
                                    self.main_model_name)

            if not os.path.isdir(save_dir):
                os.mkdir(save_dir)

            save_file_path = os.path.join(save_dir, filename)

            if not os.path.isfile(save_file_path):
                # Get default file and load those values
                default_dir = os.path.join(
                    '.\\package\\data\\default_models\\default',
                    self.main_model_name)
                default_path = os.path.join(default_dir,
                                            self.main_model_name + '.json')
                with open(default_path, 'r') as infile:
                    full_default_params = json.load(infile)
                # save_data = {
                #     'model_base': self.params[0]['model_base'],
                #     'model_module': self.params[0]['model_module'],
                #     'model_class': self.main_model_name,
                #     'question_number': self.version_item_combobox.currentData().split('\\')[-1],
                #     'version': version,
                #     'tuned': False,
                #     'params': {}
                # }
                # save_data['params'] = full_default_params['params']
                full_default_params.update({
                    "question_number":
                    self.version_item_combobox.currentData().split('\\')[-1],
                    "version":
                    version
                })
                save_data = full_default_params.copy()
            else:
                with open(save_file_path, 'r') as infile:
                    save_data = json.load(infile)

            for param_type, params in self.updated_params.items():
                if (params):
                    for param, val in params.items():
                        save_data['params'][param_type][param] = val
            try:
                with open(save_file_path, 'w') as outfile:
                    json.dump(save_data, outfile, cls=CATEncoder, indent=2)
            except Exception as e:
                self.logger.error(
                    'Error saving updated model parameters for {}.'.format(
                        self.main_model_name),
                    exc_info=True)
                print('Exception {}'.format(e))
                tb = traceback.format_exc()
                print(tb)

        self.is_dirty = False
        return

    def setupUI(self, param_type, param_dict, form):
        '''
        Build UI elements using parameters dict of scikit models

            # Attributes:
                param_type: String, type of param to update
                param_dict: dict, dictionary of parameter/default values from model.
                default_params: dict, dictionary of default parameters defined by me.
        '''
        try:
            for k, v in param_dict.items():
                label_string = k
                label = QLabel(label_string)
                val_type = v['type']
                if val_type == 'dropdown':
                    input_field = QComboBox(objectName=k)
                    for name, value in v['options'].items():
                        input_field.addItem(name, value)
                    idx = input_field.findData(v['default'])
                    if idx != -1:
                        input_field.setCurrentIndex(idx)
                    input_field.currentIndexChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, y.currentData()))
                    # form.addRow(label, input_field)
                    # self.input_widgets[k] = input_field

                elif val_type == 'double':
                    input_field = QDoubleSpinBox(objectName=k)
                    input_field.setDecimals(v['decimal_len'])
                    input_field.setRange(v['min'], v['max'])
                    if v['default'] is not None:
                        input_field.setValue(v['default'])
                    input_field.setSingleStep(v['step_size'])
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, y.value()))

                elif val_type == 'int':
                    input_field = QSpinBox(objectName=k)
                    input_field.setRange(v['min'], v['max'])
                    if v['default'] is not None:
                        input_field.setValue(v['default'])
                    input_field.setSingleStep(v['step_size'])
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, y.value()))
                elif val_type == 'range':
                    label_string = k
                    label = QLabel(label_string + ' : 1,')
                    input_field = QSpinBox(objectName=k)
                    input_field.setRange(v['min'], v['max'])
                    if v['default'] is not None:
                        input_field.setValue(v['default'][-1])
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, [1, y.value()]))
                elif val_type == 'static':
                    label_string = k
                    input_field = QLineEdit(objectName=k)
                    input_field.setText(str(v['default']))
                    # input_field.textColor(QColor.red())
                    input_field.setEnabled(False)
                    self._update_param(param_type, k, v['default'])
                if v['tooltip'] is not None:
                    input_field.setToolTip(v['tooltip'])
                form.addRow(label, input_field)
                self.input_widgets[k] = input_field
        except Exception as e:
            self.logger.error('Error generating {} dialog.', exc_info=True)
            print('Exception {} occured with key {} and value {}'.format(
                e, k, v))
            tb = traceback.format_exc()
            print(tb)

    def load_version_params(self, path):
        '''
        Loads parameters from the selected version for a specific question.  
        Resets parameters to default prior to loading.
        If default or None is selected, returns after reload.  

            # Attributes
                path: String, path to version parameters.  
        '''
        # Reset input parameters
        for model, types in self.model_params.items():
            for t, params in types.items():
                self.set_input_params(params)
        # If true, default (or none available) selected, thus Return
        if path == None or path == 'default':
            self.is_dirty = False
            return

        filename = self.main_model_name + '.json'
        model_data = {}
        try:
            with open(os.path.join(path, self.main_model_name, filename),
                      'r') as f:
                model_data = json.load(f)
            model_class = model_data['model_class']
            for kind, params in model_data['params'].items():
                self.set_input_params(params)

            self.is_dirty = False
        except FileNotFoundError as fnfe:
            pass
        except Exception as e:
            self.logger.error(f'Error updating {model} parameters',
                              exc_info=True)
            print('Exception {}'.format(e))
            tb = traceback.format_exc()
            print(tb)

    @pyqtSlot(bool)
    def check_for_default(self, force_reload=False):
        '''
        Checks for the existance of a default value file.  If none found,
        one is created.
        '''
        default_dir = os.path.join('.\\package\\data\\default_models\\default',
                                   self.main_model_name)
        if not os.path.exists(default_dir):
            os.makedirs(default_dir)

        default_path = os.path.join(default_dir,
                                    self.main_model_name + '.json')

        if not os.path.isfile(default_path) or force_reload:
            self.logger.info(
                f'{self.main_model_name} building default parameter spec files.  force_reload = {force_reload}'
            )
            save_data = {
                'model_base': self.params[0]['model_base'],
                'model_module': self.params[0]['model_module'],
                'model_class': self.main_model_name,
                'question_number': 'default',
                'version': 'default',
                'meta': {
                    'training_meta': {
                        'last_train_date': None,
                        'train_eval_score': None,
                        'checksum': None
                    },
                    'tuning_meta': {
                        'last_tune_date': None,
                        'n_iter': None,
                        'tuning_duration': None,
                        'tune_eval_score': None
                    }
                },
                'params': {}
            }
            for model, types in self.model_params.items():
                for t, params in types.items():
                    # True if model spec has more than one category of parameters.  Only TPOT and TF models at this point.
                    if not model in save_data['params'].keys():
                        save_data['params'][model] = {}
                    for param_name, data in params.items():
                        save_data['params'][model][param_name] = data[
                            'default']
            try:
                with open(default_path, 'w') as outfile:
                    json.dump(save_data, outfile, indent=2, cls=CATEncoder)
            except Exception as e:
                self.logger.error(
                    'Error saving updated model parameters for {}.'.format(
                        self.main_model_name),
                    exc_info=True)
                print('Exception {}'.format(e))
                tb = traceback.format_exc()
                print(tb)
Beispiel #15
0
class PlotDialog(QDialog):
    def __init__(self, df=None):
        super().__init__()
        self.df = df
        self.resize(721, 586)

        # set up ok and cancel buttin box
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(QRect(360, 520, 341, 32))
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")

        # set up chart select type tree widget in the left
        self.select_chart_type = QTreeWidget(self)
        self.select_chart_type.setGeometry(QRect(30, 30, 191, 471))
        self.select_chart_type.setObjectName("select_chart_type")

        self.scatter_plot = QTreeWidgetItem(self.select_chart_type)
        self.scatter = QTreeWidgetItem(self.scatter_plot)
        self.scatter_3d = QTreeWidgetItem(self.scatter_plot)

        self.line_plot = QTreeWidgetItem(self.select_chart_type)
        self.line = QTreeWidgetItem(self.line_plot)

        self.bar_plot = QTreeWidgetItem(self.select_chart_type)
        self.bar = QTreeWidgetItem(self.bar_plot)

        self.density_plot = QTreeWidgetItem(self.select_chart_type)
        self.density_contour = QTreeWidgetItem(self.density_plot)
        self.density_heatmap = QTreeWidgetItem(self.density_plot)
        self.histogram = QTreeWidgetItem(self.select_chart_type)

        self.select_chart_type.setCurrentItem(self.scatter)
        self.select_chart_type.currentItemChanged.connect(self.updateSetting)

        # set tab widget in the right
        self.scatter_tw = PlotSetting_2d(self, self.df)
        self.scatter_3d_tw = PlotSetting_3d(self, self.df)
        self.line_tw = PlotSetting_line_bar(self, self.df)
        self.bar_tw = PlotSetting_bar(self, self.df)
        self.density_contour_tw = PlotSetting_density_contour(self, self.df)
        self.density_heatmap_tw = PlotSetting_density_heatmap(self, self.df)
        self.histogram_tw = PlotSetting_histogram(self, self.df)

        self.scatter_tw.show()
        self.scatter_3d_tw.hide()
        self.line_tw.hide()
        self.bar_tw.hide()
        self.density_contour_tw.hide()
        self.density_heatmap_tw.hide()
        self.histogram_tw.hide()

        self.buttonBox.accepted.connect(self.ok)
        self.buttonBox.rejected.connect(self.cancel)
        QMetaObject.connectSlotsByName(self)
        self.setText()

        self.setWindowTitle("Plot Setting")
        self.setWindowIcon(QIcon('resource/icon.ico'))
        self.setWindowIconText('viuplot')
        self.show()

    # set up tab with in each element
    def setText(self):

        # select_chart_type
        self.select_chart_type.headerItem().setText(0, "Chart type")
        __sortingEnabled = self.select_chart_type.isSortingEnabled()
        self.select_chart_type.setSortingEnabled(False)
        self.scatter_plot.setText(0, "scatter plot")
        self.scatter.setText(0, "scatter")
        self.scatter_3d.setText(0, "scatter 3d")
        self.line_plot.setText(0, "line plot")
        self.line.setText(0, "line")
        self.bar_plot.setText(0, "bar plot")
        self.bar.setText(0, "bar")
        self.density_plot.setText(0, "density plot")
        self.density_contour.setText(0, "density contour")
        self.density_heatmap.setText(0, "density heatmap")
        self.histogram.setText(0, "histogram")
        self.select_chart_type.setSortingEnabled(__sortingEnabled)

    # update func for tab widget view when current tree widget changes
    def updateSetting(self):
        if self.select_chart_type.currentItem() == self.scatter:
            self.scatter_tw.show()
            self.scatter_3d_tw.hide()
            self.line_tw.hide()
            self.bar_tw.hide()
            self.density_contour_tw.hide()
            self.density_heatmap_tw.hide()
            self.histogram_tw.hide()
            print("scatter")
        elif self.select_chart_type.currentItem() == self.scatter_3d:
            self.scatter_tw.hide()
            self.scatter_3d_tw.show()
            self.line_tw.hide()
            self.bar_tw.hide()
            self.density_contour_tw.hide()
            self.density_heatmap_tw.hide()
            self.histogram_tw.hide()
            print("scatter 3d")
        elif self.select_chart_type.currentItem() == self.line:
            self.scatter_tw.hide()
            self.scatter_3d_tw.hide()
            self.line_tw.show()
            self.bar_tw.hide()
            self.density_contour_tw.hide()
            self.density_heatmap_tw.hide()
            self.histogram_tw.hide()
            print("line")
        elif self.select_chart_type.currentItem() == self.bar:
            self.scatter_tw.hide()
            self.scatter_3d_tw.hide()
            self.line_tw.hide()
            self.bar_tw.show()
            self.density_contour_tw.hide()
            self.density_heatmap_tw.hide()
            self.histogram_tw.hide()
            print("bar")
        elif self.select_chart_type.currentItem() == self.density_contour:
            self.scatter_tw.hide()
            self.scatter_3d_tw.hide()
            self.line_tw.hide()
            self.bar_tw.hide()
            self.density_contour_tw.show()
            self.density_heatmap_tw.hide()
            self.histogram_tw.hide()
            print("density contour")
        elif self.select_chart_type.currentItem() == self.density_heatmap:
            self.scatter_tw.hide()
            self.scatter_3d_tw.hide()
            self.line_tw.hide()
            self.bar_tw.hide()
            self.density_contour_tw.hide()
            self.density_heatmap_tw.show()
            self.histogram_tw.hide()
            print("density heatmap")
        elif self.select_chart_type.currentItem() == self.histogram:
            self.scatter_tw.hide()
            self.scatter_3d_tw.hide()
            self.line_tw.hide()
            self.bar_tw.hide()
            self.density_contour_tw.hide()
            self.density_heatmap_tw.hide()
            self.histogram_tw.show()
            print("histogram")

    # func for creating chart when clicking ok
    def ok(self):
        currentItem = self.select_chart_type.currentItem()

        if currentItem == self.scatter:
            info = self.scatter_tw.getCurrentInfo()
            info['chart_type'] = 'scatter'

        elif currentItem == self.scatter_3d:
            info = self.scatter_3d_tw.getCurrentInfo()
            info['chart_type'] = 'scatter_3d'

        elif currentItem == self.line:
            info = self.line_tw.getCurrentInfo()
            info['chart_type'] = 'line'

        elif currentItem == self.bar:
            info = self.bar_tw.getCurrentInfo()
            info['chart_type'] = 'bar'

        elif currentItem == self.density_contour:
            info = self.density_contour_tw.getCurrentInfo()
            info['chart_type'] = 'density_contour'

        elif currentItem == self.density_heatmap:
            info = self.density_heatmap_tw.getCurrentInfo()
            info['chart_type'] = 'density_heatmap'

        elif currentItem == self.histogram:
            info = self.histogram_tw.getCurrentInfo()
            info['chart_type'] = 'histogram'

        print(info)
        try:
            self.chart = Chart(self.df, info)
            self.close()
        except (AttributeError, ValueError, TypeError) as e:
            self.err_msg = QMessageBox()
            self.err_msg.setIcon(QMessageBox.Critical)
            self.err_msg.setText("Error")
            self.err_msg.setInformativeText(
                'Unable to plot with current setting.')
            self.err_msg.setWindowTitle("Error")
            self.err_msg.exec_()

    def cancel(self):
        self.close()
Beispiel #16
0
class CreateVersionWidget(QDialog):
    """
    Create version dialog used when generating a new CAT version.
    Allows user to input the expected question labels which will
    become the directory structure for storing models and parameters.
    """
    version_created = pyqtSignal(str)
    def __init__(self, parent=None):
        super(CreateVersionWidget, self).__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.parent = parent
        self.setWindowTitle("New CAT Version")
        self.version_name = None
        self.question_labels = {}
        self.input_widgets = {}
        self.main_layout = QVBoxLayout()
        self.version_groupbox = QGroupBox("Create new version")
        self.version_form = QFormLayout()

        self.version_groupbox.setLayout(self.version_form)
        self.main_layout.addWidget(self.version_groupbox)
        self.setupUI()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttonBox.setObjectName("version_warning")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.buttonBox.setWindowTitle("Version Warning")
        self.buttonBox.rejected.connect(self.reject)

        self.main_layout.addWidget(self.buttonBox)
        self.setLayout(self.main_layout)

    def _verify_params(self):
        """
        Checks that each input field has some value and that the version name
        has been specified.

            # Returns: None
        """
        for label, widget in self.input_widgets.items():
            if widget.text() == '':
                self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
                return False
        if self.version_name:
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
            return True

    def _update_version_name(self, value):
        self.version_name = value

    def _verify_unique_params(self, key, value):
        """
        Checks that field name is unique.  This is necessary as field values
        are used for version directory and data structure.

            # Arguments
                key(String): dict key for appropriate input widget
                value(String): field name.  Must be unique per version.
        """
        if value.lower() in [x.lower() for x in self.question_labels.values()]:
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
            exceptionWarning('Field names must be unique!')
            return
        try:
            self._verify_params()
        except Exception as e:
           exceptionWarning('Error updating version params.', e, title="Update version warning")
           
    def _version_check(self, version):
        """
        Checks that user has both supplied a version name and that, if supplied, 
        the name is unique.

            # Arguments
                version(String): version name supplied by user

            # Returns
                bool: True if version is supplied and unique, else False
        """
        if version == '':
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
            return False
        v = os.path.join(VERSION_BASE_DIR, version)
        if os.path.exists(v):
            msg_box = QMessageBox()
            msg_box.setIcon(QMessageBox.Warning)
            msg_box.setText("Version {} already exists!".format(version))
            msg_box.setWindowTitle('Version Warning')
            msg_box.exec_()
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
            return False
        self._verify_params()
        return True

    def _update_fields(self, state):
        """
        Appends or removes an input widget for version field labels.

            # Arguments
                state(bool): If True, add a field, else remove the last field

            # Returns
                None
        """
        current_row_idx = self.version_form.rowCount()
        if state:
            label = QLabel('Field ' + str(current_row_idx) + ':')
            q_input = QLineEdit(objectName=str(current_row_idx - 1))
            q_input.textChanged.connect(
                lambda state, x=current_row_idx-1, y=q_input:
                    self._verify_unique_params(
                        x, 
                        (None if y.text() == '' else y.text())
                    )
            )
            self.version_form.insertRow(current_row_idx, label, q_input)
            self.input_widgets[str(current_row_idx - 1)] = q_input
            q_input.setFocus()
        else:
            if current_row_idx == 1:
                return
            item = self.input_widgets[str(current_row_idx - 2)]
            try:
                del self.input_widgets[item.objectName()]
                self.version_form.removeRow(current_row_idx - 1)
                self.version_form.update()
            except Exception as e:
                exceptionWarning('Error updating version params.', e, title="Update version warning")
        self._verify_params()

    def _generate_fields(self):
        """
        Generate fields based on default version scheme.
        """
        for idx, q_label in enumerate(DEFAULT_QUESTION_LABELS):
            self.question_labels[idx] = q_label
            label = QLabel('Field ' + str(idx+ 1) + ':')
            q_input = QLineEdit(objectName=str(idx))
            q_input.setText(q_label)
            q_input.textChanged.connect(
                lambda state, x=idx, y=self.version_name_input:
                    self._verify_unique_params(
                        x, 
                        (None if y.text() == '' else y.text())
                    )
            )
            self.version_form.addRow(label, q_input)
            self.input_widgets[str(idx)] = q_input 
        self._verify_params()

    def setupUI(self):
        self.version_name_label = QLabel("Version name: ")
        self.version_name_input = QLineEdit(objectName='version_name')
        self.version_name_input.textChanged.connect(
            lambda state, y=self.version_name_input:
                self._update_version_name(
                    (y.text() if self._version_check(y.text()) else None)
                )
        )
        self.version_form.addRow(self.version_name_label, self.version_name_input)
        self._generate_fields()
        self.new_question_row_btn = QPushButton('Add field', self)
        self.new_question_row_btn.clicked.connect(lambda: self._update_fields(True))
        self.remove_question_row_btn = QPushButton('Remove field', self)
        self.remove_question_row_btn.clicked.connect(lambda: self._update_fields(False))
        
        self.button_hbox = QHBoxLayout()
 
        self.button_hbox.addWidget(self.new_question_row_btn)
        self.button_hbox.addWidget(self.remove_question_row_btn)
        self.main_layout.addLayout(self.button_hbox)

    def create_version(self):
        """
        Create the new version specified by the user.
        """
        if(self.exec_() == QDialog.Accepted):
            v_dir = os.path.join(VERSION_BASE_DIR, self.version_name)
            try:
                if not os.path.exists(v_dir):
                    os.makedirs(v_dir)
                for k,v in self.input_widgets.items():
                    sub_dir = os.path.join(v_dir, v.text())
                    if not os.path.exists(sub_dir):
                        os.makedirs(sub_dir)
                self.version_created.emit(v_dir)
            except Exception as e:
                exceptionWarning('Error occured when creating new version.', e, title='Create version exception')
            finally:
                self.question_labels = {}
                self.version_name = None
                self.version_name_input.setText('')
                for k,v in self.input_widgets.items():
                    self.version_form.removeRow(v)
                self.input_widgets = {}
                self.version_form.update()
                self._generate_fields()
Beispiel #17
0
class ColormapDialog(QDialog):

    sigColormapChanged = pyqtSignal(object)

    def __init__(self, parent=None, name="Colormap Dialog"):
        QDialog.__init__(self, parent)
        self.setWindowTitle(name)
        self.title = name

        self.colormapList = [
            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr',
            'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu',
            'PuBuGn', 'BuGn', 'YlGn'
        ]

        # histogramData is tupel(bins, counts)
        self.histogramData = None

        # default values
        self.dataMin = -10
        self.dataMax = 10
        self.minValue = 0
        self.maxValue = 1

        self.colormapIndex = 2
        self.colormapType = 0

        self.autoscale = False
        self.autoscale90 = False
        # main layout
        vlayout = QVBoxLayout(self)
        vlayout.setContentsMargins(10, 10, 10, 10)
        vlayout.setSpacing(0)

        # layout 1 : -combo to choose colormap
        #            -autoscale button
        #            -autoscale 90% button
        hbox1 = QWidget(self)
        hlayout1 = QHBoxLayout(hbox1)
        vlayout.addWidget(hbox1)
        hlayout1.setContentsMargins(0, 0, 0, 0)
        hlayout1.setSpacing(10)

        # combo
        self.combo = QComboBox(hbox1)
        for colormap in self.colormapList:
            self.combo.addItem(colormap)
        self.combo.activated[int].connect(self.colormapChange)
        hlayout1.addWidget(self.combo)

        # autoscale
        self.autoScaleButton = QPushButton("Autoscale", hbox1)
        self.autoScaleButton.setCheckable(True)
        self.autoScaleButton.setAutoDefault(False)
        self.autoScaleButton.toggled[bool].connect(self.autoscaleChange)
        hlayout1.addWidget(self.autoScaleButton)

        # autoscale 90%
        self.autoScale90Button = QPushButton("Autoscale 90%", hbox1)
        self.autoScale90Button.setCheckable(True)
        self.autoScale90Button.setAutoDefault(False)

        self.autoScale90Button.toggled[bool].connect(self.autoscale90Change)
        hlayout1.addWidget(self.autoScale90Button)

        # hlayout
        hbox0 = QWidget(self)
        self.__hbox0 = hbox0
        hlayout0 = QHBoxLayout(hbox0)
        hlayout0.setContentsMargins(0, 0, 0, 0)
        hlayout0.setSpacing(0)
        vlayout.addWidget(hbox0)
        #hlayout0.addStretch(10)

        self.buttonGroup = QButtonGroup()
        g1 = QCheckBox(hbox0)
        g1.setText("Linear")
        g2 = QCheckBox(hbox0)
        g2.setText("Logarithmic")
        g3 = QCheckBox(hbox0)
        g3.setText("Gamma")
        self.buttonGroup.addButton(g1, 0)
        self.buttonGroup.addButton(g2, 1)
        self.buttonGroup.addButton(g3, 2)
        self.buttonGroup.setExclusive(True)
        if self.colormapType == 1:
            self.buttonGroup.button(1).setChecked(True)
        elif self.colormapType == 2:
            self.buttonGroup.button(2).setChecked(True)
        else:
            self.buttonGroup.button(0).setChecked(True)
        hlayout0.addWidget(g1)
        hlayout0.addWidget(g2)
        hlayout0.addWidget(g3)
        vlayout.addWidget(hbox0)
        self.buttonGroup.buttonClicked[int].connect(self.buttonGroupChange)
        vlayout.addSpacing(20)

        hboxlimits = QWidget(self)
        hboxlimitslayout = QHBoxLayout(hboxlimits)
        hboxlimitslayout.setContentsMargins(0, 0, 0, 0)
        hboxlimitslayout.setSpacing(0)

        self.slider = None

        vlayout.addWidget(hboxlimits)

        vboxlimits = QWidget(hboxlimits)
        vboxlimitslayout = QVBoxLayout(vboxlimits)
        vboxlimitslayout.setContentsMargins(0, 0, 0, 0)
        vboxlimitslayout.setSpacing(0)
        hboxlimitslayout.addWidget(vboxlimits)

        # hlayout 2 : - min label
        #             - min texte
        hbox2 = QWidget(vboxlimits)
        self.__hbox2 = hbox2
        hlayout2 = QHBoxLayout(hbox2)
        hlayout2.setContentsMargins(0, 0, 0, 0)
        hlayout2.setSpacing(0)
        #vlayout.addWidget(hbox2)
        vboxlimitslayout.addWidget(hbox2)
        hlayout2.addStretch(10)

        self.minLabel = QLabel(hbox2)
        self.minLabel.setText("Minimum")
        hlayout2.addWidget(self.minLabel)

        hlayout2.addSpacing(5)
        hlayout2.addStretch(1)
        self.minText = MyQLineEdit(hbox2)
        self.minText.setFixedWidth(150)
        self.minText.setAlignment(QtCore.Qt.AlignRight)
        self.minText.returnPressed[()].connect(self.minTextChanged)
        hlayout2.addWidget(self.minText)

        # hlayout 3 : - min label
        #             - min text
        hbox3 = QWidget(vboxlimits)
        self.__hbox3 = hbox3
        hlayout3 = QHBoxLayout(hbox3)
        hlayout3.setContentsMargins(0, 0, 0, 0)
        hlayout3.setSpacing(0)
        #vlayout.addWidget(hbox3)
        vboxlimitslayout.addWidget(hbox3)

        hlayout3.addStretch(10)
        self.maxLabel = QLabel(hbox3)
        self.maxLabel.setText("Maximum")
        hlayout3.addWidget(self.maxLabel)

        hlayout3.addSpacing(5)
        hlayout3.addStretch(1)

        self.maxText = MyQLineEdit(hbox3)
        self.maxText.setFixedWidth(150)
        self.maxText.setAlignment(QtCore.Qt.AlignRight)

        self.maxText.returnPressed[()].connect(self.maxTextChanged)
        hlayout3.addWidget(self.maxText)

        # Graph widget for color curve...
        self.c = PlotWidget(self, backend=None)
        self.c.setGraphXLabel("Data Values")
        self.c.setInteractiveMode('select')

        self.marge = (abs(self.dataMax) + abs(self.dataMin)) / 6.0
        self.minmd = self.dataMin - self.marge
        self.maxpd = self.dataMax + self.marge

        self.c.setGraphXLimits(self.minmd, self.maxpd)
        self.c.setGraphYLimits(-11.5, 11.5)

        x = [self.minmd, self.dataMin, self.dataMax, self.maxpd]
        y = [-10, -10, 10, 10]
        self.c.addCurve(x,
                        y,
                        legend="ConstrainedCurve",
                        color='black',
                        symbol='o',
                        linestyle='-')
        self.markers = []
        self.__x = x
        self.__y = y
        labelList = ["", "Min", "Max", ""]
        for i in range(4):
            if i in [1, 2]:
                draggable = True
                color = "blue"
            else:
                draggable = False
                color = "black"
            #TODO symbol
            legend = "%d" % i
            self.c.addXMarker(x[i],
                              legend=legend,
                              text=labelList[i],
                              draggable=draggable,
                              color=color)
            self.markers.append((legend, ""))

        self.c.setMinimumSize(QSize(250, 200))
        vlayout.addWidget(self.c)

        self.c.sigPlotSignal.connect(self.chval)

        # colormap window can not be resized
        self.setFixedSize(vlayout.minimumSize())
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        vlayout.addWidget(self.buttonBox)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def plotHistogram(self, data=None):
        if data is not None:
            self.histogramData = data
        if self.histogramData is None:
            return False
        bins, counts = self.histogramData
        self.c.addCurve(bins,
                        counts,
                        "Histogram",
                        color='darkYellow',
                        histogram='center',
                        yaxis='right',
                        fill=True)

    def _update(self):
        _logger.debug("colormap _update called")
        self.marge = (abs(self.dataMax) + abs(self.dataMin)) / 6.0
        self.minmd = self.dataMin - self.marge
        self.maxpd = self.dataMax + self.marge
        self.c.setGraphXLimits(self.minmd, self.maxpd)
        self.c.setGraphYLimits(-11.5, 11.5)

        self.__x = [self.minmd, self.dataMin, self.dataMax, self.maxpd]
        self.__y = [-10, -10, 10, 10]
        self.c.addCurve(self.__x,
                        self.__y,
                        legend="ConstrainedCurve",
                        color='black',
                        symbol='o',
                        linestyle='-')
        self.c.clearMarkers()
        for i in range(4):
            if i in [1, 2]:
                draggable = True
                color = "blue"
            else:
                draggable = False
                color = "black"
            key = self.markers[i][0]
            label = self.markers[i][1]
            self.c.addXMarker(self.__x[i],
                              legend=key,
                              text=label,
                              draggable=draggable,
                              color=color)
        self.sendColormap()

    def buttonGroupChange(self, val):
        _logger.debug("buttonGroup asking to update colormap")
        self.setColormapType(val, update=True)
        self._update()

    def setColormapType(self, val, update=False):
        self.colormapType = val
        if self.colormapType == 1:
            self.buttonGroup.button(1).setChecked(True)
        elif self.colormapType == 2:
            self.buttonGroup.button(2).setChecked(True)
        else:
            self.colormapType = 0
            self.buttonGroup.button(0).setChecked(True)
        if update:
            self._update()

    def chval(self, ddict):
        _logger.debug("Received %s", ddict)
        if ddict['event'] == 'markerMoving':
            diam = int(ddict['label'])
            x = ddict['x']
            if diam == 1:
                self.setDisplayedMinValue(x)
            elif diam == 2:
                self.setDisplayedMaxValue(x)
        elif ddict['event'] == 'markerMoved':
            diam = int(ddict['label'])
            x = ddict['x']
            if diam == 1:
                self.setMinValue(x)
            if diam == 2:
                self.setMaxValue(x)

    """
    Colormap
    """

    def setColormap(self, colormap):
        self.colormapIndex = colormap
        if QTVERSION < '4.0.0':
            self.combo.setCurrentItem(colormap)
        else:
            self.combo.setCurrentIndex(colormap)

    def colormapChange(self, colormap):
        self.colormapIndex = colormap
        self.sendColormap()

    # AUTOSCALE
    """
    Autoscale
    """

    def autoscaleChange(self, val):
        self.autoscale = val
        self.setAutoscale(val)
        self.sendColormap()

    def setAutoscale(self, val):
        _logger.debug("setAutoscale called %s", val)
        if val:
            self.autoScaleButton.setChecked(True)
            self.autoScale90Button.setChecked(False)
            #self.autoScale90Button.setDown(False)
            self.setMinValue(self.dataMin)
            self.setMaxValue(self.dataMax)
            self.maxText.setEnabled(0)
            self.minText.setEnabled(0)
            self.c.setEnabled(False)
            #self.c.disablemarkermode()
        else:
            self.autoScaleButton.setChecked(False)
            self.autoScale90Button.setChecked(False)
            self.minText.setEnabled(1)
            self.maxText.setEnabled(1)
            self.c.setEnabled(True)
            #self.c.enablemarkermode()

    """
    set rangeValues to dataMin ; dataMax-10%
    """

    def autoscale90Change(self, val):
        self.autoscale90 = val
        self.setAutoscale90(val)
        self.sendColormap()

    def setAutoscale90(self, val):
        if val:
            self.autoScaleButton.setChecked(False)
            self.setMinValue(self.dataMin)
            self.setMaxValue(self.dataMax - abs(self.dataMax / 10))
            self.minText.setEnabled(0)
            self.maxText.setEnabled(0)
            self.c.setEnabled(False)
        else:
            self.autoScale90Button.setChecked(False)
            self.minText.setEnabled(1)
            self.maxText.setEnabled(1)
            self.c.setEnabled(True)
            self.c.setFocus()

    # MINIMUM
    """
    change min value and update colormap
    """

    def setMinValue(self, val):
        v = float(str(val))
        self.minValue = v
        self.minText.setText("%g" % v)
        self.__x[1] = v
        key = self.markers[1][0]
        label = self.markers[1][1]
        self.c.addXMarker(v,
                          legend=key,
                          text=label,
                          color="blue",
                          draggable=True)
        self.c.addCurve(self.__x,
                        self.__y,
                        legend="ConstrainedCurve",
                        color='black',
                        symbol='o',
                        linestyle='-')
        self.sendColormap()

    """
    min value changed by text
    """

    def minTextChanged(self):
        text = str(self.minText.text())
        if not len(text):
            return
        val = float(text)
        self.setMinValue(val)
        if self.minText.hasFocus():
            self.c.setFocus()

    """
    change only the displayed min value
    """

    def setDisplayedMinValue(self, val):
        val = float(val)
        self.minValue = val
        self.minText.setText("%g" % val)
        self.__x[1] = val
        key = self.markers[1][0]
        label = self.markers[1][1]
        self.c.addXMarker(val,
                          legend=key,
                          text=label,
                          color="blue",
                          draggable=True)
        self.c.addCurve(self.__x,
                        self.__y,
                        legend="ConstrainedCurve",
                        color='black',
                        symbol='o',
                        linestyle='-')

    # MAXIMUM
    """
    change max value and update colormap
    """

    def setMaxValue(self, val):
        v = float(str(val))
        self.maxValue = v
        self.maxText.setText("%g" % v)
        self.__x[2] = v
        key = self.markers[2][0]
        label = self.markers[2][1]
        self.c.addXMarker(v,
                          legend=key,
                          text=label,
                          color="blue",
                          draggable=True)
        self.c.addCurve(self.__x,
                        self.__y,
                        legend="ConstrainedCurve",
                        color='black',
                        symbol='o',
                        linestyle='-')
        self.sendColormap()

    """
    max value changed by text
    """

    def maxTextChanged(self):
        text = str(self.maxText.text())
        if not len(text): return
        val = float(text)
        self.setMaxValue(val)
        if self.maxText.hasFocus():
            self.c.setFocus()

    """
    change only the displayed max value
    """

    def setDisplayedMaxValue(self, val):
        val = float(val)
        self.maxValue = val
        self.maxText.setText("%g" % val)
        self.__x[2] = val
        key = self.markers[2][0]
        label = self.markers[2][1]
        self.c.addXMarker(val,
                          legend=key,
                          text=label,
                          color="blue",
                          draggable=True)
        self.c.addCurve(self.__x,
                        self.__y,
                        legend="ConstrainedCurve",
                        color='black',
                        symbol='o',
                        linestyle='-')

    # DATA values
    """
    set min/max value of data source
    """

    def setDataMinMax(self, minVal, maxVal, update=True):
        if minVal is not None:
            vmin = float(str(minVal))
            self.dataMin = vmin
        if maxVal is not None:
            vmax = float(str(maxVal))
            self.dataMax = vmax

        if update:
            # are current values in the good range ?
            self._update()

    def getColormap(self):

        if self.minValue > self.maxValue:
            vmax = self.minValue
            vmin = self.maxValue
        else:
            vmax = self.maxValue
            vmin = self.minValue
        cmap = [
            self.colormapIndex, self.autoscale, vmin, vmax, self.dataMin,
            self.dataMax, self.colormapType
        ]
        return cmap if self.exec_() else None

    """
    send 'ColormapChanged' signal
    """

    def sendColormap(self):
        _logger.debug("sending colormap")
        try:
            cmap = self.getColormap()
            self.sigColormapChanged.emit(cmap)
        except:
            sys.excepthook(sys.exc_info()[0],
                           sys.exc_info()[1],
                           sys.exc_info()[2])

    def colormapListToDict(colormapList):
        """Convert colormap from this dialog to :class:`PlotBackend`.
        :param colormapList: Colormap as returned by :meth:`getColormap`.
        :type colormapList: list or tuple
        :return: Colormap as used in :class:`PlotBackend`.
        :rtype: dict
        """
        index, autoscale, vMin, vMax, dataMin, dataMax, cmapType = colormapList
        # Warning, gamma cmapType is not supported in plot backend
        # Here it is silently replaced by linear as the default colormap
        return {
            'name': _COLORMAP_NAMES[index],
            'autoscale': autoscale,
            'vmin': vMin,
            'vmax': vMax,
            'normalization': 'log' if cmapType == 1 else 'linear',
            'colors': 256
        }

    def getColormap_name(self):
        self.getColormap()
        return _COLORMAP_NAMES[self.colormapIndex]

    def getColor(self):
        return _COLOR_NAMES[self.colormapIndex]

    def colormapDictToList(colormapDict):
        """Convert colormap from :class:`PlotBackend` to this dialog.
        :param dict colormapDict: Colormap as used in :class:`PlotBackend`.
        :return: Colormap as returned by :meth:`getColormap`.
        :rtype: list
        """
        cmapIndex = _COLORMAP_NAMES.index(colormapDict['name'])
        cmapType = 1 if colormapDict['normalization'].startswith('log') else 0
        return [
            cmapIndex,
            colormapDict['autoscale'],
            colormapDict['vmin'],
            colormapDict['vmax'],
            0,  # dataMin is not defined in PlotBackend colormap
            0,  # dataMax is not defined in PlotBackend colormap
            cmapType
        ]
Beispiel #18
0
class AddConnectedPointsDialogWidget(QDialog):
    def __init__(self, parent=None, command=None):
        """Constructor

        Args:
            parent: Qt parent Widget
            iface: QGiS interface
            command: Command instance with a run_it method which will be called
                     on acceptance of the dialog
        """
        super().__init__(parent)
        self.setupUi()

        self.command = command

        self.databases = get_databases()
        self.database_combo.addItems(list(self.databases.keys()))

        # Connect signals
        self.buttonBox.accepted.connect(self.on_accept)
        self.buttonBox.rejected.connect(self.on_reject)

        self.filename = None

    def on_accept(self):
        """Accept and run the Command.run_it method."""

        db_key = self.database_combo.currentText()
        db_entry = self.databases[db_key]
        db_type = db_entry["db_type"]

        _db_settings = db_entry["db_settings"]

        if db_type == "spatialite":
            # usage of db_type 'spatialite' instead of 'sqlite'
            # makes much more sense because it also used internally
            # by qgis, for example when by the ``QgsVectorLayer()``-object
            host = _db_settings["db_path"]
            db_settings = {
                "host": host,
                "port": "",
                "name": "",
                "username": "",
                "password": "",
                "schema": "",
                "database": "",
                "db_path": host,
            }
        else:
            db_settings = _db_settings
            db_settings["schema"] = "public"
        self.command.run_it(db_settings, db_type)

        self.accept()

    def on_reject(self):
        """Cancel"""
        self.reject()
        logger.debug("Reject")

    def closeEvent(self, event):
        """
        Close widget, called by Qt on close
        :param event: QEvent, close event
        """

        self.buttonBox.accepted.disconnect(self.on_accept)
        self.buttonBox.rejected.disconnect(self.on_reject)

        event.accept()

    def setupUi(self):

        self.resize(815, 250)
        self.verticalLayout = QVBoxLayout(self)

        self.groupBox_2 = QGroupBox(self)
        self.groupBox_2.setObjectName("groupBox_2")
        self.database_combo = QComboBox(self.groupBox_2)
        self.database_combo.setGeometry(QRect(10, 30, 481, 34))

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.database_combo.sizePolicy().hasHeightForWidth()
        )
        self.database_combo.setSizePolicy(sizePolicy)
        self.database_combo.setObjectName("database_combo")
        self.verticalLayout.addWidget(self.groupBox_2)

        self.groupBox = QGroupBox(self)
        self.verticalLayoutBox = QVBoxLayout(self.groupBox)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi()
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        self.setWindowTitle("Add connected points")
        self.groupBox_2.setTitle("Load from model database")
Beispiel #19
0
class TPOTModelDialog(BaseModelDialog):
    """
    TPOTModelDialog is the basic structure behind TPOT model dialogs in CATScore.

    # Arguments
        model_params: String, path to default parameters .json file.
        tfidf_params: String, path to default TF-IDF param file.
        fs_params: String, path to default feature selection file.
    """
    def __init__(self, parent=None, *params):
        super(BaseModelDialog, self).__init__(parent)

        self.logger = logging.getLogger(__name__)
        self.comms = Communicate()
        self.comms.check_for_existing_model.connect(self.parent().model_exists)

        self.model_params = {}
        self.updated_params = {}
        self.ui_widgets = []
        # input_widgets is a list of all dynamically created input widgets for the various model params.
        # Holds EVERY input widget, regardless of type.  Key = hyperparameter name
        self.input_widgets = {}
        self.current_version = 'default'
        self.params = params
        self.main_model_name = params[0]['model_class']

        for param in self.params:
            cls_name = param['model_class']
            full_name = param['model_module'] + '.' + param['model_class']
            self.model_params[full_name] = param[cls_name]
            self.updated_params[full_name] = {}
        self.is_dirty = False
        self.check_for_default()

        self.setWindowTitle(self.main_model_name)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Apply
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.setObjectName("model_buttonbox")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.buttonBox.rejected.connect(self.reject)

        self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(
            lambda: self.update_version(self.current_version))

        self.buttonBox.button(QDialogButtonBox.Apply).clicked.connect(
            lambda: self.apply_changes())
        self.main_layout = QVBoxLayout()
        self.form_grid = QGridLayout()
        self.version_item_combobox = QComboBox()
        self.version_item_combobox.currentIndexChanged.connect(
            lambda state, y=self.version_item_combobox: self.
            load_version_params(y.currentData()))
        self.form_grid.addWidget(self.version_item_combobox, 0, 0)
        row = 1
        col = 0
        for model, types in self.model_params.items():
            for t, params in types.items():
                groupbox = QGroupBox()
                groupbox.setTitle(model.split('.')[-1] + " " + t)
                model_param_form = QFormLayout()
                groupbox.setLayout(model_param_form)
                self.form_grid.addWidget(groupbox, row, col)
                col += 1
                self.ui_widgets.append(groupbox)
                self.ui_widgets.append(model_param_form)
                if t == 'Model':
                    self.setupTPOTModelDetailUI(params, model_param_form)
                else:
                    self.setupUI(model, params, model_param_form)

        self.main_layout.addLayout(self.form_grid)
        self.main_layout.addWidget(self.buttonBox)
        self.setLayout(self.main_layout)

    def apply_changes(self):
        version = self.current_version.split('\\')[-1]
        if version == 'default':
            return

        if self.is_dirty:
            filename = self.main_model_name + '.json'
            save_dir = os.path.join(self.version_item_combobox.currentData(),
                                    self.main_model_name)

            if not os.path.isdir(save_dir):
                os.mkdir(save_dir)

            save_file_path = os.path.join(save_dir, filename)

            if not os.path.isfile(save_file_path):
                # Get default file and load those values
                default_dir = os.path.join(
                    ".\\package\\data\\default_models\\default",
                    self.main_model_name)
                default_path = os.path.join(default_dir,
                                            self.main_model_name + '.json')
                with open(default_path, 'r') as infile:
                    full_default_params = json.load(infile)

                full_default_params.update({
                    "question_number":
                    self.version_item_combobox.currentData().split('\\')[-1],
                    "version":
                    version
                })
                save_data = full_default_params.copy()

            else:
                with open(save_file_path, 'r') as infile:
                    save_data = json.load(infile)

            for param_type, params in self.updated_params.items():
                if (params):
                    #* Check for key existence to specify which parameter we're saving
                    if (param_type in save_data['params'].keys()):
                        root = 'params'
                    else:
                        root = 'tpot_params'
                    for param, val in params.items():
                        save_data[root][param_type][param] = val
            try:
                with open(save_file_path, 'w') as outfile:
                    json.dump(save_data, outfile, cls=CATEncoder, indent=2)
            except Exception as e:
                self.logger.error(
                    "Error saving updated model parameters for {}.".format(
                        self.main_model_name),
                    exc_info=True)
                print("Exception {}".format(e))
                tb = traceback.format_exc()
                print(tb)

        self.is_dirty = False
        return

    def setupTPOTModelDetailUI(self, param_dict, form):
        '''
        Build TPOT classifier chosen model UI.

            # Attributes:
                form: QtWidget.Groupbox, container to hold UI structs
        '''
        model_name_label = QLabel('Model name:')
        model_param_label = QLabel('Model parameters:')
        self.model_name_display = QLabel()
        form.addRow(model_name_label, self.model_name_display)
        self.model_param_display = QLabel()
        # param_string = ''
        # for key, value in param_dict['model_params'].items():
        #     param_string += ('\t' + key + ': ' + str(value) +'\n')
        # self.model_param_display.setText(param_string)
        # form.addRow(model_param_label, self.model_param_display)
        self.update_trained_model_label(param_dict['model_name'],
                                        param_dict['model_params'])
        form.addRow(model_param_label)
        form.addRow(self.model_param_display)

    def setupUI(self, param_type, param_dict, form):
        """
        Build UI elements using parameters dict of scikit models

            # Attributes:
                param_type: String, type of param to update
                param_dict: dict, dictionary of parameter/default values from model.
                default_params: dict, dictionary of default parameters defined by model spec json.
                form: QtWidget.Groupbox, container to hold UI structs
        """
        try:
            for k, v in param_dict.items():
                label_string = k
                label = QLabel(label_string)
                val_type = v['type']
                if val_type == 'dropdown':
                    input_field = QComboBox(objectName=k)
                    for name, value in v['options'].items():
                        input_field.addItem(name, value)
                    idx = input_field.findData(v['default'])
                    if idx != -1:
                        input_field.setCurrentIndex(idx)
                    input_field.currentIndexChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, y.currentData()))

                elif val_type == 'double':
                    input_field = QDoubleSpinBox(objectName=k)
                    input_field.setDecimals(v['decimal_len'])
                    input_field.setRange(v['min'], v['max'])
                    if v['default'] is not None:
                        input_field.setValue(v['default'])
                    input_field.setSingleStep(v['step_size'])
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, y.value()))

                elif val_type == 'int':
                    input_field = QSpinBox(objectName=k)
                    input_field.setRange(v['min'], v['max'])
                    if v['default'] is not None:
                        input_field.setValue(v['default'])
                    input_field.setSingleStep(v['step_size'])
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, y.value()))
                elif val_type == 'range':
                    label_string = k
                    label = QLabel(label_string + ' : 1,')
                    input_field = QSpinBox(objectName=k)
                    input_field.setRange(v['min'], v['max'])
                    if v['default'] is not None:
                        input_field.setValue(v['default'][-1])
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._update_param(
                            param_type, x, [1, y.value()]))
                elif val_type == 'static':
                    label_string = k
                    input_field = QLineEdit(objectName=k)
                    input_field.setText(str(v['default']))
                    # input_field.textColor(QColor.red())
                    input_field.setEnabled(False)
                    self._update_param(param_type, k, v['default'])
                if v['tooltip'] is not None:
                    input_field.setToolTip(v['tooltip'])
                form.addRow(label, input_field)
                self.input_widgets[k] = input_field
        except Exception as e:
            self.logger.error("Error generating {} dialog.", exc_info=True)
            print("Exception {} occured with key {} and value {}".format(
                e, k, v))
            tb = traceback.format_exc()
            print(tb)

    def load_version_params(self, path):
        """
        Loads parameters from the selected version for a specific question.  
        Resets parameters to default prior to loading.
        If default or None is selected, returns after reload.  

            # Attributes
                path: String, path to version parameters.  
        """
        # Reset input parameters
        for model, types in self.model_params.items():
            for t, params in types.items():
                self.set_input_params(params)
        self.update_trained_model_label(None, None)
        # If true, default (or none available) selected, thus Return
        if path == None or path == 'default':
            self.is_dirty = False
            return

        filename = self.main_model_name + '.json'
        model_data = {}
        try:
            try:
                with open(os.path.join(path, self.main_model_name, filename),
                          'r') as f:
                    model_data = json.load(f)
                model_class = model_data['model_class']
                for kind, params in model_data['tpot_params'].items():
                    self.set_input_params(params)

                for kind, params in model_data['params'].items():
                    if (kind.split('.')[1] != 'feature_extraction'
                            or kind.split('.')[1] != 'feature_selection'):
                        self.update_trained_model_label(kind, params)
                    else:
                        self.set_input_params(params)

                # self.update_trained_model_params(model_data[''])
            except FileNotFoundError as fnfe:
                # No parameter file exists.  Pass.
                pass
            self.is_dirty = False
        except Exception as e:
            self.logger.error(f"Error updating {model} parameters",
                              exc_info=True)
            print("Exception {}".format(e))
            tb = traceback.format_exc()
            print(tb)

    def update_trained_model_label(self, model_name, param_dict):
        if not model_name:
            self.model_name_display.setText(
                self.model_params['tpot.TPOTClassifier']['Model']
                ['model_name'])
        else:
            self.model_name_display.setText(model_name)
        detail_string = ''
        if not param_dict:
            for key, value in self.model_params['tpot.TPOTClassifier'][
                    'Model']['model_params'].items():
                detail_string += ('\t' + key + ': ' + str(value) + '\n')
        else:
            for key, value in param_dict.items():
                detail_string += ('\t' + key + ': ' + str(value) + '\n')
        self.model_param_display.setText(detail_string)

    @pyqtSlot(bool)
    def check_for_default(self, force_reload=False):
        """
        Checks for the existance of a default value file.  If none found,
        one is created.
        """
        default_dir = os.path.join(".\\package\\data\\default_models\\default",
                                   self.main_model_name)
        if not os.path.exists(default_dir):
            os.makedirs(default_dir)

        default_path = os.path.join(default_dir,
                                    self.main_model_name + '.json')

        if not os.path.isfile(default_path) or force_reload:
            self.logger.debug(
                f"{self.main_model_name} building default parameter spec files.  force_reload = {force_reload}"
            )
            save_data = {
                "model_base": self.params[0]['model_base'],
                "model_module": self.params[0]['model_module'],
                "model_class": self.main_model_name,
                "question_number": "default",
                "version": "default",
                "meta": {
                    "training_meta": {},
                    "tuning_meta": {}
                },
                "params": {},
                "tpot_params": {
                    "tpot.TPOTClassifier": {}
                }
            }
            #
            for model, types in self.model_params.items():
                if model == 'tpot.TPOTClassifier':
                    for type, params in types.items():
                        if type == 'Model':
                            save_data['params'][
                                params['model_name']] = params['model_params']
                        if type == 'Hyperparameters':
                            for param_name, param_data in params.items():
                                save_data['tpot_params'][model][
                                    param_name] = param_data['default']
                else:
                    for t, params in types.items():
                        # True if model spec has more than one category of parameters.
                        if not model in save_data['params'].keys():
                            save_data['params'][model] = {}
                        for param_name, data in params.items():
                            save_data['params'][model][param_name] = data[
                                'default']
            try:
                with open(default_path, 'w') as outfile:
                    json.dump(save_data, outfile, indent=2, cls=CATEncoder)
            except Exception as e:
                self.logger.error(
                    "Error saving updated model parameters for {}.".format(
                        self.main_model_name),
                    exc_info=True)
                print("Exception {}".format(e))
                tb = traceback.format_exc()
                print(tb)
Beispiel #20
0
class NewProjectDialog(QDialog):

    #此处定义常量

    #此处定义信号

    def __init__(self):
        QDialog.__init__(self)
        self.project_dir = None
        self.project_name = None

    def setup(self):
        self.resize(450, 120)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_project_name = QLabel(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_project_name.sizePolicy().hasHeightForWidth())
        self.label_project_name.setSizePolicy(sizePolicy)
        self.label_project_name.setMinimumSize(QSize(80, 24))
        self.label_project_name.setMaximumSize(QSize(80, 24))
        self.label_project_name.setObjectName("label_project_name")
        self.horizontalLayout.addWidget(self.label_project_name)
        self.lineEdit_project_name = QLineEdit(self)
        self.lineEdit_project_name.setObjectName("lineEdit_project_name")
        self.horizontalLayout.addWidget(self.lineEdit_project_name)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_location = QLabel(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_location.sizePolicy().hasHeightForWidth())
        self.label_location.setSizePolicy(sizePolicy)
        self.label_location.setMinimumSize(QSize(80, 24))
        self.label_location.setMaximumSize(QSize(80, 24))
        self.label_location.setObjectName("label_location")
        self.horizontalLayout_2.addWidget(self.label_location)
        self.lineEdit_location = QLineEdit(self)
        self.lineEdit_location.setObjectName("lineEdit_location")
        self.lineEdit_location.setReadOnly(True)
        self.lineEdit_location.setText(os.getcwd())
        self.horizontalLayout_2.addWidget(self.lineEdit_location)
        self.toolbutton_open = QToolButton(self)
        self.toolbutton_open.setMinimumSize(QSize(24, 24))
        self.toolbutton_open.setMaximumSize(QSize(24, 24))
        self.toolbutton_open.setObjectName("toolbutton_open")
        self.horizontalLayout_2.addWidget(self.toolbutton_open)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi()

        #        给项目路径和项目赋初值
        self.project_dir = self.lineEdit_location.text()
        self.project_name = self.lineEdit_project_name.text()
        #        信号与槽进行连接
        self.buttonBox.accepted.connect(self.slot_accept)
        self.buttonBox.rejected.connect(self.reject)
        self.toolbutton_open.clicked.connect(self.slot_open)
        self.lineEdit_project_name.textChanged.connect(self.slot_set_dir)
        QMetaObject.connectSlotsByName(self)

    def get_project_info(self):
        self.setup()
        flag = self.exec_()
        if (flag == QDialog.Accepted):
            #            返回一个元组,包含路径和项目名
            return (self.project_dir, self.project_name)
        else:
            return (None, None)

# =============================================================================
# Slots
# =============================================================================
#    让用户选择项目的路径

    def slot_open(self):

        sel_dir = QFileDialog.getExistingDirectory(self, 'Select Folder')
        if sel_dir:
            sel_dir = sel_dir.replace('/', '\\')
            self.project_dir = sel_dir
            if self.project_name:
                self.lineEdit_location.setText(self.project_dir + '\\' +
                                               self.project_name)
            else:
                self.lineEdit_location.setText(self.project_dir)

#    自定义一个接受的事件,需要判断用户是否已完成项目的创建

    def slot_accept(self):

        if (self.project_dir and self.project_name):
            self.accept()
        else:
            tipDialog = QMessageBox(self)
            tipDialog.resize(300, 100)
            tipDialog.setWindowTitle("Caution")
            tipDialog.setText("You have not created a project yet!")
            tipDialog.exec_()

    def slot_set_dir(self):

        #        这里还应该判断用户输入正确的项目名字符串
        self.project_name = self.lineEdit_project_name.text()
        if self.project_name:
            self.lineEdit_location.setText(self.project_dir + '\\' +
                                           self.project_name)
        else:
            self.lineEdit_location.setText(self.project_dir)

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("NewProjectDialog", "创建新项目"))
        self.label_project_name.setText(_translate("NewProjectDialog", "项目名"))
        self.label_location.setText(_translate("NewProjectDialog", "路径"))
        self.toolbutton_open.setText(_translate("NewProjectDialog", "..."))


#    def retranslateUi(self):
#        _translate = QCoreApplication.translate
#        self.setWindowTitle(_translate("NewProjectDialog", "Create new project"))
#        self.label_project_name.setText(_translate("NewProjectDialog", "Project name"))
#        self.label_location.setText(_translate("NewProjectDialog", "Location"))
#        self.toolbutton_open.setText(_translate("NewProjectDialog", "..."))
Beispiel #21
0
class Ui_MnWndw_1(object):
    def __init__(self):
        # Define initial object attributes
        # Empty lineedit
        self.txt = ""
        # Default number of terms
        self.s = 2

    def openWindow(self, subject, s):
        '''
        :param subject: str: Determine which subject to study
        :param s: int: determine number of terms
        '''
        self.window = QMainWindow()
        self.ui = Ui_MainWindow2(subject, s)
        self.ui.setupUi(self.window)
        self.window.show()

    def setupUi(self, MnWndw_1):
        # Set layout for Mainwindow, including widgets
        # Main window
        MnWndw_1.setObjectName("MnWndw_1")
        MnWndw_1.resize(543, 434)
        self.cntrlWdgt = QWidget(MnWndw_1)
        self.cntrlWdgt.setObjectName("cntrlWdgt")
        self.grdLO_1 = QGridLayout(self.cntrlWdgt)
        self.grdLO_1.setObjectName("grdLO_1")

        # Insert widgets
        # Dialog button box, left down corner
        self.btnBx = QDialogButtonBox(self.cntrlWdgt)
        self.btnBx.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        self.btnBx.setObjectName("btnBx")
        self.grdLO_1.addWidget(self.btnBx, 2, 1, 1, 1)
        self.HLO_3 = QHBoxLayout()
        self.HLO_3.setObjectName("HLO_3")
        # Add left push button
        self.pshBtn_2 = QPushButton(self.cntrlWdgt)
        self.pshBtn_2.setObjectName("pshBtn_2")
        self.HLO_3.addWidget(self.pshBtn_2)
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.ChkBx = QCheckBox(self.cntrlWdgt)
        self.ChkBx.setObjectName("ChkBx")
        self.verticalLayout_3.addWidget(self.ChkBx)
        self.ChkBx_2 = QCheckBox(self.cntrlWdgt)
        self.ChkBx_2.setObjectName("ChkBx_2")
        self.verticalLayout_3.addWidget(self.ChkBx_2)
        self.ChkBx_3 = QCheckBox(self.cntrlWdgt)
        self.ChkBx_3.setObjectName("ChkBx_3")
        self.verticalLayout_3.addWidget(self.ChkBx_3)
        self.ChkBx_4 = QCheckBox(self.cntrlWdgt)
        self.ChkBx_4.setObjectName("ChkBx_4")
        self.verticalLayout_3.addWidget(self.ChkBx_4)
        self.line = QFrame(self.cntrlWdgt)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_3.addWidget(self.line)
        self.ChkBx_5 = QCheckBox(self.cntrlWdgt)
        self.ChkBx_5.setObjectName("ChkBx_5")
        self.verticalLayout_3.addWidget(self.ChkBx_5)
        self.HLO_3.addLayout(self.verticalLayout_3)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.HLO_3.addItem(spacerItem)
        self.grdLO_2 = QGridLayout()
        self.grdLO_2.setObjectName("grdLO_2")
        self.RadBtn_5 = QRadioButton(self.cntrlWdgt)
        self.RadBtn_5.setObjectName("RadBtn_5")
        self.grdLO_2.addWidget(self.RadBtn_5, 2, 1, 1, 1)
        self.RadBtn_4 = QRadioButton(self.cntrlWdgt)
        self.RadBtn_4.setObjectName("RadBtn_4")
        self.grdLO_2.addWidget(self.RadBtn_4, 4, 1, 1, 1)
        self.pshBtn = QPushButton(self.cntrlWdgt)
        self.pshBtn.setObjectName("pshBtn")
        self.grdLO_2.addWidget(self.pshBtn, 0, 0, 1, 1)
        self.RadBtn_2 = QRadioButton(self.cntrlWdgt)
        self.RadBtn_2.setObjectName("RadBtn_2")
        self.grdLO_2.addWidget(self.RadBtn_2, 0, 1, 1, 1)
        self.RadBtn_3 = QRadioButton(self.cntrlWdgt)
        self.RadBtn_3.setObjectName("RadBtn_3")
        self.grdLO_2.addWidget(self.RadBtn_3, 1, 1, 1, 1)
        self.RadBtn = QRadioButton(self.cntrlWdgt)
        self.RadBtn.setObjectName("RadBtn")
        self.grdLO_2.addWidget(self.RadBtn, 3, 1, 1, 1)
        self.HLO_3.addLayout(self.grdLO_2)
        self.grdLO_1.addLayout(self.HLO_3, 1, 1, 1, 1)
        self.HLO_4 = QHBoxLayout()
        self.HLO_4.setObjectName("HLO_4")
        self.lbl_2 = QLabel(self.cntrlWdgt)
        self.lbl_2.setObjectName("lbl_2")
        self.HLO_4.addWidget(self.lbl_2)
        self.lbl = QLabel(self.cntrlWdgt)
        self.lbl.setObjectName("lbl")
        self.HLO_4.addWidget(self.lbl)
        self.grdLO_1.addLayout(self.HLO_4, 0, 1, 1, 1)
        self.lineEdit = QLineEdit(self.cntrlWdgt)
        self.lineEdit.setObjectName("lineEdit")
        self.grdLO_1.addWidget(self.lineEdit, 3, 1, 1, 1)
        MnWndw_1.setCentralWidget(self.cntrlWdgt)
        self.menubar = QMenuBar(MnWndw_1)
        self.menubar.setGeometry(QRect(0, 0, 543, 26))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        MnWndw_1.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MnWndw_1)
        self.statusbar.setObjectName("statusbar")
        MnWndw_1.setStatusBar(self.statusbar)
        self.actionExit = QAction(MnWndw_1)
        self.actionExit.setObjectName("actionExit")
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MnWndw_1)
        self.ChkBx_5.toggled['bool'].connect(self.ChkBx_4.setChecked)
        self.ChkBx_5.toggled['bool'].connect(self.ChkBx_3.setChecked)
        self.ChkBx_5.toggled['bool'].connect(self.ChkBx_2.setChecked)
        self.ChkBx_5.toggled['bool'].connect(self.ChkBx.setChecked)
        self.btnBx.accepted.connect(self.lineEdit.clear)
        QMetaObject.connectSlotsByName(MnWndw_1)

    def retranslateUi(self, MnWndw_1):
        _translate = QCoreApplication.translate
        MnWndw_1.setWindowTitle(_translate("MnWndw_1", "ExampleProject"))
        self.pshBtn_2.setText(_translate("MnWndw_1", "Lock choice"))
        self.ChkBx.setText(_translate("MnWndw_1", "Division"))
        self.ChkBx_2.setText(_translate("MnWndw_1", "Multiplication"))
        self.ChkBx_3.setText(_translate("MnWndw_1", "Subtraktion"))
        self.ChkBx_4.setText(_translate("MnWndw_1", "Addition"))
        self.ChkBx_5.setText(_translate("MnWndw_1", "Check all"))
        self.RadBtn_5.setText(_translate("MnWndw_1", "3"))
        self.RadBtn_4.setText(_translate("MnWndw_1", "5"))
        self.pshBtn.setText(_translate("MnWndw_1", "Lock choice"))
        self.RadBtn_2.setText(_translate("MnWndw_1", "1"))
        self.RadBtn_3.setText(_translate("MnWndw_1", "2"))
        self.RadBtn.setText(_translate("MnWndw_1", "4"))
        self.lbl_2.setText(_translate("MnWndw_1", "Select subject"))
        self.lbl.setText(_translate("MnWndw_1", "Select difficulty"))
        self.menuFile.setTitle(_translate("MnWndw_1", "File"))
        self.actionExit.setText(_translate("MnWndw_1", "Exit"))

        # LineEdit signals
        self.btnBx.accepted.connect(lambda: self.txtAtt(self.lineEdit.text()))
        self.btnBx.rejected.connect(lambda: self.lineEdit.setText(""))

        # Radiobutton signals
        self.RadBtn.clicked.connect(lambda: self.sizing(self.RadBtn.text()))
        self.RadBtn_5.clicked.connect(
            lambda: self.sizing(self.RadBtn_5.text()))
        self.RadBtn_4.clicked.connect(
            lambda: self.sizing(self.RadBtn_4.text()))
        self.RadBtn_2.clicked.connect(
            lambda: self.sizing(self.RadBtn_2.text()))
        self.RadBtn_3.clicked.connect(
            lambda: self.sizing(self.RadBtn_3.text()))

        # Checkboxes signals
        self.ChkBx_5.toggled['bool'].connect(
            lambda: self.lineEdit.setText(self.txt))
        self.ChkBx_4.toggled['bool'].connect(
            lambda: self.openWindow(self.ChkBx_4.text(), self.s))
        self.ChkBx_3.toggled['bool'].connect(
            lambda: self.openWindow(self.ChkBx_3.text(), self.s))
        self.ChkBx_2.toggled['bool'].connect(
            lambda: self.openWindow(self.ChkBx_2.text(), self.s))
        self.ChkBx.toggled['bool'].connect(
            lambda: self.openWindow(self.ChkBx.text(), self.s))

        QMetaObject.connectSlotsByName(MnWndw_1)

    def txtAtt(self, txt):
        self.txt = txt
        fn = "tstfile" + ".txt"
        if fn not in os.listdir():
            f = open(fn, "w+")
        else:
            a = input("Do you want to overwrite file?").lower()
            if a == 'y':
                f = open(fn, "w+")
        with open(fn, "a") as f:
            f.write(txt + "\n")

    def sizing(self, s):
        self.s = int(s)
class AboutBox(QDialog):
    """
    About Window class
    """
    def __init__(self, lang):
        super().__init__()
        self.lang = lang
        self._translate = QCoreApplication.translate
        # Init
        self.label_header = QLabel(self)
        self.tabs = QTabWidget(self)
        self.tab_about = QWidget()
        self.tab_sources = QWidget()
        self.tab_authors = QWidget()
        self.tab_thanks = QWidget()
        self.sources_text = QTextBrowser(self.tab_sources)
        self.about_text = QTextBrowser(self.tab_about)
        self.authors_text = QTextBrowser(self.tab_authors)
        self.thanks_text = QTextBrowser(self.tab_thanks)
        self.button_box = QDialogButtonBox(self)

    def setup_ui(self):
        """
        setup window ui
        """
        self.setObjectName("about_box")
        self.resize(600, 345)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QSize(600, 345))
        self.setMaximumSize(QSize(600, 345))
        icon = QIcon()
        icon.addPixmap(QPixmap("icon.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.label_header.setGeometry(QRect(0, 0, 571, 41))
        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.label_header.sizePolicy().hasHeightForWidth())
        self.label_header.setSizePolicy(size_policy)
        font = QFont()
        font.setPointSize(14)
        self.label_header.setFont(font)
        self.label_header.setIndent(10)
        self.label_header.setObjectName("label_header")
        self.tabs.setGeometry(QRect(10, 40, 580, 250))
        self.tabs.setObjectName("tabs")
        self.tab_about.setObjectName("tab_about")
        self.about_text.setGeometry(QRect(0, 0, 580, 220))
        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.about_text.sizePolicy().hasHeightForWidth())
        self.about_text.setSizePolicy(size_policy)
        self.about_text.setAcceptDrops(False)
        self.about_text.setReadOnly(True)
        self.about_text.setOpenExternalLinks(True)
        self.about_text.setObjectName("about_text")
        self.tabs.addTab(self.tab_about, "")
        self.tab_sources.setObjectName("tab_sources")
        self.sources_text.setGeometry(QRect(0, 0, 580, 220))
        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.sources_text.sizePolicy().hasHeightForWidth())
        self.sources_text.setSizePolicy(size_policy)
        self.sources_text.setAcceptDrops(False)
        self.sources_text.setReadOnly(True)
        self.sources_text.setOpenExternalLinks(True)
        self.sources_text.setObjectName("sources_text")
        self.tabs.addTab(self.tab_sources, "")
        self.tab_authors.setObjectName("tab_authors")
        self.authors_text.setGeometry(QRect(0, 0, 580, 220))
        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.authors_text.sizePolicy().hasHeightForWidth())
        self.authors_text.setSizePolicy(size_policy)
        self.authors_text.setAcceptDrops(False)
        self.authors_text.setReadOnly(True)
        self.authors_text.setOpenExternalLinks(True)
        self.authors_text.setObjectName("authors_text")
        self.tabs.addTab(self.tab_authors, "")
        self.tab_thanks.setObjectName("tab_thanks")
        self.thanks_text.setGeometry(QRect(0, 0, 580, 220))
        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.thanks_text.sizePolicy().hasHeightForWidth())
        self.thanks_text.setSizePolicy(size_policy)
        self.thanks_text.setAcceptDrops(False)
        self.thanks_text.setReadOnly(True)
        self.thanks_text.setOpenExternalLinks(True)
        self.thanks_text.setObjectName("thanks_text")
        self.tabs.addTab(self.tab_thanks, "")
        self.button_box.setGeometry(QRect(490, 300, 104, 37))
        self.button_box.setOrientation(Qt.Horizontal)
        self.button_box.setStandardButtons(QDialogButtonBox.Cancel)
        cancel_button = self.button_box.button(QDialogButtonBox.Cancel)
        cancel_button.setText(self._translate("About Box", "Cancel"))
        self.button_box.setObjectName("button_box")
        self.button_box.rejected.connect(self.reject)
        self.button_box.accepted.connect(self.accept)
        adjust_layout_direction(self, self.lang)
        self.retranslate_ui()
        self.tabs.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(self)

    def retranslate_ui(self):
        """
        Items strings
        """
        self.setWindowTitle(self._translate("About Box", "About "))
        self.label_header.setText(
            self._translate("About Box", "Xiaomi Flashable Firmware Creator"))
        self.about_text.setHtml(
            self._translate(
                "About Box",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" "
                "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n "
                "<html><head><meta name=\"qrichtext\" content=\"1\" />"
                "<style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'Arial\'; "
                "font-size:11pt; font-weight:400; "
                "font-style:normal;\">\n"
                "<p style=\" margin-top:12px; margin-bottom:12px; "
                "margin-left:0px; margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/XiaomiFirmwareUpdater/"
                "xiaomi-flashable-firmware-creator.py/\">"
                "<span style=\" text-decoration: underline; "
                "color:#009dff;\">"
                "Xiaomi Flashable Firmware Creator</span></a> "
                "is a Python 3 tool that generates flashable "
                "firmware-update "
                "packages, extracted from official MIUI ROMS. "
                "By <a href=\"https://xiaomifirmwareupdater.com\">"
                "<span style=\" text-decoration: underline; "
                "color:#009dff;\">"
                "XiaomiFirmwareUpdater.</span></a></p>\n"
                "<p style=\" margin-top:12px; margin-bottom:12px; "
                "margin-left:0px; "
                "margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\">"
                "It supports creating untouched firmware, "
                "non-arb firmware, "
                "firmware + vendor flashable zip, and "
                "firmware-less ROMs.</p>\n"
                "<p style=\" margin-top:12px; margin-bottom:12px; "
                "margin-left:0px; "
                "margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://xiaomifirmwareupdater.com\">"
                "<span style=\" text-decoration: underline; "
                "color:#009dff;\">"
                "Xiaomi Firmware Updater</span></a> is a community "
                "project, started "
                "in January 2018, aims to provide firmware packages "
                "for all Xiaomi "
                "devices, in order to allow custom ROM users to update "
                "their devices’ "
                "firmware easily through custom recovery instead of "
                "having to flash "
                "full ROM every time they want to update."
                "</p></body></html>"))
        self.tabs.setTabText(self.tabs.indexOf(self.tab_about),
                             self._translate("About Box", "About"))
        self.sources_text.setHtml(
            self._translate(
                "About Box",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" "
                "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" />"
                "<style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'Arial\'; "
                "font-size:11pt; font-weight:400; "
                "font-style:normal;\">\n"
                "<p style=\" margin-top:0px; margin-bottom:0px; "
                "margin-left:0px; "
                "margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\">"
                "Xiaomi Flashable Firmware Creator is a free and "
                "open source software, "
                "licensed under the GPL-3.0 "
                "(GNU GENERAL PUBLIC LICENSE) license.</p>\n"
                "<p style=\" margin-top:12px; margin-bottom:12px; "
                "margin-left:0px; "
                "margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\">"
                "It uses the following libraries:</p>\n"
                "<ul style=\"margin-top: 0px; margin-bottom: 0px; "
                "margin-left: 0px; "
                "margin-right: 0px; -qt-list-indent: 1;\">"
                "<li style=\"\" "
                "style=\" margin-top:0px; margin-bottom:0px; "
                "margin-left:0px; "
                "margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\">"
                "PyQt 5.15.0 (built against 5.15.0)</li></ul>"
                "</body></html>"))
        self.tabs.setTabText(self.tabs.indexOf(self.tab_sources),
                             self._translate("About Box", "Sources"))
        self.authors_text.setHtml(
            self._translate(
                "About Box",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" "
                "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" />"
                "<style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'Arial\'; "
                "font-size:11pt; font-weight:400; "
                "font-style:normal;\">\n"
                "<ul style=\"margin-top: 0px; margin-bottom: "
                "0px; margin-left: "
                "0px; margin-right: 0px; -qt-list-indent: 1;\">"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/yshalsager\">"
                "<span style=\" text-decoration: underline; "
                "color:#009dff;\">"
                "yshalsager</span></a>  - Lead Developer</li><"
                "/ul></body></html>"))
        self.tabs.setTabText(self.tabs.indexOf(self.tab_authors),
                             self._translate("About Box", "Authors"))
        self.thanks_text.setHtml(
            self._translate(
                "About Box",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" "
                "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" "
                "/><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'Arial\'; "
                "font-size:11pt; font-weight:400; "
                "font-style:normal;\">\n"
                "<ul style=\"margin-top: 0px; margin-bottom: 0px; "
                "margin-left: 0px; "
                "margin-right: 0px; -qt-list-indent: 1;\">"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/ardadem\">"
                "<span style=\" text-decoration: underline; "
                "color:#009dff;\">ardadem</span></a>"
                " for shell script version</li>\n"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/hh2333\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">TH779</span>"
                "</a> and <a href=\"https://github.com/PIPIPIG233666\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">PIPIPIG233666</span>"
                "</a> for Simplified Chinese translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/zstanecic\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Zvonimir Stanecic</span>"
                "</a> for Croatian translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/0n3-70uch\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Fabian Briese</span>"
                "</a> for German translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://t.me/foxone\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Ed</span>"
                "</a> for Italian translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/kacskrz\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Orjon</span>"
                "</a> for Polish translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/DeicPro\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Pablo</span>"
                "</a> and Thorin for Spanish translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://t.me/Bodzey\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Bohdan Cherniak</span>"
                "</a> for Russian translation</li>"
                "<li style=\"\" style=\" margin-top:0px; "
                "margin-bottom:0px; "
                "margin-left:0px; margin-right:0px; "
                "-qt-block-indent:0; "
                "text-indent:0px;\">"
                "<a href=\"https://github.com/EnesSastim\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Enes Sastim</span>"
                "</a> and <a href=\"https://github.com/trzpro\">"
                "<span style=\" text-decoration: "
                "underline; color:#009dff;\">Emir Bardakçı</span>"
                "</a> for Turkish translation</li></ul>\n"
                "<p style=\" margin-top:0px; margin-bottom:0px; "
                "margin-left:0px; "
                "margin-right:0px; -qt-block-indent:0; "
                "text-indent:0px;\"><br/>"
                "And all people who have contributed "
                "and I have forgotten to mention."
                "</p></body></html>"))
        self.tabs.setTabText(self.tabs.indexOf(self.tab_thanks),
                             self._translate("About Box", "Thanks To"))
Beispiel #23
0
class NewProjectDialog(QDialog):
    def __init__(self, pro_last_dir="./", img_last_dir="./", parent=None):
        super(NewProjectDialog, self).__init__(parent)
        self.setWindowTitle("新建项目")
        self.setMinimumWidth(970)

        self.pro_last_dir = pro_last_dir
        self.img_last_dir = img_last_dir

        self.grid_layout = QGridLayout(self)
        self.grid_layout.setSpacing(20)
        self.grid_layout.setObjectName("newProjectDialogGridLayout")

        project_name_label = QLabel("项目名称(N):")
        self.project_name_edit = QLineEdit()
        project_name_label.setBuddy(self.project_name_edit)
        self.grid_layout.addWidget(project_name_label, 0, 0)
        self.grid_layout.addWidget(self.project_name_edit, 0, 1)

        project_location_label = QLabel("项目位置(L):")
        self.project_location_edit = QLineEdit()
        self.select_pro_location_btn = QPushButton("浏览(B)...")
        project_location_label.setBuddy(self.project_location_edit)
        self.grid_layout.addWidget(project_location_label, 1, 0)
        self.grid_layout.addWidget(self.project_location_edit, 1, 1)
        self.grid_layout.addWidget(self.select_pro_location_btn, 1, 2)

        image_location_label = QLabel("原始图片(I):")
        self.image_location_edit = QLineEdit()
        self.select_img_location_btn = QPushButton("浏览(S)...")
        image_location_label.setBuddy(self.image_location_edit)
        self.grid_layout.addWidget(image_location_label, 2, 0)
        self.grid_layout.addWidget(self.image_location_edit, 2, 1)
        self.grid_layout.addWidget(self.select_img_location_btn, 2, 2)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.button(QDialogButtonBox.Ok).setText("确定")
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消")
        self.buttonBox.setObjectName("buttonBox")
        self.grid_layout.addWidget(self.buttonBox, 3, 1, 1, 2)

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

        self.project_name_edit.textChanged.connect(self._set_ok_btn_enabled)
        self.project_location_edit.textChanged.connect(
            self._set_ok_btn_enabled)
        self.image_location_edit.textChanged.connect(self._set_ok_btn_enabled)

        self.select_pro_location_btn.clicked.connect(
            self._get_project_location)
        self.select_img_location_btn.clicked.connect(self._get_image_location)

    def _get_project_location(self):
        project_directory = QFileDialog.getExistingDirectory(
            self, "项目位置", self.pro_last_dir)
        self.project_location_edit.setText(project_directory)

    def _get_image_location(self):
        file_format = "Image files (*.png *.jpg *.ico *tif)"
        image_file = QFileDialog.getOpenFileName(self, "选择原始图片",
                                                 self.img_last_dir,
                                                 file_format)[0]
        self.image_location_edit.setText(image_file)

    def _set_ok_btn_enabled(self):
        project_directory = self.project_location_edit.text()
        image_file = self.image_location_edit.text()
        project_name = self.project_name_edit.text()

        if all([project_directory, image_file, project_name]):
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        else:
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    def new_project_info(self):
        return self.project_name_edit.text(), \
               self.project_location_edit.text(),\
               self.image_location_edit.text()

    def accept(self):
        class ProjectNameError(Exception):
            pass

        class ProjectDirError(Exception):
            pass

        class ImageFileError(Exception):
            pass

        project_directory = self.project_location_edit.text()
        image_file = self.image_location_edit.text()
        project_name = self.project_name_edit.text()

        try:
            if not os.path.exists(project_directory[:3]):
                raise ProjectDirError
        except ProjectDirError:
            QMessageBox.critical(self, "新建项目", "项目位置无效,请输入正确的项目位置!")
            return
        QDialog.accept(self)
class Ui_DialogSettings(QWidget):
    def __init__(self, parent, transaction_file_name, transaction_file_name_v2,
                 main_folder_name, distribution_file_name, settings_file):
        super().__init__()
        self.parent = parent
        self.transaction_file_name = transaction_file_name
        self.transaction_file_name_v2 = transaction_file_name_v2
        self.distribution_file_name = distribution_file_name
        self.main_folder_name = main_folder_name
        self.settings_file = settings_file

    def setupUi(self, dialog):

        dialog.setObjectName("Dialog")
        dialog.resize(500, 155)
        self.gridLayoutWidget_2 = QWidget(dialog)
        self.gridLayoutWidget_2.setGeometry(QRect(5, 5, 490, 100))
        self.gridLayoutWidget_2.setObjectName("gridLayoutWidget_2")
        self.gridLayout_3 = QGridLayout(self.gridLayoutWidget_2)
        self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.companies_label = QLabel(self.gridLayoutWidget_2)
        self.companies_label.setObjectName("label_4")
        self.gridLayout_3.addWidget(self.companies_label, 0, 2, 1, 1)
        self.trans_label = QLabel(self.gridLayoutWidget_2)
        self.trans_label.setObjectName("label_8")
        self.trans_label_v2 = QLabel(self.gridLayoutWidget_2)
        self.trans_label_v2.setObjectName("label_8")

        self.main_folder_label = QLabel(self.gridLayoutWidget_2)
        self.main_folder_label.setObjectName("main_folder_label")

        self.gridLayout_3.addWidget(self.trans_label, 1, 2, 1, 1)
        self.gridLayout_3.addWidget(self.trans_label_v2, 2, 2, 1, 1)
        self.gridLayout_3.addWidget(self.main_folder_label, 3, 2, 1, 1)

        self.trans_file = QLineEdit(self.gridLayoutWidget_2)
        self.trans_file.setObjectName("trans_file")
        self.trans_file.setReadOnly(True)

        self.trans_file_v2 = QLineEdit(self.gridLayoutWidget_2)
        self.trans_file_v2.setObjectName("trans_file")
        self.trans_file_v2.setReadOnly(True)

        self.main_folder = QLineEdit(self.gridLayoutWidget_2)
        self.main_folder.setObjectName("main_folder")
        self.main_folder.setReadOnly(True)

        # self.gift_codes_button = QToolButton(self.gridLayoutWidget_2)
        # # iconfolder = QIcon()
        # # iconfolder.addPixmap(QPixmap("./icons/folder.svg"), QIcon.Normal, QIcon.Off)
        # # self.gift_codes_button.setIcon(iconfolder)
        # self.gift_codes_button.setObjectName("gift_codes_button")
        #
        # # self.gift_codes_button.clicked.connect(lambda: self._open_file_gifts_codes('main_folder'))
        #self.gridLayout_3.addWidget(self.gift_codes_button, 4, 1, 1, 1)

        self.gridLayout_3.addWidget(self.trans_file, 1, 1, 1, 1)
        self.gridLayout_3.addWidget(self.trans_file_v2, 2, 1, 1, 1)
        self.gridLayout_3.addWidget(self.main_folder, 3, 1, 1, 1)

        self.no_dist_file = QLineEdit(self.gridLayoutWidget_2)
        self.no_dist_file.setObjectName("no_dist_file")
        self.no_dist_file.setReadOnly(True)
        self.gridLayout_3.addWidget(self.no_dist_file, 0, 1, 1, 1)

        self.toolButton_5 = QToolButton(self.gridLayoutWidget_2)
        iconexcel = QIcon()
        iconexcel.addPixmap(QPixmap("./icons/excel.svg"), QIcon.Normal,
                            QIcon.Off)
        self.toolButton_5.setIcon(iconexcel)
        self.toolButton_5.setObjectName("toolButton_5")
        self.gridLayout_3.addWidget(self.toolButton_5, 1, 0, 1, 1)
        self.toolButton_5.clicked.connect(
            lambda: self._open_file_dialog('trans'))

        self.trans_v2_button = QToolButton(self.gridLayoutWidget_2)
        self.trans_v2_button.setIcon(iconexcel)
        self.trans_v2_button.setObjectName("trans_v2_button")
        self.gridLayout_3.addWidget(self.trans_v2_button, 2, 0, 1, 1)
        self.trans_v2_button.clicked.connect(
            lambda: self._open_file_dialog('trans_v2'))

        self.main_folder_button = QToolButton(self.gridLayoutWidget_2)
        iconfolder = QIcon()
        iconfolder.addPixmap(QPixmap("./icons/folder.svg"), QIcon.Normal,
                             QIcon.Off)
        self.main_folder_button.setIcon(iconfolder)
        self.main_folder_button.setObjectName("main_folder_button")
        self.gridLayout_3.addWidget(self.main_folder_button, 3, 0, 1, 1)
        self.main_folder_button.clicked.connect(
            lambda: self._open_file_dialog('main_folder'))

        self.toolButton_6 = QToolButton(self.gridLayoutWidget_2)
        self.toolButton_6.setIcon(iconexcel)
        self.toolButton_6.setObjectName("toolButton_6")
        self.gridLayout_3.addWidget(self.toolButton_6, 0, 0, 1, 1)
        self.toolButton_6.clicked.connect(
            lambda: self._open_file_dialog('no_dis'))
        self.gridLayout_3.addWidget(self.toolButton_6, 0, 0, 1, 1)
        self.buttonBox = QDialogButtonBox(dialog)
        self.buttonBox.setGeometry(QRect(150, 120, 341, 32))
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setObjectName("Save")
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")

        # init data
        self.no_dist_file.setText(self.distribution_file_name)
        self.trans_file.setText(self.transaction_file_name)
        self.trans_file_v2.setText(self.transaction_file_name_v2)
        self.main_folder.setText(self.main_folder_name)

        # Extract data
        self.buttonBox.accepted.connect(self.__save)
        self.buttonBox.rejected.connect(dialog.reject)
        QMetaObject.connectSlotsByName(dialog)

        self.retranslateUi(dialog)
        return self.gridLayoutWidget_2

    def retranslateUi(self, dialog):
        _translate = QCoreApplication.translate
        dialog.setWindowTitle(_translate("Dialog", "הגדרת קבצים"))
        self.companies_label.setText(_translate("Dialog", "קובץ לא להפצה"))
        self.trans_label.setText(_translate("Dialog", "קובץ עסקאות 200"))
        self.trans_label_v2.setText(_translate("Dialog", "קובץ עסקאות 1220"))
        self.main_folder_label.setText(_translate("Dialog", "תיקיית חג ראשית"))

    def _open_file_dialog(self, name):

        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        if name == "no_dis":
            file, _ = QFileDialog.getOpenFileName(
                self,
                "QFileDialog.getOpenFileName()",
                "",
                "Excel (*.csv)",
                options=options)
            self.no_dist_file.setText('{}'.format(file))
        elif name == "trans":
            file, _ = QFileDialog.getOpenFileName(
                self,
                "QFileDialog.getOpenFileName()",
                "",
                "Excel (*.csv)",
                options=options)
            self.trans_file.setText('{}'.format(file))
        elif name == "trans_v2":
            file, _ = QFileDialog.getOpenFileName(
                self,
                "QFileDialog.getOpenFileName()",
                "",
                "Excel (*.csv)",
                options=options)
            self.trans_file_v2.setText('{}'.format(file))
        elif name == "main_folder":
            directory = str(QFileDialog.getExistingDirectory())
            self.main_folder.setText('{}'.format(directory))

    def __save(self):

        if self.no_dist_file.text() != "" and self.trans_file.text() != "" \
                and self.trans_file_v2.text() != "" and self.main_folder.text() != "":
            buttonReply = QMessageBox.question(
                self, 'שמירת הגדרות', "האם אתה בטוח שאתה רוצה לשמור?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if buttonReply == QMessageBox.Yes:
                with open(self.settings_file) as json_file:
                    settings = json.load(json_file)
                settings['קובץ לא להפצה'] = self.no_dist_file.text()
                settings['קובץ עסקאות'] = self.trans_file.text()
                settings['קובץ עסקאות 200'] = self.trans_file_v2.text()
                settings['תיקייה ראשית'] = self.main_folder.text()

                with open(self.settings_file, 'w') as outfile:
                    json.dump(settings, outfile)

                QMessageBox.about(self, "נשמר בהצלחה",
                                  "הנתונים נשמרו בהצלחה, הפעל מחדש")

                print('Saved.')
class ConfigurationWidget(QWidget):
    """
    Class implementing a dialog for the configuration of eric6.
    
    @signal preferencesChanged() emitted after settings have been changed
    @signal masterPasswordChanged(str, str) emitted after the master
        password has been changed with the old and the new password
    @signal accepted() emitted to indicate acceptance of the changes
    @signal rejected() emitted to indicate rejection of the changes
    """
    preferencesChanged = pyqtSignal()
    masterPasswordChanged = pyqtSignal(str, str)
    accepted = pyqtSignal()
    rejected = pyqtSignal()

    DefaultMode = 0
    HelpBrowserMode = 1
    TrayStarterMode = 2

    def __init__(self, parent=None, fromEric=True, displayMode=DefaultMode):
        """
        Constructor
        
        @param parent The parent widget of this dialog. (QWidget)
        @keyparam fromEric flag indicating a dialog generation from within the
            eric6 ide (boolean)
        @keyparam displayMode mode of the configuration dialog
            (DefaultMode, HelpBrowserMode, TrayStarterMode)
        @exception RuntimeError raised to indicate an invalid dialog mode
        """
        assert displayMode in (ConfigurationWidget.DefaultMode,
                               ConfigurationWidget.HelpBrowserMode,
                               ConfigurationWidget.TrayStarterMode)

        super(ConfigurationWidget, self).__init__(parent)
        self.fromEric = fromEric
        self.displayMode = displayMode

        self.__setupUi()

        self.itmDict = {}

        if not fromEric:
            from PluginManager.PluginManager import PluginManager
            try:
                self.pluginManager = e5App().getObject("PluginManager")
            except KeyError:
                self.pluginManager = PluginManager(self)
                e5App().registerObject("PluginManager", self.pluginManager)

        if displayMode == ConfigurationWidget.DefaultMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function create to
                # create the configuration page. This must have the method
                # save to save the settings.
                "applicationPage": [
                    self.tr("Application"), "preferences-application.png",
                    "ApplicationPage", None, None
                ],
                "cooperationPage": [
                    self.tr("Cooperation"), "preferences-cooperation.png",
                    "CooperationPage", None, None
                ],
                "corbaPage": [
                    self.tr("CORBA"), "preferences-orbit.png", "CorbaPage",
                    None, None
                ],
                "emailPage": [
                    self.tr("Email"), "preferences-mail_generic.png",
                    "EmailPage", None, None
                ],
                "graphicsPage": [
                    self.tr("Graphics"), "preferences-graphics.png",
                    "GraphicsPage", None, None
                ],
                "iconsPage": [
                    self.tr("Icons"), "preferences-icons.png", "IconsPage",
                    None, None
                ],
                "ircPage": [self.tr("IRC"), "irc.png", "IrcPage", None, None],
                "networkPage": [
                    self.tr("Network"), "preferences-network.png",
                    "NetworkPage", None, None
                ],
                "notificationsPage": [
                    self.tr("Notifications"), "preferences-notifications.png",
                    "NotificationsPage", None, None
                ],
                "pluginManagerPage": [
                    self.tr("Plugin Manager"), "preferences-pluginmanager.png",
                    "PluginManagerPage", None, None
                ],
                "printerPage": [
                    self.tr("Printer"), "preferences-printer.png",
                    "PrinterPage", None, None
                ],
                "pythonPage": [
                    self.tr("Python"), "preferences-python.png", "PythonPage",
                    None, None
                ],
                "qtPage": [
                    self.tr("Qt"), "preferences-qtlogo.png", "QtPage", None,
                    None
                ],
                "securityPage": [
                    self.tr("Security"), "preferences-security.png",
                    "SecurityPage", None, None
                ],
                "shellPage": [
                    self.tr("Shell"), "preferences-shell.png", "ShellPage",
                    None, None
                ],
                "tasksPage":
                [self.tr("Tasks"), "task.png", "TasksPage", None, None],
                "templatesPage": [
                    self.tr("Templates"), "preferences-template.png",
                    "TemplatesPage", None, None
                ],
                "trayStarterPage": [
                    self.tr("Tray Starter"), "erict.png", "TrayStarterPage",
                    None, None
                ],
                "vcsPage": [
                    self.tr("Version Control Systems"), "preferences-vcs.png",
                    "VcsPage", None, None
                ],
                "0debuggerPage": [
                    self.tr("Debugger"), "preferences-debugger.png", None,
                    None, None
                ],
                "debuggerGeneralPage": [
                    self.tr("General"), "preferences-debugger.png",
                    "DebuggerGeneralPage", "0debuggerPage", None
                ],
                "debuggerPythonPage": [
                    self.tr("Python"), "preferences-pyDebugger.png",
                    "DebuggerPythonPage", "0debuggerPage", None
                ],
                "debuggerPython3Page": [
                    self.tr("Python3"), "preferences-pyDebugger.png",
                    "DebuggerPython3Page", "0debuggerPage", None
                ],
                "debuggerRubyPage": [
                    self.tr("Ruby"), "preferences-rbDebugger.png",
                    "DebuggerRubyPage", "0debuggerPage", None
                ],
                "0editorPage": [
                    self.tr("Editor"), "preferences-editor.png", None, None,
                    None
                ],
                "editorAPIsPage": [
                    self.tr("APIs"), "preferences-api.png", "EditorAPIsPage",
                    "0editorPage", None
                ],
                "editorAutocompletionPage": [
                    self.tr("Autocompletion"),
                    "preferences-autocompletion.png",
                    "EditorAutocompletionPage", "0editorPage", None
                ],
                "editorAutocompletionQScintillaPage": [
                    self.tr("QScintilla"), "qscintilla.png",
                    "EditorAutocompletionQScintillaPage",
                    "editorAutocompletionPage", None
                ],
                "editorCalltipsPage": [
                    self.tr("Calltips"), "preferences-calltips.png",
                    "EditorCalltipsPage", "0editorPage", None
                ],
                "editorCalltipsQScintillaPage": [
                    self.tr("QScintilla"), "qscintilla.png",
                    "EditorCalltipsQScintillaPage", "editorCalltipsPage", None
                ],
                "editorGeneralPage": [
                    self.tr("General"), "preferences-general.png",
                    "EditorGeneralPage", "0editorPage", None
                ],
                "editorFilePage": [
                    self.tr("Filehandling"), "preferences-filehandling.png",
                    "EditorFilePage", "0editorPage", None
                ],
                "editorSearchPage": [
                    self.tr("Searching"), "preferences-search.png",
                    "EditorSearchPage", "0editorPage", None
                ],
                "editorSpellCheckingPage": [
                    self.tr("Spell checking"), "preferences-spellchecking.png",
                    "EditorSpellCheckingPage", "0editorPage", None
                ],
                "editorStylesPage": [
                    self.tr("Style"), "preferences-styles.png",
                    "EditorStylesPage", "0editorPage", None
                ],
                "editorSyntaxPage": [
                    self.tr("Code Checkers"), "preferences-debugger.png",
                    "EditorSyntaxPage", "0editorPage", None
                ],
                "editorTypingPage": [
                    self.tr("Typing"), "preferences-typing.png",
                    "EditorTypingPage", "0editorPage", None
                ],
                "editorExportersPage": [
                    self.tr("Exporters"), "preferences-exporters.png",
                    "EditorExportersPage", "0editorPage", None
                ],
                "1editorLexerPage": [
                    self.tr("Highlighters"),
                    "preferences-highlighting-styles.png", None, "0editorPage",
                    None
                ],
                "editorHighlightersPage": [
                    self.tr("Filetype Associations"),
                    "preferences-highlighter-association.png",
                    "EditorHighlightersPage", "1editorLexerPage", None
                ],
                "editorHighlightingStylesPage": [
                    self.tr("Styles"), "preferences-highlighting-styles.png",
                    "EditorHighlightingStylesPage", "1editorLexerPage", None
                ],
                "editorKeywordsPage": [
                    self.tr("Keywords"), "preferences-keywords.png",
                    "EditorKeywordsPage", "1editorLexerPage", None
                ],
                "editorPropertiesPage": [
                    self.tr("Properties"), "preferences-properties.png",
                    "EditorPropertiesPage", "1editorLexerPage", None
                ],
                "0helpPage":
                [self.tr("Help"), "preferences-help.png", None, None, None],
                "helpAppearancePage": [
                    self.tr("Appearance"), "preferences-styles.png",
                    "HelpAppearancePage", "0helpPage", None
                ],
                "helpDocumentationPage": [
                    self.tr("Help Documentation"),
                    "preferences-helpdocumentation.png",
                    "HelpDocumentationPage", "0helpPage", None
                ],
                "helpViewersPage": [
                    self.tr("Help Viewers"), "preferences-helpviewers.png",
                    "HelpViewersPage", "0helpPage", None
                ],
                "helpWebBrowserPage": [
                    self.tr("eric6 Web Browser"), "ericWeb.png",
                    "HelpWebBrowserPage", "0helpPage", None
                ],
                "0projectPage": [
                    self.tr("Project"), "preferences-project.png", None, None,
                    None
                ],
                "projectBrowserPage": [
                    self.tr("Project Viewer"), "preferences-project.png",
                    "ProjectBrowserPage", "0projectPage", None
                ],
                "projectPage": [
                    self.tr("Project"), "preferences-project.png",
                    "ProjectPage", "0projectPage", None
                ],
                "multiProjectPage": [
                    self.tr("Multiproject"), "preferences-multiproject.png",
                    "MultiProjectPage", "0projectPage", None
                ],
                "0interfacePage": [
                    self.tr("Interface"), "preferences-interface.png", None,
                    None, None
                ],
                "interfacePage": [
                    self.tr("Interface"), "preferences-interface.png",
                    "InterfacePage", "0interfacePage", None
                ],
                "viewmanagerPage": [
                    self.tr("Viewmanager"), "preferences-viewmanager.png",
                    "ViewmanagerPage", "0interfacePage", None
                ],
            }

            self.configItems.update(
                e5App().getObject("PluginManager").getPluginConfigData())
        elif displayMode == ConfigurationWidget.HelpBrowserMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function create to
                # create the configuration page. This must have the method
                # save to save the settings.
                "interfacePage": [
                    self.tr("Interface"), "preferences-interface.png",
                    "HelpInterfacePage", None, None
                ],
                "networkPage": [
                    self.tr("Network"), "preferences-network.png",
                    "NetworkPage", None, None
                ],
                "printerPage": [
                    self.tr("Printer"), "preferences-printer.png",
                    "PrinterPage", None, None
                ],
                "securityPage": [
                    self.tr("Security"), "preferences-security.png",
                    "SecurityPage", None, None
                ],
                "0helpPage":
                [self.tr("Help"), "preferences-help.png", None, None, None],
                "helpAppearancePage": [
                    self.tr("Appearance"), "preferences-styles.png",
                    "HelpAppearancePage", "0helpPage", None
                ],
                "helpDocumentationPage": [
                    self.tr("Help Documentation"),
                    "preferences-helpdocumentation.png",
                    "HelpDocumentationPage", "0helpPage", None
                ],
                "helpWebBrowserPage": [
                    self.tr("eric6 Web Browser"), "ericWeb.png",
                    "HelpWebBrowserPage", "0helpPage", None
                ],
            }
        elif displayMode == ConfigurationWidget.TrayStarterMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function create to
                # create the configuration page. This must have the method
                # save to save the settings.
                "trayStarterPage": [
                    self.tr("Tray Starter"), "erict.png", "TrayStarterPage",
                    None, None
                ],
            }
        else:
            raise RuntimeError("Illegal mode value: {0}".format(displayMode))

        # generate the list entries
        for key in sorted(self.configItems.keys()):
            pageData = self.configItems[key]
            if pageData[3]:
                pitm = self.itmDict[pageData[3]]  # get the parent item
            else:
                pitm = self.configList
            self.itmDict[key] = ConfigurationPageItem(pitm, pageData[0], key,
                                                      pageData[1])
            self.itmDict[key].setData(0, Qt.UserRole, key)
            self.itmDict[key].setExpanded(True)
        self.configList.sortByColumn(0, Qt.AscendingOrder)

        # set the initial size of the splitter
        self.configSplitter.setSizes([200, 600])

        self.configList.itemActivated.connect(self.__showConfigurationPage)
        self.configList.itemClicked.connect(self.__showConfigurationPage)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.rejected)

        if displayMode != ConfigurationWidget.TrayStarterMode:
            self.__initLexers()

    def accept(self):
        """
        Public slot to accept the buttonBox accept signal.
        """
        if not isMacPlatform():
            wdg = self.focusWidget()
            if wdg == self.configList:
                return

        self.accepted.emit()

    def __setupUi(self):
        """
        Private method to perform the general setup of the configuration
        widget.
        """
        self.setObjectName("ConfigurationDialog")
        self.resize(900, 650)
        self.verticalLayout_2 = QVBoxLayout(self)
        self.verticalLayout_2.setSpacing(6)
        self.verticalLayout_2.setContentsMargins(6, 6, 6, 6)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.configSplitter = QSplitter(self)
        self.configSplitter.setOrientation(Qt.Horizontal)
        self.configSplitter.setObjectName("configSplitter")

        self.configListWidget = QWidget(self.configSplitter)
        self.leftVBoxLayout = QVBoxLayout(self.configListWidget)
        self.leftVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.leftVBoxLayout.setSpacing(0)
        self.leftVBoxLayout.setObjectName("leftVBoxLayout")
        self.configListFilter = E5ClearableLineEdit(
            self, self.tr("Enter filter text..."))
        self.configListFilter.setObjectName("configListFilter")
        self.leftVBoxLayout.addWidget(self.configListFilter)
        self.configList = QTreeWidget()
        self.configList.setObjectName("configList")
        self.leftVBoxLayout.addWidget(self.configList)
        self.configListFilter.textChanged.connect(self.__filterTextChanged)

        self.scrollArea = QScrollArea(self.configSplitter)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setObjectName("scrollArea")

        self.configStack = QStackedWidget()
        self.configStack.setFrameShape(QFrame.Box)
        self.configStack.setFrameShadow(QFrame.Sunken)
        self.configStack.setObjectName("configStack")
        self.scrollArea.setWidget(self.configStack)

        self.emptyPage = QWidget()
        self.emptyPage.setGeometry(QRect(0, 0, 372, 591))
        self.emptyPage.setObjectName("emptyPage")
        self.vboxlayout = QVBoxLayout(self.emptyPage)
        self.vboxlayout.setSpacing(6)
        self.vboxlayout.setContentsMargins(6, 6, 6, 6)
        self.vboxlayout.setObjectName("vboxlayout")
        spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem)
        self.emptyPagePixmap = QLabel(self.emptyPage)
        self.emptyPagePixmap.setAlignment(Qt.AlignCenter)
        self.emptyPagePixmap.setObjectName("emptyPagePixmap")
        self.emptyPagePixmap.setPixmap(
            QPixmap(os.path.join(getConfig('ericPixDir'), 'eric.png')))
        self.vboxlayout.addWidget(self.emptyPagePixmap)
        self.textLabel1 = QLabel(self.emptyPage)
        self.textLabel1.setAlignment(Qt.AlignCenter)
        self.textLabel1.setObjectName("textLabel1")
        self.vboxlayout.addWidget(self.textLabel1)
        spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem1)
        self.configStack.addWidget(self.emptyPage)

        self.verticalLayout_2.addWidget(self.configSplitter)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Apply
                                          | QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok
                                          | QDialogButtonBox.Reset)
        self.buttonBox.setObjectName("buttonBox")
        if not self.fromEric and \
                self.displayMode == ConfigurationWidget.DefaultMode:
            self.buttonBox.button(QDialogButtonBox.Apply).hide()
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        self.verticalLayout_2.addWidget(self.buttonBox)

        self.setWindowTitle(self.tr("Preferences"))

        self.configList.header().hide()
        self.configList.header().setSortIndicator(0, Qt.AscendingOrder)
        self.configList.setSortingEnabled(True)
        self.textLabel1.setText(
            self.tr("Please select an entry of the list \n"
                    "to display the configuration page."))

        QMetaObject.connectSlotsByName(self)
        self.setTabOrder(self.configList, self.configStack)

        self.configStack.setCurrentWidget(self.emptyPage)

        self.configList.setFocus()

    def __filterTextChanged(self, filter):
        """
        Private slot to handle a change of the filter.
        
        @param filter text of the filter line edit (string)
        """
        self.__filterChildItems(self.configList.invisibleRootItem(), filter)

    def __filterChildItems(self, parent, filter):
        """
        Private method to filter child items based on a filter string.
        
        @param parent reference to the parent item (QTreeWidgetItem)
        @param filter filter string (string)
        @return flag indicating a visible child item (boolean)
        """
        childVisible = False
        filter = filter.lower()
        for index in range(parent.childCount()):
            itm = parent.child(index)
            if itm.childCount() > 0:
                visible = self.__filterChildItems(itm, filter) or \
                    filter == "" or filter in itm.text(0).lower()
            else:
                visible = filter == "" or filter in itm.text(0).lower()
            if visible:
                childVisible = True
            itm.setHidden(not visible)

        return childVisible

    def __initLexers(self):
        """
        Private method to initialize the dictionary of preferences lexers.
        """
        import QScintilla.Lexers
        from .PreferencesLexer import PreferencesLexer, \
            PreferencesLexerLanguageError

        self.lexers = {}
        for language in QScintilla.Lexers.getSupportedLanguages():
            if language not in self.lexers:
                try:
                    self.lexers[language] = PreferencesLexer(language, self)
                except PreferencesLexerLanguageError:
                    pass

    def __importConfigurationPage(self, name):
        """
        Private method to import a configuration page module.
        
        @param name name of the configuration page module (string)
        @return reference to the configuration page module
        """
        modName = "Preferences.ConfigurationPages.{0}".format(name)
        try:
            mod = __import__(modName)
            components = modName.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod
        except ImportError:
            E5MessageBox.critical(
                self, self.tr("Configuration Page Error"),
                self.tr("""<p>The configuration page <b>{0}</b>"""
                        """ could not be loaded.</p>""").format(name))
            return None

    def __showConfigurationPage(self, itm, column):
        """
        Private slot to show a selected configuration page.
        
        @param itm reference to the selected item (QTreeWidgetItem)
        @param column column that was selected (integer) (ignored)
        """
        pageName = itm.getPageName()
        self.showConfigurationPageByName(pageName, setCurrent=False)

    def __initPage(self, pageData):
        """
        Private method to initialize a configuration page.
        
        @param pageData data structure for the page to initialize
        @return reference to the initialized page
        """
        page = None
        if isinstance(pageData[2], types.FunctionType):
            page = pageData[2](self)
        else:
            mod = self.__importConfigurationPage(pageData[2])
            if mod:
                page = mod.create(self)
        if page is not None:
            self.configStack.addWidget(page)
            pageData[-1] = page
            try:
                page.setMode(self.displayMode)
            except AttributeError:
                pass
        return page

    def showConfigurationPageByName(self, pageName, setCurrent=True):
        """
        Public slot to show a named configuration page.
        
        @param pageName name of the configuration page to show (string)
        @param setCurrent flag indicating to set the current item (boolean)
        """
        if pageName == "empty" or pageName not in self.configItems:
            page = self.emptyPage
        else:
            pageData = self.configItems[pageName]
            if pageData[-1] is None and pageData[2] is not None:
                # the page was not loaded yet, create it
                page = self.__initPage(pageData)
            else:
                page = pageData[-1]
            if page is None:
                page = self.emptyPage
            elif setCurrent:
                items = self.configList.findItems(
                    pageData[0], Qt.MatchFixedString | Qt.MatchRecursive)
                for item in items:
                    if item.data(0, Qt.UserRole) == pageName:
                        self.configList.setCurrentItem(item)
        self.configStack.setCurrentWidget(page)
        ssize = self.scrollArea.size()
        if self.scrollArea.horizontalScrollBar():
            ssize.setHeight(ssize.height() -
                            self.scrollArea.horizontalScrollBar().height() - 2)
        if self.scrollArea.verticalScrollBar():
            ssize.setWidth(ssize.width() -
                           self.scrollArea.verticalScrollBar().width() - 2)
        psize = page.minimumSizeHint()
        self.configStack.resize(max(ssize.width(), psize.width()),
                                max(ssize.height(), psize.height()))

        if page != self.emptyPage:
            page.polishPage()
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(True)
        else:
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)

        # reset scrollbars
        for sb in [
                self.scrollArea.horizontalScrollBar(),
                self.scrollArea.verticalScrollBar()
        ]:
            if sb:
                sb.setValue(0)

        self.__currentConfigurationPageName = pageName

    def getConfigurationPageName(self):
        """
        Public method to get the page name of the current page.
        
        @return page name of the current page (string)
        """
        return self.__currentConfigurationPageName

    def calledFromEric(self):
        """
        Public method to check, if invoked from within eric.
        
        @return flag indicating invocation from within eric (boolean)
        """
        return self.fromEric

    def getPage(self, pageName):
        """
        Public method to get a reference to the named page.
        
        @param pageName name of the configuration page (string)
        @return reference to the page or None, indicating page was
            not loaded yet
        """
        return self.configItems[pageName][-1]

    def getLexers(self):
        """
        Public method to get a reference to the lexers dictionary.
        
        @return reference to the lexers dictionary
        """
        return self.lexers

    def setPreferences(self):
        """
        Public method called to store the selected values into the preferences
        storage.
        """
        for key, pageData in list(self.configItems.items()):
            if pageData[-1]:
                pageData[-1].save()
                # page was loaded (and possibly modified)
                QApplication.processEvents()  # ensure HMI is responsive

    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.buttonBox.button(QDialogButtonBox.Apply):
            self.on_applyButton_clicked()
        elif button == self.buttonBox.button(QDialogButtonBox.Reset):
            self.on_resetButton_clicked()

    @pyqtSlot()
    def on_applyButton_clicked(self):
        """
        Private slot called to apply the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            page = self.configStack.currentWidget()
            savedState = page.saveState()
            page.save()
            self.preferencesChanged.emit()
            if savedState is not None:
                page.setState(savedState)

    @pyqtSlot()
    def on_resetButton_clicked(self):
        """
        Private slot called to reset the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            currentPage = self.configStack.currentWidget()
            savedState = currentPage.saveState()
            pageName = self.configList.currentItem().getPageName()
            self.configStack.removeWidget(currentPage)
            if pageName == "editorHighlightingStylesPage":
                self.__initLexers()
            self.configItems[pageName][-1] = None

            self.showConfigurationPageByName(pageName)
            if savedState is not None:
                self.configStack.currentWidget().setState(savedState)
Beispiel #26
0
class CopyVersionWidget(QDialog):
    '''
    Fully copy an existing version, spec files and models.
    '''
    version_copied = pyqtSignal(str)
    def __init__(self, parent=None):
        super(CopyVersionWidget, self).__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.parent = parent
        self.setWindowTitle('Copy CAT Version')
        self.version_name = None
        self.main_layout = QVBoxLayout()
        self.version_form = QFormLayout()

        self.main_layout.addLayout(self.version_form)
        self.setupUI()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttonBox.setObjectName("version_copy_warning")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.buttonBox.setWindowTitle("Version Copy Warning")
        self.buttonBox.rejected.connect(self.reject)

        self.main_layout.addWidget(self.buttonBox)
        self.setLayout(self.main_layout)

    def _update_version_name(self, value):
        self.version_name = value
           

    def _version_check(self, version):
        """
        Checks that user has both supplied a version name and that, if supplied, 
        the name is unique.

            # Arguments
                version(String): version name supplied by user

            # Returns
                bool: True if version is supplied and unique, else False
        """
        if version == '':
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
            return False
        v = os.path.join(VERSION_BASE_DIR, version)
        if os.path.exists(v):
            msg_box = QMessageBox()
            msg_box.setIcon(QMessageBox.Warning)
            msg_box.setText("Version {} already exists!".format(version))
            msg_box.setWindowTitle('Version Warning')
            msg_box.exec_()
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
            return False
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        return True


    def copy_version(self):
        """
        Copy version specified by the user.
        """
        if(self.exec_() == QDialog.Accepted):
            src_dir = self.version_selection.currentData()
            dest_dir = os.path.join(VERSION_BASE_DIR, self.version_name_input.text())
            try:
                shutil.copytree(src_dir, dest_dir)
                self.version_copied.emit(dest_dir)
            except OSError as e:
                if e.errno == errno.ENOTDIR:
                    shutil.copy(src_dir, dest_dir)
                else:
                    exceptionWarning(f'Unable to copy {src_dir} to {dest_dir}', title='Copy version exception')
                    tb = traceback.format_exc()
                    print(tb)
            except Exception as e:
                exceptionWarning('Error occured when copying version.', e, title='Copy version exception')
            finally:
                self.version_name = None
                self.version_selection.addItem(self.version_name_input.text(), dest_dir)


    def setupUI(self):
        self.version_name_label = QLabel("Version name: ")
        self.version_name_input = QLineEdit(objectName='version_name')
        self.version_name_input.textChanged.connect(
            lambda state, y=self.version_name_input:
                self._update_version_name(
                    (y.text() if self._version_check(y.text()) else None)
                )
        )
        self.version_form.addRow(self.version_name_label, self.version_name_input)

        self.version_selection_label = QLabel("Select version: ")
        self.version_selection = QComboBox(objectName='version_select')

        available_versions = os.listdir(VERSION_BASE_DIR)
        for version in available_versions:
            v_path = os.path.join(VERSION_BASE_DIR, version)
            if os.path.isdir(v_path):
                self.version_selection.addItem(version, v_path)
        # self.version_selection.currentIndexChanged.connect(lambda x, y=self.version_selection:
        #                                                    self._update_version_name(
        #                                                        y.currentData())
        #                                                    )
        self.version_form.addRow(self.version_selection_label, self.version_selection)
Beispiel #27
0
class TfModelDialog(QDialog):
    """TfModelDialog is the basic structure behind model dialogs in CATScore.
    # Arguments
        model_params: String, path to default parameters .json file.
    """
    def __init__(self, parent=None, params={}):
        super(TfModelDialog, self).__init__(parent)
        self.logger = logging.getLogger(__name__)
        self.model_params = params['model_params']
        self.optimizer_params = params['optimizer_params']
        self.model_class = params['model_class']
        self.updated_model_params = {}
        # input_widgets is a list of all dynamically created input widgets for the various model params.
        self.input_widgets = {}

        self.setWindowTitle(params['model_class'])
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.setObjectName("tf_model_buttonbox")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.model_groupbox = QGroupBox()
        self.model_groupbox.setTitle("Model hyperparameters")

        self.optimizer_groupbox = QGroupBox()
        self.optimizer_groupbox.setTitle("Optimizer hyperparameters")

        self.main_layout = QVBoxLayout()
        self.outer_hbox = QHBoxLayout()
        self.model_param_form = QFormLayout()
        self.optimizer_param_form = QFormLayout()

        self.setupModelUI()
        self.setupOptimizerUI()

        self.model_groupbox.setLayout(self.model_param_form)
        self.optimizer_groupbox.setLayout(self.optimizer_param_form)

        self.outer_hbox.addWidget(self.model_groupbox)
        self.outer_hbox.addStretch()
        self.outer_hbox.addWidget(self.optimizer_groupbox)

        self.main_layout.addLayout(self.outer_hbox)
        self.main_layout.addStretch()
        self.main_layout.addWidget(self.buttonBox)
        self.setLayout(self.main_layout)
        self.move(20, 10)

    def getModelName(self):
        return self.model_params['model_class']

    def getClass(self, params):
        """Return instantiated class using importlib
        """
        module = importlib.import_module(params['model_module'])
        module_class = getattr(module, params['model_class'])
        if "static_params" in params:
            model = module_class(**params['static_params'])
        else:
            model = module_class()
        return model

    def saveParams(self):
        """Saves the parameters entered by the user.  
        """
        if (self.exec_() == QDialog.Accepted):
            print("Updated Params as they hit saveParams:")
            print(json.dumps(self.updated_model_params, indent=2))

        else:
            print("Denied!")

    def setupModelUI(self):
        self.setupUI(self.model_params, self.model_param_form)

    def setupOptimizerUI(self):
        self.setupUI(self.optimizer_params, self.optimizer_param_form)

    def setupMetricsUI(self):
        pass

    def setupUI(self, params, form):
        for k, v in params.items():
            try:
                label_string = k
                label = QLabel(' '.join(label_string.split('_')))
                if (v is True or v is False):
                    input_field = QComboBox(objectName=k)
                    input_field.addItem('True', True)
                    input_field.addItem('False', False)
                    if v:
                        input_field.setCurrentIndex(0)
                    else:
                        input_field.setCurrentIndex(1)
                    input_field.currentIndexChanged.connect(
                        lambda state, x=k, y=input_field: self._updateParam(
                            'model', x, y.currentData()))

                elif isinstance(v, float):
                    input_field = QDoubleSpinBox(objectName=k)
                    input_field.setDecimals(len(str(v)) - 2)
                    input_field.setValue(v)
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._updateParam(
                            'model', x, y.value()))

                elif isinstance(v, int):
                    input_field = QSpinBox(objectName=k)
                    input_field.setRange(0, 10000)
                    input_field.setValue(v)
                    input_field.valueChanged.connect(
                        lambda state, x=k, y=input_field: self._updateParam(
                            'model', x, y.value()))

                else:
                    input_field = QLineEdit(objectName=k)
                    input_field.setText(v)
                    # lambda for connecting pyqtSignals.  Param two will pass None instead of an empty
                    # string if no response given by user.
                    input_field.textChanged.connect(
                        lambda state, x=k, y=input_field: self._updateParam(
                            'model', x, (None
                                         if y.text() == '' else y.text())))

                form.addRow(label, input_field)
                self.input_widgets[k] = input_field
            except Exception as e:
                self.logger.error("Error generating Tensorflow Dialog",
                                  exc_info=True)
                print("Exception {} occured with key {} and value {}".format(
                    e, k, v))
                tb = traceback.format_exc()
                print(tb)

    def _splitKey(self, key):
        return key.split('__')[1]

    def _updateParam(self, param_type, key, value):
        print("updateParams key, value: {}, {}, {}".format(
            param_type, key, value))
        class_key = '__' + key + '__'
        if param_type == 'model':
            self.updated_model_params[class_key] = value

    @pyqtSlot(str)
    def update_version(self, directory):
        print("update_version in {} called with {}".format(
            self.model_class, directory))
class PopUpFunction(QDialog):
    """
    Abstract Base Class, inherting from QDialog,
    extended by function specific parameter input popups
    generic for most functions.
    Information about coefficients are taken from objective function direclty
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, function_coeffs, function_object, normal_theme):
        """
        init
        :param function_coeffs: function coefficients
        :param function_object: function object
        :param normal_theme: bool for dark/normal theme
        """
        super(PopUpFunction, self).__init__()

        # get function object
        self.function_object = function_object

        # Presets
        self._presets(function_coeffs, normal_theme)

        # Main layout
        self._create_main_layout()

        # function_coeffs table
        self._create_coeffs_table()

        # down side
        self._create_down_side()

        # OK / cancel buttons
        self._create_buttons()

        # specials
        self._create_specials()

    def _presets(self, function_coeffs, normal_theme):
        """
        presettings
        :param function_coeffs: coefficients
        :param normal_theme: bool for dark/normal theme
        """
        self.italic_font = QFont()
        self.italic_font.setItalic(True)
        self.normal_font = QFont()
        self.normal_font.setItalic(False)
        self.normal_theme = normal_theme

        # if function parameter is not set yet
        if function_coeffs is None:
            self.first_time = True
            self.function_coeffs = []  # gets filled in _create_coeffs_table
            coeff = self.function_object.get_coeffs(self.function_object)
            for i in range(len(coeff)):
                self.function_coeffs.append(coeff[i].default)
        else:
            self.first_time = False
            self.function_coeffs = function_coeffs

    def _create_main_layout(self):
        """
        Set common main layout parameters
        """
        self.setWindowTitle("Set Function Parameter")
        self.icon_parameter = QIcon(module_dir + "gui_imgs/settings.png")
        self.setWindowIcon(self.icon_parameter)
        self.verticalLayout_main = QVBoxLayout()
        self.verticalLayout_main.setObjectName("verticalLayout_main")
        self.setLayout(self.verticalLayout_main)

    def _create_coeffs_table(self):
        """
        create table of function_coeffs with default values or set values
        from corresponding entries in objective function respectively
        set function_coeffs
        """
        # horizontal layout
        # purpose: to put additional things left or right to
        # the main coeff table as in Polynimial (+/- buttons)
        self.horizontalLayout_parameter = QHBoxLayout()
        self.horizontalLayout_parameter.setObjectName(
            "horizontalLayout_parameter")
        self.verticalLayout_main.addLayout(self.horizontalLayout_parameter)

        self.table_coeffs = QTableWidget(len(self.function_coeffs), 2)
        self._table_header()
        self.table_coeffs.setObjectName("table_coeffs")
        self.table_coeffs.setItemDelegateForColumn(
            0, TableColumnNoEdit())  # set col 0 read only
        for i in range(len(self.function_coeffs)):
            # set coeff name
            coeff = self.function_object.get_coeffs(self.function_object,
                                                    len(self.function_coeffs))
            tex_param_name = MathTexPixmapWidget(
                mathtex_to_qpixmap(coeff[i].latex,
                                   normal_theme=self.normal_theme))
            self.table_coeffs.setCellWidget(i, 0, tex_param_name)
            # check if opened before
            if self.first_time:  # if so, set default function_coeffs
                self.table_coeffs.setItem(
                    i, 1, QTableWidgetItem(str(coeff[i].default)))
            else:  # or already set function_coeffs
                self.table_coeffs.setItem(
                    i, 1,
                    QTableWidgetItem(str(_round(self.function_coeffs[i]))))

        self.horizontalLayout_parameter.addWidget(self.table_coeffs)
        # what to do if value is changed
        self.table_coeffs.itemChanged.connect(self._table_coeffs_value_changed)

    def _table_header(self):
        """
        Sets table headers
        """
        self.table_coeffs.setHorizontalHeaderLabels(["Variable", "Value"])
        self.table_coeffs.setVerticalHeaderLabels(
            ["" for _ in range(len(self.function_coeffs))])

    def _create_down_side(self):
        """
        create parameter labels
        """
        self.horizontalLayout_display = QHBoxLayout()
        self.horizontalLayout_display.setObjectName("horizontalLayout_display")
        self.verticalLayout_main.addLayout(self.horizontalLayout_display)
        #   function label heading
        self.label_coeffs_head = QLabel()
        self.label_coeffs_head.setObjectName("label_coeffs_head")
        self.label_coeffs_head.setText("Function:")
        self.horizontalLayout_display.addWidget(self.label_coeffs_head)
        #   function label
        self.label_coeffs = QLabel()
        self.label_coeffs.setObjectName("label_coeffs")
        self.label_coeffs.setFont(self.italic_font)
        self.horizontalLayout_display.addWidget(self.label_coeffs)
        # set function string
        self.coeff_string = mathtex_to_qpixmap(
            self.function_object.create_formula_string(self.function_object,
                                                       self.function_coeffs),
            normal_theme=self.normal_theme)
        self.coeff_string_plain = self.function_object.create_formula_string(
            self.function_object, self.function_coeffs)
        self.label_coeffs.setPixmap(self.coeff_string)

    def _create_buttons(self):
        """
        OK / cancel buttons
        """
        self.buttons_okcancel = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        self.buttonBox_okcancel = QDialogButtonBox(self.buttons_okcancel)
        self.buttonBox_okcancel.setObjectName("buttonBox_Warning")
        self.buttonBox_okcancel.accepted.connect(self.accept)
        self.buttonBox_okcancel.rejected.connect(self.reject)
        self.verticalLayout_main.addWidget(self.buttonBox_okcancel)

    @abstractmethod
    def _create_specials(self):
        """
        Function specific stuff
        """
        pass

    def _table_coeffs_value_changed(self, item):
        """
        called when any value is changed in coeff table to
        get coeff list and coeff list display string
        :param item: object of what has been changed
        """
        # if signal comes from second column
        if item == "del" or item.column(
        ) == 1:  # "del" is used when a row has been deleted as in Polynomial
            self.function_coeffs = []
            for i in range(self.table_coeffs.rowCount()):
                try:
                    # assert float input
                    add = float(self.table_coeffs.item(i, 1).text())
                    self.function_coeffs.append(add)
                except ValueError:
                    # display warning otherwise and reset cell
                    self.Warning = PopUpWarning("Please enter decimal number")
                    self.Warning.exec_()
                    self.function_coeffs.append(0)
                    self.table_coeffs.item(i, 1).setText("0")

        self.coeff_string = mathtex_to_qpixmap(
            self.function_object.create_formula_string(self.function_object,
                                                       self.function_coeffs),
            normal_theme=self.normal_theme)
        self.coeff_string_plain = self.function_object.create_formula_string(
            self.function_object, self.function_coeffs)

        # set function string
        if self.coeff_string:
            self.label_coeffs.setPixmap(self.coeff_string)
            self.label_coeffs.setFont(self.normal_font)
        else:
            self.label_coeffs.setText("not set yet")
            self.label_coeffs.setFont(self.italic_font)

        self._table_header()
Beispiel #29
0
class UiAddMicrographDialog(object):
    """
    UiAddMicrographDialog
    User interface for the add micrograph dialog which is used to import a micrograph into the program.
    """
    def __init__(self, add_micrograph_dialog):

        # set window title, object name and window size
        add_micrograph_dialog.setWindowTitle("Add Micrograph")
        add_micrograph_dialog.setObjectName("add_micrograph_dialog")
        add_micrograph_dialog.setFixedWidth(960)
        add_micrograph_dialog.setFixedHeight(480)

        # button box
        self.button_box = QDialogButtonBox(add_micrograph_dialog)
        self.button_box.setEnabled(True)
        self.button_box.setGeometry(QRect(415, 440, 535, 32))
        self.button_box.setOrientation(Qt.Horizontal)
        self.button_box.setStandardButtons(QDialogButtonBox.Cancel
                                           | QDialogButtonBox.Ok)
        self.button_box.setObjectName("button_box")

        # widget for the two plots
        self.plot_widget = QWidget(add_micrograph_dialog)
        self.plot_widget.setGeometry(QRect(10, 10, 940, 350))
        self.plot_widget.setObjectName("plot_widget")

        # widget for the toolbar
        self.toolbar_widget = QWidget(add_micrograph_dialog)
        self.toolbar_widget.setGeometry(QRect(10, 430, 400, 50))
        self.toolbar_widget.setObjectName("toolbar_widget")

        # widget for buttons controlling the points on the plots
        self.button_widget = QWidget(add_micrograph_dialog)
        self.button_widget.setGeometry(QRect(10, 365, 940, 32))
        self.button_widget.setObjectName("button_widget")

        # button to remove all moving points
        self.clear_all_moving_push_button = QPushButton(self.button_widget)
        self.clear_all_moving_push_button.setEnabled(False)
        self.clear_all_moving_push_button.setGeometry(QRect(580, 2, 100, 28))
        self.clear_all_moving_push_button.setObjectName(
            "clear_all_moving_push_button")
        self.clear_all_moving_push_button.setText("Clear All")

        # button to remove last moving point
        self.clear_last_moving_push_button = QPushButton(self.button_widget)
        self.clear_last_moving_push_button.setEnabled(False)
        self.clear_last_moving_push_button.setGeometry(QRect(475, 2, 100, 28))
        self.clear_last_moving_push_button.setObjectName(
            "clear_last_moving_push_button")
        self.clear_last_moving_push_button.setText("Clear Last")

        # button to remove all fixed points
        self.clear_all_fixed_push_button = QPushButton(self.button_widget)
        self.clear_all_fixed_push_button.setEnabled(False)
        self.clear_all_fixed_push_button.setGeometry(QRect(110, 2, 100, 28))
        self.clear_all_fixed_push_button.setObjectName(
            "clear_all_fixed_push_button")
        self.clear_all_fixed_push_button.setText("Clear All")

        # button to remove last fixed point
        self.clear_last_fixed_push_button = QPushButton(self.button_widget)
        self.clear_last_fixed_push_button.setEnabled(False)
        self.clear_last_fixed_push_button.setGeometry(QRect(5, 2, 100, 28))
        self.clear_last_fixed_push_button.setObjectName(
            "clear_last_fixed_push_button")
        self.clear_last_fixed_push_button.setText("Clear Last")

        # connect accept and reject
        self.button_box.accepted.connect(add_micrograph_dialog.accept)
        self.button_box.rejected.connect(add_micrograph_dialog.reject)
Beispiel #30
0
class AddCutplanDialog(QWidget):
    def setupUi(self, adddata=None, sqlfile=None, host=None):
        now = datetime.now()
        if host is None:
            self.host = ''
        else:
            self.host = host
        if adddata is None:
            self.addData = DataFrame(
                columns=['ID', 'Log Count', 'Description'])
        else:
            self.addData = adddata
        self.availData = None
        self.addPD = None
        self.avalPD = None

        # SQL
        if sqlfile is None:
            self.sqlfile = "support\\cpquery.sql"
        else:
            self.sqlfile = sqlfile

        # SERVER CONNECT
        QApplication.setOverrideCursor(
            QCursor(Qt.WaitCursor))
        self.conn = connect(LogScanner)
        QApplication.restoreOverrideCursor()

        self.setObjectName("Dialog")
        # self.setWindowIcon(QIcon('images/icon.ico'))
        self.resize(250, 900)
        self.setStyleSheet(
            "#Dialog {\n"
            "    background-color: white;\n"
            "}")
        self.installEventFilter(self)
        self.horizontalLayout = QVBoxLayout(self)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.calendarWidget = QCalendarWidget(self)
        font = QFont()
        font.setFamily("Tahoma")
        font.setPointSize(10)
        self.calendarWidget.setFont(font)
        self.calendarWidget.setStyleSheet(
            "#qt_calendar_prevmonth {\n"
            "    qproperty-icon: url(\"images/prev.png\");\n"
            "}\n"
            "\n"
            "#qt_calendar_nextmonth {\n"
            "    qproperty-icon: url(\"images/next.png\");\n"
            "}\n"
            "\n"
            "#qt_calendar_navigationbar {\n"
            "    background-color: qlineargradient(spread:pad, x1:0, y1:0, "
            "x2:1, y2:1, stop:0 rgb(192, 221, 221), stop:1 rgb(180, 233, "
            "197));\n"
            "}\n"
            "\n"
            "#qt_calendar_monthbutton {\n"
            "    color: rgb(0,115,119);\n"
            "    font-size: 15px;\n"
            "}\n"
            "\n"
            "#qt_calendar_yearbutton {\n"
            "    color: rgb(0,115,119);\n"
            "    font-size: 15px;\n"
            "}\n"
            "\n"
            "QCalendarWidget QMenu {\n"
            "    background-color: white;\n"
            "    color: rgb(0,115,119);\n"
            "}\n"
            "\n"
            "QCalendarWidget QMenu::item:selected {\n"
            "    background-color: rgb(192, 221, 221);\n"
            "    color: rgb(0,115,119);\n"
            "}\n"
            "\n"
            "QCalendarWidget QSpinBox {\n"
            "    color: rgb(0,115,119);\n"
            "    selection-background-color: rgb(0, 115, 119);\n"
            "    selection-color: white;\n"
            "}\n"
            "\n"
            "#qt_calendar_calendarview:enabled {\n"
            "    background-color: rgb(192, 221, 221);\n"
            "    alternate-background-color: white;\n"
            "    color: rgb(0, 115, 119);\n"
            "    selection-background-color: rgb(0, 115, 119);\n"
            "    selection-color: white;\n"
            "}\n"
            "\n"
            "#qt_calendar_calendarview:disabled {\n"
            "    color: #44acb0;\n"
            "}\n"
            "\n"
            "")
        btn = self.calendarWidget.findChild(
            QToolButton, "qt_calendar_prevmonth")
        btn.setCursor(QCursor(Qt.PointingHandCursor))
        btn = self.calendarWidget.findChild(
            QToolButton, "qt_calendar_nextmonth")
        btn.setCursor(QCursor(Qt.PointingHandCursor))
        self.calendarWidget.setVerticalHeaderFormat(
            QCalendarWidget.NoVerticalHeader)
        self.calendarWidget.setObjectName("calendarWidget")
        self.calendarWidget.setMinimumDate(QDate(2016, 1, 1))
        self.calendarWidget.setMaximumDate(
            QDate(now.year, now.month, now.day))
        btn = self.calendarWidget.findChild(
            QSpinBox, "qt_calendar_yearedit")
        btn.setAlignment(Qt.AlignCenter)
        btn.setButtonSymbols(QSpinBox.NoButtons)
        self.horizontalLayout.addWidget(self.calendarWidget)

        self.leftTV = QTableView(self)
        self.leftTV.setStyleSheet(
            "QTableView {"
            "border: 1px solid rgb(192, 221, 221);"
            "gridline-color: rgb(192, 221, 221);"
            "selection-background-color: rgb(192, 221, 221);"
            "selection-color: rgb(0,115,119);"
            "}"
            "QTableView::item::selected:!active {"
            "selection-color: rgb(0,115,119);"
            "}"
        )
        self.leftTV.setObjectName("leftTV")
        self.leftTV.horizontalHeader().setDefaultSectionSize(65)
        self.leftTV.horizontalHeader().setStretchLastSection(True)
        self.leftTV.horizontalHeader().setStyleSheet(
            "QHeaderView::section {"
            "height: 25px;"
            "border: 1px outset rgb(192, 221, 221);"
            "background-color: white;"
            "selection-background-color: white;"
            "}"
        )
        scrollbarss = """
QScrollBar:vertical {
border: none;
background: white;
width: 5px;
margin: 0 0 0 0;
}
QScrollBar::handle:vertical {
background: rgb(192, 221, 221);
border-radius: 2px;
min-height: 20px;
}
QScrollBar::add-line:vertical {
border: none;
background: none;
height: 0;
subcontrol-position: none;
subcontrol-origin: none;
}

QScrollBar::sub-line:vertical {
border: none;
background: none;
height: 0;
subcontrol-position: none;
subcontrol-origin: none;
}
QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
border: none;
width: 0;
height: 0;
background: none;
}

QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
background: none;
}

QScrollBar:horizontal {
border: none;
background: white;
height: 5px;
margin: 0 0 0 0;
}
QScrollBar::handle:horizontal {
background: rgb(192, 221, 221);
border-radius: 2px;
min-width: 20px;
}
QScrollBar::add-line:horizontal {
border: none;
background: none;
width: 0;
}

QScrollBar::sub-line:horizontal {
border: none;
background: none;
width: 0;
}
QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
border: none;
width: 0;
height: 0;
background: none;
}

QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
background: none;
}
"""
        self.leftTV.verticalScrollBar().setStyleSheet(scrollbarss)
        self.leftTV.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.leftTV.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.leftFilter = HoverFilter()
        self.leftTV.horizontalHeader().installEventFilter(self.leftFilter)
        lcDelegate = LogCountDelegate()
        self.leftTV.setItemDelegateForColumn(1, lcDelegate)
        self.horizontalLayout.addWidget(self.leftTV)

        self.middleButtonsLayout = QHBoxLayout()
        self.middleButtonsLayout.setObjectName("middleButtonsLayout")
        self.addButton = QToolButton(self)
        self.addButton.setObjectName("addButton")
        buttonStyle = \
            "QToolButton {\n"\
            "	background-color: qlineargradient(spread:pad, x1:0, y1:0, "\
            "x2:1, y2:1, stop:0 rgba(0, 115, 119, 255), stop:1 rgb(4, 147, "\
            "131));\n"\
            "	color: white;\n"\
            "	border: None;"\
            "	border-radius: 2px;"\
            "	font: 11pt \"Tahoma\";"\
            "}"
        self.addButton.setStyleSheet(buttonStyle)
        self.addButton.setCursor(
            QCursor(Qt.PointingHandCursor))
        self.middleButtonsLayout.addWidget(self.addButton)
        self.deleteButton = QToolButton(self)
        font = QFont()
        font.setPointSize(10)
        self.deleteButton.setFont(font)
        self.deleteButton.setObjectName("deleteButton")
        self.deleteButton.setStyleSheet(buttonStyle)
        self.deleteButton.setCursor(
            QCursor(Qt.PointingHandCursor))
        self.middleButtonsLayout.addWidget(self.deleteButton)
        self.horizontalLayout.addLayout(self.middleButtonsLayout)

        self.rightTV = QTableView(self)
        self.rightTV.setStyleSheet(
            "QTableView {"
            "border: 1px solid rgb(192, 221, 221);"
            "gridline-color: rgb(192, 221, 221);"
            "selection-background-color: rgb(192, 221, 221);"
            "selection-color: rgb(0,115,119);"
            "}"
            "QTableView::item::selected:!active {"
            "selection-color: rgb(0,115,119);"
            "}"
        )
        self.rightTV.setObjectName("rightTV")
        self.rightTV.verticalScrollBar().setStyleSheet(scrollbarss)
        self.rightTV.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.rightTV.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.rightTV.horizontalHeader().setDefaultSectionSize(65)
        self.rightTV.horizontalHeader().setStretchLastSection(True)
        self.rightTV.horizontalHeader().setStyleSheet(
            "QHeaderView::section {"
            "height: 25px;"
            "border: 1px outset rgb(192, 221, 221);"
            "background-color: white;"
            "selection-background-color: white;"
            "}"
        )
        self.rightFilter = HoverFilter()
        self.rightTV.horizontalHeader().installEventFilter(self.rightFilter)
        lcDelegate = LogCountDelegate()
        self.rightTV.setItemDelegateForColumn(1, lcDelegate)
        self.horizontalLayout.addWidget(self.rightTV)
        # self.horizontalLayout.addLayout(self.vertlayoutl)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStyleSheet(
            "QDialogButtonBox QPushButton {\n"
            "    background-color: ;\n"
            "    background-color: qlineargradient(spread:pad, x1:0, y1:0, "
            "x2:1, y2:1, stop:0 rgba(0, 115, 119, 255), stop:1 rgb(4, 147, "
            "131));\n"
            "    color: white;\n"
            "    width: 70px;\n"
            "    height: 25px;\n"
            "    border: None;\n"
            "    border-radius: 2px;\n"
            "    \n"
            "    font: 11pt \"Tahoma\";\n"
            "}")
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        for w in self.buttonBox.children():
            if w.metaObject().className() == "QPushButton":
                w.setCursor(QCursor(Qt.PointingHandCursor))
        self.horizontalLayout.addWidget(self.buttonBox)

        # DATA SET UP
        # self.onDateChange()
        # self.RTVSetUp()

        # EVENTS
        self.calendarWidget.selectionChanged.connect(self.onDateChange)
        self.addButton.clicked.connect(self.addFunction)
        self.deleteButton.clicked.connect(self.deleteFunction)

        self.retranslateUi(self)
        # self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(
        #     self.accept)
        # self.buttonBox.rejected.connect(self.reject)
        QMetaObject.connectSlotsByName(self)

    def eventFilter(self, object, event):
        if object is self and event.type() == QEvent.KeyPress:
            if event.key() in (Qt.Key_Return, Qt.Key_Enter,):
                return True
        return super(AddCutplanDialog, self).eventFilter(object, event)

    def onDateChange(self):
        f = open(self.sqlfile, 'r')
        sqltext = f.read()

        selDate = self.calendarWidget.selectedDate().toPyDate()
        date1 = datetime(selDate.year, selDate.month, selDate.day, 4, 0, 0, 0)
        date2 = date1 + timedelta(1)
        sqltext = sqltext.replace(
            '@date1', str(date1)).replace('@date2', str(date2))

        self.availData = read_sql(sqltext, self.conn)
        self.LTVSetUp()

    def LTVSetUp(self):
        self.availPD = PandasModel(
            self.availData
        )
        for i in range(self.addData.shape[0]):
            for j in range(self.availData.shape[0]):
                if self.addData.ID[i] == self.availData.ID[j]:
                    self.availPD.setCompleted(j)
        self.leftTV.setModel(self.availPD)
        self.leftTV.setSelectionBehavior(QTableView.SelectRows)
        self.leftTV.verticalHeader().setVisible(False)
        self.leftTV.setColumnWidth(0, 45)
        self.availPD.dataChanged.connect(self.updateAvailPD)

    def RTVSetUp(self):
        self.addPD = PandasModel(
            self.addData
        )
        self.rightTV.setModel(self.addPD)
        self.rightTV.setSelectionBehavior(QTableView.SelectRows)
        self.rightTV.verticalHeader().setVisible(False)
        self.rightTV.setColumnWidth(0, 45)
        self.addPD.dataChanged.connect(self.updateAddPD)

    def updateAvailPD(self, index, index2):
        self.availData.iloc[index.row(), index.column()] = \
            self.availPD._df.iloc[index.row(), index.column()]

    def updateAddPD(self, index, index2):
        self.addData.iloc[index.row(), index.column()] = \
            self.addPD._df.iloc[index.row(), index.column()]

    def addFunction(self):
        sm = self.leftTV.selectionModel()
        if sm.hasSelection():
            for r in sm.selectedRows():
                if not self.availPD._completed[r.row()]:
                    data = self.availData.iloc[r.row()]
                    self.addData = self.addData.append(data, ignore_index=True)
                    self.availPD.setCompleted(r.row())
            self.RTVSetUp()

    def deleteFunction(self):
        sm = self.rightTV.selectionModel()
        if sm.hasSelection():
            for r in sm.selectedRows():
                for i in range(self.availData.shape[0]):
                    if self.availData.ID[i] == self.addData.ID[r.row()]:
                        self.availPD.setCompleted(i, False)
                self.addData = self.addData.drop(index=r.row())
            self.addData = self.addData.reset_index().drop(columns='index')
            self.RTVSetUp()

    def retranslateUi(self, Dialog):
        _translate = QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Add Cutplans"))
        self.addButton.setText(_translate("Dialog", "Add ▼"))
        self.deleteButton.setText(_translate("Dialog", "▲ Remove"))
Beispiel #31
-1
class ConfigurationWidget(QWidget):
    """
    Class implementing a dialog for the configuration of eric6.
    
    @signal preferencesChanged() emitted after settings have been changed
    @signal masterPasswordChanged(str, str) emitted after the master
        password has been changed with the old and the new password
    @signal accepted() emitted to indicate acceptance of the changes
    @signal rejected() emitted to indicate rejection of the changes
    """
    preferencesChanged = pyqtSignal()
    masterPasswordChanged = pyqtSignal(str, str)
    accepted = pyqtSignal()
    rejected = pyqtSignal()
    
    DefaultMode = 0
    HelpBrowserMode = 1
    TrayStarterMode = 2
    HexEditorMode = 3
    
    def __init__(self, parent=None, fromEric=True, displayMode=DefaultMode,
                 expandedEntries=[]):
        """
        Constructor
        
        @param parent The parent widget of this dialog. (QWidget)
        @keyparam fromEric flag indicating a dialog generation from within the
            eric6 ide (boolean)
        @keyparam displayMode mode of the configuration dialog
            (DefaultMode, HelpBrowserMode, TrayStarterMode, HexEditorMode)
        @exception RuntimeError raised to indicate an invalid dialog mode
        @keyparam expandedEntries list of entries to be shown expanded
            (list of strings)
        """
        assert displayMode in (
            ConfigurationWidget.DefaultMode,
            ConfigurationWidget.HelpBrowserMode,
            ConfigurationWidget.TrayStarterMode,
            ConfigurationWidget.HexEditorMode,
        )
        
        super(ConfigurationWidget, self).__init__(parent)
        self.fromEric = fromEric
        self.displayMode = displayMode
        
        self.__setupUi()
        
        self.itmDict = {}
        
        if not fromEric:
            from PluginManager.PluginManager import PluginManager
            try:
                self.pluginManager = e5App().getObject("PluginManager")
            except KeyError:
                self.pluginManager = PluginManager(self)
                e5App().registerObject("PluginManager", self.pluginManager)
        
        if displayMode == ConfigurationWidget.DefaultMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "applicationPage":
                [self.tr("Application"), "preferences-application.png",
                 "ApplicationPage", None, None],
                "cooperationPage":
                [self.tr("Cooperation"), "preferences-cooperation.png",
                 "CooperationPage", None, None],
                "corbaPage":
                [self.tr("CORBA"), "preferences-orbit.png",
                 "CorbaPage", None, None],
                "emailPage":
                [self.tr("Email"), "preferences-mail_generic.png",
                 "EmailPage", None, None],
                "graphicsPage":
                [self.tr("Graphics"), "preferences-graphics.png",
                 "GraphicsPage", None, None],
                "hexEditorPage":
                [self.tr("Hex Editor"), "hexEditor.png",
                 "HexEditorPage", None, None],
                "iconsPage":
                [self.tr("Icons"), "preferences-icons.png",
                 "IconsPage", None, None],
                "ircPage":
                [self.tr("IRC"), "irc.png",
                 "IrcPage", None, None],
                "logViewerPage":
                [self.tr("Log-Viewer"), "preferences-logviewer.png",
                 "LogViewerPage", None, None],
                "mimeTypesPage":
                [self.tr("Mimetypes"), "preferences-mimetypes.png",
                 "MimeTypesPage", None, None],
                "networkPage":
                [self.tr("Network"), "preferences-network.png",
                 "NetworkPage", None, None],
                "notificationsPage":
                [self.tr("Notifications"),
                 "preferences-notifications.png",
                 "NotificationsPage", None, None],
                "pluginManagerPage":
                [self.tr("Plugin Manager"),
                 "preferences-pluginmanager.png",
                 "PluginManagerPage", None, None],
                "printerPage":
                [self.tr("Printer"), "preferences-printer.png",
                 "PrinterPage", None, None],
                "pythonPage":
                [self.tr("Python"), "preferences-python.png",
                 "PythonPage", None, None],
                "qtPage":
                [self.tr("Qt"), "preferences-qtlogo.png",
                 "QtPage", None, None],
                "securityPage":
                [self.tr("Security"), "preferences-security.png",
                 "SecurityPage", None, None],
                "shellPage":
                [self.tr("Shell"), "preferences-shell.png",
                 "ShellPage", None, None],
                "tasksPage":
                [self.tr("Tasks"), "task.png",
                 "TasksPage", None, None],
                "templatesPage":
                [self.tr("Templates"), "preferences-template.png",
                 "TemplatesPage", None, None],
                "trayStarterPage":
                [self.tr("Tray Starter"), "erict.png",
                 "TrayStarterPage", None, None],
                "vcsPage":
                [self.tr("Version Control Systems"),
                 "preferences-vcs.png",
                 "VcsPage", None, None],
                
                "0debuggerPage":
                [self.tr("Debugger"), "preferences-debugger.png",
                 None, None, None],
                "debuggerGeneralPage":
                [self.tr("General"), "preferences-debugger.png",
                 "DebuggerGeneralPage", "0debuggerPage", None],
                "debuggerPythonPage":
                [self.tr("Python"), "preferences-pyDebugger.png",
                 "DebuggerPythonPage", "0debuggerPage", None],
                "debuggerPython3Page":
                [self.tr("Python3"), "preferences-pyDebugger.png",
                 "DebuggerPython3Page", "0debuggerPage", None],
                
                "0editorPage":
                [self.tr("Editor"), "preferences-editor.png",
                 None, None, None],
                "editorAPIsPage":
                [self.tr("APIs"), "preferences-api.png",
                 "EditorAPIsPage", "0editorPage", None],
                "editorAutocompletionPage":
                [self.tr("Autocompletion"),
                 "preferences-autocompletion.png",
                 "EditorAutocompletionPage", "0editorPage", None],
                "editorAutocompletionQScintillaPage":
                [self.tr("QScintilla"), "qscintilla.png",
                 "EditorAutocompletionQScintillaPage",
                 "editorAutocompletionPage", None],
                "editorCalltipsPage":
                [self.tr("Calltips"), "preferences-calltips.png",
                 "EditorCalltipsPage", "0editorPage", None],
                "editorCalltipsQScintillaPage":
                [self.tr("QScintilla"), "qscintilla.png",
                 "EditorCalltipsQScintillaPage", "editorCalltipsPage", None],
                "editorGeneralPage":
                [self.tr("General"), "preferences-general.png",
                 "EditorGeneralPage", "0editorPage", None],
                "editorFilePage":
                [self.tr("Filehandling"),
                 "preferences-filehandling.png",
                 "EditorFilePage", "0editorPage", None],
                "editorSearchPage":
                [self.tr("Searching"), "preferences-search.png",
                 "EditorSearchPage", "0editorPage", None],
                "editorSpellCheckingPage":
                [self.tr("Spell checking"),
                 "preferences-spellchecking.png",
                 "EditorSpellCheckingPage", "0editorPage", None],
                "editorStylesPage":
                [self.tr("Style"), "preferences-styles.png",
                 "EditorStylesPage", "0editorPage", None],
                "editorSyntaxPage":
                [self.tr("Code Checkers"), "preferences-debugger.png",
                 "EditorSyntaxPage", "0editorPage", None],
                "editorTypingPage":
                [self.tr("Typing"), "preferences-typing.png",
                 "EditorTypingPage", "0editorPage", None],
                "editorExportersPage":
                [self.tr("Exporters"), "preferences-exporters.png",
                 "EditorExportersPage", "0editorPage", None],
                
                "1editorLexerPage":
                [self.tr("Highlighters"),
                 "preferences-highlighting-styles.png",
                 None, "0editorPage", None],
                "editorHighlightersPage":
                [self.tr("Filetype Associations"),
                 "preferences-highlighter-association.png",
                 "EditorHighlightersPage", "1editorLexerPage", None],
                "editorHighlightingStylesPage":
                [self.tr("Styles"),
                 "preferences-highlighting-styles.png",
                 "EditorHighlightingStylesPage", "1editorLexerPage", None],
                "editorKeywordsPage":
                [self.tr("Keywords"), "preferences-keywords.png",
                 "EditorKeywordsPage", "1editorLexerPage", None],
                "editorPropertiesPage":
                [self.tr("Properties"), "preferences-properties.png",
                 "EditorPropertiesPage", "1editorLexerPage", None],
                
                "1editorMouseClickHandlers":
                [self.tr("Mouse Click Handlers"),
                 "preferences-mouse-click-handler.png",
                 "EditorMouseClickHandlerPage", "0editorPage", None],
                
                "0helpPage":
                [self.tr("Help"), "preferences-help.png",
                 None, None, None],
                "helpDocumentationPage":
                [self.tr("Help Documentation"),
                 "preferences-helpdocumentation.png",
                 "HelpDocumentationPage", "0helpPage", None],
                "helpViewersPage":
                [self.tr("Help Viewers"),
                 "preferences-helpviewers.png",
                 "HelpViewersPage", "0helpPage", None],
                
                "0projectPage":
                [self.tr("Project"), "preferences-project.png",
                 None, None, None],
                "projectBrowserPage":
                [self.tr("Project Viewer"), "preferences-project.png",
                 "ProjectBrowserPage", "0projectPage", None],
                "projectPage":
                [self.tr("Project"), "preferences-project.png",
                 "ProjectPage", "0projectPage", None],
                "multiProjectPage":
                [self.tr("Multiproject"),
                 "preferences-multiproject.png",
                 "MultiProjectPage", "0projectPage", None],
                
                "0interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 None, None, None],
                "interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 "InterfacePage", "0interfacePage", None],
                "viewmanagerPage":
                [self.tr("Viewmanager"), "preferences-viewmanager.png",
                 "ViewmanagerPage", "0interfacePage", None],
            }
            try:
                from PyQt5 import QtWebKit      # __IGNORE_WARNING__
                self.configItems.update({
                    "helpAppearancePage":
                    [self.tr("Appearance"), "preferences-styles.png",
                     "HelpAppearancePage", "0helpPage", None],
                    "helpFlashCookieManagerPage":
                    [self.tr("Flash Cookie Manager"),
                     "flashCookie16.png",
                     "HelpFlashCookieManagerPage", "0helpPage", None],
                    "helpVirusTotalPage":
                    [self.tr("VirusTotal Interface"), "virustotal.png",
                     "HelpVirusTotalPage", "0helpPage", None],
                    "helpWebBrowserPage":
                    [self.tr("eric6 Web Browser"), "ericWeb.png",
                     "HelpWebBrowserPage", "0helpPage", None],
                })
            except ImportError:
                pass
            
            self.configItems.update(
                e5App().getObject("PluginManager").getPluginConfigData())
        
        elif displayMode == ConfigurationWidget.HelpBrowserMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 "HelpInterfacePage", None, None],
                "networkPage":
                [self.tr("Network"), "preferences-network.png",
                 "NetworkPage", None, None],
                "printerPage":
                [self.tr("Printer"), "preferences-printer.png",
                 "PrinterPage", None, None],
                "securityPage":
                [self.tr("Security"), "preferences-security.png",
                 "SecurityPage", None, None],
                
                "0helpPage":
                [self.tr("Help"), "preferences-help.png",
                 None, None, None],
                "helpDocumentationPage":
                [self.tr("Help Documentation"),
                 "preferences-helpdocumentation.png",
                 "HelpDocumentationPage", "0helpPage", None],
            }
            try:
                from PyQt5 import QtWebKit      # __IGNORE_WARNING__
                self.configItems.update({
                    "helpAppearancePage":
                    [self.tr("Appearance"), "preferences-styles.png",
                     "HelpAppearancePage", "0helpPage", None],
                    "helpFlashCookieManagerPage":
                    [self.tr("Flash Cookie Manager"),
                     "flashCookie16.png",
                     "HelpFlashCookieManagerPage", "0helpPage", None],
                    "helpVirusTotalPage":
                    [self.tr("VirusTotal Interface"), "virustotal.png",
                     "HelpVirusTotalPage", "0helpPage", None],
                    "helpWebBrowserPage":
                    [self.tr("eric6 Web Browser"), "ericWeb.png",
                     "HelpWebBrowserPage", "0helpPage", None],
                })
            except ImportError:
                pass
        
        elif displayMode == ConfigurationWidget.TrayStarterMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "trayStarterPage":
                [self.tr("Tray Starter"), "erict.png",
                 "TrayStarterPage", None, None],
            }
        
        elif displayMode == ConfigurationWidget.HexEditorMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "hexEditorPage":
                [self.tr("Hex Editor"), "hexEditor.png",
                 "HexEditorPage", None, None],
            }
        
        else:
            raise RuntimeError("Illegal mode value: {0}".format(displayMode))
        
        # generate the list entries
        self.__expandedEntries = []
        for key in sorted(self.configItems.keys()):
            pageData = self.configItems[key]
            if pageData[3]:
                if pageData[3] in self.itmDict:
                    pitm = self.itmDict[pageData[3]]  # get the parent item
                else:
                    continue
            else:
                pitm = self.configList
            self.itmDict[key] = ConfigurationPageItem(pitm, pageData[0], key,
                                                      pageData[1])
            self.itmDict[key].setData(0, Qt.UserRole, key)
            if (not self.fromEric or
                displayMode != ConfigurationWidget.DefaultMode or
                    key in expandedEntries):
                self.itmDict[key].setExpanded(True)
        self.configList.sortByColumn(0, Qt.AscendingOrder)
        
        # set the initial size of the splitter
        self.configSplitter.setSizes([200, 600])
        
        self.configList.itemActivated.connect(self.__showConfigurationPage)
        self.configList.itemClicked.connect(self.__showConfigurationPage)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.rejected)
        
        if displayMode in [ConfigurationWidget.HelpBrowserMode,
                           ConfigurationWidget.TrayStarterMode,
                           ConfigurationWidget.HexEditorMode]:
            self.configListSearch.hide()
        
        if displayMode not in [ConfigurationWidget.TrayStarterMode,
                               ConfigurationWidget.HexEditorMode]:
            self.__initLexers()
        
    def accept(self):
        """
        Public slot to accept the buttonBox accept signal.
        """
        if not isMacPlatform():
            wdg = self.focusWidget()
            if wdg == self.configList:
                return
        
        self.accepted.emit()
        
    def __setupUi(self):
        """
        Private method to perform the general setup of the configuration
        widget.
        """
        self.setObjectName("ConfigurationDialog")
        self.resize(900, 650)
        self.verticalLayout_2 = QVBoxLayout(self)
        self.verticalLayout_2.setSpacing(6)
        self.verticalLayout_2.setContentsMargins(6, 6, 6, 6)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        
        self.configSplitter = QSplitter(self)
        self.configSplitter.setOrientation(Qt.Horizontal)
        self.configSplitter.setObjectName("configSplitter")
        
        self.configListWidget = QWidget(self.configSplitter)
        self.leftVBoxLayout = QVBoxLayout(self.configListWidget)
        self.leftVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.leftVBoxLayout.setSpacing(0)
        self.leftVBoxLayout.setObjectName("leftVBoxLayout")
        self.configListSearch = E5ClearableLineEdit(
            self, self.tr("Enter search text..."))
        self.configListSearch.setObjectName("configListSearch")
        self.leftVBoxLayout.addWidget(self.configListSearch)
        self.configList = QTreeWidget()
        self.configList.setObjectName("configList")
        self.leftVBoxLayout.addWidget(self.configList)
        self.configListSearch.textChanged.connect(self.__searchTextChanged)
        
        self.scrollArea = QScrollArea(self.configSplitter)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setObjectName("scrollArea")
        
        self.configStack = QStackedWidget()
        self.configStack.setFrameShape(QFrame.Box)
        self.configStack.setFrameShadow(QFrame.Sunken)
        self.configStack.setObjectName("configStack")
        self.scrollArea.setWidget(self.configStack)
        
        self.emptyPage = QWidget()
        self.emptyPage.setGeometry(QRect(0, 0, 372, 591))
        self.emptyPage.setObjectName("emptyPage")
        self.vboxlayout = QVBoxLayout(self.emptyPage)
        self.vboxlayout.setSpacing(6)
        self.vboxlayout.setContentsMargins(6, 6, 6, 6)
        self.vboxlayout.setObjectName("vboxlayout")
        spacerItem = QSpacerItem(
            20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem)
        self.emptyPagePixmap = QLabel(self.emptyPage)
        self.emptyPagePixmap.setAlignment(Qt.AlignCenter)
        self.emptyPagePixmap.setObjectName("emptyPagePixmap")
        self.emptyPagePixmap.setPixmap(
            QPixmap(os.path.join(getConfig('ericPixDir'), 'eric.png')))
        self.vboxlayout.addWidget(self.emptyPagePixmap)
        self.textLabel1 = QLabel(self.emptyPage)
        self.textLabel1.setAlignment(Qt.AlignCenter)
        self.textLabel1.setObjectName("textLabel1")
        self.vboxlayout.addWidget(self.textLabel1)
        spacerItem1 = QSpacerItem(
            20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem1)
        self.configStack.addWidget(self.emptyPage)
        
        self.verticalLayout_2.addWidget(self.configSplitter)
        
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Apply | QDialogButtonBox.Cancel |
            QDialogButtonBox.Ok | QDialogButtonBox.Reset)
        self.buttonBox.setObjectName("buttonBox")
        if not self.fromEric and \
                self.displayMode == ConfigurationWidget.DefaultMode:
            self.buttonBox.button(QDialogButtonBox.Apply).hide()
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        self.verticalLayout_2.addWidget(self.buttonBox)

        self.setWindowTitle(self.tr("Preferences"))
        
        self.configList.header().hide()
        self.configList.header().setSortIndicator(0, Qt.AscendingOrder)
        self.configList.setSortingEnabled(True)
        self.textLabel1.setText(
            self.tr("Please select an entry of the list \n"
                    "to display the configuration page."))
        
        QMetaObject.connectSlotsByName(self)
        self.setTabOrder(self.configList, self.configStack)
        
        self.configStack.setCurrentWidget(self.emptyPage)
        
        self.configList.setFocus()
    
    def __searchTextChanged(self, text):
        """
        Private slot to handle a change of the search text.
        
        @param text text to search for (string)
        """
        self.__searchChildItems(self.configList.invisibleRootItem(), text)
    
    def __searchChildItems(self, parent, text):
        """
        Private method to enable child items based on a search string.
        
        @param parent reference to the parent item (QTreeWidgetItem)
        @param text text to search for (string)
        @return flag indicating an enabled child item (boolean)
        """
        childEnabled = False
        text = text.lower()
        for index in range(parent.childCount()):
            itm = parent.child(index)
            if itm.childCount() > 0:
                enable = self.__searchChildItems(itm, text) or \
                    text == "" or text in itm.text(0).lower()
            else:
                enable = text == "" or text in itm.text(0).lower()
            if enable:
                childEnabled = True
            itm.setDisabled(not enable)
        
        return childEnabled
    
    def __initLexers(self):
        """
        Private method to initialize the dictionary of preferences lexers.
        """
        import QScintilla.Lexers
        from .PreferencesLexer import PreferencesLexer, \
            PreferencesLexerLanguageError
        
        self.lexers = {}
        for language in QScintilla.Lexers.getSupportedLanguages():
            if language not in self.lexers:
                try:
                    self.lexers[language] = PreferencesLexer(language, self)
                except PreferencesLexerLanguageError:
                    pass
        
    def __importConfigurationPage(self, name):
        """
        Private method to import a configuration page module.
        
        @param name name of the configuration page module (string)
        @return reference to the configuration page module
        """
        modName = "Preferences.ConfigurationPages.{0}".format(name)
        try:
            mod = __import__(modName)
            components = modName.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod
        except ImportError:
            E5MessageBox.critical(
                self,
                self.tr("Configuration Page Error"),
                self.tr("""<p>The configuration page <b>{0}</b>"""
                        """ could not be loaded.</p>""").format(name))
            return None
        
    def __showConfigurationPage(self, itm, column):
        """
        Private slot to show a selected configuration page.
        
        @param itm reference to the selected item (QTreeWidgetItem)
        @param column column that was selected (integer) (ignored)
        """
        pageName = itm.getPageName()
        self.showConfigurationPageByName(pageName, setCurrent=False)
        
    def __initPage(self, pageData):
        """
        Private method to initialize a configuration page.
        
        @param pageData data structure for the page to initialize
        @return reference to the initialized page
        """
        page = None
        if isinstance(pageData[2], types.FunctionType):
            page = pageData[2](self)
        else:
            mod = self.__importConfigurationPage(pageData[2])
            if mod:
                page = mod.create(self)
        if page is not None:
            self.configStack.addWidget(page)
            pageData[-1] = page
            try:
                page.setMode(self.displayMode)
            except AttributeError:
                pass
        return page
        
    def showConfigurationPageByName(self, pageName, setCurrent=True):
        """
        Public slot to show a named configuration page.
        
        @param pageName name of the configuration page to show (string)
        @param setCurrent flag indicating to set the current item (boolean)
        """
        if pageName == "empty" or pageName not in self.configItems:
            page = self.emptyPage
        else:
            pageData = self.configItems[pageName]
            if pageData[-1] is None and pageData[2] is not None:
                # the page was not loaded yet, create it
                page = self.__initPage(pageData)
            else:
                page = pageData[-1]
            if page is None:
                page = self.emptyPage
            elif setCurrent:
                items = self.configList.findItems(
                    pageData[0],
                    Qt.MatchFixedString | Qt.MatchRecursive)
                for item in items:
                    if item.data(0, Qt.UserRole) == pageName:
                        self.configList.setCurrentItem(item)
        self.configStack.setCurrentWidget(page)
        ssize = self.scrollArea.size()
        if self.scrollArea.horizontalScrollBar():
            ssize.setHeight(
                ssize.height() -
                self.scrollArea.horizontalScrollBar().height() - 2)
        if self.scrollArea.verticalScrollBar():
            ssize.setWidth(
                ssize.width() -
                self.scrollArea.verticalScrollBar().width() - 2)
        psize = page.minimumSizeHint()
        self.configStack.resize(max(ssize.width(), psize.width()),
                                max(ssize.height(), psize.height()))
        
        if page != self.emptyPage:
            page.polishPage()
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(True)
        else:
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        
        # reset scrollbars
        for sb in [self.scrollArea.horizontalScrollBar(),
                   self.scrollArea.verticalScrollBar()]:
            if sb:
                sb.setValue(0)
        
        self.__currentConfigurationPageName = pageName
        
    def getConfigurationPageName(self):
        """
        Public method to get the page name of the current page.
        
        @return page name of the current page (string)
        """
        return self.__currentConfigurationPageName
        
    def calledFromEric(self):
        """
        Public method to check, if invoked from within eric.
        
        @return flag indicating invocation from within eric (boolean)
        """
        return self.fromEric
        
    def getPage(self, pageName):
        """
        Public method to get a reference to the named page.
        
        @param pageName name of the configuration page (string)
        @return reference to the page or None, indicating page was
            not loaded yet
        """
        return self.configItems[pageName][-1]
        
    def getLexers(self):
        """
        Public method to get a reference to the lexers dictionary.
        
        @return reference to the lexers dictionary
        """
        return self.lexers
        
    def setPreferences(self):
        """
        Public method called to store the selected values into the preferences
        storage.
        """
        for key, pageData in list(self.configItems.items()):
            if pageData[-1]:
                pageData[-1].save()
                # page was loaded (and possibly modified)
                QApplication.processEvents()    # ensure HMI is responsive
        
    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.buttonBox.button(QDialogButtonBox.Apply):
            self.on_applyButton_clicked()
        elif button == self.buttonBox.button(QDialogButtonBox.Reset):
            self.on_resetButton_clicked()
        
    @pyqtSlot()
    def on_applyButton_clicked(self):
        """
        Private slot called to apply the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            page = self.configStack.currentWidget()
            savedState = page.saveState()
            page.save()
            self.preferencesChanged.emit()
            if savedState is not None:
                page.setState(savedState)
            page.polishPage()
        
    @pyqtSlot()
    def on_resetButton_clicked(self):
        """
        Private slot called to reset the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            currentPage = self.configStack.currentWidget()
            savedState = currentPage.saveState()
            pageName = self.configList.currentItem().getPageName()
            self.configStack.removeWidget(currentPage)
            if pageName == "editorHighlightingStylesPage":
                self.__initLexers()
            self.configItems[pageName][-1] = None
            
            self.showConfigurationPageByName(pageName)
            if savedState is not None:
                self.configStack.currentWidget().setState(savedState)
        
    def getExpandedEntries(self):
        """
        Public method to get a list of expanded entries.
        
        @return list of expanded entries (list of string)
        """
        return self.__expandedEntries
    
    @pyqtSlot(QTreeWidgetItem)
    def on_configList_itemCollapsed(self, item):
        """
        Private slot handling a list entry being collapsed.
        
        @param item reference to the collapsed item (QTreeWidgetItem)
        """
        pageName = item.data(0, Qt.UserRole)
        if pageName in self.__expandedEntries:
            self.__expandedEntries.remove(pageName)
    
    @pyqtSlot(QTreeWidgetItem)
    def on_configList_itemExpanded(self, item):
        """
        Private slot handling a list entry being expanded.
        
        @param item reference to the expanded item (QTreeWidgetItem)
        """
        pageName = item.data(0, Qt.UserRole)
        if pageName not in self.__expandedEntries:
            self.__expandedEntries.append(pageName)