Beispiel #1
0
class ImportParametersPage(QWizardPage):
    def __init__(self, parent=None):
        super(ImportParametersPage, self).__init__(parent)

        self.setTitle(self.tr("Parametry importu"))

        self.dirLabel = QLabel(QApplication.translate("ImportParametersPage", 'Adresář s daty RÚIAN', None, QApplication.UnicodeUTF8))
        self.setDir = QLineEdit(config['importParameters']['dataRUIANDir'])
        self.dirLabel.setBuddy(self.setDir)
        self.setDir.textChanged[str].connect(self.updateDir)

        self.suffixLabel = QLabel(QApplication.translate("CreateDBStructurePage", 'Přípona souboru', None, QApplication.UnicodeUTF8))
        self.suffix = QLineEdit(config['importParameters']['suffix'])
        self.suffixLabel.setBuddy(self.suffix)
        self.suffix.textChanged[str].connect(self.updateSuffix)

        self.openButton1 = QPushButton()
        self.curDir = os.path.dirname(__file__)
        self.pictureName = os.path.join(self.curDir, 'img\\dir.png')
        self.openButton1.setIcon(QIcon(self.pictureName))

        self.walkDir = QCheckBox(QApplication.translate("ImportParametersPage", 'Včetně podadresářů', None, QApplication.UnicodeUTF8))

        if config['importParameters']['subDirs'] == 'True':
            self.walkDir.setCheckState(Qt.Checked)
        else:
            self.walkDir.setCheckState(Qt.Unchecked)

        self.walkDir.stateChanged[int].connect(self.updateSubDirs)

        grid = QGridLayout()
        grid.addWidget(self.dirLabel, 0, 0)
        grid.addWidget(self.setDir, 0, 1)
        grid.addWidget(self.openButton1, 0, 2)
        grid.addWidget(self.suffixLabel, 1, 0)
        grid.addWidget(self.suffix, 1, 1)
        grid.addWidget(self.walkDir, 2, 1)

        self.setLayout(grid)
        self.connect(self.openButton1, SIGNAL("clicked()"), self.setPath1)

    def updateDir(self, value):
        config['importParameters']['dataRUIANDir'] = str(value)

    def updateSuffix(self, value):
        config['importParameters']['suffix'] = str(value)

    def updateSubDirs(self, value):
        if value == 2:
            config['importParameters']['subDirs'] = 'True'
        else:
            config['importParameters']['subDirs'] = 'False'

    def setPath1(self):
        dirDialog = QFileDialog.getExistingDirectory(self, QApplication.translate("CreateDBStructurePage", 'Výběr adrešáře', None, QApplication.UnicodeUTF8))
        if not dirDialog.isNull():
            self.setDir.setText(dirDialog)

    def nextId(self):
        return LicenseWizard.PageImportDB
Beispiel #2
0
 def __init__(self, parent = None):
 
     QWidget.__init__(self, parent)
     
     self.table = QTableView()
     self.imageTable = QTableView()
     delegate = PixelDelegate(self)
     self.imageTable.setItemDelegate(delegate)
     self.imageTable.horizontalHeader().hide()
     self.imageTable.verticalHeader().hide()
     self.imageTable.setShowGrid(False)
     
     self.imageCombo = QComboBox()
     self.imageCombo.addItem("Dream", QVariant(":/Pictures/dream.png"))
     self.imageCombo.addItem("Teapot", QVariant(":/Pictures/teapot.png"))
     
     gridCheckBox = QCheckBox(self.tr("Show grid:"))
     gridCheckBox.setCheckState(Qt.Unchecked)
     
     self.connect(self.imageCombo, SIGNAL("currentIndexChanged(int)"),
                  self.setModel)
     self.connect(gridCheckBox, SIGNAL("toggled(bool)"),
                  self.imageTable, SLOT("setShowGrid(bool)"))
     
     self.imageCombo.setCurrentIndex(1)
     
     layout = QGridLayout()
     layout.addWidget(self.imageTable, 0, 0, 1, 2)
     layout.addWidget(self.table, 0, 2, 1, 2)
     layout.addWidget(gridCheckBox, 1, 0)
     layout.addWidget(self.imageCombo, 1, 1)
     self.setLayout(layout)
Beispiel #3
0
    def availableColumns(self):
        """ Lists available numeric columns in the side panel """
        comboBoxOptions = ['Suma', u'Średnia']
        self.dlg.tableWidget_2.setRowCount(len(self.numFields))
        self.dlg.tableWidget_2.setColumnCount(3)

        ## Fill the table
        if len(self.numFields) == 0:
            self.dlg.tableWidget_2.setRowCount(0)
        for i in range(len(self.numFields)):
            checkBoxItem = QCheckBox()
            checkBoxItem.setCheckState(Qt.Unchecked)
            self.dlg.tableWidget_2.setCellWidget(i, 0, checkBoxItem)

            textItem = QLabel()
            textItem.setText(self.numFields.values()[i])
            self.dlg.tableWidget_2.setCellWidget(i, 1, textItem)

            comboBoxField = QComboBox()
            for j in comboBoxOptions:
                comboBoxField.addItem(j)
            self.dlg.tableWidget_2.setCellWidget(i, 2, comboBoxField)

        self.dlg.tableWidget_2.setColumnWidth(0, 25)
        self.dlg.tableWidget_2.verticalHeader().setVisible(False)
        self.dlg.tableWidget_2.horizontalHeader().setVisible(False)
Beispiel #4
0
class BoolConfigControl(ConfigControl):
    def __init__(self, config_item):
        ConfigControl.__init__(self, config_item)

        self._init_ui()
        self.update_from_config()

    def _init_ui(self):
        lbl_bool = QLabel(self._config_item.tag())
        lbl_bool.setFixedWidth(self.LABEL_WIDTH)

        self._chk_box = QCheckBox()
        self._chk_box.setTristate(False)

        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.addWidget(lbl_bool)
        hbox.addWidget(self._chk_box)
        hbox.addStretch()

        self.setLayout(hbox)

    def update_from_config(self):
        state = 2 if self._config_item.value() == True else 0
        self._chk_box.setCheckState(state)

    def save_to_config(self):
        value = True if self._chk_box.checkState() == 2 else False
        self._config_item.set(value)
class BoolConfigControl(ConfigControl):
    def __init__(self, config_item):
        ConfigControl.__init__(self, config_item)

        self._init_ui()
        self.update_from_config()

    def _init_ui(self):
        lbl_bool = QLabel(self._config_item.tag())
        lbl_bool.setFixedWidth(self.LABEL_WIDTH)

        self._chk_box = QCheckBox()
        self._chk_box.setTristate(False)

        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.addWidget(lbl_bool)
        hbox.addWidget(self._chk_box)
        hbox.addStretch()

        self.setLayout(hbox)

    def update_from_config(self):
        state = 2 if self._config_item.value() == True else 0
        self._chk_box.setCheckState(state)

    def save_to_config(self):
        value = True if self._chk_box.checkState() == 2 else False
        self._config_item.set(value)
Beispiel #6
0
 def _item_for_data(self, row, column, data, context=None):
     if column == 0:
         # create check box as our editor.
         editor = QCheckBox()
         if data == 2:
             editor.setCheckState(2)
         self.connect(
             editor, SIGNAL('stateChanged(int)'), self.parent.enablebtt)
         return editor
     return super(TrashTableWidget, self)._item_for_data(row, column,
                                                         data, context)
Beispiel #7
0
 def _item_for_data(self, row, column, data, context=None):
     if column == 0:
         # create check box as our editor.
         editor = QCheckBox()
         # editor.itemClicked.connect(self.save_order)
         if data == 2:
             editor.setCheckState(2)
         self.connect(editor, SIGNAL('stateChanged(int)'), self.save_order)
         return editor
     if column == 1:
         line_edit = IntLineEdit(u"%s" % data)
         line_edit.textChanged.connect(self.save_order)
         return line_edit
     return super(OrederTableWidget, self)._item_for_data(row, column,
                                                          data, context)
Beispiel #8
0
class DockWidgetRasterLegendSensitive(QDockWidget):
    def __init__(self, iface):
        def setupUi():
            self.setObjectName("rasterlegendasensitive_dockwidget")
            wgt = QWidget(self)
            wgt.setAttribute(Qt.WA_DeleteOnClose)
            #
            gridLayout = QGridLayout(wgt)
            gridLayout.setContentsMargins(0, 0, gridLayout.verticalSpacing(),
                                          gridLayout.verticalSpacing())
            #
            (iniY, iniX, spanY, spanX) = (0, 0, 1, 1)
            self.ckEnabled = QCheckBox("Enabled", wgt)
            gridLayout.addWidget(self.ckEnabled, iniY, iniX, spanY, spanX)
            #
            self.tree = QTreeView(wgt)
            iniY += 1
            spanX = 2
            gridLayout.addWidget(self.tree, iniY, iniX, spanY, spanX)
            #
            wgt.setLayout(gridLayout)
            self.setWidget(wgt)

        super(DockWidgetRasterLegendSensitive,
              self).__init__("Raster Legend Sensitive", iface.mainWindow())
        #
        self.tree = self.ckEnabled = None
        setupUi()
        self.rls = RasterLegendSensitive(iface, self.tree, self.ckEnabled)
        #
        self.ckEnabled.stateChanged.connect(self.enabled)
        self.rlsEnabled = True
        self.ckEnabled.setCheckState(Qt.Unchecked)
        self.enabled(Qt.Unchecked)

    def __del__(self):
        del self.rls

    @pyqtSlot(int)
    def enabled(self, state):
        enabled = True if state == Qt.Checked else False
        if not self.rlsEnabled == enabled:
            self.rls.setEnabled(enabled)
            self.rlsEnabled = enabled

    def visibility(self, visible):
        if not visible:
            self.ckEnabled.setCheckState(Qt.Unchecked)
Beispiel #9
0
    def _item_for_data(self, row, column, data, context=None):
        if column == 0:
            # create check box as our editor.
            editor = QCheckBox()
            # editor.itemClicked.connect(self.save_order)
            if data == 2:
                editor.setCheckState(2)

            self.connect(editor, SIGNAL('stateChanged(int)'), self.save_order)
            return editor
        if column == 1:
            line_edit = IntLineEdit(u"%s" % data)
            line_edit.textChanged.connect(self.save_order)
            return line_edit
        return super(OrederTableWidget,
                     self)._item_for_data(row, column, data, context)
    def put_checkbox(self, qtable, rows, checker, value):
        """ Set one column of a QtableView as QCheckBox with values from database. """

        for x in range(0, len(rows)):
            row = rows[x]
            cell_widget = QWidget()
            chk = QCheckBox()
            if row[checker] == value:
                chk.setCheckState(Qt.Checked)
            lay_out = QHBoxLayout(cell_widget)
            lay_out.addWidget(chk)
            lay_out.setAlignment(Qt.AlignCenter)
            lay_out.setContentsMargins(0, 0, 0, 0)
            cell_widget.setLayout(lay_out)
            i = qtable.model().index(x, self.chk_position)
            qtable.setIndexWidget(i, cell_widget)
Beispiel #11
0
 def add_checkbox(self, layout, propriete, titre):
     objets = [objet for objet in self.objets if objet.style(propriete) is not None]
     if objets:
         cb = QCheckBox(titre)
         cb.setTristate(True)
         layout.addWidget(cb)
         verifies = [objet.style(propriete) is True for objet in objets]
         if not any(verifies):
             etat = Qt.Unchecked
         elif all(verifies):
             etat = Qt.Checked
         else:
             etat = Qt.PartiallyChecked
         cb.setCheckState(etat)
         cb.stateChanged.connect(partial(self.checked, propriete))
         cb.stateChanged.connect(partial(cb.setTristate, False))
Beispiel #12
0
class EdwCheckBoxCell(QFrame, Cell):
    def __init__(self, initial_state, callback):
        QFrame.__init__(self)
        Cell.__init__(self)
        layout = QVBoxLayout()
        self.checkbox = QCheckBox(self)
        self.setContentsMargins(0, 0, 0, 0)
        self.setAutoFillBackground(True)
        self.callback = None

        layout.addWidget(self.checkbox)
        self.setLayout(layout)

        self.state = False
        self.connect(self.checkbox, SIGNAL("clicked(bool)"), self.setState)

        self.setState(initial_state)
        self.callback = callback

    def setState(self, state):
        self.state = state
        if self.callback:
            self.callback(state)

    def getState(self):
        return self.state

    def refresh(self):
        if self.state:
            self.checkbox.setCheckState(Qt.Checked)
        else:
            self.checkbox.setCheckState(Qt.Unchecked)

    def setPalette(self, palette):
        QFrame.setPalette(self, palette)
        palette = QPalette(palette)
        palette.setColor(QPalette.Window, palette.color(QPalette.Base))
        palette.setColor(QPalette.Background, palette.color(QPalette.Base))
        palette.setColor(QPalette.Foreground, palette.color(QPalette.Base))
        palette.setColor(QPalette.AlternateBase, palette.color(QPalette.Base))
        palette.setColor(QPalette.Button, palette.color(QPalette.Base))
        self.checkbox.setPalette(palette)
        return

    def sizeHint(self):
        return QFrame.sizeHint(self) * 1.1
    def create_checkboxes(self):
        """
            Creates the checkboxes used to determine what columns are to be
            displayed or what options should be set to the model (i.e. should
            we display the weekday, etc.)
        """
        # Hiding every columns (even those not listed in AVAILABLE_CHOICES)
        for column, field in enumerate(self._model.get_columns()):
            self.gui.tableView.hideColumn(column)

        count = 0
        for checkbox_name in AVAILABLE_CHOICES:
            checkbox = QCheckBox(self.gui.centralwidget)
            self.gui.checkboxLayout.addWidget(checkbox, 0, count, 1, 1)
            self._checkboxes[checkbox_name] = checkbox
            checkbox.setText(QApplication.translate("MainWindow",
                                                    NAMES[checkbox_name], None,
                                                    QApplication.UnicodeUTF8))
            if checkbox_name in PRE_CHOICE:
                checkbox.setCheckState(Qt.Checked)
            self._parent.connect(checkbox, SIGNAL("stateChanged(int)"),
                                self.refresh_checkboxes)
            count += 1

        for checkbox_name in AVAILABLE_OPTIONS:
            checkbox = QCheckBox(self.gui.centralwidget)
            self.gui.checkboxLayout.addWidget(checkbox, 0, count, 1, 1)
            self._checkboxes[checkbox_name] = checkbox
            checkbox.setText(QApplication.translate("MainWindow",
                                        AVAILABLE_OPTIONS[checkbox_name], None,
                                        QApplication.UnicodeUTF8))
            if checkbox_name in PRE_CHOICE:
                checkbox.setCheckState(Qt.Checked)
            self._parent.connect(checkbox, SIGNAL("stateChanged(int)"),
                         self.refresh_display_options)
            count += 1

        spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gui.checkboxLayout.addItem(spacer_item, 0, count, 1, 1)
        self.refresh_checkboxes(resize=False)
        self.refresh_display_options(resize=False)
Beispiel #14
0
    def initializePage(self):
        super(FrameworkLibraryPage, self).initializePage()
        exsits = []
        for moudel in app.g_configurations.modules:
            exsits.append(moudel['name'])

        self.checkboxs = []
        index = 0
        ret_json = app.render(app.g_configurations.config_content,
                              config=app.g_configurations)
        app.g_configurations.config = json.loads(ret_json)
        for moudel in app.g_configurations.config['moudels']:
            checkBox = QCheckBox(moudel['name'])
            checkBox.setToolTip(moudel['description'])
            if moudel['buildin']:
                checkBox.setCheckState(Qt.Checked)
                checkBox.setEnabled(False)
            elif moudel['name'] in exsits:
                checkBox.setCheckState(Qt.Checked)
            else:
                checkBox.setCheckState(Qt.Unchecked)
            row = index / 3
            offset = index % 3
            self.gLayout.addWidget(checkBox, row, offset)
            self.checkboxs.append(checkBox)
            index += 1
    def create_model_interface(self, model):
        """
            This method sets up the interface for the model in the rebase tab.
        """
        position = self._number_of_models
        branch = model.get_current_branch() or model.get_remote_ref()

        checkbox = QCheckBox(self._ui.centralwidget)
        checkbox.setText(QApplication.translate("MainWindow",
                                            branch.name,
                                            None, QApplication.UnicodeUTF8))
        self._ui.branchCheckboxLayout.addWidget(checkbox, position / 2,
                                                       position%2, 1, 1)

        branch_view = BranchView(self, model, checkbox, self._models)
        self._ui.viewLayout.addWidget(branch_view, 0, self._number_of_models)

        signals = "activated(const QModelIndex&)", "clicked(const QModelIndex&)"
        for signal in signals:
            connect(branch_view, SIGNAL(signal), self.commit_clicked)

        connect(branch_view, SIGNAL("newBranchFromCommit"),
                self.fwd_new_branch_from_commit)
        connect(branch_view, SIGNAL("newHistAction"), self.fwd_new_hist_action)

        connect(branch_view, SIGNAL("newCopiedData"), self.set_copy_data)

        if hasattr(branch, 'path') and branch == self._parent.current_branch:
            checkbox.setCheckState(Qt.Checked)
            branch_view.show()
        else:
            branch_view.hide()

        connect(checkbox, SIGNAL("stateChanged(int)"), self.checkbox_clicked)

        self._checkboxes[checkbox] = (branch_view, model)
        self._number_of_models += 1
Beispiel #16
0
    def initializePage(self):
        exsits = []
        for qtlib in app.g_configurations.qt_libs:
            exsits.append(qtlib['name'])

        index = 0
        for moudel in app.g_qt_library:
            checkBox = QCheckBox(moudel['name'])
            if app.g_configurations.initialized:
                if moudel['name'] in exsits:
                    checkBox.setCheckState(Qt.Checked)
                else:
                    checkBox.setCheckState(Qt.Unchecked)
            else:
                if moudel['refer']:
                    checkBox.setCheckState(Qt.Checked)
                else:
                    checkBox.setCheckState(Qt.Unchecked)
            row = index / 3
            offset = index % 3
            self.gLayout.addWidget(checkBox, row, offset)
            self.checkboxs.append(checkBox)
            index += 1
Beispiel #17
0
    def initializePage(self):
        exsits = []
        for qtlib in app.g_configurations.qt_libs:
            exsits.append(qtlib['name'])

        index = 0
        for moudel in app.g_qt_library:
            checkBox = QCheckBox(moudel['name'])
            if app.g_configurations.initialized:
                if moudel['name'] in exsits:
                    checkBox.setCheckState(Qt.Checked)
                else:
                    checkBox.setCheckState(Qt.Unchecked)
            else:
                if moudel['refer']:
                    checkBox.setCheckState(Qt.Checked)
                else:
                    checkBox.setCheckState(Qt.Unchecked)
            row = index / 3
            offset = index % 3
            self.gLayout.addWidget(checkBox, row, offset)
            self.checkboxs.append(checkBox)
            index += 1
Beispiel #18
0
class Chat(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent);
        # -------------------------------------------------------------------
        self.PARENT                         = _PARENT;
        self.CONF                           = _PARENT.CONF;

        self.setGeometry(3, 5, 975, 548);
        self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_Chat.png'); }" );

        # -------------------------------------------------------------------
        self.CHAT_URL                       = "https://btc-e.com/";
        self.CHAT_DATA                      = [];
        self.CHAT_LANG                      = self.CONF["USER"]["CHAT_LANG"];

        self.CHAT_HEADERS = {
            "User-Agent"        : "Mozilla/5.0 (Win-32; rv:24.0) Gecko/20140723 Firefox/24.0 Iceweasel/24.7.0",
            "Accept"            : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language"   : "en-US,en;q=0.5",
            "Referer"           : "https://btc-e.com/",
            "Connection"        : "keep-alive",
            "Cache-Control"     : "max-age=0",
            "Cookie"            : ""
        }

        self.CHAT_TIMER                     = QTimer();
        #self.CHAT_BG_COLOR                  = "#555";
        self.CHAT_BG_COLOR                  = "#0F0";
        self.CHAT_ALLOW_UPD                 = False;
        # -------------------------------------------------------------------
        self.CHAT_WIDGET                    = QTextEdit( self );
        self.CHAT_WIDGET.setGeometry( 13, 116, 690, 388 );
        self.CHAT_WIDGET.setStyleSheet( "QTextEdit{ background-color: transparent; color: #fff; background-image: url(''); }" );
        self.CHAT_WIDGET.setReadOnly( True );

        self.LANG_COMBO                     = QComboBox( self);
        self.LANG_COMBO.setGeometry( 86, 20, 108, 44 ); 
        self.connect( self.LANG_COMBO, SIGNAL('currentIndexChanged(int)'), self.CHANGE_CHAT_LANG );
        self.LANG_COMBO.setEditable(False);
        

        self.NEW_MSG                    = QLineEdit("", self);
        self.NEW_MSG.setGeometry( 20, 510, 500, 30 );
        self.NEW_MSG.setStyleSheet(" QLineEdit{ border-style: none; background-color: #333; color: #fff; background-image: url(''); }");
        self.NEW_MSG.setPlaceholderText(" Enter message:");



        self.SEND                       = QPushButton(" Send", self); 
        self.SEND.setGeometry( 593, 510, 90, 30 );
        #self.SEND.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        #self.connect( self.SEND, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );

        # -------------------------------------------------------------------
        self.ALLOW_UPDATE_CHECKBOX        = QCheckBox("", self);
        self.ALLOW_UPDATE_CHECKBOX.setGeometry( 335, 83, 17, 17 );
        self.ALLOW_UPDATE_CHECKBOX.setCheckState(Qt.Unchecked);
        self.connect(self.ALLOW_UPDATE_CHECKBOX, SIGNAL('stateChanged(int)'), self.CHANGE_VALUES );


        self.UPDATE_NOW_BTN               = QPushButton("Update Now!", self);
        self.UPDATE_NOW_BTN.setGeometry( 360, 74, 94, 24 );
        self.connect( self.UPDATE_NOW_BTN, SIGNAL('clicked()'), self.UPDATE_NOW );

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:
            self.INIT_CHAT_COMBO();
            self.UPDATE();

        except Exception as _exception:

            print("-----------------------------------------------------");
            print("[INIT]"+str(_exception));
        # -------------------------------------------------------------------

    # =======================================================================
    def UPDATE_NOW(self):

        # -------------------------------------------------------------------
        self.CHAT_ALLOW_UPD = True;

        self.UPDATE();

        self.CHAT_ALLOW_UPD = False;
        # -------------------------------------------------------------------

    # =======================================================================
    def UPDATE(self):

        # -------------------------------------------------------------------
        #print("UPDATE:")
        # -------------------------------------------------------------------
        try:

            if self.CHAT_ALLOW_UPD:

                self.GET_DATA();
                self.CHAT_WIDGET.clear();

                for msg in self.CHAT_DATA:

                    # ---------------------------------------------------------------
                    """
                    print(msg["time"]);
                    print(msg["nick"]);
                    print(msg["msg"]);
                    """

                    # ---------------------------------------------------------------
                    item = '<p style="background-color: #555;">';                
                    item += "[<span style='color: #000;'>"+msg["time"].split(" ")[1]+"</span>] : ";

                    if msg["nick"] == "admin":
                        item += "[<span style='color: #f00; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>";
                    else:
                        item += "[<span style='color: #000; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>";

                    item += msg["msg"]+"<br/>";
                    item += "</p>";

                    self.CHAT_WIDGET.append(item);


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

            self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE );

        except Exception as e:
            
            print("CHAT[0:0]"+str(e))
            self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE );

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

    # =======================================================================
    def CHANGE_VALUES(self):

        # -------------------------------------------------------------------
        if self.ALLOW_UPDATE_CHECKBOX.isChecked():
            self.CHAT_ALLOW_UPD = True;

        else:
            self.CHAT_ALLOW_UPD = False;

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

    # =======================================================================
    def GET_DATA(self):
        
        # -------------------------------------------------------------------
        try:

            self.CHAT_HEADERS["Cookie"] = "chatRefresh=1; locale="+self.CHAT_LANG+";"

            req = urllib2.Request(self.CHAT_URL, headers=self.CHAT_HEADERS);
            resp = urllib2.urlopen(req).read();

            CHAT = BeautifulSoup( resp ).body.find('div', attrs={'id':'nChat'});

            self.CHAT_DATA = [];

            for data in CHAT:

                self.CHAT_DATA.append( { "msg_id": data["id"], "nick":data.a.string, "time": data.a["title"], "msg": data.span.string } );


        except Exception as e:
            
            print("CHAT[0:1]"+str(e))
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_CHAT_LANG(self):

        # -------------------------------------------------------------------
        self.CHAT_LANG = str(self.LANG_COMBO.currentText()).lower().strip();
        #print(self.CHAT_LANG);
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT_CHAT_COMBO(self):

        # -------------------------------------------------------------------
        for LANG in self.CONF["USER"]["CHAT_LANGS"]:
            self.LANG_COMBO.addItem(LANG.upper());

        for i in xrange(0, self.LANG_COMBO.__len__()):

            self.LANG_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole );
            self.LANG_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
class EditorConfiguration(QWidget):

    def __init__(self, main):
        QWidget.__init__(self)
        self._main = main
        grid = QGridLayout(self)

        #Indentation
        groupBoxFeatures = QGroupBox('Features:')
        grid.addWidget(groupBoxFeatures, 0, 0)
        grid.addWidget(QLabel('Indentation Length:'), 1, 0, Qt.AlignRight)
        self.spin = QSpinBox()
        self.spin.setValue(EditorGeneric.indent)
        grid.addWidget(self.spin, 1, 1)
        #Find Errors
        self.checkErrors = QCheckBox('Find and Show Errors')
        errorState = Qt.Checked if EditorGeneric.findErrors else Qt.Unchecked
        self.checkErrors.setCheckState(errorState)
        grid.addWidget(self.checkErrors, 2, 1)
        #Find Check Style
        self.checkStyle = QCheckBox('Find and Show Check Style errors.')
        styleState = Qt.Checked if EditorGeneric.checkStyle else Qt.Unchecked
        self.checkStyle.setCheckState(styleState)
        grid.addWidget(self.checkStyle, 3, 1)
        #Highlight words
        self.checkWords = QCheckBox('Highlight current word.')
        wordsState = Qt.Checked if EditorGeneric.highlightVariables else Qt.Unchecked
        self.checkWords.setCheckState(wordsState)
        grid.addWidget(self.checkWords, 4, 1)

        groupBoxClose = QGroupBox('Complete:')
        grid.addWidget(groupBoxClose, 5, 0)
        self.checkParentheses = QCheckBox('Parentheses: ()')
        state = Qt.Checked if EditorGeneric.braces_strings.get('(', False) else Qt.Unchecked
        self.checkParentheses.setCheckState(state)
        self.checkKeys = QCheckBox('Keys: {}')
        state = Qt.Checked if EditorGeneric.braces_strings.get('{', False) else Qt.Unchecked
        self.checkKeys.setCheckState(state)
        self.checkBrackets = QCheckBox('Brackets: []')
        state = Qt.Checked if EditorGeneric.braces_strings.get('[', False) else Qt.Unchecked
        self.checkBrackets.setCheckState(state)
        self.checkSimpleQuotes = QCheckBox("Simple Quotes: ''")
        state = Qt.Checked if EditorGeneric.braces_strings.get("'", False) else Qt.Unchecked
        self.checkSimpleQuotes.setCheckState(state)
        self.checkDoubleQuotes = QCheckBox('Double Quotes: ""')
        state = Qt.Checked if EditorGeneric.braces_strings.get('"', False) else Qt.Unchecked
        self.checkDoubleQuotes.setCheckState(state)
        grid.addWidget(self.checkParentheses, 6, 1)
        grid.addWidget(self.checkKeys, 7, 1)
        grid.addWidget(self.checkBrackets, 8, 1)
        grid.addWidget(self.checkSimpleQuotes, 9, 1)
        grid.addWidget(self.checkDoubleQuotes, 10, 1)

        groupBoxCode = QGroupBox('Code Completion:')
        grid.addWidget(groupBoxCode, 11, 0)
        self.checkCodeDot = QCheckBox('Activate Code Completion with: "."')
        state = Qt.Checked if EditorGeneric.codeCompletion else Qt.Unchecked
        self.checkCodeDot.setCheckState(state)
#        self.checkCodeChar = QCheckBox('Activate Code Completion after:')
#        self.spinCode = QSpinBox()
#        self.spinCode.setSuffix(' characters')
        grid.addWidget(self.checkCodeDot, 12, 1)
#        grid.addWidget(self.checkCodeChar, 13, 0)
#        grid.addWidget(self.spinCode, 13, 1)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('editor')
        settings.setValue('indent', self.spin.value())
        EditorGeneric.indent = self.spin.value()
        settings.setValue('errors', self.checkErrors.isChecked())
        EditorGeneric.findErrors = self.checkErrors.isChecked()
        settings.setValue('checkStyle', self.checkStyle.isChecked())
        EditorGeneric.checkStyle = self.checkStyle.isChecked()
        settings.setValue('highlightWord', self.checkWords.isChecked())
        EditorGeneric.highlightVariables = self.checkWords.isChecked()
        settings.setValue('parentheses', self.checkParentheses.isChecked())
        if self.checkParentheses.isChecked():
            EditorGeneric.braces_strings['('] = ')'
        elif EditorGeneric.braces_strings.has_key('('):
            del EditorGeneric.braces_strings['(']
        settings.setValue('brackets', self.checkBrackets.isChecked())
        if self.checkBrackets.isChecked():
            EditorGeneric.braces_strings['['] = ']'
        elif EditorGeneric.braces_strings.has_key('['):
            del EditorGeneric.braces_strings['[']
        settings.setValue('keys', self.checkKeys.isChecked())
        if self.checkKeys.isChecked():
            EditorGeneric.braces_strings['{'] = '}'
        elif EditorGeneric.braces_strings.has_key('{'):
            del EditorGeneric.braces_strings['{']
        settings.setValue('simpleQuotes', self.checkSimpleQuotes.isChecked())
        if self.checkSimpleQuotes.isChecked():
            EditorGeneric.braces_strings["'"] = "'"
        elif EditorGeneric.braces_strings.has_key("'"):
            del EditorGeneric.braces_strings["'"]
        settings.setValue('doubleQuotes', self.checkDoubleQuotes.isChecked())
        if self.checkDoubleQuotes.isChecked():
            EditorGeneric.braces_strings['"'] = '"'
        elif EditorGeneric.braces_strings.has_key('"'):
            del EditorGeneric.braces_strings['"']
        settings.setValue('codeCompletion', self.checkCodeDot .isChecked())
        settings.endGroup()
        settings.endGroup()
