Beispiel #1
0
class PreviewWidget(QWidget):
    """Import wizard preview widget"""
    
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        
        vert_layout = QVBoxLayout()
        
        hor_layout = QHBoxLayout()
        self.array_box = QCheckBox(_("Import as array"))
        self.array_box.setEnabled(ndarray is not FakeObject)
        self.array_box.setChecked(ndarray is not FakeObject)
        hor_layout.addWidget(self.array_box)
        h_spacer = QSpacerItem(40, 20,
                               QSizePolicy.Expanding, QSizePolicy.Minimum)        
        hor_layout.addItem(h_spacer)
        
        self._table_view = PreviewTable(self)
        vert_layout.addLayout(hor_layout)
        vert_layout.addWidget(self._table_view)
        self.setLayout(vert_layout)

    def open_data(self, text, colsep=u"\t", rowsep=u"\n",
                  transpose=False, skiprows=0, comments='#'):
        """Open clipboard text as table"""
        self._table_view.process_data(text, colsep, rowsep, transpose,
                                      skiprows, comments)
    
    def get_data(self):
        """Return table data"""
        return self._table_view.get_data()
Beispiel #2
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
Beispiel #3
0
class PreviewWidget(QWidget):
    """Import wizard preview widget"""
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        vert_layout = QVBoxLayout()

        hor_layout = QHBoxLayout()
        self.array_box = QCheckBox(_("Import as array"))
        self.array_box.setEnabled(ndarray is not FakeObject)
        self.array_box.setChecked(ndarray is not FakeObject)
        hor_layout.addWidget(self.array_box)
        h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                               QSizePolicy.Minimum)
        hor_layout.addItem(h_spacer)

        self._table_view = PreviewTable(self)
        vert_layout.addLayout(hor_layout)
        vert_layout.addWidget(self._table_view)
        self.setLayout(vert_layout)

    def open_data(self,
                  text,
                  colsep=u"\t",
                  rowsep=u"\n",
                  transpose=False,
                  skiprows=0,
                  comments='#'):
        """Open clipboard text as table"""
        self._table_view.process_data(text, colsep, rowsep, transpose,
                                      skiprows, comments)

    def get_data(self):
        """Return table data"""
        return self._table_view.get_data()
Beispiel #4
0
 def populate(self):
     self.tree.connect(self.tree,
                       SIGNAL("itemClicked(QTreeWidgetItem *, int)"),
                       self.clicked)
     self.tree.connect(self.tree,
                       SIGNAL("itemPressed(QTreeWidgetItem *, int)"),
                       self.clicked)
     for mimetype, mimecontent in self.mm.mimetypes.iteritems():
         mimetypeItem = QTreeWidgetItem(self.tree, [mimetype])
         mimetypeItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled
                               | Qt.ItemIsSelectable)
         mimetypeItem.setCheckState(0, Qt.Unchecked)
         rCheckBox = RootCheckBox()
         rCheckBox.setEnabled(False)
         self.tree.setItemWidget(mimetypeItem, 1, rCheckBox)
         self.typeItems.append(mimetypeItem)
         for value in mimecontent:
             filetypeItem = QTreeWidgetItem(mimetypeItem, [value])
             filetypeItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled
                                   | Qt.ItemIsSelectable)
             filetypeItem.setCheckState(0, Qt.Unchecked)
             checkBox = QCheckBox()
             checkBox.setEnabled(False)
             rCheckBox.addChild(checkBox)
             rCheckBox.connect(checkBox, SIGNAL("stateChanged(int)"),
                               rCheckBox.update)
             self.tree.setItemWidget(filetypeItem, 1, checkBox)
     self.tree.resizeColumnToContents(0)
class DeletionOptions(QDialog):
    def __init__(self, parent, model):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.model = model
        self._setupUi()
        self.model.view = self
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupUi(self):
        self.setWindowTitle(tr("Deletion Options"))
        self.resize(400, 270)
        self.verticalLayout = QVBoxLayout(self)
        self.msgLabel = QLabel()
        self.verticalLayout.addWidget(self.msgLabel)
        self.linkCheckbox = QCheckBox(tr("Link deleted files"))
        self.verticalLayout.addWidget(self.linkCheckbox)
        text = tr("After having deleted a duplicate, place a link targeting the reference file "
            "to replace the deleted file.")
        self.linkMessageLabel = QLabel(text)
        self.linkMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.linkMessageLabel)
        self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False)
        self.verticalLayout.addWidget(self.linkTypeRadio)
        if not self.model.supports_links():
            self.linkCheckbox.setEnabled(False)
            self.linkTypeRadio.setEnabled(False)
            self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)"))
        self.directCheckbox = QCheckBox(tr("Directly delete files"))
        self.verticalLayout.addWidget(self.directCheckbox)
        text = tr("Instead of sending files to trash, delete them directly. This option is usually "
            "used as a workaround when the normal deletion method doesn't work.")
        self.directMessageLabel = QLabel(text)
        self.directMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.directMessageLabel)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
        self.verticalLayout.addWidget(self.buttonBox)
    
    #--- model --> view
    def update_msg(self, msg):
        self.msgLabel.setText(msg)
    
    def show(self):
        self.linkCheckbox.setChecked(self.model.link_deleted)
        self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0
        self.directCheckbox.setChecked(self.model.direct)
        result = self.exec()
        self.model.link_deleted = self.linkCheckbox.isChecked()
        self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1
        self.model.direct = self.directCheckbox.isChecked()
        return result == QDialog.Accepted
 def _addPropertyWidgets(self, layout, autoUpdateEnabled):
     propertiesLayout = QHBoxLayout()
     propertiesLayout.setContentsMargins(0, 0, 0, 0)
     
     activeCheckBox = QCheckBox("Active", self)
     activeCheckBox.setChecked(True)
     propertiesLayout.addWidget(activeCheckBox)
     self._activeBoxes.append(activeCheckBox)
     
     autoUpdateCheckBox = QCheckBox("Auto Update", self)
     autoUpdateCheckBox.setEnabled(autoUpdateEnabled)
     propertiesLayout.addWidget(autoUpdateCheckBox, 1, Qt.AlignLeft)
     self._autoUpdateBoxes.append(autoUpdateCheckBox)
     
     layout.addLayout(propertiesLayout)
Beispiel #7
0
def script_engine_test():
    app = QApplication(sys.argv)

    # 创建js引擎
    engine = QScriptEngine()

    fun = engine.evaluate("(function(a, b) { return a + b; })")
    args = [QScriptValue(1), QScriptValue(3)]
    three_again = fun.call(QScriptValue(), args)
    print
    three_again.toInt32()

    # 创建qt对象到js引擎,js可调用这个实例对象
    button1 = QCheckBox('test---1')
    button2 = QCheckBox('test---2')
    button3 = QCheckBox('test---3')
    script_button1 = engine.newQObject(button1)
    script_button2 = engine.newQObject(button2)
    script_button3 = engine.newQObject(button3)
    engine.globalObject().setProperty("button1", script_button1)
    engine.globalObject().setProperty("button2", script_button2)
    engine.globalObject().setProperty("button3", script_button3)

    # 三种方式调用

    # 1、用js的方式调用
    engine.evaluate("button1.show()")
    engine.evaluate("button1.setChecked(true)")
    engine.evaluate("button1.setEnabled(false)")

    # 2、用js对象的方式调用
    script_button2.property("show").call()
    script_button2.property("setChecked").call(QScriptValue(),
                                               [QScriptValue(True)])
    script_button2.property("setEnabled").call(QScriptValue(),
                                               [QScriptValue(False)])

    # 3、用qt对象的方式调用
    button3.show()
    button3.setChecked(True)
    button3.setEnabled(False)

    sys.exit(app.exec_())
Beispiel #8
0
    def __init__(self, parent, data, xy, readonly):
        QWidget.__init__(self, parent)
        self.data = data
        self.old_data_shape = None
        if len(self.data.shape) == 1:
            self.old_data_shape = self.data.shape
            self.data.shape = (self.data.shape[0], 1)
        elif len(self.data.shape) == 0:
            self.old_data_shape = self.data.shape
            self.data.shape = (1, 1)

        self.changes = {}

        format = SUPPORTED_FORMATS.get(data.dtype.name, '%s')
        self.model = ArrayModel(self.data,
                                self.changes,
                                format=format,
                                xy_mode=xy,
                                readonly=readonly,
                                parent=self)
        self.view = ArrayView(self, self.model, data.dtype, data.shape)

        btn_layout = QHBoxLayout()
        btn_layout.setAlignment(Qt.AlignLeft)
        btn = QPushButton(translate("ArrayEditor", "Format"))
        # disable format button for int type
        btn.setEnabled(is_float(data.dtype))
        btn_layout.addWidget(btn)
        self.connect(btn, SIGNAL("clicked()"), self.change_format)
        btn = QPushButton(translate("ArrayEditor", "Resize"))
        btn_layout.addWidget(btn)
        self.connect(btn, SIGNAL("clicked()"), self.view.resize_to_contents)
        bgcolor = QCheckBox(translate("ArrayEditor", 'Background color'))
        bgcolor.setChecked(self.model.bgcolor_enabled)
        bgcolor.setEnabled(self.model.bgcolor_enabled)
        self.connect(bgcolor, SIGNAL("stateChanged(int)"), self.model.bgcolor)
        btn_layout.addWidget(bgcolor)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(btn_layout)
        self.setLayout(layout)
Beispiel #9
0
    def fill(self):
        sessions = self.client.call('session', 'list')
        cookie = self.client.getCookie()
        self.checkboxes = []
        self.sessions = [session for session in sessions
            if ('cookie' not in session) or (session['cookie'] != cookie)]
        if not sessions:
            return False
        self.sessions.sort(key=lambda session: session['idle'])

        table = self.ui.session_table
        table.setRowCount(len(self.sessions))
        for row, session in enumerate(self.sessions):
            user = session['user']
            creation = fuzzyDatetime(parseDatetime(session['creation']))
            idle = timedelta(seconds=session['idle'])
            idle = fuzzyTimedelta(idle)
            if 'login' in user:
                login = user['login']
            else:
                login = u"<%s>" % tr("anonymous")
            application = user['client_name']
            application = APPLICATION_NAME.get(application, application)
            if 'client_release' in user:
                application += ' (%s)' % (user['client_release'],)
            columns = (
                login,
                user['host'],
                application,
                creation,
                idle)
            checkbox = QCheckBox(self)
            if 'cookie' not in session:
                checkbox.setEnabled(False)
            self.connect(checkbox, SIGNAL("toggled(bool)"), self.toggleSession)
            table.setCellWidget(row, 0, checkbox)
            self.checkboxes.append(checkbox)
            for column, text in enumerate(columns):
                table.setItem(row, 1 + column, QTableWidgetItem(text))
        table.resizeColumnsToContents()
        self.ui.destroy_button.setEnabled(False)
Beispiel #10
0
 def populate(self):
     self.tree.connect(self.tree, SIGNAL("itemClicked(QTreeWidgetItem *, int)"), self.clicked)
     self.tree.connect(self.tree, SIGNAL("itemPressed(QTreeWidgetItem *, int)"), self.clicked)
     for mimetype, mimecontent in self.mm.mimetypes.iteritems():
         mimetypeItem = QTreeWidgetItem(self.tree, [mimetype])
         mimetypeItem.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable)
         mimetypeItem.setCheckState(0, Qt.Unchecked)
         rCheckBox = RootCheckBox()
         rCheckBox.setEnabled(False)
         self.tree.setItemWidget(mimetypeItem, 1, rCheckBox)
         self.typeItems.append(mimetypeItem)
         for value in mimecontent:
             filetypeItem = QTreeWidgetItem(mimetypeItem, [value])
             filetypeItem.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable)
             filetypeItem.setCheckState(0, Qt.Unchecked)
             checkBox = QCheckBox()
             checkBox.setEnabled(False)
             rCheckBox.addChild(checkBox)
             rCheckBox.connect(checkBox, SIGNAL("stateChanged(int)"), rCheckBox.update)
             self.tree.setItemWidget(filetypeItem, 1, checkBox)
     self.tree.resizeColumnToContents(0)
class Banjo(TablaturePart):
    @staticmethod
    def title(_=_base.translate):
        return _("Banjo")
    
    @staticmethod
    def short(_=_base.translate):
        return _("abbreviation for Banjo", "Bj.")
    
    midiInstrument = 'banjo'
    tabFormat = 'fret-number-tablature-format-banjo'
    tunings = (
        ('banjo-open-g-tuning', lambda: _("Open G-tuning (aDGBD)")),
        ('banjo-c-tuning', lambda: _("C-tuning (gCGBD)")),
        ('banjo-modal-tuning', lambda: _("Modal tuning (gDGCD)")),
        ('banjo-open-d-tuning', lambda: _("Open D-tuning (aDF#AD)")),
        ('banjo-open-dm-tuning', lambda: _("Open Dm-tuning (aDFAD)")),
    )
    
    def createTuningWidgets(self, layout):
        super(Banjo, self).createTuningWidgets(layout)
        self.fourStrings = QCheckBox()
        layout.addWidget(self.fourStrings)
        
    def translateTuningWidgets(self):
        super(Banjo, self).translateTuningWidgets()
        self.fourStrings.setText(_("Four strings (instead of five)"))
    
    def setTunings(self, tab):
        i = self.tuning.currentIndex()
        if i > len(self.tunings) or not self.fourStrings.isChecked():
            super(Banjo, self).setTunings(tab)
        else:
            tab.getWith()['stringTunings'] = ly.dom.Scheme(
                '(four-string-banjo {0})'.format(
                    self.tunings[i][0]))

    def slotCustomTuningEnable(self, index):
        super(Banjo, self).slotCustomTuningEnable(index)
        self.fourStrings.setEnabled(index <= len(self.tunings))
Beispiel #12
0
class Banjo(TablaturePart):
    @staticmethod
    def title(_=_base.translate):
        return _("Banjo")

    @staticmethod
    def short(_=_base.translate):
        return _("abbreviation for Banjo", "Bj.")

    midiInstrument = 'banjo'
    tabFormat = 'fret-number-tablature-format-banjo'
    tunings = (
        ('banjo-open-g-tuning', lambda: _("Open G-tuning (aDGBD)")),
        ('banjo-c-tuning', lambda: _("C-tuning (gCGBD)")),
        ('banjo-modal-tuning', lambda: _("Modal tuning (gDGCD)")),
        ('banjo-open-d-tuning', lambda: _("Open D-tuning (aDF#AD)")),
        ('banjo-open-dm-tuning', lambda: _("Open Dm-tuning (aDFAD)")),
    )

    def createTuningWidgets(self, layout):
        super(Banjo, self).createTuningWidgets(layout)
        self.fourStrings = QCheckBox()
        layout.addWidget(self.fourStrings)

    def translateTuningWidgets(self):
        super(Banjo, self).translateTuningWidgets()
        self.fourStrings.setText(_("Four strings (instead of five)"))

    def setTunings(self, tab):
        i = self.tuning.currentIndex()
        if i > len(self.tunings) or not self.fourStrings.isChecked():
            super(Banjo, self).setTunings(tab)
        else:
            tab.getWith()['stringTunings'] = ly.dom.Scheme(
                '(four-string-banjo {0})'.format(self.tunings[i][0]))

    def slotCustomTuningEnable(self, index):
        super(Banjo, self).slotCustomTuningEnable(index)
        self.fourStrings.setEnabled(index <= len(self.tunings))
Beispiel #13
0
    def __init__(self, parent, data, xy, readonly):
        QWidget.__init__(self, parent)
        self.data = data
        self.old_data_shape = None
        if len(self.data.shape) == 1:
            self.old_data_shape = self.data.shape
            self.data.shape = (self.data.shape[0], 1)
        elif len(self.data.shape) == 0:
            self.old_data_shape = self.data.shape
            self.data.shape = (1, 1)

        self.changes = {}
       
        format = SUPPORTED_FORMATS.get(data.dtype.name, '%s')
        self.model = ArrayModel(self.data, self.changes, format=format,
                                xy_mode=xy, readonly=readonly, parent=self)
        self.view = ArrayView(self, self.model, data.dtype, data.shape)
        
        btn_layout = QHBoxLayout()
        btn_layout.setAlignment(Qt.AlignLeft)
        btn = QPushButton(translate("ArrayEditor", "Format"))
        # disable format button for int type
        btn.setEnabled(is_float(data.dtype))
        btn_layout.addWidget(btn)
        self.connect(btn, SIGNAL("clicked()"), self.change_format)
        btn = QPushButton(translate("ArrayEditor", "Resize"))
        btn_layout.addWidget(btn)
        self.connect(btn, SIGNAL("clicked()"), self.view.resize_to_contents)
        bgcolor = QCheckBox(translate("ArrayEditor", 'Background color'))
        bgcolor.setChecked(self.model.bgcolor_enabled)
        bgcolor.setEnabled(self.model.bgcolor_enabled)
        self.connect(bgcolor, SIGNAL("stateChanged(int)"), self.model.bgcolor)
        btn_layout.addWidget(bgcolor)
        
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(btn_layout)        
        self.setLayout(layout)
Beispiel #14
0
class CompletionSection(QWidget):
    def __init__(self):
        super(CompletionSection, self).__init__()
        EditorConfiguration.install_widget(self.tr("Autocompletado"), self)
        container = QVBoxLayout(self)

        group_complete = QGroupBox(self.tr("Completar:"))
        box = QGridLayout(group_complete)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_bracket = QCheckBox(self.tr("Corchetes []"))
        box.addWidget(self.check_bracket, 0, 0)
        self.check_paren = QCheckBox(self.tr("Paréntesis ()"))
        box.addWidget(self.check_paren, 0, 1)
        self.check_key = QCheckBox(self.tr("Llaves {}"))
        box.addWidget(self.check_key, 1, 0)
        self.check_quote = QCheckBox(self.tr("Comillas Dobles \" \""))
        box.addWidget(self.check_quote, 1, 1)
        self.check_single_quote = QCheckBox(self.tr("Comillas Simples ' '"))
        box.addWidget(self.check_single_quote, 2, 0)

        group_completion = QGroupBox(self.tr("Completado de Código:"))
        box = QGridLayout(group_completion)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_completion = QCheckBox(self.tr("Activar Completado"))
        box.addWidget(self.check_completion, 0, 0)
        self.check_document = QCheckBox(self.tr("Basado en el código"))
        box.addWidget(self.check_document, 0, 1)
        self.check_keywords = QCheckBox(self.tr("Palabras Claves"))
        box.addWidget(self.check_keywords, 1, 0)
        self.check_cs = QCheckBox(
            self.tr("Sensitivo a mayúsculas y minúsculas"))
        box.addWidget(self.check_cs, 1, 1)
        self.check_replace_word = QCheckBox(self.tr("Reemplazar Palabra"))
        box.addWidget(self.check_replace_word, 2, 0)
        self.check_show_single = QCheckBox(self.tr("Mostrar Simple"))
        box.addWidget(self.check_show_single, 2, 1)
        hbox = QHBoxLayout()
        hbox.addWidget(
            QLabel(self.tr("Número de caractéres para mostrar lista:")))
        self.spin_threshold = QSpinBox()
        self.spin_threshold.setMinimum(1)
        self.spin_threshold.setFixedWidth(100)
        hbox.addWidget(self.spin_threshold)
        box.addLayout(hbox, 3, 0, Qt.AlignLeft)

        # Agrupo al contenedor principal
        container.addWidget(group_complete)
        container.addWidget(group_completion)
        container.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self._state_change(self.check_completion.isChecked())
        # Conexiones
        self.check_completion.stateChanged[int].connect(self._state_change)

        # Configuration
        self.check_key.setChecked(
            settings.get_setting('editor/complete-brace'))
        self.check_bracket.setChecked("[" in settings.BRACES)
        self.check_paren.setChecked("(" in settings.BRACES)
        self.check_quote.setChecked('""' in settings.QUOTES)
        #settings.get_setting('editor/complete-double-quote'))
        self.check_single_quote.setChecked("''" in settings.QUOTES)
        #settings.get_setting('editor/complete-single-quote'))
        self.check_completion.setChecked(
            settings.get_setting('editor/completion'))
        self.spin_threshold.setValue(
            settings.get_setting('editor/completion-threshold'))
        self.check_keywords.setChecked(
            settings.get_setting('editor/completion-keywords'))
        self.check_document.setChecked(
            settings.get_setting('editor/completion-document'))
        self.check_cs.setChecked(settings.get_setting('editor/completion-cs'))
        self.check_replace_word.setChecked(
            settings.get_setting('editor/completion-replace-word'))
        self.check_show_single.setChecked(
            settings.get_setting('editor/completion-single'))

    def _state_change(self, value):
        state = bool(value)
        self.check_document.setEnabled(state)
        self.check_keywords.setEnabled(state)
        self.check_cs.setEnabled(state)
        self.check_replace_word.setEnabled(state)
        self.check_show_single.setEnabled(state)
        self.spin_threshold.setEnabled(state)

    def save(self):
        settings.set_setting('editor/complete-brace',
                             self.check_key.isChecked())
        settings.set_setting('editor/complete-bracket',
                             self.check_bracket.isChecked())
        if self.check_bracket.isChecked():
            settings.BRACES['['] = ']'
        elif ('[') in settings.BRACES:
            del settings.BRACES['[']
        settings.set_setting('editor/complete-paren',
                             self.check_paren.isChecked())
        if self.check_paren.isChecked():
            settings.BRACES['('] = ')'
        elif ('(') in settings.BRACES:
            del settings.BRACES['(']
        settings.set_setting('editor/complete-double-quote',
                             self.check_quote.isChecked())
        if self.check_quote.isChecked():
            settings.QUOTES.append('""')
        elif '""' in settings.QUOTES:
            settings.QUOTES.remove('""')
        settings.set_setting('editor/complete-single-quote',
                             self.check_single_quote.isChecked())
        if self.check_single_quote.isChecked():
            settings.QUOTES.append('""')
        elif "''" in settings.QUOTES:
            settings.QUOTES.remove("''")
        code_completion = self.check_completion.isChecked()
        settings.set_setting('editor/completion', code_completion)
        settings.set_setting('editor/completion-threshold',
                             self.spin_threshold.value())
        settings.set_setting('editor/completion-keywords',
                             self.check_keywords.isChecked())
        settings.set_setting('editor/completion-document',
                             self.check_document.isChecked())
        settings.set_setting('editor/completion-cs', self.check_cs.isChecked())
        settings.set_setting('editor/completion-replace-word',
                             self.check_replace_word.isChecked())
        settings.set_setting('editor/completion-single',
                             self.check_show_single.isChecked())
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            editor.active_code_completion(code_completion)
Beispiel #15
0
    def __init__(self, scenario, parent=None):
        super(InfoComp, self).__init__(parent)

        self.resize(300, 223)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.setWindowTitle(u"Informations complémentaires")
        icon = get_icon(":/images/people.png")
        self.setWindowIcon(icon)
        self.verticalLayout = QVBoxLayout(self)
        self.gridLayout = QGridLayout()
        self.gridLayout.setHorizontalSpacing(10)
        self.setStyleSheet(OfSs.bold_center)

        self.label_0 = QLabel(u'n°', self)
        self.gridLayout.addWidget(self.label_0, 0, 0, 1, 1)

        self.label_1 = QLabel(u'Activité', self)
        self.gridLayout.addWidget(self.label_1, 0, 1, 1, 1)

        self.label_2 = QLabel(u"Invalide", self)
        self.gridLayout.addWidget(self.label_2, 0, 2, 1, 1)

        self.label_3 = QLabel(u'Garde\nalternée', self)
        self.gridLayout.addWidget(self.label_3, 0, 3, 1, 1)

        self.gridLayout.setColumnStretch(1, 1)
        self.gridLayout.setColumnStretch(2, 1)
        self.gridLayout.setColumnStretch(3, 1)
        self.verticalLayout.addLayout(self.gridLayout)

        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok,
                                          parent=self)
        self.verticalLayout.addWidget(self.buttonBox)

        self.connect(self.buttonBox, SIGNAL('accepted()'), self.accept)
        self.connect(self.buttonBox, SIGNAL('rejected()'), self.reject)

        self.parent = parent
        self.scenario = scenario
        self.inv_list = []
        self.alt_list = []
        self.act_list = []
        for noi, vals in self.scenario.indiv.iteritems():
            self.gridLayout.addWidget(QLabel('%d' % (noi + 1), self), noi + 1,
                                      0)

            # Acitivité
            cb_act = QComboBox(self)
            cb_act.addItems([
                u'Actif occupé', u'Chômeur', u'Étudiant, élève', u'Retraité',
                u'Autre inactif'
            ])
            cb_act.setCurrentIndex(vals['activite'])
            self.act_list.append(cb_act)
            self.gridLayout.addWidget(cb_act, noi + 1, 1)

            # Invalide
            cb_inv = QCheckBox(self)
            cb_inv.setChecked(vals['inv'])
            layout1 = QHBoxLayout()
            layout1.addItem(
                QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            layout1.addWidget(cb_inv)
            layout1.addItem(
                QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            self.inv_list.append(cb_inv)
            self.gridLayout.addLayout(layout1, noi + 1, 2)

            # Garde alternée
            cb_alt = QCheckBox(self)
            if vals['quifoy'][:3] != 'pac':
                vals['alt'] = 0
                cb_alt.setEnabled(False)
            cb_alt.setChecked(vals['alt'])
            layout2 = QHBoxLayout()
            layout2.addItem(
                QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            layout2.addWidget(cb_alt)
            layout2.addItem(
                QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            self.alt_list.append(cb_alt)
            self.gridLayout.addLayout(layout2, noi + 1, 3)
Beispiel #16
0
class TermPayDialog(QDialog):

    holdc = {}

    def __init__(self, student, term, parent=None):
        super(TermPayDialog, self).__init__(parent)
        #term data
        self.term = term
        terms = self.pullOnes('terms', self.term)
        session = self.pullOnes('session', terms['sessionID'])
        self.termname = str(
            session['name']) + ' ' + terms['name'] + ' Term Report'
        self.pagetitle = self.termname

        #student data
        self.student = student
        st = self.pullStudent(self.student)
        fullname = str(st['surname'] + ' ' + st['firstname'] + ' ' +
                       st['othername']).title()
        schno = st['schno']
        db_class = 'student_class' + str(self.term)
        student_clasz = self.pullOne(db_class, {'studentID': self.student})

        clasz = self.pullOne('datas', {'id': student_clasz['classID']})
        self.clasz = clasz['subID']
        armz = self.pullOne('datas', {'id': clasz['subID']})
        classname = armz['abbrv'] + ' ' + clasz['abbrv']
        #pull all CA

        fullNameText = QLabel(fullname)
        schnoText = QLabel(schno)
        classText = QLabel(classname)

        topLay = QGridLayout()
        topLay.addWidget(fullNameText, 0, 0)
        topLay.addWidget(schnoText, 1, 0)
        topLay.addWidget(classText, 2, 0)

        groupBox = QGroupBox('Current Payment')
        groupBox.setLayout(topLay)

        payAmountText = QLabel('Amount')
        self.payBalanceText = QLabel('Balance')
        self.payBalanceAmount = QLabel('0.0')
        self.payAmount = QLineEdit()
        self.payAmount.setObjectName("pay")
        self.payAmount.setPlaceholderText("000.00")
        payText = QLabel('Select Account')
        self.payMethod = QComboBox()
        accounts = self.pullAccount()
        self.holdaccount = {}
        i = 0
        for h in accounts:
            tex = str(h['name']).upper()
            self.payMethod.addItem(tex)
            self.holdaccount[i] = h['id']

        payDateText = QLabel('Balance')
        self.payDate = QDateEdit()
        self.payDate.setDateTime(QDateTime.currentDateTime())
        self.payDate.setCalendarPopup(True)
        tellerText = QLabel('Teller/Receipt No.')
        self.teller = QLineEdit()
        self.teller.setObjectName("teller")
        self.teller.textChanged.connect(self.pullTeller)
        self.teller.setPlaceholderText("0000000")

        self.hw = QGridLayout()
        self.hw.addWidget(payAmountText, 0, 0)
        self.hw.addWidget(self.payAmount, 0, 1)
        self.hw.addWidget(tellerText, 0, 2)
        self.hw.addWidget(self.teller, 0, 3)
        self.hw.addWidget(payText, 1, 0)
        self.hw.addWidget(self.payMethod, 1, 1)
        self.hw.addWidget(payDateText, 1, 2)
        self.hw.addWidget(self.payDate, 1, 3)

        head_col1 = QLabel('ITEM')
        head_col2 = QLabel('AMOUNT')
        head_col3 = QLabel('FULL PAY')
        head_col4 = QLabel('PART PAY')
        head_col5 = QLabel('BALANCE')

        layout1 = QGridLayout()
        layout1.addWidget(head_col1, 0, 0)
        layout1.addWidget(head_col2, 0, 1)
        layout1.addWidget(head_col3, 0, 2)
        layout1.addWidget(head_col4, 0, 3)
        layout1.addWidget(head_col5, 0, 4)

        arr = self.pullFees()
        feex = arr[1]
        payx = arr[2]

        normal_pay = []
        full_pay = []
        part_pay = []
        bal_pay = []
        ko = 1

        self.holdval = []
        self.holdfee = {}
        self.holdtextfee = {}
        self.holdtextfeeperm = {}
        self.holdpaid = {}
        self.holdcpaid = {}
        self.holdtextpaid = {}
        self.holdpayments = {}
        self.holdtextbal = {}
        self.holdbal = {}

        for val in arr[0]:
            paid = False
            s_normal_pay = []
            s_full_pay = []
            s_part_pay = []
            self.holdval.append(val)
            mz = self.pullOne('datas', {'id': val})
            self.num = val
            self.d = QLabel('Text')
            self.d.setText(str(mz['name']).upper())
            self.d1 = QLabel()
            if val in feex:
                fk = feex[int(val)].values()
                normal_pay.append(float(fk[0]))
                s_normal_pay.append(float(fk[0]))
                self.d1.setText(str("{:,}".format(float(fk[0]))).upper())
            else:
                self.d1.setText(str('-.-').upper())

            nHbo1 = QVBoxLayout()
            if val in feex:
                fk = feex[int(val)].values()
                fky = feex[int(val)].keys()
                self.c = QCheckBox('cb' + str(val))
                self.c.setEnabled(False)
                self.c.setText(str("{:,}".format(float(fk[0]))).upper())
                self.c.setObjectName("chk" + str(val))
                self.holdfee[int(val)] = self.c
                self.holdtextfee[int(val)] = fk[0]
                self.holdtextfeeperm[int(val)] = fk[0]
                self.c.toggled.connect(lambda state, x=fky[0], fee=int(
                    val), money=fk[0]: self.chkFunc(x, fee, money, self.c))
                if (val in payx) and len(payx[int(val)]) == 1:
                    pk = payx[int(val)].values()
                    self.c.setChecked(True)
                    if float(pk[0]) == float(fk[0]):
                        full_pay.append(float(fk[0]))
                        s_full_pay.append(float(fk[0]))
                        paid = True
                else:
                    self.c.setChecked(False)
                nHbo1.addWidget(self.c)
            else:
                nHbo1.addWidget(QLabel('-.-'))
                #nHbo1.hide()

            nHbo2 = QHBoxLayout()
            fk = feex[int(val)].values()
            fky = feex[int(val)].keys()
            c2 = QCheckBox()
            c2.setEnabled(False)
            c2.setMaximumWidth(15)
            c2.setObjectName("chk2" + str(val))
            p = QLineEdit()
            p.setDisabled(True)
            p.setMaximumWidth(50)
            p.setFixedWidth(51)
            p.setObjectName("pay" + str(val))
            p.setPlaceholderText("00.0")
            self.holdpaid[int(val)] = p
            self.holdcpaid[int(val)] = c2
            self.holdtextpaid[int(val)] = list()
            c2.toggled.connect(
                lambda state, x=fky[0], fee=int(val): self.chkFunc1(x, fee, p))
            if paid == False:
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)
                if val in payx and len(payx[val]) > 0:
                    for j in payx[int(val)]:
                        self.c1 = QCheckBox('cb1' + str(j))
                        self.c1.setEnabled(False)
                        self.c1.setText(str(payx[int(val)][j]).upper())
                        self.c1.setObjectName("chk" + str(j))
                        self.c1.toggled.connect(
                            lambda state, x=j: self.chkFunc1(x))
                        self.c1.setChecked(True)
                        part_pay.append(float(fk[0]))
                        s_part_pay.append(float(fk[0]))
                        self.holdpayments[j] = self.c1
                        self.holdtextpaid[val].append(float(fk[0]))
                        nHbo2.addWidget(self.c1)
                else:
                    pass
            else:
                p.hide()
                c2.hide()
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)

            s_tot = sum(s_normal_pay) - (sum(s_full_pay) + sum(s_part_pay))
            bal_pay.append(float(s_tot))
            d2 = QLabel('')
            self.holdbal[int(val)] = d2
            d2.setText(str("{:,}".format(s_tot)).upper())
            self.holdtextbal[int(val)] = s_tot

            layout1.addWidget(self.d, ko, 0)
            layout1.addWidget(self.d1, ko, 1)
            layout1.addLayout(nHbo1, ko, 2)
            layout1.addLayout(nHbo2, ko, 3)
            layout1.addWidget(d2, ko, 4)
            ko += 1

        normal_payx = sum(normal_pay)
        full_payx = sum(full_pay)
        part_payx = sum(part_pay)
        bal_payx = sum(bal_pay)

        self.head_col1 = QLabel('ITEM')
        self.head_col2 = QLabel(str("{:,}".format(normal_payx)).upper())
        self.head_col3 = QLabel(str("{:,}".format(full_payx)).upper())
        self.head_col4 = QLabel(str("{:,}".format(part_payx)).upper())
        self.head_col5 = QLabel(str("{:,}".format(bal_payx)).upper())

        layout1.addWidget(self.head_col1, ko, 0)
        layout1.addWidget(self.head_col2, ko, 1)
        layout1.addWidget(self.head_col3, ko, 2)
        layout1.addWidget(self.head_col4, ko, 3)
        layout1.addWidget(self.head_col5, ko, 4)

        self.hw1 = QGridLayout()
        self.hw1.addWidget(self.payBalanceText, 0, 0)
        self.hw1.addWidget(self.payBalanceAmount, 1, 0)

        second1 = QGridLayout()
        second1.addLayout(self.hw, 0, 0)
        second1.addLayout(layout1, 1, 0)
        second1.addLayout(self.hw1, 2, 0)

        groupBox1 = QGroupBox('Current Payment')
        groupBox1.setLayout(second1)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Fees")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Add")
        self.pb2.setText("Print Receipts")

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb1)
        hbo.addStretch()
        hbo.addWidget(self.pb)
        hbo.addStretch()
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('')
        groupBox2.setLayout(hbo)

        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        grid.addWidget(groupBox1, 1, 0)
        grid.addWidget(groupBox2, 2, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))

        self.setWindowTitle(self.pagetitle)

    def reCalFull(self):
        fees_arr = self.holdfee
        fee_store = list()
        for a in fees_arr:
            if fees_arr[a].isChecked() == True:
                h = self.holdtextfee[a]
                fee_store.append(float(h))
            else:
                pass

        fee_sum = sum(fee_store)
        self.head_col3.setText('{:,}'.format(fee_sum))

    def reCalPart(self):
        fees_arr = self.holdtextpaid
        fee_store = list()
        for a in fees_arr:
            if self.holdtextpaid[a]:
                h = sum(self.holdtextpaid[a])
                fee_store.append(float(h))

        fee_sum = sum(fee_store)
        self.head_col4.setText('{:,}'.format(fee_sum))

    def reCalBal(self):
        bal_arr = self.holdbal
        bal_store = list()
        for a in bal_arr:
            h = self.holdtextbal[a]
            bal_store.append(float(h))

        bal_sum = sum(bal_store)
        self.head_col5.setText('{:,}'.format(bal_sum))

    def reCalSingleBal(self):
        bal_arr = self.holdval
        fees_arr = self.holdfee
        for a in bal_arr:
            if fees_arr[a].isChecked() == True:
                b = self.holdtextfee[a]
                self.holdbal[a].setText('{:,}'.format(0))
                self.holdtextbal[a] = 0
            elif fees_arr[a].isChecked() == False:
                b = self.holdtextfee[a]
                self.holdbal[a].setText('{:,}'.format(float(b)))
                self.holdtextbal[a] = float(b)

        self.reCalBal()

    def chkFunc(self, a, c, d, b):
        # checkbox select to make fuul payment
        self.a = a
        db_fee = 'student_fee' + str(self.term)
        db_pay = 'student_pay' + str(self.term)
        amount = self.payAmount.text()
        teller = self.teller.text()
        # get all paments made for that fee
        # get the check box
        g = Db()
        fee = g.selectn(db_fee, '', 1, {'id': a})
        loc = self.holdfee[int(fee['feeID'])]
        poc = self.holdpaid[int(fee['feeID'])]
        pocc = self.holdcpaid[int(fee['feeID'])]

        try:
            ## fee was checked full pay
            ## confirm if money posted and its greater than or equals
            # confimr if teller number was provided
            ## if those conditions are met payment of fees is possible

            if (float(amount) >= float(d)) and len(str(teller)) > 0:
                # confirm if the checkbox was checked
                if loc.isChecked() == True:

                    #if it was checked prepare to insert payment data
                    pay = {}
                    pay['studentID'] = self.student
                    pay['accountID'] = self.payAmount.text()
                    pay['amount'] = d
                    pay['teller'] = teller
                    pay['feeID'] = fee['feeID']
                    pay['datepaid'] = self.payDate.date().toPyDate()
                    # however confirm if full payment had bee made b4
                    dat = g.select(db_pay, '', '', {
                        'studentID': self.student,
                        'feeID': fee['feeID']
                    })
                    if dat and len(dat) > 0 and float(
                            dat[0]['amount']) > 0 and float(
                                dat[0]['amount']) == float(d):
                        # full payment made
                        # dont post
                        # keep part pay disabled
                        poc.hide()
                        pocc.hide()
                        # inform user
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Info")
                        msg.setText(
                            "This fee has already been paid for. You cannot repay for it"
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()
                    else:
                        # post payment
                        h = g.insert(db_pay, pay)
                        if int(h) > 0:
                            # deduct from balance

                            # keep part pay disabled]
                            poc.hide()
                            pocc.hide()
                            # recalculate
                            self.reCalFull()
                            self.reCalSingleBal()
                        else:
                            poc.show()

                else:
                    # money was not posted
                    if len(str(self.teller.text())) > 0:
                        pay = {}
                        pay['studentID'] = self.student
                        pay['teller'] = self.teller.text()
                        pay['feeID'] = fee['feeID']
                        h = g.delete(db_pay, pay)
                        poc.show()
                        pocc.show()
                        self.reCalFull()
                        self.reCalSingleBal()

                    else:
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Info")
                        msg.setText(
                            "Please provide the teller/receipt details before removing amount."
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()
                    #add to money
            ## if those conditions are not met
            # payment of fees is not possible
            # however user might want to revoke a payment
            # meaning checkbox was unchecked
            else:
                if loc.isChecked() == False:
                    # prepare to remove payment
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    # remove payment
                    h = g.delete(db_pay, pay)
                    # confirm if removal was succesful
                    if h == 1:
                        # if successful
                        poc.show()
                        pocc.show()
                        # refund balance

                        # recalculate
                        self.reCalFull()
                        self.reCalSingleBal()
                    else:
                        # not sussefull
                        # details not complete
                        #restore it to check
                        #loc.setChecked(True)
                        poc.hide()
                        pocc.hide()
                        # inform user
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Safety Measure:")
                        msg.setText(
                            "You will need to enter the correct teller/receipt details for this payment before removing it"
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()

                # user trying to make payment with no funds
                else:
                    # uncheck user
                    loc.setChecked(False)
                    poc.show()
                    pocc.show()
                    #give info
                    msg = QMessageBox()
                    msg.setIcon(QMessageBox.Information)
                    msg.setWindowTitle(" Payment Error")
                    msg.setText(
                        "Please provide teller/receipt details or Insufficient funds to make full payments "
                    )
                    msg.setStandardButtons(QMessageBox.Cancel)
                    msg.exec_()
        except:
            if loc.isChecked() == False:
                # money was not posted
                if len(str(self.teller.text())) > 0:
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    h = g.delete(db_pay, pay)
                    poc.show()
                    pocc.show()
                    self.reCalFull()
                    self.reCalSingleBal()
                else:
                    pass

            else:
                loc.setChecked(False)
                poc.show()
                pocc.show()
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle(" Payment Error:")
                msg.setText("Please insert amount and Teller/Receipt details ")
                msg.setStandardButtons(QMessageBox.Cancel)
                msg.exec_()

    def chkFunc1(self, a, b, c):
        # checkbox select to make fuul payment
        self.a = a
        db_fee = 'student_fee' + str(self.term)
        db_pay = 'student_pay' + str(self.term)

        amount = self.payAmount.text()
        teller = self.teller.text()
        # get all paments made for that fee
        # get the check box
        g = Db()
        fee = g.selectn(db_fee, '', 1, {'id': a})
        loc = self.holdfee[b]
        payfull = self.holdtextfee[b]
        pocc = self.holdpaid[b]
        poc = self.holdcpaid[b]

        d = pocc.text()

        try:
            ## fee was checked full pay
            ## confirm if money posted and its greater than or equals
            # confimr if teller number was provided
            ## if those conditions are met payment of fees is possible
            if (float(amount) >= float(d)) and len(str(teller)) > 0:
                # confirm if the checkbox was checked
                if poc.isChecked() == True:
                    #if it was checked prepare to insert payment data
                    pay = {}
                    pay['studentID'] = self.student
                    pay['accountID'] = self.payAmount.text()
                    pay['teller'] = teller
                    pay['feeID'] = fee['feeID']
                    pay['datepaid'] = self.payDate.date().toPyDate()
                    # however confirm if full payment had bee made b4
                    dat = g.selectn(db_pay, '', '', {
                        'studentID': self.student,
                        'feeID': fee['feeID']
                    })

                    if dat and len(dat) > 0:
                        mon = list()
                        for dd in dat:
                            mon.append(float(dd['amount']))
                        # full payment made
                        # dont post
                        # keep part pay disabled
                        total_money_paid = sum(mon)
                        #no payments required
                        if float(total_money_paid) >= float(payfull):
                            pass
                        #payment required
                        elif float(total_money_paid) < float(payfull):
                            if float(amount) >= float(d):
                                pay['amount'] = d
                                #post
                                h = g.insert(db_pay, pay)
                                if int(h) > 0:
                                    # deduct from balance

                                    # keep part pay disabled]
                                    loc.hide()
                                    pocc.setDisabled(True)
                                    # recalculate
                                    self.reCalFull()
                                    self.reCalPart()
                                    self.reCalSingleBal()
                                else:
                                    poc.show()
                            else:
                                msg = QMessageBox()
                                msg.setIcon(QMessageBox.Information)
                                msg.setWindowTitle("Info")
                                msg.setText("Insufficient funds.")
                                msg.setStandardButtons(QMessageBox.Cancel)
                                msg.exec_()

                        loc.hide()
                        pocc.setDisabled(True)
                        # inform user

                    else:
                        # post payment
                        if float(amount) >= float(d):
                            pay['amount'] = d

                            #post
                            h = g.insert(db_pay, pay)

                            if int(h) > 0:
                                # deduct from balance

                                # keep part pay disabled]
                                loc.hide()
                                pocc.setDisabled(True)
                                # recalculate
                                self.reCalFull()
                                self.reCalSingleBal()
                            else:
                                poc.show()

                    # money was not posted
                    if len(str(self.teller.text())) > 0:
                        pay = {}
                        pay['studentID'] = self.student
                        pay['teller'] = self.teller.text()
                        pay['feeID'] = fee['feeID']
                        h = g.delete(db_pay, pay)
                        poc.show()
                        pocc.show()
                        self.reCalFull()
                        self.reCalSingleBal()

                    else:
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Info")
                        msg.setText(
                            "Please provide the teller/receipt details before removing amount."
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()
                    #add to money
            ## if those conditions are not met
            # payment of fees is not possible
            # however user might want to revoke a payment
            # meaning checkbox was unchecked
            else:
                if loc.isChecked() == False:
                    # prepare to remove payment
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    # remove payment
                    h = g.delete(db_pay, pay)
                    # confirm if removal was succesful
                    if h == 1:
                        # if successful
                        poc.show()
                        pocc.show()
                        # refund balance

                        # recalculate
                        self.reCalFull()
                        self.reCalSingleBal()
                    else:
                        # not sussefull
                        # details not complete
                        #restore it to check
                        #loc.setChecked(True)
                        poc.hide()
                        pocc.hide()
                        # inform user
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Safety Measure:")
                        msg.setText(
                            "You will need to enter the correct teller/receipt details for this payment before removing it"
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()

                # user trying to make payment with no funds
                else:
                    # uncheck user
                    loc.setChecked(False)
                    poc.show()
                    pocc.show()
                    #give info
                    msg = QMessageBox()
                    msg.setIcon(QMessageBox.Information)
                    msg.setWindowTitle(" Payment Error")
                    msg.setText(
                        "Please provide teller/receipt details or Insufficient funds to make full payments "
                    )
                    msg.setStandardButtons(QMessageBox.Cancel)
                    msg.exec_()
        except:

            if loc.isChecked() == False:
                # money was not posted
                if len(str(self.teller.text())) > 0:
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    h = g.delete(db_pay, pay)
                    poc.show()
                    pocc.show()
                    self.reCalFull()
                    self.reCalSingleBal()
                else:
                    pass

            else:
                loc.setChecked(False)
                poc.show()
                pocc.show()
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle(" Payment Error:")
                msg.setText("Please insert amount and Teller/Receipt details ")
                msg.setStandardButtons(QMessageBox.Cancel)
                msg.exec_()

    def getClass(self, x):
        # shost is a QString object
        class_arr = []
        for i in self.cla_arr:
            if self.cla_arr[i].checkState(0) == Qt.Checked:
                class_arr.append(i)

        c = self.getClassStudent(class_arr)
        self.feesPop.setText('Total: ' + str(c[0]))
        self.cla = class_arr
        self.students = c[1]

    def pullStudent(self, student):
        cn = Db()
        arr = cn.selectn('students', '', 1, {'id': student})
        return arr

    def pullTeller(self):
        cn = Con()
        teller = self.teller.text()
        if len(str(teller)) > 0:
            h1 = self.holdfee
            for x in h1:
                h1[x].setEnabled(True)

            h2 = self.holdpaid
            h3 = self.holdcpaid
            for x in h2:
                h2[x].setEnabled(True)
                h3[x].setEnabled(True)
        else:
            h1 = self.holdfee
            for x in h1:
                h1[x].setEnabled(False)

            h2 = self.holdpaid
            h3 = self.holdcpaid
            for x in h2:
                h2[x].setEnabled(False)
                h3[x].setEnabled(False)

        arr = cn.getTeller(self.term, self.student, teller)
        arr1 = cn.getNonTeller(self.term, self.student, teller)

        amount = self.payAmount.text()

        if amount and (float(amount) > 0):
            if arr1 and float(arr1['amount']) > 0:
                self.payBalanceAmount.setText('This teller :' + str(teller) +
                                              ' is already in use ')
            else:
                if arr and float(arr['amount']) > 0:
                    amt = arr['amount']
                    amt_a = "{:,}".format(float(amt))
                    bl = float(amount) - float(amt)
                    bl_a = "{:,}".format(float(bl))
                    self.payBalanceAmount.setText(
                        'The sum of' + str(amt_a) +
                        ' has been deducted from this teller')
                    self.payBalanceText.setText('Balance on ' + str(teller) +
                                                ' : ' + str(bl_a) + '')
                else:
                    bl = float(amount)
                    bl_a = "{:,}".format(float(bl))
                    self.payBalanceAmount.setText(
                        'No transaction on teller :' + str(teller))
                    self.payBalanceText.setText('Balance on ' + str(teller) +
                                                ' : ' + str(bl_a) + '')
        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle("Error")
            msg.setText("Error! Please enter an amount before you proceed...")
            msg.setStandardButtons(QMessageBox.Cancel)
            msg.exec_()

    def pullFees(self):
        term = self.term
        student = self.student
        fee_id_array = []
        cn = Db()
        db_fee = 'student_fee' + str(term)
        db_pay = 'student_pay' + str(term)

        fee = cn.selectn(db_fee, '', '', {'studentID': student})
        pay = cn.selectn(db_pay, '', '', {'studentID': student})
        #get all fees
        arr = {}
        arr1 = {}
        for r in fee:
            fee_id_array.append(int(r['feeID']))
            arr[int(r['feeID'])] = {}

        for r in pay:
            fee_id_array.append(int(r['feeID']))
            arr1[int(r['feeID'])] = {}

        for r in fee:
            get_mon = cn.selectn(
                'datas', '', 1, {
                    'pubID': 'fee',
                    'subID': self.term,
                    'name': self.clasz,
                    'abbrv': r['feeID']
                })
            if arr[int(r['feeID'])] and isinstance(arr[int(r['feeID'])], dict):
                arr[int(r['feeID'])][int(r['id'])] = get_mon['description']
            else:
                arr[int(r['feeID'])] = {}
                arr[int(r['feeID'])][int(r['id'])] = get_mon['description']

        for r in pay:
            if arr1[int(r['feeID'])] and isinstance(arr1[int(r['feeID'])],
                                                    dict):
                arr1[int(r['feeID'])][int(r['id'])] = r['amount']
            else:
                arr1[int(r['feeID'])] = {}
                arr1[int(r['feeID'])][int(r['id'])] = r['amount']

        fee_ids = list(set(fee_id_array))
        fin = [fee_ids, arr, arr1]
        return fin

    def pullOne(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, b)
        return arr

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def pullAccount(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullRep(self):
        cn = Db()
        ca = "rep"
        arr = cn.selectn('datas', '', '', {"subID": self.sid, "pubID": ca})
        return arr

    def button_close(self, b):
        b.close()

    def button_click(self):
        tex = ' Please wait processing, do not cancel or close..'
        self.feesPop.setText(tex)
        _term = self.term
        _class = self.cla
        _students = self.students
        _amount = self.feesAmount.text()
        _fee = self.hol[self.feesCombo.currentIndex()]

        for j in _class:
            data = {}
            data['pubID'] = 'fee'
            data['subID'] = _term
            data['abbrv'] = _fee
            data['name'] = j

            cn = Db()
            feeStudent = self.feeStudents(_term, _students, _fee, _amount)
            check = cn.selectn('datas', '', 1, data)
            if (check and check['id'] == 0):
                pass
            else:
                data['description'] = _amount
                cn.insert('datas', data)

        ins = feeStudent
        tex = ' TOTAL of ' + str(ins) + ' inserted'
        self.feesPop.setText(tex)

    def feeStudents(self, session, students, fee, amount):
        db = 'student_fee' + str(session)
        cn = Db()
        fd = []
        ed = []

        for s in students:
            data = {}
            data['studentID'] = s[0]
            data['feeID'] = fee

            chk = cn.selectn(db, '', 1, data)
            if (chk and int(chk['id']) > 0):
                #confirm if money available
                pass
            else:
                #if money not set , set
                e = cn.insert(db, data)
                ed.append(e)

        return len(ed)

    def lunchEditForm(self, row):
        term = self.term
        self.close()
        self.post = EditReportDialog(term, row)
        self.post.show()

    def lunchDeleteForm(self, row):
        cn = Db()
        arr = cn.update('datas', {"active": 1})
        self.close()
        self.__init__(self.term, self.termname)
Beispiel #17
0
class DHCPWidget(QFrame):
    def __init__(self, client, main_window, parent):
        QFrame.__init__(self, parent)
        self._parent = parent
        self._loading = True
        self._modified = False
        self.client = client
        self.main_window = main_window
        self.addToInfoArea = self.main_window.addToInfoArea
        self.q_netobject = QNetObject.getInstance()
#        try:
#            self.q_netobject.registerCallbacks(self.acceptNetworkChange, self.handleNetworkChange)
#        except Exception, err:
#            raise

        self.dhcpcfg = None
        self.range_widgets = set()
        self.drawGUI()
        self.resetConf()
        self._loading = False

    def drawGUI(self):
        form_layout = QFormLayout(self)
        form_layout.setFormAlignment(Qt.AlignLeft)
        title = QLabel(tr("<H1>DHCP Configuration</H1>"))
        form_layout.addRow(title)

        self.enable = QCheckBox(tr("Enable DHCP Server on configured LANs"))
        form_layout.addRow(self.enable)
        self.main_window.writeAccessNeeded(self.enable)

        self.add_button = AddButton()
        self.add_button.setText(tr("Add a range"))
        self.main_window.writeAccessNeeded(self.add_button)
        form_layout.addRow(self.add_button, QLabel())
        if not self.main_window.readonly:
            self.connect(self.enable, SIGNAL('stateChanged(int)'), self.setDHCPEnabled)
            self.connect(self.add_button, SIGNAL('clicked()'), self.addRange)

        self.setLayout(form_layout)

    def addRange(self):
        self.setModified(True)
        self.addRangeFrontend()

    def fetchCfg(self):
        dhcpcfg_repr = self.main_window.init_call("dhcp", "getDhcpConfig")
        if dhcpcfg_repr is None:
            #Failing to fetch dhcp config
            return None
        netcfg = self.q_netobject.netcfg
        if netcfg is None:
            return None
        return deserialize(dhcpcfg_repr, netcfg)

    def setDHCPEnabled(self, state):
        self.setModified(True)
        if state == Qt.Unchecked:
            self.dhcpcfg.enabled = DISABLED
        else:
            self.dhcpcfg.enabled = ENABLED

    def isModified(self):
        return self._modified

    def setModified(self, bool=True):
        if self._loading:
            return
        if bool == True:
            self.main_window.setModified(self._parent, True)
        if self._modified is False and bool is True:
            self.addToInfoArea(tr("DHCP Server configuration edited."))
        self._modified = bool

    def resetConf(self):
        self.dhcpcfg = self.fetchCfg()
        if self.dhcpcfg is None:
            self._clearWidgets()
            msg_area = MessageArea()
            msg_area.setMessage(
                tr("Problem loading the network or dhcp configuration!"),
                tr("A problem occured while loading the network "
                "or dhcp config from the appliance!"),
                "critical"
                )
            self.layout().insertRow(2, msg_area)
            self.enable.setEnabled(False)
            self.add_button.setEnabled(False)
        else:
            self.fillView()
        self._modified = False

    def _clearWidgets(self):
        for widget in self.range_widgets:
            # sometimes the widget stay visible
            widget.close()

        self.range_widgets.clear()

    def fillView(self):
        self._clearWidgets()
        if self.dhcpcfg is None:
            return

        for range in self.dhcpcfg.ranges:
            self.addRangeFrontend(range=range)
        if  self.dhcpcfg.enabled == ENABLED:
            check_state = Qt.Checked
        else:
            check_state = Qt.Unchecked
        self.enable.setCheckState(check_state)

    def addRangeFrontend(self, range=None):
        # called by resetConf so we can access to QNetObject.getInstance().netcfg
        range_widget = NewRangeFrontend(dhcprange=range)

        self.main_window.writeAccessNeeded(range_widget)
        self.range_widgets.add(range_widget)
        self.connect(range_widget, SIGNAL('deleted'), self.delRangeFrontend)
        self.connect(range_widget, SIGNAL('modified'), self.setModified)
        if range is None:
            self.dhcpcfg.ranges.add(range_widget.dhcprange)
        layout = self.layout()
        layout.insertRow(2, range_widget)

        range_widget.setParent(self)

    def getWidgetFromRange(self, range):
        for widget in self.range_widgets:
            if widget.range is range:
                return widget

    def delRangeFrontend(self, range_widget):
        self.dhcpcfg.ranges.discard(range_widget.dhcprange)
        self.range_widgets.discard(range_widget)
        self.setModified(True)

    def isValid(self):
        to_remove = set()
        for range_widget in self.range_widgets:
            dhcprange = range_widget.dhcprange
            if dhcprange not in self.dhcpcfg.ranges or dhcprange.is_fully_unset():
                to_remove.add(range_widget)
                continue
        for range_widget in to_remove:
            self.delRangeFrontend(range_widget)
            range_widget.close()
        return self.dhcpcfg.isValid()

    def saveConf(self, message):
        dhcpcfg_repr = self.dhcpcfg.serialize()
        self.client.call("dhcp", 'setDhcpConfig', dhcpcfg_repr, message)
        self.setModified(False)
        self.addToInfoArea(tr("DHCP server configuration uploaded to server."))

    def acceptNetworkChange(self):
        deletable = set()
        translatable = set()

        translated_ranges = {}

        if self.dhcpcfg is None:
            return True, translated_ranges, deletable

        deletable, translatable = self.dhcpcfg.computeChanges(self.q_netobject.netcfg)

        if not (deletable | translatable):
            #Nothing to do (yay!) we agree with proposed changes
            return True

        #oh, questions arrive
        accept = True
        generic_text = "<h2>%s</h2>" % tr("This change affects the DHCP server configuration")

        #TODO: add questions and return


        for range in translatable:

            if not accept:
                break

            if not isinstance(range.router, IP):
                new_router_ip = UNSET
            else:
                new_router_ip = adjust_ip(range.net.net, range.router)

            widget_range = self.getWidgetFromRange(range)
            simulation = {
                'start': adjust_ip(range.net.net, range.start),
                'end': adjust_ip(range.net.net, range.end),
                'router': new_router_ip,
                'custom_dns': widget_range.custom_dns,
                }

            cur_router = _valuefromrouter(range.router)
            new_router = _valuefromrouter(simulation['router'])

            help_items = []
            help_items.append(tr("Clicking \"Yes\" will change the DHCP range."))
            help_items.append(tr("Clicking \"Ignore\" will not change the DHCP range. Double-check the DHCP server configuration before saving."))
            help_items.append(tr("Clicking \"Cancel\" will cancel your changes to the network configuration"))
            help_text = unicode(htmlList(help_items))

            title = tr("DHCP: Translate a range?")

            html = u"""<table>
                %(title)s<br />
                %(ask)s<br />
                <tr>
                    <td><h2>%(start)s</h2></td>
                    <td>%(cur_start)s</td>
                    <td><img src=":/icons-32/go-next"/></td>
                    <td>%(simu_start)s</td>
                </tr>
                <tr>
                    <td><h2>%(end)s</h2></td>
                    <td>%(cur_end)s</td>
                    <td><img src=":/icons-32/go-next"/></td>
                    <td>%(simu_end)s</td>
                </tr>
                <tr>
                    <td><h2>%(router)s</h2></td>
                    <td>%(cur_router)s</td>
                    <td><img src=":/icons-32/go-next"/></td>
                    <td>%(simu_router)s</td>
                </tr>
            </table>
            """ % {
                'title' : tr("You changed the network address for the '<i>%s</i>' network") % range.net.label,
                'ask' : tr("Do you want to adjust the range?"),
                'start' : tr("Start IP"),
                'cur_start' : range.start,
                'simu_start' : unicode(simulation['start']),
                'end' : tr("End IP"),
                'cur_end' : range.end,
                'simu_end' : unicode(simulation['end']),
                'router' : tr("Router IP"),
                'cur_router' : cur_router,
                'simu_router' : unicode(new_router),
            }

            html += help_text

            message_box = QMessageBox(self)
            message_box.setWindowTitle(title)
            message_box.setText(generic_text)
            message_box.setInformativeText(html)
            message_box.setStandardButtons(
                QMessageBox.Yes | QMessageBox.Ignore | QMessageBox.Cancel
            )

            clicked_button = message_box.exec_()
            accept = clicked_button in (QMessageBox.Yes, QMessageBox.Ignore)
            if clicked_button == QMessageBox.Yes:
                translated_ranges[range] = simulation

        deletable_ranges = frozenset()

        if accept and deletable:
            deletable_tr = tr("Consequence: the following DHCP range will be deleted:")
            deletable_html = u"<ul>"
            for range in deletable:
                deletable_html += "<li>%s %s: %s > %s</li>" % (
                    deletable_tr,
                    unicode(range.net),
                    unicode(range.start),
                    unicode(range.end)
                    )
            deletable_html += u"</ul>"
            title = tr("DHCP configuration")
            message_box = QMessageBox(self)
            message_box.setWindowTitle(title)
            message_box.setText(generic_text)
            message_box.setInformativeText(deletable_html)
            message_box.setStandardButtons(
                QMessageBox.Yes | QMessageBox.Cancel
            )

            clicked_button = message_box.exec_()
            accept = (clicked_button == QMessageBox.Yes)
            if accept:
                deletable_ranges = deletable

        if not accept:
            return False

        return True, translated_ranges, deletable_ranges

    def handleNetworkChange(self, *args):
        if args:
            translated_ranges, deleted_ranges = args

            changed = False
            for range in deleted_ranges:
                self.dhcpcfg.ranges.remove(range)
                changed = True

            for range, translation in translated_ranges.iteritems():
                range.start = translation['start']
                range.end = translation['end']
                range.router = translation['router']
                changed = True

            if changed:
                self.setModified(True)
        self.fillView()
Beispiel #18
0
class GeneralPreferences(QGroupBox):
    def __init__(self, parent):
        super(GeneralPreferences, self).__init__(parent)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.typq = QCheckBox()
        self.tagl = QCheckBox()
        self.barnum = QCheckBox()
        self.neutdir = QCheckBox()
        self.midi = QCheckBox()
        self.metro = QCheckBox()
        self.paperSizeLabel = QLabel()
        self.paper = QComboBox()
        self.paper.addItems(paperSizes)
        self.paperLandscape = QCheckBox(enabled=False)
        self.paper.activated.connect(self.slotPaperChanged)

        layout.addWidget(self.typq)
        layout.addWidget(self.tagl)
        layout.addWidget(self.barnum)
        layout.addWidget(self.neutdir)
        layout.addWidget(self.midi)
        layout.addWidget(self.metro)

        box = QHBoxLayout(spacing=2)
        box.addWidget(self.paperSizeLabel)
        box.addWidget(self.paper)
        box.addWidget(self.paperLandscape)
        layout.addLayout(box)
        app.translateUI(self)

        self.loadSettings()
        self.window().finished.connect(self.saveSettings)

    def translateUI(self):
        self.setTitle(_("General preferences"))
        self.typq.setText(_("Use typographical quotes"))
        self.typq.setToolTip(
            _("Replace normal quotes in titles with nice typographical quotes."
              ))
        self.tagl.setText(_("Remove default tagline"))
        self.tagl.setToolTip(
            _("Suppress the default tagline output by LilyPond."))
        self.barnum.setText(_("Remove bar numbers"))
        self.barnum.setToolTip(
            _("Suppress the display of measure numbers at the beginning of "
              "every system."))
        self.neutdir.setText(_("Smart neutral stem direction"))
        self.neutdir.setToolTip(
            _("Use a logical direction (up or down) for stems on the middle "
              "line of a staff."))
        self.midi.setText(_("Create MIDI output"))
        self.midi.setToolTip(
            _("Create a MIDI file in addition to the PDF file."))
        self.metro.setText(_("Show metronome mark"))
        self.metro.setToolTip(
            _("If checked, show the metronome mark at the beginning of the "
              "score. The MIDI output also uses the metronome setting."))
        # paper size:
        self.paperSizeLabel.setText(_("Paper size:"))
        self.paper.setItemText(0, _("Default"))
        self.paperLandscape.setText(_("Landscape"))

    def slotPaperChanged(self, index):
        self.paperLandscape.setEnabled(bool(index))

    def getPaperSize(self):
        """Returns the configured papersize or the empty string for default."""
        return paperSizes[self.paper.currentIndex()]

    def loadSettings(self):
        s = QSettings()
        s.beginGroup('scorewiz/preferences')
        self.typq.setChecked(s.value('typographical_quotes', True, bool))
        self.tagl.setChecked(s.value('remove_tagline', False, bool))
        self.barnum.setChecked(s.value('remove_barnumbers', False, bool))
        self.neutdir.setChecked(s.value('smart_neutral_direction', False,
                                        bool))
        self.midi.setChecked(s.value('midi', True, bool))
        self.metro.setChecked(s.value('metronome_mark', False, bool))
        psize = s.value('paper_size', '', type(""))
        enable = bool(psize and psize in paperSizes)
        self.paper.setCurrentIndex(paperSizes.index(psize) if enable else 0)
        self.paperLandscape.setChecked(s.value('paper_landscape', False, bool))
        self.paperLandscape.setEnabled(enable)

    def saveSettings(self):
        s = QSettings()
        s.beginGroup('scorewiz/preferences')
        s.setValue('typographical_quotes', self.typq.isChecked())
        s.setValue('remove_tagline', self.tagl.isChecked())
        s.setValue('remove_barnumbers', self.barnum.isChecked())
        s.setValue('smart_neutral_direction', self.neutdir.isChecked())
        s.setValue('midi', self.midi.isChecked())
        s.setValue('metronome_mark', self.metro.isChecked())
        s.setValue('paper_size', paperSizes[self.paper.currentIndex()])
        s.setValue('paper_landscape', self.paperLandscape.isChecked())
Beispiel #19
0
class RunDialog(QDialog):
    """ Run parameters dialog implementation """

    # See utils.run for runParameters
    def __init__(self,
                 path,
                 runParameters,
                 termType,
                 profilerParams,
                 debuggerParams,
                 action="",
                 parent=None):
        QDialog.__init__(self, parent)

        # Used as a return value
        self.termType = termType
        self.profilerParams = copy.deepcopy(profilerParams)
        self.debuggerParams = copy.deepcopy(debuggerParams)

        self.__action = action.lower()

        # Avoid pylint complains
        self.__argsEdit = None
        self.__scriptWDRButton = None
        self.__dirRButton = None
        self.__dirEdit = None
        self.__dirSelectButton = None
        self.__inheritParentRButton = None
        self.__inheritParentPlusRButton = None
        self.__inhPlusEnvTable = None
        self.__addInhButton = None
        self.__delInhButton = None
        self.__editInhButton = None
        self.__specificRButton = None
        self.__specEnvTable = None
        self.__addSpecButton = None
        self.__delSpecButton = None
        self.__editSpecButton = None
        self.__runButton = None
        self.__nodeLimitEdit = None
        self.__edgeLimitEdit = None

        self.__createLayout(action)
        self.setWindowTitle(action + " parameters for " + path)

        # Restore the values
        self.runParams = copy.deepcopy(runParameters)
        self.__argsEdit.setText(self.runParams.arguments)

        # Working dir
        if self.runParams.useScriptLocation:
            self.__scriptWDRButton.setChecked(True)
            self.__dirEdit.setEnabled(False)
            self.__dirSelectButton.setEnabled(False)
        else:
            self.__dirRButton.setChecked(True)
            self.__dirEdit.setEnabled(True)
            self.__dirSelectButton.setEnabled(True)

        self.__dirEdit.setText(self.runParams.specificDir)

        # Environment
        self.__populateTable(self.__inhPlusEnvTable,
                             self.runParams.additionToParentEnv)
        self.__populateTable(self.__specEnvTable, self.runParams.specificEnv)

        if self.runParams.envType == RunParameters.InheritParentEnv:
            self.__inheritParentRButton.setChecked(True)
            self.__setEnabledInheritedPlusEnv(False)
            self.__setEnabledSpecificEnv(False)
        elif self.runParams.envType == RunParameters.InheritParentEnvPlus:
            self.__inheritParentPlusRButton.setChecked(True)
            self.__setEnabledSpecificEnv(False)
        else:
            self.__specificRButton.setChecked(True)
            self.__setEnabledInheritedPlusEnv(False)

        # Terminal
        if self.termType == TERM_REDIRECT:
            self.__redirectRButton.setChecked(True)
        elif self.termType == TERM_AUTO:
            self.__autoRButton.setChecked(True)
        elif self.termType == TERM_KONSOLE:
            self.__konsoleRButton.setChecked(True)
        elif self.termType == TERM_GNOME:
            self.__gnomeRButton.setChecked(True)
        else:
            self.__xtermRButton.setChecked(True)

        # Close checkbox
        self.__closeCheckBox.setChecked(self.runParams.closeTerminal)
        if self.termType == TERM_REDIRECT:
            self.__closeCheckBox.setEnabled(False)

        # Profile limits if so
        if self.__action == "profile":
            if self.profilerParams.nodeLimit < 0.0 or \
               self.profilerParams.nodeLimit > 100.0:
                self.profilerParams.nodeLimit = 1.0
            self.__nodeLimitEdit.setText(str(self.profilerParams.nodeLimit))
            if self.profilerParams.edgeLimit < 0.0 or \
               self.profilerParams.edgeLimit > 100.0:
                self.profilerParams.edgeLimit = 1.0
            self.__edgeLimitEdit.setText(str(self.profilerParams.edgeLimit))
        elif self.__action == "debug":
            self.__reportExceptionCheckBox.setChecked(
                self.debuggerParams.reportExceptions)
            self.__traceInterpreterCheckBox.setChecked(
                self.debuggerParams.traceInterpreter)
            self.__stopAtFirstCheckBox.setChecked(
                self.debuggerParams.stopAtFirstLine)
            self.__autoforkCheckBox.setChecked(self.debuggerParams.autofork)
            self.__debugChildCheckBox.setChecked(
                self.debuggerParams.followChild)
            self.__debugChildCheckBox.setEnabled(self.debuggerParams.autofork)

        self.__setRunButtonProps()
        return

    @staticmethod
    def __populateTable(table, dictionary):
        " Populates the given table "
        for key, value in dictionary.iteritems():
            item = QTreeWidgetItem([key, value])
            table.addTopLevelItem(item)
        if dictionary:
            table.setCurrentItem(table.topLevelItem(0))
        return

    def __setEnabledInheritedPlusEnv(self, value):
        " Disables/enables 'inherited and add' section controls "
        self.__inhPlusEnvTable.setEnabled(value)
        self.__addInhButton.setEnabled(value)
        self.__delInhButton.setEnabled(value)
        self.__editInhButton.setEnabled(value)
        return

    def __setEnabledSpecificEnv(self, value):
        " Disables/enables 'specific env' section controls "
        self.__specEnvTable.setEnabled(value)
        self.__addSpecButton.setEnabled(value)
        self.__delSpecButton.setEnabled(value)
        self.__editSpecButton.setEnabled(value)
        return

    def __createLayout(self, action):
        """ Creates the dialog layout """

        self.resize(650, 300)
        self.setSizeGripEnabled(True)

        # Top level layout
        layout = QVBoxLayout(self)

        # Cmd line arguments
        argsLabel = QLabel("Command line arguments")
        self.__argsEdit = QLineEdit()
        self.__argsEdit.textChanged.connect(self.__argsChanged)
        argsLayout = QHBoxLayout()
        argsLayout.addWidget(argsLabel)
        argsLayout.addWidget(self.__argsEdit)
        layout.addLayout(argsLayout)

        # Working directory
        workDirGroupbox = QGroupBox(self)
        workDirGroupbox.setTitle("Working directory")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        workDirGroupbox.sizePolicy().hasHeightForWidth() )
        workDirGroupbox.setSizePolicy(sizePolicy)

        gridLayoutWD = QGridLayout(workDirGroupbox)
        self.__scriptWDRButton = QRadioButton(workDirGroupbox)
        self.__scriptWDRButton.setText("&Use script location")
        gridLayoutWD.addWidget(self.__scriptWDRButton, 0, 0)
        self.__scriptWDRButton.clicked.connect(self.__scriptWDirClicked)

        self.__dirRButton = QRadioButton(workDirGroupbox)
        self.__dirRButton.setText("Select &directory")
        gridLayoutWD.addWidget(self.__dirRButton, 1, 0)
        self.__dirRButton.clicked.connect(self.__dirClicked)

        self.__dirEdit = QLineEdit(workDirGroupbox)
        gridLayoutWD.addWidget(self.__dirEdit, 1, 1)
        self.__dirEdit.textChanged.connect(self.__workingDirChanged)

        self.__dirSelectButton = QPushButton(workDirGroupbox)
        self.__dirSelectButton.setText("...")
        gridLayoutWD.addWidget(self.__dirSelectButton, 1, 2)
        self.__dirSelectButton.clicked.connect(self.__selectDirClicked)

        layout.addWidget(workDirGroupbox)

        # Environment
        envGroupbox = QGroupBox(self)
        envGroupbox.setTitle("Environment")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        envGroupbox.sizePolicy().hasHeightForWidth() )
        envGroupbox.setSizePolicy(sizePolicy)

        layoutEnv = QVBoxLayout(envGroupbox)
        self.__inheritParentRButton = QRadioButton(envGroupbox)
        self.__inheritParentRButton.setText("Inherit &parent")
        self.__inheritParentRButton.clicked.connect(self.__inhClicked)
        layoutEnv.addWidget(self.__inheritParentRButton)

        self.__inheritParentPlusRButton = QRadioButton(envGroupbox)
        self.__inheritParentPlusRButton.setText(
            "Inherit parent and add/&modify")
        self.__inheritParentPlusRButton.clicked.connect(self.__inhPlusClicked)
        layoutEnv.addWidget(self.__inheritParentPlusRButton)
        hInhPlusLayout = QHBoxLayout()
        self.__inhPlusEnvTable = QTreeWidget()
        self.__inhPlusEnvTable.itemActivated.connect(
            self.__inhPlusItemActivated)
        self.__tuneTable(self.__inhPlusEnvTable)
        hInhPlusLayout.addWidget(self.__inhPlusEnvTable)
        vInhPlusLayout = QVBoxLayout()
        self.__addInhButton = QPushButton()
        self.__addInhButton.clicked.connect(self.__addInhClicked)
        self.__addInhButton.setText('Add')
        vInhPlusLayout.addWidget(self.__addInhButton)
        self.__delInhButton = QPushButton()
        self.__delInhButton.clicked.connect(self.__delInhClicked)
        self.__delInhButton.setText('Delete')
        vInhPlusLayout.addWidget(self.__delInhButton)
        self.__editInhButton = QPushButton()
        self.__editInhButton.clicked.connect(self.__editInhClicked)
        self.__editInhButton.setText("Edit")
        vInhPlusLayout.addWidget(self.__editInhButton)
        hInhPlusLayout.addLayout(vInhPlusLayout)
        layoutEnv.addLayout(hInhPlusLayout)

        self.__specificRButton = QRadioButton(envGroupbox)
        self.__specificRButton.setText("&Specific")
        self.__specificRButton.clicked.connect(self.__specClicked)
        layoutEnv.addWidget(self.__specificRButton)
        hSpecLayout = QHBoxLayout()
        self.__specEnvTable = QTreeWidget()
        self.__specEnvTable.itemActivated.connect(self.__specItemActivated)
        self.__tuneTable(self.__specEnvTable)
        hSpecLayout.addWidget(self.__specEnvTable)
        vSpecLayout = QVBoxLayout()
        self.__addSpecButton = QPushButton()
        self.__addSpecButton.clicked.connect(self.__addSpecClicked)
        self.__addSpecButton.setText('Add')
        vSpecLayout.addWidget(self.__addSpecButton)
        self.__delSpecButton = QPushButton()
        self.__delSpecButton.clicked.connect(self.__delSpecClicked)
        self.__delSpecButton.setText('Delete')
        vSpecLayout.addWidget(self.__delSpecButton)
        self.__editSpecButton = QPushButton()
        self.__editSpecButton.clicked.connect(self.__editSpecClicked)
        self.__editSpecButton.setText("Edit")
        vSpecLayout.addWidget(self.__editSpecButton)
        hSpecLayout.addLayout(vSpecLayout)
        layoutEnv.addLayout(hSpecLayout)
        layout.addWidget(envGroupbox)

        # Terminal and profile limits
        if self.__action in ["profile", "debug"]:
            layout.addWidget(self.__getIDEWideGroupbox())
        else:
            termGroupbox = self.__getTermGroupbox()
            termGroupbox.setTitle("Terminal to run in (IDE wide setting)")
            layout.addWidget(termGroupbox)

        # Close checkbox
        self.__closeCheckBox = QCheckBox("&Close terminal upon "
                                         "successful completion")
        self.__closeCheckBox.stateChanged.connect(self.__onCloseChanged)
        layout.addWidget(self.__closeCheckBox)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__runButton = buttonBox.addButton(action,
                                               QDialogButtonBox.AcceptRole)
        self.__runButton.setDefault(True)
        self.__runButton.clicked.connect(self.onAccept)
        layout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return

    def __getTermGroupbox(self):
        " Creates the term groupbox "
        termGroupbox = QGroupBox(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            termGroupbox.sizePolicy().hasHeightForWidth())
        termGroupbox.setSizePolicy(sizePolicy)

        layoutTerm = QVBoxLayout(termGroupbox)
        self.__redirectRButton = QRadioButton(termGroupbox)
        self.__redirectRButton.setText("&Redirect to IDE")
        self.__redirectRButton.toggled.connect(self.__redirectedChanged)
        layoutTerm.addWidget(self.__redirectRButton)
        self.__autoRButton = QRadioButton(termGroupbox)
        self.__autoRButton.setText("Aut&o detection")
        layoutTerm.addWidget(self.__autoRButton)
        self.__konsoleRButton = QRadioButton(termGroupbox)
        self.__konsoleRButton.setText("Default &KDE konsole")
        layoutTerm.addWidget(self.__konsoleRButton)
        self.__gnomeRButton = QRadioButton(termGroupbox)
        self.__gnomeRButton.setText("gnome-&terminal")
        layoutTerm.addWidget(self.__gnomeRButton)
        self.__xtermRButton = QRadioButton(termGroupbox)
        self.__xtermRButton.setText("&xterm")
        layoutTerm.addWidget(self.__xtermRButton)
        return termGroupbox

    def __redirectedChanged(self, checked):
        " Triggered when the redirected radio button changes its state "
        self.__closeCheckBox.setEnabled(not checked)
        return

    def __getIDEWideGroupbox(self):
        " Creates the IDE wide groupbox "
        ideGroupbox = QGroupBox(self)
        ideGroupbox.setTitle("IDE Wide Settings")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            ideGroupbox.sizePolicy().hasHeightForWidth())
        ideGroupbox.setSizePolicy(sizePolicy)

        layoutIDE = QHBoxLayout(ideGroupbox)

        termGroupbox = self.__getTermGroupbox()
        termGroupbox.setTitle("Terminal to run in")
        layoutIDE.addWidget(termGroupbox)

        if self.__action == "profile":
            # Profile version of the dialog
            limitsGroupbox = self.__getProfileLimitsGroupbox()
            layoutIDE.addWidget(limitsGroupbox)
        else:
            # Debug version of the dialog
            dbgGroupbox = self.__getDebugGroupbox()
            layoutIDE.addWidget(dbgGroupbox)
        return ideGroupbox

    def __getProfileLimitsGroupbox(self):
        " Creates the profile limits groupbox "
        limitsGroupbox = QGroupBox(self)
        limitsGroupbox.setTitle("Profiler diagram limits")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            limitsGroupbox.sizePolicy().hasHeightForWidth())
        limitsGroupbox.setSizePolicy(sizePolicy)

        layoutLimits = QGridLayout(limitsGroupbox)
        self.__nodeLimitEdit = QLineEdit()
        self.__nodeLimitEdit.textEdited.connect(self.__setRunButtonProps)
        self.__nodeLimitValidator = QDoubleValidator(0.0, 100.0, 2, self)
        self.__nodeLimitValidator.setNotation(
            QDoubleValidator.StandardNotation)
        self.__nodeLimitEdit.setValidator(self.__nodeLimitValidator)
        nodeLimitLabel = QLabel("Hide nodes below")
        self.__edgeLimitEdit = QLineEdit()
        self.__edgeLimitEdit.textEdited.connect(self.__setRunButtonProps)
        self.__edgeLimitValidator = QDoubleValidator(0.0, 100.0, 2, self)
        self.__edgeLimitValidator.setNotation(
            QDoubleValidator.StandardNotation)
        self.__edgeLimitEdit.setValidator(self.__edgeLimitValidator)
        edgeLimitLabel = QLabel("Hide edges below")
        layoutLimits.addWidget(nodeLimitLabel, 0, 0)
        layoutLimits.addWidget(self.__nodeLimitEdit, 0, 1)
        layoutLimits.addWidget(QLabel("%"), 0, 2)
        layoutLimits.addWidget(edgeLimitLabel, 1, 0)
        layoutLimits.addWidget(self.__edgeLimitEdit, 1, 1)
        layoutLimits.addWidget(QLabel("%"), 1, 2)
        return limitsGroupbox

    def __getDebugGroupbox(self):
        " Creates the debug settings groupbox "
        dbgGroupbox = QGroupBox(self)
        dbgGroupbox.setTitle("Debugger")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            dbgGroupbox.sizePolicy().hasHeightForWidth())
        dbgGroupbox.setSizePolicy(sizePolicy)

        dbgLayout = QVBoxLayout(dbgGroupbox)
        self.__reportExceptionCheckBox = QCheckBox("Report &exceptions")
        self.__reportExceptionCheckBox.stateChanged.connect(
            self.__onReportExceptionChanged)
        self.__traceInterpreterCheckBox = QCheckBox("T&race interpreter libs")
        self.__traceInterpreterCheckBox.stateChanged.connect(
            self.__onTraceInterpreterChanged)
        self.__stopAtFirstCheckBox = QCheckBox("Stop at first &line")
        self.__stopAtFirstCheckBox.stateChanged.connect(
            self.__onStopAtFirstChanged)
        self.__autoforkCheckBox = QCheckBox("&Fork without asking")
        self.__autoforkCheckBox.stateChanged.connect(self.__onAutoforkChanged)
        self.__debugChildCheckBox = QCheckBox("Debu&g child process")
        self.__debugChildCheckBox.stateChanged.connect(self.__onDebugChild)

        dbgLayout.addWidget(self.__reportExceptionCheckBox)
        dbgLayout.addWidget(self.__traceInterpreterCheckBox)
        dbgLayout.addWidget(self.__stopAtFirstCheckBox)
        dbgLayout.addWidget(self.__autoforkCheckBox)
        dbgLayout.addWidget(self.__debugChildCheckBox)
        return dbgGroupbox

    @staticmethod
    def __tuneTable(table):
        " Sets the common settings for a table "

        table.setAlternatingRowColors(True)
        table.setRootIsDecorated(False)
        table.setItemsExpandable(False)
        table.setUniformRowHeights(True)
        table.setSelectionMode(QAbstractItemView.SingleSelection)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        table.setItemDelegate(NoOutlineHeightDelegate(4))
        table.setHeaderLabels(["Variable", "Value"])

        header = table.header()
        header.setSortIndicator(0, Qt.AscendingOrder)
        header.setSortIndicatorShown(True)
        header.setClickable(True)
        table.setSortingEnabled(True)
        return

    def __scriptWDirClicked(self):
        " The script working dir button is clicked "
        self.__dirEdit.setEnabled(False)
        self.__dirSelectButton.setEnabled(False)
        self.runParams.useScriptLocation = True

        self.__setRunButtonProps()
        return

    def __dirClicked(self):
        " The script specific working dir button is clicked "
        self.__dirEdit.setEnabled(True)
        self.__dirSelectButton.setEnabled(True)
        self.runParams.useScriptLocation = False

        self.__setRunButtonProps()
        return

    def __argsChanged(self, value):
        " Triggered when cmd line args are changed "
        value = str(value).strip()
        self.runParams.arguments = value
        self.__setRunButtonProps()
        return

    def __workingDirChanged(self, value):
        " Triggered when a working dir value is changed "
        value = str(value)
        self.runParams.specificDir = value
        self.__setRunButtonProps()
        return

    def __onCloseChanged(self, state):
        " Triggered when the close terminal check box changed "
        self.runParams.closeTerminal = state != 0
        return

    def __onReportExceptionChanged(self, state):
        " Triggered when exception report check box changed "
        self.debuggerParams.reportExceptions = state != 0
        return

    def __onTraceInterpreterChanged(self, state):
        " Triggered when trace interpreter changed "
        self.debuggerParams.traceInterpreter = state != 0
        return

    def __onStopAtFirstChanged(self, state):
        " Triggered when stop at first changed "
        self.debuggerParams.stopAtFirstLine = state != 0
        return

    def __onAutoforkChanged(self, state):
        " Triggered when autofork changed "
        self.debuggerParams.autofork = state != 0
        self.__debugChildCheckBox.setEnabled(self.debuggerParams.autofork)
        return

    def __onDebugChild(self, state):
        " Triggered when debug child changed "
        self.debuggerParams.followChild = state != 0
        return

    def __argumentsOK(self):
        " Returns True if the arguments are OK "
        try:
            parseCommandLineArguments(self.runParams.arguments)
            return True
        except:
            return False

    def __dirOK(self):
        " Returns True if the working dir is OK "
        if self.__scriptWDRButton.isChecked():
            return True
        return os.path.isdir(self.__dirEdit.text())

    def __setRunButtonProps(self, newText=None):
        " Enable/disable run button and set its tooltip "
        if not self.__argumentsOK():
            self.__runButton.setEnabled(False)
            self.__runButton.setToolTip("No closing quotation in arguments")
            return

        if not self.__dirOK():
            self.__runButton.setEnabled(False)
            self.__runButton.setToolTip("The given working "
                                        "dir is not found")
            return

        if self.__nodeLimitEdit is not None:
            txt = self.__nodeLimitEdit.text().strip()
            try:
                value = float(txt)
                if value < 0.0 or value > 100.0:
                    raise Exception("Out of range")
            except:
                self.__runButton.setEnabled(False)
                self.__runButton.setToolTip("The given node limit "
                                            "is out of range")
                return

        if self.__edgeLimitEdit is not None:
            txt = self.__edgeLimitEdit.text().strip()
            try:
                value = float(txt)
                if value < 0.0 or value > 100.0:
                    raise Exception("Out of range")
            except:
                self.__runButton.setEnabled(False)
                self.__runButton.setToolTip("The given edge limit "
                                            "is out of range")
                return

        self.__runButton.setEnabled(True)
        self.__runButton.setToolTip("Save parameters and " + self.__action +
                                    " script")
        return

    def __selectDirClicked(self):
        " Selects the script working dir "
        dirName = QFileDialog.getExistingDirectory(
            self, "Select the script working directory", self.__dirEdit.text(),
            QFileDialog.Options(QFileDialog.ShowDirsOnly))

        if dirName:
            self.__dirEdit.setText(os.path.normpath(dirName))
        return

    def __inhClicked(self):
        " Inerit parent env radio button clicked "
        self.__setEnabledInheritedPlusEnv(False)
        self.__setEnabledSpecificEnv(False)
        self.runParams.envType = RunParameters.InheritParentEnv
        return

    def __inhPlusClicked(self):
        " Inherit parent and add radio button clicked "
        self.__setEnabledInheritedPlusEnv(True)
        self.__setEnabledSpecificEnv(False)
        self.runParams.envType = RunParameters.InheritParentEnvPlus

        if self.__inhPlusEnvTable.selectedIndexes():
            self.__delInhButton.setEnabled(True)
            self.__editInhButton.setEnabled(True)
        else:
            self.__delInhButton.setEnabled(False)
            self.__editInhButton.setEnabled(False)
        return

    def __specClicked(self):
        " Specific env radio button clicked "
        self.__setEnabledInheritedPlusEnv(False)
        self.__setEnabledSpecificEnv(True)
        self.runParams.envType = RunParameters.SpecificEnvironment

        if self.__specEnvTable.selectedIndexes():
            self.__delSpecButton.setEnabled(True)
            self.__editSpecButton.setEnabled(True)
        else:
            self.__delSpecButton.setEnabled(False)
            self.__editSpecButton.setEnabled(False)
        return

    @staticmethod
    def __delAndInsert(table, name, value):
        " Deletes an item by name if so; insert new; highlight it "
        for index in xrange(table.topLevelItemCount()):
            item = table.topLevelItem(index)
            if str(item.text(0)) == name:
                table.takeTopLevelItem(index)
                break

        item = QTreeWidgetItem([name, value])
        table.addTopLevelItem(item)
        table.setCurrentItem(item)
        return item

    def __addInhClicked(self):
        " Add env var button clicked "
        dlg = EnvVarDialog()
        if dlg.exec_() == QDialog.Accepted:
            name = str(dlg.name)
            value = str(dlg.value)
            self.__delAndInsert(self.__inhPlusEnvTable, name, value)
            self.runParams.additionToParentEnv[name] = value
            self.__delInhButton.setEnabled(True)
            self.__editInhButton.setEnabled(True)
        return

    def __addSpecClicked(self):
        " Add env var button clicked "
        dlg = EnvVarDialog()
        if dlg.exec_() == QDialog.Accepted:
            name = str(dlg.name)
            value = str(dlg.value)
            self.__delAndInsert(self.__specEnvTable, name, value)
            self.runParams.specificEnv[name] = value
            self.__delSpecButton.setEnabled(True)
            self.__editSpecButton.setEnabled(True)
        return

    def __delInhClicked(self):
        " Delete the highlighted variable "
        if self.__inhPlusEnvTable.topLevelItemCount() == 0:
            return

        name = self.__inhPlusEnvTable.currentItem().text(0)
        for index in xrange(self.__inhPlusEnvTable.topLevelItemCount()):
            item = self.__inhPlusEnvTable.topLevelItem(index)
            if name == item.text(0):
                self.__inhPlusEnvTable.takeTopLevelItem(index)
                break

        del self.runParams.additionToParentEnv[str(name)]
        if self.__inhPlusEnvTable.topLevelItemCount() == 0:
            self.__delInhButton.setEnabled(False)
            self.__editInhButton.setEnabled(False)
        else:
            self.__inhPlusEnvTable.setCurrentItem( \
                                self.__inhPlusEnvTable.topLevelItem( 0 ) )
        return

    def __delSpecClicked(self):
        " Delete the highlighted variable "
        if self.__specEnvTable.topLevelItemCount() == 0:
            return

        name = self.__specEnvTable.currentItem().text(0)
        for index in xrange(self.__specEnvTable.topLevelItemCount()):
            item = self.__specEnvTable.topLevelItem(index)
            if name == item.text(0):
                self.__specEnvTable.takeTopLevelItem(index)
                break

        del self.runParams.specificEnv[str(name)]
        if self.__specEnvTable.topLevelItemCount() == 0:
            self.__delSpecButton.setEnabled(False)
            self.__editSpecButton.setEnabled(False)
        else:
            self.__specEnvTable.setCurrentItem( \
                            self.__specEnvTable.topLevelItem( 0 ) )
        return

    def __editInhClicked(self):
        " Edits the highlighted variable "
        if self.__inhPlusEnvTable.topLevelItemCount() == 0:
            return

        item = self.__inhPlusEnvTable.currentItem()
        dlg = EnvVarDialog(str(item.text(0)), str(item.text(1)), self)
        if dlg.exec_() == QDialog.Accepted:
            name = str(dlg.name)
            value = str(dlg.value)
            self.__delAndInsert(self.__inhPlusEnvTable, name, value)
            self.runParams.additionToParentEnv[name] = value
        return

    def __inhPlusItemActivated(self, item, column):
        " Triggered when a table item is activated "
        self.__editInhClicked()
        return

    def __editSpecClicked(self):
        " Edits the highlighted variable "
        if self.__specEnvTable.topLevelItemCount() == 0:
            return

        item = self.__specEnvTable.currentItem()
        dlg = EnvVarDialog(str(item.text(0)), str(item.text(1)), self)
        if dlg.exec_() == QDialog.Accepted:
            name = str(dlg.name)
            value = str(dlg.value)
            self.__delAndInsert(self.__specEnvTable, name, value)
            self.runParams.specificEnv[name] = value
        return

    def __specItemActivated(self, item, column):
        " Triggered when a table item is activated "
        self.__editSpecClicked()
        return

    def onAccept(self):
        " Saves the selected terminal and profiling values "
        if self.__redirectRButton.isChecked():
            self.termType = TERM_REDIRECT
        elif self.__autoRButton.isChecked():
            self.termType = TERM_AUTO
        elif self.__konsoleRButton.isChecked():
            self.termType = TERM_KONSOLE
        elif self.__gnomeRButton.isChecked():
            self.termType = TERM_GNOME
        else:
            self.termType = TERM_XTERM

        if self.__action == "profile":
            self.profilerParams.nodeLimit = float(self.__nodeLimitEdit.text())
            self.profilerParams.edgeLimit = float(self.__edgeLimitEdit.text())

        self.accept()
        return
Beispiel #20
0
class TodoPropertiesDialog( QDialog ):
    """ todo properties dialog implementation """

    def __init__( self, todo = None, parent = None ):

        QDialog.__init__( self, parent )
        self.setWindowTitle( "Todo Properties" )

        self.__createLayout()

        if todo is not None:
            self.descriptionEdit.setText( todo.description )
            self.completedCheckBox.setChecked( todo.completed )
            self.filenameEdit.setText( todo.filename )
            if todo.lineno:
                self.linenoEdit.setText( str( todo.lineno ) )
        return

    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 579, 297 )
        self.setSizeGripEnabled( True )

        self.gridlayout = QGridLayout( self )

        self.descriptionLabel = QLabel( self )
        self.descriptionLabel.setText( "Description:" )
        self.gridlayout.addWidget( self.descriptionLabel, 0, 0, 1, 1 )

        self.descriptionEdit = QLineEdit( self )
        self.gridlayout.addWidget( self.descriptionEdit, 0, 1, 1, 3 )

        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )

        self.completedCheckBox = QCheckBox( self )
        self.completedCheckBox.setText( "Completed" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth( self.completedCheckBox.sizePolicy().hasHeightForWidth() )
        self.completedCheckBox.setSizePolicy( sizePolicy )
        self.gridlayout.addWidget( self.completedCheckBox, 3, 3, 1, 1 )

        self.filenameLabel = QLabel( self )
        self.filenameLabel.setText( "File name:" )
        self.gridlayout.addWidget( self.filenameLabel, 4, 0, 1, 1 )

        self.filenameEdit = QLineEdit( self )
        self.filenameEdit.setFocusPolicy( Qt.NoFocus )
        self.filenameEdit.setReadOnly( True )
        self.gridlayout.addWidget( self.filenameEdit, 4, 1, 1, 3 )

        self.lineLabel = QLabel( self )
        self.lineLabel.setText( "Line:" )
        self.gridlayout.addWidget( self.lineLabel, 5, 0, 1, 1 )

        self.linenoEdit = QLineEdit( self )
        self.linenoEdit.setFocusPolicy( Qt.NoFocus )
        self.linenoEdit.setReadOnly( True )
        self.gridlayout.addWidget( self.linenoEdit, 5, 1, 1, 3 )

        self.buttonBox = QDialogButtonBox( self )
        self.buttonBox.setOrientation( Qt.Horizontal )
        self.buttonBox.setStandardButtons( QDialogButtonBox.Cancel | \
                                           QDialogButtonBox.Ok )
        self.gridlayout.addWidget( self.buttonBox, 6, 0, 1, 4 )

        self.descriptionLabel.setBuddy( self.descriptionEdit )

        self.buttonBox.accepted.connect( self.accept )
        self.buttonBox.rejected.connect( self.reject )
        QMetaObject.connectSlotsByName( self )
        self.setTabOrder( self.completedCheckBox, self.buttonBox )
        return

    def setReadOnly( self ):
        """ Disables editing some fields """

        self.descriptionEdit.setReadOnly( True )
        self.completedCheckBox.setEnabled( False )
        return

    def getData( self ):
        """ Provides the dialog data """

        return ( self.descriptionEdit.text(),
                 self.completedCheckBox.isChecked() )
Beispiel #21
0
class AnimationWindow(PyDialog):
    """
    +-------------------+
    | Animation         |
    +-------------------------+
    | icase   ______          |
    | scale   ______  Default |
    | time    ______  Default |
    |                         |
    | nframes ______  Default |
    | resolu. ______  Default |
    | Dir     ______  Browse  |
    | iFrame  ______          |
    |                         |
    | Animations:             |
    | o Scale, Phase, Time    |  # TODO: add time
    |                         |
    | x delete images         |
    | x repeat                |  # TODO: change to an integer
    | x make gif              |
    |                         |
    |      Step, RunAll       |
    |         Close           |
    +-------------------------+

    TODO: add key-frame support
    """
    def __init__(self, data, win_parent=None):
        PyDialog.__init__(self, data, win_parent)
        self.set_font_size(data['font_size'])
        self.istep = 0
        self._animate_type = 'time'

        self._updated_animation = False
        self._icase = data['icase']
        self._default_name = data['name']
        self._default_time = data['time']
        self._default_fps = data['frames/sec']
        self._default_resolution = data['resolution']

        self._scale = data['scale']
        self._default_scale = data['default_scale']
        self._default_is_scale = data['is_scale']

        self._phase = data['phase']
        self._default_phase = data['default_phase']

        self._default_dirname = data['dirname']
        self._default_gif_name = os.path.join(self._default_dirname,
                                              data['name'] + '.gif')

        self.animation_types = [
            'Animate Scale',
        ]
        #'Animate Phase',
        #'Animate Time',
        #'Animate Frequency Sweep'
        #]

        self.setWindowTitle('Animate Model')
        self.create_widgets()
        self.create_layout()
        self.set_connections()

        self.is_gui = False
        if hasattr(self.win_parent, '_updated_legend'):
            self.win_parent.is_animate_open = True
            self.is_gui = True

    def create_widgets(self):
        """creates the menu objects"""
        icase_max = 1000  # TODO: update 1000

        self.icase = QLabel("iCase:")
        self.icase_edit = QSpinBox(self)
        self.icase_edit.setRange(1, icase_max)
        self.icase_edit.setSingleStep(1)
        self.icase_edit.setValue(self._icase)
        self.icase_edit.setToolTip(
            'Case Number for the Scale/Phase Animation Type.\n'
            'Defaults to the result you had shown when you clicked "Create Animation".\n'
            'iCase can be seen by clicking "Apply" on a result.')

        self.scale = QLabel("Scale:")
        self.scale_edit = QLineEdit(str(self._scale))
        self.scale_button = QPushButton("Default")
        self.scale_edit.setToolTip('Scale factor of the "deflection"')
        self.scale_button.setToolTip('Sets the scale factor of the gif to %s' %
                                     self._scale)

        self.time = QLabel("Total Time (sec):")
        self.time_edit = QDoubleSpinBox(self)
        self.time_edit.setValue(self._default_time)
        self.time_edit.setRange(0.1, 10.0)
        self.time_edit.setDecimals(2)
        self.time_edit.setSingleStep(0.1)
        self.time_button = QPushButton("Default")
        self.time_edit.setToolTip("Total time of the gif")
        self.time_button.setToolTip('Sets the total time of the gif to %.2f' %
                                    self._default_time)

        self.fps = QLabel("Frames/Second:")
        self.fps_edit = QSpinBox(self)
        self.fps_edit.setRange(1, 60)
        self.fps_edit.setSingleStep(1)
        self.fps_edit.setValue(self._default_fps)
        self.fps_button = QPushButton("Default")
        self.fps_edit.setToolTip(
            "A higher FPS is smoother, but may not play well for large gifs")
        self.fps_button.setToolTip('Sets the FPS to %s' % self._default_fps)

        self.resolution = QLabel("Resolution Scale:")
        self.resolution_edit = QSpinBox(self)
        self.resolution_edit.setRange(1, 5)
        self.resolution_edit.setSingleStep(1)
        self.resolution_edit.setValue(self._default_resolution)
        self.resolution_button = QPushButton("Default")
        self.resolution_edit.setToolTip(
            'Scales the window resolution by an integer factor')
        self.resolution_button.setToolTip('Sets the resolution to %s' %
                                          self._default_resolution)

        #-----------------
        # Time plot
        self.icase_start = QLabel("iCase Start:")
        self.icase_start_edit = QSpinBox(self)
        self.icase_start_edit.setRange(0, icase_max)
        self.icase_start_edit.setSingleStep(1)
        self.icase_start_edit.setValue(self._icase)
        self.icase_start_button = QPushButton("Default")

        self.icase_end = QLabel("iCase End:")
        self.icase_end_edit = QSpinBox(self)
        self.icase_end_edit.setRange(0, icase_max)
        self.icase_end_edit.setSingleStep(1)
        self.icase_end_edit.setValue(self._icase)
        self.icase_end_button = QPushButton("Default")

        self.icase_delta = QLabel("iCase Delta:")
        self.icase_delta_edit = QSpinBox(self)
        self.icase_delta_edit.setRange(1, icase_max)
        self.icase_delta_edit.setSingleStep(1)
        self.icase_delta_edit.setValue(1)
        self.icase_delta_button = QPushButton("Default")

        self.min_value = QLabel("Min Value:")
        self.min_value_edit = QLineEdit(str(0.))
        #self.min_value_edit.setRange(1, 1000)
        #self.min_value_edit.setSingleStep(1)
        #self.min_value_edit.setValue(1)
        self.min_value_button = QPushButton("Default")

        self.max_value = QLabel("Max Value:")
        self.max_value_edit = QLineEdit(str(1.))
        #self.min_value_edit.setRange(1, 1000)  # TODO: update 1000
        #self.min_value_edit.setSingleStep(1)
        #self.min_value_edit.setValue(1)
        self.max_value_button = QPushButton("Default")

        self.icase_start_edit.setToolTip('The first frame of the animation')
        self.icase_end_edit.setToolTip(
            'The last frame of the animation\n'
            'Assumes icase_start + nframes * icase_delta = icase_end')
        self.icase_delta_edit.setToolTip(
            'The frame step size (to skip non-consecutive results).\n'
            'Frame skipping can be used to:\n'
            "  - skip across results that you don't want to plot\n"
            '  - adjust the FPS')

        self.min_value_edit.setToolTip(
            'Min value of the legend (not supported)')
        self.max_value_edit.setToolTip(
            'Max value of the legend (not supported)')
        #'time' : 0.,
        #'default_time' : 0,
        #'icase_start' : 10,
        #'icase_delta' : 3,
        #'min_value' : 0.,
        #'max_value' : 1000.,

        self.browse_folder = QLabel('Output Directory:')
        self.browse_folder_edit = QLineEdit(str(self._default_dirname))
        self.browse_folder_button = QPushButton('Browse')
        self.browse_folder_edit.setToolTip(
            'Location to save the png/gif files')

        self.gif = QLabel("Gif Filename:")
        self.gif_edit = QLineEdit(str(self._default_name + '.gif'))
        self.gif_button = QPushButton('Default')
        self.gif_edit.setToolTip('Name of the gif')
        self.gif_button.setToolTip('Sets the name of the gif to %s.gif' %
                                   self._default_name)

        # scale / phase
        self.animate_scale_radio = QRadioButton("Animate Scale")
        self.animate_phase_radio = QRadioButton("Animate Phase")
        self.animate_time_radio = QRadioButton("Animate Time")
        self.animate_freq_sweeep_radio = QRadioButton(
            "Animate Frequency Sweep")
        self.animate_scale_radio.setToolTip(
            'Animates the scale factor based on the "Animation Type"')
        self.animate_time_radio.setToolTip('Animates the time/load/mode step')

        self.animate_scale_radio.setChecked(self._default_is_scale)
        self.animate_phase_radio.setChecked(not self._default_is_scale)
        self.animate_time_radio.setChecked(False)

        msg = 'Scale : Animates the scale factor based on the "Animation Profile"\n'
        if self._default_phase is None:
            self.animate_phase_radio.setDisabled(True)
            self.animate_phase_radio.setToolTip('Animates the phase angle '
                                                '(only for complex results)')
            msg += 'Phase : Animates the phase angle (only for complex results)\n'
        else:
            self.animate_phase_radio.setToolTip("Animates the phase angle")
            msg += 'Phase : Animates the phase angle\n'
        msg += (
            'Time : Animates the time/load/mode step\n'
            'Freq Sweep : Animates a complex result across a range of frequencies '
            '(not supported)\n')

        self.animate_freq_sweeep_radio.setDisabled(True)
        self.animate_freq_sweeep_radio.setToolTip(
            'Animates a complex result across a range of frequencies (not supported)'
        )
        self.animation_type = QLabel("Animation Type:")
        animation_type = OrderedDict()
        #scale_msg = 'Scale\n'
        #phase_msg = 'Phase\n'
        #time_msg = 'Time\n'
        #animation_types = [
        #('Animate Scale', scale_msg),
        #('Animate Phase', phase_msg),
        #('Animate Time', time_msg),
        ##'Animate Frequency Sweep'
        #]

        if self._phase is not None:
            self.animation_types.append('Animate Phase')
        self.animation_types.append('Animate Time')

        self.animation_profile = QLabel("Animation Profile:")

        self.animation_profile_edit = QComboBox()
        for animation_profile in ANIMATION_PROFILES:
            self.animation_profile_edit.addItem(animation_profile)
        self.animation_profile_edit.setToolTip('The profile for a scaled GIF')

        self.animation_type_edit = QComboBox()
        # TODO: add a tooltip for each item
        for animation_type in self.animation_types:
            self.animation_type_edit.addItem(animation_type)
        #self.animation_type_edit.setToolTip('The profile for a scaled GIF')
        self.animation_type_edit.setToolTip(msg)

        self.csv_profile = QLabel("CSV profile:")
        self.csv_profile_edit = QLineEdit()
        self.csv_profile_browse_button = QPushButton('Browse')
        self.csv_profile_edit.setToolTip(
            'The path to the CSV file of (Scale1, Scale2, Scale3, ...)')

        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.animate_scale_radio)
        horizontal_vertical_group.addButton(self.animate_phase_radio)
        horizontal_vertical_group.addButton(self.animate_time_radio)
        horizontal_vertical_group.addButton(self.animate_freq_sweeep_radio)

        # one / two sided
        self.onesided_radio = QRadioButton("One Sided")
        self.onesided_radio.setToolTip(
            "A one sided gif doesn't return to the starting point (e.g., 0 to 360 degrees)"
        )
        self.twosided_radio = QRadioButton("Two Sided")
        self.twosided_radio.setToolTip(
            'A two sided gif returns to the starting point (e.g., 0 to 10 to 0)'
        )

        if self._default_phase is None:
            self.onesided_radio.setChecked(False)
            self.twosided_radio.setChecked(True)
        else:
            self.onesided_radio.setChecked(True)
            self.twosided_radio.setChecked(False)
        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.onesided_radio)
        horizontal_vertical_group.addButton(self.twosided_radio)

        # animate in gui
        self.animate_in_gui_checkbox = QCheckBox("Animate In GUI?")
        self.animate_in_gui_checkbox.setChecked(True)

        # make images
        self.make_images_checkbox = QCheckBox("Make images?")
        self.make_images_checkbox.setChecked(True)

        # make images
        self.overwrite_images_checkbox = QCheckBox("Overwrite images?")
        self.overwrite_images_checkbox.setChecked(True)

        # delete images when finished
        self.delete_images_checkbox = QCheckBox("Delete images when finished?")
        self.delete_images_checkbox.setChecked(True)

        # endless loop
        self.repeat_checkbox = QCheckBox("Repeat?")
        self.repeat_checkbox.setChecked(True)
        self.repeat_checkbox.setToolTip(
            "Repeating creates an infinitely looping gif")

        # endless loop
        self.make_gif_checkbox = QCheckBox("Make Gif?")
        if IS_IMAGEIO:
            self.make_gif_checkbox.setChecked(True)
        else:
            self.make_gif_checkbox.setChecked(False)
            self.make_gif_checkbox.setEnabled(False)
            self.make_gif_checkbox.setToolTip(
                'imageio is not available; install it')

        # bottom buttons
        self.step_button = QPushButton("Step")
        self.stop_button = QPushButton("Stop")
        self.run_button = QPushButton("Run All")

        #self.apply_button = QPushButton("Apply")
        #self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Close")

        #self.set_grid_time(enabled=False)
        #self.set_grid_scale(enabled=self._default_is_scale)
        if self._default_phase:
            self.on_animate_phase(force=True)
        else:
            self.on_animate_scale(force=True)

    def set_connections(self):
        """creates button actions"""
        self.scale_button.clicked.connect(self.on_default_scale)
        self.time_button.clicked.connect(self.on_default_time)

        self.fps_button.clicked.connect(self.on_default_fps)
        self.resolution_button.clicked.connect(self.on_default_resolution)
        self.browse_folder_button.clicked.connect(self.on_browse_folder)
        self.csv_profile_browse_button.clicked.connect(self.on_browse_csv)
        self.gif_button.clicked.connect(self.on_default_name)

        self.step_button.clicked.connect(self.on_step)
        self.stop_button.clicked.connect(self.on_stop)
        self.run_button.clicked.connect(self.on_run)

        #self.animate_scale_radio.clicked.connect(self.on_animate_scale)
        #self.animate_phase_radio.clicked.connect(self.on_animate_phase)
        #self.animate_time_radio.clicked.connect(self.on_animate_time)
        self.animation_type_edit.currentIndexChanged.connect(self.on_animate)
        #self.animate_freq_sweeep_radio

        #self.apply_button.clicked.connect(self.on_apply)
        #self.ok_button.clicked.connect(self.on_ok)
        self.cancel_button.clicked.connect(self.on_cancel)

        self.animate_in_gui_checkbox.clicked.connect(self.on_animate_in_gui)
        self.animate_in_gui_checkbox.setChecked(True)
        self.on_animate_in_gui()

    def on_animate_in_gui(self):
        animate_in_gui = self.animate_in_gui_checkbox.isChecked()
        enable = not animate_in_gui
        self.make_images_checkbox.setEnabled(enable)
        self.delete_images_checkbox.setEnabled(enable)
        self.make_gif_checkbox.setEnabled(enable)
        self.repeat_checkbox.setEnabled(enable)
        self.resolution_button.setEnabled(enable)
        self.resolution_edit.setEnabled(enable)
        self.gif_edit.setEnabled(enable)
        self.gif_button.setEnabled(enable)
        self.browse_folder_button.setEnabled(enable)
        self.browse_folder_edit.setEnabled(enable)
        self.step_button.setEnabled(enable)

    def on_animate(self, value):
        """
        animate pulldown

        Parameters
        ----------
        value : int
            index in animation_types
        """
        #animation_types = ['Animate Scale', 'Animate Phase', 'Animate Time',
        #'Animate Frequency Sweep']
        animation_type = self.animation_types[value]
        if animation_type == 'Animate Scale':
            self.on_animate_scale()
        elif animation_type == 'Animate Phase':
            self.on_animate_phase()
        elif animation_type == 'Animate Time':
            self.on_animate_time()
        else:
            raise NotImplementedError('value = ', value)

    def on_animate_time(self, force=False):
        """enables the secondary input"""
        #print('on_animate_time')
        if self._animate_type == 'scale' or force:
            self.set_grid_scale(False, 'time')
        self.set_grid_time(True, 'time')
        self._animate_type = 'time'

    def on_animate_scale(self, force=False):
        """enables the secondary input"""
        #print('on_animate_scale')
        self.set_grid_scale(True, 'scale')
        if self._animate_type == 'time' or force:
            self.set_grid_time(False, 'scale')
        self._animate_type = 'scale'

    def on_animate_phase(self, force=False):
        """enables the secondary input"""
        #print('on_animate_phase')
        if self._animate_type == 'scale' or force:
            self.set_grid_scale(False, 'phase')
        if self._animate_type == 'time' or force:
            self.set_grid_time(False, 'phase')
        self._animate_type = 'phase'

    def set_grid_scale(self, enabled=True, word=''):
        """enables/disables the secondary input"""
        #print('%s-set_grid_scale; enabled = %r' % (word, enabled))
        self.animation_profile.setEnabled(enabled)
        self.animation_profile_edit.setEnabled(enabled)

        # TODO: doesn't work...
        #self.csv_profile.setEnabled(enabled)
        #self.csv_profile_edit.setEnabled(enabled)
        #self.csv_profile_button.setEnabled(enabled)

    def set_grid_time(self, enabled=True, word=''):
        """enables/disables the secondary input"""
        #print('%s-set_grid_time; enabled = %r' % (word, enabled))
        self.icase_start.setEnabled(enabled)
        self.icase_start_edit.setEnabled(enabled)
        self.icase_start_button.setEnabled(enabled)

        self.icase_end.setEnabled(enabled)
        self.icase_end_edit.setEnabled(enabled)
        self.icase_end_button.setEnabled(enabled)

        self.icase_delta.setEnabled(enabled)
        self.icase_delta_edit.setEnabled(enabled)
        self.icase_delta_button.setEnabled(enabled)

        self.min_value.setEnabled(enabled)
        self.min_value_edit.setEnabled(enabled)
        self.min_value_button.setEnabled(enabled)

        self.max_value.setEnabled(enabled)
        self.max_value_edit.setEnabled(enabled)
        self.max_value_button.setEnabled(enabled)

        self.icase.setEnabled(not enabled)
        self.icase_edit.setEnabled(not enabled)
        self.fps.setEnabled(not enabled)
        self.fps_edit.setEnabled(not enabled)
        self.fps_button.setEnabled(not enabled)

    def on_browse_folder(self):
        """opens a folder dialog"""
        dirname = open_directory_dialog(self, 'Select a Directory')
        if not dirname:
            return
        self.browse_folder_edit.setText(dirname)

    def on_browse_csv(self):
        """opens a file dialog"""
        default_filename = ''
        file_types = 'Delimited Text (*.txt; *.dat; *.csv)'
        dirname = open_file_dialog(self, 'Select a CSV File', default_filename,
                                   file_types)
        if not dirname:
            return
        self.csv_profile_browse_button.setText(dirname)

    def on_default_name(self):
        """sets the default gif name"""
        self.gif_edit.setText(self._default_name + '.gif')

    def on_default_scale(self):
        """sets the default displacement scale factor"""
        self.scale_edit.setText(str(self._default_scale))
        self.scale_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_time(self):
        """sets the default gif time"""
        self.time_edit.setValue(self._default_time)

    def on_default_fps(self):
        """sets the default FPS"""
        self.fps_edit.setValue(self._default_fps)

    def on_default_resolution(self):
        """sets the default image resolution scale factor"""
        self.resolution_edit.setValue(self._default_resolution)

    def create_layout(self):
        """displays the menu objects"""
        grid = QGridLayout()

        grid.addWidget(self.icase, 0, 0)
        grid.addWidget(self.icase_edit, 0, 1)

        grid.addWidget(self.scale, 1, 0)
        grid.addWidget(self.scale_edit, 1, 1)
        grid.addWidget(self.scale_button, 1, 2)

        grid.addWidget(self.time, 2, 0)
        grid.addWidget(self.time_edit, 2, 1)
        grid.addWidget(self.time_button, 2, 2)

        # spacer
        spacer = QLabel('')

        grid.addWidget(self.fps, 3, 0)
        grid.addWidget(self.fps_edit, 3, 1)
        grid.addWidget(self.fps_button, 3, 2)

        grid.addWidget(self.resolution, 4, 0)
        grid.addWidget(self.resolution_edit, 4, 1)
        grid.addWidget(self.resolution_button, 4, 2)

        grid.addWidget(self.browse_folder, 5, 0)
        grid.addWidget(self.browse_folder_edit, 5, 1)
        grid.addWidget(self.browse_folder_button, 5, 2)

        grid.addWidget(self.gif, 6, 0)
        grid.addWidget(self.gif_edit, 6, 1)
        grid.addWidget(self.gif_button, 6, 2)

        grid.addWidget(self.animation_type, 7, 0)
        grid.addWidget(self.animation_type_edit, 7, 1)

        grid.addWidget(spacer, 8, 0)

        #----------
        #Time
        grid_time = QGridLayout()
        grid_time.addWidget(self.icase_start, 0, 0)
        grid_time.addWidget(self.icase_start_edit, 0, 1)
        #grid_time.addWidget(self.icase_start_button, 0, 2)

        grid_time.addWidget(self.icase_end, 1, 0)
        grid_time.addWidget(self.icase_end_edit, 1, 1)
        #grid_time.addWidget(self.icase_end_button, 1, 2)

        grid_time.addWidget(self.icase_delta, 2, 0)
        grid_time.addWidget(self.icase_delta_edit, 2, 1)
        #grid_time.addWidget(self.icase_delta_button, 2, 2)

        #grid_time.addWidget(self.min_value, 3, 0)
        #grid_time.addWidget(self.min_value_edit, 3, 1)
        #grid_time.addWidget(self.min_value_button, 3, 2)

        #grid_time.addWidget(self.max_value, 4, 0)
        #grid_time.addWidget(self.max_value_edit, 4, 1)
        #grid_time.addWidget(self.max_value_button, 4, 2)
        grid_time.addWidget(spacer, 5, 0)

        #--------------
        grid_scale = QGridLayout()
        grid_scale.addWidget(self.animation_profile, 0, 0)
        grid_scale.addWidget(self.animation_profile_edit, 0, 1)

        #grid_scale.addWidget(self.csv_profile, 1, 0)
        #grid_scale.addWidget(self.csv_profile_edit, 1, 1)
        #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2)

        self.csv_profile = QLabel("CSV profile:")
        self.csv_profile_edit = QLineEdit()
        self.csv_profile_button = QPushButton('Browse')

        #box_time = QVBoxLayout()
        # TODO: It's super annoying that the animate time box doesn't
        #       line up with the previous box
        box_scale = QGroupBox('Animate Scale')
        box_scale.setLayout(grid_scale)

        box_time = QGroupBox('Animate Time')
        box_time.setLayout(grid_time)
        #----------

        grid2 = QGridLayout()
        #grid2.addWidget(self.animate_scale_radio, 8, 0)
        #grid2.addWidget(self.animate_phase_radio, 8, 1)
        #grid2.addWidget(self.animate_time_radio, 8, 2)
        #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3)

        grid2.addWidget(self.animate_in_gui_checkbox, 10, 0)
        grid2.addWidget(self.make_images_checkbox, 11, 0)
        #grid2.addWidget(self.overwrite_images_checkbox, 11, 0)
        grid2.addWidget(self.delete_images_checkbox, 11, 1)
        grid2.addWidget(self.make_gif_checkbox, 11, 2)
        grid2.addWidget(self.repeat_checkbox, 12, 0)

        grid2.addWidget(spacer, 13, 0)
        grid_hbox = QHBoxLayout()
        grid_hbox.addWidget(spacer)
        grid_hbox.addLayout(grid2)
        grid_hbox.addWidget(spacer)

        # bottom buttons
        step_run_box = QHBoxLayout()
        step_run_box.addWidget(self.step_button)
        step_run_box.addWidget(self.stop_button)
        step_run_box.addWidget(self.run_button)

        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.cancel_button)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addWidget(box_scale)
        vbox.addWidget(box_time)
        #vbox.addLayout(checkboxes)
        vbox.addLayout(grid_hbox)
        vbox.addStretch()
        vbox.addLayout(step_run_box)
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def on_step(self):
        """click the Step button"""
        passed, validate_out = self.on_validate()
        if passed:
            try:
                self._make_gif(validate_out, istep=self.istep)
                self.istep += 1
            except IndexError:
                self._make_gif(validate_out, istep=0)
                self.istep += 1

    def on_stop(self):
        passed, validate_out = self.on_validate()
        if passed:
            self._make_gif(validate_out, stop_animation=True)

    def on_run(self):
        """click the Run button"""
        self.istep = 0
        passed, validate_out = self.on_validate()
        if passed:
            self._make_gif(validate_out, istep=None)
        return passed

    def _make_gif(self, validate_out, istep=None, stop_animation=False):
        """interface for making the gif"""
        icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase = validate_out

        gif_filename = None
        if not stop_animation and not animate_in_gui:
            if gifbase.lower().endswith('.gif'):
                gifbase = gifbase[:-4]
            gif_filename = os.path.join(output_dir, gifbase + '.gif')

        animate_scale = self.animate_scale_radio.isChecked()
        animate_phase = self.animate_phase_radio.isChecked()
        animate_time = self.animate_time_radio.isChecked()

        animate_scale = False
        animate_phase = False
        animate_time = False
        if self._animate_type == 'scale':
            animate_scale = True
        elif self._animate_type == 'phase':
            animate_phase = True
        elif self._animate_type == 'time':
            animate_time = True
        else:
            raise NotImplementedError(self._animate_type)

        make_images = self.make_images_checkbox.isChecked()
        delete_images = self.delete_images_checkbox.isChecked()
        make_gif = self.make_gif_checkbox.isChecked()
        key = str(self.animation_profile_edit.currentText())
        #profile = ANIMATION_PROFILES[key]

        #ANIMATION_PROFILES['0 to Scale'] = [0., 1.]
        #ANIMATION_PROFILES['0 to Scale to 0'] = [0., 1., 0.]
        if key == '0 to Scale':
            onesided = True
        else:
            onesided = False

        icase_start = self.icase_start_edit.value()
        icase_end = self.icase_end_edit.value()
        icase_delta = self.icase_delta_edit.value()

        #onesided = self.onesided_radio.isChecked()
        bool_repeat = self.repeat_checkbox.isChecked(
        )  # TODO: change this to an integer
        if bool_repeat:
            nrepeat = 0
        else:
            nrepeat = 1
        #self.out_data['is_shown'] = self.show_radio.isChecked()
        #icase = self._icase
        if self.is_gui:
            self.win_parent.win_parent.make_gif(
                gif_filename,
                scale,
                istep=istep,
                animate_scale=animate_scale,
                animate_phase=animate_phase,
                animate_time=animate_time,
                icase=icase,
                icase_start=icase_start,
                icase_end=icase_end,
                icase_delta=icase_delta,
                time=time,
                onesided=onesided,
                nrepeat=nrepeat,
                fps=fps,
                magnify=magnify,
                make_images=make_images,
                delete_images=delete_images,
                make_gif=make_gif,
                stop_animation=stop_animation,
                animate_in_gui=animate_in_gui,
            )

        self.out_data['clicked_ok'] = True
        self.out_data['close'] = True

    def on_validate(self):
        """checks to see if the input is valid"""
        icase, flag0 = self.check_int(self.icase_edit)
        scale, flag1 = self.check_float(self.scale_edit)
        time, flag2 = self.check_float(self.time_edit)
        fps, flag3 = self.check_float(self.fps_edit)
        animate_in_gui = self.animate_in_gui_checkbox.isChecked()

        if animate_in_gui:
            passed = all([flag0, flag1, flag2, flag3])
            return passed, (icase, scale, time, fps, animate_in_gui, None,
                            None, None)

        magnify, flag4 = self.check_int(self.resolution_edit)
        output_dir, flag5 = self.check_path(self.browse_folder_edit)
        gifbase, flag6 = self.check_name(self.gif_edit)
        passed = all([flag0, flag1, flag2, flag3, flag4, flag5, flag6])
        return passed, (icase, scale, time, fps, animate_in_gui, magnify,
                        output_dir, gifbase)

    @staticmethod
    def check_name(cell):
        """verifies that the data is string-able"""
        cell_value = cell.text()
        try:
            text = str(cell_value).strip()
        except UnicodeEncodeError:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

        if len(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    def check_path(self, cell):
        """verifies that the path exists"""
        text, passed = self.check_name(cell)
        if not passed:
            return None, False

        if os.path.exists(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    #def on_ok(self):
    #"""click the OK button"""
    #passed = self.on_apply()
    #if passed:
    #self.win_parent._animation_window_shown = False
    #self.close()
    ##self.destroy()

    def on_cancel(self):
        """click the Cancel button"""
        self.on_stop()
        self.out_data['close'] = True
        self.close()
Beispiel #22
0
    def __init__(self, student, term, parent=None):
        super(TermPayDialog, self).__init__(parent)
        #term data
        self.term = term
        terms = self.pullOnes('terms', self.term)
        session = self.pullOnes('session', terms['sessionID'])
        self.termname = str(
            session['name']) + ' ' + terms['name'] + ' Term Report'
        self.pagetitle = self.termname

        #student data
        self.student = student
        st = self.pullStudent(self.student)
        fullname = str(st['surname'] + ' ' + st['firstname'] + ' ' +
                       st['othername']).title()
        schno = st['schno']
        db_class = 'student_class' + str(self.term)
        student_clasz = self.pullOne(db_class, {'studentID': self.student})

        clasz = self.pullOne('datas', {'id': student_clasz['classID']})
        self.clasz = clasz['subID']
        armz = self.pullOne('datas', {'id': clasz['subID']})
        classname = armz['abbrv'] + ' ' + clasz['abbrv']
        #pull all CA

        fullNameText = QLabel(fullname)
        schnoText = QLabel(schno)
        classText = QLabel(classname)

        topLay = QGridLayout()
        topLay.addWidget(fullNameText, 0, 0)
        topLay.addWidget(schnoText, 1, 0)
        topLay.addWidget(classText, 2, 0)

        groupBox = QGroupBox('Current Payment')
        groupBox.setLayout(topLay)

        payAmountText = QLabel('Amount')
        self.payBalanceText = QLabel('Balance')
        self.payBalanceAmount = QLabel('0.0')
        self.payAmount = QLineEdit()
        self.payAmount.setObjectName("pay")
        self.payAmount.setPlaceholderText("000.00")
        payText = QLabel('Select Account')
        self.payMethod = QComboBox()
        accounts = self.pullAccount()
        self.holdaccount = {}
        i = 0
        for h in accounts:
            tex = str(h['name']).upper()
            self.payMethod.addItem(tex)
            self.holdaccount[i] = h['id']

        payDateText = QLabel('Balance')
        self.payDate = QDateEdit()
        self.payDate.setDateTime(QDateTime.currentDateTime())
        self.payDate.setCalendarPopup(True)
        tellerText = QLabel('Teller/Receipt No.')
        self.teller = QLineEdit()
        self.teller.setObjectName("teller")
        self.teller.textChanged.connect(self.pullTeller)
        self.teller.setPlaceholderText("0000000")

        self.hw = QGridLayout()
        self.hw.addWidget(payAmountText, 0, 0)
        self.hw.addWidget(self.payAmount, 0, 1)
        self.hw.addWidget(tellerText, 0, 2)
        self.hw.addWidget(self.teller, 0, 3)
        self.hw.addWidget(payText, 1, 0)
        self.hw.addWidget(self.payMethod, 1, 1)
        self.hw.addWidget(payDateText, 1, 2)
        self.hw.addWidget(self.payDate, 1, 3)

        head_col1 = QLabel('ITEM')
        head_col2 = QLabel('AMOUNT')
        head_col3 = QLabel('FULL PAY')
        head_col4 = QLabel('PART PAY')
        head_col5 = QLabel('BALANCE')

        layout1 = QGridLayout()
        layout1.addWidget(head_col1, 0, 0)
        layout1.addWidget(head_col2, 0, 1)
        layout1.addWidget(head_col3, 0, 2)
        layout1.addWidget(head_col4, 0, 3)
        layout1.addWidget(head_col5, 0, 4)

        arr = self.pullFees()
        feex = arr[1]
        payx = arr[2]

        normal_pay = []
        full_pay = []
        part_pay = []
        bal_pay = []
        ko = 1

        self.holdval = []
        self.holdfee = {}
        self.holdtextfee = {}
        self.holdtextfeeperm = {}
        self.holdpaid = {}
        self.holdcpaid = {}
        self.holdtextpaid = {}
        self.holdpayments = {}
        self.holdtextbal = {}
        self.holdbal = {}

        for val in arr[0]:
            paid = False
            s_normal_pay = []
            s_full_pay = []
            s_part_pay = []
            self.holdval.append(val)
            mz = self.pullOne('datas', {'id': val})
            self.num = val
            self.d = QLabel('Text')
            self.d.setText(str(mz['name']).upper())
            self.d1 = QLabel()
            if val in feex:
                fk = feex[int(val)].values()
                normal_pay.append(float(fk[0]))
                s_normal_pay.append(float(fk[0]))
                self.d1.setText(str("{:,}".format(float(fk[0]))).upper())
            else:
                self.d1.setText(str('-.-').upper())

            nHbo1 = QVBoxLayout()
            if val in feex:
                fk = feex[int(val)].values()
                fky = feex[int(val)].keys()
                self.c = QCheckBox('cb' + str(val))
                self.c.setEnabled(False)
                self.c.setText(str("{:,}".format(float(fk[0]))).upper())
                self.c.setObjectName("chk" + str(val))
                self.holdfee[int(val)] = self.c
                self.holdtextfee[int(val)] = fk[0]
                self.holdtextfeeperm[int(val)] = fk[0]
                self.c.toggled.connect(lambda state, x=fky[0], fee=int(
                    val), money=fk[0]: self.chkFunc(x, fee, money, self.c))
                if (val in payx) and len(payx[int(val)]) == 1:
                    pk = payx[int(val)].values()
                    self.c.setChecked(True)
                    if float(pk[0]) == float(fk[0]):
                        full_pay.append(float(fk[0]))
                        s_full_pay.append(float(fk[0]))
                        paid = True
                else:
                    self.c.setChecked(False)
                nHbo1.addWidget(self.c)
            else:
                nHbo1.addWidget(QLabel('-.-'))
                #nHbo1.hide()

            nHbo2 = QHBoxLayout()
            fk = feex[int(val)].values()
            fky = feex[int(val)].keys()
            c2 = QCheckBox()
            c2.setEnabled(False)
            c2.setMaximumWidth(15)
            c2.setObjectName("chk2" + str(val))
            p = QLineEdit()
            p.setDisabled(True)
            p.setMaximumWidth(50)
            p.setFixedWidth(51)
            p.setObjectName("pay" + str(val))
            p.setPlaceholderText("00.0")
            self.holdpaid[int(val)] = p
            self.holdcpaid[int(val)] = c2
            self.holdtextpaid[int(val)] = list()
            c2.toggled.connect(
                lambda state, x=fky[0], fee=int(val): self.chkFunc1(x, fee, p))
            if paid == False:
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)
                if val in payx and len(payx[val]) > 0:
                    for j in payx[int(val)]:
                        self.c1 = QCheckBox('cb1' + str(j))
                        self.c1.setEnabled(False)
                        self.c1.setText(str(payx[int(val)][j]).upper())
                        self.c1.setObjectName("chk" + str(j))
                        self.c1.toggled.connect(
                            lambda state, x=j: self.chkFunc1(x))
                        self.c1.setChecked(True)
                        part_pay.append(float(fk[0]))
                        s_part_pay.append(float(fk[0]))
                        self.holdpayments[j] = self.c1
                        self.holdtextpaid[val].append(float(fk[0]))
                        nHbo2.addWidget(self.c1)
                else:
                    pass
            else:
                p.hide()
                c2.hide()
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)

            s_tot = sum(s_normal_pay) - (sum(s_full_pay) + sum(s_part_pay))
            bal_pay.append(float(s_tot))
            d2 = QLabel('')
            self.holdbal[int(val)] = d2
            d2.setText(str("{:,}".format(s_tot)).upper())
            self.holdtextbal[int(val)] = s_tot

            layout1.addWidget(self.d, ko, 0)
            layout1.addWidget(self.d1, ko, 1)
            layout1.addLayout(nHbo1, ko, 2)
            layout1.addLayout(nHbo2, ko, 3)
            layout1.addWidget(d2, ko, 4)
            ko += 1

        normal_payx = sum(normal_pay)
        full_payx = sum(full_pay)
        part_payx = sum(part_pay)
        bal_payx = sum(bal_pay)

        self.head_col1 = QLabel('ITEM')
        self.head_col2 = QLabel(str("{:,}".format(normal_payx)).upper())
        self.head_col3 = QLabel(str("{:,}".format(full_payx)).upper())
        self.head_col4 = QLabel(str("{:,}".format(part_payx)).upper())
        self.head_col5 = QLabel(str("{:,}".format(bal_payx)).upper())

        layout1.addWidget(self.head_col1, ko, 0)
        layout1.addWidget(self.head_col2, ko, 1)
        layout1.addWidget(self.head_col3, ko, 2)
        layout1.addWidget(self.head_col4, ko, 3)
        layout1.addWidget(self.head_col5, ko, 4)

        self.hw1 = QGridLayout()
        self.hw1.addWidget(self.payBalanceText, 0, 0)
        self.hw1.addWidget(self.payBalanceAmount, 1, 0)

        second1 = QGridLayout()
        second1.addLayout(self.hw, 0, 0)
        second1.addLayout(layout1, 1, 0)
        second1.addLayout(self.hw1, 2, 0)

        groupBox1 = QGroupBox('Current Payment')
        groupBox1.setLayout(second1)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Fees")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Add")
        self.pb2.setText("Print Receipts")

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb1)
        hbo.addStretch()
        hbo.addWidget(self.pb)
        hbo.addStretch()
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('')
        groupBox2.setLayout(hbo)

        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        grid.addWidget(groupBox1, 1, 0)
        grid.addWidget(groupBox2, 2, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))

        self.setWindowTitle(self.pagetitle)
class MainWindow(QWidget):
    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(500, 300)

        self.mainLayout = QHBoxLayout()
        self.chooseLayout = QHBoxLayout()
        self.continuousLayout = QHBoxLayout()
        self.layout = QVBoxLayout()
        self.pixLayout = QHBoxLayout()
        self.thresholdLayout = QHBoxLayout()
        self.timeLayout = QHBoxLayout()
        self.contoursLayout = QHBoxLayout()
        self.setLayout(self.mainLayout)
        self.setWindowTitle(
            "Image To Gcode V1.0 ----- build By yizheneng [email protected]")

        self.imageLabel = QLabel("image")

        self.mainLayout.addWidget(self.imageLabel)
        self.mainLayout.addLayout(self.layout)
        self.mainLayout.setStretchFactor(self.layout, 1)
        self.mainLayout.setStretchFactor(self.imageLabel, 3)

        self.pixLengthLabel = QLabel(u"像素大小(mm):")
        self.pixDoubleSpinBox = QDoubleSpinBox()
        self.pixDoubleSpinBox.setValue(1)
        self.pixDoubleSpinBox.setDecimals(6)
        self.pixLayout.addWidget(self.pixLengthLabel)
        self.pixLayout.addWidget(self.pixDoubleSpinBox)

        self.thresholdLabel = QLabel(u"阈值:")
        self.thresholdSpinBox = QSpinBox()
        self.thresholdSpinBox.valueChanged.connect(self.ThresholdValChange)
        self.thresholdSpinBox.setMaximum(255)
        self.thresholdSpinBox.setValue(120)
        self.thresholdLayout.addWidget(self.thresholdLabel)
        self.thresholdLayout.addWidget(self.thresholdSpinBox)

        self.timeLabel = QLabel(u"灼烧时间:")
        self.timeDoubleSpinBox = QDoubleSpinBox()
        self.timeDoubleSpinBox.setValue(0.3)
        self.timeLayout.addWidget(self.timeLabel)
        self.timeLayout.addWidget(self.timeDoubleSpinBox)

        self.chooseLabel = QLabel(u"只雕刻轮廓:")
        self.chooseBox = QCheckBox()
        self.chooseLayout.addWidget(self.chooseLabel)
        self.chooseLayout.addWidget(self.chooseBox)
        self.chooseBox.stateChanged.connect(self.ChooseValChanged)

        self.continuousLabel = QLabel(u"连续雕刻:")
        self.continuousBox = QCheckBox()
        self.continuousBox.setEnabled(False)
        self.continuousBox.stateChanged.connect(self.ChooseValChanged)
        self.continuousLayout.addWidget(self.continuousLabel)
        self.continuousLayout.addWidget(self.continuousBox)

        self.contoursWidthLabel = QLabel(u"边框宽度")
        self.ContoursWidthSpinBox = QSpinBox()
        self.ContoursWidthSpinBox.setEnabled(False)
        self.ContoursWidthSpinBox.setValue(1)
        self.contoursLayout.addWidget(self.contoursWidthLabel)
        self.contoursLayout.addWidget(self.ContoursWidthSpinBox)

        self.loadImageButton = QPushButton(u"加载图片")
        self.loadImageButton.clicked.connect(self.LoadImageButtonClicked)
        self.previewButton = QPushButton(u"预览")
        self.previewButton.clicked.connect(self.ThresholdValChange)
        self.makeCodeButton = QPushButton(u"生成G代码")
        self.makeCodeButton.clicked.connect(self.MakeGcode)

        self.layout.addLayout(self.pixLayout)
        self.layout.addLayout(self.thresholdLayout)
        self.layout.addLayout(self.timeLayout)
        self.layout.addLayout(self.chooseLayout)
        self.layout.addLayout(self.continuousLayout)
        self.layout.addLayout(self.contoursLayout)
        self.layout.addWidget(self.loadImageButton)
        self.layout.addWidget(self.previewButton)
        self.layout.addWidget(self.makeCodeButton)

    def LoadImageButtonClicked(self):
        self.filePath = QFileDialog.getOpenFileName(self, u"选择图片文件", "",
                                                    "Images (*.bmp)")
        if self.filePath == "":
            QMessageBox.warning(self, u"发生错误", u"没有选择可以识别的文件!!")
            return

        self.srcImage = QImage(self.filePath)
        self.grayImage = QImage(self.srcImage.size(), QImage.Format_Indexed8)

        for i in range(256):
            self.grayImage.setColor(i, qRgb(i, i, i))

        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = qGray(self.srcImage.pixel(i, j))
                self.grayImage.setPixel(i, j, temp)

        self.srcImage = QImage(self.grayImage)
        self.resultImage = QImage(self.grayImage)
        self.imageLabel.setPixmap(QPixmap(self.srcImage))

    def ChooseValChanged(self):
        self.continuousBox.setEnabled(self.chooseBox.isChecked())
        self.ContoursWidthSpinBox.setEnabled(
            (self.chooseBox.isChecked())
            and (not self.continuousBox.isChecked()))

    def ThresholdValChange(self):
        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = self.srcImage.pixelIndex(i, j)
                if (temp >= self.thresholdSpinBox.value()):
                    self.grayImage.setPixel(i, j, 255)
                else:
                    self.grayImage.setPixel(i, j, 0)
        self.resultImage = QImage(self.grayImage)
        #如果选中了只雕刻轮廓
        if self.chooseBox.isChecked():
            img = np.zeros(
                (self.grayImage.height(), self.grayImage.width(), 1), np.uint8)
            for i in range(self.grayImage.width()):
                for j in range(self.grayImage.height()):
                    img[j, i] = self.grayImage.pixelIndex(i, j)
            #提取轮廓
            contours = cv.findContours(img, cv.RETR_LIST,
                                       cv.CHAIN_APPROX_SIMPLE)
            img = np.zeros(
                (self.grayImage.height(), self.grayImage.width(), 1), np.uint8)
            cv.drawContours(img, contours[1][:-1], -1, (255, 255, 255),
                            self.ContoursWidthSpinBox.value())
            self.contours = contours[1][:-1]
            #转换轮廓到显示界面
            for i in range(self.resultImage.width()):
                for j in range(self.resultImage.height()):
                    if img[j, i] == 0:
                        self.resultImage.setPixel(i, j, 255)
                    else:
                        self.resultImage.setPixel(i, j, 0)

        self.imageLabel.setPixmap(QPixmap(self.resultImage))

    def MakeGcode(self):
        path = QFileDialog.getSaveFileName(self, u"选择保存路径", "", " (*.nc)")
        if path == "":
            QMessageBox.warning(self, u"发生错误", u"路径错误!!")
            return

        f = open(path, 'w')
        f.write("M5\n")

        if self.continuousBox.isChecked() and self.chooseBox.isChecked():
            for contour in self.contours:
                f.write("G0 X%f Y%f\n" %
                        ((contour[0][0][0] * self.pixDoubleSpinBox.value()),
                         (contour[0][0][1] * self.pixDoubleSpinBox.value())))
                f.write("M3\n")
                for con in contour:
                    f.write("G0 X%f Y%f\n" %
                            ((con[0][0] * self.pixDoubleSpinBox.value()),
                             (con[0][1] * self.pixDoubleSpinBox.value())))

                f.write("G0 X%f Y%f\n" %
                        ((contour[0][0][0] * self.pixDoubleSpinBox.value()),
                         (contour[0][0][1] * self.pixDoubleSpinBox.value())))
                f.write("M5\n")
        else:
            for i in range(self.resultImage.width()):
                flag = False
                #检测这一行是否有点
                for j in range(self.resultImage.height()):
                    if self.resultImage.pixelIndex(i, j) < 128:
                        flag = True
                        break
                #如果这一行都没有点则跳过这一行
                if flag:
                    f.write("G0 Y%f\n" % (i * self.pixDoubleSpinBox.value()))
                else:
                    continue

                if (i % 2) > 0:
                    for j in range(self.resultImage.height()):
                        if self.resultImage.pixelIndex(i, j) < 128:
                            f.write("G0 X%f\n" %
                                    (j * self.pixDoubleSpinBox.value()))
                            f.write("M3\n")
                            f.write("G4 P%f\n" %
                                    self.timeDoubleSpinBox.value())
                            f.write("M5\n")
                else:
                    for j in range(self.resultImage.height())[::-1]:
                        if self.resultImage.pixelIndex(i, j) < 128:
                            f.write("G0 X%f\n" %
                                    (j * self.pixDoubleSpinBox.value()))
                            f.write("M3\n")
                            f.write("G4 P%f\n" %
                                    self.timeDoubleSpinBox.value())
                            f.write("M5\n")

        f.write("M5\n")
        f.write("G0 X0 Y0\n")
        f.close()
        QMessageBox.information(self, u"成功", u"生成G代码文件成功!!")
class GithubRepoWizardPage(QWizardPage):
    def __init__(self, github, parent=None):
        super(GithubRepoWizardPage, self).__init__(
            parent,
            title="Github Repository",
            subTitle="Configure the new Github repository")
        
        self.github = github
        
        # moreButton

        self.moreButton = QPushButton(
                "More",
                checkable=True,
                clicked=self.more)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        moreButtonHBox = QHBoxLayout()
        moreButtonHBox.addWidget(spacer)
        moreButtonHBox.addWidget(self.moreButton)

        #  LineEdits

        self.nameEdit = QLineEdit(textChanged=self.update)
        self.nameEdit.setValidator(QRegExpValidator(
                QRegExp(r'[a-zA-Z0-9-_]+[a-zA-Z0-9-_]*')))
        self.descriptionEdit = QLineEdit(textChanged=self.update)
        self.homepageEdit = QLineEdit(textChanged=self.update)
        
        # CheckBox

        self.privateCheckBox = QCheckBox(stateChanged=self.update)
        self.initCheckBox = QCheckBox(stateChanged=self.update)
        self.hasWikiCheckBox = QCheckBox(stateChanged=self.update)
        self.hasDownloadsCheckBox = QCheckBox(stateChanged=self.update)
        self.hasIssuesCheckBox = QCheckBox(stateChanged=self.update)
        
        # gitignoreComboBox

        self.gitignoreComboBox = QComboBox(currentIndexChanged=self.update)
        self.gitignoreComboBox.addItem('None')
        for i in gitignore_types(self.github):
            self.gitignoreComboBox.addItem(i)
            
        hbox2 = QHBoxLayout()
        hbox2.addWidget(QLabel(
            'Initialize this repository with a README and .gitignore'))
        hbox2.addWidget(self.initCheckBox)
        
        # Extension Form

        self.form_extension = QFormLayout()
        self.form_extension.addRow("Homepage", self.homepageEdit)  
        self.form_extension.addRow("Has wiki", self.hasWikiCheckBox)
        self.form_extension.addRow("Has issues", self.hasIssuesCheckBox)
        self.form_extension.addRow("Has downloads", self.hasDownloadsCheckBox)

        # Extension

        self.extension = QWidget()
        self.extension.setLayout(self.form_extension)

        # Form

        self.form = QFormLayout()
        self.form.addRow("Name: ", self.nameEdit)
        self.form.addRow("Description: ", self.descriptionEdit)
        self.form.addRow('Private', self.privateCheckBox)
        self.form.addRow(hbox2)
        self.form.addRow('Add .gitignore', self.gitignoreComboBox)
        self.form.addRow(moreButtonHBox)
        self.form.addRow(self.extension)
        
        # Layout

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.form)
        self.setLayout(self.mainLayout)
    
        # Fields

        self.registerField('name*', self.nameEdit)
        self.registerField('description', self.descriptionEdit)
        self.registerField('private', self.privateCheckBox)
        self.registerField('auto_init', self.initCheckBox)
        self.registerField('gitignore', self.gitignoreComboBox, 'currentText')
        self.registerField('homepage', self.homepageEdit)
        self.registerField('has_issues', self.hasIssuesCheckBox)
        self.registerField('has_downloads', self.hasDownloadsCheckBox)
        self.registerField('has_wiki', self.hasWikiCheckBox)
        
        # Setup

        self.hasWikiCheckBox.toggle()
        self.hasDownloadsCheckBox.toggle()
        self.hasIssuesCheckBox.toggle()
        if not self.github.get_user().plan:
            self.privateCheckBox.setEnabled(False)
        
        self.extension.hide()

    def update(self):

        if self.initCheckBox.isChecked():
            self.gitignoreComboBox.setEnabled(True)
        else:
            self.gitignoreComboBox.setEnabled(False)

    def more(self):
            
        if self.moreButton.isChecked():
            self.moreButton.setText("Less")
            self.extension.show()
            self.wizard().resize(self.wizard().sizeHint())
        else:
            self.moreButton.setText("More")
            self.extension.hide()
            size = self.sizeHint()
            wizard_size = self.wizard().sizeHint()
            self.wizard().resize(wizard_size.width(), size.height())
Beispiel #25
0
class CompletionSection(QWidget):

    def __init__(self):
        super(CompletionSection, self).__init__()
        EditorConfiguration.install_widget(self.tr("Autocompletado"), self)
        container = QVBoxLayout(self)

        group_complete = QGroupBox(self.tr("Completar:"))
        box = QGridLayout(group_complete)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_bracket = QCheckBox(self.tr("Corchetes []"))
        box.addWidget(self.check_bracket, 0, 0)
        self.check_paren = QCheckBox(self.tr("Paréntesis ()"))
        box.addWidget(self.check_paren, 0, 1)
        self.check_key = QCheckBox(self.tr("Llaves {}"))
        box.addWidget(self.check_key, 1, 0)
        self.check_quote = QCheckBox(self.tr("Comillas Dobles \" \""))
        box.addWidget(self.check_quote, 1, 1)
        self.check_single_quote = QCheckBox(self.tr("Comillas Simples ' '"))
        box.addWidget(self.check_single_quote, 2, 0)

        group_completion = QGroupBox(self.tr("Completado de Código:"))
        box = QGridLayout(group_completion)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_completion = QCheckBox(self.tr("Activar Completado"))
        box.addWidget(self.check_completion, 0, 0)
        self.check_document = QCheckBox(self.tr("Basado en el código"))
        box.addWidget(self.check_document, 0, 1)
        self.check_keywords = QCheckBox(self.tr("Palabras Claves"))
        box.addWidget(self.check_keywords, 1, 0)
        self.check_cs = QCheckBox(
            self.tr("Sensitivo a mayúsculas y minúsculas"))
        box.addWidget(self.check_cs, 1, 1)
        self.check_replace_word = QCheckBox(self.tr("Reemplazar Palabra"))
        box.addWidget(self.check_replace_word, 2, 0)
        self.check_show_single = QCheckBox(self.tr("Mostrar Simple"))
        box.addWidget(self.check_show_single, 2, 1)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(
            self.tr("Número de caractéres para mostrar lista:")))
        self.spin_threshold = QSpinBox()
        self.spin_threshold.setMinimum(1)
        self.spin_threshold.setFixedWidth(100)
        hbox.addWidget(self.spin_threshold)
        box.addLayout(hbox, 3, 0, Qt.AlignLeft)

        # Agrupo al contenedor principal
        container.addWidget(group_complete)
        container.addWidget(group_completion)
        container.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
                          QSizePolicy.Expanding))

        self._state_change(self.check_completion.isChecked())
        # Conexiones
        self.check_completion.stateChanged[int].connect(self._state_change)

        # Configuration
        self.check_key.setChecked(
            settings.get_setting('editor/complete-brace'))
        self.check_bracket.setChecked("[" in settings.BRACES)
        self.check_paren.setChecked("(" in settings.BRACES)
        self.check_quote.setChecked('""' in settings.QUOTES)
            #settings.get_setting('editor/complete-double-quote'))
        self.check_single_quote.setChecked("''" in settings.QUOTES)
            #settings.get_setting('editor/complete-single-quote'))
        self.check_completion.setChecked(
            settings.get_setting('editor/completion'))
        self.spin_threshold.setValue(
            settings.get_setting('editor/completion-threshold'))
        self.check_keywords.setChecked(
            settings.get_setting('editor/completion-keywords'))
        self.check_document.setChecked(
            settings.get_setting('editor/completion-document'))
        self.check_cs.setChecked(
            settings.get_setting('editor/completion-cs'))
        self.check_replace_word.setChecked(
            settings.get_setting('editor/completion-replace-word'))
        self.check_show_single.setChecked(
            settings.get_setting('editor/completion-single'))

    def _state_change(self, value):
        state = bool(value)
        self.check_document.setEnabled(state)
        self.check_keywords.setEnabled(state)
        self.check_cs.setEnabled(state)
        self.check_replace_word.setEnabled(state)
        self.check_show_single.setEnabled(state)
        self.spin_threshold.setEnabled(state)

    def save(self):
        settings.set_setting('editor/complete-brace',
            self.check_key.isChecked())
        settings.set_setting('editor/complete-bracket',
            self.check_bracket.isChecked())
        if self.check_bracket.isChecked():
            settings.BRACES['['] = ']'
        elif ('[') in settings.BRACES:
            del settings.BRACES['[']
        settings.set_setting('editor/complete-paren',
            self.check_paren.isChecked())
        if self.check_paren.isChecked():
            settings.BRACES['('] = ')'
        elif ('(') in settings.BRACES:
            del settings.BRACES['(']
        settings.set_setting('editor/complete-double-quote',
            self.check_quote.isChecked())
        if self.check_quote.isChecked():
            settings.QUOTES.append('""')
        elif '""' in settings.QUOTES:
            settings.QUOTES.remove('""')
        settings.set_setting('editor/complete-single-quote',
            self.check_single_quote.isChecked())
        if self.check_single_quote.isChecked():
            settings.QUOTES.append('""')
        elif "''" in settings.QUOTES:
            settings.QUOTES.remove("''")
        code_completion = self.check_completion.isChecked()
        settings.set_setting('editor/completion',
            code_completion)
        settings.set_setting('editor/completion-threshold',
            self.spin_threshold.value())
        settings.set_setting('editor/completion-keywords',
            self.check_keywords.isChecked())
        settings.set_setting('editor/completion-document',
            self.check_document.isChecked())
        settings.set_setting('editor/completion-cs',
            self.check_cs.isChecked())
        settings.set_setting('editor/completion-replace-word',
            self.check_replace_word.isChecked())
        settings.set_setting('editor/completion-single',
            self.check_show_single.isChecked())
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            editor.active_code_completion(code_completion)
Beispiel #26
0
class ViewDataTools(QMainWindow):
    def __init__(self, parent=None):
        super(ViewDataTools, self).__init__(parent)

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # DATATOOLS WINDOWS:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.setWindowTitle(ui_strings.DATATOOLS_TITLE)
        self._width = 680
        self._height = 560
        self._left_margin = 10
        self.resize(self._width, self._height)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QtCore.QSize(self._width, self._height))
        self.setMaximumSize(QtCore.QSize(self._width, self._height))
        self.setWindowIcon(QIcon(resources.ICON_LOGO))

        # central widget
        self.central_widget = QWidget(self)

        # DataTools description
        self.lbl_description = QLabel(self.central_widget)
        self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30))
        self.lbl_description.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION)

        # group input files
        self.group_input_file = QGroupBox(self.central_widget)
        self.group_input_file.setGeometry(QtCore.QRect(self._left_margin, 30, 660, 80))
        self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT)

        # frame input files
        self.frame_inputs = QFrame(self.group_input_file)
        self.frame_inputs.setGeometry(QtCore.QRect(self._left_margin, 0, 270, 80))
        self.frame_inputs.setFrameShape(QFrame.StyledPanel)
        self.frame_inputs.setFrameShadow(QFrame.Raised)

        # label input type
        self.lbl_input_type = QLabel(self.frame_inputs)
        self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15))
        self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE)

        # button xls
        self.btn_xls = QToolButton(self.frame_inputs)
        self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35))
        icon_xls = QIcon()
        icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal, QIcon.Off)
        self.btn_xls.setIcon(icon_xls)
        self.btn_xls.setIconSize(QtCore.QSize(24, 24))
        self.btn_xls.setCheckable(True)
        self.btn_xls.setAutoExclusive(True)
        self.btn_xls.setObjectName("xls_button")

        # button csv
        self.btn_csv = QToolButton(self.frame_inputs)
        self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35))
        icon_csv = QIcon()
        icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal, QIcon.Off)
        self.btn_csv.setIcon(icon_csv)
        self.btn_csv.setIconSize(QtCore.QSize(24, 24))
        self.btn_csv.setCheckable(True)
        self.btn_csv.setAutoExclusive(True)
        self.btn_csv.setObjectName("csv_button")

        # checkbox csv with headers
        self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS, self.frame_inputs)
        self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15))
        self.chk_csv_headers.setEnabled(False)

        # TextEdit + PushButton (FindFolder)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # lbl sheet name
        self.lbl_file_path = QLabel(self.group_input_file)
        self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15))
        self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE)

        self.txt_file = QLineEdit(self.group_input_file)
        self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20))
        self.txt_file.setReadOnly(True)

        self.btn_path = QPushButton(self.group_input_file)
        self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22))
        self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # lbl sheet name
        self.lbl_sheet_name = QLabel(self.group_input_file)
        self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15))
        self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME)

        # Combobox select sheet - initially does not contain values
        self.cbo_sheet = QComboBox(self.group_input_file)
        self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20))

        # data grid to visualize error messages
        self.tbl_errors = QTableWidget(self.central_widget)
        self.tbl_errors.setGeometry(QtCore.QRect(self._left_margin, 420, 660, 100))

        # data grid to visualize those records with errors.
        self.tbl_uploaded_data = QTableWidget(self.central_widget)
        self.tbl_uploaded_data.setGeometry(QtCore.QRect(self._left_margin, 120, 500, 220))

        # group run options
        self.group_run_options = QGroupBox(self.central_widget)
        self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220))
        self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN)

        # Errors summary:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # group summary errors
        self.group_errors = QGroupBox(self.central_widget)
        self.group_errors.setGeometry(QtCore.QRect(self._left_margin, 350, 660, 60))
        self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS)

        # lbl records
        self.lbl_records = QLabel(self.group_errors)
        self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15))
        self.lbl_records.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS)

        self.txt_records = QLineEdit(self.group_errors)
        self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20))
        self.txt_records.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_records.setReadOnly(True)

        # lbl errors
        self.lbl_errors = QLabel(self.group_errors)
        self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15))
        self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS)

        self.txt_errors = QLineEdit(self.group_errors)
        self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20))
        self.txt_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_errors.setReadOnly(True)

        # lbl time
        self.lbl_time = QLabel(self.group_errors)
        self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15))
        self.lbl_time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_time.setText(ui_strings.DATATOOLS_TIME)

        self.txt_time = QLineEdit(self.group_errors)
        self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20))
        self.txt_time.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_time.setReadOnly(True)

        # history button
        self.btn_history = QToolButton(self.group_errors)
        self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25))
        icon_history = QIcon()
        icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal, QIcon.Off)
        self.btn_history.setIcon(icon_history)
        self.btn_history.setIconSize(QtCore.QSize(20, 20))
        self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.btn_history.setText(ui_strings.DATATOOLS_HISTORY)
        self.btn_history.setCheckable(True)
        self.btn_history.setAutoExclusive(True)
        self.btn_history.setObjectName("history_button")
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # btn data uploader
        self.btn_data_uploader = QPushButton(ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options)
        self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25))
        self.btn_data_uploader.setCheckable(True)
        self.btn_data_uploader.setAutoExclusive(True)
        self.btn_data_uploader.setFlat(False)

        # btn data testing
        self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING, self.group_run_options)
        self.btn_data_testing.setEnabled(False)
        self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25))
        self.btn_data_testing.setCheckable(True)
        self.btn_data_testing.setAutoExclusive(True)

        # btn data to database
        self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB, self.group_run_options)
        self.btn_data_db.setEnabled(False)
        self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23))
        self.btn_data_db.setCheckable(True)
        self.btn_data_db.setAutoExclusive(True)

        # frame run options
        self.frame_run = QFrame(self.group_run_options)
        self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80))
        self.frame_run.setFrameShape(QFrame.StyledPanel)
        self.frame_run.setFrameShadow(QFrame.Raised)

        # option process until first error
        self.rbtn_process_error = QRadioButton(ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run)
        self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20))

        # option process all data
        self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL, self.frame_run)
        self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30))

        # checkbox to filter by records with errors.
        #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run)
        #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15))
        #self.chk_filter_errors.setEnabled(False)

        # icons -> pass - error: Initially are empty labels
        # if not started -> ICON_MINI_WAIT
        # if error -> ICON_DELETE
        # if pass -> ICON_CHECK

        # state icon data uploader
        self.lbl_state_du = QLabel(self.group_run_options)
        self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20))
        self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_du.setScaledContents(True)

        # state icon data to database
        self.lbl_state_dt = QLabel(self.group_run_options)
        self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20))
        self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_dt.setScaledContents(True)

         # state icon data testing
        self.lbl_state_db = QLabel(self.group_run_options)
        self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20))
        self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_db.setScaledContents(True)

        # progress bar
        self.progress_bar = QProgressBar(self.central_widget)
        self.progress_bar.setGeometry(QtCore.QRect(self._left_margin, 530, 660, 15))
        self.progress_bar.setMaximum(100)
        self.progress_bar.setProperty("value", 0)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setOrientation(QtCore.Qt.Horizontal)
        self.progress_bar.setInvertedAppearance(False)
        self.progress_bar.setTextDirection(QProgressBar.TopToBottom)

        self.setCentralWidget(self.central_widget)
Beispiel #27
0
class ExternalPythonShell(ExternalShellBase):
    """External Shell widget: execute Python script in a separate process"""
    SHELL_CLASS = ExtPyQsciShell

    def __init__(self,
                 parent=None,
                 fname=None,
                 wdir=None,
                 commands=[],
                 interact=False,
                 debug=False,
                 path=[]):
        ExternalShellBase.__init__(self,
                                   parent,
                                   wdir,
                                   history_filename='.history_ec.py')

        self.shell.set_externalshell(self)

        self.toggle_globals_explorer(False)
        self.interact_check.setChecked(interact)
        self.debug_check.setChecked(debug)

        self.monitor_socket = None
        self.interpreter = fname is None
        self.fname = startup.__file__ if fname is None else fname

        if self.interpreter:
            self.interact_check.hide()
            self.debug_check.hide()
            self.terminate_button.hide()

        self.commands = ["import sys", "sys.path.insert(0, '')"] + commands

        # Additional python path list
        self.path = path

    def get_toolbar_buttons(self):
        ExternalShellBase.get_toolbar_buttons(self)
        self.globalsexplorer_button = create_toolbutton(
            self,
            get_icon('dictedit.png'),
            self.tr("Variables"),
            tip=self.tr("Show/hide global variables explorer"),
            toggled=self.toggle_globals_explorer)
        self.terminate_button = create_toolbutton(
            self,
            get_icon('terminate.png'),
            self.tr("Terminate"),
            tip=self.tr("Attempts to terminate the process.\n"
                        "The process may not exit as a result of clicking "
                        "this button\n(it is given the chance to prompt "
                        "the user for any unsaved files, etc)."))
        self.interact_check = QCheckBox(self.tr("Interact"), self)
        self.debug_check = QCheckBox(self.tr("Debug"), self)
        return [
            self.interact_check, self.debug_check, self.globalsexplorer_button,
            self.run_button, self.terminate_button, self.kill_button
        ]

    def get_shell_widget(self):
        # Globals explorer
        self.globalsexplorer = GlobalsExplorer(self)
        self.connect(self.globalsexplorer, SIGNAL('collapse()'),
                     lambda: self.toggle_globals_explorer(False))

        # Shell splitter
        self.splitter = splitter = QSplitter(Qt.Vertical, self)
        self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'),
                     self.splitter_moved)
        splitter.addWidget(self.shell)
        splitter.setCollapsible(0, False)
        splitter.addWidget(self.globalsexplorer)
        splitter.setStretchFactor(0, 2)
        splitter.setStretchFactor(1, 1)
        return splitter

    def get_icon(self):
        return get_icon('python.png')

    def set_buttons_runnning_state(self, state):
        ExternalShellBase.set_buttons_runnning_state(self, state)
        self.interact_check.setEnabled(not state)
        self.debug_check.setEnabled(not state)
        self.terminate_button.setEnabled(state)
        if not state:
            self.toggle_globals_explorer(False)
        self.globalsexplorer_button.setEnabled(state)

    def create_process(self):
        self.shell.clear()

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        self.connect(self.shell, SIGNAL("wait_for_ready_read()"),
                     lambda: self.process.waitForReadyRead(250))

        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)

        #-------------------------Python specific-------------------------------
        # Python arguments
        p_args = ['-u']
        if self.interact_check.isChecked():
            p_args.append('-i')
        if self.debug_check.isChecked():
            p_args.extend(['-m', 'pdb'])
        p_args.append(self.fname)

        env = self.process.systemEnvironment()

        # Monitor
        env.append('SHELL_ID=%s' % id(self))
        from spyderlib.widgets.externalshell.monitor import start_server
        server, port = start_server()
        self.notification_thread = server.register(str(id(self)), self)
        self.connect(self.notification_thread, SIGNAL('refresh()'),
                     self.globalsexplorer.refresh_table)
        env.append('SPYDER_PORT=%d' % port)

        # Python init commands (interpreter only)
        if self.commands and self.interpreter:
            env.append('PYTHONINITCOMMANDS=%s' % ';'.join(self.commands))
            self.process.setEnvironment(env)

        pathlist = []

        # Fix encoding with custom "sitecustomize.py"
        scpath = osp.dirname(osp.abspath(__file__))
        pathlist.append(scpath)

        # Adding Spyder path
        pathlist += self.path

        # Adding path list to PYTHONPATH environment variable
        pypath = "PYTHONPATH"
        pathstr = os.pathsep.join(pathlist)
        if os.environ.get(pypath) is not None:
            env.replaceInStrings(pypath + '=',
                                 pypath + '=' + pathstr + os.pathsep,
                                 Qt.CaseSensitive)
        else:
            env.append(pypath + '=' + pathstr)
        self.process.setEnvironment(env)
        #-------------------------Python specific-------------------------------

        if self.arguments:
            p_args.extend(self.arguments.split(' '))

        self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
                     self.write_output)
        self.connect(self.process,
                     SIGNAL("finished(int,QProcess::ExitStatus)"),
                     self.finished)

        self.connect(self.terminate_button, SIGNAL("clicked()"),
                     self.process.terminate)
        self.connect(self.kill_button, SIGNAL("clicked()"), self.process.kill)

        #-------------------------Python specific-------------------------------
        self.process.start(sys.executable, p_args)
        #-------------------------Python specific-------------------------------

        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, self.tr("Error"),
                                 self.tr("Process failed to start"))
        else:
            self.shell.setFocus()
            self.emit(SIGNAL('started()'))

        return self.process

#===============================================================================
#    Input/Output
#===============================================================================

    def _write_error(self, text, findstr):
        pos = text.find(findstr)
        if pos != -1:
            self.shell.write(text[:pos])
            if text.endswith(">>> "):
                self.shell.write_error(text[pos:-5])
                self.shell.write(text[-5:], flush=True)
            else:
                self.shell.write_error(text[pos:])
            return True
        return False

    def write_output(self):
        text = self.get_stdout()
        if not self._write_error(text, 'Traceback (most recent call last):') \
           and not self._write_error(text, 'File "<stdin>", line 1'):
            self.shell.write(text)
        QApplication.processEvents()

    def send_to_process(self, qstr):
        if not isinstance(qstr, QString):
            qstr = QString(qstr)
        if not qstr.endsWith('\n'):
            qstr.append('\n')
        self.process.write(qstr.toLocal8Bit())
        self.process.waitForBytesWritten(-1)

    def keyboard_interrupt(self):
        communicate(self.monitor_socket, "thread.interrupt_main()")

#===============================================================================
#    Globals explorer
#===============================================================================

    def toggle_globals_explorer(self, state):
        self.splitter.setSizes([1, 1 if state else 0])
        self.globalsexplorer_button.setChecked(state)
        if state:
            self.globalsexplorer.refresh_table()

    def splitter_moved(self, pos, index):
        self.globalsexplorer_button.setChecked(self.splitter.sizes()[1])
Beispiel #28
0
class ViewDataTools(QMainWindow):
    def __init__(self, parent=None):
        super(ViewDataTools, self).__init__(parent)

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # DATATOOLS WINDOWS:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.setWindowTitle(ui_strings.DATATOOLS_TITLE)
        self._width = 680
        self._height = 560
        self._left_margin = 10
        self.resize(self._width, self._height)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QtCore.QSize(self._width, self._height))
        self.setMaximumSize(QtCore.QSize(self._width, self._height))
        self.setWindowIcon(QIcon(resources.ICON_LOGO))

        # central widget
        self.central_widget = QWidget(self)

        # DataTools description
        self.lbl_description = QLabel(self.central_widget)
        self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30))
        self.lbl_description.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION)

        # group input files
        self.group_input_file = QGroupBox(self.central_widget)
        self.group_input_file.setGeometry(
            QtCore.QRect(self._left_margin, 30, 660, 80))
        self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT)

        # frame input files
        self.frame_inputs = QFrame(self.group_input_file)
        self.frame_inputs.setGeometry(
            QtCore.QRect(self._left_margin, 0, 270, 80))
        self.frame_inputs.setFrameShape(QFrame.StyledPanel)
        self.frame_inputs.setFrameShadow(QFrame.Raised)

        # label input type
        self.lbl_input_type = QLabel(self.frame_inputs)
        self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15))
        self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE)

        # button xls
        self.btn_xls = QToolButton(self.frame_inputs)
        self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35))
        icon_xls = QIcon()
        icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal,
                           QIcon.Off)
        self.btn_xls.setIcon(icon_xls)
        self.btn_xls.setIconSize(QtCore.QSize(24, 24))
        self.btn_xls.setCheckable(True)
        self.btn_xls.setAutoExclusive(True)
        self.btn_xls.setObjectName("xls_button")

        # button csv
        self.btn_csv = QToolButton(self.frame_inputs)
        self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35))
        icon_csv = QIcon()
        icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal,
                           QIcon.Off)
        self.btn_csv.setIcon(icon_csv)
        self.btn_csv.setIconSize(QtCore.QSize(24, 24))
        self.btn_csv.setCheckable(True)
        self.btn_csv.setAutoExclusive(True)
        self.btn_csv.setObjectName("csv_button")

        # checkbox csv with headers
        self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS,
                                         self.frame_inputs)
        self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15))
        self.chk_csv_headers.setEnabled(False)

        # TextEdit + PushButton (FindFolder)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # lbl sheet name
        self.lbl_file_path = QLabel(self.group_input_file)
        self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15))
        self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE)

        self.txt_file = QLineEdit(self.group_input_file)
        self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20))
        self.txt_file.setReadOnly(True)

        self.btn_path = QPushButton(self.group_input_file)
        self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22))
        self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # lbl sheet name
        self.lbl_sheet_name = QLabel(self.group_input_file)
        self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15))
        self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME)

        # Combobox select sheet - initially does not contain values
        self.cbo_sheet = QComboBox(self.group_input_file)
        self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20))

        # data grid to visualize error messages
        self.tbl_errors = QTableWidget(self.central_widget)
        self.tbl_errors.setGeometry(
            QtCore.QRect(self._left_margin, 420, 660, 100))

        # data grid to visualize those records with errors.
        self.tbl_uploaded_data = QTableWidget(self.central_widget)
        self.tbl_uploaded_data.setGeometry(
            QtCore.QRect(self._left_margin, 120, 500, 220))

        # group run options
        self.group_run_options = QGroupBox(self.central_widget)
        self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220))
        self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN)

        # Errors summary:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # group summary errors
        self.group_errors = QGroupBox(self.central_widget)
        self.group_errors.setGeometry(
            QtCore.QRect(self._left_margin, 350, 660, 60))
        self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS)

        # lbl records
        self.lbl_records = QLabel(self.group_errors)
        self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15))
        self.lbl_records.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS)

        self.txt_records = QLineEdit(self.group_errors)
        self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20))
        self.txt_records.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_records.setReadOnly(True)

        # lbl errors
        self.lbl_errors = QLabel(self.group_errors)
        self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15))
        self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS)

        self.txt_errors = QLineEdit(self.group_errors)
        self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20))
        self.txt_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_errors.setReadOnly(True)

        # lbl time
        self.lbl_time = QLabel(self.group_errors)
        self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15))
        self.lbl_time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_time.setText(ui_strings.DATATOOLS_TIME)

        self.txt_time = QLineEdit(self.group_errors)
        self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20))
        self.txt_time.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_time.setReadOnly(True)

        # history button
        self.btn_history = QToolButton(self.group_errors)
        self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25))
        icon_history = QIcon()
        icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal,
                               QIcon.Off)
        self.btn_history.setIcon(icon_history)
        self.btn_history.setIconSize(QtCore.QSize(20, 20))
        self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.btn_history.setText(ui_strings.DATATOOLS_HISTORY)
        self.btn_history.setCheckable(True)
        self.btn_history.setAutoExclusive(True)
        self.btn_history.setObjectName("history_button")
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # btn data uploader
        self.btn_data_uploader = QPushButton(
            ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options)
        self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25))
        self.btn_data_uploader.setCheckable(True)
        self.btn_data_uploader.setAutoExclusive(True)
        self.btn_data_uploader.setFlat(False)

        # btn data testing
        self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING,
                                            self.group_run_options)
        self.btn_data_testing.setEnabled(False)
        self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25))
        self.btn_data_testing.setCheckable(True)
        self.btn_data_testing.setAutoExclusive(True)

        # btn data to database
        self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB,
                                       self.group_run_options)
        self.btn_data_db.setEnabled(False)
        self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23))
        self.btn_data_db.setCheckable(True)
        self.btn_data_db.setAutoExclusive(True)

        # frame run options
        self.frame_run = QFrame(self.group_run_options)
        self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80))
        self.frame_run.setFrameShape(QFrame.StyledPanel)
        self.frame_run.setFrameShadow(QFrame.Raised)

        # option process until first error
        self.rbtn_process_error = QRadioButton(
            ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run)
        self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20))

        # option process all data
        self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL,
                                             self.frame_run)
        self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30))

        # checkbox to filter by records with errors.
        #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run)
        #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15))
        #self.chk_filter_errors.setEnabled(False)

        # icons -> pass - error: Initially are empty labels
        # if not started -> ICON_MINI_WAIT
        # if error -> ICON_DELETE
        # if pass -> ICON_CHECK

        # state icon data uploader
        self.lbl_state_du = QLabel(self.group_run_options)
        self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20))
        self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_du.setScaledContents(True)

        # state icon data to database
        self.lbl_state_dt = QLabel(self.group_run_options)
        self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20))
        self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_dt.setScaledContents(True)

        # state icon data testing
        self.lbl_state_db = QLabel(self.group_run_options)
        self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20))
        self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_db.setScaledContents(True)

        # progress bar
        self.progress_bar = QProgressBar(self.central_widget)
        self.progress_bar.setGeometry(
            QtCore.QRect(self._left_margin, 530, 660, 15))
        self.progress_bar.setMaximum(100)
        self.progress_bar.setProperty("value", 0)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setOrientation(QtCore.Qt.Horizontal)
        self.progress_bar.setInvertedAppearance(False)
        self.progress_bar.setTextDirection(QProgressBar.TopToBottom)

        self.setCentralWidget(self.central_widget)
Beispiel #29
0
class DeletionOptions(QDialog):
    def __init__(self, parent, model):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.model = model
        self._setupUi()
        self.model.view = self

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

    def _setupUi(self):
        self.setWindowTitle(tr("Deletion Options"))
        self.resize(400, 270)
        self.verticalLayout = QVBoxLayout(self)
        self.msgLabel = QLabel()
        self.verticalLayout.addWidget(self.msgLabel)
        self.linkCheckbox = QCheckBox(tr("Link deleted files"))
        self.verticalLayout.addWidget(self.linkCheckbox)
        text = tr(
            "After having deleted a duplicate, place a link targeting the reference file "
            "to replace the deleted file.")
        self.linkMessageLabel = QLabel(text)
        self.linkMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.linkMessageLabel)
        self.linkTypeRadio = RadioBox(items=[tr("Symlink"),
                                             tr("Hardlink")],
                                      spread=False)
        self.verticalLayout.addWidget(self.linkTypeRadio)
        if not self.model.supports_links():
            self.linkCheckbox.setEnabled(False)
            self.linkTypeRadio.setEnabled(False)
            self.linkCheckbox.setText(self.linkCheckbox.text() +
                                      tr(" (unsupported)"))
        self.directCheckbox = QCheckBox(tr("Directly delete files"))
        self.verticalLayout.addWidget(self.directCheckbox)
        text = tr(
            "Instead of sending files to trash, delete them directly. This option is usually "
            "used as a workaround when the normal deletion method doesn't work."
        )
        self.directMessageLabel = QLabel(text)
        self.directMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.directMessageLabel)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
        self.verticalLayout.addWidget(self.buttonBox)

    #--- model --> view
    def update_msg(self, msg):
        self.msgLabel.setText(msg)

    def show(self):
        self.linkCheckbox.setChecked(self.model.link_deleted)
        self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0
        self.directCheckbox.setChecked(self.model.direct)
        result = self.exec()
        self.model.link_deleted = self.linkCheckbox.isChecked()
        self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1
        self.model.direct = self.directCheckbox.isChecked()
        return result == QDialog.Accepted
Beispiel #30
0
    def create_account_dialog(self):
        def coinapult_signup():
            try:
                self.client.createAccount(createLocalKeys=True, changeAuthMethod=True, tag="electrum-gfk36")
                self.client.activateAccount(agree=True)
            except (CoinapultError, CoinapultErrorECC) as ce:
                QMessageBox.warning(None, _("Unable to create Coinapult account because %s" % str(ce),
                                            QString(_("OK"))))

        def signup_done(result):
            self.ca_ok_button.setDisabled(False)
            self.wallet.storage.put("coinapult_ecc_public", str(self.client.ecc_pub_pem))
            self.ecc_pub_key_edit.setText(self.client.ecc_pub_pem)
            self.wallet.storage.put("coinapult_ecc_private", str(self.client.ecc['privkey'].to_pem()))
            self.ecc_priv_key_edit.setText(str(self.client.ecc['privkey'].to_pem()))
            self.config.set_key('coinapult_auth_method', 'ECC', True)
            ecc_pub = self.wallet.storage.get("coinapult_ecc_public", '')
            ecc_priv = self.wallet.storage.get("coinapult_ecc_private", '')
            try:
                self.client = CoinapultClient(ecc={'pubkey': ecc_pub, 'privkey': ecc_priv}, authmethod='ecc')
            except (CoinapultError, CoinapultErrorECC):
                self.client = None
                QMessageBox.warning(None, _('Coinapult Connection failed'),
                                    _('Failed to connect to Coinapult. Locks disabled for this session.'), _('OK'))
            d.accept()

        def on_change_tos(checked):
            if checked:
                self.config.set_key('plugin_coinapult_locks_tos', 'checked')
            else:
                self.config.set_key('plugin_coinapult_locks_tos', 'unchecked')

        def ok_clicked():
            if self.agreed_tos():
                self.ca_ok_button.setDisabled(True)
                self.waiting_dialog = WaitingDialog(d, 'Creating your Coinapult account. One moment please...',
                                                    coinapult_signup, signup_done)
                self.waiting_dialog.start()

        d = QDialog()
        d.setWindowTitle("Create Coinapult Account")
        layout = QGridLayout(d)

        # lable = None
        text_edit = QPlainTextEdit()
        text = open(os.path.dirname(__file__) + '/lib/TERMS.txt').read()
        text_edit.setPlainText(text)
        layout.addWidget(text_edit, 0, 0)
        layout.setRowStretch(0, 8)

        layout.addWidget(QLabel(_("Do you agree to Coinapult's Terms of Service (https://coinapult.com/terms)?: ")),
                         3, 0)
        tos_checkbox = QCheckBox()
        tos_checkbox.setEnabled(True)
        tos_checkbox.setChecked(self.config.get('plugin_coinapult_locks_tos', 'unchecked') != 'unchecked')
        tos_checkbox.stateChanged.connect(on_change_tos)
        layout.addWidget(tos_checkbox, 3, 1)

        layout.addWidget(
            QLabel(_("<font color='red'>This will overwrite any Coinapult API keys in your wallet.<br>"
                     "If you do not have backups of your API keys, this will lock you out of your "  # TODO This isn't actually stored in the wallet yet...
                     "account!</font>")), 4, 0)

        self.ca_ok_button = QPushButton(_("OK"))
        self.ca_ok_button.clicked.connect(ok_clicked)
        layout.addWidget(self.ca_ok_button, 5, 1)

        if d.exec_():
            return True
        else:
            return False
Beispiel #31
0
class GeneralPreferences(QGroupBox):
    def __init__(self, parent):
        super(GeneralPreferences, self).__init__(parent)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.typq = QCheckBox()
        self.tagl = QCheckBox()
        self.barnum = QCheckBox()
        self.neutdir = QCheckBox()
        self.midi = QCheckBox()
        self.metro = QCheckBox()
        self.paperSizeLabel = QLabel()
        self.paper = QComboBox()
        self.paper.addItems(paperSizes)
        self.paperLandscape = QCheckBox(enabled=False)
        self.paper.activated.connect(self.slotPaperChanged)
        
        layout.addWidget(self.typq)
        layout.addWidget(self.tagl)
        layout.addWidget(self.barnum)
        layout.addWidget(self.neutdir)
        layout.addWidget(self.midi)
        layout.addWidget(self.metro)
        
        box = QHBoxLayout(spacing=2)
        box.addWidget(self.paperSizeLabel)
        box.addWidget(self.paper)
        box.addWidget(self.paperLandscape)
        layout.addLayout(box)
        app.translateUI(self)
        
        self.loadSettings()
        self.window().finished.connect(self.saveSettings)
        
    def translateUI(self):
        self.setTitle(_("General preferences"))
        self.typq.setText(_("Use typographical quotes"))
        self.typq.setToolTip(_(
            "Replace normal quotes in titles with nice typographical quotes."))
        self.tagl.setText(_("Remove default tagline"))
        self.tagl.setToolTip(_(
            "Suppress the default tagline output by LilyPond."))
        self.barnum.setText(_("Remove bar numbers"))
        self.barnum.setToolTip(_(
            "Suppress the display of measure numbers at the beginning of "
            "every system."))
        self.neutdir.setText(_("Smart neutral stem direction"))
        self.neutdir.setToolTip(_(
            "Use a logical direction (up or down) for stems on the middle "
            "line of a staff."))
        self.midi.setText(_("Create MIDI output"))
        self.midi.setToolTip(_(
            "Create a MIDI file in addition to the PDF file."))
        self.metro.setText(_("Show metronome mark"))
        self.metro.setToolTip(_(
            "If checked, show the metronome mark at the beginning of the "
            "score. The MIDI output also uses the metronome setting."))
        # paper size:
        self.paperSizeLabel.setText(_("Paper size:"))
        self.paper.setItemText(0, _("Default"))
        self.paperLandscape.setText(_("Landscape"))
  
    def slotPaperChanged(self, index):
        self.paperLandscape.setEnabled(bool(index))
    
    def getPaperSize(self):
        """Returns the configured papersize or the empty string for default."""
        return paperSizes[self.paper.currentIndex()]
    
    def loadSettings(self):
        s = QSettings()
        s.beginGroup('scorewiz/preferences')
        self.typq.setChecked(s.value('typographical_quotes', True, bool))
        self.tagl.setChecked(s.value('remove_tagline', False, bool))
        self.barnum.setChecked(s.value('remove_barnumbers', False, bool))
        self.neutdir.setChecked(s.value('smart_neutral_direction', False, bool))
        self.midi.setChecked(s.value('midi', True, bool))
        self.metro.setChecked(s.value('metronome_mark', False, bool))
        psize = s.value('paper_size', '', type(""))
        enable = bool(psize and psize in paperSizes)
        self.paper.setCurrentIndex(paperSizes.index(psize) if enable else 0)
        self.paperLandscape.setChecked(s.value('paper_landscape', False, bool))
        self.paperLandscape.setEnabled(enable)

    def saveSettings(self):
        s = QSettings()
        s.beginGroup('scorewiz/preferences')
        s.setValue('typographical_quotes', self.typq.isChecked())
        s.setValue('remove_tagline', self.tagl.isChecked())
        s.setValue('remove_barnumbers', self.barnum.isChecked())
        s.setValue('smart_neutral_direction', self.neutdir.isChecked())
        s.setValue('midi', self.midi.isChecked())
        s.setValue('metronome_mark', self.metro.isChecked())
        s.setValue('paper_size', paperSizes[self.paper.currentIndex()])
        s.setValue('paper_landscape', self.paperLandscape.isChecked())
class GetIPDialog(QDialog):
    def __init__(self):
        super(GetIPDialog, self).__init__()

        # Create UI
        if Gl.NoInternet:
            title = Strings.NoInternetTitle
            string = Strings.NoInternetText
        else:
            title = Strings.IPAddressRequestTitle
            string = Strings.IPAddressRequest.format(Gl.myIP)
        self.text = string
        grid = QGridLayout(self)
        self.NameEdit = QLineEdit(self)
        self.NameEdit.setPlaceholderText(Strings.PlaceHolderName)
        self.IPEdit = QLineEdit(self)
        self.IPEdit.setPlaceholderText(Strings.PlaceHolderIPEnter)
        self.Label = QLabel(self.text)
        self.BeServer = QCheckBox(Strings.BeServer, self)
        self.PlayOffline = QCheckBox(Strings.PlayOffline, self)
        grid.addWidget(self.Label, 0, 0, 1, 3)
        grid.addWidget(self.NameEdit, 1, 0, 1, 3)
        grid.addWidget(self.IPEdit, 2, 0, 1, 3)
        grid.addWidget(self.BeServer, 3, 0, 1, 2)
        grid.addWidget(self.PlayOffline, 4, 0, 1, 2)

        self.BeServer.stateChanged.connect(self.check_box)
        self.PlayOffline.stateChanged.connect(self.offline)

        ok = QPushButton("Submit", self)
        ok.clicked.connect(self.accept)

        grid.addWidget(ok, 5, 2, 1, 1)
        self.setLayout(grid)

        self.setWindowTitle(title)

        if os.path.isfile(Gl.LastConnectionFile):
            with open(Gl.LastConnectionFile, "r") as f:
                self.NameEdit.setText(f.readline()[:-1])
                self.IPEdit.setText(f.readline())

    def check_box(self):
        self.IPEdit.setEnabled(not self.BeServer.isChecked())

    def offline(self):
        self.IPEdit.setEnabled(not self.PlayOffline.isChecked())
        self.BeServer.setEnabled(not self.PlayOffline.isChecked())
        if self.PlayOffline.isChecked():
            self.text = Strings.PlayOfflineText
        else:
            self.text = Strings.IPAddressRequest.format(Gl.myIP)
        self.Label.setText(self.text)

    def get_text(self, text=False):
        if text:
            self.Label.setText(self.text + text)
        else:
            self.Label.setText(self.text)
        ok = self.exec_()
        name = self.NameEdit.text()
        if self.PlayOffline.isChecked():
            ip = "Offline"
        elif self.BeServer.isChecked():
            ip = "Server"
        else:
            ip = self.IPEdit.text()
        return name, ip, ok

    def set_offline(self, state):
        self.PlayOffline.setChecked(state)
Beispiel #33
0
class TodoPropertiesDialog(QDialog):
    """ todo properties dialog implementation """
    def __init__(self, todo=None, parent=None):

        QDialog.__init__(self, parent)
        self.setWindowTitle("Todo Properties")

        self.__createLayout()

        if todo is not None:
            self.descriptionEdit.setText(todo.description)
            self.completedCheckBox.setChecked(todo.completed)
            self.filenameEdit.setText(todo.filename)
            if todo.lineno:
                self.linenoEdit.setText(str(todo.lineno))
        return

    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(579, 297)
        self.setSizeGripEnabled(True)

        self.gridlayout = QGridLayout(self)

        self.descriptionLabel = QLabel(self)
        self.descriptionLabel.setText("Description:")
        self.gridlayout.addWidget(self.descriptionLabel, 0, 0, 1, 1)

        self.descriptionEdit = QLineEdit(self)
        self.gridlayout.addWidget(self.descriptionEdit, 0, 1, 1, 3)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)

        self.completedCheckBox = QCheckBox(self)
        self.completedCheckBox.setText("Completed")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.completedCheckBox.sizePolicy().hasHeightForWidth())
        self.completedCheckBox.setSizePolicy(sizePolicy)
        self.gridlayout.addWidget(self.completedCheckBox, 3, 3, 1, 1)

        self.filenameLabel = QLabel(self)
        self.filenameLabel.setText("File name:")
        self.gridlayout.addWidget(self.filenameLabel, 4, 0, 1, 1)

        self.filenameEdit = QLineEdit(self)
        self.filenameEdit.setFocusPolicy(Qt.NoFocus)
        self.filenameEdit.setReadOnly(True)
        self.gridlayout.addWidget(self.filenameEdit, 4, 1, 1, 3)

        self.lineLabel = QLabel(self)
        self.lineLabel.setText("Line:")
        self.gridlayout.addWidget(self.lineLabel, 5, 0, 1, 1)

        self.linenoEdit = QLineEdit(self)
        self.linenoEdit.setFocusPolicy(Qt.NoFocus)
        self.linenoEdit.setReadOnly(True)
        self.gridlayout.addWidget(self.linenoEdit, 5, 1, 1, 3)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons( QDialogButtonBox.Cancel | \
                                           QDialogButtonBox.Ok )
        self.gridlayout.addWidget(self.buttonBox, 6, 0, 1, 4)

        self.descriptionLabel.setBuddy(self.descriptionEdit)

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        QMetaObject.connectSlotsByName(self)
        self.setTabOrder(self.completedCheckBox, self.buttonBox)
        return

    def setReadOnly(self):
        """ Disables editing some fields """

        self.descriptionEdit.setReadOnly(True)
        self.completedCheckBox.setEnabled(False)
        return

    def getData(self):
        """ Provides the dialog data """

        return (self.descriptionEdit.text(),
                self.completedCheckBox.isChecked())
Beispiel #34
0
class MobileWidget(QWidget):
    """
    Mobile widget
    """
    RefreshScreen = pyqtSignal()
    RefreshAutomatic = pyqtSignal(bool)
    TapOn = pyqtSignal(int, int)

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

        self.origWidth = 0
        self.origHeight = 0
        self.imagePath = None

        self.createActions()
        self.createWidget()
        self.createToolbar()
        self.center()

    def createActions(self):
        """
        Create qt actions
        """
        self.refreshAction = QtHelper.createAction(self,
                                                   self.tr("&Refresh"),
                                                   self.refreshScreen,
                                                   icon=None)
        self.refreshAction.setEnabled(False)

        self.copyAction = QtHelper.createAction(self,
                                                self.tr("&Copy"),
                                                self.copyItem,
                                                icon=None)

    def createWidget(self):
        """
        Create qt widget
        """

        self.screenResolutionLabel = QLabel(self)
        self.screenTapLabel = QLabel(self)

        mobileLayout = QVBoxLayout()

        self.mobileDockToolbar = QToolBar(self)
        self.mobileDockToolbar.setStyleSheet("QToolBar { border: 0px }")
        self.mobileDockToolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.mobileImageLabel = QLabel(self)
        self.mobileImageLabel.setMouseTracking(True)
        self.mobileImageLabel.installEventFilter(self)
        self.mobileImageLabel.setScaledContents(True)
        self.mobileImageLabel.mousePressEvent = self.pixelSelect

        self.refreshCheckbox = QCheckBox("Automatic Refresh", self)
        self.refreshCheckbox.setEnabled(False)
        self.refreshCheckbox.stateChanged.connect(self.onRefreshChanged)

        self.clickCheckbox = QCheckBox("Enable Tap", self)
        self.clickCheckbox.setEnabled(False)

        self.model = DomModel(QDomDocument(), self)
        self.mobileTreeView = QTreeView(self)
        self.mobileTreeView.setMinimumWidth(300)
        self.mobileTreeView.setModel(self.model)
        self.mobileTreeView.clicked.connect(self.onTreeViewClicked)

        header = ["Attribute", "Value"]
        self.tableModel = MyTableModel(self, [], header)
        self.mobileTableView = QTableView(self)
        self.mobileTableView.setSelectionMode(
            QAbstractItemView.SingleSelection)
        self.mobileTableView.setModel(self.tableModel)
        self.mobileTableView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mobileTableView.customContextMenuRequested.connect(
            self.onContextMenuEvent)
        self.mobileTableView.setMinimumWidth(300)

        mobileViewLayout = QHBoxLayout()
        mobileViewLayout.addWidget(self.mobileImageLabel)
        mobileViewLayout.addWidget(self.mobileTreeView)
        mobileViewLayout.addWidget(self.mobileTableView)

        mobileLayout.addWidget(self.mobileDockToolbar)
        mobileLayout.addLayout(mobileViewLayout)

        self.setLayout(mobileLayout)

    def createToolbar(self):
        """
        Create qt toolbar
        """
        self.mobileDockToolbar.setObjectName("Toolbar")
        self.mobileDockToolbar.addWidget(self.refreshCheckbox)
        self.mobileDockToolbar.addWidget(self.clickCheckbox)
        self.mobileDockToolbar.addSeparator()
        self.mobileDockToolbar.addAction(self.refreshAction)
        self.mobileDockToolbar.addSeparator()
        self.mobileDockToolbar.addWidget(self.screenResolutionLabel)
        self.mobileDockToolbar.addSeparator()
        self.mobileDockToolbar.addWidget(self.screenTapLabel)
        self.mobileDockToolbar.addSeparator()
        self.mobileDockToolbar.setIconSize(QSize(16, 16))

    def center(self):
        """
        Center the dialog
        """
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def eventFilter(self, srcEvent, event):
        """
        On event filtering
        """
        if srcEvent == self.mobileImageLabel:

            if event.type() == QEvent.MouseMove:
                x = event.pos().x()
                y = event.pos().y()

                pixmap = self.mobileImageLabel.pixmap()
                if pixmap is not None:
                    x_scaled = int((self.origWidth * x) / pixmap.width())
                    y_scaled = int((self.origHeight * y) / pixmap.height())
                    self.mobileImageLabel.setToolTip("%sx%s" %
                                                     (x_scaled, y_scaled))

        return False

    def onContextMenuEvent(self, event):
        """
        On context menu event
        """
        menu = QMenu(self)
        menu.addAction(self.copyAction)
        menu.popup(QCursor.pos())

    def copyItem(self):
        """
        Copy the item
        """
        indexes = self.mobileTableView.selectedIndexes()
        if len(indexes):
            data = self.tableModel.mylist[indexes[0].row()][
                indexes[0].column()]

            clipboard = QApplication.clipboard()
            clipboard.setText(data)

    def onTreeViewClicked(self, qindex):
        """
        On click in the treeview
        """
        item = qindex.internalPointer()
        attributes = []
        node = item.node()
        attributeMap = node.attributes()
        nodeName = node.nodeName()

        bounds_str = None
        for i in range(0, attributeMap.count()):
            attribute = attributeMap.item(i)
            attributes.append((attribute.nodeName(), attribute.nodeValue()))

            if attribute.nodeName() == 'bounds':
                bounds_str = attribute.nodeValue()

        self.tableModel.mylist = attributes

        if sys.version_info > (3, ):
            self.tableModel.beginResetModel()
            self.tableModel.endResetModel()
        else:
            self.tableModel.reset()

        self.mobileTableView.resizeColumnsToContents()
        self.mobileTableView.resizeRowsToContents()

        # redraw image with rectangle
        if bounds_str is not None:
            xy = bounds_str.split('][')[0].split('[')[1]
            wh = bounds_str.split('][')[1].split(']')[0]
            x, y = xy.split(',')
            w, h = wh.split(',')

            # get label size
            pixmap = self.mobileImageLabel.pixmap()
            xlabel = pixmap.width()
            ylabel = pixmap.height()

            # resize the rectangle
            y_scaled = (pixmap.height() * int(y)) / self.origHeight
            x_scaled = (pixmap.width() * int(x)) / self.origWidth

            h_scaled = (pixmap.height() * (int(h) - int(y))) / self.origHeight
            w_scaled = (pixmap.width() * (int(w) - int(x))) / self.origWidth

            # finally reload
            self.reloadScreen(x=int(x_scaled),
                              y=int(y_scaled),
                              w=int(w_scaled),
                              h=int(h_scaled))

    def onDeviceReady(self):
        """
        On device ready
        """
        self.refreshAction.setEnabled(True)
        self.refreshCheckbox.setEnabled(True)
        self.clickCheckbox.setEnabled(True)

    def refreshScreen(self):
        """
        Refresh the screen
        """
        self.RefreshScreen.emit()

    def onRefreshChanged(self, state):
        """
        On refresh changed
        """
        if state == Qt.Checked:
            self.RefreshAutomatic.emit(True)
        else:
            self.RefreshAutomatic.emit(False)

    def pixelSelect(self, event):
        """
        Select pixel to click
        """
        position = QPoint(event.pos().x(), event.pos().y())

        x = event.pos().x()
        y = event.pos().y()

        pixmap = self.mobileImageLabel.pixmap()

        x_scaled = int((self.origWidth * x) / pixmap.width())
        y_scaled = int((self.origHeight * y) / pixmap.height())

        self.screenTapLabel.setText("Tap on (%s,%s)" % (x_scaled, y_scaled))

        if self.clickCheckbox.isChecked():
            self.TapOn.emit(x_scaled, y_scaled)

    def drawRectangle(self, x=0, y=0, w=0, h=0):
        """
        Draw a rectangle
        """
        self.mobileImageLabel.update()
        pixmap = self.mobileImageLabel.pixmap()
        if pixmap is not None:

            p = QPainter(pixmap)
            pen = QPen(Qt.red, 2, Qt.SolidLine)
            p.setPen(pen)
            p.drawRect(x, y, w, h)
            p.end()

    def reloadScreen(self, x, y, w, h):
        """
        Reload the screen
        """
        if self.imagePath is not None:
            self.updateScreen(filename=self.imagePath,
                              xmlPath='',
                              x=x,
                              y=y,
                              w=w,
                              h=h,
                              reloadMode=True)

    def updateScreen(self,
                     filename,
                     xmlPath,
                     x=0,
                     y=0,
                     w=0,
                     h=0,
                     reloadMode=False):
        """
        Update the screen
        """
        self.imagePath = filename

        if not reloadMode:
            self.tableModel.mylist = []
            self.tableModel.beginResetModel()
            self.tableModel.endResetModel()

        pixmap = QPixmap(filename)
        if pixmap is not None:
            self.origWidth = pixmap.width()
            self.origHeight = pixmap.height()

            self.screenResolutionLabel.setText(
                "Resolution=%sx%s" % (self.origWidth, self.origHeight))

            #portrait
            if self.origWidth < self.origHeight:
                pixmap = pixmap.scaledToHeight(Settings.getInt(
                    'MobileAndroid', 'resolution-screen-height'),
                                               mode=Qt.SmoothTransformation)
                self.mobileImageLabel.setPixmap(pixmap)
            else:
                pixmap = pixmap.scaledToWidth(Settings.getInt(
                    'MobileAndroid', 'resolution-screen-width'),
                                              mode=Qt.SmoothTransformation)
                self.mobileImageLabel.setPixmap(pixmap)

            self.drawRectangle(x=x, y=y, w=w, h=h)

        self.resize(pixmap.width(), pixmap.height())

        # convert xml to dict
        if len(xmlPath):
            f = QFile(xmlPath)
            if f.open(QIODevice.ReadOnly):
                document = QDomDocument()
                if document.setContent(f):
                    newModel = DomModel(document, self)
                    self.mobileTreeView.setModel(newModel)
                    self.mobileTreeView.expandAll()
                    self.mobileTreeView.resizeColumnToContents(0)
                f.close()
Beispiel #35
0
class Settings(SymbolManager, QWidget):
    """
    The widget where users can set other preferences.
    """
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        SymbolManager.__init__(self)
        parent.addPage(self, i18n("Score settings"))

        h = QHBoxLayout(self)
        v = QVBoxLayout()
        h.addLayout(v)
        score = QGroupBox(i18n("Score settings"))
        v.addWidget(score)
        lily =  QGroupBox(i18n("LilyPond"))
        v.addWidget(lily)

        v = QVBoxLayout()
        h.addLayout(v)
        prefs = QGroupBox(i18n("General preferences"))
        v.addWidget(prefs)
        instr = QGroupBox(i18n("Instrument names"))
        v.addWidget(instr)

        # Score settings:
        v = QVBoxLayout(score)
        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Key signature:"), h)
        self.key = QComboBox(h) # the key names are filled in later
        self.mode = QComboBox(h)
        self.mode.addItems([title for name, title in ly.modes(i18n)])
        l.setBuddy(self.key)

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Time signature:"), h)
        self.time = QComboBox(h)
        self.time.setEditable(True)
        self.time.addItems([
            '(4/4)', '(2/2)',
            '2/4', '3/4', '4/4', '5/4', '6/4', '7/4',
            '2/2', '3/2', '4/2',
            '3/8', '5/8', '6/8', '7/8', '8/8', '9/8', '12/8',
            '3/16', '6/16', '12/16'])
        # palette sensitive icons for the first two items
        self.addItemSymbol(self.time, 0, 'time_c44')
        self.addItemSymbol(self.time, 1, 'time_c22')
        l.setBuddy(self.time)

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Pickup measure:"), h)
        self.pickup = QComboBox(h)
        self.pickup.addItem(i18n("None"))
        self.pickup.insertSeparator(1)
        durs = [('note_' + d.replace('.', 'd'), d) for d in durations]
        for icon, text in durs:
            self.addItemSymbol(self.pickup, self.pickup.count(), icon)
            self.pickup.addItem(text)
        l.setBuddy(self.pickup)

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Metronome mark:"), h)
        self.metroDur = QComboBox(h)

        l.setBuddy(self.metroDur)
        for icon, text in durs:
            self.addItemSymbol(self.metroDur, self.metroDur.count(), icon)
            self.metroDur.addItem('')
        l = QLabel('=', h)
        l.setAlignment(Qt.AlignCenter)
        l.setMaximumWidth(20)
        self.metroVal = QComboBox(h)
        self.metroVal.setEditable(True)
        metroValues, start = [], 40
        for end, step in (60, 2), (72, 3), (120, 4), (144, 6), (210, 8):
            metroValues.extend(range(start, end, step))
            start = end
        # reverse so mousewheeling is more intuitive
        self.metroValues = metroValues[::-1]
        self.metroVal.addItems(map(str, self.metroValues))
        def tap(bpm):
            """ Tap the tempo tap button """
            l = [abs(t - bpm) for t in self.metroValues]
            m = min(l)
            if m < 6:
                self.metroVal.setCurrentIndex(l.index(m))
        TapButton(h, tap)

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Tempo indication:"), h)
        self.tempoInd = KLineEdit(h)
        parent.complete(self.tempoInd, "tempo")
        l.setBuddy(self.tempoInd)
        h.setToolTip(i18n("A tempo indication, e.g. \"Allegro.\""))

        # LilyPond settings
        v = QVBoxLayout(lily)
        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Pitch name language:"), h)
        self.languageNames = list(sorted(ly.keyNames))
        self.lylang = QComboBox(h)
        l.setBuddy(self.lylang)
        self.lylang.addItem(i18n("Default"))
        self.lylang.insertSeparator(1)
        self.lylang.addItems([l.title() for l in self.languageNames])
        h.setToolTip(i18n(
            "The LilyPond language you want to use for the pitch names."))
        self.lylang.currentIndexChanged.connect(self.slotLanguageChanged)
        self.slotLanguageChanged(0) # init with default
        
        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Version:"), h)
        self.lyversion = QComboBox(h)
        self.lyversion.setEditable(True)
        l.setBuddy(self.lyversion)
        version = defaultVersion()
        if version:
            self.lyversion.addItem(str(version))
        self.lyversion.addItems(('2.12.0', '2.10.0'))
        h.setToolTip(i18n(
            "The LilyPond version you will be using for this document."))

        # General preferences
        v = QVBoxLayout(prefs)
        self.typq = QCheckBox(i18n("Use typographical quotes"))
        self.typq.setToolTip(i18n(
            "Replace normal quotes in titles with nice typographical quotes."))
        v.addWidget(self.typq)
        self.tagl = QCheckBox(i18n("Remove default tagline"))
        self.tagl.setToolTip(i18n(
            "Suppress the default tagline output by LilyPond."))
        v.addWidget(self.tagl)
        self.barnum = QCheckBox(i18n("Remove bar numbers"))
        self.barnum.setToolTip(i18n(
            "Suppress the display of measure numbers at the beginning of "
            "every system."))
        v.addWidget(self.barnum)
        self.midi = QCheckBox(i18n("Create MIDI output"))
        self.midi.setToolTip(i18n(
            "Create a MIDI file in addition to the PDF file."))
        v.addWidget(self.midi)
        self.metro = QCheckBox(i18n("Show metronome mark"))
        self.metro.setToolTip(i18n(
            "If checked, show the metronome mark at the beginning of the "
            "score. The MIDI output also uses the metronome setting."))
        v.addWidget(self.metro)

        self.book = QCheckBox(i18n("Wrap score in \\book block"))
        self.book.setToolTip(i18n(
            "If checked, wraps the \\score block inside a \\book block."))
        v.addWidget(self.book)

        # paper size:
        h = KHBox()
        v.addWidget(h)
        h.setSpacing(2)
        l = QLabel(i18n("Paper size:"), h)
        self.paper = QComboBox(h)
        l.setBuddy(self.paper)
        self.paperLandscape = QCheckBox(i18n("Landscape"), h)
        self.paper.addItem(i18n("Default"))
        self.paper.addItems(ly.paperSizes)
        self.paper.activated.connect(lambda i: self.paperLandscape.setEnabled(bool(i)))

        # Instrument names
        instr.setCheckable(True)
        self.instr = instr
        v = QVBoxLayout(instr)

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("First system:"), h)
        self.instrFirst = QComboBox(h)
        l.setBuddy(self.instrFirst)
        self.instrFirst.addItems((i18n("Long"), i18n("Short")))
        h.setToolTip(i18n(
            "Use long or short instrument names before the first system."))

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Other systems:"), h)
        self.instrOther = QComboBox(h)
        l.setBuddy(self.instrOther)
        self.instrOther.addItems((i18n("Long"), i18n("Short"), i18n("None")))
        h.setToolTip(i18n(
            "Use short, long or no instrument names before the next systems."))

        h = KHBox()
        v.addWidget(h)
        l = QLabel(i18n("Language:"), h)
        self.instrLang = QComboBox(h)
        l.setBuddy(self.instrLang)
        self.instrLang.addItems((i18n("Default"), KGlobal.locale().languageCodeToName("en")))
        h.setToolTip(i18n("Which language to use for the instrument names."))

        langs = KGlobal.dirs().findAllResources("locale", "*/LC_MESSAGES/frescobaldi.mo")
        self.instrLanguages = list(sorted(set(lang.split('/')[-3] for lang in langs)))
        self.instrLang.addItems(map(KGlobal.locale().languageCodeToName, self.instrLanguages))
        
        self.default()
        self.loadConfig()

    def saveConfig(self):
        conf = config()
        conf.writeEntry('language', self.getLanguage() or 'default')
        conf.writeEntry('typographical', self.typq.isChecked())
        conf.writeEntry('remove tagline', self.tagl.isChecked())
        conf.writeEntry('remove barnumbers', self.barnum.isChecked())
        conf.writeEntry('midi', self.midi.isChecked())
        conf.writeEntry('metronome mark', self.metro.isChecked())
        conf.writeEntry('wrap in book', self.book.isChecked())
        if self.paper.currentIndex() > 0:
            conf.writeEntry('paper size', ly.paperSizes[self.paper.currentIndex() - 1])
        conf.writeEntry('paper landscape', self.paperLandscape.isChecked())
        g = config('instrument names')
        g.writeEntry('show', self.instr.isChecked())
        g.writeEntry('first', ['long', 'short'][self.instrFirst.currentIndex()])
        g.writeEntry('other', ['long', 'short', 'none'][self.instrOther.currentIndex()])
        g.writeEntry('lang', (['default', 'english'] + self.instrLanguages)[self.instrLang.currentIndex()])

    def loadConfig(self):
        conf = config()
        self.setLanguage(conf.readEntry('language', 'default'))
        self.typq.setChecked(conf.readEntry('typographical', True))
        self.tagl.setChecked(conf.readEntry('remove tagline', False))
        self.barnum.setChecked(conf.readEntry('remove barnumbers', False))
        self.midi.setChecked(conf.readEntry('midi', True))
        self.metro.setChecked(conf.readEntry('metronome mark', False))
        self.book.setChecked(conf.readEntry('wrap in book', False))

        psize = conf.readEntry('paper size', "")
        if psize in ly.paperSizes:
            self.paper.setCurrentIndex(ly.paperSizes.index(psize) + 1)
        self.paperLandscape.setChecked(conf.readEntry('paper landscape', False))
        self.paperLandscape.setEnabled(psize in ly.paperSizes)

        g = config('instrument names')
        def readconf(entry, itemlist, defaultIndex):
            item = g.readEntry(entry, itemlist[defaultIndex])
            if item in itemlist:
                return itemlist.index(item)
            else:
                return defaultIndex

        first = readconf('first', ['long', 'short'], 0)
        other = readconf('other', ['long', 'short', 'none'], 2)
        lang = readconf('lang', ['default', 'english'] + self.instrLanguages, 0)

        self.instrFirst.setCurrentIndex(first)
        self.instrOther.setCurrentIndex(other)
        self.instrLang.setCurrentIndex(lang)
        self.instr.setChecked(g.readEntry('show', True))

    def default(self):
        """ Set various items to their default state """
        self.lylang.setCurrentIndex(0)
        self.key.setCurrentIndex(0)
        self.mode.setCurrentIndex(0)
        self.time.setCurrentIndex(0)
        self.pickup.setCurrentIndex(0)
        self.metroVal.setCurrentIndex(self.metroValues.index(100))
        self.metroDur.setCurrentIndex(durations.index('4'))
        self.tempoInd.clear()
        self.typq.setChecked(True)
        self.tagl.setChecked(False)
        self.barnum.setChecked(False)
        self.midi.setChecked(True)
        self.metro.setChecked(False)
        self.book.setChecked(False)
        self.paper.setCurrentIndex(0)
        self.paperLandscape.setEnabled(False)
        self.instrFirst.setCurrentIndex(0)
        self.instrOther.setCurrentIndex(2)
        self.instrLang.setCurrentIndex(0)
        self.instr.setChecked(True)

    def getLanguage(self):
        """ Return the configured LilyPond pitch language, '' for default. """
        if self.lylang.currentIndex() >= 2:
            return self.languageNames[self.lylang.currentIndex() - 2]
        else:
            return ''

    def setLanguage(self, lang):
        """ Sets the language combobox to the specified language """
        if lang not in self.languageNames:
            self.lylang.setCurrentIndex(0)
        else:
            self.lylang.setCurrentIndex(self.languageNames.index(lang) + 2)
    
    def slotLanguageChanged(self, index):
        """ Change the LilyPond language, affects key names """
        lang = index < 2 and "nederlands" or self.languageNames[index - 2]
        key = self.key.currentIndex()
        if key == -1:
            key = 0
        self.key.clear()
        self.key.addItems(ly.keyNames[lang])
        self.key.setCurrentIndex(key)
Beispiel #36
0
    def __init__(self, scenario, parent = None):
        super(InfoComp, self).__init__(parent)

        self.resize(300, 223)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.setWindowTitle(u"Informations complémentaires")
        icon = get_icon(":/images/people.png")
        self.setWindowIcon(icon)
        self.verticalLayout = QVBoxLayout(self)
        self.gridLayout = QGridLayout()
        self.gridLayout.setHorizontalSpacing(10)
        self.setStyleSheet(OfSs.bold_center)

        self.label_0 = QLabel(u'n°', self)
        self.gridLayout.addWidget(self.label_0, 0, 0, 1, 1)

        self.label_1 = QLabel(u'Activité', self)
        self.gridLayout.addWidget(self.label_1, 0, 1, 1, 1)
        
        self.label_2 = QLabel(u"Invalide", self)
        self.gridLayout.addWidget(self.label_2, 0, 2, 1, 1)

        self.label_3 = QLabel(u'Garde\nalternée', self)
        self.gridLayout.addWidget(self.label_3, 0, 3, 1, 1)

        self.gridLayout.setColumnStretch(1, 1)
        self.gridLayout.setColumnStretch(2, 1)
        self.gridLayout.setColumnStretch(3, 1)
        self.verticalLayout.addLayout(self.gridLayout)

        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel| QDialogButtonBox.Ok, parent = self)
        self.verticalLayout.addWidget(self.buttonBox)

        self.connect(self.buttonBox, SIGNAL('accepted()'), self.accept);
        self.connect(self.buttonBox, SIGNAL('rejected()'), self.reject);

        self.parent = parent
        self.scenario = scenario
        self.inv_list = []
        self.alt_list = []
        self.act_list = []
        for noi, vals in self.scenario.indiv.iteritems():
            self.gridLayout.addWidget(QLabel('%d' % (noi + 1), self), noi + 1, 0)
            
            # Acitivité
            cb_act = QComboBox(self)
            cb_act.addItems([u'Actif occupé', u'Chômeur', u'Étudiant, élève', u'Retraité', u'Autre inactif'])
            cb_act.setCurrentIndex(vals['activite'])
            self.act_list.append(cb_act)
            self.gridLayout.addWidget(cb_act, noi + 1, 1)

            # Invalide
            cb_inv = QCheckBox(self)
            cb_inv.setChecked(vals['inv'])
            layout1 = QHBoxLayout()
            layout1.addItem(QSpacerItem(0,0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            layout1.addWidget(cb_inv)
            layout1.addItem(QSpacerItem(0,0, QSizePolicy.Expanding, QSizePolicy.Minimum))            
            self.inv_list.append(cb_inv)
            self.gridLayout.addLayout(layout1, noi + 1, 2)

            # Garde alternée
            cb_alt = QCheckBox(self)
            if vals['quifoy'][:3] != 'pac':
                vals['alt'] = 0
                cb_alt.setEnabled(False)
            cb_alt.setChecked(vals['alt'])
            layout2 = QHBoxLayout()
            layout2.addItem(QSpacerItem(0,0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            layout2.addWidget(cb_alt)
            layout2.addItem(QSpacerItem(0,0, QSizePolicy.Expanding, QSizePolicy.Minimum))
            self.alt_list.append(cb_alt)
            self.gridLayout.addLayout(layout2, noi + 1, 3)
Beispiel #37
0
class ExternalPythonShell(ExternalShellBase):
    """External Shell widget: execute Python script in a separate process"""
    SHELL_CLASS = ExtPyQsciShell
    def __init__(self, parent=None, fname=None, wdir=None, commands=[],
                 interact=False, debug=False, path=[]):
        ExternalShellBase.__init__(self, parent, wdir,
                                   history_filename='.history_ec.py')
        
        self.shell.set_externalshell(self)

        self.toggle_globals_explorer(False)
        self.interact_check.setChecked(interact)
        self.debug_check.setChecked(debug)
        
        self.monitor_socket = None
        self.interpreter = fname is None
        self.fname = startup.__file__ if fname is None else fname
        
        if self.interpreter:
            self.interact_check.hide()
            self.debug_check.hide()
            self.terminate_button.hide()
        
        self.commands = ["import sys", "sys.path.insert(0, '')"] + commands
        
        # Additional python path list
        self.path = path
        
    def get_toolbar_buttons(self):
        ExternalShellBase.get_toolbar_buttons(self)
        self.globalsexplorer_button = create_toolbutton(self,
                          get_icon('dictedit.png'), self.tr("Variables"),
                          tip=self.tr("Show/hide global variables explorer"),
                          toggled=self.toggle_globals_explorer)
        self.terminate_button = create_toolbutton(self,
              get_icon('terminate.png'), self.tr("Terminate"),
              tip=self.tr("Attempts to terminate the process.\n"
                          "The process may not exit as a result of clicking "
                          "this button\n(it is given the chance to prompt "
                          "the user for any unsaved files, etc)."))        
        self.interact_check = QCheckBox(self.tr("Interact"), self)
        self.debug_check = QCheckBox(self.tr("Debug"), self)
        return [self.interact_check, self.debug_check,
                self.globalsexplorer_button, self.run_button,
                self.terminate_button, self.kill_button]
        
    def get_shell_widget(self):
        # Globals explorer
        self.globalsexplorer = GlobalsExplorer(self)
        self.connect(self.globalsexplorer, SIGNAL('collapse()'),
                     lambda: self.toggle_globals_explorer(False))
        
        # Shell splitter
        self.splitter = splitter = QSplitter(Qt.Vertical, self)
        self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'),
                     self.splitter_moved)
        splitter.addWidget(self.shell)
        splitter.setCollapsible(0, False)
        splitter.addWidget(self.globalsexplorer)
        splitter.setStretchFactor(0, 2)
        splitter.setStretchFactor(1, 1)
        return splitter
    
    def get_icon(self):
        return get_icon('python.png')

    def set_buttons_runnning_state(self, state):
        ExternalShellBase.set_buttons_runnning_state(self, state)
        self.interact_check.setEnabled(not state)
        self.debug_check.setEnabled(not state)
        self.terminate_button.setEnabled(state)
        if not state:
            self.toggle_globals_explorer(False)
        self.globalsexplorer_button.setEnabled(state)
    
    def create_process(self):
        self.shell.clear()
            
        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        self.connect(self.shell, SIGNAL("wait_for_ready_read()"),
                     lambda: self.process.waitForReadyRead(250))
        
        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)

        #-------------------------Python specific-------------------------------
        # Python arguments
        p_args = ['-u']
        if self.interact_check.isChecked():
            p_args.append('-i')
        if self.debug_check.isChecked():
            p_args.extend(['-m', 'pdb'])
        p_args.append(self.fname)
        
        env = self.process.systemEnvironment()
        
        # Monitor
        env.append('SHELL_ID=%s' % id(self))
        from spyderlib.widgets.externalshell.monitor import start_server
        server, port = start_server()
        self.notification_thread = server.register(str(id(self)), self)
        self.connect(self.notification_thread, SIGNAL('refresh()'),
                     self.globalsexplorer.refresh_table)
        env.append('SPYDER_PORT=%d' % port)
        
        # Python init commands (interpreter only)
        if self.commands and self.interpreter:
            env.append('PYTHONINITCOMMANDS=%s' % ';'.join(self.commands))
            self.process.setEnvironment(env)
            
        pathlist = []

        # Fix encoding with custom "sitecustomize.py"
        scpath = osp.dirname(osp.abspath(__file__))
        pathlist.append(scpath)
        
        # Adding Spyder path
        pathlist += self.path
        
        # Adding path list to PYTHONPATH environment variable
        pypath = "PYTHONPATH"
        pathstr = os.pathsep.join(pathlist)
        if os.environ.get(pypath) is not None:
            env.replaceInStrings(pypath+'=', pypath+'='+pathstr+os.pathsep,
                                 Qt.CaseSensitive)
        else:
            env.append(pypath+'='+pathstr)
        self.process.setEnvironment(env)
        #-------------------------Python specific-------------------------------
            
        if self.arguments:
            p_args.extend( self.arguments.split(' ') )
                        
        self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
                     self.write_output)
        self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"),
                     self.finished)

        self.connect(self.terminate_button, SIGNAL("clicked()"),
                     self.process.terminate)
        self.connect(self.kill_button, SIGNAL("clicked()"),
                     self.process.kill)
        
        #-------------------------Python specific-------------------------------
        self.process.start(sys.executable, p_args)
        #-------------------------Python specific-------------------------------
            
        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, self.tr("Error"),
                                 self.tr("Process failed to start"))
        else:
            self.shell.setFocus()
            self.emit(SIGNAL('started()'))
            
        return self.process
    
#===============================================================================
#    Input/Output
#===============================================================================
    def _write_error(self, text, findstr):
        pos = text.find(findstr)
        if pos != -1:
            self.shell.write(text[:pos])
            if text.endswith(">>> "):
                self.shell.write_error(text[pos:-5])
                self.shell.write(text[-5:], flush=True)
            else:
                self.shell.write_error(text[pos:])
            return True
        return False
    
    def write_output(self):
        text = self.get_stdout()
        if not self._write_error(text, 'Traceback (most recent call last):') \
           and not self._write_error(text, 'File "<stdin>", line 1'):
            self.shell.write(text)
        QApplication.processEvents()
        
    def send_to_process(self, qstr):
        if not isinstance(qstr, QString):
            qstr = QString(qstr)
        if not qstr.endsWith('\n'):
            qstr.append('\n')
        self.process.write(qstr.toLocal8Bit())
        self.process.waitForBytesWritten(-1)
        
    def keyboard_interrupt(self):
        communicate(self.monitor_socket, "thread.interrupt_main()")
            
#===============================================================================
#    Globals explorer
#===============================================================================
    def toggle_globals_explorer(self, state):
        self.splitter.setSizes([1, 1 if state else 0])
        self.globalsexplorer_button.setChecked(state)
        if state:
            self.globalsexplorer.refresh_table()
        
    def splitter_moved(self, pos, index):
        self.globalsexplorer_button.setChecked( self.splitter.sizes()[1] )
Beispiel #38
0
class RunDialog( QDialog ):
    """ Run parameters dialog implementation """

    # See utils.run for runParameters
    def __init__( self, path, runParameters, termType,
                  profilerParams, debuggerParams,
                  action = "", parent = None ):
        QDialog.__init__( self, parent )

        # Used as a return value
        self.termType = termType
        self.profilerParams = copy.deepcopy( profilerParams )
        self.debuggerParams = copy.deepcopy( debuggerParams )

        self.__action = action.lower()

        # Avoid pylint complains
        self.__argsEdit = None
        self.__scriptWDRButton = None
        self.__dirRButton = None
        self.__dirEdit = None
        self.__dirSelectButton = None
        self.__inheritParentRButton = None
        self.__inheritParentPlusRButton = None
        self.__inhPlusEnvTable = None
        self.__addInhButton = None
        self.__delInhButton = None
        self.__editInhButton = None
        self.__specificRButton = None
        self.__specEnvTable = None
        self.__addSpecButton = None
        self.__delSpecButton = None
        self.__editSpecButton = None
        self.__runButton = None
        self.__nodeLimitEdit = None
        self.__edgeLimitEdit = None

        self.__createLayout( action )
        self.setWindowTitle( action + " parameters for " + path )

        # Restore the values
        self.runParams = copy.deepcopy( runParameters )
        self.__argsEdit.setText( self.runParams.arguments )

        # Working dir
        if self.runParams.useScriptLocation:
            self.__scriptWDRButton.setChecked( True )
            self.__dirEdit.setEnabled( False )
            self.__dirSelectButton.setEnabled( False )
        else:
            self.__dirRButton.setChecked( True )
            self.__dirEdit.setEnabled( True )
            self.__dirSelectButton.setEnabled( True )

        self.__dirEdit.setText( self.runParams.specificDir )

        # Environment
        self.__populateTable( self.__inhPlusEnvTable,
                              self.runParams.additionToParentEnv )
        self.__populateTable( self.__specEnvTable,
                              self.runParams.specificEnv )

        if self.runParams.envType == RunParameters.InheritParentEnv:
            self.__inheritParentRButton.setChecked( True )
            self.__setEnabledInheritedPlusEnv( False )
            self.__setEnabledSpecificEnv( False )
        elif self.runParams.envType == RunParameters.InheritParentEnvPlus:
            self.__inheritParentPlusRButton.setChecked( True )
            self.__setEnabledSpecificEnv( False )
        else:
            self.__specificRButton.setChecked( True )
            self.__setEnabledInheritedPlusEnv( False )

        # Terminal
        if self.termType == TERM_REDIRECT:
            self.__redirectRButton.setChecked( True )
        elif self.termType == TERM_AUTO:
            self.__autoRButton.setChecked( True )
        elif self.termType == TERM_KONSOLE:
            self.__konsoleRButton.setChecked( True )
        elif self.termType == TERM_GNOME:
            self.__gnomeRButton.setChecked( True )
        else:
            self.__xtermRButton.setChecked( True )

        # Close checkbox
        self.__closeCheckBox.setChecked( self.runParams.closeTerminal )
        if self.termType == TERM_REDIRECT:
            self.__closeCheckBox.setEnabled( False )

        # Profile limits if so
        if self.__action == "profile":
            if self.profilerParams.nodeLimit < 0.0 or \
               self.profilerParams.nodeLimit > 100.0:
                self.profilerParams.nodeLimit = 1.0
            self.__nodeLimitEdit.setText( str( self.profilerParams.nodeLimit ) )
            if self.profilerParams.edgeLimit < 0.0 or \
               self.profilerParams.edgeLimit > 100.0:
                self.profilerParams.edgeLimit = 1.0
            self.__edgeLimitEdit.setText( str( self.profilerParams.edgeLimit ) )
        elif self.__action == "debug":
            self.__reportExceptionCheckBox.setChecked(
                                    self.debuggerParams.reportExceptions )
            self.__traceInterpreterCheckBox.setChecked(
                                    self.debuggerParams.traceInterpreter )
            self.__stopAtFirstCheckBox.setChecked(
                                    self.debuggerParams.stopAtFirstLine )
            self.__autoforkCheckBox.setChecked(
                                    self.debuggerParams.autofork )
            self.__debugChildCheckBox.setChecked(
                                    self.debuggerParams.followChild )
            self.__debugChildCheckBox.setEnabled( self.debuggerParams.autofork )

        self.__setRunButtonProps()
        return

    @staticmethod
    def __populateTable( table, dictionary ):
        " Populates the given table "
        for key, value in dictionary.iteritems():
            item = QTreeWidgetItem( [ key, value ] )
            table.addTopLevelItem( item )
        if dictionary:
            table.setCurrentItem( table.topLevelItem( 0 ) )
        return

    def __setEnabledInheritedPlusEnv( self, value ):
        " Disables/enables 'inherited and add' section controls "
        self.__inhPlusEnvTable.setEnabled( value )
        self.__addInhButton.setEnabled( value )
        self.__delInhButton.setEnabled( value )
        self.__editInhButton.setEnabled( value )
        return

    def __setEnabledSpecificEnv( self, value ):
        " Disables/enables 'specific env' section controls "
        self.__specEnvTable.setEnabled( value )
        self.__addSpecButton.setEnabled( value )
        self.__delSpecButton.setEnabled( value )
        self.__editSpecButton.setEnabled( value )
        return

    def __createLayout( self, action ):
        """ Creates the dialog layout """

        self.resize( 650, 300 )
        self.setSizeGripEnabled( True )

        # Top level layout
        layout = QVBoxLayout( self )

        # Cmd line arguments
        argsLabel = QLabel( "Command line arguments" )
        self.__argsEdit = QLineEdit()
        self.__argsEdit.textChanged.connect( self.__argsChanged )
        argsLayout = QHBoxLayout()
        argsLayout.addWidget( argsLabel )
        argsLayout.addWidget( self.__argsEdit )
        layout.addLayout( argsLayout )

        # Working directory
        workDirGroupbox = QGroupBox( self )
        workDirGroupbox.setTitle( "Working directory" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth( \
                        workDirGroupbox.sizePolicy().hasHeightForWidth() )
        workDirGroupbox.setSizePolicy( sizePolicy )

        gridLayoutWD = QGridLayout( workDirGroupbox )
        self.__scriptWDRButton = QRadioButton( workDirGroupbox )
        self.__scriptWDRButton.setText( "&Use script location" )
        gridLayoutWD.addWidget( self.__scriptWDRButton, 0, 0 )
        self.__scriptWDRButton.clicked.connect( self.__scriptWDirClicked )

        self.__dirRButton = QRadioButton( workDirGroupbox )
        self.__dirRButton.setText( "Select &directory" )
        gridLayoutWD.addWidget( self.__dirRButton, 1, 0 )
        self.__dirRButton.clicked.connect( self.__dirClicked )

        self.__dirEdit = QLineEdit( workDirGroupbox )
        gridLayoutWD.addWidget( self.__dirEdit, 1, 1 )
        self.__dirEdit.textChanged.connect( self.__workingDirChanged )

        self.__dirSelectButton = QPushButton( workDirGroupbox )
        self.__dirSelectButton.setText( "..." )
        gridLayoutWD.addWidget( self.__dirSelectButton, 1, 2 )
        self.__dirSelectButton.clicked.connect( self.__selectDirClicked )

        layout.addWidget( workDirGroupbox )

        # Environment
        envGroupbox = QGroupBox( self )
        envGroupbox.setTitle( "Environment" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth( \
                        envGroupbox.sizePolicy().hasHeightForWidth() )
        envGroupbox.setSizePolicy( sizePolicy )

        layoutEnv = QVBoxLayout( envGroupbox )
        self.__inheritParentRButton = QRadioButton( envGroupbox )
        self.__inheritParentRButton.setText( "Inherit &parent" )
        self.__inheritParentRButton.clicked.connect( self.__inhClicked )
        layoutEnv.addWidget( self.__inheritParentRButton )

        self.__inheritParentPlusRButton = QRadioButton( envGroupbox )
        self.__inheritParentPlusRButton.setText( "Inherit parent and add/&modify" )
        self.__inheritParentPlusRButton.clicked.connect( self.__inhPlusClicked )
        layoutEnv.addWidget( self.__inheritParentPlusRButton )
        hInhPlusLayout = QHBoxLayout()
        self.__inhPlusEnvTable = QTreeWidget()
        self.__inhPlusEnvTable.itemActivated.connect( self.__inhPlusItemActivated )
        self.__tuneTable( self.__inhPlusEnvTable )
        hInhPlusLayout.addWidget( self.__inhPlusEnvTable )
        vInhPlusLayout = QVBoxLayout()
        self.__addInhButton = QPushButton()
        self.__addInhButton.clicked.connect( self.__addInhClicked )
        self.__addInhButton.setText( 'Add' )
        vInhPlusLayout.addWidget( self.__addInhButton )
        self.__delInhButton = QPushButton()
        self.__delInhButton.clicked.connect( self.__delInhClicked )
        self.__delInhButton.setText( 'Delete' )
        vInhPlusLayout.addWidget( self.__delInhButton )
        self.__editInhButton = QPushButton()
        self.__editInhButton.clicked.connect( self.__editInhClicked )
        self.__editInhButton.setText( "Edit" )
        vInhPlusLayout.addWidget( self.__editInhButton )
        hInhPlusLayout.addLayout( vInhPlusLayout )
        layoutEnv.addLayout( hInhPlusLayout )

        self.__specificRButton = QRadioButton( envGroupbox )
        self.__specificRButton.setText( "&Specific" )
        self.__specificRButton.clicked.connect( self.__specClicked )
        layoutEnv.addWidget( self.__specificRButton )
        hSpecLayout = QHBoxLayout()
        self.__specEnvTable = QTreeWidget()
        self.__specEnvTable.itemActivated.connect( self.__specItemActivated )
        self.__tuneTable( self.__specEnvTable )
        hSpecLayout.addWidget( self.__specEnvTable )
        vSpecLayout = QVBoxLayout()
        self.__addSpecButton = QPushButton()
        self.__addSpecButton.clicked.connect( self.__addSpecClicked )
        self.__addSpecButton.setText( 'Add' )
        vSpecLayout.addWidget( self.__addSpecButton )
        self.__delSpecButton = QPushButton()
        self.__delSpecButton.clicked.connect( self.__delSpecClicked )
        self.__delSpecButton.setText( 'Delete' )
        vSpecLayout.addWidget( self.__delSpecButton )
        self.__editSpecButton = QPushButton()
        self.__editSpecButton.clicked.connect( self.__editSpecClicked )
        self.__editSpecButton.setText( "Edit" )
        vSpecLayout.addWidget( self.__editSpecButton )
        hSpecLayout.addLayout( vSpecLayout )
        layoutEnv.addLayout( hSpecLayout )
        layout.addWidget( envGroupbox )

        # Terminal and profile limits
        if self.__action in [ "profile", "debug" ]:
            layout.addWidget( self.__getIDEWideGroupbox() )
        else:
            termGroupbox = self.__getTermGroupbox()
            termGroupbox.setTitle( "Terminal to run in (IDE wide setting)" )
            layout.addWidget( termGroupbox )

        # Close checkbox
        self.__closeCheckBox = QCheckBox( "&Close terminal upon "
                                          "successful completion" )
        self.__closeCheckBox.stateChanged.connect( self.__onCloseChanged )
        layout.addWidget( self.__closeCheckBox )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel )
        self.__runButton = buttonBox.addButton( action,
                                                QDialogButtonBox.AcceptRole )
        self.__runButton.setDefault( True )
        self.__runButton.clicked.connect( self.onAccept )
        layout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.close )
        return

    def __getTermGroupbox( self ):
        " Creates the term groupbox "
        termGroupbox = QGroupBox( self )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                        termGroupbox.sizePolicy().hasHeightForWidth() )
        termGroupbox.setSizePolicy( sizePolicy )

        layoutTerm = QVBoxLayout( termGroupbox )
        self.__redirectRButton = QRadioButton( termGroupbox )
        self.__redirectRButton.setText( "&Redirect to IDE" )
        self.__redirectRButton.toggled.connect( self.__redirectedChanged )
        layoutTerm.addWidget( self.__redirectRButton )
        self.__autoRButton = QRadioButton( termGroupbox )
        self.__autoRButton.setText( "Aut&o detection" )
        layoutTerm.addWidget( self.__autoRButton )
        self.__konsoleRButton = QRadioButton( termGroupbox )
        self.__konsoleRButton.setText( "Default &KDE konsole" )
        layoutTerm.addWidget( self.__konsoleRButton )
        self.__gnomeRButton = QRadioButton( termGroupbox )
        self.__gnomeRButton.setText( "gnome-&terminal" )
        layoutTerm.addWidget( self.__gnomeRButton )
        self.__xtermRButton = QRadioButton( termGroupbox )
        self.__xtermRButton.setText( "&xterm" )
        layoutTerm.addWidget( self.__xtermRButton )
        return termGroupbox

    def __redirectedChanged( self, checked ):
        " Triggered when the redirected radio button changes its state "
        self.__closeCheckBox.setEnabled( not checked )
        return

    def __getIDEWideGroupbox( self ):
        " Creates the IDE wide groupbox "
        ideGroupbox = QGroupBox( self )
        ideGroupbox.setTitle( "IDE Wide Settings" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                        ideGroupbox.sizePolicy().hasHeightForWidth() )
        ideGroupbox.setSizePolicy( sizePolicy )

        layoutIDE = QHBoxLayout( ideGroupbox )

        termGroupbox = self.__getTermGroupbox()
        termGroupbox.setTitle( "Terminal to run in" )
        layoutIDE.addWidget( termGroupbox )

        if self.__action == "profile":
            # Profile version of the dialog
            limitsGroupbox = self.__getProfileLimitsGroupbox()
            layoutIDE.addWidget( limitsGroupbox )
        else:
            # Debug version of the dialog
            dbgGroupbox = self.__getDebugGroupbox()
            layoutIDE.addWidget( dbgGroupbox )
        return ideGroupbox

    def __getProfileLimitsGroupbox( self ):
        " Creates the profile limits groupbox "
        limitsGroupbox = QGroupBox( self )
        limitsGroupbox.setTitle( "Profiler diagram limits" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                limitsGroupbox.sizePolicy().hasHeightForWidth() )
        limitsGroupbox.setSizePolicy( sizePolicy )

        layoutLimits = QGridLayout( limitsGroupbox )
        self.__nodeLimitEdit = QLineEdit()
        self.__nodeLimitEdit.textEdited.connect( self.__setRunButtonProps )
        self.__nodeLimitValidator = QDoubleValidator( 0.0, 100.0, 2, self )
        self.__nodeLimitValidator.setNotation( QDoubleValidator.StandardNotation )
        self.__nodeLimitEdit.setValidator( self.__nodeLimitValidator )
        nodeLimitLabel = QLabel( "Hide nodes below" )
        self.__edgeLimitEdit = QLineEdit()
        self.__edgeLimitEdit.textEdited.connect( self.__setRunButtonProps )
        self.__edgeLimitValidator = QDoubleValidator( 0.0, 100.0, 2, self )
        self.__edgeLimitValidator.setNotation( QDoubleValidator.StandardNotation )
        self.__edgeLimitEdit.setValidator( self.__edgeLimitValidator )
        edgeLimitLabel = QLabel( "Hide edges below" )
        layoutLimits.addWidget( nodeLimitLabel, 0, 0 )
        layoutLimits.addWidget( self.__nodeLimitEdit, 0, 1 )
        layoutLimits.addWidget( QLabel( "%" ), 0, 2 )
        layoutLimits.addWidget( edgeLimitLabel, 1, 0 )
        layoutLimits.addWidget( self.__edgeLimitEdit, 1, 1 )
        layoutLimits.addWidget( QLabel( "%" ), 1, 2 )
        return limitsGroupbox

    def __getDebugGroupbox( self ):
        " Creates the debug settings groupbox "
        dbgGroupbox = QGroupBox( self )
        dbgGroupbox.setTitle( "Debugger" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                    dbgGroupbox.sizePolicy().hasHeightForWidth() )
        dbgGroupbox.setSizePolicy( sizePolicy )

        dbgLayout = QVBoxLayout( dbgGroupbox )
        self.__reportExceptionCheckBox = QCheckBox( "Report &exceptions" )
        self.__reportExceptionCheckBox.stateChanged.connect(
                                            self.__onReportExceptionChanged )
        self.__traceInterpreterCheckBox = QCheckBox( "T&race interpreter libs" )
        self.__traceInterpreterCheckBox.stateChanged.connect(
                                            self.__onTraceInterpreterChanged )
        self.__stopAtFirstCheckBox = QCheckBox( "Stop at first &line" )
        self.__stopAtFirstCheckBox.stateChanged.connect(
                                            self.__onStopAtFirstChanged )
        self.__autoforkCheckBox = QCheckBox( "&Fork without asking" )
        self.__autoforkCheckBox.stateChanged.connect(self.__onAutoforkChanged )
        self.__debugChildCheckBox = QCheckBox( "Debu&g child process" )
        self.__debugChildCheckBox.stateChanged.connect( self.__onDebugChild )

        dbgLayout.addWidget( self.__reportExceptionCheckBox )
        dbgLayout.addWidget( self.__traceInterpreterCheckBox )
        dbgLayout.addWidget( self.__stopAtFirstCheckBox )
        dbgLayout.addWidget( self.__autoforkCheckBox )
        dbgLayout.addWidget( self.__debugChildCheckBox )
        return dbgGroupbox


    @staticmethod
    def __tuneTable( table ):
        " Sets the common settings for a table "

        table.setAlternatingRowColors( True )
        table.setRootIsDecorated( False )
        table.setItemsExpandable( False )
        table.setUniformRowHeights( True )
        table.setSelectionMode( QAbstractItemView.SingleSelection )
        table.setSelectionBehavior( QAbstractItemView.SelectRows )
        table.setItemDelegate( NoOutlineHeightDelegate( 4 ) )
        table.setHeaderLabels( [ "Variable", "Value" ] )

        header = table.header()
        header.setSortIndicator( 0, Qt.AscendingOrder )
        header.setSortIndicatorShown( True )
        header.setClickable( True )
        table.setSortingEnabled( True )
        return

    def __scriptWDirClicked( self ):
        " The script working dir button is clicked "
        self.__dirEdit.setEnabled( False )
        self.__dirSelectButton.setEnabled( False )
        self.runParams.useScriptLocation = True

        self.__setRunButtonProps()
        return

    def __dirClicked( self ):
        " The script specific working dir button is clicked "
        self.__dirEdit.setEnabled( True )
        self.__dirSelectButton.setEnabled( True )
        self.runParams.useScriptLocation = False

        self.__setRunButtonProps()
        return

    def __argsChanged( self, value ):
        " Triggered when cmd line args are changed "
        value = str( value ).strip()
        self.runParams.arguments = value
        self.__setRunButtonProps()
        return

    def __workingDirChanged( self, value ):
        " Triggered when a working dir value is changed "
        value = str( value )
        self.runParams.specificDir = value
        self.__setRunButtonProps()
        return

    def __onCloseChanged( self, state ):
        " Triggered when the close terminal check box changed "
        self.runParams.closeTerminal = state != 0
        return

    def __onReportExceptionChanged( self, state ):
        " Triggered when exception report check box changed "
        self.debuggerParams.reportExceptions = state != 0
        return

    def __onTraceInterpreterChanged( self, state ):
        " Triggered when trace interpreter changed "
        self.debuggerParams.traceInterpreter = state != 0
        return

    def __onStopAtFirstChanged( self, state ):
        " Triggered when stop at first changed "
        self.debuggerParams.stopAtFirstLine = state != 0
        return

    def __onAutoforkChanged( self, state ):
        " Triggered when autofork changed "
        self.debuggerParams.autofork = state != 0
        self.__debugChildCheckBox.setEnabled( self.debuggerParams.autofork )
        return

    def __onDebugChild( self, state ):
        " Triggered when debug child changed "
        self.debuggerParams.followChild = state != 0
        return

    def __argumentsOK( self ):
        " Returns True if the arguments are OK "
        try:
            parseCommandLineArguments( self.runParams.arguments )
            return True
        except:
            return False

    def __dirOK( self ):
        " Returns True if the working dir is OK "
        if self.__scriptWDRButton.isChecked():
            return True
        return os.path.isdir( self.__dirEdit.text() )

    def __setRunButtonProps( self, newText = None ):
        " Enable/disable run button and set its tooltip "
        if not self.__argumentsOK():
            self.__runButton.setEnabled( False )
            self.__runButton.setToolTip( "No closing quotation in arguments" )
            return

        if not self.__dirOK():
            self.__runButton.setEnabled( False )
            self.__runButton.setToolTip( "The given working "
                                         "dir is not found" )
            return

        if self.__nodeLimitEdit is not None:
            txt = self.__nodeLimitEdit.text().strip()
            try:
                value = float( txt )
                if value < 0.0 or value > 100.0:
                    raise Exception( "Out of range" )
            except:
                self.__runButton.setEnabled( False )
                self.__runButton.setToolTip( "The given node limit "
                                             "is out of range" )
                return

        if self.__edgeLimitEdit is not None:
            txt = self.__edgeLimitEdit.text().strip()
            try:
                value = float( txt )
                if value < 0.0 or value > 100.0:
                    raise Exception( "Out of range" )
            except:
                self.__runButton.setEnabled( False )
                self.__runButton.setToolTip( "The given edge limit "
                                             "is out of range" )
                return

        self.__runButton.setEnabled( True )
        self.__runButton.setToolTip( "Save parameters and " +
                                     self.__action + " script" )
        return

    def __selectDirClicked( self ):
        " Selects the script working dir "
        dirName = QFileDialog.getExistingDirectory( self,
                    "Select the script working directory",
                    self.__dirEdit.text(),
                    QFileDialog.Options( QFileDialog.ShowDirsOnly ) )

        if dirName:
            self.__dirEdit.setText( os.path.normpath( dirName ) )
        return

    def __inhClicked( self ):
        " Inerit parent env radio button clicked "
        self.__setEnabledInheritedPlusEnv( False )
        self.__setEnabledSpecificEnv( False )
        self.runParams.envType = RunParameters.InheritParentEnv
        return

    def __inhPlusClicked( self ):
        " Inherit parent and add radio button clicked "
        self.__setEnabledInheritedPlusEnv( True )
        self.__setEnabledSpecificEnv( False )
        self.runParams.envType = RunParameters.InheritParentEnvPlus

        if self.__inhPlusEnvTable.selectedIndexes():
            self.__delInhButton.setEnabled( True )
            self.__editInhButton.setEnabled( True )
        else:
            self.__delInhButton.setEnabled( False )
            self.__editInhButton.setEnabled( False )
        return

    def __specClicked( self ):
        " Specific env radio button clicked "
        self.__setEnabledInheritedPlusEnv( False )
        self.__setEnabledSpecificEnv( True )
        self.runParams.envType = RunParameters.SpecificEnvironment

        if self.__specEnvTable.selectedIndexes():
            self.__delSpecButton.setEnabled( True )
            self.__editSpecButton.setEnabled( True )
        else:
            self.__delSpecButton.setEnabled( False )
            self.__editSpecButton.setEnabled( False )
        return

    @staticmethod
    def __delAndInsert( table, name, value ):
        " Deletes an item by name if so; insert new; highlight it "
        for index in xrange( table.topLevelItemCount() ):
            item = table.topLevelItem( index )
            if str( item.text( 0 ) ) == name:
                table.takeTopLevelItem( index )
                break

        item = QTreeWidgetItem( [ name, value ] )
        table.addTopLevelItem( item )
        table.setCurrentItem( item )
        return item

    def __addInhClicked( self ):
        " Add env var button clicked "
        dlg = EnvVarDialog()
        if dlg.exec_() == QDialog.Accepted:
            name = str( dlg.name )
            value = str( dlg.value )
            self.__delAndInsert( self.__inhPlusEnvTable, name, value )
            self.runParams.additionToParentEnv[ name ] = value
            self.__delInhButton.setEnabled( True )
            self.__editInhButton.setEnabled( True )
        return

    def __addSpecClicked( self ):
        " Add env var button clicked "
        dlg = EnvVarDialog()
        if dlg.exec_() == QDialog.Accepted:
            name = str( dlg.name )
            value = str( dlg.value )
            self.__delAndInsert( self.__specEnvTable, name, value )
            self.runParams.specificEnv[ name ] = value
            self.__delSpecButton.setEnabled( True )
            self.__editSpecButton.setEnabled( True )
        return

    def __delInhClicked( self ):
        " Delete the highlighted variable "
        if self.__inhPlusEnvTable.topLevelItemCount() == 0:
            return

        name = self.__inhPlusEnvTable.currentItem().text( 0 )
        for index in xrange( self.__inhPlusEnvTable.topLevelItemCount() ):
            item = self.__inhPlusEnvTable.topLevelItem( index )
            if name == item.text( 0 ):
                self.__inhPlusEnvTable.takeTopLevelItem( index )
                break

        del self.runParams.additionToParentEnv[ str( name ) ]
        if self.__inhPlusEnvTable.topLevelItemCount() == 0:
            self.__delInhButton.setEnabled( False )
            self.__editInhButton.setEnabled( False )
        else:
            self.__inhPlusEnvTable.setCurrentItem( \
                                self.__inhPlusEnvTable.topLevelItem( 0 ) )
        return

    def __delSpecClicked( self ):
        " Delete the highlighted variable "
        if self.__specEnvTable.topLevelItemCount() == 0:
            return

        name = self.__specEnvTable.currentItem().text( 0 )
        for index in xrange( self.__specEnvTable.topLevelItemCount() ):
            item = self.__specEnvTable.topLevelItem( index )
            if name == item.text( 0 ):
                self.__specEnvTable.takeTopLevelItem( index )
                break

        del self.runParams.specificEnv[ str( name ) ]
        if self.__specEnvTable.topLevelItemCount() == 0:
            self.__delSpecButton.setEnabled( False )
            self.__editSpecButton.setEnabled( False )
        else:
            self.__specEnvTable.setCurrentItem( \
                            self.__specEnvTable.topLevelItem( 0 ) )
        return

    def __editInhClicked( self ):
        " Edits the highlighted variable "
        if self.__inhPlusEnvTable.topLevelItemCount() == 0:
            return

        item = self.__inhPlusEnvTable.currentItem()
        dlg = EnvVarDialog( str( item.text( 0 ) ), str( item.text( 1 ) ), self )
        if dlg.exec_() == QDialog.Accepted:
            name = str( dlg.name )
            value = str( dlg.value )
            self.__delAndInsert( self.__inhPlusEnvTable, name, value )
            self.runParams.additionToParentEnv[ name ] = value
        return

    def __inhPlusItemActivated( self, item, column ):
        " Triggered when a table item is activated "
        self.__editInhClicked()
        return

    def __editSpecClicked( self ):
        " Edits the highlighted variable "
        if self.__specEnvTable.topLevelItemCount() == 0:
            return

        item = self.__specEnvTable.currentItem()
        dlg = EnvVarDialog( str( item.text( 0 ) ), str( item.text( 1 ) ), self )
        if dlg.exec_() == QDialog.Accepted:
            name = str( dlg.name )
            value = str( dlg.value )
            self.__delAndInsert( self.__specEnvTable, name, value )
            self.runParams.specificEnv[ name ] = value
        return

    def __specItemActivated( self, item, column ):
        " Triggered when a table item is activated "
        self.__editSpecClicked()
        return

    def onAccept( self ):
        " Saves the selected terminal and profiling values "
        if self.__redirectRButton.isChecked():
            self.termType = TERM_REDIRECT
        elif self.__autoRButton.isChecked():
            self.termType = TERM_AUTO
        elif self.__konsoleRButton.isChecked():
            self.termType = TERM_KONSOLE
        elif self.__gnomeRButton.isChecked():
            self.termType = TERM_GNOME
        else:
            self.termType = TERM_XTERM

        if self.__action == "profile":
            self.profilerParams.nodeLimit = float(
                                    self.__nodeLimitEdit.text() )
            self.profilerParams.edgeLimit = float(
                                    self.__edgeLimitEdit.text() )

        self.accept()
        return
Beispiel #39
0
class Calculatrice(Panel_simple):
    __titre__ = u"Calculatrice" # Donner un titre a chaque module

    def __init__(self, *args, **kw):
        Panel_simple.__init__(self, *args, **kw)
        self.interprete = Interprete(calcul_exact = self.param("calcul_exact"),
                                ecriture_scientifique = self.param("ecriture_scientifique"),
                                changer_separateurs = self.param("changer_separateurs"),
                                separateurs_personnels = self.param("separateurs_personnels"),
                                copie_automatique = self.param("copie_automatique"),
                                formatage_OOo = self.param("formatage_OOo"),
                                formatage_LaTeX = self.param("formatage_LaTeX"),
                                ecriture_scientifique_decimales = self.param("ecriture_scientifique_decimales"),
                                precision_calcul = self.param("precision_calcul"),
                                precision_affichage = self.param("precision_affichage"),
                                simpify = True,
                                )

##        self.entrees = wx.BoxSizer(wx.HORIZONTAL)
##        self.entree = wx.TextCtrl(self, size = (550, -1), style = wx.TE_PROCESS_ENTER)
##        self.entrees.Add(self.entree, 1, wx.ALL|wx.GROW, 5)
##        self.valider = wx.Button(self, wx.ID_OK)
##        self.entrees.Add(self.valider, 0, wx.ALL, 5)
        self.entree = entree = LigneCommande(self, longueur = 550, action = self.affichage_resultat)
        entree.setToolTip(u"[Maj]+[Entrée] pour une valeur approchée.")
        self.entree.texte.setContextMenuPolicy(Qt.CustomContextMenu)
        self.entree.texte.customContextMenuRequested.connect(self.EvtMenu)


        self.sizer = sizer = QVBoxLayout()
        sizer.addWidget(entree)
        self.corps = corps = QHBoxLayout()
        sizer.addLayout(corps)
        self.gauche = gauche = QVBoxLayout()
        corps.addLayout(gauche, 1)
        self.resultats = resultats = QTextEdit(self)
        resultats.setMinimumSize(450, 310)
        resultats.setReadOnly(True)
        gauche.addWidget(resultats)

        self.figure = Figure(figsize=(5,1.3), frameon=True, facecolor="w")
        self.visualisation = FigureCanvas(self.figure)
        self.axes = axes = self.figure.add_axes([0, 0, 1, 1], frameon=False)
        axes.axison = False
        self.pp_texte = axes.text(0.5, 0.5, "", horizontalalignment='center', verticalalignment='center', transform = axes.transAxes, size=18)
        gauche.addWidget(self.visualisation) # wx.ALL|wx.ALIGN_CENTER
        self.visualisation.setContextMenuPolicy(Qt.CustomContextMenu)
        self.visualisation.customContextMenuRequested.connect(self.EvtMenuVisualisation)

        ### Pave numerique de la calculatrice ###
        # On construit le pavé de la calculatrice.
        # Chaque bouton du pavé doit provoquer l'insertion de la commande correspondante.

        self.pave = pave = QVBoxLayout()
        corps.addLayout(pave)
#        pave.setSpacing(1)
        boutons = ["2nde", "ans", "ouv", "ferm", "egal", "7", "8", "9", "div", "x", "4", "5", "6", "mul", "y", "1", "2", "3", "minus", "z", "0", "pt", "pow", "plus", "t", "rac", "sin", "cos", "tan", "exp", "i", "pi", "e", "abs", "mod"]
        inserer = ["", "ans()", "(", ")", "=", "7", "8", "9",  "/", "x", "4", "5", "6", "*", "y", "1", "2", "3", "-", "z", "0", ".", "^", "+", "t", "sqrt(", ("sin(", "asin(", "sinus / arcsinus"), ("cos(", "acos(", "cosinus / arccosinus"), ("tan(", "atan(", "tangente / arctangente"), ("exp(", "ln(", "exponentielle / logarithme neperien"), ("i", "cbrt(", "i / racine cubique"), ("pi", "sinh(", "pi / sinus hyperbolique"), ("e", "cosh", "e / cosinus hyperbolique"), ("abs(", "tanh", "valeur absolue / tangente hyperbolique"), (" mod ", "log10(", "modulo / logarithme decimal")]

        self.seconde = False # indique si la touche 2nde est activee.

        def action(event = None):
            self.seconde = not self.seconde
            if self.seconde:
                self.message(u"Touche [2nde] activée.")
            else:
                self.message("")

        self.actions = [action]

        for i in range(len(boutons)):
            # On aligne les boutons de la calculatrice par rangées de 5.
            if i%5 == 0:
                self.rangee = rangee = QHBoxLayout()
                rangee.addStretch(1)
                pave.addLayout(rangee)

            # Ensuite, on construit une liste de fonctions, parallèlement à la liste des boutons.
            if i > 0:
                #XXX: ce serait plus propre en utilisant partial().
                def action(event = None, entree = self.entree, j = i):
                    if type(inserer[j]) == tuple:
                        entree.insert(inserer[j][self.seconde])
                    else:
                        entree.insert(inserer[j])
                    n = entree.cursorPosition()
                    entree.setFocus()
                    entree.setCursorPosition(n)
                    self.seconde = False
                    self.message("")
                self.actions.append(action)

            bouton = QPushButton()
            pix = png('btn_' + boutons[i])
            bouton.setIcon(QIcon(pix))
            bouton.setIconSize(pix.size())
            bouton.setFlat(True)
#            bouton.setSize()
#            bouton.SetBackgroundColour(self.GetBackgroundColour())
            rangee.addWidget(bouton)
            if i%5 == 4:
                rangee.addStretch(2)
            # A chaque bouton, on associe une fonction de la liste.
            bouton.clicked.connect(self.actions[i])
            if type(inserer[i]) == tuple:
                bouton.setToolTip(inserer[i][2])

#        self.pave.Add(QHBoxLayout())


        ### Liste des options ###
        # En dessous du pavé apparait la liste des différents modes de fonctionnement de la calculatrice.

        # Calcul exact
        ligne = QHBoxLayout()
        pave.addLayout(ligne)
        self.cb_calcul_exact = QCheckBox(self)
        self.cb_calcul_exact.setChecked(not self.param("calcul_exact"))
        ligne.addWidget(self.cb_calcul_exact) #, flag = wx.ALIGN_CENTER_VERTICAL)
        ligne.addWidget(QLabel(u"Valeur approchée."))#, flag = wx.ALIGN_CENTER_VERTICAL)
        ligne.addStretch()

        self.cb_calcul_exact.stateChanged.connect(self.EvtCalculExact)

        # Notation scientifique
        ligne = QHBoxLayout()
        pave.addLayout(ligne)
        self.cb_notation_sci = QCheckBox(self)
        self.cb_notation_sci.setChecked(self.param("ecriture_scientifique"))
        ligne.addWidget(self.cb_notation_sci)#, flag = wx.ALIGN_CENTER_VERTICAL)
        self.st_notation_sci = QLabel(u"Écriture scientifique (arrondie à ")
        ligne.addWidget(self.st_notation_sci)#, flag = wx.ALIGN_CENTER_VERTICAL)
        self.sc_decimales = sd = QSpinBox(self)
        # size = (45, -1)
        sd.setRange(0, 11)
        self.sc_decimales.setValue(self.param("ecriture_scientifique_decimales"))
        ligne.addWidget(self.sc_decimales)#, flag = wx.ALIGN_CENTER_VERTICAL)
        self.st_decimales = QLabel(u" décimales).")
        ligne.addWidget(self.st_decimales)#, flag = wx.ALIGN_CENTER_VERTICAL)
        ligne.addStretch()
        self.EvtCalculExact()

        self.cb_notation_sci.stateChanged.connect(self.EvtNotationScientifique)
        self.sc_decimales.valueChanged.connect(self.EvtNotationScientifique)

        # Copie du résultat dans le presse-papier
        ligne = QHBoxLayout()
        pave.addLayout(ligne)
        self.cb_copie_automatique = QCheckBox(self)
        self.cb_copie_automatique.setChecked(self.param("copie_automatique"))
        ligne.addWidget(self.cb_copie_automatique)#, flag = wx.ALIGN_CENTER_VERTICAL)
        ligne.addWidget(QLabel(u"Copie du résultat dans le presse-papier."))#, flag = wx.ALIGN_CENTER_VERTICAL)
        ligne.addStretch()

        self.cb_copie_automatique.stateChanged.connect(self.EvtCopieAutomatique)

        # En mode LaTeX
        ligne = QHBoxLayout()
        pave.addLayout(ligne)
        self.cb_copie_automatique_LaTeX = QCheckBox(self)
        self.cb_copie_automatique_LaTeX.setChecked(self.param("copie_automatique_LaTeX"))
        ligne.addWidget(self.cb_copie_automatique_LaTeX)
        self.st_copie_automatique_LaTeX = QLabel(u"Copie au format LaTeX (si possible).")
        ligne.addWidget(self.st_copie_automatique_LaTeX)
        ligne.addStretch()

        self.EvtCopieAutomatique()
        self.cb_copie_automatique_LaTeX.stateChanged.connect(self.EvtCopieAutomatiqueLatex)

        # Autres options
        self.options = [(u"Virgule comme séparateur décimal.", u"changer_separateurs"),
##                    (u"Copie du résultat dans le presse-papier.", u"copie_automatique"),
                    (u"Accepter la syntaxe OpenOffice.org", u"formatage_OOo"),
                    (u"Accepter la syntaxe LaTeX", u"formatage_LaTeX"),
                        ]
        self.options_box = []
        for i in range(len(self.options)):
            ligne = QHBoxLayout()
            pave.addLayout(ligne)
            self.options_box.append(QCheckBox(self))
            ligne.addWidget(self.options_box[i])
            self.options_box[i].setChecked(self.param(self.options[i][1]))
            def action(event, chaine = self.options[i][1], entree = self.entree, self = self):
                self.param(chaine, not self.param(chaine))
                entree.setFocus()
            self.options_box[i].stateChanged.connect(action)
            ligne.addWidget(QLabel(self.options[i][0]))
            ligne.addStretch()

        self.setLayout(self.sizer)
#        self.adjustSize()

        #TODO:
#        self.entree.texte.Bind(wx.EVT_RIGHT_DOWN, self.EvtMenu)
#        self.visualisation.Bind(wx.EVT_RIGHT_DOWN, self.EvtMenuVisualisation)

        self.initialiser()


    def activer(self):
        # Actions à effectuer lorsque l'onglet devient actif
        self.entree.setFocus()


    def _sauvegarder(self, fgeo):
        fgeo.contenu["Calculatrice"] = [{}]
        fgeo.contenu["Calculatrice"][0]["Historique"] = [repr(self.entree.historique)]
#        fgeo.contenu["Calculatrice"][0]["Resultats"] = [repr(self.interprete.derniers_resultats)]
        fgeo.contenu["Calculatrice"][0]["Affichage"] = [self.resultats.toPlainText()]
        fgeo.contenu["Calculatrice"][0]["Etat_interne"] = [self.interprete.save_state()]
        fgeo.contenu["Calculatrice"][0]["Options"] = [{}]
        for i in range(len(self.options)):
            fgeo.contenu["Calculatrice"][0]["Options"][0][self.options[i][1]] = [str(self.options_box[i].isChecked())]



    def _ouvrir(self, fgeo):
        if fgeo.contenu.has_key("Calculatrice"):
            calc = fgeo.contenu["Calculatrice"][0]
            self.initialiser()

            self.entree.historique = eval_safe(calc["Historique"][0])
#            self.interprete.derniers_resultats = securite.eval_safe(calc["Resultats"][0])
            self.resultats.setPlainText(calc["Affichage"][0] + "\n")
            self.interprete.load_state(calc["Etat_interne"][0])

            liste = calc["Options"][0].items()
            options = [option for aide, option in self.options]
            for key, value in liste:
                value = eval_safe(value[0])
                self.param(key, value)
                if key in options:
                    self.options_box[options.index(key)].setChecked(value)
            # il faudrait encore sauvegarder les variables, mais la encore, 2 problemes :
            # - pb de securite pour evaluer les variables
            # - pb pour obtenir le code source d'une fonction.
            # Pour remedier a cela, il faut envisager de :
            # - creer un module d'interpretation securisee.
            # - rajouter a chaque fonction un attribut __code__, ou creer une nouvelle classe.


    def modifier_pp_texte(self, chaine):
        u"""Modifier le résultat affiché en LaTeX (pretty print)."""
        if self.param("latex"):
            chaine = "$" + chaine + "$"
        else:
            chaine = chaine.replace("\\mapsto", "\\rightarrow")
            if chaine.startswith(r"$\begin{bmatrix}"):
                chaine = chaine.replace(r"\begin{bmatrix}", r'\left({')
                chaine = chaine.replace(r"\end{bmatrix}", r'}\right)')
                chaine = chaine.replace(r"&", r'\,')
        self.pp_texte.set_text(chaine)
        self.visualisation.draw()

    def vers_presse_papier(self, event = None, texte = None):
        if texte is None:
            texte = self.dernier_resultat
        Panel_simple.vers_presse_papier(texte)

    def copier_latex(self, event = None):
        self.vers_presse_papier(texte = self.interprete.latex_dernier_resultat.strip("$"))

    def initialiser(self, event = None):
        self.dernier_resultat = "" # dernier resultat, sous forme de chaine formatee pour l'affichage
        self.entree.initialiser()
        self.interprete.initialiser()
        self.resultats.clear()

    def affichage_resultat(self, commande, **kw):
        # Commandes spéciales:
        if commande in ('clear', 'clear()', 'efface', 'efface()'):
            self.initialiser()
            self.modifier_pp_texte(u"Calculatrice réinitialisée.")
            return

        self.modifie = True
        try:
            try:
                if kw["shift"]:
                    self.interprete.calcul_exact = False
                resultat, latex = self.interprete.evaluer(commande)
                if latex == "$?$": # provoque une erreur (matplotlib 0.99.1.1)
                    latex = u"Désolé, je ne sais pas faire..."
            finally:
                self.interprete.calcul_exact = self.param('calcul_exact')
            aide = resultat.startswith("\n== Aide sur ")
            #LaTeX
            debug("Expression LaTeX: " + latex)
            try:
                self.modifier_pp_texte((latex or resultat) if not aide else '')
            except Exception:
                print_error()
                self.modifier_pp_texte("<Affichage impossible>")
            #Presse-papier
            self.dernier_resultat = resultat
            if self.param("copie_automatique"):
                if self.param("copie_automatique_LaTeX"):
                    self.copier_latex()
                else:
                    self.vers_presse_papier()
            # TextCtrl
            numero = str(len(self.interprete.derniers_resultats))
            # Évite le décalage entre la première ligne et les suivantes (matrices)
            if "\n" in resultat and not aide:
                resultat = "\n" + "\n".join(20*" " + ligne for ligne in resultat.split("\n"))
            self.resultats.insertPlainText(u" Calcul n\xb0" + numero + " :   "
                                                        + uu(commande) + u"\n Résultat :"
                                                        + " "*(4+len(numero))
                                                        + resultat + "\n__________________\n\n")
            self.message(u"Calcul effectué." + self.interprete.warning)
            self.entree.clear()
#            self.resultats.setCursorPosition(len(self.resultats.plainText()))
#            self.resultats.setFocus()
#            self.resultats.ScrollLines(1)
            self.entree.setFocus()
        except Exception:
            self.message(u"Calcul impossible.")
            self.entree.setFocus()
            if param.debug:
                raise


    def insere(self, event=None, nom='', parentheses=True):
        entree = self.entree
        deb, fin = entree.getSelection()
        if parentheses:
            entree.setCursorPosition(fin)
            entree.insert(")")
            entree.setCursorPosition(deb)
            entree.insert(nom + "(")
            entree.setFocus()
            if deb == fin:
                final = fin + len(nom) + 1
            else:
                final = fin + len(nom) + 2
        else:
            entree.insert(nom)
            final = fin + len(nom)
        entree.setFocus()
        entree.setCursorPosition(final)


    def EvtMenu(self, event):
#        if not event.ControlDown():
#            event.Skip()
#            return
#            entree.setSelection(final, final)
        menu = QMenu()
        menu.setWindowTitle(u"Fonctions mathématiques")
        debut = True
        for rubrique in __classement__:
            if not debut:
                menu.addSeparator()
            debut = False
            for titre, nom, doc in filter(None, __classement__[rubrique]):
                action = menu.addAction(titre, partial(self.insere, nom=nom, parentheses=(rubrique != "Symboles")))
                # Pas de parenthèses après un symbole.
                action.setToolTip(doc)
        menu.exec_(QCursor.pos())


    def EvtMenuVisualisation(self, event):
        menu = QMenu()
        action = menu.addAction("Copier LaTeX", self.copier_latex)
        action.setToolTip("Copier le code LaTeX dans le presse-papier.")
        menu.exec_(QCursor.pos())
#        self.PopupMenu(menu)
#        menu.Destroy()



    def param(self, parametre, valeur = no_argument, defaut = False):
        if valeur is not no_argument:
            setattr(self.interprete, parametre, valeur)
        return Panel_simple.param(self, parametre = parametre, valeur = valeur, defaut = defaut)

    def EvtCalculExact(self, event = None):
        valeur = self.cb_calcul_exact.isChecked()
        self.param("calcul_exact", not valeur)
        if valeur:
            self.cb_notation_sci.setEnabled(True)
            self.st_notation_sci.setEnabled(True)
            self.sc_decimales.setEnabled(True)
            self.st_decimales.setEnabled(True)
        else:
            self.cb_notation_sci.setEnabled(False)
            self.st_notation_sci.setEnabled(False)
            self.sc_decimales.setEnabled(False)
            self.st_decimales.setEnabled(False)


    def EvtNotationScientifique(self, event = None):
        self.param("ecriture_scientifique", self.cb_notation_sci.isChecked())
        self.param("ecriture_scientifique_decimales", self.sc_decimales.value())

    def EvtCopieAutomatique(self, event = None):
        valeur = self.cb_copie_automatique.isChecked()
        self.param("copie_automatique", valeur)
        if valeur:
            self.cb_copie_automatique_LaTeX.setEnabled(True)
            self.st_copie_automatique_LaTeX.setEnabled(True)
        else:
            self.cb_copie_automatique_LaTeX.setEnabled(False)
            self.st_copie_automatique_LaTeX.setEnabled(False)

    def EvtCopieAutomatiqueLatex(self, event = None):
        self.param("copie_automatique_LaTeX", self.cb_copie_automatique_LaTeX.isChecked())

    def EtatInterne(self, event):
        contenu = self.interprete.save_state()
        h = FenCode(self, u"État interne de l'inteprète", contenu, self.interprete.load_state)
        h.show()
Beispiel #40
0
class FindReplaceBase(QWidget):
    """ Base class for both find and replace widgets """

    maxHistory = 16
    incSearchDone = pyqtSignal(bool)

    def __init__(self, editorsManager, parent=None):

        QWidget.__init__(self, parent)
        self._skip = True

        self.editorsManager = editorsManager
        self._currentWidget = None
        self._isTextEditor = False
        self._editor = None
        self._editorUUID = False
        self.findHistory = GlobalData().project.findHistory
        self._findBackward = False

        # Incremental search support
        self._searchSupport = SearchSupport()
        self.connect(editorsManager, SIGNAL("tabClosed"), self.__onTabClosed)

        # Common graphics items
        self.closeButton = QToolButton(self)
        self.closeButton.setToolTip("Close the dialog (ESC)")
        self.closeButton.setIcon(PixmapCache().getIcon("close.png"))
        self.closeButton.clicked.connect(self.hide)

        self.findLabel = QLabel(self)
        self.findLabel.setText("Find:")

        self.findtextCombo = ComboBoxNoUndo(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.findtextCombo.sizePolicy().hasHeightForWidth())
        self.findtextCombo.setSizePolicy(sizePolicy)
        self.findtextCombo.setEditable(True)
        self.findtextCombo.setInsertPolicy(QComboBox.InsertAtTop)
        self.findtextCombo.setAutoCompletion(False)
        self.findtextCombo.setDuplicatesEnabled(False)
        self.findtextCombo.setEnabled(False)
        self.findtextCombo.editTextChanged.connect(self._onEditTextChanged)

        self.findPrevButton = QToolButton(self)
        self.findPrevButton.setToolTip("Previous occurrence (Shift+F3)")
        self.findPrevButton.setIcon(PixmapCache().getIcon("1leftarrow.png"))
        self.findPrevButton.setIconSize(QSize(24, 16))
        self.findPrevButton.setFocusPolicy(Qt.NoFocus)
        self.findPrevButton.setEnabled(False)

        self.findNextButton = QToolButton(self)
        self.findNextButton.setToolTip("Next occurrence (F3)")
        self.findNextButton.setIcon(PixmapCache().getIcon("1rightarrow.png"))
        self.findNextButton.setIconSize(QSize(24, 16))
        self.findNextButton.setFocusPolicy(Qt.NoFocus)
        self.findNextButton.setEnabled(False)

        self.caseCheckBox = QCheckBox(self)
        self.caseCheckBox.setText("Match case")
        self.caseCheckBox.setFocusPolicy(Qt.NoFocus)
        self.caseCheckBox.setEnabled(False)
        self.caseCheckBox.stateChanged.connect(self._onCheckBoxChange)

        self.wordCheckBox = QCheckBox(self)
        self.wordCheckBox.setText("Whole word")
        self.wordCheckBox.setFocusPolicy(Qt.NoFocus)
        self.wordCheckBox.setEnabled(False)
        self.wordCheckBox.stateChanged.connect(self._onCheckBoxChange)

        self.regexpCheckBox = QCheckBox(self)
        self.regexpCheckBox.setText("Regexp")
        self.regexpCheckBox.setFocusPolicy(Qt.NoFocus)
        self.regexpCheckBox.setEnabled(False)
        self.regexpCheckBox.stateChanged.connect(self._onCheckBoxChange)

        self.findtextCombo.lineEdit().returnPressed.connect(
            self.__findByReturnPressed)
        self._skip = False
        return

    def keyPressEvent(self, event):
        " Handles the ESC key for the search bar "
        if event.key() == Qt.Key_Escape:
            self._searchSupport.clearStartPositions()
            event.accept()
            self.hide()
            activeWindow = self.editorsManager.currentWidget()
            if activeWindow:
                activeWindow.setFocus()
        return

    def __onTabClosed(self, uuid):
        " Triggered when a tab is closed "
        self._searchSupport.delete(uuid)
        return

    def setFocus(self):
        " Overridded setFocus "
        self.findtextCombo.lineEdit().selectAll()
        self.findtextCombo.setFocus()
        return

    def show(self, text=''):
        " Overridden show() method "
        self._skip = True
        self.findtextCombo.clear()
        self.findtextCombo.addItems(self.findHistory)
        self.findtextCombo.setEditText(text)
        self.findtextCombo.lineEdit().selectAll()
        self.regexpCheckBox.setChecked(False)
        self.findtextCombo.setFocus()
        self._findBackward = False
        self._skip = False

        QWidget.show(self)
        self.activateWindow()

        self._performSearch(True)
        return

    def startHiddenSearch(self, text):
        " Initiates search without activating the widget "
        self._skip = True
        self.findtextCombo.clear()
        self.findtextCombo.addItems(self.findHistory)
        self.findtextCombo.setEditText(text)
        self.findtextCombo.lineEdit().selectAll()
        self.regexpCheckBox.setChecked(False)
        self._findBackward = False
        self._skip = False

        self._performSearch(True)
        return

    def updateStatus(self):
        " Triggered when the current tab is changed "

        # Memorize the current environment
        self._currentWidget = self.editorsManager.currentWidget()
        self._isTextEditor = self._currentWidget.getType() in \
                                [ MainWindowTabWidgetBase.PlainTextEditor,
                                  MainWindowTabWidgetBase.VCSAnnotateViewer ]
        if self._isTextEditor:
            self._editor = self._currentWidget.getEditor()
            self._editorUUID = self._currentWidget.getUUID()
        else:
            self._editor = None
            self._editorUUID = ""

        self.findtextCombo.setEnabled(self._isTextEditor)

        textAvailable = self.findtextCombo.currentText() != ""
        self.findPrevButton.setEnabled(self._isTextEditor and textAvailable)
        self.findNextButton.setEnabled(self._isTextEditor and textAvailable)

        self.caseCheckBox.setEnabled(self._isTextEditor)
        self.wordCheckBox.setEnabled(self._isTextEditor)
        self.regexpCheckBox.setEnabled(self._isTextEditor)
        return

    def _resetHighlightOtherEditors(self, uuid):
        " Resets all the highlights in other editors except of the given "
        searchAttributes = None
        if self._searchSupport.hasEditor(uuid):
            searchAttributes = self._searchSupport.get(uuid)

        for key in self._searchSupport.editorSearchAttributes:
            if key == uuid:
                continue
            widget = self.editorsManager.getWidgetByUUID(key)
            if widget is None:
                continue
            editor = widget.getEditor()
            editor.clearSearchIndicators()

        # Clear what is memorized about the other editors
        self._searchSupport.editorSearchAttributes = {}

        if searchAttributes is not None:
            self._searchSupport.add(uuid, searchAttributes)
        return

    def _onCheckBoxChange(self, newState):
        " Triggered when a search check box state is changed "
        if self._skip:
            return
        self._resetHighlightOtherEditors(self._editorUUID)
        self._performSearch(False)
        return

    def _onEditTextChanged(self, text):
        " Triggered when the search text has been changed "
        if self._skip:
            return
        self._resetHighlightOtherEditors(self._editorUUID)
        self._performSearch(False)
        return

    def _performSearch(self, fromScratch):
        " Performs the incremental search "
        if not self._isTextEditor:
            return

        # Memorize the search arguments
        text = self.findtextCombo.currentText()
        isRegexp = self.regexpCheckBox.isChecked()
        isCase = self.caseCheckBox.isChecked()
        isWord = self.wordCheckBox.isChecked()

        status = text != ""
        self.findNextButton.setEnabled(status)
        self.findPrevButton.setEnabled(status)

        if fromScratch:
            self._searchSupport.delete(self._editorUUID)
        self._initialiseSearchAttributes(self._editorUUID)
        searchAttributes = self._searchSupport.get(self._editorUUID)

        if not fromScratch:
            # We've been searching here already
            if text == "":
                # Remove the highlight and scroll back
                self._editor.clearAllIndicators(self._editor.searchIndicator)
                self._editor.clearAllIndicators(self._editor.matchIndicator)

                self._editor.setCursorPosition(searchAttributes.line,
                                               searchAttributes.pos)
                self._editor.ensureLineVisible(searchAttributes.firstLine)
                searchAttributes.match = [-1, -1, -1]
                self.incSearchDone.emit(False)
                return

            matchTarget = self._editor.highlightMatch(text,
                                                      searchAttributes.line,
                                                      searchAttributes.pos,
                                                      isRegexp, isCase, isWord)
            searchAttributes.match = matchTarget
            if matchTarget != [-1, -1, -1]:
                # Select the match starting from the end. This will move the
                # cursor to the beginnig of the match.
                tgtPos = self._editor.positionFromLineIndex(
                    matchTarget[0], matchTarget[1])
                eLine, ePos = self._editor.lineIndexFromPosition(
                    tgtPos + matchTarget[2])
                self._editor.setSelection(eLine, ePos, matchTarget[0],
                                          matchTarget[1])
                self._editor.ensureLineVisible(matchTarget[0])
                self.incSearchDone.emit(True)
            else:
                # Nothing is found, so scroll back to the original
                self._editor.setCursorPosition(searchAttributes.line,
                                               searchAttributes.pos)
                self._editor.ensureLineVisible(searchAttributes.firstLine)
                self.incSearchDone.emit(False)

            return

        # Brand new editor to search in
        if text == "":
            self.incSearchDone.emit(False)
            return

        matchTarget = self._editor.highlightMatch(text, searchAttributes.line,
                                                  searchAttributes.pos,
                                                  isRegexp, isCase, isWord)
        searchAttributes.match = matchTarget
        self._searchSupport.add(self._editorUUID, searchAttributes)

        if matchTarget != [-1, -1, -1]:
            # Select the match starting from the end. This will move the
            # cursor to the beginnig of the match.
            tgtPos = self._editor.positionFromLineIndex(
                matchTarget[0], matchTarget[1])
            eLine, ePos = self._editor.lineIndexFromPosition(tgtPos +
                                                             matchTarget[2])
            self._editor.setSelection(eLine, ePos, matchTarget[0],
                                      matchTarget[1])
            self._editor.ensureLineVisible(matchTarget[0])
            self.incSearchDone.emit(True)
            return

        self.incSearchDone.emit(False)
        return

    def _initialiseSearchAttributes(self, uuid):
        " Creates a record if none existed "
        if self._searchSupport.hasEditor(uuid):
            return

        searchAttributes = SearchAttr()
        searchAttributes.line = self._currentWidget.getLine()
        searchAttributes.pos = self._currentWidget.getPos()
        searchAttributes.firstLine = self._editor.firstVisibleLine()

        searchAttributes.match = [-1, -1, -1]
        self._searchSupport.add(uuid, searchAttributes)
        return

    def _advanceMatchIndicator(self, uuid, newLine, newPos, newLength):
        " Advances the current match indicator for the given editor "

        if not self._searchSupport.hasEditor(uuid):
            return

        searchAttributes = self._searchSupport.get(uuid)
        match = searchAttributes.match

        widget = self.editorsManager.getWidgetByUUID(uuid)
        if widget is None:
            return
        editor = widget.getEditor()

        # Replace the old highlight
        if searchAttributes.match != [-1, -1, -1]:
            tgtPos = editor.positionFromLineIndex(match[0], match[1])
            editor.clearIndicatorRange(editor.matchIndicator, tgtPos, match[2])
            editor.setIndicatorRange(editor.searchIndicator, tgtPos, match[2])

        # Memorise new target
        searchAttributes.match = [newLine, newPos, newLength]
        self._searchSupport.add(uuid, searchAttributes)

        # Update the new highlight
        tgtPos = editor.positionFromLineIndex(newLine, newPos)
        editor.clearIndicatorRange(editor.searchIndicator, tgtPos, newLength)
        editor.setIndicatorRange(editor.matchIndicator, tgtPos, newLength)

        # Select the match from end to the start - this will move the
        # cursor to the first symbol of the match
        eLine, ePos = editor.lineIndexFromPosition(tgtPos + newLength)
        editor.setSelection(eLine, ePos, newLine, newPos)

        # Move the cursor to the new match
        editor.ensureLineVisible(newLine)
        return

    def onNext(self, clearSBMessage=True):
        " Triggered when the find next is clicked "
        if not self.onPrevNext():
            return

        self._findBackward = False
        if not self.__findNextPrev(clearSBMessage):
            GlobalData().mainWindow.showStatusBarMessage(
                "The '" + self.findtextCombo.currentText() +
                "' was not found.", 0)
            self.incSearchDone.emit(False)
        else:
            self.incSearchDone.emit(True)
        return

    def onPrev(self, clearSBMessage=True):
        " Triggered when the find prev is clicked "
        if not self.onPrevNext():
            return

        self._findBackward = True
        if not self.__findNextPrev(clearSBMessage):
            GlobalData().mainWindow.showStatusBarMessage(
                "The '" + self.findtextCombo.currentText() +
                "' was not found.", 0)
            self.incSearchDone.emit(False)
        else:
            self.incSearchDone.emit(True)
        return

    def onPrevNext(self):
        """ Checks prerequisites, saves the history and
            returns True if the search should be done """
        txt = self.findtextCombo.currentText()
        if txt == "":
            return False

        currentWidget = self.editorsManager.currentWidget()
        if currentWidget.getType() not in \
                    [ MainWindowTabWidgetBase.PlainTextEditor,
                      MainWindowTabWidgetBase.VCSAnnotateViewer ]:
            return False

        return True

    def __findByReturnPressed(self):
        " Triggered when 'Enter' or 'Return' is clicked "
        if self._findBackward:
            self.onPrev()
        else:
            self.onNext()
        return

    def __findNextPrev(self, clearSBMessage=True):
        " Finds the next occurrence of the search text "
        if not self._isTextEditor:
            return False

        # Identify the search start point
        startLine = self._currentWidget.getLine()
        startPos = self._currentWidget.getPos()

        if self._searchSupport.hasEditor(self._editorUUID):
            searchAttributes = self._searchSupport.get(self._editorUUID)
            if startLine == searchAttributes.match[ 0 ] and \
               startPos == searchAttributes.match[ 1 ]:
                # The cursor is on the current match, i.e. the user did not
                # put the focus into the editor and did not move it
                if not self._findBackward:
                    # The match[ 2 ] gives the length in bytes, not in chars
                    # which could be national i.e. multibytes. So calc the
                    # right length in chars...
                    pos = self._editor.positionFromLineIndex(
                        startLine, startPos)
                    adjustment = len(
                        self._editor.stringAt(pos, searchAttributes.match[2]))
                    startPos = startPos + adjustment
            else:
                # The cursor is not at the same position as the last match,
                # i.e. the user moved it some way
                # Update the search attributes as if a new search is started
                searchAttributes.line = startLine
                searchAttributes.pos = startPos
                searchAttributes.firstLine = self._editor.firstVisibleLine()
                searchAttributes.match = [-1, -1, -1]
                self._searchSupport.add(self._editorUUID, searchAttributes)
        else:
            # There were no search in this editor
            searchAttributes = SearchAttr()
            searchAttributes.line = startLine
            searchAttributes.pos = startPos
            searchAttributes.firstLine = self._editor.firstVisibleLine()
            searchAttributes.match = [-1, -1, -1]
            self._searchSupport.add(self._editorUUID, searchAttributes)

        # Here: start point has been identified
        if self.__searchFrom(startLine, startPos, clearSBMessage):
            # Something new has been found - change the start pos
            searchAttributes = self._searchSupport.get(self._editorUUID)
            searchAttributes.line = self._currentWidget.getLine()
            searchAttributes.pos = self._currentWidget.getPos()
            searchAttributes.firstLine = self._editor.firstVisibleLine()
            self._searchSupport.add(self._editorUUID, searchAttributes)
            return True

        return False

    def __searchFrom(self, startLine, startPos, clearSBMessage=True):
        " Searches starting from the given position "

        # Memorize the search arguments
        text = self.findtextCombo.currentText()
        isRegexp = self.regexpCheckBox.isChecked()
        isCase = self.caseCheckBox.isChecked()
        isWord = self.wordCheckBox.isChecked()

        if not self._findBackward:
            # Search forward
            self._editor.highlightMatch(text, startLine, startPos, isRegexp,
                                        isCase, isWord, False, False)
            targets = self._editor.getTargets(text, isRegexp, isCase, isWord,
                                              startLine, startPos, -1, -1)
            if len(targets) == 0:
                GlobalData().mainWindow.showStatusBarMessage(
                    "Reached the end of the document. "
                    "Searching from the beginning...", 0)
                targets = self._editor.getTargets(text, isRegexp, isCase,
                                                  isWord, 0, 0, startLine,
                                                  startPos)
                if len(targets) == 0:
                    searchAttributes = self._searchSupport.get(
                        self._editorUUID)
                    searchAttributes.match = [-1, -1, -1]
                    self._searchSupport.add(self._editorUUID, searchAttributes)
                    return False  # Nothing has matched
            else:
                if clearSBMessage:
                    # Hide the 'reached the end of ...' message
                    GlobalData().mainWindow.clearStatusBarMessage(0)

            # Move the highlight and the cursor to the new match and
            # memorize a new match
            self._advanceMatchIndicator(self._editorUUID, targets[0][0],
                                        targets[0][1], targets[0][2])
            return True

        # Search backward
        self._editor.highlightMatch(text, startLine, startPos, isRegexp,
                                    isCase, isWord, False, False)
        targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0,
                                          startLine, startPos)
        if len(targets) == 0:
            GlobalData().mainWindow.showStatusBarMessage(
                "Reached the beginning of the document. "
                "Searching from the end...", 0)
            targets = self._editor.getTargets(text, isRegexp, isCase, isWord,
                                              startLine, startPos, -1, -1)
            if len(targets) == 0:
                searchAttributes = self._searchSupport.get(self._editorUUID)
                searchAttributes.match = [-1, -1, -1]
                self._searchSupport.add(self._editorUUID, searchAttributes)
                return False  # Nothing has matched
        else:
            if clearSBMessage:
                # Hide the 'reached the beginning of ...' message
                GlobalData().mainWindow.clearStatusBarMessage(0)

        # Move the highlight and the cursor to the new match and
        # memorize a new match
        index = len(targets) - 1
        self._advanceMatchIndicator(self._editorUUID, targets[index][0],
                                    targets[index][1], targets[index][2])
        return True

    def _addToHistory(self, combo, history, text):
        " Adds the item to the history. Returns true if need to add. "
        text = str(text)
        changes = False

        if text in history:
            if history[0] != text:
                changes = True
                history.remove(text)
                history.insert(0, text)
        else:
            changes = True
            history.insert(0, text)

        if len(history) > self.maxHistory:
            changes = True
            history = history[:self.maxHistory]

        self._skip = True
        combo.clear()
        combo.addItems(history)
        self._skip = False
        return changes

    def getLastSearchString(self):
        " Provides the string which was searched last time "
        return self.findtextCombo.currentText()
class Ventana(QWidget):
	'''
	Ventana de interfaz grafica para la aplicacion
	'''

	def __init__(self):
		super(Ventana, self).__init__()
		
		self._CLIENTE = "Cliente"
		self._SERVIDOR = "Servidor"
		
		self.rol = ""
		self.pasos = []
		self.mensaje = []
		
		self.labelSemanticaT = QLabel("Semantica: ")
		self.labelSemanticaR = QLabel("Semantica: ")
		self.labelSemanticaT.adjustSize()
		self.labelSemanticaR.adjustSize()
		
		#campos de texto transmisor
		self.textoMensajeT = QLineEdit()
		self.textoFramesT = QLineEdit("1")
		self.textoIndicador1T = QLineEdit()
		self.textoACKT = QLineEdit()
		self.textoENQT = QLineEdit()
		self.textoCTRT = QLineEdit()
		self.textoDATT = QLineEdit()
		self.textoPPTT = QLineEdit()
		self.textoLPRT = QLineEdit()
		self.textoNUMT = QLineEdit()
		self.textoInfoT = QLineEdit()
		self.textoIndicador2T = QLineEdit()
		
		#Selectores de campos de control
		self.checkACK = QCheckBox()
		self.checkENQ = QCheckBox()
		self.checkCTR = QCheckBox()
		self.checkDAT = QCheckBox()
		self.checkPPT = QCheckBox()
		self.checkLPR = QCheckBox()
		
		#boton de transmision
		self.botonTransmisor = QPushButton("ENVIAR")
		
		#campos de texto receptor
		self.textoIndicador1R = QLineEdit()
		self.textoACKR = QLineEdit()
		self.textoENQR = QLineEdit()
		self.textoCTRR = QLineEdit()
		self.textoDATR = QLineEdit()
		self.textoPPTR = QLineEdit()
		self.textoLPRR = QLineEdit()
		self.textoNUMR = QLineEdit()
		self.textoInfoR = QLineEdit()
		self.textoIndicador2R = QLineEdit()
		self.textoMensajeR = QLineEdit()
			
		#boton de respuesta
		self.botonRecibir = QPushButton("RECIBIR")
		self.trama = Trama()
		self.trama_anterior = None
		self.transmisor = Transmisor()
		self._inicializar()
				
	def _inicializar(self):
		self.setWindowTitle("Protocolo de transmision de datos")
		
		#------------------------------------#
		#		ELEMENTOS DEL TRANSMISOR	 #
		#------------------------------------#
		
		#Etiquetas transmisor
		tituloT = QLabel("TRANSMISION")
		labelMensajeT = QLabel("Mensaje a transmitir:")
		labelFramesT = QLabel("Numero de frames:")
		labelIndicador1T = QLabel("INDICADOR")
		labelACKT = QLabel("ACK")
		labelENQT = QLabel("ENQ")
		labelCTRT = QLabel("CTR")
		labelDATT = QLabel("DAT")
		labelPPTT = QLabel("PPT")
		labelLPRT = QLabel("LPR")
		labelNUMT = QLabel("NUM")
		labelInfoT = QLabel("INFORMACION")
		labelIndicador2T = QLabel("INDICADOR")
				
		tituloT.adjustSize()
		labelMensajeT.adjustSize()
		labelFramesT.adjustSize()
		labelIndicador1T.adjustSize()
		labelACKT.adjustSize()
		labelENQT.adjustSize()
		labelCTRT.adjustSize()
		labelDATT.adjustSize()
		labelPPTT.adjustSize()
		labelLPRT.adjustSize()
		labelNUMT.adjustSize()
		labelInfoT.adjustSize()
		labelIndicador2T.adjustSize()
			
		#agregar los elementos al segundo nivel de layout
		fila1 = QHBoxLayout()
		fila2 = QHBoxLayout()
		fila3 = QHBoxLayout()
		fila4 = QHBoxLayout()
		cajaTransmisor = QVBoxLayout()
		
		fila1.addWidget(tituloT)
		fila2.addWidget(labelMensajeT)
		fila2.addWidget(self.textoMensajeT)
		fila2.addWidget(labelFramesT)
		fila2.addWidget(self.textoFramesT)
		fila4.addWidget(self.labelSemanticaT)
		
		fila3_1 = QVBoxLayout()
		fila3_2 = QVBoxLayout()
		fila3_3 = QVBoxLayout()
		fila3_4 = QVBoxLayout()
		fila3_5 = QVBoxLayout()
		fila3_6 = QVBoxLayout()
		fila3_7 = QVBoxLayout()
		fila3_8 = QVBoxLayout()
		fila3_9 = QVBoxLayout()
		fila3_10 = QVBoxLayout()
		
		fila3_1.addWidget(labelIndicador1T)
		fila3_1.addWidget(self.textoIndicador1T)
		fila3_1.setAlignment(Qt.AlignTop)
		fila3_2.addWidget(labelACKT)
		fila3_2.addWidget(self.textoACKT)
		fila3_2.addWidget(self.checkACK)
		fila3_3.addWidget(labelENQT)
		fila3_3.addWidget(self.textoENQT)
		fila3_3.addWidget(self.checkENQ)
		fila3_4.addWidget(labelCTRT)
		fila3_4.addWidget(self.textoCTRT)
		fila3_4.addWidget(self.checkCTR)
		fila3_5.addWidget(labelDATT)
		fila3_5.addWidget(self.textoDATT)
		fila3_5.addWidget(self.checkDAT)
		fila3_6.addWidget(labelPPTT)
		fila3_6.addWidget(self.textoPPTT)
		fila3_6.addWidget(self.checkPPT)
		fila3_7.addWidget(labelLPRT)
		fila3_7.addWidget(self.textoLPRT)
		fila3_7.addWidget(self.checkLPR)
		fila3_8.addWidget(labelNUMT)
		fila3_8.addWidget(self.textoNUMT)
		fila3_8.setAlignment(Qt.AlignTop)
		fila3_9.addWidget(labelInfoT)
		fila3_9.addWidget(self.textoInfoT)
		fila3_9.setAlignment(Qt.AlignTop)
		fila3_10.addWidget(labelIndicador2T)
		fila3_10.addWidget(self.textoIndicador2T)
		fila3_10.setAlignment(Qt.AlignTop)
		fila3.addLayout(fila3_1)
		fila3.addLayout(fila3_2)
		fila3.addLayout(fila3_3)
		fila3.addLayout(fila3_4)
		fila3.addLayout(fila3_5)
		fila3.addLayout(fila3_6)
		fila3.addLayout(fila3_7)
		fila3.addLayout(fila3_8)
		fila3.addLayout(fila3_9)
		fila3.addLayout(fila3_10)
		fila3.addWidget(self.botonTransmisor)
		
		cajaTransmisor.addLayout(fila1)
		cajaTransmisor.addLayout(fila2)
		cajaTransmisor.addLayout(fila3)
		cajaTransmisor.addLayout(fila4)
		
		#------------------------------------#
		#		ELEMENTOS DEL RECEPTOR		 #
		#------------------------------------#
		
		#Etiquetas receptor
		tituloR = QLabel("RECEPCION")
		labelFrameR = QLabel("Trama recibida:")
		labelRespuestaR = QLabel("Recibido: ")
		labelIndicador1R = QLabel("INDICADOR")
		labelACKR = QLabel("ACK")
		labelENQR = QLabel("ENQ")
		labelCTRR = QLabel("CTR")
		labelDATR = QLabel("DAT")
		labelPPTR = QLabel("PPT")
		labelLPRR = QLabel("LPR")
		labelNUMR = QLabel("NUM")
		labelInfoR = QLabel("INFORMACION")
		labelIndicador2R = QLabel("INDICADOR")
		labelMensajeR = QLabel("Mensaje recibido:")
		
		tituloR.adjustSize()
		labelFrameR.adjustSize()
		labelRespuestaR.adjustSize()
		labelIndicador1R.adjustSize()
		labelACKR.adjustSize()
		labelENQR.adjustSize()
		labelCTRR.adjustSize()
		labelDATR.adjustSize()
		labelPPTR.adjustSize()
		labelLPRR.adjustSize()
		labelNUMR.adjustSize()
		labelInfoR.adjustSize()
		labelIndicador2R.adjustSize()
		labelMensajeR.adjustSize()
				
		#agregar los elementos al segundo nivel de layout
		fila5 = QHBoxLayout()
		fila6 = QHBoxLayout()
		fila8 = QHBoxLayout()
		fila9 = QHBoxLayout()
		fila10 = QHBoxLayout()
		fila11 = QHBoxLayout()
		cajaReceptor = QVBoxLayout()
				
		fila5.addWidget(tituloR)
		fila6.addWidget(labelFrameR)
		fila8.addWidget(labelRespuestaR)
		
		#fila9
		fila9_1 = QVBoxLayout()
		fila9_2 = QVBoxLayout()
		fila9_3 = QVBoxLayout()
		fila9_4 = QVBoxLayout()
		fila9_5 = QVBoxLayout()
		fila9_6 = QVBoxLayout()
		fila9_7 = QVBoxLayout()
		fila9_8 = QVBoxLayout()
		fila9_9 = QVBoxLayout()
		fila9_10 = QVBoxLayout()
		
		fila9_1.addWidget(labelIndicador1R)
		fila9_1.addWidget(self.textoIndicador1R)
		fila9_2.addWidget(labelACKR)
		fila9_2.addWidget(self.textoACKR)
		fila9_3.addWidget(labelENQR)
		fila9_3.addWidget(self.textoENQR)
		fila9_4.addWidget(labelCTRR)
		fila9_4.addWidget(self.textoCTRR)
		fila9_5.addWidget(labelDATR)
		fila9_5.addWidget(self.textoDATR)
		fila9_6.addWidget(labelPPTR)
		fila9_6.addWidget(self.textoPPTR)
		fila9_7.addWidget(labelLPRR)
		fila9_7.addWidget(self.textoLPRR)
		fila9_8.addWidget(labelNUMR)
		fila9_8.addWidget(self.textoNUMR)
		fila9_9.addWidget(labelInfoR)
		fila9_9.addWidget(self.textoInfoR)
		fila9_10.addWidget(labelIndicador2R)
		fila9_10.addWidget(self.textoIndicador2R)
		
		fila9.addLayout(fila9_1)
		fila9.addLayout(fila9_2)
		fila9.addLayout(fila9_3)
		fila9.addLayout(fila9_4)
		fila9.addLayout(fila9_5)
		fila9.addLayout(fila9_6)
		fila9.addLayout(fila9_7)
		fila9.addLayout(fila9_8)
		fila9.addLayout(fila9_9)
		fila9.addLayout(fila9_10)
		fila9.addWidget(self.botonRecibir)
		
		fila10.addWidget(self.labelSemanticaR)
		fila11.addWidget(labelMensajeR)
		fila11.addWidget(self.textoMensajeR)
		
		cajaReceptor.addLayout(fila5)
		cajaReceptor.addLayout(fila6)
		cajaReceptor.addLayout(fila8)
		cajaReceptor.addLayout(fila9)
		cajaReceptor.addLayout(fila10)
		cajaReceptor.addLayout(fila11)
		
		#------------------------------------#
				
		#agregar el segundo nivel de layout al panel
		panelTransmisor = QFrame(self)
		panelTransmisor.setFrameShape(QFrame.StyledPanel)
		panelTransmisor.setLayout(cajaTransmisor)
		
		#agregar el segundo nivel de layout al panel
		panelReceptor = QFrame(self)
		panelReceptor.setFrameShape(QFrame.StyledPanel)
		panelReceptor.setLayout(cajaReceptor)
		
		#agregar el panel al separador
		separador = QSplitter(Qt.Vertical)
		separador.addWidget(panelTransmisor)
		separador.addWidget(panelReceptor)
		
		#agregar el separador al primer layout
		caja = QVBoxLayout(self)
		caja.addWidget(separador)
		
		#agregar el layout a la ventana
		self.setLayout(caja)
		
		self.setFixedSize(800, 400)
		self._configurar()
		self.show()
		self.crear_conexion()
		
	def _configurar(self):
		
		self.textoIndicador1T.setEnabled(False)
		self.textoACKT.setEnabled(False)
		self.textoENQT.setEnabled(False)
		self.textoCTRT.setEnabled(False)
		self.textoDATT.setEnabled(False)
		self.textoPPTT.setEnabled(False)
		self.textoLPRT.setEnabled(False)
		self.textoNUMT.setEnabled(False)
		self.textoInfoT.setEnabled(False)
		self.textoIndicador2T.setEnabled(False)
		
		self.textoIndicador1R.setEnabled(False)
		self.textoACKR.setEnabled(False)
		self.textoENQR.setEnabled(False)
		self.textoCTRR.setEnabled(False)
		self.textoDATR.setEnabled(False)
		self.textoPPTR.setEnabled(False)
		self.textoLPRR.setEnabled(False)
		self.textoNUMR.setEnabled(False)
		self.textoInfoR.setEnabled(False)
		self.textoIndicador2R.setEnabled(False)
		self.textoMensajeR.setEnabled(False)
		
		self.checkACK.setEnabled(False)
		self.checkENQ.setEnabled(False)
		self.checkPPT.setEnabled(False)
		self.checkLPR.setEnabled(False)
		
		self.checkACK.stateChanged.connect(self._seleccionarACK)
		self.checkENQ.stateChanged.connect(self._seleccionarENQ)
		self.checkCTR.stateChanged.connect(self._seleccionarCTR)
		self.checkDAT.stateChanged.connect(self._seleccionarDAT)
		self.checkPPT.stateChanged.connect(self._seleccionarPPT)
		self.checkLPR.stateChanged.connect(self._seleccionarLPR)
		self.botonTransmisor.clicked.connect(self._enviar_mensaje)
		self.botonRecibir.clicked.connect(self._recibir_mensaje)
		
		self._mostrar_trama(self._SERVIDOR)
		
	def _seleccionarACK(self, estado):
		if estado == Qt.Checked:
			self.textoACKT.setText("1")
			self.checkPPT.setChecked(False)
			self.checkLPR.setChecked(False)
		else:
			self.textoACKT.setText("0")
		
	def _seleccionarENQ(self, estado):
		if estado == Qt.Checked:
			self.textoENQT.setText("1")
		else:
			self.textoENQT.setText("0")
		
	def _seleccionarCTR(self, estado):
		if estado == Qt.Checked:
			self.textoCTRT.setText("1")
			self.checkDAT.setChecked(False)
			self.checkACK.setEnabled(True)
			self.checkPPT.setEnabled(True)
			self.checkLPR.setEnabled(True)
		else:
			self.textoCTRT.setText("0")
			self.checkACK.setChecked(False)
			self.checkPPT.setChecked(False)
			self.checkLPR.setChecked(False)
			self.checkACK.setEnabled(False)
			self.checkPPT.setEnabled(False)
			self.checkLPR.setEnabled(False)
			self.checkENQ.setEnabled(False)
			
	def _seleccionarDAT(self, estado):
		if estado == Qt.Checked:
			self.textoDATT.setText("1")
			self.checkCTR.setChecked(False)
			self.checkENQ.setEnabled(True)
		else:
			self.textoDATT.setText("0")
			self.checkENQ.setChecked(False)
			self.checkENQ.setEnabled(False)
			
	def _seleccionarPPT(self, estado):
		if estado == Qt.Checked:
			self.textoPPTT.setText("1")
			self.checkACK.setChecked(False)
			self.checkLPR.setChecked(False)
		else:
			self.textoPPTT.setText("0")
			
	def _seleccionarLPR(self, estado):
		
		if estado == Qt.Checked:
			self.textoLPRT.setText("1")
			self.checkACK.setChecked(False)
			self.checkPPT.setChecked(False)
		else:
			self.textoLPRT.setText("0")
			
	def crear_conexion(self):
		tipo = QInputDialog.getItem(self, "Tipo de usuario", "usuario", ["" ,self._SERVIDOR, self._CLIENTE])
		self.rol = str(tipo[0])
		self.setWindowTitle("Protocolo de transmision de datos  --" + self.rol)
		if self.rol == self._SERVIDOR:
			port = QInputDialog.getInt(self, "ingrese puerto", "Puerto", 56032)
			nom = self.transmisor.crear_servidor(port[0])
			msg = QMessageBox.information(self, "Servidor", "El nombre del servidor es: " + nom)
			del msg
			if self.transmisor.conectar_servidor():
				resp = QMessageBox.information(self, "Conectado", "Se ha establecido la conexion con el cliente")
				del resp
		elif self.rol == self._CLIENTE:
			host = QInputDialog.getText(self, "ingrese host", "Host")
			port = QInputDialog.getInt(self, "ingrese puerto", "Puerto", 56032)
			self.transmisor.conectar_cliente((str(host[0]), port[0]))
		else:
			self.destroy()
			
	def _enviar_mensaje(self):
		self.trama_anterior = self.trama
		if not self.pasos:
			if self.trama.esPPT():			
				self._generar_trama()
				if self.trama.esLPR():
					self.pasos.append("LPR")
					self.transmisor.enviar(self.trama())
					self._mostrar_trama(self._SERVIDOR)
				else:
					err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
					self.trama = self.trama_anterior
			elif self.trama.esNull():
				self._generar_trama()
				if self.trama.esPPT():
					self.pasos.append("PPT")
					self.transmisor.enviar(self.trama())
					self._mostrar_trama(self._SERVIDOR)
				else:
					err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
					self.trama = self.trama_anterior
			else:
				err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
		elif "PPT" in self.pasos:
			if self.trama.esLPR() or self.trama.esACK():
				cant = int(self.textoFramesT.text())
				if not self.mensaje:
					self._preparar_mensaje(cant)
				self._generar_trama()
				if self.trama.esDAT():
					if len(self.mensaje)>1:
						self.trama.INFO = self.mensaje.pop(0)
						self.trama.NUM = str(cant - len(self.mensaje))
						self.transmisor.enviar(self.trama())
						self._mostrar_trama(self._SERVIDOR)
					else:
						err = QMessageBox.information(self, "Error", "Ultima trama, envie ENQ")
						self.trama = self.trama_anterior
						del err
				elif self.trama.esENQ():
					if len(self.mensaje)>1:
						err = QMessageBox.information(self, "Error", "Faltan mas tramas, envie DAT")
						self.trama = self.trama_anterior
						del err
					else:
						self.trama.INFO = self.mensaje.pop(0)
						self.trama.NUM = str(cant)
						self.transmisor.enviar(self.trama())
						self.pasos.append("ENQ")
						self.pasos.remove("PPT")
						self._mostrar_trama(self._SERVIDOR)
			else:
				err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
		elif "LPR" in self.pasos:
			if self.trama.esDAT() or self.trama.esENQ():
				self._generar_trama()
				if self.trama.esACK():
					self.trama.INFO=""
					self.transmisor.enviar(self.trama())
					self._mostrar_trama(self._SERVIDOR)
				else:
					err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
					self.trama = self.trama_anterior
					del err
			else:
				err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
		elif "ENQ" in self.pasos:
			if self.trama.esACK():
				err = QMessageBox.information(self, "Terminado", "El mensaje se ha entregado por completo")
				self.textoMensajeT.clear()
				self.textoFramesT.clear()
				self.textoMensajeT.setEnabled(True)
				self.textoFramesT.setEnabled(True)
				self.trama = Trama()
				self.pasos.remove("ENQ")
				self._mostrar_trama(self._SERVIDOR)
			elif self.trama.esENQ():
				self._generar_trama()
				if self.trama.esACK():
					self.trama.INFO=""
					self.transmisor.enviar(self.trama())
					self._mostrar_trama(self._SERVIDOR)
				else:
					err = QMessageBox.information(self, "Error", "Trama fuera de contexto")
					self.trama = self.trama_anterior
					del err
			else:
				err = QMessageBox.information(self, "Error", "Trama fuera de contexto")

	def _recibir_mensaje(self):
		self.trama_anterior = self.trama
		msg = self.transmisor.recibir()
		if len(msg)!=0:
			datos = list(msg.split(self.trama.INDICADOR)[1])
			self.trama.ACK = datos.pop(0)
			self.trama.ENQ = datos.pop(0)
			self.trama.CTR = datos.pop(0)
			self.trama.DAT = datos.pop(0)
			self.trama.PPT = datos.pop(0)
			self.trama.LPR = datos.pop(0)
			self.trama.NUM = datos.pop(0)
			self.trama.INFO = "".join(datos)
			self._mostrar_trama(self._CLIENTE)
			if self.trama.esDAT():
				self.textoMensajeR.setText(self.textoMensajeR.text()+self.trama.INFO)
			elif self.trama.esENQ():
				self.textoMensajeR.setText(self.textoMensajeR.text()+self.trama.INFO)
				self.pasos.remove("LPR")
				self.pasos.append("ENQ")
				err = QMessageBox.information(self, "Terminado", "El mensaje se ha recibido por completo")
			elif self.trama.esPPT():
				self.textoMensajeR.clear()
			elif self.trama.esACK():
				if "ENQ" in self.pasos:
					err = QMessageBox.information(self, "Terminado", "El mensaje se ha entregado por completo")
		else:
			err = QMessageBox.information(self, "Error", "Se ha perdido la conexion")
			del err

	def _preparar_mensaje(self, cant):
		self.textoMensajeT.setEnabled(False)
		self.textoFramesT.setEnabled(False)
		men = str(self.textoMensajeT.text())
		tam = len(men)/cant + 1
		for i in range(cant):
			self.mensaje.append(men[(i*tam):(i+1)*tam])

	def _generar_trama(self):
		self.trama.ACK = str(self.textoACKT.text())
		self.trama.ENQ = str(self.textoENQT.text())
		self.trama.CTR = str(self.textoCTRT.text())
		self.trama.DAT = str(self.textoDATT.text())
		self.trama.PPT = str(self.textoPPTT.text())
		self.trama.LPR = str(self.textoLPRT.text())
		self.trama.NUM = str(self.textoNUMT.text())
		self.trama.INFO = str(self.textoInfoT.text())

	def _mostrar_trama(self, tipo):
		if tipo == self._CLIENTE:
			self.textoIndicador1R.setText(self.trama.INDICADOR)
			self.textoACKR.setText(self.trama.ACK)
			self.textoENQR.setText(self.trama.ENQ)
			self.textoCTRR.setText(self.trama.CTR)
			self.textoDATR.setText(self.trama.DAT)
			self.textoPPTR.setText(self.trama.PPT)
			self.textoLPRR.setText(self.trama.LPR)
			self.textoNUMR.setText(self.trama.NUM)
			self.textoInfoR.setText(self.trama.INFO)
			self.textoIndicador2R.setText(self.trama.INDICADOR)
		elif tipo == self._SERVIDOR:
			self.textoIndicador1T.setText(self.trama.INDICADOR)
			self.textoACKT.setText(self.trama.ACK)
			self.textoENQT.setText(self.trama.ENQ)
			self.textoCTRT.setText(self.trama.CTR)
			self.textoDATT.setText(self.trama.DAT)
			self.textoPPTT.setText(self.trama.PPT)
			self.textoLPRT.setText(self.trama.LPR)
			self.textoNUMT.setText(self.trama.NUM)
			self.textoInfoT.setText(self.trama.INFO)
			self.textoIndicador2T.setText(self.trama.INDICADOR)
		self._actualizar_semantica(tipo)

	def _actualizar_semantica(self, tipo):
		if tipo == self._CLIENTE:
			if self.trama.esACK():
				self.labelSemanticaR.setText("Semantica: Trama de control, recibio con exito.")
			elif self.trama.esPPT():
				self.labelSemanticaR.setText("Semantica: Trama de control, permiso para transmitir.")
			elif self.trama.esLPR():
				self.labelSemanticaR.setText("Semantica: Trama de control, listo para recibir.")
			elif self.trama.esDAT():
				self.labelSemanticaR.setText("Semantica: Trama de datos.")
			elif self.trama.esENQ():
				self.labelSemanticaR.setText("Semantica: Trama de datos, ultima trama")
			elif self.trama.esNull():
				self.labelSemanticaR.setText("Semantica:")
			self.labelSemanticaR.adjustSize()
		elif tipo == self._SERVIDOR:
			if self.trama.esACK():
				self.labelSemanticaT.setText("Semantica: Trama de control, recibio con exito.")
			elif self.trama.esPPT():
				self.labelSemanticaT.setText("Semantica: Trama de control, permiso para transmitir.")
			elif self.trama.esLPR():
				self.labelSemanticaT.setText("Semantica: Trama de control, listo para recibir.")
			elif self.trama.esDAT():
				self.labelSemanticaT.setText("Semantica: Trama de datos.")
			elif self.trama.esENQ():
				self.labelSemanticaT.setText("Semantica: Trama de datos, ultima trama")
			elif self.trama.esNull():
				self.labelSemanticaT.setText("Semantica:")
			self.labelSemanticaT.adjustSize()
class FindReplaceBase(QWidget):
    """ Base class for both find and replace widgets """

    maxHistory = 16
    incSearchDone = pyqtSignal(bool)

    def __init__(self, editorsManager, parent=None):

        QWidget.__init__(self, parent)
        self._skip = True

        self.editorsManager = editorsManager
        self._currentWidget = None
        self._isTextEditor = False
        self._editor = None
        self._editorUUID = False
        self.findHistory = GlobalData().project.findHistory
        self._findBackward = False

        # Incremental search support
        self._searchSupport = SearchSupport()
        self.connect(editorsManager, SIGNAL("tabClosed"), self.__onTabClosed)

        # Common graphics items
        self.closeButton = QToolButton(self)
        self.closeButton.setToolTip("Close the dialog (ESC)")
        self.closeButton.setIcon(PixmapCache().getIcon("close.png"))
        self.closeButton.clicked.connect(self.hide)

        self.findLabel = QLabel(self)
        self.findLabel.setText("Find:")

        self.findtextCombo = ComboBoxNoUndo(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.findtextCombo.sizePolicy().hasHeightForWidth())
        self.findtextCombo.setSizePolicy(sizePolicy)
        self.findtextCombo.setEditable(True)
        self.findtextCombo.setInsertPolicy(QComboBox.InsertAtTop)
        self.findtextCombo.setAutoCompletion(False)
        self.findtextCombo.setDuplicatesEnabled(False)
        self.findtextCombo.setEnabled(False)
        self.findtextCombo.editTextChanged.connect(self._onEditTextChanged)

        self.findPrevButton = QToolButton(self)
        self.findPrevButton.setToolTip("Previous occurrence (Shift+F3)")
        self.findPrevButton.setIcon(PixmapCache().getIcon("1leftarrow.png"))
        self.findPrevButton.setIconSize(QSize(24, 16))
        self.findPrevButton.setFocusPolicy(Qt.NoFocus)
        self.findPrevButton.setEnabled(False)

        self.findNextButton = QToolButton(self)
        self.findNextButton.setToolTip("Next occurrence (F3)")
        self.findNextButton.setIcon(PixmapCache().getIcon("1rightarrow.png"))
        self.findNextButton.setIconSize(QSize(24, 16))
        self.findNextButton.setFocusPolicy(Qt.NoFocus)
        self.findNextButton.setEnabled(False)

        self.caseCheckBox = QCheckBox(self)
        self.caseCheckBox.setText("Match case")
        self.caseCheckBox.setFocusPolicy(Qt.NoFocus)
        self.caseCheckBox.setEnabled(False)
        self.caseCheckBox.stateChanged.connect(self._onCheckBoxChange)

        self.wordCheckBox = QCheckBox(self)
        self.wordCheckBox.setText("Whole word")
        self.wordCheckBox.setFocusPolicy(Qt.NoFocus)
        self.wordCheckBox.setEnabled(False)
        self.wordCheckBox.stateChanged.connect(self._onCheckBoxChange)

        self.regexpCheckBox = QCheckBox(self)
        self.regexpCheckBox.setText("Regexp")
        self.regexpCheckBox.setFocusPolicy(Qt.NoFocus)
        self.regexpCheckBox.setEnabled(False)
        self.regexpCheckBox.stateChanged.connect(self._onCheckBoxChange)

        self.findtextCombo.lineEdit().returnPressed.connect(self.__findByReturnPressed)
        self._skip = False
        return

    def keyPressEvent(self, event):
        " Handles the ESC key for the search bar "
        if event.key() == Qt.Key_Escape:
            self._searchSupport.clearStartPositions()
            event.accept()
            self.hide()
            activeWindow = self.editorsManager.currentWidget()
            if activeWindow:
                activeWindow.setFocus()
        return

    def __onTabClosed(self, uuid):
        " Triggered when a tab is closed "
        self._searchSupport.delete(uuid)
        return

    def setFocus(self):
        " Overridded setFocus "
        self.findtextCombo.lineEdit().selectAll()
        self.findtextCombo.setFocus()
        return

    def show(self, text=""):
        " Overridden show() method "
        self._skip = True
        self.findtextCombo.clear()
        self.findtextCombo.addItems(self.findHistory)
        self.findtextCombo.setEditText(text)
        self.findtextCombo.lineEdit().selectAll()
        self.regexpCheckBox.setChecked(False)
        self.findtextCombo.setFocus()
        self._findBackward = False
        self._skip = False

        QWidget.show(self)
        self.activateWindow()

        self._performSearch(True)
        return

    def startHiddenSearch(self, text):
        " Initiates search without activating the widget "
        self._skip = True
        self.findtextCombo.clear()
        self.findtextCombo.addItems(self.findHistory)
        self.findtextCombo.setEditText(text)
        self.findtextCombo.lineEdit().selectAll()
        self.regexpCheckBox.setChecked(False)
        self._findBackward = False
        self._skip = False

        self._performSearch(True)
        return

    def updateStatus(self):
        " Triggered when the current tab is changed "

        # Memorize the current environment
        self._currentWidget = self.editorsManager.currentWidget()
        self._isTextEditor = self._currentWidget.getType() in [
            MainWindowTabWidgetBase.PlainTextEditor,
            MainWindowTabWidgetBase.VCSAnnotateViewer,
        ]
        if self._isTextEditor:
            self._editor = self._currentWidget.getEditor()
            self._editorUUID = self._currentWidget.getUUID()
        else:
            self._editor = None
            self._editorUUID = ""

        self.findtextCombo.setEnabled(self._isTextEditor)

        textAvailable = self.findtextCombo.currentText() != ""
        self.findPrevButton.setEnabled(self._isTextEditor and textAvailable)
        self.findNextButton.setEnabled(self._isTextEditor and textAvailable)

        self.caseCheckBox.setEnabled(self._isTextEditor)
        self.wordCheckBox.setEnabled(self._isTextEditor)
        self.regexpCheckBox.setEnabled(self._isTextEditor)
        return

    def _resetHighlightOtherEditors(self, uuid):
        " Resets all the highlights in other editors except of the given "
        searchAttributes = None
        if self._searchSupport.hasEditor(uuid):
            searchAttributes = self._searchSupport.get(uuid)

        for key in self._searchSupport.editorSearchAttributes:
            if key == uuid:
                continue
            widget = self.editorsManager.getWidgetByUUID(key)
            if widget is None:
                continue
            editor = widget.getEditor()
            editor.clearSearchIndicators()

        # Clear what is memorized about the other editors
        self._searchSupport.editorSearchAttributes = {}

        if searchAttributes is not None:
            self._searchSupport.add(uuid, searchAttributes)
        return

    def _onCheckBoxChange(self, newState):
        " Triggered when a search check box state is changed "
        if self._skip:
            return
        self._resetHighlightOtherEditors(self._editorUUID)
        self._performSearch(False)
        return

    def _onEditTextChanged(self, text):
        " Triggered when the search text has been changed "
        if self._skip:
            return
        self._resetHighlightOtherEditors(self._editorUUID)
        self._performSearch(False)
        return

    def _performSearch(self, fromScratch):
        " Performs the incremental search "
        if not self._isTextEditor:
            return

        # Memorize the search arguments
        text = self.findtextCombo.currentText()
        isRegexp = self.regexpCheckBox.isChecked()
        isCase = self.caseCheckBox.isChecked()
        isWord = self.wordCheckBox.isChecked()

        status = text != ""
        self.findNextButton.setEnabled(status)
        self.findPrevButton.setEnabled(status)

        if fromScratch:
            self._searchSupport.delete(self._editorUUID)
        self._initialiseSearchAttributes(self._editorUUID)
        searchAttributes = self._searchSupport.get(self._editorUUID)

        if not fromScratch:
            # We've been searching here already
            if text == "":
                # Remove the highlight and scroll back
                self._editor.clearAllIndicators(self._editor.searchIndicator)
                self._editor.clearAllIndicators(self._editor.matchIndicator)

                self._editor.setCursorPosition(searchAttributes.line, searchAttributes.pos)
                self._editor.ensureLineVisible(searchAttributes.firstLine)
                searchAttributes.match = [-1, -1, -1]
                self.incSearchDone.emit(False)
                return

            matchTarget = self._editor.highlightMatch(
                text, searchAttributes.line, searchAttributes.pos, isRegexp, isCase, isWord
            )
            searchAttributes.match = matchTarget
            if matchTarget != [-1, -1, -1]:
                # Select the match starting from the end. This will move the
                # cursor to the beginnig of the match.
                tgtPos = self._editor.positionFromLineIndex(matchTarget[0], matchTarget[1])
                eLine, ePos = self._editor.lineIndexFromPosition(tgtPos + matchTarget[2])
                self._editor.setSelection(eLine, ePos, matchTarget[0], matchTarget[1])
                self._editor.ensureLineVisible(matchTarget[0])
                self.incSearchDone.emit(True)
            else:
                # Nothing is found, so scroll back to the original
                self._editor.setCursorPosition(searchAttributes.line, searchAttributes.pos)
                self._editor.ensureLineVisible(searchAttributes.firstLine)
                self.incSearchDone.emit(False)

            return

        # Brand new editor to search in
        if text == "":
            self.incSearchDone.emit(False)
            return

        matchTarget = self._editor.highlightMatch(
            text, searchAttributes.line, searchAttributes.pos, isRegexp, isCase, isWord
        )
        searchAttributes.match = matchTarget
        self._searchSupport.add(self._editorUUID, searchAttributes)

        if matchTarget != [-1, -1, -1]:
            # Select the match starting from the end. This will move the
            # cursor to the beginnig of the match.
            tgtPos = self._editor.positionFromLineIndex(matchTarget[0], matchTarget[1])
            eLine, ePos = self._editor.lineIndexFromPosition(tgtPos + matchTarget[2])
            self._editor.setSelection(eLine, ePos, matchTarget[0], matchTarget[1])
            self._editor.ensureLineVisible(matchTarget[0])
            self.incSearchDone.emit(True)
            return

        self.incSearchDone.emit(False)
        return

    def _initialiseSearchAttributes(self, uuid):
        " Creates a record if none existed "
        if self._searchSupport.hasEditor(uuid):
            return

        searchAttributes = SearchAttr()
        searchAttributes.line = self._currentWidget.getLine()
        searchAttributes.pos = self._currentWidget.getPos()
        searchAttributes.firstLine = self._editor.firstVisibleLine()

        searchAttributes.match = [-1, -1, -1]
        self._searchSupport.add(uuid, searchAttributes)
        return

    def _advanceMatchIndicator(self, uuid, newLine, newPos, newLength):
        " Advances the current match indicator for the given editor "

        if not self._searchSupport.hasEditor(uuid):
            return

        searchAttributes = self._searchSupport.get(uuid)
        match = searchAttributes.match

        widget = self.editorsManager.getWidgetByUUID(uuid)
        if widget is None:
            return
        editor = widget.getEditor()

        # Replace the old highlight
        if searchAttributes.match != [-1, -1, -1]:
            tgtPos = editor.positionFromLineIndex(match[0], match[1])
            editor.clearIndicatorRange(editor.matchIndicator, tgtPos, match[2])
            editor.setIndicatorRange(editor.searchIndicator, tgtPos, match[2])

        # Memorise new target
        searchAttributes.match = [newLine, newPos, newLength]
        self._searchSupport.add(uuid, searchAttributes)

        # Update the new highlight
        tgtPos = editor.positionFromLineIndex(newLine, newPos)
        editor.clearIndicatorRange(editor.searchIndicator, tgtPos, newLength)
        editor.setIndicatorRange(editor.matchIndicator, tgtPos, newLength)

        # Select the match from end to the start - this will move the
        # cursor to the first symbol of the match
        eLine, ePos = editor.lineIndexFromPosition(tgtPos + newLength)
        editor.setSelection(eLine, ePos, newLine, newPos)

        # Move the cursor to the new match
        editor.ensureLineVisible(newLine)
        return

    def onNext(self, clearSBMessage=True):
        " Triggered when the find next is clicked "
        if not self.onPrevNext():
            return

        self._findBackward = False
        if not self.__findNextPrev(clearSBMessage):
            GlobalData().mainWindow.showStatusBarMessage(
                "The '" + self.findtextCombo.currentText() + "' was not found.", 0
            )
            self.incSearchDone.emit(False)
        else:
            self.incSearchDone.emit(True)
        return

    def onPrev(self, clearSBMessage=True):
        " Triggered when the find prev is clicked "
        if not self.onPrevNext():
            return

        self._findBackward = True
        if not self.__findNextPrev(clearSBMessage):
            GlobalData().mainWindow.showStatusBarMessage(
                "The '" + self.findtextCombo.currentText() + "' was not found.", 0
            )
            self.incSearchDone.emit(False)
        else:
            self.incSearchDone.emit(True)
        return

    def onPrevNext(self):
        """ Checks prerequisites, saves the history and
            returns True if the search should be done """
        txt = self.findtextCombo.currentText()
        if txt == "":
            return False

        currentWidget = self.editorsManager.currentWidget()
        if currentWidget.getType() not in [
            MainWindowTabWidgetBase.PlainTextEditor,
            MainWindowTabWidgetBase.VCSAnnotateViewer,
        ]:
            return False

        return True

    def __findByReturnPressed(self):
        " Triggered when 'Enter' or 'Return' is clicked "
        if self._findBackward:
            self.onPrev()
        else:
            self.onNext()
        return

    def __findNextPrev(self, clearSBMessage=True):
        " Finds the next occurrence of the search text "
        if not self._isTextEditor:
            return False

        # Identify the search start point
        startLine = self._currentWidget.getLine()
        startPos = self._currentWidget.getPos()

        if self._searchSupport.hasEditor(self._editorUUID):
            searchAttributes = self._searchSupport.get(self._editorUUID)
            if startLine == searchAttributes.match[0] and startPos == searchAttributes.match[1]:
                # The cursor is on the current match, i.e. the user did not
                # put the focus into the editor and did not move it
                if not self._findBackward:
                    # The match[ 2 ] gives the length in bytes, not in chars
                    # which could be national i.e. multibytes. So calc the
                    # right length in chars...
                    pos = self._editor.positionFromLineIndex(startLine, startPos)
                    adjustment = len(self._editor.stringAt(pos, searchAttributes.match[2]))
                    startPos = startPos + adjustment
            else:
                # The cursor is not at the same position as the last match,
                # i.e. the user moved it some way
                # Update the search attributes as if a new search is started
                searchAttributes.line = startLine
                searchAttributes.pos = startPos
                searchAttributes.firstLine = self._editor.firstVisibleLine()
                searchAttributes.match = [-1, -1, -1]
                self._searchSupport.add(self._editorUUID, searchAttributes)
        else:
            # There were no search in this editor
            searchAttributes = SearchAttr()
            searchAttributes.line = startLine
            searchAttributes.pos = startPos
            searchAttributes.firstLine = self._editor.firstVisibleLine()
            searchAttributes.match = [-1, -1, -1]
            self._searchSupport.add(self._editorUUID, searchAttributes)

        # Here: start point has been identified
        if self.__searchFrom(startLine, startPos, clearSBMessage):
            # Something new has been found - change the start pos
            searchAttributes = self._searchSupport.get(self._editorUUID)
            searchAttributes.line = self._currentWidget.getLine()
            searchAttributes.pos = self._currentWidget.getPos()
            searchAttributes.firstLine = self._editor.firstVisibleLine()
            self._searchSupport.add(self._editorUUID, searchAttributes)
            return True

        return False

    def __searchFrom(self, startLine, startPos, clearSBMessage=True):
        " Searches starting from the given position "

        # Memorize the search arguments
        text = self.findtextCombo.currentText()
        isRegexp = self.regexpCheckBox.isChecked()
        isCase = self.caseCheckBox.isChecked()
        isWord = self.wordCheckBox.isChecked()

        if not self._findBackward:
            # Search forward
            self._editor.highlightMatch(text, startLine, startPos, isRegexp, isCase, isWord, False, False)
            targets = self._editor.getTargets(text, isRegexp, isCase, isWord, startLine, startPos, -1, -1)
            if len(targets) == 0:
                GlobalData().mainWindow.showStatusBarMessage(
                    "Reached the end of the document. " "Searching from the beginning...", 0
                )
                targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0, startLine, startPos)
                if len(targets) == 0:
                    searchAttributes = self._searchSupport.get(self._editorUUID)
                    searchAttributes.match = [-1, -1, -1]
                    self._searchSupport.add(self._editorUUID, searchAttributes)
                    return False  # Nothing has matched
            else:
                if clearSBMessage:
                    # Hide the 'reached the end of ...' message
                    GlobalData().mainWindow.clearStatusBarMessage(0)

            # Move the highlight and the cursor to the new match and
            # memorize a new match
            self._advanceMatchIndicator(self._editorUUID, targets[0][0], targets[0][1], targets[0][2])
            return True

        # Search backward
        self._editor.highlightMatch(text, startLine, startPos, isRegexp, isCase, isWord, False, False)
        targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0, startLine, startPos)
        if len(targets) == 0:
            GlobalData().mainWindow.showStatusBarMessage(
                "Reached the beginning of the document. " "Searching from the end...", 0
            )
            targets = self._editor.getTargets(text, isRegexp, isCase, isWord, startLine, startPos, -1, -1)
            if len(targets) == 0:
                searchAttributes = self._searchSupport.get(self._editorUUID)
                searchAttributes.match = [-1, -1, -1]
                self._searchSupport.add(self._editorUUID, searchAttributes)
                return False  # Nothing has matched
        else:
            if clearSBMessage:
                # Hide the 'reached the beginning of ...' message
                GlobalData().mainWindow.clearStatusBarMessage(0)

        # Move the highlight and the cursor to the new match and
        # memorize a new match
        index = len(targets) - 1
        self._advanceMatchIndicator(self._editorUUID, targets[index][0], targets[index][1], targets[index][2])
        return True

    def _addToHistory(self, combo, history, text):
        " Adds the item to the history. Returns true if need to add. "
        text = str(text)
        changes = False

        if text in history:
            if history[0] != text:
                changes = True
                history.remove(text)
                history.insert(0, text)
        else:
            changes = True
            history.insert(0, text)

        if len(history) > self.maxHistory:
            changes = True
            history = history[: self.maxHistory]

        self._skip = True
        combo.clear()
        combo.addItems(history)
        self._skip = False
        return changes

    def getLastSearchString(self):
        " Provides the string which was searched last time "
        return self.findtextCombo.currentText()
class NetWorkSettingWidget(QWidget):

    def __init__(self, app, parent = None):
        super(NetWorkSettingWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px;")
        self.app = app
        CDLL("../lib/libjson-c.so", mode=RTLD_GLOBAL)
        self.jytcapi = cdll.LoadLibrary('../lib/libjytcapi.so')
        self.jytcapi.jyinittcapi()
        self.initLayout()

        self.initCheckBoxStatus()

        self.restartNetworkTD = RestartNetworkThread()
        self.waitingDlg = InfoHintDialog(None)

        #绑定信号
        self.connect(self.autoGetIpCheckbox, SIGNAL("stateChanged(int)"),self.slotSettingDHCPType)

        self.connect(self.staticIpGroupbox, SIGNAL("clicked(bool)"),self.slotSettingStaticType)

        self.connect(self.autoGetDNSCheckBox, SIGNAL("stateChanged(int)"),self.slotSettingDNSType)

        self.connect(self.dnsServerAddressGroupbox, SIGNAL("clicked(bool)"),self.slotSettingCustomDNSType)

        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)

        self.connect(self.restartNetworkTD, SIGNAL("restartNetwork"),self.slotShowRestartNetworkInfo)

    def initLayout(self):
        #IP设置
        self.autoGetIpCheckbox = QCheckBox(self.tr("Auto get IP"))

        self.staticIpGroupbox = QGroupBox(self.tr("Use this IP"))
        self.staticIpGroupbox.setCheckable(True)

        self.ipLabel = QLabel(self.tr("IP address"))
        self.netmastLabel = QLabel(self.tr("Net mask"))
        self.defaultGatewayLabel = QLabel(self.tr("Default gateway"))

        topSpaceWidget = QLabel()
        topSpaceWidget.setFixedHeight(1)

        self.ip = QLineEdit()
        self.ip.setContextMenuPolicy(Qt.NoContextMenu)
        self.ip.setFixedSize(400, 30)
        self.netmast = QLineEdit()
        self.netmast.setContextMenuPolicy(Qt.NoContextMenu)
        self.defaultGateway = QLineEdit()
        self.defaultGateway.setContextMenuPolicy(Qt.NoContextMenu)

        topGridLayout = QGridLayout()
        topGridLayout.setSpacing(15)
        topGridLayout.setMargin(20)
        topGridLayout.addWidget(self.ipLabel, 0, 0, 1, 1)
        topGridLayout.addWidget(self.ip, 0, 1, 1, 1)
        topGridLayout.addWidget(self.netmastLabel, 1, 0, 1, 1)
        topGridLayout.addWidget(self.netmast, 1, 1, 1, 1)
        topGridLayout.addWidget(self.defaultGatewayLabel, 2, 0, 1, 1)
        topGridLayout.addWidget(self.defaultGateway, 2, 1, 1, 1)
        topGridLayout.addWidget(topSpaceWidget, 3, 0, 1, 1)

        self.staticIpGroupbox.setLayout(topGridLayout)

        #DNS设置
        self.autoGetDNSCheckBox = QCheckBox(self.tr("Auto Get DNS"))

        self.dnsServerAddressGroupbox = QGroupBox(self.tr("Use This DNS"))
        self.dnsServerAddressGroupbox.setCheckable(True)

        self.dnsLabel = QLabel(self.tr("DNS"))
        self.backupDnsLabel = QLabel(self.tr("Backup DNS"))

        bottomSpaceWidget = QLabel()
        bottomSpaceWidget.setFixedHeight(1)

        self.dns = QLineEdit()
        self.dns.setContextMenuPolicy(Qt.NoContextMenu)
        self.backupDns = QLineEdit()
        self.backupDns.setContextMenuPolicy(Qt.NoContextMenu)

        self.saveBtn = QPushButton(self.tr("Save"))
        self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;")

        bottomGridLayout = QGridLayout()
        bottomGridLayout.setSpacing(15)
        bottomGridLayout.setMargin(20)
        bottomGridLayout.addWidget(self.dnsLabel, 0, 0, 1, 1)
        bottomGridLayout.addWidget(self.dns, 0, 1, 1, 1)
        bottomGridLayout.addWidget(self.backupDnsLabel, 1, 0, 1, 1)
        bottomGridLayout.addWidget(self.backupDns, 1, 1, 1, 1)
        bottomGridLayout.addWidget(bottomSpaceWidget, 2, 0, 1, 1)

        self.dnsServerAddressGroupbox.setLayout(bottomGridLayout)

        #布局调整
        vLayout = QVBoxLayout()
        vLayout.setSpacing(10)
        vLayout.setMargin(10)

        vLayout.addWidget(self.autoGetIpCheckbox)
        vLayout.addWidget(self.staticIpGroupbox)
        vLayout.addSpacing(15)
        vLayout.addWidget(self.autoGetDNSCheckBox)
        vLayout.addWidget(self.dnsServerAddressGroupbox)
        vLayout.addStretch()

        topMainLayout = QHBoxLayout()
        topMainLayout.addStretch()
        topMainLayout.addSpacing(50)
        topMainLayout.addLayout(vLayout)
        topMainLayout.addStretch(2)

        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.saveBtn)
        bottomHLayout.addStretch()

        mainVLayout = QVBoxLayout()
        mainVLayout.addLayout(topMainLayout)
        mainVLayout.addSpacing(10)
        mainVLayout.addLayout(bottomHLayout)

        self.setLayout(mainVLayout)
        
    def updateWindow(self):
        self.autoGetDNSCheckBox.setText(self.tr("Auto Get DNS"))
        self.autoGetIpCheckbox.setText(self.tr("Auto get IP"))
        self.dnsServerAddressGroupbox.setTitle(self.tr("Use This DNS"))
        self.staticIpGroupbox.setTitle(self.tr("Use this IP"))
        self.ipLabel.setText(self.tr("IP address"))
        self.netmastLabel.setText(self.tr("Net mask"))
        self.defaultGatewayLabel.setText(self.tr("Gate way"))
        self.dnsLabel.setText(self.tr("DNS"))
        self.backupDnsLabel.setText(self.tr("Backup DNS"))
        self.saveBtn.setText(self.tr("Save"))

    def slotShowRestartNetworkInfo(self, status):
        """显示重启网络的状态信息"""
            
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        """显示重启网络的状态信息"""
        
        if status == "Start":
            self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting..."))
        elif status == "Success":
            self.waitingDlg.setHintInfo(self.tr("network start success!"))
            vmtype = StoreInfoParser.instance().getVmType()
            if vmtype == "offline":
                pass 
        elif status == "Failed":
            self.waitingDlg.setHintInfo(self.tr("network restart failed!"))
        else:
            return
        
        if self.waitingDlg.isHidden():
            self.waitingDlg.exec_()

    def slotSave(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
            
        if not self.checkInputValid():
            return

        if self.autoGetIpCheckbox.isChecked():
            netconf = self.setDynamicNetwork()
        elif self.staticIpGroupbox.isChecked():
            netconf = self.setStaticNetwork()

        #重新启动网络
        self.restartNetworkTD.setNetConf(netconf)
        self.restartNetworkTD.start()

        return

    def getCmdExecValueT(self, cmd):
        """得到命令执行的结果"""
        statusOutput = commands.getstatusoutput(cmd)
        monitorList = statusOutput[1].split("\n")
        return monitorList

    def getNetDnsType(self):
        typeList = ["dhcp","dhcp"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "conf":
                    if item.split(":")[1] == "0":
                        typeList[0] = "dhcp"
                    else:
                        typeList[0] = "static"
                else:
                    pass
        DNSStatus = StoreInfoParser.instance().getDNSStatus()
        if DNSStatus == None:
            pass
        else:
            typeList[1] = DNSStatus
        return typeList

    def getNetStatic(self):
        netList = ["0.0.0.0","255.255.255.0","1.1.1.1"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "ip":
                    netList[0] = item.split(":")[1] 
                elif item.split(":")[0] == "mask":
                    netList[1] = item.split(":")[1] 
                elif item.split(":")[0] == "gateway":
                    netList[2] = item.split(":")[1] 
        return netList

    def getDnsStatic(self):
        dnsList = ["0.0.0.0","2.5.5.0"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "dns1":
                    dnsList[0] = item.split(":")[1] 
                elif item.split(":")[0] == "dns2":
                    dnsList[1] = item.split(":")[1] 
        return dnsList


    def initCheckBoxStatus(self):
        """读取网络配置文件,初始化相应的checkbox的状态"""
        [netType, DNSType] = self.getNetDnsType()
        if netType == "dhcp":
            self.autoGetIpCheckbox.setChecked(True)
            self.staticIpGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.dnsServerAddressGroupbox.setEnabled(False)
        else:
            self.autoGetIpCheckbox.setChecked(False)
            self.staticIpGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.dnsServerAddressGroupbox.setEnabled(True)
            [ip, netmask, gateway] = self.getNetStatic()
            if ip:
                self.ip.setText(ip)

            if netmask:
                self.netmast.setText(netmask)

            if gateway:
                self.defaultGateway.setText(gateway)


        if DNSType == "dhcp":
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            [DNS_first, DNS_second] = self.getDnsStatic()
            if DNS_first:
                self.dns.setText(DNS_first)

            if DNS_second:
                self.backupDns.setText(DNS_second)


    def getCustomDNSInfo(self):
        """得到自定义DNS的内容"""
        DNS_first = None
        DNS_second = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split(" ")[0] == "dns-nameservers":
                    DNS_first = value.split(" ")[1]
                    if len(value.split(" ")) > 2:
                        DNS_second = value.split(" ")[2]

        return [DNS_first, DNS_second]


    def getStaticNetworkInfo(self):
        """得到静态网络的信息"""
        ip = netmask = gateway = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split(" ")[0] == "address":
                    ip = value.split(" ")[1]
                elif value.split(" ")[0] == "netmask":
                    netmask = value.split(" ")[1]
                elif value.split(" ")[0] == "gateway":
                    gateway = value.split(" ")[1]

        return [ip, netmask, gateway]

    def getNetworkType(self):
        """得到网络是静态还是动态类型"""
        netType = None
        DNSType = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            output = QString(statusOutput[1])
            if output.contains("dhcp"):
                netType = "dhcp"
            else:
                netType = "static"

            if output.contains("dns-nameservers"):
                DNSType = "customDNS"
            else:
                DNSType = "AUTODNS"

        return [netType, DNSType]

    def checkInputValid(self):
        """检测输入的有效性"""
        if self.checkStaticIPInputValid() and self.checkDnsInputValid():
            return True
        return False

    def checkStaticIPInputValid(self):
        """检查静态IP输入内容的有效性"""
        ip = self.ip.text().trimmed()
        netmask = self.netmast.text().trimmed()
        gateway = self.defaultGateway.text().trimmed()

        if not self.autoGetIpCheckbox.isChecked():
            if ip.isEmpty() or ip.isNull() or netmask.isEmpty() or netmask.isNull():
                InfoHintDialog(u'IP地址或子网掩码不能为空').exec_()
                return False

            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, ip)
            if matchObj is None:
                InfoHintDialog(u'IP地址格式有误,请重新填入').exec_()
                self.ip.setFocus()
                return False

            matchObj = re.match(pattern, str(netmask))
            if matchObj is None:
                InfoHintDialog(u'子网掩码地址格式有误,请重新填入').exec_()
                self.netmast.setFocus()
                return False

            if gateway:
                matchObj = re.match(pattern, str(gateway))
                if matchObj is None:
                    InfoHintDialog(u'网关地址格式有误,请重新填入').exec_()
                    self.netmast.setFocus()
                    return False

        return True

    def checkDnsInputValid(self):
        """检查DNS输入的内容的有效性"""
        if not self.autoGetDNSCheckBox.isChecked():
            dns = self.dns.text().trimmed()
            backupDns = self.backupDns.text().trimmed()
            if dns.isEmpty() or dns.isNull():
                InfoHintDialog(u'DNS不能为空').exec_()
                return False

            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, str(dns))
            if matchObj is None:
                InfoHintDialog(u'DNS地址格式有误,请重新填入').exec_()
                self.dns.setFocus()
                return False

            if backupDns:
                matchObj = re.match(pattern, str(backupDns))
                if matchObj is None:
                    InfoHintDialog(u'备用DNS地址格式有误,请重新填入').exec_()
                    self.backupDns.setFocus()
                    return False
            return True
        else:
            return True

    def slotSettingDNSType(self, status):
        if status == Qt.Checked:
            self.dnsServerAddressGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.dnsServerAddressGroupbox.setChecked(True)

    def slotSettingCustomDNSType(self, status):
        if status:
            self.autoGetDNSCheckBox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(True)

    def slotSettingDHCPType(self, status):
        if status == Qt.Checked:
            self.staticIpGroupbox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.dnsServerAddressGroupbox.setEnabled(False)
        elif status == Qt.Unchecked:
            self.staticIpGroupbox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setEnabled(True)



    def slotSettingStaticType(self, status):
        if status:
            self.autoGetIpCheckbox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setEnabled(True)
        else:
            self.autoGetIpCheckbox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setEnabled(False)
 

    def setDynamicNetwork(self):
        """设置动态网络的信息到配置文件"""
        netconf="conf=0&ip=&mask=&gateway="
        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
            if not backupDns:
                netconf = netconf + "&dns1=" + dns 
            else:
                netconf = netconf + "&dns1=" + dns + "&dns2=" + backupDns 
            StoreInfoParser.instance().setDNSStatus("static")
        else:
            netconf = netconf + "&dns1=&dns2=" 
            StoreInfoParser.instance().setDNSStatus("dhcp")
        return netconf 
    def setStaticNetwork(self):
        """设置静态网络的信息到配置文件"""

        IPADDR = str(self.ip.text().trimmed())
        NETMASK = str(self.netmast.text().trimmed())
        GATEWAY = str(self.defaultGateway.text().trimmed())
        content = None
        if not GATEWAY:
            content = "conf=1&ip=%s&mask=%s&gateway=" % (IPADDR, NETMASK)
        else:
            content = "conf=1&ip=%s&mask=%s&gateway=%s" % (IPADDR, NETMASK, GATEWAY)

        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
            if not backupDns:
                content = content + "&dns1=" + dns 
            else:
                content = content + "&dns1=" + dns + "&dns2=" + backupDns 
            StoreInfoParser.instance().setDNSStatus("static")
        else:
            content = content + "&dns1=&dns2="
            StoreInfoParser.instance().setDNSStatus("dhcp")
        return content 
Beispiel #44
0
class GithubRepoWizardPage(QWizardPage):
    def __init__(self, github, parent=None):
        super(GithubRepoWizardPage,
              self).__init__(parent,
                             title="Github Repository",
                             subTitle="Configure the new Github repository")

        self.github = github

        # moreButton

        self.moreButton = QPushButton("More",
                                      checkable=True,
                                      clicked=self.more)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        moreButtonHBox = QHBoxLayout()
        moreButtonHBox.addWidget(spacer)
        moreButtonHBox.addWidget(self.moreButton)

        #  LineEdits

        self.nameEdit = QLineEdit(textChanged=self.update)
        self.nameEdit.setValidator(
            QRegExpValidator(QRegExp(r'[a-zA-Z0-9-_]+[a-zA-Z0-9-_]*')))
        self.descriptionEdit = QLineEdit(textChanged=self.update)
        self.homepageEdit = QLineEdit(textChanged=self.update)

        # CheckBox

        self.privateCheckBox = QCheckBox(stateChanged=self.update)
        self.initCheckBox = QCheckBox(stateChanged=self.update)
        self.hasWikiCheckBox = QCheckBox(stateChanged=self.update)
        self.hasDownloadsCheckBox = QCheckBox(stateChanged=self.update)
        self.hasIssuesCheckBox = QCheckBox(stateChanged=self.update)

        # gitignoreComboBox

        self.gitignoreComboBox = QComboBox(currentIndexChanged=self.update)
        self.gitignoreComboBox.addItem('None')
        for i in gitignore_types(self.github):
            self.gitignoreComboBox.addItem(i)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(
            QLabel('Initialize this repository with a README and .gitignore'))
        hbox2.addWidget(self.initCheckBox)

        # Extension Form

        self.form_extension = QFormLayout()
        self.form_extension.addRow("Homepage", self.homepageEdit)
        self.form_extension.addRow("Has wiki", self.hasWikiCheckBox)
        self.form_extension.addRow("Has issues", self.hasIssuesCheckBox)
        self.form_extension.addRow("Has downloads", self.hasDownloadsCheckBox)

        # Extension

        self.extension = QWidget()
        self.extension.setLayout(self.form_extension)

        # Form

        self.form = QFormLayout()
        self.form.addRow("Name: ", self.nameEdit)
        self.form.addRow("Description: ", self.descriptionEdit)
        self.form.addRow('Private', self.privateCheckBox)
        self.form.addRow(hbox2)
        self.form.addRow('Add .gitignore', self.gitignoreComboBox)
        self.form.addRow(moreButtonHBox)
        self.form.addRow(self.extension)

        # Layout

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.form)
        self.setLayout(self.mainLayout)

        # Fields

        self.registerField('name*', self.nameEdit)
        self.registerField('description', self.descriptionEdit)
        self.registerField('private', self.privateCheckBox)
        self.registerField('auto_init', self.initCheckBox)
        self.registerField('gitignore', self.gitignoreComboBox, 'currentText')
        self.registerField('homepage', self.homepageEdit)
        self.registerField('has_issues', self.hasIssuesCheckBox)
        self.registerField('has_downloads', self.hasDownloadsCheckBox)
        self.registerField('has_wiki', self.hasWikiCheckBox)

        # Setup

        self.hasWikiCheckBox.toggle()
        self.hasDownloadsCheckBox.toggle()
        self.hasIssuesCheckBox.toggle()
        if not self.github.get_user().plan:
            self.privateCheckBox.setEnabled(False)

        self.extension.hide()

    def update(self):

        if self.initCheckBox.isChecked():
            self.gitignoreComboBox.setEnabled(True)
        else:
            self.gitignoreComboBox.setEnabled(False)

    def more(self):

        if self.moreButton.isChecked():
            self.moreButton.setText("Less")
            self.extension.show()
            self.wizard().resize(self.wizard().sizeHint())
        else:
            self.moreButton.setText("More")
            self.extension.hide()
            size = self.sizeHint()
            wizard_size = self.wizard().sizeHint()
            self.wizard().resize(wizard_size.width(), size.height())