Beispiel #20
0
class DesignPage(QWidget):
    """
    Design Export Page
    """
    ExportTests = pyqtSignal(list, dict) 
    def __init__(self, parent, core, debugMode=False):
        """
        Constructor
        @param parent:
        """
        QWidget.__init__(self, parent)
        self.__core = core
        self.__debugMode = debugMode
        self.__rawXml = ""
        self.__listCsv = []
        
        self.createWidgets()
        self.creationConnections()
        
        if self.__debugMode: self.readXml(rawXml=DESIGN_EXAMPLE)
    
    def core(self):
        """
        """
        return self.__core

    def creationConnections (self):
        """
        QtSignals connection:
        """
        self.exportButton.clicked.connect( self.exportClicked )
        self.loadCsvButton.clicked.connect( self.loadCsv )
        self.testsTable.LoadSteps.connect( self.onLoadSteps )
        
        self.mergeCheckBox.toggled.connect( self.onOptionToggled )
        self.showTcNameCheckBox.toggled.connect( self.onOptionToggled )
        self.mergeStepsCheckBox.toggled.connect( self.onOptionToggled )
        self.replaceTcCheckBox.toggled.connect( self.onOptionToggled )
        
    def createWidgets(self):
        """
        """
        # options
        self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one"))
        if self.core().settings().cfg()["export-tests"]["merge-all-tests"]:
            self.mergeCheckBox.setCheckState(Qt.Checked) 
            
        self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name"))
        if self.core().settings().cfg()["export-tests"]["original-test"]:
            self.showTcNameCheckBox.setCheckState(Qt.Checked) 
            
        self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname"))
        if self.core().settings().cfg()["export-tests"]["replace-testcase"]:
            self.replaceTcCheckBox.setCheckState(Qt.Checked) 
            
        self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one"))
        if self.core().settings().cfg()["export-tests"]["merge-all-steps"]:
            self.mergeStepsCheckBox.setCheckState(Qt.Checked) 
            
        self.addMissingFoldersCheckBox = QCheckBox(self.tr("Create missing folders"))
        if self.core().settings().cfg()["export-tests"]["add-folders"]:
            self.addMissingFoldersCheckBox.setCheckState(Qt.Checked) 
            
        self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcase(s)"))
        if self.core().settings().cfg()["export-tests"]["overwrite-tests"]:
            self.overwriteTcCheckBox.setCheckState(Qt.Checked) 
            
        # actions to export
        self.loadCsvButton = QPushButton(self.tr("Load CSV"), self)
        
        self.exportButton = QPushButton(self.tr("Export Test"), self)
        self.exportButton.setMinimumWidth(300)
        self.exportStatusLabel = QLabel( "Status: Disconnected", self)

        # tables definition
        self.testsTable = TestsTableView(self, core=self.core())
        self.stepsTable = StepsTableView(self, core=self.core())
        
        # options layout
        optionsTpLayout = QHBoxLayout()
        optionsTpLayout.addWidget(self.addMissingFoldersCheckBox)
        optionsTpLayout.addWidget(self.overwriteTcCheckBox)
        optionsTpLayout.addStretch(1)
        
        optionsLayout = QHBoxLayout()
        optionsLayout.addWidget(self.mergeCheckBox)
        optionsLayout.addWidget(self.showTcNameCheckBox)
        optionsLayout.addWidget(self.replaceTcCheckBox)
        optionsLayout.addStretch(1)
        
        layoutGrid = QGridLayout()
        layoutGrid.addWidget(QLabel("Remote TestPlan:"), 0, 0)
        layoutGrid.addLayout(optionsTpLayout, 0, 1)
        layoutGrid.addWidget(QLabel("Local Test:"), 1, 0)
        layoutGrid.addLayout(optionsLayout, 1, 1)
        layoutGrid.addWidget(QLabel("Tests Listing:"), 2, 0)
        layoutGrid.addWidget(self.testsTable, 2, 1)
        layoutGrid.addWidget(self.mergeStepsCheckBox, 3, 1)
        layoutGrid.addWidget(QLabel("Steps Listing:"), 4, 0)
        layoutGrid.addWidget(self.stepsTable, 4, 1)
        
        layoutRight = QHBoxLayout()
        layoutRight.addWidget(self.exportButton)
        layoutRight.addWidget(self.loadCsvButton)
        layoutRight.addWidget(self.exportStatusLabel)
        layoutRight.addStretch(1)
        
        layoutGrid.addWidget(QLabel("Controls:"), 5, 0)
        layoutGrid.addLayout(layoutRight, 5, 1)
        
        layoutMain = QVBoxLayout()
        layoutMain.addLayout(layoutGrid)
    
        self.setLayout(layoutMain)

    def resetBuffers(self):
        """
        """
        self.__rawXml = ""
        self.__listCsv = []
        
    def loadCsv(self):
        """
        """
        self.resetBuffers()
        
        fileName = QFileDialog.getOpenFileName(self,
              self.tr("Open File"), "", "CSV (*.csv)")
        if not len(fileName):
            return

        csv.register_dialect('coma', delimiter=';')

        tests = []
            
        with open(fileName, encoding='iso-8859-1') as f:
            reader = csv.DictReader(f, dialect="coma")
            prev = None
            for row in reader:
                if prev is not None:
                    if prev["testpath"] == row["testpath"] and prev["testcase"] == row["testcase"]:
                        prev["steps"].append( { 
                                            "summary": row["step description"],
                                            "action": row["step description"],         
                                            "expected": row["step expected"] 
                                        } )
                        continue

                test = {
                            "testpath": row["testpath"], 
                            "requirement": "", 
                            "testname": "",
                            "testcase": row["testcase"], 
                            "purpose": row["purpose"], 
                            "steps": [ 
                                        { 
                                            "summary": row["step description"],
                                            "action": row["step description"],         
                                            "expected": row["step expected"] 
                                        }
                                    ]
                        }
                tests.append(test)
                prev = test

        self.readListCsv(listCsv=tests)
        
    def exportClicked (self):
        """
        Called on accept button
        """
        indexes = self.testsTable.selectionModel().selectedRows()
        if not len(indexes):
            QMessageBox.warning(self, self.tr("Export Test") , 
                                self.tr("Please to select a testcase!") )
            return
        
        testcases = []
        
        error = False
        for index in indexes:
            selectedIndex = index.row()
            row = self.testsTable.model.getData()[selectedIndex]
            if not len(row["testcase"]): error = True
            testcases.append(row)
        
        if error: 
            QMessageBox.warning(self, self.tr("Export Test") , 
                                self.tr("Please to set a testcase name!") )
            return

        config = {}
        for cfg in self.core().settings().cfg()["custom-test-fields"]:
            config.update( {cfg["key"]: cfg["value"] } )
            
        self.disableExport()
        
        config["Add_Folders"] = self.addMissingFoldersCheckBox.isChecked()
        config["Overwrite_Tests"] = self.overwriteTcCheckBox.isChecked()
                    
        self.ExportTests.emit(testcases, config)
        
    def onOptionToggled (self, toggled):
        """
        Called on accept button
        """
        # reload from initial dict
        if len(self.__listCsv):
            self.readListCsv(listCsv=self.__listCsv)
        
        # reload from initial xml, default       
        else:
            self.readXml(rawXml=self.__rawXml)

    def logStatus(self, status):
        """
        """
        self.exportStatusLabel.setText(status)
        
    def enableExport(self):
        """
        """
        self.exportButton.setEnabled(True)
        
    def disableExport(self):
        """
        """
        self.exportButton.setEnabled(False)
 
    def onLoadSteps(self, steps):
        """
        """
        self.stepsTable.loadTable(data=steps)

    def onLoadTests(self, data):
        """
        """
        self.stepsTable.clear()
        self.testsTable.loadTable(data=data)

    def readListCsv(self, listCsv):
        """
        """
        self.resetBuffers()
        
        self.__listCsv = listCsv
        
        testcases = copy.deepcopy(listCsv)

        if self.mergeCheckBox.isChecked(): testcases = self.mergeTests(testcases=testcases)
            
        for tc in testcases:
            # read and merge all tests in one ?
            if self.mergeStepsCheckBox.isChecked(): tc["steps"] = self.mergeCsvSteps(steps=tc["steps"])

        # finally loading all tests in table model
        self.core().debug().addLogSuccess("Tests detected in csv: %s"  % len(testcases) )
        if len(testcases):  self.onLoadTests(data=testcases)
        
    def mergeTests(self, testcases):
        """
        """
        tc = {
                    "testpath": testcases[0]["testpath"], 
                    "requirement": testcases[0]["requirement"], 
                    "testname": testcases[0]["testname"], 
                    "testcase": testcases[0]["testcase"], 
                    "purpose": testcases[0]["purpose"],  
                    "steps": []
                }
        for t in testcases:  tc["steps"].extend(t["steps"]) 
        return [ tc ]
        
    def mergeCsvSteps(self, steps):
        """
        """
        summaries = []
        actions = []
        expecteds = []
        i = 0
        for stp in steps:
            i += 1
            summaries.append( "%s. %s" %  (i, stp["summary"]) )
            actions.append( "%s. %s" %  (i, stp["action"]) )
            expecteds.append( "%s. %s" % (i, stp["expected"]) )
            
        ret = {
                 'summary': "\n".join(summaries),
                 'action': "\n".join(actions),
                 'expected': "\n".join(expecteds)
                }
        return [ ret ]
        
    def readXml(self, rawXml):
        """
        """
        self.resetBuffers()
        
        # init and save the xml provided
        self.__rawXml = rawXml
        testcases = []
        
        # load the xml provided
        try:
            root = ET.fromstring(rawXml)
        except Exception as e:
            self.core().debug().addLogError("Unable to read xml: %s"  % e )
        else: 
            designs = root.find(".")

            # read and merge all tests in one ?
            if self.mergeCheckBox.isChecked(): testcases = self.mergeXmlTests(designsXml=designs)
                
            # otherwise read all tests
            else: testcases = self.readXmlTests(designsXml=designs)
             
            # finally loading all tests in table model
            self.core().debug().addLogSuccess("Export tests detected: %s"  % len(testcases) )
            if len(testcases):  self.onLoadTests(data=testcases)

    def mergeXmlTests(self, designsXml):
        """
        """
        testcases = []
        tc = { "steps": [] }
        summaries = []
        actions = []
        expecteds = []
        delta = 0
        for i in range(len(designsXml)):
            if i == 0:
                tc["requirement"] = designsXml[i].find("requirement").text
                tc["purpose"] = designsXml[i].find("purpose").text
                if self.showTcNameCheckBox.isChecked():
                    tc["testpath"] = designsXml[i].find("testpath").text
                    tc["testname"] = designsXml[i].find("testname").text
                    tc["testcase"] = designsXml[i].find("testcase").text
                else:
                    tc["testpath"] = designsXml[i].find("filepath").text
                    tc["testname"] = designsXml[i].find("filename").text
                    tc["testcase"] = designsXml[i].find("testname").text
                    
                if self.replaceTcCheckBox.isChecked():
                    tc["testpath"] = designsXml[i].find("filepath").text
                    tc["testname"] = ""
                    tc["testcase"] = designsXml[i].find("filename").text
                    
            stepsDesigns = designsXml[i].findall("steps/step")

            steps, nb_steps = self.readXmlSteps(stepsXml=stepsDesigns, delta=delta)
            delta += nb_steps
            if self.mergeStepsCheckBox.isChecked() and len(steps):
                summaries.append(steps[0]["summary"])
                actions.append(steps[0]["action"])
                expecteds.append(steps[0]["expected"])
            else:
                tc["steps"].extend(steps) 

        testcases.append(tc)
        if self.mergeStepsCheckBox.isChecked():
            stp = {
                     'summary': "\n".join(summaries),
                     'action': "\n".join(actions),
                     'expected': "\n".join(expecteds)
                    }
            tc["steps"].extend( [ stp ] )
        return testcases
        
    def readXmlTests(self, designsXml):
        """
        """
        testcases = []
        for design in designsXml:
            tc = { 
                    "requirement": design.find("requirement").text,
                    "purpose": design.find("purpose").text,
                 }
            
            # replace testcase name ?
            if not self.showTcNameCheckBox.isChecked():
                tc.update( {
                            "testpath": design.find("filepath").text,
                            "testname": design.find("filename").text,
                            "testcase": design.find("testname").text
                            } )
            else:
                tc.update( {
                            "testpath": design.find("testpath").text,
                            "testname": design.find("testname").text,
                            "testcase": design.find("testcase").text
                            } )
                            
            if self.replaceTcCheckBox.isChecked():
                tc.update( {
                            "testpath": design.find("testpath").text,
                            "testname": "",
                            "testcase": design.find("testname").text
                            } )
                
            # read steps
            stepsDesigns = design.findall("steps/step")
            steps, nb_steps = self.readXmlSteps(stepsXml=stepsDesigns)
            tc.update( {"steps": steps} )
            
            testcases.append(tc)
        return testcases
        
    def readXmlSteps(self, stepsXml, delta=0):
        """
        """
        steps = []
        summaries = []
        actions = []
        expecteds = []
        i = 0
        for stp in stepsXml:
            i += 1
            summary = stp.find("summary").text
            action = stp.find("action").text
            expected = stp.find("expected").text
            if self.mergeStepsCheckBox.isChecked():
                summaries.append( "%s. %s" % (i + delta, summary) )
                actions.append( "%s. %s" % (i + delta, action) )
                expecteds.append( "%s. %s" % (i + delta, expected) )
            else:
                stp = {
                         'summary': summary,
                         'action': action,
                         'expected': expected
                        }
                steps.append(stp)
                
        if self.mergeStepsCheckBox.isChecked():
            stp = {
                     'summary': "\n".join(summaries),
                     'action': "\n".join(actions),
                     'expected': "\n".join(expecteds)
                    }
            steps.append(stp)
        return (steps, i)
Beispiel #21
0
class WProbes(QWidget, Logger.ClassLogger):
    """
    Widget for probes
    """
    def __init__(self, parent):
        """
        Constructs WProbes widget

        @param parent: 
        @type parent:
        """
        QWidget.__init__(self, parent)
        self.parent = parent
        self.name = self.tr("Probes")
        self.itemCurrentRunning = None
        self.itemCurrentInstalled = None
        self.itemCurrentDefault = None
        self.probes = {}

        self.nbPrbs = 0
        # self.prbsInstalled = None

        self.createWidgets()
        self.createConnections()
        self.createActions()
        self.createToolbar()
        self.deactivate()

    def createWidgets (self):
        """
        QtWidgets creation

        QTreeWidget (Name, Running on address, Type, Sched at, Version, Description)
         _______________
        |               |
        |---------------|
        |               |
        |               |
        |_______________|
        """
        layout = QHBoxLayout()

        self.deployBox = QGroupBox("Default probes")
        self.probesAvailable = QTreeWidget(self)
        self.probesAvailable.setIndentation(10)
        self.labelsAvail = [ self.tr("Installed") ]
        self.probesAvailable.setHeaderLabels(self.labelsAvail)

        self.runningBox = QGroupBox("Running")
        self.probesRegistered = QTreeWidget(self)
        self.probesRegistered.setIndentation(10)
        self.runningDockToolbar = QToolBar(self)
        self.runningDockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.availDockToolbar = QToolBar(self)
        self.availDockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.labels = [ self.tr("Name"), self.tr("Running on address"), self.tr("Started at"), 
                        self.tr("Type"), self.tr("Auto Startup"), self.tr("Description") ]        
        self.probesRegistered.setHeaderLabels(self.labels)
        self.probesRegistered.setColumnWidth(0, 180)
        self.probesRegistered.setColumnWidth(1, 120)
        self.probesRegistered.setColumnWidth(2, 150)
        self.probesRegistered.setColumnWidth(3, 70)
        self.probesRegistered.setContextMenuPolicy(Qt.CustomContextMenu)

        self.probesDefault = QTreeWidget(self)
        self.probesDefault.setIndentation(10)
        self.labelsDefault = [ self.tr("Enabled"), self.tr("Name"), self.tr("Type"), self.tr("Description") ]
        self.probesDefault.setHeaderLabels(self.labelsDefault)
        self.probesDefault.setContextMenuPolicy(Qt.CustomContextMenu)
        self.probesDefault.setColumnWidth(1, 180)


        layoutRunning = QVBoxLayout()
        layoutRunning.addWidget(self.runningDockToolbar)
        layoutRunning.addWidget(self.probesRegistered)
        self.runningBox.setLayout(layoutRunning)

        self.probeNameEdit = QLineEdit('')
        self.probeNameEdit.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )

        self.probeDescEdit = QLineEdit('')
        self.probeDescEdit.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )

        self.probeTypeEdit = QLineEdit('')
        self.probeTypeEdit.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )
        self.probeTypeEdit.setEnabled(False)
        
        self.probeDescrInstalledEdit = QTextEdit('')
        self.probeDescrInstalledEdit.setEnabled(False)
        
        self.checkAutoStartOption = QCheckBox()
        self.checkStartNowOption = QCheckBox()

        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Type:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeTypeEdit, 0, 1)
        paramLayout.addWidget(QLabel("Name:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeNameEdit, 1, 1)
        paramLayout.addWidget(QLabel("Description:"), 2, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeDescEdit, 2, 1)
        paramLayout.addWidget(QLabel("Startup on boot:"), 3, 0, Qt.AlignRight)
        paramLayout.addWidget(self.checkAutoStartOption, 3, 1)
        paramLayout.addWidget(QLabel("Start now:"), 4, 0, Qt.AlignRight)
        paramLayout.addWidget(self.checkStartNowOption, 4, 1)
      
        layoutLeft = QVBoxLayout()

        layoutAvail = QHBoxLayout()
        layoutAvail.addWidget(self.probesAvailable)
        layoutAvail.addWidget(self.probeDescrInstalledEdit)
        
        layoutLeft.addLayout(layoutAvail)
        layoutLeft.addWidget(self.runningBox)

        layoutDeploy = QVBoxLayout()
        layoutDeploy.addWidget(self.availDockToolbar)
        layoutDeploy.addLayout(paramLayout)
        layoutDeploy.addWidget(self.probesDefault)
        self.deployBox.setLayout(layoutDeploy)

        layoutRight = QVBoxLayout()
        layoutRight.addWidget(self.deployBox)   

        layout.addLayout(layoutLeft)
        layout.addLayout(layoutRight)
        self.setLayout(layout)

    def createConnections (self):
        """
        Create Qt Connections
        """
        self.probesRegistered.customContextMenuRequested.connect(self.onPopupMenu)
        self.probesRegistered.currentItemChanged.connect(self.currentItemChanged)
        self.probesRegistered.itemClicked.connect(self.itemClicked)

        self.probesAvailable.currentItemChanged.connect(self.currentItemChanged)

        self.probesDefault.currentItemChanged.connect(self.currentItemChanged)
        self.probesDefault.customContextMenuRequested.connect(self.onPopupMenuDefault)

    def createActions (self):
        """
        Actions defined:
         * stop probe
         * start probe
         * delete one probe
         * clear fields
         * refresh running probes
         * refresh default probes
        """
        self.stopAction = QtHelper.createAction(self, "&Stop", self.stopProbe, tip = 'Stop probe', 
                                        icon = QIcon(":/act-stop.png"))
        self.startAction = QtHelper.createAction(self, "&Add / Start", self.startProbe, tip = 'Add default probe', 
                                        icon = QIcon(":/probe-add.png"))
        self.delProbeAction = QtHelper.createAction(self, "&Delete", self.delProbe, tip = 'Delete default probe', 
                                        icon = QIcon(":/probe-del.png"))
        self.cancelAction = QtHelper.createAction(self, "&Clear", self.resetProbe, tip = 'Clear fields', 
                                        icon = QIcon(":/clear.png") )
        self.refreshRunningAction = QtHelper.createAction(self, "&Refresh", 
                                        self.refreshRunningProbe, tip = 'Refresh running probes', 
                                        icon = QIcon(":/act-refresh.png") )
        self.refreshDefaultAction = QtHelper.createAction(self, "&Refresh", 
                                        self.refreshDefaultProbe, tip = 'Refresh default probes', 
                                        icon = QIcon(":/act-refresh.png") )

    def createToolbar(self):
        """
        Toolbar creation
            
        ||-------||
        || Empty ||
        ||-------||
        """
        self.runningDockToolbar.setObjectName("Registered Probe toolbar")
        self.runningDockToolbar.addAction(self.refreshRunningAction)
        self.runningDockToolbar.addSeparator()
        self.runningDockToolbar.addAction(self.stopAction)
        self.runningDockToolbar.addSeparator()
        self.runningDockToolbar.setIconSize(QSize(16, 16))

        self.availDockToolbar.setObjectName("Installed Probe toolbar")
        self.availDockToolbar.addAction(self.refreshDefaultAction)
        self.availDockToolbar.addSeparator()
        self.availDockToolbar.addAction(self.startAction)
        self.availDockToolbar.addAction(self.delProbeAction)
        self.availDockToolbar.addSeparator()
        self.availDockToolbar.addAction(self.cancelAction)
        self.availDockToolbar.addSeparator()
        self.availDockToolbar.setIconSize(QSize(16, 16))

    def itemClicked(self, currentItem):
        """
        On item clicked

        @param currentItem: 
        @type currentItem:  
        """
        if currentItem is not None:
            if isinstance( currentItem, ProbeItem ):
                self.itemCurrentRunning = currentItem
                self.stopAction.setEnabled(True)

    def currentItemChanged(self, currentItem, previousItem):
        """
        On current item changed

        @param currentItem: 
        @type currentItem:  

        @param previousItem: 
        @type previousItem: 
        """
        if currentItem is not None:
            if isinstance( currentItem, ProbeInstalledItem ):
                self.itemCurrentInstalled = currentItem
                if 'description' in currentItem.dataProbe:
                    self.probeDescrInstalledEdit.setText( currentItem.dataProbe['description'] )
                    self.probeTypeEdit.setText( currentItem.dataProbe['type'] )
                else:
                    self.probeDescrInstalledEdit.setText( '' )
            elif isinstance( currentItem, ProbeItem ):
                self.itemCurrentRunning = currentItem
                self.stopAction.setEnabled(True)
            elif isinstance( currentItem, ProbeDefaultItem ):
                self.itemCurrentDefault = currentItem
                self.delProbeAction.setEnabled(True)
            else:
                self.stopAction.setEnabled(False)
                self.delProbeAction.setEnabled(False)
                self.probeDescrInstalledEdit.setText( '' )

    def onPopupMenu(self, pos):
        """
        Display menu on right click

        @param pos: 
        @type pos:
        """
        self.menu = QMenu()
        item = self.probesRegistered.itemAt(pos)
        if item:
            self.itemCurrentRunning = item
            self.menu.addAction( "Stop...", self.stopProbe)
            self.menu.popup(self.probesRegistered.mapToGlobal(pos))

    def onPopupMenuDefault(self, pos):
        """
        Display menu on right click

        @param pos: 
        @type pos:
        """
        self.menu = QMenu()
        item = self.probesDefault.itemAt(pos)
        if item:
            self.itemCurrentDefault = item
            self.menu.addAction( "Delete...", self.delProbe)
            self.menu.popup(self.probesDefault.mapToGlobal(pos))


    def refreshDefaultProbe(self):
        """
        Refresh the default list of probes
        """
        RCI.instance().defaultProbes()
        
    def refreshRunningProbe(self):
        """
        Refresh the running list of probes
        """
        RCI.instance().runningProbes()
        
    def delProbe(self):
        """
        Delete probe
        """
        if self.itemCurrentDefault is not None:
            reply = QMessageBox.question(self, "Stop probe", "Are you sure ?",
                QMessageBox.Yes | QMessageBox.No )
            if reply == QMessageBox.Yes:
                probeName = self.itemCurrentDefault.dataProbe['name']
                self.delProbeAction.setEnabled(False)
                
                # rest call
                RCI.instance().removeProbe(probeName=probeName)
                
    def stopProbe(self):
        """
        Stop the selected probe
        """
        if self.itemCurrentRunning is not None:
            reply = QMessageBox.question(self, "Stop probe", "Are you sure ?",
                QMessageBox.Yes | QMessageBox.No )
            if reply == QMessageBox.Yes:
                probeName = self.itemCurrentRunning.dataProbe['id']
                self.itemCurrentRunning = None
                self.stopAction.setEnabled(False)
                
                # rest call
                RCI.instance().disconnectProbe(probeName=probeName)
                
    def startProbe(self):
        """
        Start a new probe
        """
        # some checks before
        if self.probeTypeEdit.text() == '':
            QMessageBox.information(self, "Add Default Probe" , "Please select the probe type.")
            return
        if self.probeNameEdit.text() == '':
            QMessageBox.information(self, "Add Default Probe" , "Probe name is mandatory.")
            return
        if not self.checkAutoStartOption.isChecked() and not self.checkStartNowOption.isChecked():
            QMessageBox.information(self, "Add Default Probe" , "Select startup option.")
            return
            
        # call web services
        probeType = str( self.probeTypeEdit.text() )
        probeName = str( self.probeNameEdit.text() )
        probeDescription =  str( self.probeDescEdit.text() )
        probeAutoStart = self.checkAutoStartOption.isChecked()

        if not self.checkStartNowOption.isChecked():
            RCI.instance().addProbe(probeName=probeName, probeType=probeType, 
                                    probeDescription=probeDescription)
        else:
            RCI.instance().connectProbe(probeName=probeName, probeType=probeType, 
                                        probeDescription=probeDescription, 
                                        probeBoot=probeAutoStart)
                                        
    def resetProbe(self):
        """
        Clear probe field
        """
        self.probeDescrInstalledEdit.setText( '' )
        self.probeDescEdit.setText( '' )
        self.probeNameEdit.setText( '' )
        self.probeTypeEdit.setText( '' )
        
        # clear selection
        itms = self.probesAvailable.selectedItems()
        for i in itms:
            if i.isSelected():
                i.setSelected(False)
        self.itemCurrentInstalled = None

    def active (self):
        """
        Enables QTreeWidget
        """
        self.probesRegistered.setEnabled(True)
        self.probesAvailable.setEnabled(True)
        self.deployBox.setEnabled(True)
        self.runningBox.setEnabled(True)

        self.refreshRunningAction.setEnabled(True)

    def deactivate (self):
        """
        Clears QTreeWidget and disables it
        """
        self.checkAutoStartOption.setCheckState(Qt.Unchecked) 
        self.checkStartNowOption.setCheckState(Qt.Unchecked) 

        self.probesAvailable.clear()
        self.probeDescrInstalledEdit.setText('')
        
        self.probesRegistered.clear()
        self.probesDefault.clear()
        self.probes = {}
        
        self.probesRegistered.setEnabled(False)
        self.probesAvailable.setEnabled(False)
        self.deployBox.setEnabled(False)
        self.runningBox.setEnabled(False)

        # actions
        self.stopAction.setEnabled(False)
        self.delProbeAction.setEnabled(False)
        
        self.itemCurrentRunning = None
        self.itemCurrentInstalled = None

        self.probeDescEdit.setText( '' )
        self.probeTypeEdit.setText( '' )
        self.probeNameEdit.setText( '' )

        self.resetNbProbes()

        self.refreshRunningAction.setEnabled(False)

    def getRunningProbes(self):
        """
        Get running probes 
        """
        if sys.version_info > (3,): # python3 support
            return list(self.probes.keys())
        else:
            return self.probes.keys()

    def getProbeTypeByName(self, name):
        """
        Get probe type by name

        @param name: 
        @type name:
        """
        if name in self.probes:
            return self.probes[name].getProbeType()
        else:
            return ''

    def loadDefault (self, data):
        """
        Loads default probes

        @param data: 
        @type data: dict
        """
        self.probesDefault.clear()

        for defProbe in data:
            defProbeItem = ProbeDefaultItem( probe = defProbe, parent= self.probesDefault)

    def loadData (self, data, dataInstalled=None):
        """
        Loads probes

        @param data: 
        @type data: dict

        @param dataInstalled: 
        @type dataInstalled:
        """
        if isinstance(data, dict):
            data = [ data ]

        self.probesRegistered.clear()

        for probe in data:
            probeItem = ProbeItem( probe = probe, parent= self.probesRegistered)
            self.probes[probe['id']] = probeItem

        # load tests stats
        if dataInstalled is not None:
            if len(dataInstalled) == 0:
                self.deployBox.setEnabled(False)
                self.probesAvailable.setEnabled(False)

    def resetNbProbes(self, data=None):
        """
        Reset the number of probes
        """
        pass

    def refreshData (self, data, action):
        """
        Refresh probes

        @param data: 
        @type data: dict

        @param action: expected values in 'del' and 'add'
        @type action: string
        """
        if action == 'del':
            self.probesRegistered.clear()
            self.probes = {}
            self.resetNbProbes(data=data)
            self.loadData( data = data )
        elif action == 'add':
            self.resetNbProbes(data=data)
            self.loadData( data = data )        
        else:
            self.error( 'action unknown: %s' % str(action) )
    
    def refreshDataDefault(self, data, action):
        """
        Refresh probes

        @param data: 
        @type data: dict

        @param action: expected values in 'del' and 'add'
        @type action: string
        """
        if action == 'del':
            self.probesDefault.clear()
            self.loadDefault( data = data )
        elif action == 'add':
            self.probesDefault.clear()
            self.loadDefault( data = data )     
        else:
            self.error( 'action unknown: %s' % str(action) )
Beispiel #22
0
class clothCheck_UI(QtGui.QWidget):
    def __init__(self):
        super(clothCheck_UI, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Check cloth scene health")
        self.checklayout = QVBoxLayout()
        self.checkLayout = QBoxLayout(2)
        self.playlist_names = QComboBox()
        self.checklayout.addLayout(self.checkLayout)
        self.check_all = QPushButton("check all")
        self.connect(self.check_all, SIGNAL("clicked()"),lambda: self._check_all())
        self.checkLayout.addWidget(self.check_all)
        self.check_none = QPushButton("check none")
        self.connect(self.check_none, SIGNAL("clicked()"),lambda: self._check_none())
        self.checkLayout.addWidget(self.check_none)
        self.checkRange = QCheckBox("Framerange")
        self.checkRange.setCheckState(0)
        self.checkLayout.addWidget(self.checkRange)
        self.nuc_category = QLabel("Nucleus")
        self.nuc_enable = QCheckBox("nuc enabled")
        self.nuc_enable.setCheckState(1)
        self.checkLayout.addWidget(self.nuc_enable)
        self.checkLayout.addWidget(self.nuc_category)
        self.nuc_strt = QCheckBox("Nucleus startframe")
        self.nuc_strt.setCheckState(1)
        self.checkLayout.addWidget(self.nuc_strt)
        self.space_scale = QCheckBox("space scale")
        self.space_scale.setCheckState(1)
        self.checkLayout.addWidget(self.space_scale)
        self.nuc_subs = QCheckBox("substeps")
        self.nuc_subs.setCheckState(1)
        self.checkLayout.addWidget(self.nuc_subs)
        self.coll_iter = QCheckBox("collision iterations")
        self.coll_iter.setCheckState(1)
        self.checkLayout.addWidget(self.coll_iter)
        self.rgd_category = QLabel("Rigids")
        self.checkLayout.addWidget(self.rgd_category)
        self.rgd_pnt_mass = QCheckBox("rgd point mass")
        self.rgd_pnt_mass.setCheckState(1)
        self.checkLayout.addWidget(self.rgd_pnt_mass)
        self.clth_category = QLabel("Cloth")
        self.checkLayout.addWidget(self.clth_category)
        self.scale_rel = QCheckBox("scale relations")
        self.scale_rel.setCheckState(1)
        self.checkLayout.addWidget(self.scale_rel)

        self.trap_check = QCheckBox("trapped check")
        self.trap_check.setCheckState(1)
        self.checkLayout.addWidget(self.trap_check)


        self.clth_enable = QCheckBox("enabled")
        self.clth_enable.setCheckState(1)
        self.checkLayout.addWidget(self.clth_enable)

        self.dyn_cnstrnt_category = QLabel("Dynamic Constraints")
        self.checkLayout.addWidget(self.dyn_cnstrnt_category)

        self.dyncnstrnt_exc = QCheckBox("dconstrnt exclusions")
        self.dyncnstrnt_exc.setCheckState(1)
        self.checkLayout.addWidget(self.dyncnstrnt_exc)


        self.dyncnstrnt_cmp = QCheckBox("dconstrnt component")
        self.dyncnstrnt_cmp.setCheckState(1)
        self.checkLayout.addWidget(self.dyncnstrnt_cmp)


        self.dry_button = QPushButton("dry run")
        self.connect(self.dry_button, SIGNAL("clicked()"),lambda: self.dry_run())
        self.checkLayout.addWidget(self.dry_button)
        self.doit_button = QPushButton("check cloth scene")
        self.connect(self.doit_button, SIGNAL("clicked()"),lambda: self.checkit())
        self.checkLayout.addWidget(self.doit_button)
        self.close_button = QPushButton("close")
        self.connect(self.close_button, SIGNAL("clicked()"),lambda: self.gotoAppend())
        # self.checkLayout.addWidget(self.label)
        self.checkLayout.addWidget(self.close_button)
        self.setLayout(self.checklayout)

    def gotoAppend(self):
        self.close()

    def dry_run(self):
        get_baseTools=mockTools.mToolKit()
        get_baseTools.troubleshoot_clth()

    def checkit(self):
        check_dict={}
        getrange={"range":self.checkRange.checkState()}
        check_dict.update(getrange)
        getnucstart={"nucstart":self.nuc_strt.checkState()}
        check_dict.update(getnucstart)
        getnucenable={"nucenable":self.nuc_enable.checkState()}
        check_dict.update(getnucenable)
        getspcscl={"nuc_spc_scl":self.space_scale.checkState()}
        check_dict.update(getspcscl)
        getnucsubstp={"nuc_sub_stp":self.nuc_subs.checkState()}
        check_dict.update(getnucsubstp)
        getnuccoliter={"nuc_col_itr":self.coll_iter.checkState()}
        check_dict.update(getnuccoliter)
        getrdgmss={"rgd_mass":self.rgd_pnt_mass.checkState()}
        check_dict.update(getrdgmss)
        getsclerel={"scl_rel":self.scale_rel.checkState()}
        check_dict.update(getsclerel)
        getdyncnstrntexcl={"dyn_cnstrnt_exc":self.dyncnstrnt_exc.checkState()}
        check_dict.update(getdyncnstrntexcl)
        getdyncnstrntcmpl={"dyn_cnstrnt_exc":self.dyncnstrnt_cmp.checkState()}
        check_dict.update(getdyncnstrntcmpl)
        getclthenble={"clthenable":self.clth_enable.checkState()}
        check_dict.update(getclthenble)
        getclthtrpchk={"clth_trp_chk":self.trap_check.checkState()}
        check_dict.update(getclthtrpchk)
        get_baseTools=mockTools.mToolKit()
        get_baseTools.set_troubleshoot(check_dict)

    def _check_all(self):
        self.checkRange.setCheckState(1)
        self.nuc_strt.setCheckState(1)
        self.clth_enable.setCheckState(1)
        self.nuc_enable.setCheckState(1)
        self.space_scale.setCheckState(1)
        self.nuc_subs.setCheckState(1)
        self.coll_iter.setCheckState(1)
        self.rgd_pnt_mass.setCheckState(1)
        self.scale_rel.setCheckState(1)
        self.dyncnstrnt_exc.setCheckState(1)
        self.dyncnstrnt_cmp.setCheckState(1)
        self.clth_enable.setCheckState(1)

    def _check_none(self):
        self.checkRange.setCheckState(0)
        self.nuc_strt.setCheckState(0)
        self.clth_enable.setCheckState(0)
        self.nuc_enable.setCheckState(0)
        self.space_scale.setCheckState(0)
        self.nuc_subs.setCheckState(0)
        self.coll_iter.setCheckState(0)
        self.rgd_pnt_mass.setCheckState(0)
        self.scale_rel.setCheckState(0)
        self.dyncnstrnt_exc.setCheckState(0)
        self.dyncnstrnt_cmp.setCheckState(0)
        self.trap_check.setCheckState(0)
Beispiel #23
0
class StatusBar(QStatusBar):
    def __init__(self):
        QStatusBar.__init__(self)
        self.editor = None

        self.widgetStatus = QWidget()
        vbox = QVBoxLayout(self.widgetStatus)
        vbox.setContentsMargins(0, 0, 0, 0)
        #Search Layout
        hSearch = QHBoxLayout()
        self.line = TextLine(self)
        self.line.setMinimumWidth(250)
        self.checkBackward = QCheckBox('Find Backward')
        self.checkSensitive = QCheckBox('Respect Case Sensitive')
        self.checkWholeWord = QCheckBox('Find Whole Words')
        self.btnClose = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btnFind = QPushButton(QIcon(resources.images['find']), '')
        self.btnPrevious = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowLeft), '')
        self.btnNext = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowRight), '')
        hSearch.addWidget(self.btnClose)
        hSearch.addWidget(self.line)
        hSearch.addWidget(self.btnFind)
        hSearch.addWidget(self.btnPrevious)
        hSearch.addWidget(self.btnNext)
        hSearch.addWidget(self.checkBackward)
        hSearch.addWidget(self.checkSensitive)
        hSearch.addWidget(self.checkWholeWord)
        vbox.addLayout(hSearch)
        #Replace Layout
        hReplace = QHBoxLayout()
        self.lineReplace = TextLine(self)
        self.lineReplace.setMinimumWidth(250)
        self.btnCloseReplace = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btnReplace = QPushButton('Replace')
        self.btnReplaceAll = QPushButton('Replace All')
        hReplace.addWidget(self.btnCloseReplace)
        hReplace.addWidget(self.lineReplace)
        hReplace.addWidget(self.btnReplace)
        hReplace.addWidget(self.btnReplaceAll)
        vbox.addLayout(hReplace)
        self.replace_visibility(False)

        self.addWidget(self.widgetStatus)

        self.shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self)

        self.connect(self.btnClose, SIGNAL("clicked()"), self.hide_status)
        self.connect(self.btnFind, SIGNAL("clicked()"), self.find)
        self.connect(self.btnNext, SIGNAL("clicked()"), self.find_next)
        self.connect(self.btnPrevious, SIGNAL("clicked()"), self.find_previous)
        self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end)
        self.connect(self.btnCloseReplace, SIGNAL("clicked()"),
                     lambda: self.replace_visibility(False))
        self.connect(self.btnReplace, SIGNAL("clicked()"), self.replace)
        self.connect(self.btnReplaceAll, SIGNAL("clicked()"), self.replace_all)
        self.connect(self.shortEsc, SIGNAL("activated()"), self.hide_status)

    def focus_find(self, editor):
        self.line.setFocus()
        self.editor = editor
        self.line.selectAll()

    def replace_visibility(self, val):
        self.lineReplace.setVisible(val)
        self.btnCloseReplace.setVisible(val)
        self.btnReplace.setVisible(val)
        self.btnReplaceAll.setVisible(val)

    def hide_status(self):
        self.checkSensitive.setCheckState(Qt.Unchecked)
        self.checkWholeWord.setCheckState(Qt.Unchecked)
        self.checkBackward.setCheckState(Qt.Unchecked)
        self.hide()
        self.replace_visibility(False)
        if self.editor is not None:
            self.editor.setFocus()

    def replace(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.replace_match(str(self.line.text()),
                                  str(self.lineReplace.text()), s, w)

    def replace_all(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.replace_match(str(self.line.text()),
                                  str(self.lineReplace.text()), s, w, True)

    def find(self):
        b = False if self.checkBackward.checkState() == Qt.Unchecked else True
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.find_match(str(self.line.text()), b, s, w)

    def find_next(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.find_match(str(self.line.text()), False, s, w)

    def find_previous(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.find_match(str(self.line.text()), True, s, w)

    def showMessage(self, message, timeout):
        self.widgetStatus.hide()
        self.replace_visibility(False)
        self.show()
        super(StatusBar, self).showMessage(message, timeout)

    def message_end(self, message):
        if message == '':
            self.hide()
            super(StatusBar, self).clearMessage()
            self.widgetStatus.show()
class VerdictPage(QWidget):
    """
    Verdict Export Page
    """
    ExportResults = pyqtSignal(list, dict) 
    def __init__(self, parent, core, debugMode=False):
        """
        Constructor
        @param parent:
        """
        QWidget.__init__(self, parent)
        self.__core = core
        self.__debugMode = debugMode
        self.__rawXml = ""
        
        self.createWidgets()
        self.creationConnections()
        
        if self.__debugMode:  self.onCheckboxesChanged(toggled=False)

    def core(self):
        """
        """
        return self.__core
        
    def creationConnections (self):
        """
        QtSignals connection:
        """
        self.testsTable.LoadTestcases.connect( self.onLoadTestcases )
        self.testcasesTable.LoadSteps.connect( self.onLoadSteps )
        self.ignoreTestcases.toggled.connect(self.onCheckboxesChanged)
        self.ignoreUncomplete.toggled.connect(self.onCheckboxesChanged)
        self.exportButton.clicked.connect( self.onExportClicked )
        
    def createWidgets(self):
        """
        """
        self.listingTab = QTabWidget()
        self.listingTab.setMinimumWidth(650)
        
        layoutGrid = QGridLayout()
        
        self.testSetPath = QLineEdit()
        self.testSetName = QLineEdit()
        
        self.testsTable = TestsTableView(self, core=self.core())
        self.testcasesTable = TestcasesTableView(self, core=self.core())
        
        self.stepsTable = StepsTableView(self, core=self.core())

        self.listingTab.addTab( self.testsTable, "Test(s)")
        self.listingTab.addTab( self.testcasesTable, "Testcase(s)")
        self.listingTab.addTab( self.stepsTable, "Steps(s)")
        
        self.ignoreTestcases = QCheckBox("Ignore testcase(s)")
        if self.core().settings().cfg()["export-results"]["ignore-testcase"]:
            self.ignoreTestcases.setCheckState(Qt.Checked) 
        
        self.ignoreUncomplete = QCheckBox("Ignore uncomplete result(s)")
        if self.core().settings().cfg()["export-results"]["ignore-uncomplete"]:
            self.ignoreUncomplete.setCheckState(Qt.Checked) 
            
        self.addMissingFoldersCheckBox = QCheckBox(self.tr("Create missing folders"))
        if self.core().settings().cfg()["export-results"]["add-folders"]:
            self.addMissingFoldersCheckBox.setCheckState(Qt.Checked) 
            
        self.addTestsetCheckBox = QCheckBox(self.tr("Create testset"))
        if self.core().settings().cfg()["export-results"]["add-testset"]:
            self.addTestsetCheckBox.setCheckState(Qt.Checked) 
            
        self.addTestinstanceCheckBox = QCheckBox(self.tr("Add test instance in testset"))
        if self.core().settings().cfg()["export-results"]["add-testinstance"]:
            self.addTestinstanceCheckBox.setCheckState(Qt.Checked) 
            
        optionsLayout = QHBoxLayout()
        optionsLayout.addWidget(self.ignoreTestcases)
        optionsLayout.addWidget(self.ignoreUncomplete)
        optionsLayout.addStretch(1)
            
        optionsTsLayout = QHBoxLayout()
        optionsTsLayout.addWidget(self.addTestsetCheckBox)
        optionsTsLayout.addWidget(self.addTestinstanceCheckBox)
        optionsTsLayout.addStretch(1)
        
        layoutGrid.addWidget(QLabel("Remote Test Set Path:"), 0, 0)
        layoutGrid.addWidget(self.testSetPath, 0, 1)
        layoutGrid.addWidget(self.addMissingFoldersCheckBox, 1, 1)
        layoutGrid.addWidget(QLabel("Remote Test Set Name:"), 2, 0)
        layoutGrid.addWidget(self.testSetName, 2, 1)
        layoutGrid.addLayout(optionsTsLayout, 3, 1)
        layoutGrid.addWidget(QLabel("Local result(s):"), 4, 0)
        layoutGrid.addLayout(optionsLayout, 4, 1)
        layoutGrid.addWidget(QLabel("Test(s) Verdict:"), 5, 0)
        layoutGrid.addWidget(self.listingTab, 5, 1)

        self.exportStatusLabel = QLabel( "Status: Disconnected", self)
        self.exportButton = QPushButton(self.tr("Export Result"), self)
        self.exportButton.setMinimumWidth(300)
        
        layoutRight = QHBoxLayout()
        layoutRight.addWidget(self.exportButton)
        layoutRight.addWidget(self.exportStatusLabel)
        layoutRight.addStretch(1)
        
        layoutGrid.addWidget(QLabel("Controls:"), 6, 0)
        layoutGrid.addLayout(layoutRight, 6, 1)
        
        layoutMain = QHBoxLayout()
        layoutMain.addLayout(layoutGrid)

        self.setLayout(layoutMain)
        
    def onExportClicked(self):
        """
        """
        testsetPath = self.testSetPath.text()
        if not len(testsetPath):
            QMessageBox.warning(self, self.tr("Export Result") , 
                                self.tr("Please to specific the remote testset path!") )
            return
        testsetName = self.testSetName.text()
        if not len(testsetName):
            QMessageBox.warning(self, self.tr("Export Result") , 
                                self.tr("Please to specific the remote testset name!") )
            return
        
        testcases = []
        if self.ignoreTestcases.isChecked():
            indexes = self.testsTable.selectionModel().selectedRows()
            if not len(indexes):
                QMessageBox.warning(self, self.tr("Export Result") , 
                                    self.tr("Please to select one test!") )
                return
        
            error = False
            for index in indexes:
                selectedIndex = index.row()
                row = self.testsTable.model.getData()[selectedIndex]
                testcases.append(row)

        else:
            indexes = self.testcasesTable.selectionModel().selectedRows()
            if not len(indexes):
                QMessageBox.warning(self, self.tr("Export Result") , 
                                    self.tr("Please to select one testcase!") )
                return
        
            error = False
            for index in indexes:
                selectedIndex = index.row()
                row = self.testcasesTable.model.getData()[selectedIndex]
                testcases.append(row)

        config = { 
                    "TestSet_Path": testsetPath, 
                    "TestSet_Name": testsetName, 
                    "Add_Folders": self.addMissingFoldersCheckBox.isChecked(),
                    "Add_TestSet": self.addTestsetCheckBox.isChecked(),
                    "Add_TestInstance": self.addTestinstanceCheckBox.isChecked()
                 }
        for cfg in self.core().settings().cfg()["custom-testset-fields"]:
            config.update( {cfg["key"]: cfg["value"] } )
            
        self.disableExport()
        self.ExportResults.emit(testcases, config)
        
    def logStatus(self, status):
        """
        """
        self.exportStatusLabel.setText(status)
        
    def enableExport(self):
        """
        """
        self.exportButton.setEnabled(True)
        
    def disableExport(self):
        """
        """
        self.exportButton.setEnabled(False)
           
    def onCheckboxesChanged(self, toggled):
        """
        """
        if self.ignoreUncomplete.isChecked() or self.ignoreTestcases.isChecked():
            self.testcasesTable.setEnabled(False)
            self.testcasesTable.clear()
            self.stepsTable.setEnabled(False)
            self.stepsTable.clear()
            
        if not self.ignoreTestcases.isChecked():
            self.testcasesTable.setEnabled(True)
            self.stepsTable.setEnabled(True)

        # reload data
        if self.__debugMode: 
            self.readXml(rawXml=VERDICT_EXAMPLE)
        else:
            self.readXml(rawXml=self.__rawXml)
        
    def clearTables(self):
        """
        Clear all tables
        """
        self.stepsTable.clear()
        self.testcasesTable.clear()
        self.testsTable.clear()
        
    def onLoadSteps(self, steps):
        """
        """
        self.stepsTable.loadTable(data=steps)

    def onLoadTestcases(self, testcases):
        """
        """
        if self.ignoreTestcases.isChecked():
            return
            
        self.stepsTable.clear()
        self.testcasesTable.loadTable(data=testcases)
        
    def onLoadTests(self, data):
        """
        """
        # clear the table before to start
        self.clearTables()
        
        # load tables according to the data provided
        self.testsTable.loadTable(data=data)

    def convertResult(self, result):
        """
        """
        if result == "PASS":
            return QC_PASSED
        elif result == "FAIL":
            return QC_FAILED
        else:
            return QC_UNCOMPLETED
        
    def readXml(self, rawXml):
        """
        """
        # init and save the xml provided
        self.__rawXml = rawXml
        try:
            root = ET.fromstring(rawXml)
        except Exception as e:
            self.core().debug().addLogError("Unable to read xml: %s"  % e )
        else:
            tests = []
            testsVerdict = root.find(".")
            
            testPath = testsVerdict.attrib["path"]
            testProject = testsVerdict.attrib["project"]
            testName = testsVerdict.attrib["name"]
            self.testSetPath.setText(testPath)
            self.testSetName.setText(testName)
            
            # read all tests
            testsName = {}
            for ts in testsVerdict:
                if ts.attrib["status"] in  [ "not-executed", "disabled" ]:
                    continue
                    
                tcs = ts.findall("testcase")
                if len(tcs) and self.ignoreTestcases.isChecked():
                    continue
                    
                tsName = ts.attrib["name"]
                tsName = tsName.strip()
                
                if tsName not in testsName: 
                    testsName[tsName] = 1
                else:
                    testsName[tsName] += 1
                ts_result = self.convertResult(ts.attrib["result"]) 
                if self.ignoreUncomplete.isChecked():
                    if ts_result == QC_UNCOMPLETED:
                        continue
                    
                testname_instance = "[%s]%s" % (testsName[tsName], tsName)
                if self.core().settings().cfg()["qc-server"]["use-rest"]:
                    testname_instance = "%s [%s]" % (tsName, testsName[tsName])
                test = { 
                        "name": testname_instance, 
                        "result": ts_result,
                        "testpath": ts.attrib["path"],
                        "testname": tsName
                       }
                # read all testcases
                testcases = []
                tcsName = {}
                for tc in tcs:
                    tcName = tc.attrib["name"]
                    
                    # read all steps
                    stepsVerdict = tc.findall("step")
                    steps = []
                    for stp in stepsVerdict:
                        steps.append( {"result": self.convertResult(stp.attrib["result"]), 
                                        "actual": stp.attrib["actual"] } )
                        
                    if tcName not in tcsName: 
                        tcsName[tcName] = 1
                    else:
                        tcsName[tcName] += 1
                    tc_result = self.convertResult(tc.attrib["result"])
                    testcases.append( {"name": "[%s]%s" % (tcsName[tcName], tcName), 
                                        "result": tc_result, 
                                        "steps": steps})
                
                test.update({"testcases": testcases})
                tests.append(test)
            self.core().debug().addLogSuccess("Export results detected: %s"  % len(tests) )
            if len(tests): self.onLoadTests(data=tests)
Beispiel #25
0
class TabGeneral(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        v_box = QVBoxLayout(self)
        self.setFixedWidth(500)
        self.settings = QSettings('NINJA-IDE', 'Kunai')

        #Groups
        self.gbox_Home = QGroupBox('On Start:')
        self.gbox_Close = QGroupBox("On Close:")
        self.gbox_Routes = QGroupBox('Routes:')

        v_box.addWidget(self.gbox_Home)
        v_box.addWidget(self.gbox_Close)
        v_box.addWidget(self.gbox_Routes)

        self.settings.beginGroup('Preferences')
        self.settings.beginGroup('General')
        #Home
        #Layout
        v_home = QVBoxLayout()
        ##CheckBox
        self.ch_lastSesionFiles = QCheckBox('Load files from last session.')
        self.ch_lastSesionFiles.setCheckState(
            self.settings.value('load_files', 2).toInt()[0])
        self.ch_activatePlugins = QCheckBox('Activate Plugins.')
        self.ch_activatePlugins.setCheckState(
            self.settings.value('activate_plugins', 2).toInt()[0])
        self.ch_notifyUpdates = QCheckBox(
            'Nofity me for new available updates.')
        self.ch_notifyUpdates.setCheckState(
            self.settings.value('notify_updates', 0).toInt()[0])
        v_home.addWidget(self.ch_lastSesionFiles)
        v_home.addWidget(self.ch_activatePlugins)
        v_home.addWidget(self.ch_notifyUpdates)
        self.gbox_Home.setLayout(v_home)

        #Close
        #Layout
        v_close = QVBoxLayout()
        ##CheckBox
        self.ch_saveState = QCheckBox('Save the window position and geometry.')
        self.ch_saveState.setCheckState(
            self.settings.value('save_position_geometry', 0).toInt()[0])
        self.ch_confirmExit = QCheckBox('Confirm Exit.')
        self.ch_confirmExit.setCheckState(
            self.settings.value('confirm_exit', 2).toInt()[0])
        v_close.addWidget(self.ch_saveState)
        v_close.addWidget(self.ch_confirmExit)
        self.gbox_Close.setLayout(v_close)

        #Routes
        #Layout
        g_routes = QGridLayout()
        ##TextBox
        self.txt_startRoute = QLineEdit()
        self.txt_startRoute.setText(
            self.settings.value('start_route', '').toString())
        self.txt_projectRoute = QLineEdit()
        self.txt_projectRoute.setText(
            self.settings.value('project_route', '').toString())
        self.txt_xtraPlugins = QLineEdit()
        self.txt_xtraPlugins.setText(
            self.settings.value('extra_plugins_route', '').toString())
        ##Button
        self.btn_startRoute = QPushButton(
            QIcon(resources.images['openFolder']), '')
        self.btn_projectRoute = QPushButton(
            QIcon(resources.images['openFolder']), '')
        self.btn_xtraPlugins = QPushButton(
            QIcon(resources.images['openFolder']), '')

        def load_start_route():
            self.txt_startRoute.setText(load_directory(self, 'Start Route'))

        def load_project_route():
            self.txt_projectRoute.setText(load_directory(
                self, 'Project Route'))

        def load_xtra_plugins_route():
            self.txt_xtraPlugins.setText(
                load_directory(self, 'Extra Plugins Route'))

        self.settings.endGroup()  #End General Preferences
        self.settings.endGroup()

        #Signal
        self.connect(self.btn_startRoute, SIGNAL('clicked()'),
                     load_start_route)
        self.connect(self.btn_projectRoute, SIGNAL('clicked()'),
                     load_project_route)
        self.connect(self.btn_xtraPlugins, SIGNAL('clicked()'),
                     load_xtra_plugins_route)

        g_routes.addWidget(QLabel('Start Route:'), 0, 0, Qt.AlignRight)
        g_routes.addWidget(QLabel('Project Files:'), 1, 0, Qt.AlignRight)
        #g_routes.addWidget(QLabel('Extra Plugins Route:'), 2, 0, Qt.AlignRight)
        g_routes.addWidget(self.txt_startRoute, 0, 1)
        g_routes.addWidget(self.txt_projectRoute, 1, 1)
        #g_routes.addWidget(self.txt_xtraPlugins, 2 ,1)
        g_routes.addWidget(self.btn_startRoute, 0, 2)
        g_routes.addWidget(self.btn_projectRoute, 1, 2)
        #g_routes.addWidget(self.btn_xtraPlugins, 2, 2)

        self.gbox_Routes.setLayout(g_routes)

    def save_state(self):
        self.settings.beginGroup('Preferences')
        self.settings.beginGroup('General')

        #CheckBox
        self.settings.setValue('load_files',
                               self.ch_lastSesionFiles.checkState())
        self.settings.setValue('activate_plugins',
                               self.ch_activatePlugins.checkState())
        self.settings.setValue('save_position_geometry',
                               self.ch_saveState.checkState())
        self.settings.setValue('confirm_exit',
                               self.ch_confirmExit.checkState())
        self.settings.setValue('notify_updates',
                               self.ch_notifyUpdates.checkState())

        #TextBox
        self.settings.setValue('start_route', self.txt_startRoute.text())
        self.settings.setValue('project_route', self.txt_projectRoute.text())
        self.settings.setValue('extra_plugins_route',
                               self.txt_xtraPlugins.text())

        self.settings.endGroup()  #End General Preferences
        self.settings.endGroup()
class WellExportDialog(QDialog):
    def __init__(self):
        super(WellExportDialog, self).__init__()
        self.resize(400, 300)
        self.initUI()
        self.export_Button.clicked.connect(self.export_well)
        self.button_box.rejected.connect(self.close)
        self.select_Button.clicked.connect(self.select_file)
        self.well_comboBox.currentIndexChanged.connect(
            self.populate_log_listWidget)

        self.update_well_comboBox()

    def initUI(self):
        self.setWindowIcon(QIcon(':/icon/export'))
        self.setWindowTitle("Export Well")
        self.layout = QGridLayout(self)
        # add QLabel
        self.label_0 = QLabel(self)
        self.label_0.setGeometry(QRect(0, 24, 31, 20))
        self.label_0.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)
        self.label_0.setText("Well to export:")
        self.layout.addWidget(self.label_0, 0, 0)
        # add QComboBox
        self.well_comboBox = QComboBox(self)
        self.well_comboBox.setGeometry(QRect(10, 10, 101, 24))
        self.layout.addWidget(self.well_comboBox, 0, 1, 1, 1)
        # add QCheckBox
        self.checkbox = QCheckBox(self)
        self.checkbox.setText("Full LAS")
        self.checkbox.setCheckState(Qt.Unchecked)
        self.layout.addWidget(self.checkbox, 0, 2)
        # add QListWidget
        self.logs_listWidget = QListWidget(self)
        self.logs_listWidget.setGeometry(QRect(0, 0, 101, 201))
        # self.well_comboBox.setMaximumHeight(151)
        self.layout.addWidget(self.logs_listWidget, 1, 1)
        # add QLabel
        self.label_1 = QLabel(self)
        self.label_1.setGeometry(QRect(0, 24, 31, 20))
        self.label_1.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)
        self.label_1.setText("Output File:")
        self.layout.addWidget(self.label_1, 2, 0)
        # add QLineEdit
        self.file_path_lineEdit = QLineEdit(self)
        self.file_path_lineEdit.setGeometry(QRect(50, 24, 81, 20))
        self.layout.addWidget(self.file_path_lineEdit, 2, 1)
        # add Button
        self.select_Button = QPushButton(self)
        self.select_Button.setMaximumSize(QSize(61, 24))
        self.select_Button.setText("Select")
        self.layout.addWidget(self.select_Button, 2, 2)
        # add QDialogButtonBox
        self.button_box = QDialogButtonBox(self)
        self.export_Button = self.button_box.addButton(
            "Export", QDialogButtonBox.ApplyRole)
        self.button_box.addButton(QDialogButtonBox.Cancel)
        self.layout.addWidget(self.button_box, 3, 0, 1, 3)

    def update_well_comboBox(self):
        survey_file = CONF.survey_dir / '.survey'
        if survey_file.exists():
            dnames = get_data_files(CONF.well_dir)
            self.well_comboBox.addItems(dnames)

    def populate_log_listWidget(self):
        self.logs_listWidget.clear()
        well = ppp.Well(
            str(CONF.well_dir /
                ".{}".format(self.well_comboBox.currentText())))
        # self.logs_listWidget.addItems(well.logs)
        for name in well.logs:
            new_item = QListWidgetItem(name, self.logs_listWidget)
            new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
            new_item.setCheckState(Qt.Unchecked)

    def export_well(self):
        file_name = str(self.file_path_lineEdit.text())
        if not file_name:
            QMessageBox().information(self, "Info",
                                      "Please select ouput file.")
            pass
        else:
            well = well = ppp.Well(
                str(CONF.well_dir /
                    ".{}".format(self.well_comboBox.currentText())))
            logs_to_export = []
            for i in range(self.logs_listWidget.count()):
                item = self.logs_listWidget.item(i)
                if item.checkState() == Qt.Checked:
                    logs_to_export.append(str(item.text()))
            full = True if self.checkbox.checkState() == Qt.Checked \
                else False
            well.export(file_name, logs_to_export, full)
            QMessageBox().information(self, "Info", "Succeed!")

    def select_file(self):
        fl = QFileDialog.getSaveFileName(self, 'Save File', str(CONF.well_dir))
        self.file_path_lineEdit.setText(fl)
Beispiel #27
0
class FindReplace(QWidget):
    """
    Find widget
    """
    STYLE = {False: "background-color:rgb(255, 175, 90);",
             True: ""}
    def __init__(self, parent, enable_replace=False):
        QWidget.__init__(self, parent)
        self.enable_replace = enable_replace
        self.editor = None
        
        glayout = QGridLayout()
        glayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(glayout)
        
        self.close_button = create_toolbutton(self, triggered=self.hide,
                                      icon=get_std_icon("DialogCloseButton"))
        glayout.addWidget(self.close_button, 0, 0)
        
        # Find layout
        self.search_text = PatternComboBox(self, tip=self.tr("Search string"),
                                           adjust_to_minimum=False)
        self.connect(self.search_text, SIGNAL("editTextChanged(QString)"),
                     self.text_has_changed)
        
        self.previous_button = create_toolbutton(self,
                                             text=self.tr("Previous"),
                                             triggered=self.find_previous,
                                             icon=get_std_icon("ArrowBack"))
        self.next_button = create_toolbutton(self,
                                             text=self.tr("Next"),
                                             triggered=self.find_next,
                                             icon=get_std_icon("ArrowForward"))
        self.connect(self.next_button, SIGNAL('clicked()'),
                     self.update_search_combo)
        self.connect(self.previous_button, SIGNAL('clicked()'),
                     self.update_search_combo)

        self.case_check = QCheckBox(self.tr("Case Sensitive"))
        self.connect(self.case_check, SIGNAL("stateChanged(int)"), self.find)
        self.words_check = QCheckBox(self.tr("Whole words"))
        self.connect(self.words_check, SIGNAL("stateChanged(int)"), self.find)

        hlayout = QHBoxLayout()
        self.widgets = [self.close_button, self.search_text, self.previous_button,
                        self.next_button, self.case_check, self.words_check]
        for widget in self.widgets[1:]:
            hlayout.addWidget(widget)
        glayout.addLayout(hlayout, 0, 1)

        # Replace layout
        replace_with1 = QLabel(self.tr("Replace"))
        replace_with2 = QLabel()
        font = replace_with2.font()
        font.setBold(True)
        replace_with2.setFont(font)
        replace_with3 = QLabel(self.tr("with:"))
        self.replace_text = PatternComboBox(self, adjust_to_minimum=False,
                                            tip=self.tr("Replace string"))
        
        self.replace_button = create_toolbutton(self,
                                     text=self.tr("Replace/find"),
                                     triggered=self.replace_find,
                                     icon=get_std_icon("DialogApplyButton"))
        self.connect(self.replace_button, SIGNAL('clicked()'),
                     self.update_replace_combo)
        self.connect(self.replace_button, SIGNAL('clicked()'),
                     self.update_search_combo)
        
        self.all_check = QCheckBox(self.tr("Replace all"))
        
        self.replace_layout = QHBoxLayout()
        widgets = [replace_with1, replace_with2, replace_with3,
                   self.replace_text, self.replace_button, self.all_check]
        for widget in widgets:
            self.replace_layout.addWidget(widget)
        self.connect(self.search_text, SIGNAL("editTextChanged(QString)"),
                     replace_with2, SLOT("setText(QString)"))
        glayout.addLayout(self.replace_layout, 1, 1)
        self.widgets.extend(widgets)
        self.replace_widgets = widgets
        self.hide_replace()
        
        self.search_text.setTabOrder(self.search_text, self.replace_text)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
    def update_search_combo(self):
        self.search_text.lineEdit().emit(SIGNAL('returnPressed()'))
        
    def update_replace_combo(self):
        self.replace_text.lineEdit().emit(SIGNAL('returnPressed()'))
        
    def keyPressEvent(self, event):
        """Reimplemented to handle key events"""
        ctrl = event.modifiers() & Qt.ControlModifier
        if event.key() == Qt.Key_Escape:
            self.hide()
            event.accept()
            return
        elif event.key() == Qt.Key_F3:
            # Find next
            self.find_next()
            event.accept()
        elif event.key() == Qt.Key_F and ctrl:
            # Toggle find widgets
            if self.isVisible():
                self.hide()
            else:
                self.show()
            event.accept()
        elif event.key() == Qt.Key_H and ctrl and self.enable_replace:
            # Toggle replace widgets
            if self.replace_widgets[0].isVisible():
                self.hide_replace()
                self.hide()
            else:
                self.show_replace()
                self.replace_text.setFocus()
            event.accept()
        else:
            event.ignore()
        
    def show(self):
        """Overrides Qt Method"""
        QWidget.show(self)
        if self.editor is not None:
            text = self.editor.selectedText()
            if len(text)>0:
                self.search_text.setEditText(text)
                self.search_text.lineEdit().selectAll()
                self.refresh()
            else:
                self.search_text.lineEdit().selectAll()
        
    def hide(self):
        """Overrides Qt Method"""
        for widget in self.replace_widgets:
            widget.hide()
        QWidget.hide(self)
        if self.editor is not None:
            self.editor.setFocus()
        
    def show_replace(self):
        """Show replace widgets"""
        for widget in self.replace_widgets:
            widget.show()
            
    def hide_replace(self):
        """Hide replace widgets"""
        for widget in self.replace_widgets:
            widget.hide()
        
    def refresh(self):
        """Refresh widget"""
        if self.isHidden():
            return
        state = self.editor is not None
        for widget in self.widgets:
            widget.setEnabled(state)
        if state:
            self.find()
            
    def set_editor(self, editor, refresh=True):
        """Set parent editor"""
        self.editor = editor
        if refresh:
            self.refresh()
        
    def find_next(self):
        """Find next occurence"""
        self.find(changed=False, forward=True)
        
    def find_previous(self):
        """Find previous occurence"""
        self.find(changed=False, forward=False)
        
    def text_has_changed(self, text):
        """Find text has changed"""
        self.find(changed=True, forward=True)
        
    def find(self, changed=True, forward=True):
        """Call the find function"""
        text = self.search_text.currentText()
        if len(text)==0:
            self.search_text.lineEdit().setStyleSheet("")
            return None
        else:
            found = self.editor.find_text(text, changed, forward,
                                          case=self.case_check.isChecked(),
                                          words=self.words_check.isChecked())
            self.search_text.lineEdit().setStyleSheet(self.STYLE[found])
            return found
            
    def replace_find(self):
        """Replace and find"""
        if (self.editor is not None):
            replace_text = self.replace_text.currentText()
            first = True
            while True:
                if first:
                    # First found
                    if self.editor.hasSelectedText() \
                       and self.editor.selectedText() == self.search_text.currentText():
                        # Text was already found, do nothing
                        pass
                    else:
                        self.find(changed=False, forward=True)
                    first = False
                    wrapped = False
                    position = self.editor.get_position('cursor')
                    position0 = position
                else:
                    position1 = self.editor.get_position('cursor')
                    if position1 == position0:
                        # Avoid infinite loop: single found occurence
                        break
                    if self.editor.compare_position_inf(position1, position0):
                        wrapped = True
                    if wrapped:
                        if self.editor.compare_position_sup(position0, position):
                            # Avoid infinite loop: replace string includes
                            # part of the search string
                            break
                    position0 = position1
                
                self.editor.replace(replace_text)
                self.find_next()
                if not self.all_check.isChecked():
                    break
            self.all_check.setCheckState(Qt.Unchecked)
            
Beispiel #28
0
class WizardDialog(QDialog):
    """The dialog for update."""
    def __init__(self, main_window):
        super(WizardDialog, self).__init__()
        self.mw = main_window
        vbox = QVBoxLayout(self)

        # label and checkbox
        self.main_text = QLabel(u"init text")
        vbox.addWidget(self.main_text)
        self.notthisagain = QCheckBox(u"No mostrar automáticamente esta ayuda")
        nowizard = config.get('nowizard', False)
        self.notthisagain.setCheckState(nowizard)
        self.notthisagain.stateChanged.connect(self._notthisagain_toggled)
        vbox.addWidget(self.notthisagain)

        # buttons
        bbox = QDialogButtonBox()
        self.navbut_actn = QPushButton(u"init text")
        bbox.addButton(self.navbut_actn, QDialogButtonBox.ActionRole)
        self.navbut_prev = QPushButton(u"Anterior")
        bbox.addButton(self.navbut_prev, QDialogButtonBox.ActionRole)
        self.navbut_next = QPushButton(u"Siguiente")
        bbox.addButton(self.navbut_next, QDialogButtonBox.ActionRole)
        vbox.addWidget(bbox)

        self.show()
        self.step = 0
        self._move(0)

    def _notthisagain_toggled(self, state):
        """The "not this again" checkbutton togled state."""
        logger.info("Configuring 'nowizard' to %s", state)
        config['nowizard'] = state

    def _move(self, delta_step):
        """The engine for the wizard steps."""
        self.step += delta_step
        logger.debug("Entering into step %d", self.step)
        (text, ign_func, act_label, act_func) = STEPS[self.step]
        # if this step should be ignored, just leave
        if ign_func is not None:
            m = getattr(self, "_ign_" + ign_func)
            if m():
                # keep going
                return self._move(delta_step)

        # adjust navigation buttons
        if self.step == 0:
            self.navbut_prev.setEnabled(False)
            self.navbut_next.setText(u"Siguiente")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(lambda: self._move(1))
            self.notthisagain.show()
        elif self.step == len(STEPS) - 1:
            self.navbut_prev.setEnabled(True)
            self.navbut_prev.clicked.disconnect()
            self.navbut_prev.clicked.connect(lambda: self._move(-1))
            self.navbut_next.setText(u"Terminar")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(self.accept)
            self.notthisagain.hide()
        else:
            self.navbut_prev.setEnabled(True)
            self.navbut_prev.clicked.disconnect()
            self.navbut_prev.clicked.connect(lambda: self._move(-1))
            self.navbut_next.setText(u"Siguiente")
            self.navbut_next.clicked.disconnect()
            self.navbut_next.clicked.connect(lambda: self._move(1))
            self.notthisagain.hide()

        # adjust main text and action button
        if self.step == len(STEPS) - 1:
            if self.mw.have_metadata() and self.mw.have_config():
                self.main_text.setText(TEXT_HAPPY_END)
            else:
                self.main_text.setText(TEXT_SAD_END)
        else:
            self.main_text.setText(text)

        if act_label is None:
            self.navbut_actn.hide()
        else:
            self.navbut_actn.show()
            self.navbut_actn.setText(act_label)
            method_to_call = getattr(self, "_act_" + act_func)
            self.navbut_actn.clicked.disconnect()
            self.navbut_actn.clicked.connect(method_to_call)

    def _act_configure(self, _):
        """Open the config dialog."""
        self.mw.open_preferences()

    def _act_update(self, *a):
        """Open the update dialog."""
        self.mw.refresh_episodes()

    def _ign_episode(self):
        """Tell if the episode step should be ignored."""
        return self.mw.have_metadata()

    def _ign_config(self):
        """Tell if the configure step should be ignored."""
        return self.mw.have_config()
class FindReplace(QWidget):
    """
    Find replace widget bar
    """
    NbReplaced = pyqtSignal(int)

    def __init__(self, parent=None):
        """
        This class provides an graphical interface to find and replace text

        @param parent: 
        @type parent:
        """
        QWidget.__init__(self, parent)
        self.editor = None
        self.styleEdit = {
            False: "background-color:rgb(255, 175, 90);",
            True: ""
        }

        self.createButton()
        self.createWidgets()
        self.createConnections()

    def showEnhanced(self, textSelected=''):
        """
        Show enhanced (focus and text selected)
        """
        self.show()
        if len(textSelected): self.edit.setEditText(textSelected)
        self.edit.setFocus()
        self.edit.lineEdit().selectAll()

    def createButton(self):
        """
        create qt buttons
        Buttons defined:
         * Previous
         * Next
         * Replace
        """
        self.previousButton = QtHelper.createButton(
            self,
            text=self.tr("Find Previous"),
            triggered=self.findPrevious,
            icon=QIcon(":/find_previous.png"))
        self.nextButton = QtHelper.createButton(self,
                                                text=self.tr("Find Next"),
                                                triggered=self.findNext,
                                                icon=QIcon(":/find_next.png"))
        self.replaceButton = QtHelper.createButton(self,
                                                   text=self.tr("Replace..."),
                                                   triggered=self.replaceFind,
                                                   icon=QIcon(":/replace.png"))

    def createWidgets(self):
        """
        QtWidgets creation

        QHBoxLayout
         -------------------------------------------.....
        | QLabel: QLineEdit QButton QButton QCheckBox |
         -------------------------------------------.....

        ....--------------------------------------
             QLabel: QLineEdit QButton QCheckBox |
        ....--------------------------------------
        """
        glayout = QGridLayout()

        self.edit = QLineEditMore(parent=self)
        self.edit.setEditable(1)
        self.edit.setMaxCount(10)
        self.edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.edit.lineEdit().setPlaceholderText("Search text in your test?")
        self.edit.setMinimumWidth(200)

        self.replaceEdit = QComboBox(self)
        self.replaceEdit.setEditable(1)
        self.replaceEdit.setMaxCount(10)
        self.replaceEdit.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        self.replaceEdit.lineEdit().setPlaceholderText(
            "Replace the text with?")
        self.replaceEdit.setMinimumWidth(200)

        self.caseCheck = QCheckBox(self.tr("Case Sensitive"))
        self.caseCheck.setChecked(
            QtHelper.str2bool(Settings.instance().readValue(
                key='Editor/find-case-sensitive')))
        self.caseWordCheck = QCheckBox(self.tr("Whole word only"))
        self.caseWordCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/find-whole-word')))
        self.allCheck = QCheckBox(self.tr("All occurences"))
        self.allCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/replace-all')))
        self.caseRegexpCheck = QCheckBox(self.tr("Regular expression"))
        self.caseRegexpCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/find-regexp')))
        self.caseWrapCheck = QCheckBox(self.tr("Wrap at the end"))
        self.caseWrapCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/find-wrap')))

        glayout.addWidget(self.edit, 0, 1)
        glayout.addWidget(self.nextButton, 0, 3)
        glayout.addWidget(self.previousButton, 0, 2)
        glayout.addWidget(self.caseCheck, 2, 2)
        glayout.addWidget(self.caseWrapCheck, 2, 3)
        glayout.addWidget(self.caseWordCheck, 3, 2)
        glayout.addWidget(self.caseRegexpCheck, 3, 3)

        glayout.addWidget(self.replaceEdit, 1, 1)
        glayout.addWidget(self.replaceButton, 1, 2)
        glayout.addWidget(self.allCheck, 1, 3)

        self.previousButton.setDisabled(True)
        self.nextButton.setDisabled(True)

        self.setLayout(glayout)

        flags = Qt.WindowFlags()
        flags |= Qt.Window
        flags |= Qt.WindowTitleHint
        flags |= Qt.WindowCloseButtonHint
        flags |= Qt.MSWindowsFixedSizeDialogHint
        self.setWindowFlags(flags)

        self.setWindowIcon(QIcon(":/main.png"))
        self.setWindowTitle("Find And Replace")

    def createConnections(self):
        """
        create qt connection
        """
        self.edit.editTextChanged.connect(self.textHasChanged)
        self.edit.EnterPressed.connect(self.returnPressed)
        self.caseCheck.stateChanged.connect(self.find)

    def returnPressed(self):
        """
        Return key pressed
        Find next in this case
        """
        self.findNext()

    def setEditor(self, editor):
        """
        Set the target to find the text

        @param editor: 
        @type editor:   
        """
        self.editor = editor

    def textHasChanged(self, txt):
        """
        Find text has changed
        """
        text = self.edit.currentText()
        if len(text) > 0:
            self.previousButton.setEnabled(True)
            self.nextButton.setEnabled(True)
            self.find(changed=True, forward=True)
        else:
            self.previousButton.setDisabled(True)
            self.nextButton.setDisabled(True)

    def updateComboBox(self):
        """
        Update combobox
        """
        comboUpdated = False
        for i in range(self.edit.count()):
            if self.edit.itemText(i) == self.edit.currentText():
                comboUpdated = True
        if not comboUpdated:
            self.edit.addItem(self.edit.currentText())

        comboUpdated = False
        for i in range(self.replaceEdit.count()):
            if self.replaceEdit.itemText(i) == self.replaceEdit.currentText():
                comboUpdated = True
        if not comboUpdated:
            self.replaceEdit.addItem(self.replaceEdit.currentText())

    def clearText(self):
        """
        Clear all QlineEdit
        """
        self.edit.setStyleSheet("")

        self.edit.clearEditText()

        self.replaceEdit.clearEditText()

    def findPrevious(self):
        """
        Find previous occurence
        """
        # update combobox
        self.updateComboBox()

        # find previous
        self.find(changed=False, forward=False)

    def findNext(self, line=-1, index=-1):
        """
        Find next occurence
        """
        # update combobox
        self.updateComboBox()

        return self.find(changed=False, forward=True, line=line, index=index)

    def find(self, changed=True, forward=True, line=-1, index=-1):
        """
        Call the find function

        @param changed: 
        @type changed: boolean  

        @param forward: 
        @type forward: boolean      
        """
        text = self.edit.currentText()
        if len(text) == 0:
            self.edit.setStyleSheet("")
            return None
        else:
            found = self.editor.findText(
                text,
                changed,
                forward,
                case=self.caseCheck.isChecked(),
                words=self.caseWordCheck.isChecked(),
                regexp=self.caseRegexpCheck.isChecked(),
                wraps=self.caseWrapCheck.isChecked(),
                line=line,
                index=index)
            self.edit.setStyleSheet(self.styleEdit[found])
            return found

    def replaceFind(self):
        """
        Replace and find
        """
        if (self.editor is None): return

        replaceText = self.replaceEdit.currentText()
        searchText = self.edit.currentText()
        if not self.caseCheck.isChecked(): searchText = searchText.lower()
        current = -1
        nbReplaced = 0

        # find the first occurence from the beginning of the doc or not
        if not self.allCheck.isChecked():
            detected = self.findNext()
        else:
            detected = self.findNext(line=0, index=0)
        (line, _) = self.editor.getCursorPosition()

        while detected:
            previous = current
            selectedText = self.editor.selectedText()

            # normalize the text in lower case if the case sensitive is not activated
            if not self.caseCheck.isChecked():
                selectedText = selectedText.lower()

            # replace the selection
            if self.editor.hasSelectedText() and selectedText == searchText:
                self.editor.replace(replaceText)
                nbReplaced += 1

            # find the next occurence of the word
            detected = self.findNext()
            (current, _) = self.editor.getCursorPosition()

            # all doc readed ? break the loop
            if previous > current: break
            if current == line and previous != -1: break

            # just execute one replace
            if not self.allCheck.isChecked(): break

        self.allCheck.setCheckState(Qt.Unchecked)
        self.NbReplaced.emit(nbReplaced)
class CheckTrait(QWidget):
	"""
	\brief An- bzw. Abwählbare Eigenschaft.

	Diese Eigensachft ist ähnlich wie CharaTrait mit den Eigenschaften im Speicher verknpüft, allerdings besitzen sie keine Werte, sondern sind nur an- oder Abwählbar. Beispiel für eine solche Eigenscahft sind die Nachteile.
	"""

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

		self.__trait = trait

		#character = StorageCharacter::getInstance();

		self.__layout = QHBoxLayout()
		self.setLayout( self.__layout )

		self.__checkBox = QCheckBox()
		self.__checkBox.setText( trait.name )
		self.__checkBox.setMaximumHeight( Config.WIDGET_INLINE_HEIGHT_MAX )

		self.__lineEdit = QLineEdit()
		#self.__lineEdit.setMinimumWidth( Config.TRAIT_CUSTOMTEXT_WIDTH_MIN )
		self.__lineEdit.setMaximumHeight(Config.WIDGET_INLINE_HEIGHT_MAX)

		self.__layout.addWidget( self.__checkBox )
		self.__layout.addStretch()
		self.__layout.addWidget( self.__lineEdit )

		self.__checkBox.stateChanged.connect(self.setTraitValue)
		self.__lineEdit.textChanged.connect(self.setTraitCustomText)
		self.__trait.valueChanged.connect(self.setValue)
		if type(self.__trait) == StandardTrait:
			self.__trait.customTextChanged.connect(self.setText)
		self.__trait.availableChanged.connect(self.setEnabled)


	def __getValue(self):
		return self.__checkBox.checkState()

	def setValue(self, value):
		if value == 0:
			checkState = Qt.Unchecked
		elif value == 1:
			checkState = Qt.PartiallyChecked
		else:
			checkState = Qt.Checked

		self.__checkBox.setCheckState(checkState)

	value = property(__getValue, setValue)


	def setTraitValue( self, value ):
		"""
		Legt den Wert der Eigenschaft im Speicher fest.
		"""
		
		if ( self.__trait.value != value ):
			self.__trait.value = value


	def setText(self, text):
		"""
		Legt den Zusatztext in diesem Widget fest.
		"""
		
		self.__lineEdit.setText(text)


	def setTraitCustomText( self, text ):
		"""
		Legt den Zusatztext der Eigenschaft im Speicher fest.
		"""
		
		if ( self.__trait.customText != text ):
			self.__trait.customText = text


	def setDescriptionHidden( self, sw ):
		"""
		Mit dieser Methode verstecke ich die Textzeile, in welcher zusätzlicher Beschreibungstext eingegeben werden kann.
		"""

		if ( sw ):
			self.__lineEdit.hide()
		else:
			self.__lineEdit.show()


	def hideOrShowTrait(self, species=None, age=None, era=None, breed=None, faction=None):
		"""
		Versteckt oder zeigt diese Eigenschaft.

		\note age und era gibt es zwar nicht bei SubPowerTrait, aber damit diese Funktion mit StorageCharacter.traitVisibleReasonChanged kompatible bleibt, werden sie als Argument übergeben.
		"""

		visible = True
		# Es können nur Eigenschaften versteckt werden, die einen age- bzw. era-Eintrag besitzen.
		if (
			(species and self.__trait.species and self.__trait.species != species) or
			#(age and self.__trait.age and self.__trait.age != age) or
			#(era and self.__trait.era and era not in self.__trait.era) or
			((breed or faction) and self.__trait.only and breed not in self.__trait.only and faction not in self.__trait.only)
		):
			visible = False

		self.setVisible(visible)
Beispiel #31
0
class NewOrEditUserViewWidget(QDialog, FWidget):

    def __init__(self, pp=None, owner=None, parent=None, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

        self.setWindowTitle(u"Nouvel utilisateur")
        self.parent = parent
        self.pp = pp
        self.owner = owner

        vbox = QVBoxLayout()
        formbox = QFormLayout()
        self.checked = QCheckBox("Active")
        self.error_mssg = ""
        if self.owner:
            self.new = False
            self.title = u"Modification de l'utilisateur {}".format(
                self.owner.username)
            self.succes_msg = u"L'utilisateur a été bien mise à jour"
            if self.owner.isactive:
                self.checked.setCheckState(Qt.Checked)
        else:
            self.checked.setCheckState(Qt.Checked)
            self.new = True
            self.succes_msg = u"L'utilisateur a été bien enregistré"
            self.title = u"Création d'un nouvel utilisateur"
            self.owner = Owner()
        # self.checked.setToolTip(msg)
        self.setWindowTitle(self.title)

        self.username_field = LineEdit(self.owner.username)
        self.username_field.setEnabled(self.new)
        self.password_field = LineEdit()
        self.password_field.setEchoMode(LineEdit.PasswordEchoOnEdit)
        self.password_field_v = LineEdit()
        self.password_field_v.setEchoMode(LineEdit.PasswordEchoOnEdit)
        self.password_field_v.textChanged.connect(
            self.check_password_is_valide)
        self.phone_field = IntLineEdit(self.owner.phone)

        self.liste_group = [Owner.ADMIN, Owner.USER]
        # Combobox widget
        self.box_group = QComboBox()
        for index in self.liste_group:
            self.box_group.addItem(u'%(group)s' % {'group': index})

        butt = Button_save(u"Enregistrer")
        butt.clicked.connect(self.add_or_edit_user)
        cancel_but = Button(u"Annuler")
        cancel_but.clicked.connect(self.cancel)

        formbox.addRow(FLabel(u"Identifiant"), self.username_field)
        formbox.addRow(FLabel(u"Mot de passe"), self.password_field)
        if self.new:
            formbox.addRow(
                FLabel(u"Verification du Mot de passe"), self.password_field_v)
        formbox.addRow(FLabel(u"Numero de Téléphone"), self.phone_field)
        formbox.addRow(FLabel(u"Groupe"), self.box_group)
        formbox.addRow(cancel_but, butt)
        vbox.addWidget(self.checked)
        vbox.addLayout(formbox)
        self.setLayout(vbox)

    def cancel(self):
        self.close()

    def is_valide(self):
        # print("isactive")
        if (check_is_empty(self.username_field)):
            return False
        if (check_is_empty(self.password_field)):
            return False
        if (self.new and check_is_empty(self.password_field_v)):
            return False
        if (not self.check_password_is_valide()):
            return False
        return True

    def check_password_is_valide(self):
        self.password = str(self.password_field.text())
        self.password_v = str(
            self.password_field_v.text()) if self.new else self.owner.password

        if is_valide_codition_field(
                self.password_field_v, "Les mots de passe sont differents" if self.new else "Mot de passe incorrect",
                self.password != self.password_v):
            return
        return True

    def add_or_edit_user(self):
        # print(""" add User """)
        if not self.is_valide():
            print("is not valide")
            return

        username = str(self.username_field.text()).strip()
        password = str(self.password_field.text()).strip()
        phone = str(self.phone_field.text())
        group = self.liste_group[self.box_group.currentIndex()]
        status = False
        if self.checked.checkState() == Qt.Checked:
            status = True

        ow = self.owner
        ow.username = username
        ow.password = Owner().crypt_password(
            password) if self.new else password

        ow.phone = phone
        ow.group = group
        ow.isactive = status
        try:
            ow.save()
            self.close()
            self.accept()
            if self.pp:
                self.pp.refresh_()
                self.parent.Notify("L'identifiant %s a été enregistré" %
                                   ow.username, "success")
        except IntegrityError as e:
            field_error(
                self.name_field, u"L'utilisateurs %s existe déjà dans la base de donnée" % ow.username)
Beispiel #32
0
class BookKeeping(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent);
        # -------------------------------------------------------------------
        self.PARENT                         = _PARENT;
        self.CONF                           = _PARENT.CONF;

        #self.SHA256                         = hashlib.sha256;
        #UID_SHA256 = self.SHA256( str(time.time()) ).hexdigest();
        self.SELECTED_BKKPG_UID             = None;

        # -------------------------------------------------------------------
        self.setGeometry( 3, 5, 975, 555 );
        self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_BookKeeping.png'); }" );

        self.PAIR_COMBO                     = QComboBox( self);
        self.PAIR_COMBO.setGeometry( 86, 20, 108, 44 ); 
        self.connect( self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'), self.CREATE_LISTS );
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False);

        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style                          = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_BookKeeping_line.png'); }"; # ./data/imgs/BookKeeping_line.png
        lable_style                         = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"; 

        # -------------------------------------------------------------------
        self.DATA_TO_SEND                   = None;
        self._i_                            = "|"; # List delimiter
        self.CALCULATE_ONLY_COMPLETED       = True;
        self.DATA_TO_SEND_SELECTED          = False;
        
        # -------------------------------------------------------------------
        self.BOOKKEEPING_WIDGET             = QListWidget( self );
        self.BOOKKEEPING_WIDGET.setGeometry( 13, 144, 949, 259 );
        self.BOOKKEEPING_WIDGET.setStyleSheet( list_style );

        self.connect( self.BOOKKEEPING_WIDGET, SIGNAL('itemSelectionChanged()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET") );
        self.BOOKKEEPING_WIDGET.itemClicked.connect( lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SELECT_VALUES") );


        self.BOUGHT_TTL_LABLE               = QLabel("0.0", self);
        self.BOUGHT_TTL_LABLE.setGeometry( 304, 406, 85, 17 );
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet( lable_style );
        self.BOUGHT_TTL                     = 0;

        self.BOUGHT_TTL_PLUS_FEE_LABLE      = QLabel("0.0", self);
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry( 396, 406, 85, 17 );
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet( lable_style );
        self.BOUGHT_TTL_PLUS_FEE            = 0;


        self.SOLD_TTL_LABLE                 = QLabel("0.0", self);
        self.SOLD_TTL_LABLE.setGeometry( 694, 406, 85, 17 );
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet( lable_style );
        self.SOLD_TTL                       = 0;

        self.SOLD_TTL_PLUS_FEE_LABLE        = QLabel("0.0", self);
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry( 784, 406, 85, 17 );
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet( lable_style );
        self.SOLD_TTL_PLUS_FEE              = 0;

        self.PROFIT_TTL_LABLE               = QLabel("0.0", self);
        self.PROFIT_TTL_LABLE.setGeometry( 874, 406, 88, 17 );
        #self.PROFIT_TTL_LABLE.setEditable( False );
        self.PROFIT_TTL_LABLE.setStyleSheet( lable_style );
        self.PROFIT_TTL                     = 0;

        # -------------------------------------------------------------------
        self.SEND_ID_LABLE                  = QLabel("n/a", self);
        self.SEND_ID_LABLE.setGeometry( 18, 467, 43, 17 );
        self.SEND_ID_LABLE.setStyleSheet( lable_style );

        self.SEND_AMOUNT_LABLE              = QLabel("n/a", self);
        self.SEND_AMOUNT_LABLE.setGeometry( 66, 467, 85, 17 );
        self.SEND_AMOUNT_LABLE.setStyleSheet( lable_style );

        self.SEND_AT_PRICE_LABLE            = QLabel("n/a", self);
        self.SEND_AT_PRICE_LABLE.setGeometry( 156, 467, 43, 17 );
        self.SEND_AT_PRICE_LABLE.setStyleSheet( lable_style );

        self.SEND_VALUES_BTN                = QPushButton("", self); 
        self.SEND_VALUES_BTN.setGeometry( 60, 502, 131, 33 );
        self.SEND_VALUES_BTN.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        self.connect( self.SEND_VALUES_BTN, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );

        # -------------------------------------------------------------------
        self.ONLY_COMPLETED_CHECKBOX        = QCheckBox("", self);
        self.ONLY_COMPLETED_CHECKBOX.setGeometry( 665, 444, 17, 17 );
        self.ONLY_COMPLETED_CHECKBOX.setCheckState(Qt.Checked);
        #self.ONLY_COMPLETED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_COMPLETED_CHECKBOX, SIGNAL('stateChanged(int)'), lambda: self.CHANGE_VALUES("only_completed") );

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR();
            self.CREATE_LISTS();

        except Exception as _exception:

            print("-----------------------------------------------------");
            print("[INIT]"+str(_exception));
        # -------------------------------------------------------------------

    # =======================================================================
    def BKKPG_UID_ACTION(self, _ACTION, BKKPG_UID, _D):

        # -------------------------------------------------------------------
        #print("_ACTION: ", _ACTION, "BKKPG_UID: ", BKKPG_UID)
        # -------------------------------------------------------------------
        try:

            CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower().strip();

            order_id    = _D[0];
            unix_time   = _D[1];
            filled      = _D[2];
            amount      = _D[3];
            at_price    = _D[4];

            if _ACTION == "buy":

                # For CRYPTO
                ttl = amount;
                fee = ( ttl/100*self.PARENT.FEE );
            
            elif _ACTION == "sell":

                # For USD
                ttl = amount*at_price;
                fee = ( ttl/100*self.PARENT.FEE );

            grand_ttl = ttl-fee;

            # -------------------------------------------------------------------
            if BKKPG_UID == "": # Is New Record

                TPL = "buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl ";
                
                _SQL = "INSERT INTO "+CURR_PAIR+"( BKKPG_UID, completed, started, "+TPL+", profit_ttl ) ";

                if _ACTION == "buy":
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format( _D[0],_D[1],_D[2],_D[3],_D[4],fee, ttl, grand_ttl, 0, 0, 0, 0, 0, 0, 0, 0 );

                else:
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format( 0, 0, 0, 0, 0, 0, 0, 0, _D[0], _D[1],_D[2],_D[3],_D[4],fee, ttl, grand_ttl );


                self.PARENT.DB.EXEC("BOOK_DB", _SQL);

            else: # Existing Record

                # ------------------------------------------------
                if filled == 1:

                    completed = 1;

                    _SQL = "SELECT ACT_grand_ttl from "+CURR_PAIR+" WHERE BKKPG_UID="+BKKPG_UID;
                    
                    if _ACTION == "buy":

                        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL.replace("ACT","sell"), ALL=False);
                        profit_ttl = DATA - grand_ttl;

                    else:

                        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL.replace("ACT","buy"), ALL=False);
                        profit_ttl = grand_ttl - DATA;
                else:
                    profit_ttl = 0;
                    completed = 0;

                # ------------------------------------------------
                A = _ACTION;
                
                _SQL = "UPDATE "+CURR_PAIR+" SET completed={0}, "+A+"_order_id={1}, "+A+"_unix_time={2}, "+A+"_filled={3}, ";
                _SQL += A+"_amount={4}, "+A+"_at_price={5}, "+A+"_fee={6}, "+A+"_ttl={7}, "+A+"_grand_ttl={8}";
                _SQL += " WHERE BKKPG_UID="+BKKPG_UID;

                _SQL = _SQL.format( completed, order_id, unix_time, filled, amount, at_price, fee, ttl, grand_ttl );

                self.PARENT.DB.EXEC("BOOK_DB", _SQL);

        except Exception as _exception:

            print(" BOOKKEEPING[0:0]");
            print(_exception);
        # -------------------------------------------------------------------
        """
        BKKPG_UID, completed, started, 
        
        buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, 
        sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl, 
        
        profit_ttl
        """
        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

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

        _SQL = "SELECT buy_order_id, sell_order_id FROM "+_pair;
        _SQL += " WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);

        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False);

        if DATA is None:
            pass;

        if _type == "buy" and DATA[1] == 0:

            _SQL = "DELETE FROM "+_pair+" WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);
            self.PARENT.DB.EXEC("BOOK_DB", _SQL);
            self.CREATE_LISTS();

        elif _type == "sell" and DATA[0] == 0:

            _SQL = "DELETE FROM "+_pair+" WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);
            self.PARENT.DB.EXEC("BOOK_DB", _SQL);
            self.CREATE_LISTS();

        else:

            A = _type;

            _SQL = "UPDATE "+self.PARENT.CURR_PAIR+" SET ";
            _SQL += " completed=0, "+A+"_order_id=0, "+A+"_unix_time=0, "+A+"_filled=0, ";
            _SQL += A+"_amount=0, "+A+"_at_price=0, "+A+"_fee=0, "+A+"_ttl=0, "+A+"_grand_ttl=0 ";
            _SQL += "WHERE "+A+"_order_id="+str(_order_id);

            self.PARENT.DB.EXEC("BOOK_DB", _SQL);

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

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:
            CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();

            # -------------------------------------------------------------------
            self.BOOK = { "bought" : [], "sold" : [] };

            self.BOUGHT_TTL = 0;
            self.BOUGHT_TTL_PLUS_FEE = 0;

            self.SOLD_TTL = 0;
            self.SOLD_TTL_PLUS_FEE = 0;

            # -------------------------------------------------------------------
            #self.PARENT.DB.EXEC( "BOOK_DB", "DELETE FROM "+CURR_PAIR+" WHERE BKKPG_UID>7" );

            DATA = self.PARENT.DB.FETCH("BOOK_DB", "SELECT * FROM "+CURR_PAIR+" ORDER BY BKKPG_UID DESC", ALL=True);
            self.BOOKKEEPING_WIDGET.clear();

            for data in DATA:

                # ---------------------------------------------------------------
                """ " "" 
                print( data )
                for d in data:
                    print( d )
                exit();
                "" " """ 
                # ---------------------------------------------------------------
                # In-Memory DATA
                BKKPG_UID       = data[0]
                completed       = data[1]
                started         = data[2]

                buy_order_id    = data[3]
                buy_unix_time   = data[4]
                buy_filled      = data[5]
                buy_amount      = data[6]
                buy_at_price    = data[7]
                #buy_fee         = data[8]
                buy_ttl         = data[9]
                buy_grand_ttl   = data[10]

                sell_order_id   = data[11]
                sell_unix_time  = data[12]
                sell_filled     = data[13]
                sell_amount     = data[14]

                sell_at_price   = data[15]
                #sell_fee        = data[16]
                sell_ttl        = data[17]
                sell_grand_ttl  = data[18]

                profit_ttl      = data[19]

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

                # ---------------------------------------------------------------
                """
                self.BOOK[ data[3] ].append( {
                                            
                                        BKKPG_UID,
                                        completed,
                                        started,

                                        buy_order_id,
                                        buy_unix_time,
                                        buy_filled,
                                        buy_amount,
                                        buy_at_price,
                                        buy_fee,
                                        buy_ttl,
                                        buy_grand_ttl,

                                        sell_order_id,
                                        sell_unix_time,
                                        sell_filled,
                                        sell_amount,
                                        sell_at_price,
                                        sell_fee,
                                        sell_ttl,
                                        sell_grand_ttl,

                                        profit_ttl

                                            } );

                """
                # ---------------------------------------------------------------
                if self.CALCULATE_ONLY_COMPLETED:

                    if buy_filled == 1 and sell_filled == 1:

                        self.BOUGHT_TTL += buy_ttl;
                        self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl*buy_at_price;

                        self.SOLD_TTL += sell_ttl;
                        self.SOLD_TTL_PLUS_FEE += sell_grand_ttl;

                else:

                    self.BOUGHT_TTL += buy_ttl;
                    self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl*buy_at_price;

                    self.SOLD_TTL += sell_ttl;
                    self.SOLD_TTL_PLUS_FEE += sell_grand_ttl;


                self.PROFIT_TTL_LABLE.setText( "{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE - self.BOUGHT_TTL_PLUS_FEE) );


                # ---------------------------------------------------------------
                # Formating data to Display in BookKeeping Wodget

                item = "";

                item += "DEL{:7} ".format(str( BKKPG_UID )); # id

                # BUY / BOUGHT
                item += "#{:11} DEL".format( str(buy_order_id) ); # order_id
                item += "{:4} DEL".format( str(buy_filled) ); # filed
                item += "{:13} DEL".format( str("{:10,.6f}".format( float(buy_amount) )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( buy_at_price )).strip() ); # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( buy_ttl )).strip() ); # ttl
                item += "{:14} ".format( str("{:10,.6f}".format( buy_grand_ttl )).strip() ); # grand_ttl

                # SELL / SOLD
                item += "#{:11} DEL".format( str(sell_order_id) ); # order_id
                item += "{:4} DEL".format( str(sell_filled) ); # filed
                item += "{:13} DEL".format( str("{:10,.6f}".format( sell_amount )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( sell_at_price )).strip() ); # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( sell_ttl )).strip() ); # ttl
                item += "{:14} ".format( str("{:10,.6f}".format( sell_grand_ttl )).strip() ); # grand_ttl
                
                # PROFIT
                item += "{:13}".format( str("{:10,.6f}".format( profit_ttl )).strip() ); # grand_ttl

                newItem = QListWidgetItem( QIcon("./data/imgs/icon_filled_status_0.png"), item.replace("DEL", self._i_), self.BOOKKEEPING_WIDGET, 0);
                #newItemToolTip = "Order ID: #"+str()+" Created: "+time.ctime(int(data[2]));
                #newItem.setToolTip(newItemToolTip);

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

            # / for
            # -------------------------------------------------------------------
            try: 
                self.BOUGHT_TTL_LABLE.setText( str("{:10,.6f}".format( self.BOUGHT_TTL ).strip()) );
                self.BOUGHT_TTL_PLUS_FEE_LABLE.setText( str("{:10,.6f}".format( self.BOUGHT_TTL_PLUS_FEE ).strip()) );

                self.SOLD_TTL_LABLE.setText( str("{:10,.6f}".format( self.SOLD_TTL ).strip()) );
                self.SOLD_TTL_PLUS_FEE_LABLE.setText( str("{:10,.6f}".format( self.SOLD_TTL_PLUS_FEE ).strip()) );

            except Exception as e:
                print("BOOKKEEPING[3:0]"+str(e))


        except Exception as _exception:

            print(" BOOKKEEPING[1:0]");
            print(_exception);
        # -------------------------------------------------------------------

    # =======================================================================
    def RESET_BKKPG_UID(self):

        # -------------------------------------------------------------------
        #CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();
        self.PARENT.GUI.BKKPG_UID_VALUE.setText("");
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show");
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show");
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_completed":
            if self.ONLY_COMPLETED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_COMPLETED = True;
            else:
                self.CALCULATE_ONLY_COMPLETED = False;

        # -------------------------------------------------------------------
        self.CREATE_LISTS();
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper());

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper());

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole );
            self.PAIR_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "SELECT_VALUES":

            self.DATA_TO_SEND_SELECTED = True;
            #self.DATA_TO_SEND = [ str(item).stip() for iten in str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")];
            self.DATA_TO_SEND = str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")[1].split("#")[0].strip();

        elif _action == "SEND_VALUES":

            if self.DATA_TO_SEND_SELECTED:

                _SQL = "SELECT buy_order_id, sell_order_id FROM "+self.PARENT.CURR_PAIR;
                _SQL += " WHERE BKKPG_UID="+self.DATA_TO_SEND;

                DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False);

                if DATA[0] != 0 and DATA[1] != 0:

                    self.PARENT.GUI.SHOW_QMESSAGE("info", "This UID is Full!<br> You can't add data to it enymore.<br>Bud You can delete sell and/or buy part<br/> and add new part.");
                    return;

                self.PARENT.GUI.BKKPG_UID_VALUE.setText( self.DATA_TO_SEND );

                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show");
                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show");

                self.DATA_TO_SEND_SELECTED = False;
                self.DATA_TO_SEND = None;

                # Clear Lables 
                self.SEND_ID_LABLE.setText( "n/a" );
                self.SEND_AMOUNT_LABLE.setText( "n/a" );
                self.SEND_AT_PRICE_LABLE.setText( "n/a" );


                if DATA[0] == 0:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "hide");

                else:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "hide");


                # Switch to Trader-Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0);

            else:

                self.PARENT.GUI.SHOW_QMESSAGE("info", " Select first item which one you would like<br/> send to the Trade-Terminal !");
                return; 
                
        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:
    
            self.SEND_ID_LABLE.setText( self.DATA_TO_SEND );
Beispiel #33
0
class TabInterface(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        v_box = QVBoxLayout(self)
        self.setFixedWidth(500)
        self.settings = QSettings('NINJA-IDE', 'Kunai')

        #groups
        self.gbox_bars = QGroupBox('Lateral Bars:')
        self.gbox_fonts = QGroupBox('Fonts:')
        self.gbox_tabs = QGroupBox('Editor Tabs:')
        self.gbox_tabsPosition = QGroupBox('Tabs Position:')

        v_box.addWidget(self.gbox_bars)
        v_box.addWidget(self.gbox_fonts)
        v_box.addWidget(self.gbox_tabs)
        v_box.addWidget(self.gbox_tabsPosition)

        self.settings.beginGroup('Preferences')
        self.settings.beginGroup('Interface')

        #Lateral Bars
        ##Checks
        self.ch_simbols = QCheckBox('Show Simbols List.')
        self.ch_simbols.setCheckState(
            self.settings.value('show_simbol_list', 2).toInt()[0])
        self.ch_files = QCheckBox('Show Files List.')
        self.ch_files.setCheckState(
            self.settings.value('show_files_list', 2).toInt()[0])

        v_bars = QVBoxLayout()
        v_bars.addWidget(self.ch_simbols)
        v_bars.addWidget(self.ch_files)

        self.gbox_bars.setLayout(v_bars)

        #Buttons
        self.btn_editor_font = QPushButton(
            self.settings.value('editor_font', 'Monospace, 10').toString())

        #self.btn_simbol_font = QPushButton(self.settings.value('simbol_list_font','Monospace, 10').toString())
        #self.btn_message_font = QPushButton(self.settings.value('window_message_font','Monospace, 10').toString())

        def load_editor_font():
            self.btn_editor_font.setText(
                load_font(
                    self,
                    self.get_font_from_string(self.btn_editor_font.text())))

        def load_simbol_font():
            self.btn_simbol_font.setText(load_font())

        def load_message_font():
            self.btn_message_font.setText(load_font())

        #SIGNALS
        self.connect(self.btn_editor_font, SIGNAL("clicked()"),
                     load_editor_font)
        #self.connect(self.btn_simbol_font, SIGNAL ("clicked()"), load_simbol_font)
        #self.connect(self.btn_message_font, SIGNAL("clicked()"), load_message_font)

        g_font = QGridLayout()
        g_font.addWidget(QLabel('Editor Font:'), 0, 0, Qt.AlignRight)
        #g_font.addWidget(QLabel('Simbol List:'),1, 0, Qt.AlignRight)
        #g_font.addWidget(QLabel('Messages Window:'),2,0,Qt.AlignRight)
        g_font.addWidget(self.btn_editor_font, 0, 1)
        #g_font.addWidget(self.btn_simbol_font, 1, 1)
        #g_font.addWidget(self.btn_message_font, 2, 1)

        self.gbox_fonts.setLayout(g_font)

        #Edition Tabs
        #Checks
        self.ch_showEditTabs = QCheckBox('Show Editor Tabs')
        self.ch_showEditTabs.setCheckState(
            self.settings.value('show_editor_tabs', 2).toInt()[0])
        self.ch_showClose = QCheckBox('Show Close Button on Tabs')
        self.ch_showClose.setCheckState(
            self.settings.value('show_close_tabs', 2).toInt()[0])
        self.ch_hidePanel = QCheckBox('F11 hide/show side Panels')
        self.ch_hidePanel.setCheckState(
            self.settings.value('hide_show_panels', 2).toInt()[0])

        #Option
        self.opt_left = QRadioButton('Left')
        self.opt_right = QRadioButton('Right')
        if (self.settings.value('next_tabs_location', 1).toInt()[0] == 1):
            self.opt_right.setChecked(True)
        else:
            self.opt_left.setChecked(True)
        h_optionNewFiles = QHBoxLayout()
        h_optionNewFiles.addWidget(QLabel('Location for New Files Tabs'))
        h_optionNewFiles.addWidget(self.opt_left)
        h_optionNewFiles.addWidget(self.opt_right)

        v_tabs = QVBoxLayout()
        v_tabs.addWidget(self.ch_showEditTabs)
        v_tabs.addWidget(self.ch_showClose)
        v_tabs.addLayout(h_optionNewFiles)
        #v_tabs.addWidget(self.ch_hidePanel)

        self.gbox_tabs.setLayout(v_tabs)

        #Tabs Position
        #Buttons
        #self.btn_orientation_change = QPushButton
        self.btn_hchange = QPushButton(QIcon(resources.images['splitCRotate']),
                                       '')
        self.btn_hchange.setIconSize(QSize(64, 64))
        self.btn_right_vchange = QPushButton(
            QIcon(resources.images['splitMRotate']), '')
        self.btn_right_vchange.setIconSize(QSize(64, 64))

        #SIGNAL
        self.connect(self.btn_hchange, SIGNAL('clicked()'),
                     parent._splitter_central_rotate)
        self.connect(self.btn_right_vchange, SIGNAL('clicked()'),
                     parent._splitter_main_rotate)

        self.settings.endGroup()  #End General Preferences
        self.settings.endGroup()

        g_tabPosition = QGridLayout()
        g_tabPosition.addWidget(self.btn_hchange, 0, 0)
        g_tabPosition.addWidget(self.btn_right_vchange, 0, 1)
        g_tabPosition.addWidget(QLabel('Vertical Change'), 1, 0,
                                Qt.AlignCenter)
        g_tabPosition.addWidget(QLabel('Horizontal Change'), 1, 1,
                                Qt.AlignCenter)

        self.gbox_tabsPosition.setLayout(g_tabPosition)


#Fonts

    def get_font_from_string(self, font):
        if (font.isEmpty()):
            return QFont("Monospace", 10)

        listFont = font.remove(' ').split(',')
        ret = QFont(listFont[0], listFont[1].toInt()[0])
        return ret

    def save_state(self, parent):

        self.settings.beginGroup('Preferences')
        self.settings.beginGroup('Interface')
        #CheckBox
        self.settings.setValue('show_simbol_list',
                               self.ch_simbols.checkState())
        self.settings.setValue('show_files_list', self.ch_files.checkState())
        self.settings.setValue('show_editor_tabs',
                               self.ch_showEditTabs.checkState())
        self.settings.setValue('show_close_tabs',
                               self.ch_showClose.checkState())
        self.settings.setValue('hide_show_panels',
                               self.ch_hidePanel.checkState())
        #OptionButton
        if (self.opt_right.isChecked()):
            self.settings.setValue('next_tabs_location', 1)
        else:
            self.settings.setValue('next_tabs_location', 0)
        #Fonts
        self.settings.setValue('editor_font', self.btn_editor_font.text())
        #self.settings.setValue('simbol_list_font', self.btn_simbol_font.text())
        #self.settings.setValue('window_message_font', self.btn_message_font.text())

        #Panels Positions
        if (parent.get_splitter_position_0() == CentralWidget):
            self.settings.setValue('central_tab_position', 0)
            self.settings.setValue('container_tab_position', 1)
        else:
            self.settings.setValue('central_tab_position', 1)
            self.settings.setValue('container_tab_position', 0)

        if (parent.get_splitter_main_position_0() == QSplitter):
            self.settings.setValue('main_tab_position', 0)
            self.settings.setValue('properties_tab_position', 1)
        else:
            self.settings.setValue('main_tab_position', 1)
            self.settings.setValue('properties_tab_position', 0)

        self.settings.endGroup()  #End Interface Preferences
        self.settings.endGroup()
Beispiel #34
0
class EditorConfiguration(QWidget):
    def __init__(self, main):
        QWidget.__init__(self)
        self._main = main
        grid = QGridLayout(self)

        #Indentation
        groupBoxFeatures = QGroupBox('Features:')
        grid.addWidget(groupBoxFeatures, 0, 0)
        grid.addWidget(QLabel('Indentation Length:'), 1, 0, Qt.AlignRight)
        self.spin = QSpinBox()
        self.spin.setValue(EditorGeneric.indent)
        grid.addWidget(self.spin, 1, 1)
        #Find Errors
        self.checkErrors = QCheckBox('Find and Show Errors')
        errorState = Qt.Checked if EditorGeneric.findErrors else Qt.Unchecked
        self.checkErrors.setCheckState(errorState)
        grid.addWidget(self.checkErrors, 2, 1)
        #Find Check Style
        self.checkStyle = QCheckBox('Find and Show Check Style errors.')
        styleState = Qt.Checked if EditorGeneric.checkStyle else Qt.Unchecked
        self.checkStyle.setCheckState(styleState)
        grid.addWidget(self.checkStyle, 3, 1)
        #Highlight words
        self.checkWords = QCheckBox('Highlight current word.')
        wordsState = Qt.Checked if EditorGeneric.highlightVariables else Qt.Unchecked
        self.checkWords.setCheckState(wordsState)
        grid.addWidget(self.checkWords, 4, 1)

        groupBoxClose = QGroupBox('Complete:')
        grid.addWidget(groupBoxClose, 5, 0)
        self.checkParentheses = QCheckBox('Parentheses: ()')
        state = Qt.Checked if EditorGeneric.braces_strings.get(
            '(', False) else Qt.Unchecked
        self.checkParentheses.setCheckState(state)
        self.checkKeys = QCheckBox('Keys: {}')
        state = Qt.Checked if EditorGeneric.braces_strings.get(
            '{', False) else Qt.Unchecked
        self.checkKeys.setCheckState(state)
        self.checkBrackets = QCheckBox('Brackets: []')
        state = Qt.Checked if EditorGeneric.braces_strings.get(
            '[', False) else Qt.Unchecked
        self.checkBrackets.setCheckState(state)
        self.checkSimpleQuotes = QCheckBox("Simple Quotes: ''")
        state = Qt.Checked if EditorGeneric.braces_strings.get(
            "'", False) else Qt.Unchecked
        self.checkSimpleQuotes.setCheckState(state)
        self.checkDoubleQuotes = QCheckBox('Double Quotes: ""')
        state = Qt.Checked if EditorGeneric.braces_strings.get(
            '"', False) else Qt.Unchecked
        self.checkDoubleQuotes.setCheckState(state)
        grid.addWidget(self.checkParentheses, 6, 1)
        grid.addWidget(self.checkKeys, 7, 1)
        grid.addWidget(self.checkBrackets, 8, 1)
        grid.addWidget(self.checkSimpleQuotes, 9, 1)
        grid.addWidget(self.checkDoubleQuotes, 10, 1)

        groupBoxCode = QGroupBox('Code Completion:')
        grid.addWidget(groupBoxCode, 11, 0)
        self.checkCodeDot = QCheckBox('Activate Code Completion with: "."')
        state = Qt.Checked if EditorGeneric.codeCompletion else Qt.Unchecked
        self.checkCodeDot.setCheckState(state)
        #        self.checkCodeChar = QCheckBox('Activate Code Completion after:')
        #        self.spinCode = QSpinBox()
        #        self.spinCode.setSuffix(' characters')
        grid.addWidget(self.checkCodeDot, 12, 1)
#        grid.addWidget(self.checkCodeChar, 13, 0)
#        grid.addWidget(self.spinCode, 13, 1)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('editor')
        settings.setValue('indent', self.spin.value())
        EditorGeneric.indent = self.spin.value()
        settings.setValue('errors', self.checkErrors.isChecked())
        EditorGeneric.findErrors = self.checkErrors.isChecked()
        settings.setValue('checkStyle', self.checkStyle.isChecked())
        EditorGeneric.checkStyle = self.checkStyle.isChecked()
        settings.setValue('highlightWord', self.checkWords.isChecked())
        EditorGeneric.highlightVariables = self.checkWords.isChecked()
        settings.setValue('parentheses', self.checkParentheses.isChecked())
        if self.checkParentheses.isChecked():
            EditorGeneric.braces_strings['('] = ')'
        elif EditorGeneric.braces_strings.has_key('('):
            del EditorGeneric.braces_strings['(']
        settings.setValue('brackets', self.checkBrackets.isChecked())
        if self.checkBrackets.isChecked():
            EditorGeneric.braces_strings['['] = ']'
        elif EditorGeneric.braces_strings.has_key('['):
            del EditorGeneric.braces_strings['[']
        settings.setValue('keys', self.checkKeys.isChecked())
        if self.checkKeys.isChecked():
            EditorGeneric.braces_strings['{'] = '}'
        elif EditorGeneric.braces_strings.has_key('{'):
            del EditorGeneric.braces_strings['{']
        settings.setValue('simpleQuotes', self.checkSimpleQuotes.isChecked())
        if self.checkSimpleQuotes.isChecked():
            EditorGeneric.braces_strings["'"] = "'"
        elif EditorGeneric.braces_strings.has_key("'"):
            del EditorGeneric.braces_strings["'"]
        settings.setValue('doubleQuotes', self.checkDoubleQuotes.isChecked())
        if self.checkDoubleQuotes.isChecked():
            EditorGeneric.braces_strings['"'] = '"'
        elif EditorGeneric.braces_strings.has_key('"'):
            del EditorGeneric.braces_strings['"']
        settings.setValue('codeCompletion', self.checkCodeDot.isChecked())
        settings.endGroup()
        settings.endGroup()
Beispiel #35
0
class Skin(QWidget):
    
    def __init__(self, pref):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        vbox.addWidget(QLabel('Configure the CSS (Skin) for this Application'))
        self.checkDefault = QCheckBox('Default')
        self.checkCustom = QCheckBox('Custom')
        self.checkNoSkin = QCheckBox('No Skin')
        hbox = QHBoxLayout()
        hbox.addWidget(self.checkDefault)
        hbox.addWidget(self.checkCustom)
        hbox.addWidget(self.checkNoSkin)
        vbox.addLayout(hbox)

        self.text = QPlainTextEdit()
        self.text.setEnabled(False)
        self.text.setPlainText(styles.css_styles)
        vbox.addWidget(self.text)
        if pref.get('noSkin', False):
            self.checkNoSkin.setCheckState(Qt.Checked)
        elif pref.get('custom', False):
            self.checkCustom.setCheckState(Qt.Checked)
            self.text.setEnabled(True)
            self.text.setPlainText(pref.get('skin', ''))
        else:
            self.checkDefault.setCheckState(Qt.Checked)

        self.connect(self.checkDefault, SIGNAL("stateChanged(int)"), self.use_default)
        self.connect(self.checkCustom, SIGNAL("stateChanged(int)"), self.use_custom)
        self.connect(self.checkNoSkin, SIGNAL("stateChanged(int)"), self.use_no_skin)

    def use_default(self, val):
        if val == 2:
            self.checkDefault.setCheckState(Qt.Checked)
            self.checkCustom.setCheckState(Qt.Unchecked)
            self.checkNoSkin.setCheckState(Qt.Unchecked)
            self.text.setEnabled(False)

    def use_custom(self, val):
        if val == 2:
            self.checkDefault.setCheckState(Qt.Unchecked)
            self.checkCustom.setCheckState(Qt.Checked)
            self.checkNoSkin.setCheckState(Qt.Unchecked)
            self.text.setEnabled(True)

    def use_no_skin(self, val):
        if val == 2:
            self.checkDefault.setCheckState(Qt.Unchecked)
            self.checkCustom.setCheckState(Qt.Unchecked)
            self.checkNoSkin.setCheckState(Qt.Checked)
            self.text.setEnabled(False)
Beispiel #36
0
class FindInFilesDialog(QDialog):

    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
            self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(self,
            self.tr("Open Directory"),
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
Beispiel #37
0
class Downloads(QWidget):
    
    def __init__(self, pref):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        self.checkAsk = QCheckBox('Ask for every Download')
        self.checkFolder = QCheckBox('Use always the following folder:')
        vbox.addWidget(self.checkAsk)
        vbox.addWidget(self.checkFolder)
        hbox = QHBoxLayout()
        self.lineFolder = QLineEdit()
        self.lineFolder.setReadOnly(True)
        self.btnBrowse = QPushButton('Browse')
        if pref.get('ask', True):
            self.checkAsk.setCheckState(Qt.Checked)
            self.btnBrowse.setEnabled(False)
        else:
            self.checkFolder.setCheckState(Qt.Checked)
            self.lineFolder.setText(pref.get('folder', ''))
        hbox.addWidget(self.lineFolder)
        hbox.addWidget(self.btnBrowse)
        vbox.addLayout(hbox)

        self.connect(self.checkAsk, SIGNAL("stateChanged(int)"), self.use_ask)
        self.connect(self.checkFolder, SIGNAL("stateChanged(int)"), self.use_folder)
        self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_folder)

    def select_folder(self):
        folderName = str(QFileDialog.getExistingDirectory(self, 'Save File in...'))
        if folderName != '':
            self.lineFolder.setText(folderName)

    def use_ask(self, val):
        if val == 2:
            self.checkAsk.setCheckState(Qt.Checked)
            self.checkFolder.setCheckState(Qt.Unchecked)
            self.btnBrowse.setEnabled(False)
            self.lineFolder.setText('')
        else:
            self.use_folder(2)

    def use_folder(self, val):
        if val == 2:
            self.checkFolder.setCheckState(Qt.Checked)
            self.checkAsk.setCheckState(Qt.Unchecked)
            self.btnBrowse.setEnabled(True)
        else:
            self.use_ask(2)
Beispiel #38
0
class FindInFilesDialog(QDialog):

    """Dialog to configure and trigger the search in the files."""

    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"), translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(QCompleter(
            ["*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(
            translations.TR_TEXT_FOR_REPLACE + "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(self, translations.TR_OPEN,
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
Beispiel #39
0
class MikidownCfgDialog(QDialog):
    def __init__(self, parent=None):
        super(MikidownCfgDialog, self).__init__(parent)
        #tab = QWidget()
        #tab2 = QWidget()
        self.setWindowTitle(self.tr("Settings - mikidown"))
        self.recentNotesCount = QSpinBox()
        recent_notes_n = Mikibook.settings.value('recentNotesNumber',type=int, defaultValue=20)
        self.recentNotesCount.setValue(recent_notes_n)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        self.hltCfg = MikidownHighlightCfgWidget(parent=self)
        self.tabWidth = QSpinBox(self)
        self.tabWidth.setRange(2, 8)
        self.tabWidth.setSingleStep(2)
        self.iconTheme = QLineEdit(self)
        self.iconTheme.setText(Mikibook.settings.value('iconTheme', QIcon.themeName()))

        self.editorFont = QFontButton(parent=self)
        fontval = QFont()
        fontfam = Mikibook.settings.value('editorFont', defaultValue=None)
        fontsize = Mikibook.settings.value('editorFontSize', type=int, defaultValue=12)
        if fontfam is not None:
            fontval.setFamily(fontfam)
        fontval.setPointSize(fontsize)

        self.headerScalesFont = QCheckBox(self)
        if Mikibook.settings.value('headerScaleFont', type=bool, defaultValue=True):
            self.headerScalesFont.setCheckState(Qt.Checked)
        else:
            self.headerScalesFont.setCheckState(Qt.Unchecked)

        self.editorFont.font = fontval

        self.tabWidth.setValue(Mikibook.settings.value('tabWidth', type=int, defaultValue=4))

        self.tabToSpaces = QCheckBox(self)
        if Mikibook.settings.value('tabInsertsSpaces', type=bool, defaultValue=True):
            self.tabToSpaces.setCheckState(Qt.Checked)
        else:
            self.tabToSpaces.setCheckState(Qt.Unchecked)

        layout = QGridLayout(self)
        layout.addWidget(QLabel(self.tr("# of recently viewed notes to keep")),0,0,1,1)
        layout.addWidget(self.recentNotesCount,0,1,1,1)
        layout.addWidget(QLabel(self.tr("Editor font")), 1, 0, 1, 1)
        layout.addWidget(self.editorFont, 1, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Header rank scales editor font?")), 2, 0, 1, 1)
        layout.addWidget(self.headerScalesFont, 2, 1, 1, 1)
        qs = QScrollArea(self)
        qs.setWidget(self.hltCfg)
        layout.addWidget(QLabel(self.tr("Tabs expand to spaces?")), 3, 0, 1, 1)
        layout.addWidget(self.tabToSpaces, 3, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Tab width")), 4, 0, 1, 1)
        layout.addWidget(self.tabWidth, 4, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Icon Theme")),5,0,1,1)
        layout.addWidget(self.iconTheme,5,1,1,1)
        layout.addWidget(qs,6,0,1,2)
        layout.addWidget(self.buttonBox,7,0,1,2)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def accept(self):
        Mikibook.settings.setValue('recentNotesNumber', self.recentNotesCount.value())
        Mikibook.settings.setValue('editorFont', self.editorFont.font.family())
        Mikibook.settings.setValue('editorFontSize', self.editorFont.font.pointSize())
        if self.headerScalesFont.isChecked():
            Mikibook.settings.setValue('headerScaleFont', True)
        else:
            Mikibook.settings.setValue('headerScaleFont', False)
        Mikibook.settings.setValue('tabWidth', self.tabWidth.value())
        Mikibook.settings.setValue('iconTheme', self.iconTheme.text())
        if self.tabToSpaces.isChecked():
            Mikibook.settings.setValue('tabInsertsSpaces', True)
        else:
            Mikibook.settings.setValue('tabInsertsSpaces', False)
        Mikibook.setHighlighterColors(self.hltCfg.configToList())
        QIcon.setThemeName(self.iconTheme.text())

        #then make mikidown use these settings NOW
        self.parent().loadHighlighter()
        QDialog.accept(self)
Beispiel #40
0
class MikidownCfgDialog(QDialog):
    def __init__(self, parent=None):
        super(MikidownCfgDialog, self).__init__(parent)
        #tab = QWidget()
        #tab2 = QWidget()
        self.setWindowTitle(self.tr("Settings - mikidown"))
        self.recentNotesCount = QSpinBox()
        recent_notes_n = Mikibook.settings.value('recentNotesNumber',
                                                 type=int,
                                                 defaultValue=20)
        self.recentNotesCount.setValue(recent_notes_n)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.hltCfg = MikidownHighlightCfgWidget(parent=self)
        self.tabWidth = QSpinBox(self)
        self.tabWidth.setRange(2, 8)
        self.tabWidth.setSingleStep(2)
        self.iconTheme = QLineEdit(self)
        self.iconTheme.setText(
            Mikibook.settings.value('iconTheme', QIcon.themeName()))

        self.editorFont = QFontButton(parent=self)
        fontval = QFont()
        fontfam = Mikibook.settings.value('editorFont', defaultValue=None)
        fontsize = Mikibook.settings.value('editorFontSize',
                                           type=int,
                                           defaultValue=12)
        if fontfam is not None:
            fontval.setFamily(fontfam)
        fontval.setPointSize(fontsize)

        self.headerScalesFont = QCheckBox(self)
        if Mikibook.settings.value('headerScaleFont',
                                   type=bool,
                                   defaultValue=True):
            self.headerScalesFont.setCheckState(Qt.Checked)
        else:
            self.headerScalesFont.setCheckState(Qt.Unchecked)

        self.editorFont.font = fontval

        self.tabWidth.setValue(
            Mikibook.settings.value('tabWidth', type=int, defaultValue=4))

        self.tabToSpaces = QCheckBox(self)
        if Mikibook.settings.value('tabInsertsSpaces',
                                   type=bool,
                                   defaultValue=True):
            self.tabToSpaces.setCheckState(Qt.Checked)
        else:
            self.tabToSpaces.setCheckState(Qt.Unchecked)

        layout = QGridLayout(self)
        layout.addWidget(QLabel(self.tr("# of recently viewed notes to keep")),
                         0, 0, 1, 1)
        layout.addWidget(self.recentNotesCount, 0, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Editor font")), 1, 0, 1, 1)
        layout.addWidget(self.editorFont, 1, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Header rank scales editor font?")), 2,
                         0, 1, 1)
        layout.addWidget(self.headerScalesFont, 2, 1, 1, 1)
        qs = QScrollArea(self)
        qs.setWidget(self.hltCfg)
        layout.addWidget(QLabel(self.tr("Tabs expand to spaces?")), 3, 0, 1, 1)
        layout.addWidget(self.tabToSpaces, 3, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Tab width")), 4, 0, 1, 1)
        layout.addWidget(self.tabWidth, 4, 1, 1, 1)
        layout.addWidget(QLabel(self.tr("Icon Theme")), 5, 0, 1, 1)
        layout.addWidget(self.iconTheme, 5, 1, 1, 1)
        layout.addWidget(qs, 6, 0, 1, 2)
        layout.addWidget(self.buttonBox, 7, 0, 1, 2)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def accept(self):
        Mikibook.settings.setValue('recentNotesNumber',
                                   self.recentNotesCount.value())
        Mikibook.settings.setValue('editorFont', self.editorFont.font.family())
        Mikibook.settings.setValue('editorFontSize',
                                   self.editorFont.font.pointSize())
        if self.headerScalesFont.isChecked():
            Mikibook.settings.setValue('headerScaleFont', True)
        else:
            Mikibook.settings.setValue('headerScaleFont', False)
        Mikibook.settings.setValue('tabWidth', self.tabWidth.value())
        Mikibook.settings.setValue('iconTheme', self.iconTheme.text())
        if self.tabToSpaces.isChecked():
            Mikibook.settings.setValue('tabInsertsSpaces', True)
        else:
            Mikibook.settings.setValue('tabInsertsSpaces', False)
        Mikibook.setHighlighterColors(self.hltCfg.configToList())
        QIcon.setThemeName(self.iconTheme.text())

        #then make mikidown use these settings NOW
        self.parent().loadHighlighter()
        QDialog.accept(self)
Beispiel #41
0
class BookKeeping(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF

        #self.SHA256                         = hashlib.sha256;
        #UID_SHA256 = self.SHA256( str(time.time()) ).hexdigest();
        self.SELECTED_BKKPG_UID = None

        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 975, 555)
        self.setStyleSheet(
            "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_BookKeeping.png'); }"
        )

        self.PAIR_COMBO = QComboBox(self)
        self.PAIR_COMBO.setGeometry(86, 20, 108, 44)
        self.connect(self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'),
                     self.CREATE_LISTS)
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False)
        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_BookKeeping_line.png'); }"
        # ./data/imgs/BookKeeping_line.png
        lable_style = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"

        # -------------------------------------------------------------------
        self.DATA_TO_SEND = None
        self._i_ = "|"
        # List delimiter
        self.CALCULATE_ONLY_COMPLETED = True
        self.DATA_TO_SEND_SELECTED = False

        # -------------------------------------------------------------------
        self.BOOKKEEPING_WIDGET = QListWidget(self)
        self.BOOKKEEPING_WIDGET.setGeometry(13, 144, 949, 259)
        self.BOOKKEEPING_WIDGET.setStyleSheet(list_style)

        self.connect(self.BOOKKEEPING_WIDGET, SIGNAL('itemSelectionChanged()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))
        self.BOOKKEEPING_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SELECT_VALUES"))

        self.BOUGHT_TTL_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_LABLE.setGeometry(304, 406, 85, 17)
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL = 0

        self.BOUGHT_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry(396, 406, 85, 17)
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_PLUS_FEE = 0

        self.SOLD_TTL_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_LABLE.setGeometry(694, 406, 85, 17)
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL = 0

        self.SOLD_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry(784, 406, 85, 17)
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_PLUS_FEE = 0

        self.PROFIT_TTL_LABLE = QLabel("0.0", self)
        self.PROFIT_TTL_LABLE.setGeometry(874, 406, 88, 17)
        #self.PROFIT_TTL_LABLE.setEditable( False );
        self.PROFIT_TTL_LABLE.setStyleSheet(lable_style)
        self.PROFIT_TTL = 0

        # -------------------------------------------------------------------
        self.SEND_ID_LABLE = QLabel("n/a", self)
        self.SEND_ID_LABLE.setGeometry(18, 467, 43, 17)
        self.SEND_ID_LABLE.setStyleSheet(lable_style)

        self.SEND_AMOUNT_LABLE = QLabel("n/a", self)
        self.SEND_AMOUNT_LABLE.setGeometry(66, 467, 85, 17)
        self.SEND_AMOUNT_LABLE.setStyleSheet(lable_style)

        self.SEND_AT_PRICE_LABLE = QLabel("n/a", self)
        self.SEND_AT_PRICE_LABLE.setGeometry(156, 467, 43, 17)
        self.SEND_AT_PRICE_LABLE.setStyleSheet(lable_style)

        self.SEND_VALUES_BTN = QPushButton("", self)
        self.SEND_VALUES_BTN.setGeometry(60, 502, 131, 33)
        self.SEND_VALUES_BTN.setStyleSheet(
            "QPushButton{ background-color: transparent; border-style: none; }"
        )
        self.connect(self.SEND_VALUES_BTN, SIGNAL('clicked()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES"))

        # -------------------------------------------------------------------
        self.ONLY_COMPLETED_CHECKBOX = QCheckBox("", self)
        self.ONLY_COMPLETED_CHECKBOX.setGeometry(665, 444, 17, 17)
        self.ONLY_COMPLETED_CHECKBOX.setCheckState(Qt.Checked)
        #self.ONLY_COMPLETED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_COMPLETED_CHECKBOX, SIGNAL('stateChanged(int)'),
                     lambda: self.CHANGE_VALUES("only_completed"))

        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR()
            self.CREATE_LISTS()

        except Exception as _exception:

            print("-----------------------------------------------------")
            print("[INIT]" + str(_exception))
        # -------------------------------------------------------------------

    # =======================================================================
    def BKKPG_UID_ACTION(self, _ACTION, BKKPG_UID, _D):

        # -------------------------------------------------------------------
        #print("_ACTION: ", _ACTION, "BKKPG_UID: ", BKKPG_UID)
        # -------------------------------------------------------------------
        try:

            CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower().strip()

            order_id = _D[0]
            unix_time = _D[1]
            filled = _D[2]
            amount = _D[3]
            at_price = _D[4]

            if _ACTION == "buy":

                # For CRYPTO
                ttl = amount
                fee = (ttl / 100 * self.PARENT.FEE)

            elif _ACTION == "sell":

                # For USD
                ttl = amount * at_price
                fee = (ttl / 100 * self.PARENT.FEE)

            grand_ttl = ttl - fee

            # -------------------------------------------------------------------
            if BKKPG_UID == "":  # Is New Record

                TPL = "buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl "

                _SQL = "INSERT INTO " + CURR_PAIR + "( BKKPG_UID, completed, started, " + TPL + ", profit_ttl ) "

                if _ACTION == "buy":
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format(
                        _D[0], _D[1], _D[2], _D[3], _D[4], fee, ttl, grand_ttl,
                        0, 0, 0, 0, 0, 0, 0, 0)

                else:
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format(
                        0, 0, 0, 0, 0, 0, 0, 0, _D[0], _D[1], _D[2], _D[3],
                        _D[4], fee, ttl, grand_ttl)

                self.PARENT.DB.EXEC("BOOK_DB", _SQL)

            else:  # Existing Record

                # ------------------------------------------------
                if filled == 1:

                    completed = 1

                    _SQL = "SELECT ACT_grand_ttl from " + CURR_PAIR + " WHERE BKKPG_UID=" + BKKPG_UID

                    if _ACTION == "buy":

                        DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                                    _SQL.replace(
                                                        "ACT", "sell"),
                                                    ALL=False)
                        profit_ttl = DATA - grand_ttl

                    else:

                        DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                                    _SQL.replace("ACT", "buy"),
                                                    ALL=False)
                        profit_ttl = grand_ttl - DATA
                else:
                    profit_ttl = 0
                    completed = 0

                # ------------------------------------------------
                A = _ACTION

                _SQL = "UPDATE " + CURR_PAIR + " SET completed={0}, " + A + "_order_id={1}, " + A + "_unix_time={2}, " + A + "_filled={3}, "
                _SQL += A + "_amount={4}, " + A + "_at_price={5}, " + A + "_fee={6}, " + A + "_ttl={7}, " + A + "_grand_ttl={8}"
                _SQL += " WHERE BKKPG_UID=" + BKKPG_UID

                _SQL = _SQL.format(completed, order_id, unix_time, filled,
                                   amount, at_price, fee, ttl, grand_ttl)

                self.PARENT.DB.EXEC("BOOK_DB", _SQL)

        except Exception as _exception:

            print(" BOOKKEEPING[0:0]")
            print(_exception)
        # -------------------------------------------------------------------
        """
        BKKPG_UID, completed, started, 
        
        buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, 
        sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl, 
        
        profit_ttl
        """
        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

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

        _SQL = "SELECT buy_order_id, sell_order_id FROM " + _pair
        _SQL += " WHERE buy_order_id=" + str(
            _order_id) + " OR sell_order_id=" + str(_order_id)

        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False)

        if DATA is None:
            pass

        if _type == "buy" and DATA[1] == 0:

            _SQL = "DELETE FROM " + _pair + " WHERE buy_order_id=" + str(
                _order_id) + " OR sell_order_id=" + str(_order_id)
            self.PARENT.DB.EXEC("BOOK_DB", _SQL)
            self.CREATE_LISTS()

        elif _type == "sell" and DATA[0] == 0:

            _SQL = "DELETE FROM " + _pair + " WHERE buy_order_id=" + str(
                _order_id) + " OR sell_order_id=" + str(_order_id)
            self.PARENT.DB.EXEC("BOOK_DB", _SQL)
            self.CREATE_LISTS()

        else:

            A = _type

            _SQL = "UPDATE " + self.PARENT.CURR_PAIR + " SET "
            _SQL += " completed=0, " + A + "_order_id=0, " + A + "_unix_time=0, " + A + "_filled=0, "
            _SQL += A + "_amount=0, " + A + "_at_price=0, " + A + "_fee=0, " + A + "_ttl=0, " + A + "_grand_ttl=0 "
            _SQL += "WHERE " + A + "_order_id=" + str(_order_id)

            self.PARENT.DB.EXEC("BOOK_DB", _SQL)

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

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:
            CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower()

            # -------------------------------------------------------------------
            self.BOOK = {
                "bought": [],
                "sold": []
            }

            self.BOUGHT_TTL = 0
            self.BOUGHT_TTL_PLUS_FEE = 0

            self.SOLD_TTL = 0
            self.SOLD_TTL_PLUS_FEE = 0

            # -------------------------------------------------------------------
            #self.PARENT.DB.EXEC( "BOOK_DB", "DELETE FROM "+CURR_PAIR+" WHERE BKKPG_UID>7" );

            DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                        "SELECT * FROM " + CURR_PAIR +
                                        " ORDER BY BKKPG_UID DESC",
                                        ALL=True)
            self.BOOKKEEPING_WIDGET.clear()

            for data in DATA:

                # ---------------------------------------------------------------
                """ " "" 
                print( data )
                for d in data:
                    print( d )
                exit();
                "" " """
                # ---------------------------------------------------------------
                # In-Memory DATA
                BKKPG_UID = data[0]
                completed = data[1]
                started = data[2]

                buy_order_id = data[3]
                buy_unix_time = data[4]
                buy_filled = data[5]
                buy_amount = data[6]
                buy_at_price = data[7]
                #buy_fee         = data[8]
                buy_ttl = data[9]
                buy_grand_ttl = data[10]

                sell_order_id = data[11]
                sell_unix_time = data[12]
                sell_filled = data[13]
                sell_amount = data[14]

                sell_at_price = data[15]
                #sell_fee        = data[16]
                sell_ttl = data[17]
                sell_grand_ttl = data[18]

                profit_ttl = data[19]

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

                # ---------------------------------------------------------------
                """
                self.BOOK[ data[3] ].append( {
                                            
                                        BKKPG_UID,
                                        completed,
                                        started,

                                        buy_order_id,
                                        buy_unix_time,
                                        buy_filled,
                                        buy_amount,
                                        buy_at_price,
                                        buy_fee,
                                        buy_ttl,
                                        buy_grand_ttl,

                                        sell_order_id,
                                        sell_unix_time,
                                        sell_filled,
                                        sell_amount,
                                        sell_at_price,
                                        sell_fee,
                                        sell_ttl,
                                        sell_grand_ttl,

                                        profit_ttl

                                            } );

                """
                # ---------------------------------------------------------------
                if self.CALCULATE_ONLY_COMPLETED:

                    if buy_filled == 1 and sell_filled == 1:

                        self.BOUGHT_TTL += buy_ttl
                        self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl * buy_at_price

                        self.SOLD_TTL += sell_ttl
                        self.SOLD_TTL_PLUS_FEE += sell_grand_ttl

                else:

                    self.BOUGHT_TTL += buy_ttl
                    self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl * buy_at_price

                    self.SOLD_TTL += sell_ttl
                    self.SOLD_TTL_PLUS_FEE += sell_grand_ttl

                self.PROFIT_TTL_LABLE.setText(
                    "{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE -
                                       self.BOUGHT_TTL_PLUS_FEE))

                # ---------------------------------------------------------------
                # Formating data to Display in BookKeeping Wodget

                item = ""

                item += "DEL{:7} ".format(str(BKKPG_UID))
                # id

                # BUY / BOUGHT
                item += "#{:11} DEL".format(str(buy_order_id))
                # order_id
                item += "{:4} DEL".format(str(buy_filled))
                # filed
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(float(buy_amount))).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(buy_at_price)).strip())
                # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( buy_ttl )).strip() ); # ttl
                item += "{:14} ".format(
                    str("{:10,.6f}".format(buy_grand_ttl)).strip())
                # grand_ttl

                # SELL / SOLD
                item += "#{:11} DEL".format(str(sell_order_id))
                # order_id
                item += "{:4} DEL".format(str(sell_filled))
                # filed
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(sell_amount)).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(sell_at_price)).strip())
                # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( sell_ttl )).strip() ); # ttl
                item += "{:14} ".format(
                    str("{:10,.6f}".format(sell_grand_ttl)).strip())
                # grand_ttl

                # PROFIT
                item += "{:13}".format(
                    str("{:10,.6f}".format(profit_ttl)).strip())
                # grand_ttl

                newItem = QListWidgetItem(
                    QIcon("./data/imgs/icon_filled_status_0.png"),
                    item.replace("DEL", self._i_), self.BOOKKEEPING_WIDGET, 0)
                #newItemToolTip = "Order ID: #"+str()+" Created: "+time.ctime(int(data[2]));
                #newItem.setToolTip(newItemToolTip);

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

            # / for
            # -------------------------------------------------------------------
            try:
                self.BOUGHT_TTL_LABLE.setText(
                    str("{:10,.6f}".format(self.BOUGHT_TTL).strip()))
                self.BOUGHT_TTL_PLUS_FEE_LABLE.setText(
                    str("{:10,.6f}".format(self.BOUGHT_TTL_PLUS_FEE).strip()))

                self.SOLD_TTL_LABLE.setText(
                    str("{:10,.6f}".format(self.SOLD_TTL).strip()))
                self.SOLD_TTL_PLUS_FEE_LABLE.setText(
                    str("{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE).strip()))

            except Exception as e:
                print("BOOKKEEPING[3:0]" + str(e))

        except Exception as _exception:

            print(" BOOKKEEPING[1:0]")
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def RESET_BKKPG_UID(self):

        # -------------------------------------------------------------------
        #CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();
        self.PARENT.GUI.BKKPG_UID_VALUE.setText("")
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show")
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show")
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_completed":
            if self.ONLY_COMPLETED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_COMPLETED = True
            else:
                self.CALCULATE_ONLY_COMPLETED = False

        # -------------------------------------------------------------------
        self.CREATE_LISTS()
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData(i, QColor("#333"), Qt.BackgroundRole)
            self.PAIR_COMBO.setItemData(i, QColor("#fff"), Qt.ForegroundRole)
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "SELECT_VALUES":

            self.DATA_TO_SEND_SELECTED = True
            #self.DATA_TO_SEND = [ str(item).stip() for iten in str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")];
            self.DATA_TO_SEND = str(
                self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split(
                    "|")[1].split("#")[0].strip()

        elif _action == "SEND_VALUES":

            if self.DATA_TO_SEND_SELECTED:

                _SQL = "SELECT buy_order_id, sell_order_id FROM " + self.PARENT.CURR_PAIR
                _SQL += " WHERE BKKPG_UID=" + self.DATA_TO_SEND

                DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False)

                if DATA[0] != 0 and DATA[1] != 0:

                    self.PARENT.GUI.SHOW_QMESSAGE(
                        "info",
                        "This UID is Full!<br> You can't add data to it enymore.<br>Bud You can delete sell and/or buy part<br/> and add new part."
                    )
                    return

                self.PARENT.GUI.BKKPG_UID_VALUE.setText(self.DATA_TO_SEND)

                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show")
                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show")

                self.DATA_TO_SEND_SELECTED = False
                self.DATA_TO_SEND = None

                # Clear Lables
                self.SEND_ID_LABLE.setText("n/a")
                self.SEND_AMOUNT_LABLE.setText("n/a")
                self.SEND_AT_PRICE_LABLE.setText("n/a")

                if DATA[0] == 0:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "hide")

                else:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "hide")

                # Switch to Trader-Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0)

            else:

                self.PARENT.GUI.SHOW_QMESSAGE(
                    "info",
                    " Select first item which one you would like<br/> send to the Trade-Terminal !"
                )
                return

        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:

            self.SEND_ID_LABLE.setText(self.DATA_TO_SEND)
class InterfaceTab(QWidget):

    def __init__(self, parent):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        self._main = parent

        groupBoxExplorer = QGroupBox('Explorer Panel:')
        groupBoxGui = QGroupBox('GUI Customization:')

        #Explorer
        vboxExplorer = QVBoxLayout(groupBoxExplorer)
        self.checkProjectExplorer = QCheckBox('Show Project Explorer.')
        self.checkSymbols = QCheckBox('Show Symbols List.')
        vboxExplorer.addWidget(self.checkProjectExplorer)
        vboxExplorer.addWidget(self.checkSymbols)
        #GUI
        self.btnCentralRotate = QPushButton(QIcon(resources.images['splitCPosition']), '')
        self.btnCentralRotate.setIconSize(QSize(64, 64))
        self.btnCentralRotate.setCheckable(True)
        self.btnPanelsRotate = QPushButton(QIcon(resources.images['splitMPosition']), '')
        self.btnPanelsRotate.setIconSize(QSize(64, 64))
        self.btnPanelsRotate.setCheckable(True)
        self.btnCentralOrientation = QPushButton(QIcon(resources.images['splitCRotate']), '')
        self.btnCentralOrientation.setIconSize(QSize(64, 64))
        self.btnCentralOrientation.setCheckable(True)
        gridGuiConfig = QGridLayout(groupBoxGui)
        gridGuiConfig.addWidget(self.btnCentralRotate, 0, 0)
        gridGuiConfig.addWidget(self.btnPanelsRotate, 0, 1)
        gridGuiConfig.addWidget(self.btnCentralOrientation, 0, 2)
        gridGuiConfig.addWidget(QLabel("Rotate Central"), 1, 0, Qt.AlignCenter)
        gridGuiConfig.addWidget(QLabel("Rotate Lateral"), 1, 1, Qt.AlignCenter)
        gridGuiConfig.addWidget(QLabel("Central Orientation"), 1, 2, Qt.AlignCenter)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('interface')
        self.checkProjectExplorer.setCheckState(settings.value('showProjectExplorer', Qt.Checked).toInt()[0])
        self.checkSymbols.setCheckState(settings.value('showSymbolsList', Qt.Checked).toInt()[0])
        self.btnCentralRotate.setChecked(settings.value('centralRotate', False).toBool())
        self.btnPanelsRotate.setChecked(settings.value('panelsRotate', False).toBool())
        self.btnCentralOrientation.setChecked(settings.value('centralOrientation', False).toBool())
        settings.endGroup()
        settings.endGroup()

        vbox.addWidget(groupBoxExplorer)
        vbox.addWidget(groupBoxGui)

        #Signals
        self.connect(self.btnCentralRotate, SIGNAL('clicked()'), parent._splitter_central_rotate)
        self.connect(self.btnPanelsRotate, SIGNAL('clicked()'), parent._splitter_main_rotate)
        self.connect(self.btnCentralOrientation, SIGNAL('clicked()'), parent._splitter_central_orientation)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('interface')
        settings.setValue('showProjectExplorer', self.checkProjectExplorer.checkState())
        settings.setValue('showSymbolsList', self.checkSymbols.checkState())
        settings.setValue('centralRotate', self.btnCentralRotate.isChecked())
        settings.setValue('panelsRotate', self.btnPanelsRotate.isChecked())
        settings.setValue('centralOrientation', self.btnCentralOrientation.isChecked())
        settings.endGroup()
        settings.endGroup()
Beispiel #43
0
class GeneralTab(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)

        groupBoxStart = QGroupBox('On Start:')
        groupBoxClose = QGroupBox('On Close:')
        groupBoxWorkspace = QGroupBox('Workspace and Project:')

        #Start
        vboxStart = QVBoxLayout(groupBoxStart)
        self.checkLastSession = QCheckBox('Load files from last session')
        self.checkActivatePlugins = QCheckBox('Activate Plugins')
        self.checkNotifyUpdates = QCheckBox(
            'Nofity me for new available updates.')
        vboxStart.addWidget(self.checkLastSession)
        vboxStart.addWidget(self.checkActivatePlugins)
        vboxStart.addWidget(self.checkNotifyUpdates)
        #Close
        vboxClose = QVBoxLayout(groupBoxClose)
        self.checkConfirmExit = QCheckBox('Confirm Exit.')
        vboxClose.addWidget(self.checkConfirmExit)
        #Workspace and Project
        gridWorkspace = QGridLayout(groupBoxWorkspace)
        self.txtWorkspace = QLineEdit()
        self.txtWorkspace.setReadOnly(True)
        self.btnWorkspace = QPushButton(QIcon(resources.images['openFolder']),
                                        '')
        gridWorkspace.addWidget(QLabel('Workspace'), 0, 0, Qt.AlignRight)
        gridWorkspace.addWidget(self.txtWorkspace, 0, 1)
        gridWorkspace.addWidget(self.btnWorkspace, 0, 2)
        self.txtExtensions = QLineEdit()
        gridWorkspace.addWidget(QLabel('Supported Extensions:'), 1, 0,
                                Qt.AlignRight)
        gridWorkspace.addWidget(self.txtExtensions, 1, 1)
        self.txtPythonPath = QLineEdit()
        self.btnPythonPath = QPushButton(QIcon(resources.images['open']), '')
        gridWorkspace.addWidget(QLabel('Python Path:'), 2, 0, Qt.AlignRight)
        gridWorkspace.addWidget(self.txtPythonPath, 2, 1)
        gridWorkspace.addWidget(self.btnPythonPath, 2, 2)
        gridWorkspace.addWidget(
            QLabel('(This property need to be configured for Windows)'), 3, 1,
            Qt.AlignRight)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('general')
        self.checkLastSession.setCheckState(
            settings.value('loadFiles', Qt.Checked).toInt()[0])
        self.checkActivatePlugins.setCheckState(
            settings.value('activatePlugins', Qt.Checked).toInt()[0])
        self.checkNotifyUpdates.setCheckState(
            settings.value('notifyUpdates', Qt.Checked).toInt()[0])
        self.checkConfirmExit.setCheckState(
            settings.value('confirmExit', Qt.Checked).toInt()[0])
        self.txtWorkspace.setText(settings.value('workspace', '').toString())
        self.txtPythonPath.setText(
            settings.value('pythonPath', resources.python_path).toString())
        extensions = tuple(
            settings.value('extensions',
                           list(manage_files.supported_extensions)).toList())
        extensions = ', '.join([str(e.toString()) for e in extensions])
        self.txtExtensions.setText(extensions)
        settings.endGroup()
        settings.endGroup()

        vbox.addWidget(groupBoxStart)
        vbox.addWidget(groupBoxClose)
        vbox.addWidget(groupBoxWorkspace)

        #Signals
        self.connect(self.btnWorkspace, SIGNAL("clicked()"),
                     self._load_workspace)
        self.connect(self.btnPythonPath, SIGNAL("clicked()"),
                     self._load_python_path)

    def _load_workspace(self):
        path = str(QFileDialog.getExistingDirectory(self, 'Select Workspace'))
        self.txtWorkspace.setText(path)

    def _load_python_path(self):
        path = str(QFileDialog.getOpenFileName(self, 'Select Python Path'))
        self.txtPythonPath.setText(path)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('general')
        settings.setValue('loadFiles', self.checkLastSession.checkState())
        settings.setValue('activatePlugins',
                          self.checkActivatePlugins.checkState())
        settings.setValue('notifyUpdates',
                          self.checkNotifyUpdates.checkState())
        settings.setValue('confirmExit', self.checkConfirmExit.checkState())
        settings.setValue('workspace', self.txtWorkspace.text())
        settings.setValue('pythonPath', self.txtPythonPath.text())
        resources.python_path = str(self.txtPythonPath.text())
        resources.workspace = str(self.txtWorkspace.text())
        extensions = str(self.txtExtensions.text()).split(',')
        extensions = [e.strip() for e in extensions]
        settings.setValue('extensions', extensions)
        manage_files.supported_extensions = tuple(extensions)
        settings.endGroup()
        settings.endGroup()
class GeneralTab(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)

        groupBoxStart = QGroupBox('On Start:')
        groupBoxClose = QGroupBox('On Close:')
        groupBoxWorkspace = QGroupBox('Workspace and Project:')

        #Start
        vboxStart = QVBoxLayout(groupBoxStart)
        self.checkLastSession = QCheckBox('Load files from last session')
        self.checkActivatePlugins = QCheckBox('Activate Plugins')
        self.checkNotifyUpdates = QCheckBox('Nofity me for new available updates.')
        vboxStart.addWidget(self.checkLastSession)
        vboxStart.addWidget(self.checkActivatePlugins)
        vboxStart.addWidget(self.checkNotifyUpdates)
        #Close
        vboxClose = QVBoxLayout(groupBoxClose)
        self.checkConfirmExit = QCheckBox('Confirm Exit.')
        vboxClose.addWidget(self.checkConfirmExit)
        #Workspace and Project
        gridWorkspace = QGridLayout(groupBoxWorkspace)
        self.txtWorkspace = QLineEdit()
        self.txtWorkspace.setReadOnly(True)
        self.btnWorkspace = QPushButton(QIcon(resources.images['openFolder']), '')
        gridWorkspace.addWidget(QLabel('Workspace'), 0, 0, Qt.AlignRight)
        gridWorkspace.addWidget(self.txtWorkspace, 0, 1)
        gridWorkspace.addWidget(self.btnWorkspace, 0, 2)
        self.txtExtensions = QLineEdit()
        gridWorkspace.addWidget(QLabel('Supported Extensions:'), 1, 0, Qt.AlignRight)
        gridWorkspace.addWidget(self.txtExtensions, 1, 1)
        self.txtPythonPath = QLineEdit()
        self.btnPythonPath = QPushButton(QIcon(resources.images['open']), '')
        gridWorkspace.addWidget(QLabel('Python Path:'), 2, 0, Qt.AlignRight)
        gridWorkspace.addWidget(self.txtPythonPath, 2, 1)
        gridWorkspace.addWidget(self.btnPythonPath, 2, 2)
        gridWorkspace.addWidget(QLabel('(This property need to be configured for Windows)'), 3, 1, Qt.AlignRight)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('general')
        self.checkLastSession.setCheckState(settings.value('loadFiles', Qt.Checked).toInt()[0])
        self.checkActivatePlugins.setCheckState(settings.value('activatePlugins', Qt.Checked).toInt()[0])
        self.checkNotifyUpdates.setCheckState(settings.value('notifyUpdates', Qt.Checked).toInt()[0])
        self.checkConfirmExit.setCheckState(settings.value('confirmExit', Qt.Checked).toInt()[0])
        self.txtWorkspace.setText(settings.value('workspace', '').toString())
        self.txtPythonPath.setText(settings.value('pythonPath', resources.python_path).toString())
        extensions = tuple(settings.value('extensions', list(manage_files.supported_extensions)).toList())
        extensions = ', '.join([str(e.toString()) for e in extensions])
        self.txtExtensions.setText(extensions)
        settings.endGroup()
        settings.endGroup()

        vbox.addWidget(groupBoxStart)
        vbox.addWidget(groupBoxClose)
        vbox.addWidget(groupBoxWorkspace)

        #Signals
        self.connect(self.btnWorkspace, SIGNAL("clicked()"), self._load_workspace)
        self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path)

    def _load_workspace(self):
        path = str(QFileDialog.getExistingDirectory(self, 'Select Workspace'))
        self.txtWorkspace.setText(path)

    def _load_python_path(self):
        path = str(QFileDialog.getOpenFileName(self, 'Select Python Path'))
        self.txtPythonPath.setText(path)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('general')
        settings.setValue('loadFiles', self.checkLastSession.checkState())
        settings.setValue('activatePlugins', self.checkActivatePlugins.checkState())
        settings.setValue('notifyUpdates', self.checkNotifyUpdates.checkState())
        settings.setValue('confirmExit', self.checkConfirmExit.checkState())
        settings.setValue('workspace', self.txtWorkspace.text())
        settings.setValue('pythonPath', self.txtPythonPath.text())
        resources.python_path = str(self.txtPythonPath.text())
        resources.workspace = str(self.txtWorkspace.text())
        extensions = str(self.txtExtensions.text()).split(',')
        extensions = [e.strip() for e in extensions]
        settings.setValue('extensions', extensions)
        manage_files.supported_extensions = tuple(extensions)
        settings.endGroup()
        settings.endGroup()
class SingleCategoryView(QWidget):
    def __init__(self, action, parent, logger, category=None, mode=None):
        super(SingleCategoryView, self).__init__(parent)
        
        self.logger = logger
        self._action = action
        self._category = category
        self._resetting = False
        
        if mode is not None:
            topWidget = None
            self._determineOwnMode = False
        else:
            self._determineOwnMode = True
            mode = PrivacySettings.get().getPolicy(self._action, self._category, useModified=True, categoryPolicy=self._getCategoryPolicy())
            topWidget = self._initTopView(mode)
            
        centralWidget = self._initPeerList(mode)
        bottomWidget = self._initBottomWidget()
        
        mainLayout = QVBoxLayout(self)
        if topWidget is None:
            # inside multiple categories view -> no margins
            mainLayout.setContentsMargins(0, 0, 0, 0)
        if topWidget is not None:
            mainLayout.addWidget(topWidget)
        mainLayout.addWidget(centralWidget, 1)
        mainLayout.addWidget(bottomWidget)
        self._modeChanged(mode, notify=False, resetModel=False)
        
        get_notification_center().connectPeerNameAdded(self._peerModel.peerNameAdded)
        get_notification_center().connectDisplayedPeerNameChanged(self._peerModel.peerNameChanged)
        get_notification_center().connectPrivacySettingsChanged(self._privacySettingsChanged)
        get_notification_center().connectPrivacySettingsDiscarded(self._privacySettingsChanged)
        
    def finish(self):
        get_notification_center().disconnectPeerNameAdded(self._peerModel.peerNameAdded)
        get_notification_center().disconnectDisplayedPeerNameChanged(self._peerModel.peerNameChanged)
        get_notification_center().disconnectPrivacySettingsChanged(self._privacySettingsChanged)
        get_notification_center().disconnectPrivacySettingsDiscarded(self._privacySettingsChanged)
        
    def _getCategoryPolicy(self):
        return PrivacySettings.CATEGORY_NEVER if self._category is None else PrivacySettings.CATEGORY_ALWAYS
        
    def _initTopView(self, mode):
        topWidget = QWidget(self)
        
        self._modeCombo = QComboBox(topWidget)
        self._modeCombo.addItem(u"nobody")
        self._modeCombo.addItem(u"nobody, except")
        self._modeCombo.addItem(u"everybody, except")
        self._modeCombo.addItem(u"everybody")
        self._modeCombo.setCurrentIndex(mode)
        self._modeCombo.currentIndexChanged.connect(self._modeChanged)
        
        topLayout = QHBoxLayout(topWidget)
        topLayout.setContentsMargins(0, 0, 0, 0)
        topLayout.addWidget(QLabel(u"Accept from"), 0)
        topLayout.addWidget(self._modeCombo, 1, Qt.AlignLeft)
        return topWidget
        
    def _initPeerList(self, mode):
        capsuleWidget = QWidget()
        capsuleLayout = QVBoxLayout(capsuleWidget)
        capsuleLayout.setContentsMargins(10, 0, 10, 0)
        
        if mode in (PrivacySettings.POLICY_EVERYBODY_EX, PrivacySettings.POLICY_NOBODY_EX, PrivacySettings.POLICY_PEER_EXCEPTION):
            exceptions = PrivacySettings.get().getExceptions(self._action, self._category, mode, useModified=True, categoryPolicy=self._getCategoryPolicy())
        else:
            exceptions = {}
        self._peerModel = PeerModel(exceptions,
                                    mode == PrivacySettings.POLICY_PEER_EXCEPTION,
                                    self.logger)
        self._peerModel.itemChanged.connect(self._peerDataChanged)
        
        proxyModel = QSortFilterProxyModel(self)
        proxyModel.setDynamicSortFilter(True)
        proxyModel.setSortCaseSensitivity(Qt.CaseInsensitive)
        proxyModel.setSourceModel(self._peerModel)
        proxyModel.sort(0)
        
        self._peerList = QTreeView(self)
        self._peerList.setAlternatingRowColors(False)
        self._peerList.setHeaderHidden(True)
        self._peerList.setItemsExpandable(False)
        self._peerList.setIndentation(0)
        self._peerList.setModel(proxyModel)
        self._peerList.setSelectionMode(QTreeView.NoSelection)
        self._peerList.setAutoFillBackground(False)
        self._peerList.viewport().setAutoFillBackground(False)
        self._peerList.setFrameShape(QFrame.NoFrame)
        self._peerList.setFocusPolicy(Qt.NoFocus)
        
        capsuleLayout.addWidget(self._peerList)
        return capsuleWidget
    
    def _initBottomWidget(self):
        self._askForConfirmationBox = QCheckBox(u"Ask if state is unknown", self)
        self._askForConfirmationBox.stateChanged.connect(self._askForConfirmationChanged)
        return self._askForConfirmationBox
    
    @loggingSlot(QStandardItem)
    def _peerDataChanged(self, item):
        if not self._resetting:
            PrivacySettings.get().addException(self._action,
                                               self._category,
                                               self._mode,
                                               convert_string(item.data(PeerModel.KEY_ROLE).toString()),
                                               1 if item.checkState() == Qt.Checked else 0 if item.checkState() == Qt.Unchecked else -1,
                                               applyImmediately=False,
                                               categoryPolicy=self._getCategoryPolicy())
    
    @loggingSlot(int)
    def _askForConfirmationChanged(self, newState):
        if not self._resetting:
            PrivacySettings.get().setAskForConfirmation(self._action, self._category, newState == Qt.Checked, applyImmediately=False, categoryPolicy=self._getCategoryPolicy())
        
    @loggingSlot(int)
    def _modeChanged(self, newMode, notify=True, resetModel=True):
        self._resetting = True
        if newMode in (PrivacySettings.POLICY_EVERYBODY_EX, PrivacySettings.POLICY_NOBODY_EX, PrivacySettings.POLICY_PEER_EXCEPTION):
            if resetModel:
                # no change notifications, we are just resetting the model
                self._peerModel.itemChanged.disconnect(self._peerDataChanged)
                self._peerModel.setExceptionData(PrivacySettings.get().getExceptions(self._action, self._category, newMode, useModified=True, categoryPolicy=self._getCategoryPolicy()))
                self._peerModel.itemChanged.connect(self._peerDataChanged)
            self._peerList.setVisible(True)
        else:
            self._peerList.setVisible(False)
        
        if newMode == PrivacySettings.POLICY_NOBODY_EX:
            ask = PrivacySettings.get().getAskForConfirmation(self._action, self._category, useModified=True, categoryPolicy=self._getCategoryPolicy())
            self._askForConfirmationBox.setCheckState(Qt.Checked if ask else Qt.Unchecked)
            self._askForConfirmationBox.setVisible(True)
        else:
            self._askForConfirmationBox.setVisible(False)
        self._mode = newMode
        
        self._resetting = False
        if notify:
            PrivacySettings.get().setPolicy(self._action, self._category, self._mode, applyImmediately=False, categoryPolicy=self._getCategoryPolicy())
        
    def setMode(self, newMode):
        self._modeChanged(newMode, notify=False)

    def getCategory(self):
        return self._category

    @loggingSlot(object, object)
    def _privacySettingsChanged(self, pluginName, actionName):
        if pluginName != self._action.getPluginName() or actionName != self._action.getName():
            return
        if self._determineOwnMode:
            newMode = PrivacySettings.get().getPolicy(self._action, self._category, categoryPolicy=self._getCategoryPolicy())
        else:
            newMode = self._mode
        self._modeChanged(newMode, notify=False)
Beispiel #46
0
class SettingsPage(QWidget):
    """
    """
    ReloadSettings = pyqtSignal()
    TestSettings = pyqtSignal(dict) 
    def __init__(self, parent):
        """
        """
        super(SettingsPage, self).__init__()
        self.__core = parent
        self.config = None

        self.createWidgets()
        self.createConnections()
        
        self.loadCfg()
        
    def core(self):
        """
        """
        return self.__core

    def createConnections(self):
        """
        """
        self.saveButton.clicked.connect( self.__saveCfg )
        self.testButton.clicked.connect( self.testConnection )
        
    def createWidgets(self):
        """
        """
        qcCredGroup = QGroupBox(self.tr("HP ALM server credentials"))
        self.hpCredLogin = QLineEdit()
        self.hpCredPwd = QLineEdit()
        self.hpCredPwd.setEchoMode(QLineEdit.Password)
        qcCredLayout = QGridLayout()
        qcCredLayout.addWidget( QLabel("Login"), 0, 0)
        qcCredLayout.addWidget( self.hpCredLogin, 0, 1)
        qcCredLayout.addWidget( QLabel("Password"), 1, 0)
        qcCredLayout.addWidget( self.hpCredPwd, 1, 1)
        qcCredGroup.setLayout(qcCredLayout)
        
        qcSvrGroup = QGroupBox(self.tr("HP ALM server informations"))
        self.hpSvrURL = QLineEdit()
        self.hpSvrDomain = QLineEdit()
        self.hpSvrProject = QLineEdit()

        self.comAPI = QRadioButton("COM")
        self.comAPI.setChecked(False)
        self.comAPI.setEnabled(False)
        
        self.restAPI = QRadioButton("REST")
        self.restAPI.setChecked(True)
        
        layoutApi = QHBoxLayout()
        layoutApi.addWidget(self.comAPI)
        layoutApi.addWidget(self.restAPI)
        
        qcSvrLayout = QGridLayout()
        qcSvrLayout.addWidget( QLabel("URL"), 0, 0)
        qcSvrLayout.addWidget( self.hpSvrURL, 0, 1)
        qcSvrLayout.addWidget( QLabel("Domain"), 1, 0)
        qcSvrLayout.addWidget( self.hpSvrDomain, 1, 1)
        qcSvrLayout.addWidget( QLabel("Project"), 2, 0)
        qcSvrLayout.addWidget( self.hpSvrProject, 2, 1)
        qcSvrLayout.addWidget( QLabel("API"), 3, 0)
        qcSvrLayout.addLayout( layoutApi, 3, 1)
        
        qcSvrGroup.setLayout(qcSvrLayout)

        # begin export result settings
        qcExportResultGroup = QGroupBox(self.tr("Export results"))
        self.ignoreTcCheckBox = QCheckBox(self.tr("Ignore testcase(s)"))
        self.ignoreUncompleteCheckBox = QCheckBox(self.tr("Ignore uncomplete test(s)"))
        self.addFoldersTlCheckBox = QCheckBox(self.tr("Create missing folders in test lab"))
        self.addTestsetCheckBox = QCheckBox(self.tr("Create testset if missing in test lab"))
        self.addTestinstanceCheckBox = QCheckBox(self.tr("Create test instance in test set"))
        self.cfgsTestsetTable = DesignPage.ConfigsTableView(self, core=self.core())
        qcExportResultLayout = QVBoxLayout()
        qcExportResultLayout.addWidget( self.ignoreTcCheckBox )
        qcExportResultLayout.addWidget( self.ignoreUncompleteCheckBox )
        qcExportResultLayout.addWidget( self.addFoldersTlCheckBox )
        qcExportResultLayout.addWidget( self.addTestsetCheckBox )
        qcExportResultLayout.addWidget( self.addTestinstanceCheckBox )
        qcExportResultLayout.addWidget( QLabel("Custom TestSet Fields"))
        qcExportResultLayout.addWidget( self.cfgsTestsetTable )
        qcExportResultLayout.addStretch(1)
        qcExportResultGroup.setLayout(qcExportResultLayout)
        # end 
        
        # begin export test settings
        qcExportGroup = QGroupBox(self.tr("Export tests"))
        
        self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one"))
        self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one"))
        self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name"))
        self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname"))
        self.addFoldersTpCheckBox = QCheckBox(self.tr("Create missing folders in test plan"))
        self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcases in test plan"))
        self.cfgsTable = DesignPage.ConfigsTableView(self, core=self.core())

        qcExportLayout = QGridLayout()
        qcExportLayout.addWidget( self.mergeCheckBox, 0, 0)
        qcExportLayout.addWidget( self.mergeStepsCheckBox, 1, 0)
        qcExportLayout.addWidget( self.showTcNameCheckBox, 2, 0)
        qcExportLayout.addWidget( self.replaceTcCheckBox, 3, 0)
        qcExportLayout.addWidget( self.addFoldersTpCheckBox, 4, 0)
        qcExportLayout.addWidget( self.overwriteTcCheckBox, 5, 0)
        qcExportLayout.addWidget( QLabel("Custom Test Fields"), 6, 0)
        qcExportLayout.addWidget( self.cfgsTable, 7, 0)
        qcExportGroup.setLayout(qcExportLayout)
        # end 
        
        layoutCtrls = QHBoxLayout()
        self.saveButton = QPushButton(self.tr("Save Settings"), self)
        self.testButton = QPushButton(self.tr("Test Connection"), self)
        layoutCtrls.addWidget(self.saveButton)
        layoutCtrls.addWidget(self.testButton)
        
        mainLayout = QGridLayout()
        mainLayout.addWidget(qcSvrGroup, 0, 0)
        mainLayout.addWidget(qcCredGroup, 0, 1)
        mainLayout.addWidget(qcExportGroup, 2, 0)
        mainLayout.addWidget(qcExportResultGroup, 2, 1)
        mainLayout.addLayout(layoutCtrls, 3, 1)
        self.setLayout(mainLayout)
        
    def loadCfg(self):
        """
        """
        with open( "%s/config.json" % (QtHelper.dirExec()) ) as f:
            CONFIG_RAW = f.read()
        self.config = json.loads(CONFIG_RAW)

        self.hpCredLogin.setText(self.config["credentials"]["login"])
        self.hpSvrURL.setText(self.config["qc-server"]["url"])
        self.hpSvrDomain.setText(self.config["qc-server"]["domain"])
        self.hpSvrProject.setText(self.config["qc-server"]["project"])

        self.restAPI.setChecked(True) 
        
        if self.config["export-tests"]["merge-all-tests"]: 
            self.mergeCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["merge-all-steps"]: 
            self.mergeStepsCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["original-test"]: 
            self.showTcNameCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["replace-testcase"]: 
            self.replaceTcCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["add-folders"]: 
            self.addFoldersTpCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["overwrite-tests"]: 
            self.overwriteTcCheckBox.setCheckState(Qt.Checked) 
        self.cfgsTable.loadTable(data=self.config["custom-test-fields"])
        
        if self.config["export-results"]["ignore-testcase"]: 
            self.ignoreTcCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["ignore-uncomplete"]: 
            self.ignoreUncompleteCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-folders"]: 
            self.addFoldersTlCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-testset"]: 
            self.addTestsetCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-testinstance"]: 
            self.addTestinstanceCheckBox.setCheckState(Qt.Checked) 
        self.cfgsTestsetTable.loadTable(data=self.config["custom-testset-fields"])
        
        # decrypt password
        if len(self.config["credentials"]["password"]):
            decrypted = self.decryptPwd(
                                        key=bytes(self.config["credentials"]["login"], "utf8" ),
                                        ciphertext=bytes(self.config["credentials"]["password"], "utf8" )
                                        )
            self.config["credentials"]["password"] = decrypted
            self.hpCredPwd.setText(decrypted)

    def __saveCfg(self):
        """
        """
        self.saveCfg(successMsg=True)
        
    def saveCfg(self, successMsg=True):
        """
        """
        # if successMsg:
        if not len(self.hpSvrURL.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server url") )
            return
        if not len(self.hpSvrDomain.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server domain") )
            return
        if not len(self.hpSvrProject.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server project") )
            return

        if not len(self.hpCredLogin.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a login") )
            return
        if not len(self.hpCredPwd.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a password") )
            return
            
        self.config["credentials"]["login"] = self.hpCredLogin.text()
        # encrypt password
        encryptPwd = self.encryptPwd(
                                    key=self.hpCredLogin.text(),
                                    plaintext=self.hpCredPwd.text()
                                   )
        self.config["credentials"]["password"] = str(encryptPwd, "utf8")
        
        self.config["qc-server"]["url"] = self.hpSvrURL.text()
        self.config["qc-server"]["domain"] = self.hpSvrDomain.text()
        self.config["qc-server"]["project"] = self.hpSvrProject.text()
        self.config["qc-server"]["use-rest"] = False
        if self.restAPI.isChecked(): self.config["qc-server"]["use-rest"] = True
        
        self.config["export-tests"]["merge-all-tests"] = False
        self.config["export-tests"]["merge-all-steps"] = False
        self.config["export-tests"]["original-test"] = False
        self.config["export-tests"]["replace-testcase"] = False
        self.config["export-tests"]["add-folders"] = False
        self.config["export-tests"]["overwrite-tests"] = False
        if self.mergeCheckBox.isChecked(): self.config["export-tests"]["merge-all-tests"] = True
        if self.mergeStepsCheckBox.isChecked(): self.config["export-tests"]["merge-all-steps"] = True
        if self.showTcNameCheckBox.isChecked(): self.config["export-tests"]["original-test"] = True
        if self.replaceTcCheckBox.isChecked(): self.config["export-tests"]["replace-testcase"] = True
        if self.addFoldersTpCheckBox.isChecked(): self.config["export-tests"]["add-folders"] = True
        if self.overwriteTcCheckBox.isChecked(): self.config["export-tests"]["overwrite-tests"] = True
        self.config["custom-test-fields"] = self.cfgsTable.model.getData()
        
        self.config["export-results"]["add-folders"] = False
        self.config["export-results"]["ignore-testcase"] = False
        self.config["export-results"]["ignore-uncomplete"] = False
        self.config["export-results"]["add-testset"] = False
        self.config["export-results"]["add-testinstance"] = False
        if self.ignoreTcCheckBox.isChecked(): self.config["export-results"]["ignore-testcase"] = True
        if self.ignoreUncompleteCheckBox.isChecked(): self.config["export-results"]["ignore-uncomplete"] = True
        if self.addFoldersTlCheckBox.isChecked(): self.config["export-results"]["add-folders"] = True
        if self.addTestsetCheckBox.isChecked(): self.config["export-results"]["add-testset"] = True
        if self.addTestinstanceCheckBox.isChecked(): self.config["export-results"]["add-testinstance"] = True
        self.config["custom-testset-fields"] = self.cfgsTestsetTable.model.getData()
        
        with open( "%s/config.json" % (QtHelper.dirExec()), "w" ) as f:
            f.write( json.dumps(self.config) )
            
        if len(self.config["credentials"]["password"]):
            self.config["credentials"]["password"] = self.decryptPwd(
                                            key=bytes(self.config["credentials"]["login"], "utf8" ),
                                            ciphertext=bytes(self.config["credentials"]["password"], "utf8" )
                                  )
                
        self.ReloadSettings.emit()
        
        if successMsg: QMessageBox.information(self, self.tr("Save Settings") ,  self.tr("Settings saved.") )
                                
    def cfg(self):
        """
        """
        return self.config
        
    def encryptPwd(self, key, plaintext):
        """
        """
        return base64.b64encode( bytes( plaintext, "utf8" ) )

    def decryptPwd(self, key, ciphertext):
        """
        """
        return str( base64.b64decode(ciphertext) , "utf8")
    
    def testConnection(self):
        """
        """
        self.TestSettings.emit(self.config)
Beispiel #47
0
class CheckTrait(QWidget):
    """
	\brief An- bzw. Abwählbare Eigenschaft.

	Diese Eigensachft ist ähnlich wie CharaTrait mit den Eigenschaften im Speicher verknpüft, allerdings besitzen sie keine Werte, sondern sind nur an- oder Abwählbar. Beispiel für eine solche Eigenscahft sind die Nachteile.
	"""
    def __init__(self, trait, parent=None):
        super(CheckTrait, self).__init__(parent)

        self.__trait = trait

        #character = StorageCharacter::getInstance();

        self.__layout = QHBoxLayout()
        self.setLayout(self.__layout)

        self.__checkBox = QCheckBox()
        self.__checkBox.setText(trait.name)
        self.__checkBox.setMaximumHeight(Config.WIDGET_INLINE_HEIGHT_MAX)

        self.__lineEdit = QLineEdit()
        #self.__lineEdit.setMinimumWidth( Config.TRAIT_CUSTOMTEXT_WIDTH_MIN )
        self.__lineEdit.setMaximumHeight(Config.WIDGET_INLINE_HEIGHT_MAX)

        self.__layout.addWidget(self.__checkBox)
        self.__layout.addStretch()
        self.__layout.addWidget(self.__lineEdit)

        self.__checkBox.stateChanged.connect(self.setTraitValue)
        self.__lineEdit.textChanged.connect(self.setTraitCustomText)
        self.__trait.valueChanged.connect(self.setValue)
        if type(self.__trait) == StandardTrait:
            self.__trait.customTextChanged.connect(self.setText)
        self.__trait.availableChanged.connect(self.setEnabled)

    def __getValue(self):
        return self.__checkBox.checkState()

    def setValue(self, value):
        if value == 0:
            checkState = Qt.Unchecked
        elif value == 1:
            checkState = Qt.PartiallyChecked
        else:
            checkState = Qt.Checked

        self.__checkBox.setCheckState(checkState)

    value = property(__getValue, setValue)

    def setTraitValue(self, value):
        """
		Legt den Wert der Eigenschaft im Speicher fest.
		"""

        if (self.__trait.value != value):
            self.__trait.value = value

    def setText(self, text):
        """
		Legt den Zusatztext in diesem Widget fest.
		"""

        self.__lineEdit.setText(text)

    def setTraitCustomText(self, text):
        """
		Legt den Zusatztext der Eigenschaft im Speicher fest.
		"""

        if (self.__trait.customText != text):
            self.__trait.customText = text

    def setDescriptionHidden(self, sw):
        """
		Mit dieser Methode verstecke ich die Textzeile, in welcher zusätzlicher Beschreibungstext eingegeben werden kann.
		"""

        if (sw):
            self.__lineEdit.hide()
        else:
            self.__lineEdit.show()

    def hideOrShowTrait(self,
                        species=None,
                        age=None,
                        era=None,
                        breed=None,
                        faction=None):
        """
		Versteckt oder zeigt diese Eigenschaft.

		\note age und era gibt es zwar nicht bei SubPowerTrait, aber damit diese Funktion mit StorageCharacter.traitVisibleReasonChanged kompatible bleibt, werden sie als Argument übergeben.
		"""

        visible = True
        # Es können nur Eigenschaften versteckt werden, die einen age- bzw. era-Eintrag besitzen.
        if ((species and self.__trait.species
             and self.__trait.species != species) or
                #(age and self.__trait.age and self.__trait.age != age) or
                #(era and self.__trait.era and era not in self.__trait.era) or
            ((breed or faction) and self.__trait.only
             and breed not in self.__trait.only
             and faction not in self.__trait.only)):
            visible = False

        self.setVisible(visible)
Beispiel #48
0
class DockWidgetTitleBar(QWidget):
    def __init__(self, dockWidget, hasCheckState=False, hasReport=False):
        super(DockWidgetTitleBar, self).__init__(dockWidget)
        q = dockWidget
        self.floatButton = DockWidgetTitleBarButton(self)
        self.floatButton.setIcon(q.style().standardIcon(
            QStyle.SP_TitleBarNormalButton, None, q))
        self.floatButton.clicked.connect(self.toggleFloating)
        self.floatButton.setVisible(True)
        self.floatButton.setToolTip(self.tr("Undock"))
        self.closeButton = DockWidgetTitleBarButton(self)
        self.closeButton.setIcon(q.style().standardIcon(
            QStyle.SP_TitleBarCloseButton, None, q))
        self.closeButton.clicked.connect(dockWidget.close)
        self.closeButton.setVisible(True)
        self.closeButton.setToolTip(self.tr("Close"))

        if hasCheckState:
            self.checkStateButton = QCheckBox(self)
            self.checkStateButton.setCheckState(2)
            self.checkStateButton.setToolTip(self.tr("Disable this window"))
            self.connect(self.checkStateButton, SIGNAL("stateChanged(int)"),
                         self.toggleCheckState)
        else:
            self.checkStateButton = False
        dockWidget.featuresChanged.connect(self.featuresChanged)
        self.featuresChanged(0)
        self.reportIcon = QIcon(":report")
        if hasReport:
            self.reportButton = DockWidgetTitleBarButton(self)
            self.reportButton.setIcon(self.reportIcon)
            self.reportButton.clicked.connect(self.toggleReport)
            self.reportButton.setVisible(True)
            self.reportButton.setToolTip(self.tr("Add content to report"))
        else:
            self.reportButton = None

    def hasFeature(self, dockwidget, feature):
        return dockwidget.features() & feature == feature

    def minimumSizeHint(self):
        return self.sizeHint()

    def sizeHint(self):
        q = self.parentWidget()
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
        closeSize = QSize(0, 0)
        if self.closeButton:
            closeSize = self.closeButton.sizeHint()

        floatSize = QSize(0, 0)
        if self.floatButton:
            floatSize = self.floatButton.sizeHint()
        hideSize = self.hideSizeHint()

        buttonHeight = max(max(closeSize.height(), floatSize.height()),
                           hideSize.height()) + 2
        buttonWidth = closeSize.width() + floatSize.width() + hideSize.width()
        titleFontMetrics = q.fontMetrics()
        fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
        height = max(buttonHeight, fontHeight)
        return QSize(buttonWidth + height + 4 * mw + 2 * fw, height)

    def hideSizeHint(self):
        if self.reportButton and self.checkStateButton:
            return self.reportButton.sizeHint(
            ) + self.checkStateButton.sizeHint()
        elif self.reportButton:
            return self.reportButton.sizeHint()
        elif self.checkStateButton:
            return self.checkStateButton.sizeHint()
        else:
            return QSize(0, 0)

    def paintEvent(self, _event):
        p = QStylePainter(self)
        q = self.parentWidget()
        fw = q.isFloating() and q.style().pixelMetric(
            QStyle.PM_DockWidgetFrameWidth, None, q) or 0
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        titleOpt = QStyleOptionDockWidgetV2()
        titleOpt.initFrom(q)
        titleOpt.rect = self.titleOptionRect(fw, mw)
        titleOpt.title = q.windowTitle()
        titleOpt.closable = self.hasFeature(q, QDockWidget.DockWidgetClosable)
        titleOpt.floatable = self.hasFeature(q,
                                             QDockWidget.DockWidgetFloatable)
        p.drawControl(QStyle.CE_DockWidgetTitle, titleOpt)

    def titleOptionRect(self, fw, mw):
        if self.reportButton and self.checkStateButton:
            return QRect(
                QPoint(
                    fw + mw + self.reportButton.size().width() +
                    self.checkStateButton.size().width(), fw),
                QSize(
                    self.geometry().width() - (fw * 2) - mw -
                    self.reportButton.size().width() -
                    self.checkStateButton.size().width(),
                    self.geometry().height() - (fw * 2)))
        elif self.reportButton:
            return QRect(
                QPoint(fw + mw + self.reportButton.size().width(), fw),
                QSize(
                    self.geometry().width() - (fw * 2) - mw -
                    self.reportButton.size().width(),
                    self.geometry().height() - (fw * 2)))
        elif self.checkStateButton:
            return QRect(
                QPoint(fw + mw + self.checkStateButton.size().width(), fw),
                QSize(
                    self.geometry().width() - (fw * 2) - mw -
                    self.checkStateButton.size().width(),
                    self.geometry().height() - (fw * 2)))
        else:
            return QRect(
                QPoint(fw + mw, fw),
                QSize(self.geometry().width() - (fw * 2) - mw,
                      self.geometry().height() - (fw * 2)))

    def resizeEvent(self, _event):
        q = self.parentWidget()
        fw = q.isFloating() and q.style().pixelMetric(
            QStyle.PM_DockWidgetFrameWidth, None, q) or 0
        opt = QStyleOptionDockWidgetV2()
        opt.initFrom(q)
        opt.rect = QRect(
            QPoint(fw, fw),
            QSize(self.geometry().width() - (fw * 2),
                  self.geometry().height() - (fw * 2)))
        opt.title = q.windowTitle()
        opt.closable = self.hasFeature(q, QDockWidget.DockWidgetClosable)
        opt.floatable = self.hasFeature(q, QDockWidget.DockWidgetFloatable)
        floatRect = q.style().subElementRect(QStyle.SE_DockWidgetFloatButton,
                                             opt, q)
        if not floatRect.isNull():
            self.floatButton.setGeometry(floatRect)
        closeRect = q.style().subElementRect(QStyle.SE_DockWidgetCloseButton,
                                             opt, q)
        if not closeRect.isNull():
            self.closeButton.setGeometry(closeRect)
        top = fw
        if not floatRect.isNull():
            top = floatRect.y()
        elif not closeRect.isNull():
            top = closeRect.y()
        if self.checkStateButton:
            size = self.checkStateButton.size()
            if not closeRect.isNull():
                size = self.closeButton.size()
            elif not floatRect.isNull():
                size = self.floatButton.size()
            checkStateRect = QRect(QPoint(fw, top), size)
            self.checkStateButton.setGeometry(checkStateRect)
        if self.reportButton:
            size = self.reportButton.size()
            if not closeRect.isNull():
                size = self.closeButton.size()
            elif not floatRect.isNull():
                size = self.floatButton.size()
            reportRect = QRect(QPoint(fw, top), size)
            self.reportButton.setGeometry(reportRect)

    def toggleFloating(self):
        parent = self.parentWidget()
        parent.setFloating(not parent.isFloating())

    def toggleCheckState(self, state):
        parent = self.parentWidget()
        if parent:
            if state != 0:
                parent.updateCheckState(True)
            else:
                parent.updateCheckState(False)

    def toggleReport(self):
        parent = self.parentWidget()
        if parent:
            parent.report()

    def featuresChanged(self, _features):
        parent = self.parentWidget()
        self.closeButton.setVisible(
            self.hasFeature(parent, QDockWidget.DockWidgetClosable))
        self.floatButton.setVisible(
            self.hasFeature(parent, QDockWidget.DockWidgetFloatable))
Beispiel #49
0
class StatusBar(QStatusBar):

    def __init__(self):
        QStatusBar.__init__(self)
        self.editor = None

        self.widgetStatus = QWidget()
        vbox = QVBoxLayout(self.widgetStatus)
        vbox.setContentsMargins(0, 0, 0, 0)
        #Search Layout
        hSearch = QHBoxLayout()
        self.line = TextLine(self)
        self.line.setMinimumWidth(250)
        self.checkBackward = QCheckBox('Find Backward')
        self.checkSensitive = QCheckBox('Respect Case Sensitive')
        self.checkWholeWord = QCheckBox('Find Whole Words')
        self.btnClose = QPushButton(self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btnFind = QPushButton(QIcon(resources.images['find']), '')
        self.btnPrevious = QPushButton(self.style().standardIcon(QStyle.SP_ArrowLeft), '')
        self.btnNext = QPushButton(self.style().standardIcon(QStyle.SP_ArrowRight), '')
        hSearch.addWidget(self.btnClose)
        hSearch.addWidget(self.line)
        hSearch.addWidget(self.btnFind)
        hSearch.addWidget(self.btnPrevious)
        hSearch.addWidget(self.btnNext)
        hSearch.addWidget(self.checkBackward)
        hSearch.addWidget(self.checkSensitive)
        hSearch.addWidget(self.checkWholeWord)
        vbox.addLayout(hSearch)
        #Replace Layout
        hReplace = QHBoxLayout()
        self.lineReplace = TextLine(self)
        self.lineReplace.setMinimumWidth(250)
        self.btnCloseReplace = QPushButton(self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btnReplace = QPushButton('Replace')
        self.btnReplaceAll = QPushButton('Replace All')
        hReplace.addWidget(self.btnCloseReplace)
        hReplace.addWidget(self.lineReplace)
        hReplace.addWidget(self.btnReplace)
        hReplace.addWidget(self.btnReplaceAll)
        vbox.addLayout(hReplace)
        self.replace_visibility(False)

        self.addWidget(self.widgetStatus)

        self.shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self)

        self.connect(self.btnClose, SIGNAL("clicked()"), self.hide_status)
        self.connect(self.btnFind, SIGNAL("clicked()"), self.find)
        self.connect(self.btnNext, SIGNAL("clicked()"), self.find_next)
        self.connect(self.btnPrevious, SIGNAL("clicked()"), self.find_previous)
        self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end)
        self.connect(self.btnCloseReplace, SIGNAL("clicked()"), lambda: self.replace_visibility(False))
        self.connect(self.btnReplace, SIGNAL("clicked()"), self.replace)
        self.connect(self.btnReplaceAll, SIGNAL("clicked()"), self.replace_all)
        self.connect(self.shortEsc, SIGNAL("activated()"), self.hide_status)

    def focus_find(self, editor):
        self.line.setFocus()
        self.editor = editor
        self.line.selectAll()

    def replace_visibility(self, val):
        self.lineReplace.setVisible(val)
        self.btnCloseReplace.setVisible(val)
        self.btnReplace.setVisible(val)
        self.btnReplaceAll.setVisible(val)

    def hide_status(self):
        self.checkSensitive.setCheckState(Qt.Unchecked)
        self.checkWholeWord.setCheckState(Qt.Unchecked)
        self.checkBackward.setCheckState(Qt.Unchecked)
        self.hide()
        self.replace_visibility(False)
        self.editor.setFocus()

    def replace(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w)

    def replace_all(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w, True)

    def find(self):
        b = False if self.checkBackward.checkState() == Qt.Unchecked else True
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.find_match(str(self.line.text()), b, s, w)

    def find_next(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.find_match(str(self.line.text()), False, s, w)

    def find_previous(self):
        s = False if self.checkSensitive.checkState() == Qt.Unchecked else True
        w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True
        self.editor.find_match(str(self.line.text()), True, s, w)

    def showMessage(self, message, timeout):
        self.show()
        super(StatusBar, self).showMessage(message, timeout)

    def message_end(self, message):
        if message == '':
            self.hide()
            super(StatusBar, self).clearMessage()
Beispiel #50
0
class EkdMessage(QDialog):
    '''
    EkdMessage : Classe représentant une boite de dialogue avec un texte,
    des bouton et une icone permettant d'avertir l'utilisateur
    '''
    def __init__(self, titre, texte="", min_w=320, min_h=250, max_w=500,
                    max_h=600, icone="Icones/messagebox_info.png",
                    checkbox=False, parent=None):
        """Boite de message standard pour ekd.
           Usage :
             1. initialisation en spécifiant la taille, le titre et
                éventuellement le texte de la fenêtre.
                l'icone est également paramétrable
             2. Ajout du text avec la fonction setAideText.
             3. Affichage de la fenêtre en appelant la fonction show().
           Facilité :
             1. Redimensionnement de la fenêtre par appel de la fonction
                setSize(w, h)
             2. Ajout automatique des bars de défilement."""
        super(EkdMessage, self).__init__(parent)
        self.setWindowTitle(titre)
        self.setMaximumHeight(max_h)
        self.setMaximumWidth(max_w)
        self.setMinimumHeight(min_h)
        self.setMinimumWidth(min_w)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setVerticalStretch(1)
        self.setSizePolicy(sizePolicy)

        self.w = min_w
        self.h = min_h
        self.verticalLayout = QVBoxLayout(self)
        self.hbox1 = QHBoxLayout()
        self.vbox1 = QVBoxLayout()

        # Icone
        self.iconeI = QLabel(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
                    self.iconeI.sizePolicy().hasHeightForWidth())
        self.iconeI.setSizePolicy(sizePolicy)
        self.iconeI.setPixmap(QPixmap(icone))
        self.vbox1.addWidget(self.iconeI)
        spacerItem = QSpacerItem(20, 40,
                                QSizePolicy.Minimum,
                                QSizePolicy.Expanding)
        self.vbox1.addItem(spacerItem)
        self.hbox1.addLayout(self.vbox1)
        ##

        # Definition de la zone de texte
        self.text = QTextEdit(self)

        ## On utilise le même thème que la fenêtre pour la zone de texte
        ## On force les couleur ici, on ne laisse pas le Thème s'en charger
        palette = self.text.palette()
        palette.setBrush(QPalette.Active,
                            QPalette.Base,
                            self.palette().window())
        palette.setBrush(QPalette.Inactive,
                            QPalette.Base,
                            self.palette().window())
        palette.setBrush(QPalette.Disabled,
                            QPalette.Base,
                            self.palette().window())
        palette.setBrush(QPalette.Active,
                            QPalette.Text,
                            self.palette().windowText())
        palette.setBrush(QPalette.Inactive,
                            QPalette.Text,
                            self.palette().windowText())
        palette.setBrush(QPalette.Disabled,
                            QPalette.Text,
                            self.palette().windowText())
        self.text.setPalette(palette)

        self.text.setFrameShape(QFrame.NoFrame)
        self.text.setFrameShadow(QFrame.Plain)
        self.text.setLineWidth(0)
        self.text.setReadOnly(True)
        self.text.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.text.sizePolicy().hasHeightForWidth())
        self.text.setSizePolicy(sizePolicy)
        self.hbox1.addWidget(self.text)
        ##

        self.verticalLayout.addLayout(self.hbox1)
        self.hbox2 = QHBoxLayout()
        self.ok = QPushButton(self)
        self.ok.setText(_("Ok"))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.ok.sizePolicy().hasHeightForWidth())
        self.ok.setSizePolicy(sizePolicy)
        self.hbox2.addWidget(self.ok)
        self.verticalLayout.addLayout(self.hbox2)
        self.setText(texte)

        '''
        Checkbox pour savoir si l'utilisateur veut oui ou non revoir
        l'avertissement
        '''
        if checkbox :
            self.checkbox = QCheckBox(_(u"Voir ce message la prochaine fois"),
                                        self)
            self.hbox2.addWidget(self.checkbox)
            try :
                self.checkbox.setCheckState(int(EkdConfig.get("general",
                                                    "show_warning_messages")))
            except Exception, e:
                #print "First time launched"
		EkdPrint(u"First time launched")
            self.connect(self.checkbox, SIGNAL("stateChanged(int)"),
                                                    self.setDontShow)

        self.connect(self.ok, SIGNAL("clicked()"), self.close)
class QgsAnnotationWidget(QWidget):
    def __init__(self, parent, item):
        QWidget.__init__(self, parent)
        self.gridLayout_2 = QGridLayout(self)
        self.gridLayout_2.setObjectName(("gridLayout_2"))
        self.mMapPositionFixedCheckBox = QCheckBox(self)
        self.mMapPositionFixedCheckBox.setObjectName(
            ("mMapPositionFixedCheckBox"))
        self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1)
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName(("gridLayout"))
        self.mFrameColorButton = QgsColorButton(self)
        self.mFrameColorButton.setText((""))
        self.mFrameColorButton.setObjectName(("mFrameColorButton"))
        self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1)
        self.mFrameColorButton.colorChanged.connect(
            self.on_mFrameColorButton_colorChanged)
        self.mBackgroundColorLabel = QLabel(self)
        self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel"))
        self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1)
        self.mMapMarkerLabel = QLabel(self)
        self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel"))
        self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1)
        self.mBackgroundColorButton = QgsColorButton(self)
        self.mBackgroundColorButton.setText((""))
        self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton"))
        self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1)
        self.mBackgroundColorButton.colorChanged.connect(
            self.on_mBackgroundColorButton_colorChanged)
        self.mMapMarkerButton = QPushButton(self)
        self.mMapMarkerButton.setText((""))
        self.mMapMarkerButton.setObjectName(("mMapMarkerButton"))
        self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1)
        self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked)
        self.mFrameWidthLabel = QLabel(self)
        self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel"))
        self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1)
        self.mFrameWidthSpinBox = QDoubleSpinBox(self)
        self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox"))
        self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1)
        self.mFrameColorLabel = QLabel(self)
        self.mFrameColorLabel.setObjectName(("mFrameColorLabel"))
        self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1)
        self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton)
        self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox)

        self.setWindowTitle("QgsAnnotationWidgetBase")
        self.mMapPositionFixedCheckBox.setText("Fixed map position")
        self.mBackgroundColorLabel.setText("Background color")
        self.mMapMarkerLabel.setText("Map marker")
        self.mFrameWidthLabel.setText("Frame width")
        self.mFrameColorLabel.setText("Frame color")
        self.setLayout(self.gridLayout_2)
        self.mItem = item
        if (self.mItem != None):
            self.blockAllSignals(True)

            if (self.mItem.mapPositionFixed()):
                self.mMapPositionFixedCheckBox.setCheckState(Qt.Checked)
            else:
                self.mMapPositionFixedCheckBox.setCheckState(Qt.Unchecked)

            self.mFrameWidthSpinBox.setValue(self.mItem.frameBorderWidth())
            self.mFrameColorButton.setColor(self.mItem.frameColor())
            self.mFrameColorButton.setColorDialogTitle("Select frame color")
            self.mFrameColorButton.setColorDialogOptions(
                QColorDialog.ShowAlphaChannel)
            self.mBackgroundColorButton.setColor(
                self.mItem.frameBackgroundColor())
            self.mBackgroundColorButton.setColorDialogTitle(
                "Select background color")
            self.mBackgroundColorButton.setColorDialogOptions(
                QColorDialog.ShowAlphaChannel)
            self.symbol = self.mItem.markerSymbol()
            if (self.symbol != None):
                self.mMarkerSymbol = self.symbol.clone()
                self.updateCenterIcon()
            self.blockAllSignals(False)

    def apply(self):
        if (self.mItem != None):
            self.mItem.setMapPositionFixed(
                self.mMapPositionFixedCheckBox.checkState() == Qt.Checked)
            self.mItem.setFrameBorderWidth(self.mFrameWidthSpinBox.value())
            self.mItem.setFrameColor(self.mFrameColorButton.color())
            self.mItem.setFrameBackgroundColor(
                self.mBackgroundColorButton.color())
            self.mItem.setMarkerSymbol(self.mMarkerSymbol)
            self.mMarkerSymbol = None  #//item takes ownership
            self.mItem.update()

    def blockAllSignals(self, block):
        self.mMapPositionFixedCheckBox.blockSignals(block)
        self.mMapMarkerButton.blockSignals(block)
        self.mFrameWidthSpinBox.blockSignals(block)
        self.mFrameColorButton.blockSignals(block)

    def on_mMapMarkerButton_clicked(self):
        if (self.mMarkerSymbol == None):
            return
        markerSymbol = self.mMarkerSymbol.clone()
        dlg = QgsSymbolV2SelectorDialog(markerSymbol,
                                        QgsStyleV2.defaultStyle(), None, self)
        if (dlg.exec_() != QDialog.Rejected):
            self.mMarkerSymbol = markerSymbol
            self.updateCenterIcon()

    def on_mFrameColorButton_colorChanged(self, color):
        if (self.mItem == None):
            return
        self.mItem.setFrameColor(color)

    def updateCenterIcon(self):
        if (self.mMarkerSymbol == None):
            return
        icon = QgsSymbolLayerV2Utils.symbolPreviewIcon(
            self.mMarkerSymbol, self.mMapMarkerButton.iconSize())
        self.mMapMarkerButton.setIcon(icon)

    def on_mBackgroundColorButton_colorChanged(self, color):
        if (self.mItem == None):
            return
        self.mItem.setFrameBackgroundColor(color)
Beispiel #52
0
    def _set_add_rocon_master(self):
        print '_add_rocon_master'
        if self._connect_dlg_isValid:
            print "Dialog is live!!"
            self._connect_dlg.done(0)

        #dialog
        self._connect_dlg = QDialog(self._widget_main)
        self._connect_dlg.setWindowTitle("Add Ros Master")
        self._connect_dlg.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)
        self._connect_dlg.setMinimumSize(350, 0)
        # dlg_rect = self._connect_dlg.geometry()

        #dialog layout
        ver_layout = QVBoxLayout(self._connect_dlg)
        ver_layout.setContentsMargins(9, 9, 9, 9)

        #param layout
        text_grid_sub_widget = QWidget()
        text_grid_layout = QGridLayout(text_grid_sub_widget)
        text_grid_layout.setColumnStretch(1, 0)
        text_grid_layout.setRowStretch(2, 0)

        #param 1
        title_widget1 = QLabel("MASTER_URI: ")
        context_widget1 = QTextEdit()
        context_widget1.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)
        context_widget1.setMinimumSize(0, 30)
        context_widget1.append(self.master_uri)

        #param 2
        title_widget2 = QLabel("HOST_NAME: ")
        context_widget2 = QTextEdit()
        context_widget2.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)
        context_widget2.setMinimumSize(0, 30)
        context_widget2.append(self.host_name)

        #add param
        text_grid_layout.addWidget(title_widget1)
        text_grid_layout.addWidget(context_widget1)
        text_grid_layout.addWidget(title_widget2)
        text_grid_layout.addWidget(context_widget2)

        #add param layout
        ver_layout.addWidget(text_grid_sub_widget)

        #button layout
        button_hor_sub_widget = QWidget()
        button_hor_layout = QHBoxLayout(button_hor_sub_widget)

        params = {}
        params['param1'] = context_widget1
        params['param2'] = context_widget2

        #check box
        use_env_var_check = QCheckBox("Use environment variables")
        use_env_var_check.setCheckState(Qt.Unchecked)

        def set_use_env_var(data, text_widget1, text_widget2):
            if data == Qt.Unchecked:
                text_widget1.setText(self.master_uri)
                text_widget2.setText(self.host_name)
            elif data == Qt.Checked:
                self.master_uri = str(text_widget1.toPlainText())
                self.host_name = str(text_widget2.toPlainText())
                text_widget1.setText(self.env_master_uri)
                text_widget2.setText(self.env_host_name)

        def check_event(data):
            set_use_env_var(data, context_widget1, context_widget2)

        use_env_var_check.stateChanged.connect(check_event)
        ver_layout.addWidget(use_env_var_check)

        #button
        btn_call = QPushButton("Add")
        btn_cancel = QPushButton("Cancel")

        btn_call.clicked.connect(lambda: self._connect_dlg.done(0))
        btn_call.clicked.connect(lambda: self._add_rocon_master(params))

        btn_cancel.clicked.connect(lambda: self._connect_dlg.done(0))

        #add button
        button_hor_layout.addWidget(btn_call)
        button_hor_layout.addWidget(btn_cancel)

        #add button layout
        ver_layout.addWidget(button_hor_sub_widget)
        self._connect_dlg.setVisible(True)
        self._connect_dlg.finished.connect(self._destroy_connect_dlg)
        self._connect_dlg_isValid = True
Beispiel #53
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        self.tpr.start()
        
    def quitProcessRunner(self):
        self.tpr.join()
        self.tpr.quit()
        self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()
Beispiel #54
0
class InterfaceTab(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        self._main = parent

        groupBoxExplorer = QGroupBox('Explorer Panel:')
        groupBoxGui = QGroupBox('GUI Customization:')

        #Explorer
        vboxExplorer = QVBoxLayout(groupBoxExplorer)
        self.checkProjectExplorer = QCheckBox('Show Project Explorer.')
        self.checkSymbols = QCheckBox('Show Symbols List.')
        vboxExplorer.addWidget(self.checkProjectExplorer)
        vboxExplorer.addWidget(self.checkSymbols)
        #GUI
        self.btnCentralRotate = QPushButton(
            QIcon(resources.images['splitCPosition']), '')
        self.btnCentralRotate.setIconSize(QSize(64, 64))
        self.btnCentralRotate.setCheckable(True)
        self.btnPanelsRotate = QPushButton(
            QIcon(resources.images['splitMPosition']), '')
        self.btnPanelsRotate.setIconSize(QSize(64, 64))
        self.btnPanelsRotate.setCheckable(True)
        self.btnCentralOrientation = QPushButton(
            QIcon(resources.images['splitCRotate']), '')
        self.btnCentralOrientation.setIconSize(QSize(64, 64))
        self.btnCentralOrientation.setCheckable(True)
        gridGuiConfig = QGridLayout(groupBoxGui)
        gridGuiConfig.addWidget(self.btnCentralRotate, 0, 0)
        gridGuiConfig.addWidget(self.btnPanelsRotate, 0, 1)
        gridGuiConfig.addWidget(self.btnCentralOrientation, 0, 2)
        gridGuiConfig.addWidget(QLabel("Rotate Central"), 1, 0, Qt.AlignCenter)
        gridGuiConfig.addWidget(QLabel("Rotate Lateral"), 1, 1, Qt.AlignCenter)
        gridGuiConfig.addWidget(QLabel("Central Orientation"), 1, 2,
                                Qt.AlignCenter)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('interface')
        self.checkProjectExplorer.setCheckState(
            settings.value('showProjectExplorer', Qt.Checked).toInt()[0])
        self.checkSymbols.setCheckState(
            settings.value('showSymbolsList', Qt.Checked).toInt()[0])
        self.btnCentralRotate.setChecked(
            settings.value('centralRotate', False).toBool())
        self.btnPanelsRotate.setChecked(
            settings.value('panelsRotate', False).toBool())
        self.btnCentralOrientation.setChecked(
            settings.value('centralOrientation', False).toBool())
        settings.endGroup()
        settings.endGroup()

        vbox.addWidget(groupBoxExplorer)
        vbox.addWidget(groupBoxGui)

        #Signals
        self.connect(self.btnCentralRotate, SIGNAL('clicked()'),
                     parent._splitter_central_rotate)
        self.connect(self.btnPanelsRotate, SIGNAL('clicked()'),
                     parent._splitter_main_rotate)
        self.connect(self.btnCentralOrientation, SIGNAL('clicked()'),
                     parent._splitter_central_orientation)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('interface')
        settings.setValue('showProjectExplorer',
                          self.checkProjectExplorer.checkState())
        settings.setValue('showSymbolsList', self.checkSymbols.checkState())
        settings.setValue('centralRotate', self.btnCentralRotate.isChecked())
        settings.setValue('panelsRotate', self.btnPanelsRotate.isChecked())
        settings.setValue('centralOrientation',
                          self.btnCentralOrientation.isChecked())
        settings.endGroup()
        settings.endGroup()
Beispiel #55
0
class FindReplace(QWidget):
    """
    Find widget
    
    Signals:
        visibility_changed(bool)
    """
    STYLE = {False: "background-color:rgb(255, 175, 90);",
             True: ""}
    def __init__(self, parent, enable_replace=False):
        QWidget.__init__(self, parent)
        self.enable_replace = enable_replace
        self.editor = None
        self.is_code_editor = None
        
        glayout = QGridLayout()
        glayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(glayout)
        
        self.close_button = create_toolbutton(self, triggered=self.hide,
                                      icon=get_std_icon("DialogCloseButton"))
        glayout.addWidget(self.close_button, 0, 0)
        
        # Find layout
        self.search_text = PatternComboBox(self, tip=_("Search string"),
                                           adjust_to_minimum=False)
        self.connect(self.search_text, SIGNAL('valid(bool)'),
                     lambda state:
                     self.find(changed=False, forward=True, rehighlight=False))
        self.connect(self.search_text.lineEdit(),
                     SIGNAL("textEdited(QString)"), self.text_has_been_edited)
        
        self.previous_button = create_toolbutton(self,
                                             triggered=self.find_previous,
                                             icon=get_std_icon("ArrowBack"))
        self.next_button = create_toolbutton(self,
                                             triggered=self.find_next,
                                             icon=get_std_icon("ArrowForward"))
        self.connect(self.next_button, SIGNAL('clicked()'),
                     self.update_search_combo)
        self.connect(self.previous_button, SIGNAL('clicked()'),
                     self.update_search_combo)

        self.re_button = create_toolbutton(self, icon=get_icon("advanced.png"),
                                           tip=_("Regular expression"))
        self.re_button.setCheckable(True)
        self.connect(self.re_button, SIGNAL("toggled(bool)"),
                     lambda state: self.find())
        
        self.case_button = create_toolbutton(self,
                                             icon=get_icon("upper_lower.png"),
                                             tip=_("Case Sensitive"))
        self.case_button.setCheckable(True)
        self.connect(self.case_button, SIGNAL("toggled(bool)"),
                     lambda state: self.find())
                     
        self.words_button = create_toolbutton(self,
                                              icon=get_icon("whole_words.png"),
                                              tip=_("Whole words"))
        self.words_button.setCheckable(True)
        self.connect(self.words_button, SIGNAL("toggled(bool)"),
                     lambda state: self.find())
                     
        self.highlight_button = create_toolbutton(self,
                                              icon=get_icon("highlight.png"),
                                              tip=_("Highlight matches"))
        self.highlight_button.setCheckable(True)
        self.connect(self.highlight_button, SIGNAL("toggled(bool)"),
                     self.toggle_highlighting)

        hlayout = QHBoxLayout()
        self.widgets = [self.close_button, self.search_text,
                        self.previous_button, self.next_button,
                        self.re_button, self.case_button, self.words_button,
                        self.highlight_button]
        for widget in self.widgets[1:]:
            hlayout.addWidget(widget)
        glayout.addLayout(hlayout, 0, 1)

        # Replace layout
        replace_with = QLabel(_("Replace with:"))
        self.replace_text = PatternComboBox(self, adjust_to_minimum=False,
                                            tip=_("Replace string"))
        
        self.replace_button = create_toolbutton(self,
                                     text=_("Replace/find"),
                                     icon=get_std_icon("DialogApplyButton"),
                                     triggered=self.replace_find,
                                     text_beside_icon=True)
        self.connect(self.replace_button, SIGNAL('clicked()'),
                     self.update_replace_combo)
        self.connect(self.replace_button, SIGNAL('clicked()'),
                     self.update_search_combo)
        
        self.all_check = QCheckBox(_("Replace all"))
        
        self.replace_layout = QHBoxLayout()
        widgets = [replace_with, self.replace_text, self.replace_button,
                   self.all_check]
        for widget in widgets:
            self.replace_layout.addWidget(widget)
        glayout.addLayout(self.replace_layout, 1, 1)
        self.widgets.extend(widgets)
        self.replace_widgets = widgets
        self.hide_replace()
        
        self.search_text.setTabOrder(self.search_text, self.replace_text)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        self.findnext_sc = QShortcut(QKeySequence("F3"), parent,
                                     self.find_next)
        self.findnext_sc.setContext(Qt.WidgetWithChildrenShortcut)
        self.findprev_sc = QShortcut(QKeySequence("Shift+F3"), parent,
                                     self.find_previous)
        self.findprev_sc.setContext(Qt.WidgetWithChildrenShortcut)
        self.togglefind_sc = QShortcut(QKeySequence("Ctrl+F"), parent,
                                       self.show)
        self.togglefind_sc.setContext(Qt.WidgetWithChildrenShortcut)
        self.togglereplace_sc = QShortcut(QKeySequence("Ctrl+H"), parent,
                                          self.toggle_replace_widgets)
        self.togglereplace_sc.setContext(Qt.WidgetWithChildrenShortcut)
        
        escape_sc = QShortcut(QKeySequence("Escape"), parent, self.hide)
        escape_sc.setContext(Qt.WidgetWithChildrenShortcut)

        self.highlight_timer = QTimer(self)
        self.highlight_timer.setSingleShot(True)
        self.highlight_timer.setInterval(1000)
        self.connect(self.highlight_timer, SIGNAL("timeout()"),
                     self.highlight_matches)
        
    def get_shortcut_data(self):
        """
        Returns shortcut data, a list of tuples (shortcut, text, default)
        shortcut (QShortcut or QAction instance)
        text (string): action/shortcut description
        default (string): default key sequence
        """
        return [(self.findnext_sc, "Find next", "F3"),
                (self.findprev_sc, "Find previous", "Shift+F3"),
                (self.togglefind_sc, "Find text", "Ctrl+F"),
                (self.togglereplace_sc, "Replace text", "Ctrl+H"),]
        
    def update_search_combo(self):
        self.search_text.lineEdit().emit(SIGNAL('returnPressed()'))
        
    def update_replace_combo(self):
        self.replace_text.lineEdit().emit(SIGNAL('returnPressed()'))
    
    def toggle_replace_widgets(self):
        if self.enable_replace:
            # Toggle replace widgets
            if self.replace_widgets[0].isVisible():
                self.hide_replace()
                self.hide()
            else:
                self.show_replace()
                self.replace_text.setFocus()
                
    def toggle_highlighting(self, state):
        """Toggle the 'highlight all results' feature"""
        if self.editor is not None:
            if state:
                self.highlight_matches()
            else:
                self.clear_matches()
        
    def show(self):
        """Overrides Qt Method"""
        QWidget.show(self)
        self.emit(SIGNAL("visibility_changed(bool)"), True)
        if self.editor is not None:
            text = self.editor.get_selected_text()
            if len(text) > 0:
                self.search_text.setEditText(text)
                self.search_text.lineEdit().selectAll()
                self.refresh()
            else:
                self.search_text.lineEdit().selectAll()
            self.search_text.setFocus()
        
    def hide(self):
        """Overrides Qt Method"""
        for widget in self.replace_widgets:
            widget.hide()
        QWidget.hide(self)
        self.emit(SIGNAL("visibility_changed(bool)"), False)
        if self.editor is not None:
            self.editor.setFocus()
            self.clear_matches()
        
    def show_replace(self):
        """Show replace widgets"""
        self.show()
        for widget in self.replace_widgets:
            widget.show()
            
    def hide_replace(self):
        """Hide replace widgets"""
        for widget in self.replace_widgets:
            widget.hide()
        
    def refresh(self):
        """Refresh widget"""
        if self.isHidden():
            if self.editor is not None:
                self.clear_matches()
            return
        state = self.editor is not None
        for widget in self.widgets:
            widget.setEnabled(state)
        if state:
            self.find()
            
    def set_editor(self, editor, refresh=True):
        """
        Set associated editor/web page:
            codeeditor.base.TextEditBaseWidget
            browser.WebView
        """
        self.editor = editor
        from PyQt4.QtWebKit import QWebView
        self.words_button.setVisible(not isinstance(editor, QWebView))
        self.re_button.setVisible(not isinstance(editor, QWebView))
        from SMlib.widgets.sourcecode.codeeditor import CodeEditor
        self.is_code_editor = isinstance(editor, CodeEditor)
        self.highlight_button.setVisible(self.is_code_editor)
        if refresh:
            self.refresh()
        if self.isHidden() and editor is not None:
            self.clear_matches()
        
    def find_next(self):
        """Find next occurence"""
        state = self.find(changed=False, forward=True, rehighlight=False)
        self.editor.setFocus()
        self.search_text.add_current_text()
        return state
        
    def find_previous(self):
        """Find previous occurence"""
        state = self.find(changed=False, forward=False, rehighlight=False)
        self.editor.setFocus()
        return state

    def text_has_been_edited(self, text):
        """Find text has been edited (this slot won't be triggered when 
        setting the search pattern combo box text programmatically"""
        self.find(changed=True, forward=True, start_highlight_timer=True)
        
    def highlight_matches(self):
        """Highlight found results"""
        if self.is_code_editor and self.highlight_button.isChecked():
            text = self.search_text.currentText()
            words = self.words_button.isChecked()
            regexp = self.re_button.isChecked()
            self.editor.highlight_found_results(text, words=words,
                                                regexp=regexp)
                                                
    def clear_matches(self):
        """Clear all highlighted matches"""
        if self.is_code_editor:
            self.editor.clear_found_results()
        
    def find(self, changed=True, forward=True,
             rehighlight=True, start_highlight_timer=False):
        """Call the find function"""
        text = self.search_text.currentText()
        if len(text) == 0:
            self.search_text.lineEdit().setStyleSheet("")
            return None
        else:
            case = self.case_button.isChecked()
            words = self.words_button.isChecked()
            regexp = self.re_button.isChecked()
            found = self.editor.find_text(text, changed, forward, case=case,
                                          words=words, regexp=regexp)
            self.search_text.lineEdit().setStyleSheet(self.STYLE[found])
            if self.is_code_editor and found:
                if rehighlight or not self.editor.found_results:
                    self.highlight_timer.stop()
                    if start_highlight_timer:
                        self.highlight_timer.start()
                    else:
                        self.highlight_matches()
            else:
                self.clear_matches()
            return found
            
    def replace_find(self):
        """Replace and find"""
        if (self.editor is not None):
            replace_text = unicode(self.replace_text.currentText())
            search_text = unicode(self.search_text.currentText())
            pattern = search_text if self.re_button.isChecked() else None
            case = self.case_button.isChecked()
            first = True
            cursor = None
            while True:
                if first:
                    # First found
                    seltxt = unicode(self.editor.get_selected_text())
                    cmptxt1 = search_text if case else search_text.lower()
                    cmptxt2 = seltxt if case else seltxt.lower()
                    if self.editor.has_selected_text() and cmptxt1 == cmptxt2:
                        # Text was already found, do nothing
                        pass
                    else:
                        if not self.find(changed=False, forward=True,
                                         rehighlight=False):
                            break
                    first = False
                    wrapped = False
                    position = self.editor.get_position('cursor')
                    position0 = position
                    cursor = self.editor.textCursor()
                    cursor.beginEditBlock()
                else:
                    position1 = self.editor.get_position('cursor')
                    if wrapped:
                        if position1 == position or \
                           is_position_sup(position1, position):
                            # Avoid infinite loop: replace string includes
                            # part of the search string
                            break
                    if position1 == position0:
                        # Avoid infinite loop: single found occurence
                        break
                    if is_position_inf(position1, position0):
                        wrapped = True
                    position0 = position1
                if pattern is None:
                    cursor.removeSelectedText()
                    cursor.insertText(replace_text)
                else:
                    seltxt = unicode(cursor.selectedText())
                    cursor.removeSelectedText()
                    cursor.insertText(re.sub(pattern, replace_text, seltxt))
                if self.find_next():
                    found_cursor = self.editor.textCursor()
                    cursor.setPosition(found_cursor.selectionStart(),
                                       QTextCursor.MoveAnchor)
                    cursor.setPosition(found_cursor.selectionEnd(),
                                       QTextCursor.KeepAnchor)
                else:
                    break
                if not self.all_check.isChecked():
                    break
            self.all_check.setCheckState(Qt.Unchecked)
            if cursor is not None:
                cursor.endEditBlock()
Beispiel #56
0
class FindInFilesDialog(QDialog):
    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
                                       self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(
            self, self.tr("Open Directory"), self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
class TraceWindow(QMainWindow):

    def __init__(self, params_pipe, number_pipe, data_pipe, mads_pipe, peaks_pipe,
                 probe_path=None, screen_resolution=None):

        QMainWindow.__init__(self)

        # Receive parameters.
        params = params_pipe[0].recv()
        self.probe = load_probe(probe_path)
        self._nb_samples = params['nb_samples']
        self._sampling_rate = params['sampling_rate']
        self._display_list = list(range(self.probe.nb_channels))

        self._params = {
            'nb_samples': self._nb_samples,
            'sampling_rate': self._sampling_rate,
            'time': {
                'min': 10.0,  # ms
                'max': 1000.0,  # ms
                'init': 100.0,  # ms
            },
            'voltage': {
                'min': 10.0,  # µV
                'max': 10e+3,  # µV
                'init': 20.0,  # µV
            },
            'mads': {
                'min': 0.0,  # µV
                'max': 100,  # µV
                'init': 3,  # µV
            },
            'channels': self._display_list
        }

        self._canvas = TraceCanvas(probe_path=probe_path, params=self._params)

        central_widget = self._canvas.native

        # Create controls widgets.
        label_time = QLabel()
        label_time.setText(u"time")
        label_time_unit = QLabel()
        label_time_unit.setText(u"ms")

        self._dsp_time = QDoubleSpinBox()
        self._dsp_time.setMinimum(self._params['time']['min'])
        self._dsp_time.setMaximum(self._params['time']['max'])
        self._dsp_time.setValue(self._params['time']['init'])
        self._dsp_time.valueChanged.connect(self._on_time_changed)

        label_display_mads = QLabel()
        label_display_mads.setText(u"Display Mads")
        self._display_mads = QCheckBox()
        self._display_mads.stateChanged.connect(self._on_mads_display)

        label_display_peaks = QLabel()
        label_display_peaks.setText(u"Display Peaks")
        self._display_peaks = QCheckBox()
        self._display_peaks.stateChanged.connect(self._on_peaks_display)

        label_mads = QLabel()
        label_mads.setText(u"Mads")
        label_mads_unit = QLabel()
        label_mads_unit.setText(u"unit")
        self._dsp_mads = QDoubleSpinBox()
        self._dsp_mads.setMinimum(self._params['mads']['min'])
        self._dsp_mads.setMaximum(self._params['mads']['max'])
        self._dsp_mads.setValue(self._params['mads']['init'])
        self._dsp_mads.valueChanged.connect(self._on_mads_changed)

        label_voltage = QLabel()
        label_voltage.setText(u"voltage")
        label_voltage_unit = QLabel()
        label_voltage_unit.setText(u"µV")
        self._dsp_voltage = QDoubleSpinBox()
        self._dsp_voltage.setMinimum(self._params['voltage']['min'])
        self._dsp_voltage.setMaximum(self._params['voltage']['max'])
        self._dsp_voltage.setValue(self._params['voltage']['init'])
        self._dsp_voltage.valueChanged.connect(self._on_voltage_changed)

        # Color spikes
        self._color_spikes = QCheckBox()
        self._color_spikes.setText('See Spikes color')
        self._color_spikes.setCheckState(Qt.Checked)
        self._color_spikes.stateChanged.connect(self.display_spikes_color)



        # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291))

        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)

        # Create controls grid.
        grid = QGridLayout()
        # # Add time row.
        grid.addWidget(label_time, 0, 0)
        grid.addWidget(self._dsp_time, 0, 1)
        grid.addWidget(label_time_unit, 0, 2)
        # # Add voltage row.
        grid.addWidget(label_voltage, 1, 0)
        grid.addWidget(self._dsp_voltage, 1, 1)
        grid.addWidget(label_voltage_unit, 1, 2)
        # # Add Mads widgets

        grid.addWidget(label_display_mads, 3, 0)
        grid.addWidget(self._display_mads, 3, 1)

        grid.addWidget(label_mads, 4, 0)
        grid.addWidget(self._dsp_mads, 4, 1)
        grid.addWidget(label_mads_unit, 4, 2)

        grid.addWidget(self._color_spikes, 5, 0)

        # # Add spacer.
        grid.addItem(spacer)

        # # Create info group.
        controls_group = QGroupBox()
        controls_group.setLayout(grid)


        self._selection_channels = QListWidget()
        self._selection_channels.setSelectionMode(
            QAbstractItemView.ExtendedSelection
        )

        for i in range(self.probe.nb_channels):
            item = QListWidgetItem("Channel %i" % i)
            self._selection_channels.addItem(item)
            self._selection_channels.item(i).setSelected(True)

        def add_channel():
            items = self._selection_channels.selectedItems()
            self._display_list = []
            for i in range(len(items)):
                self._display_list.append(i)
            self._on_channels_changed()

        # self._selection_channels.itemClicked.connect(add_channel)

        nb_channel = self.probe.nb_channels
        self._selection_channels.itemSelectionChanged.connect(lambda: self.selected_channels(nb_channel))

        # Create info grid.
        channels_grid = QGridLayout()
        # # Add Channel selection
        # grid.addWidget(label_selection, 3, 0)
        channels_grid.addWidget(self._selection_channels, 0, 1)

        # # Add spacer.
        channels_grid.addItem(spacer)

        # Create controls group.
        channels_group = QGroupBox()
        channels_group.setLayout(channels_grid)

        # # Create controls dock.
        channels_dock = QDockWidget()
        channels_dock.setWidget(channels_group)
        channels_dock.setWindowTitle("Channels selection")

        # # Create controls dock.
        control_dock = QDockWidget()
        control_dock.setWidget(controls_group)
        control_dock.setWindowTitle("Controls")

        # Create info widgets.
        label_time = QLabel()
        label_time.setText(u"time")
        self._label_time_value = QLineEdit()
        self._label_time_value.setText(u"0")
        self._label_time_value.setReadOnly(True)
        self._label_time_value.setAlignment(Qt.AlignRight)
        label_time_unit = QLabel()
        label_time_unit.setText(u"s")
        info_buffer_label = QLabel()
        info_buffer_label.setText(u"buffer")
        self._info_buffer_value_label = QLineEdit()
        self._info_buffer_value_label.setText(u"0")
        self._info_buffer_value_label.setReadOnly(True)
        self._info_buffer_value_label.setAlignment(Qt.AlignRight)
        info_buffer_unit_label = QLabel()
        info_buffer_unit_label.setText(u"")
        info_probe_label = QLabel()
        info_probe_label.setText(u"probe")
        info_probe_value_label = QLineEdit()
        info_probe_value_label.setText(u"{}".format(probe_path))
        info_probe_value_label.setReadOnly(True)
        # TODO place the following info in another grid?
        info_probe_unit_label = QLabel()
        info_probe_unit_label.setText(u"")

        info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)

        # Create info grid.
        info_grid = QGridLayout()
        # # Time row.
        info_grid.addWidget(label_time, 0, 0)
        info_grid.addWidget(self._label_time_value, 0, 1)
        info_grid.addWidget(label_time_unit, 0, 2)
        # # Buffer row.
        info_grid.addWidget(info_buffer_label, 1, 0)
        info_grid.addWidget(self._info_buffer_value_label, 1, 1)
        info_grid.addWidget(info_buffer_unit_label, 1, 2)
        # # Probe row.
        info_grid.addWidget(info_probe_label, 2, 0)
        info_grid.addWidget(info_probe_value_label, 2, 1)
        info_grid.addWidget(info_probe_unit_label, 2, 2)
        # # Spacer.
        info_grid.addItem(info_spacer)

        # Create info group.
        info_group = QGroupBox()
        info_group.setLayout(info_grid)

        # Create info dock.
        info_dock = QDockWidget()
        info_dock.setWidget(info_group)
        info_dock.setWindowTitle("Info")

        # Create thread.
        thread = Thread(number_pipe, data_pipe, mads_pipe, peaks_pipe)
        thread.number_signal.connect(self._number_callback)
        thread.reception_signal.connect(self._reception_callback)
        thread.start()

        # Add dockable windows.
        self.addDockWidget(Qt.LeftDockWidgetArea, control_dock)
        self.addDockWidget(Qt.LeftDockWidgetArea, info_dock)
        self.addDockWidget(Qt.LeftDockWidgetArea, channels_dock)
        # Set central widget.
        self.setCentralWidget(central_widget)
        # Set window size.
        if screen_resolution is not None:
            screen_width = screen_resolution.width()
            screen_height = screen_resolution.height()
            self.resize(screen_width, screen_height)
        # Set window title.
        self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display")

        print(" ")  # TODO remove?

    def _number_callback(self, number):

        text = u"{}".format(number)
        self._info_buffer_value_label.setText(text)

        text = u"{:8.3f}".format(float(number) * float(self._nb_samples) / self._sampling_rate)
        self._label_time_value.setText(text)

        return

    def _reception_callback(self, data, mads, peaks):

        self._canvas.on_reception(data, mads, peaks)

        return

    def _on_time_changed(self):

        time = self._dsp_time.value()
        self._canvas.set_time(time)

        return

    def _on_voltage_changed(self):

        voltage = self._dsp_voltage.value()
        self._canvas.set_voltage(voltage)

        return

    def _on_mads_changed(self):

        mads = self._dsp_mads.value()
        self._canvas.set_mads(mads)

        return

    def _on_mads_display(self):

        value = self._display_mads.isChecked()
        self._canvas.show_mads(value)

        return

    def _on_peaks_display(self):

        value = self._display_peaks.isChecked()
        self._canvas.show_peaks(value)

        return

    def _on_channels_changed(self):
        self._canvas.set_channels(self._display_list)

        return

    def display_spikes_color(self, s):
        self._canvas.color_spikes(s)

    def selected_channels(self, max_channel):
        # print(self._selection_channels.selectedItems())
        list_channel = []
        for i in range(max_channel):
            if self._selection_channels.item(i).isSelected():
                list_channel.append(i)
        self._canvas.selected_channels(list_channel)
        return
class FindInFilesDialog(QDialog):
    """Dialog to configure and trigger the search in the files."""
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"),
                                       translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(
            QCompleter([
                "*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS
            ]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(translations.TR_TEXT_FOR_REPLACE +
                                             "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(
            self, translations.TR_OPEN, self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
Beispiel #59
0
class CustomAttributes(QGroupBox):
    
    changed = pyqtSignal()
    
    def __init__(self, parent=None):
        super(CustomAttributes, self).__init__(parent)
        grid = QGridLayout()
        self.setLayout(grid)
        
        self.toplabel = QLabel()
        self.toplabel.setEnabled(False)
        self.toplabel.setAlignment(Qt.AlignCenter)
        grid.addWidget(self.toplabel, 0, 0, 1, 3)
        
        self.textColor = ColorButton()
        l = self.textLabel = QLabel()
        l.setBuddy(self.textColor)
        grid.addWidget(l, 1, 0)
        grid.addWidget(self.textColor, 1, 1)
        c = ClearButton(iconSize=QSize(16, 16))
        c.clicked.connect(self.textColor.clear)
        grid.addWidget(c, 1, 2)
        
        self.backgroundColor = ColorButton()
        l = self.backgroundLabel = QLabel()
        l.setBuddy(self.backgroundColor)
        grid.addWidget(l, 2, 0)
        grid.addWidget(self.backgroundColor, 2, 1)
        c = ClearButton(iconSize=QSize(16, 16))
        c.clicked.connect(self.backgroundColor.clear)
        grid.addWidget(c, 2, 2)
        
        self.bold = QCheckBox()
        self.italic = QCheckBox()
        self.underline = QCheckBox()
        grid.addWidget(self.bold, 3, 0)
        grid.addWidget(self.italic, 4, 0)
        grid.addWidget(self.underline, 5, 0)
        
        self.underlineColor = ColorButton()
        grid.addWidget(self.underlineColor, 5, 1)
        c = ClearButton(iconSize=QSize(16, 16))
        c.clicked.connect(self.underlineColor.clear)
        grid.addWidget(c, 5, 2)
        grid.setRowStretch(6, 2)
        
        self.textColor.colorChanged.connect(self.changed)
        self.backgroundColor.colorChanged.connect(self.changed)
        self.underlineColor.colorChanged.connect(self.changed)
        self.bold.stateChanged.connect(self.changed)
        self.italic.stateChanged.connect(self.changed)
        self.underline.stateChanged.connect(self.changed)
        
        app.translateUI(self)
        
    def translateUI(self):
        self.textLabel.setText(_("Text"))
        self.backgroundLabel.setText(_("Background"))
        self.bold.setText(_("Bold"))
        self.italic.setText(_("Italic"))
        self.underline.setText(_("Underline"))
    
    def setTopText(self, text):
        self.toplabel.setText(text)
        
    def setTristate(self, enable):
        self._tristate = enable
        self.bold.setTristate(enable)
        self.italic.setTristate(enable)
        self.underline.setTristate(enable)
    
    def textFormat(self):
        """Returns our settings as a QTextCharFormat object."""
        f = QTextCharFormat()
        if self._tristate:
            value = lambda checkbox: [False, None, True][checkbox.checkState()]
        else:
            value = lambda checkbox: checkbox.isChecked()
        res = value(self.bold)
        if res is not None:
            f.setFontWeight(QFont.Bold if res else QFont.Normal)
        res = value(self.italic)
        if res is not None:
            f.setFontItalic(res)
        res = value(self.underline)
        if res is not None:
            f.setFontUnderline(res)
        if self.textColor.color().isValid():
            f.setForeground(self.textColor.color())
        if self.backgroundColor.color().isValid():
            f.setBackground(self.backgroundColor.color())
        if self.underlineColor.color().isValid():
            f.setUnderlineColor(self.underlineColor.color())
        return f

    def setTextFormat(self, f):
        """Sets our widget to the QTextCharFormat settings."""
        block = self.blockSignals(True)
        absent = Qt.PartiallyChecked if self._tristate else Qt.Unchecked
        if f.hasProperty(QTextFormat.FontWeight):
            self.bold.setChecked(f.fontWeight() >= QFont.Bold)
        else:
            self.bold.setCheckState(absent)
        if f.hasProperty(QTextFormat.FontItalic):
            self.italic.setChecked(f.fontItalic())
        else:
            self.italic.setCheckState(absent)
        if f.hasProperty(QTextFormat.TextUnderlineStyle):
            self.underline.setChecked(f.fontUnderline())
        else:
            self.underline.setCheckState(absent)
        
        if f.hasProperty(QTextFormat.ForegroundBrush):
            self.textColor.setColor(f.foreground().color())
        else:
            self.textColor.setColor(QColor())
        if f.hasProperty(QTextFormat.BackgroundBrush):
            self.backgroundColor.setColor(f.background().color())
        else:
            self.backgroundColor.setColor(QColor())
        if f.hasProperty(QTextFormat.TextUnderlineColor):
            self.underlineColor.setColor(f.underlineColor())
        else:
            self.underlineColor.setColor(QColor())
        self.blockSignals(block)