Ejemplo n.º 1
0
 def _build_field(self):
     #build option
     if self.option.is_compound:
         #make container
         container = QGroupBox(self.title, self.parent)
         container.setToolTip(self.option.formatted_desc)
         layout    = QGridLayout(container)
         self._addRow(container, self.parent.layout())
         #make option
         if not self.option.is_poly or self.value_required or self.field is not None:
             field = dict((opt.name, Field(opt, container)) for opt in self.option.options)
             self._add_or_set('container', container)
             self._add_or_set('field', field)
         #add +/- buttons if poly-option
         if self.option.is_poly:
             new_row = layout.rowCount()
             if self.field is not None and len(self.field) > int(self.value_required):
                 del_button = QPushButton('-', container)
                 del_button.setToolTip('Delete this %s' % self.title)
                 del_option_gui = trigger(self._del_instance, self.field[-1], self.container[-1])
                 del_button.clicked.connect(del_option_gui)
                 layout.addWidget(del_button, new_row, 0)
             add_button = QPushButton('+', container)
             add_button.setToolTip('Add another %s' % self.title)
             add_button.clicked.connect(self._add_instance)
             layout.addWidget(add_button, new_row, 1)
     else: 
         field = self._make_simple_field(self.option, self.parent)
         self._add_or_set('field', field)
Ejemplo n.º 2
0
 def _build_field(self):
     #build option
     if self.option.is_compound:
         #make container
         container = QGroupBox(self.title, self.parent)
         container.setToolTip(self.option.formatted_desc)
         layout = QGridLayout(container)
         self._addRow(container, self.parent.layout())
         #make option
         if not self.option.is_poly or self.value_required or self.field is not None:
             field = dict((opt.name, Field(opt, container))
                          for opt in self.option.options)
             self._add_or_set('container', container)
             self._add_or_set('field', field)
         #add +/- buttons if poly-option
         if self.option.is_poly:
             new_row = layout.rowCount()
             if self.field is not None and len(self.field) > int(
                     self.value_required):
                 del_button = QPushButton('-', container)
                 del_button.setToolTip('Delete this %s' % self.title)
                 del_option_gui = trigger(self._del_instance,
                                          self.field[-1],
                                          self.container[-1])
                 del_button.clicked.connect(del_option_gui)
                 layout.addWidget(del_button, new_row, 0)
             add_button = QPushButton('+', container)
             add_button.setToolTip('Add another %s' % self.title)
             add_button.clicked.connect(self._add_instance)
             layout.addWidget(add_button, new_row, 1)
     else:
         field = self._make_simple_field(self.option, self.parent)
         self._add_or_set('field', field)
Ejemplo n.º 3
0
    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])
Ejemplo n.º 4
0
 def create_fontgroup(self, option=None, text=None,
                      tip=None, fontfilters=None):
     """Option=None -> setting plugin font"""
     fontlabel = QLabel(_("Font: "))
     fontbox = QFontComboBox()
     if fontfilters is not None:
         fontbox.setFontFilters(fontfilters)
     sizelabel = QLabel("  "+_("Size: "))
     sizebox = QSpinBox()
     sizebox.setRange(7, 100)
     self.fontboxes[(fontbox, sizebox)] = option
     layout = QHBoxLayout()
     for subwidget in (fontlabel, fontbox, sizelabel, sizebox):
         layout.addWidget(subwidget)
     layout.addStretch(1)
     if text is None:
         text = _("Font style")
     group = QGroupBox(text)
     group.setLayout(layout)
     if tip is not None:
         group.setToolTip(tip)
     return group
Ejemplo n.º 5
0
class Main(plugin.Plugin):
    ' main class for plugin '
    def initialize(self, *args, **kwargs):
        ' class init '
        super(Main, self).initialize(*args, **kwargs)
        self.group0 = QGroupBox()
        self.group0.setTitle(' Options ')
        self.group0.setCheckable(True)
        self.group0.toggled.connect(lambda: self.group0.hide())
        self.spin1, self.spin2, self.spin3 = QSpinBox(), QSpinBox(), QSpinBox()
        self.spin4, self.spin5, self.spin6 = QSpinBox(), QSpinBox(), QSpinBox()
        self.spin7, self.spin8, self.spin9 = QSpinBox(), QSpinBox(), QSpinBox()
        self.spin10, self.output = QSpinBox(), QTextEdit()
        self.reset = QPushButton(QIcon.fromTheme("face-smile"), 'Reset Options')
        self.reset.clicked.connect(self.reset_options)
        self.reset_options()
        self.output.setReadOnly(True)
        vboxg3 = QVBoxLayout(self.group0)
        for each_widget in (QLabel('<b>Max Attributes Per Class:'), self.spin1,
            QLabel('<b>Max Methods Per Class:'), self.spin2,
            QLabel('<b>Max Functions Per File:'), self.spin3,
            QLabel('<b>Max Classes Per File:'), self.spin4,
            QLabel('<b>Max Parameters Per Function:'), self.spin5,
            QLabel('<b>Max Lines Per Function:'), self.spin6,
            QLabel('<b>Max ControlStatements Per Function:'), self.spin7,
            QLabel('<b>Max Lines Per File:'), self.spin8,
            QLabel('<b>Max Indentation Levels:'), self.spin9,
            QLabel('<b>Max Tabs:'), self.spin10, self.reset):
            vboxg3.addWidget(each_widget)

        self.group1, self.auto = QGroupBox(), QComboBox()
        self.group1.setTitle(' Automation ')
        self.group1.setCheckable(True)
        self.group1.setToolTip('<font color="red"><b>WARNING:Advanced Setting!')
        self.group1.toggled.connect(lambda: self.group1.hide())
        self.auto.addItems(['Never run automatically', 'Run when File Saved',
            'Run when File Executed', 'Run when Tab Changed',
            'Run when File Opened', 'Run before File Saved'])
        self.auto.currentIndexChanged.connect(self.on_auto_changed)
        QVBoxLayout(self.group1).addWidget(self.auto)

        self.button = QPushButton(' Analyze for Best Practice ')
        self.button.setMinimumSize(75, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>Best Practice analyzer'),
            self.group0, self.group1, QLabel('<b>Best Practice Errors:'),
            self.output, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Check")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
            ).clicked.connect(lambda:
            QMessageBox.information(self.dock, __doc__, HELPMSG))

    def run(self):
        ' run the actions '
        global MAXVAL
        self.output.clear()
        self.button.setDisabled(True)
        maxvalues = {'maxAttributesPerClass': int(self.spin1.value()),
            'maxFunctionsPerClass': int(self.spin2.value()),
            'maxFunctionsPerFile': int(self.spin3.value()),
            'maxClassesPerFile': int(self.spin4.value()),
            'maxParametersPerFunction': int(self.spin5.value()),
            'maxLinesPerFunction': int(self.spin6.value()),
            'maxControlStatementsPerFunction': int(self.spin7.value()),
            'maxLinesPerFile': int(self.spin8.value()),
            'maxIndentationLevel': int(self.spin9.value()),
            'maxTabs': int(self.spin10.value())}
        MAXVAL = maxvalues
        self.output.append(SimplePythonChecker().analyze(str(
            self.locator.get_service("editor").get_opened_documents()[
             self.locator.get_service("editor").get_tab_manager().currentIndex()
            ]), maxvalues))
        self.output.setFocus()
        self.button.setEnabled(True)

    def on_auto_changed(self):
        ' automation connects '
        if self.auto.currentIndex() is 1:
            self.locator.get_service('editor').fileSaved.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when any File is Saved !')
        elif self.auto.currentIndex() is 2:
            self.locator.get_service('editor').fileExecuted.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when any File is Executed !')
        elif self.auto.currentIndex() is 3:
            self.locator.get_service('editor').currentTabChanged.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when current Tab is Changed')
        elif self.auto.currentIndex() is 4:
            self.locator.get_service('editor').fileOpened.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when any File is Opened !')
        elif self.auto.currentIndex() is 5:
            self.locator.get_service('editor').beforeFileSaved.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically before any File is Saved !')
        self.group1.setDisabled(True)

    def reset_options(self):
        ' reset the options '
        self.spin1.setRange(1, 99)
        self.spin2.setRange(1, 99)
        self.spin3.setRange(1, 99)
        self.spin4.setRange(1, 99)
        self.spin5.setRange(1, 9)
        self.spin6.setRange(1, 999)
        self.spin7.setRange(1, 99)
        self.spin8.setRange(1, 9999)
        self.spin9.setRange(1, 9)
        self.spin10.setRange(1, 9)
        self.spin1.setValue(20)
        self.spin2.setValue(20)
        self.spin3.setValue(20)
        self.spin4.setValue(5)
        self.spin5.setValue(5)
        self.spin6.setValue(100)
        self.spin7.setValue(20)
        self.spin8.setValue(999)
        self.spin9.setValue(5)
        self.spin10.setValue(5)
Ejemplo n.º 6
0
class Main(plugin.Plugin):
    ' main class for plugin '
    def initialize(self, *args, **kwargs):
        ' class init '
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.Dirs | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        menu = QMenu('Clones')
        menu.addAction('Analyze for Code Clones here', lambda: self.make_clon())
        self.locator.get_service('explorer').add_project_menu(menu, lang='all')

        self.group1 = QGroupBox()
        self.group1.setTitle(' Target ')
        self.outdir, self.igndir = QLineEdit(path.expanduser("~")), QLineEdit()
        self.outdir.setCompleter(self.completer)
        self.btn1 = QPushButton(QIcon.fromTheme("document-open"), ' Open ')
        self.btn1.clicked.connect(lambda: self.outdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Please, Open a Target Directory...', path.expanduser("~")))))
        self.btn1a = QPushButton(QIcon.fromTheme("face-smile"),
                                 'Get from Ninja active project')
        self.btn1a.clicked.connect(lambda: self.outdir.setText(
          self.locator.get_service('explorer').get_current_project_item().path))

        self.ignckb, self.ignmor = QComboBox(), QTextEdit()
        self.ignckb.addItems(['Single Directory', 'Multiple Directories CSV'])
        self.ignckb.currentIndexChanged.connect(self.on_ignore_changed)
        self.ignmor.hide()
        self.igndir.setPlaceholderText('Exclude directory')
        self.igndir.setCompleter(self.completer)
        self.btn2 = QPushButton(QIcon.fromTheme("document-open"), ' Open ')
        self.btn2.clicked.connect(lambda: self.igndir.setText(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Please, Open a Ignore Directory...', path.expanduser("~")))))
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (QLabel('<b>Target directory path: '), self.outdir,
            self.btn1, self.btn1a, QLabel('<b>Ignore directory path: '),
            self.ignckb, self.ignmor, self.igndir, self.btn2, ):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(' Output ')
        self.outfle = QLineEdit(path.join(path.expanduser("~"), 'output.html'))
        self.outfle.setPlaceholderText('Exclude directory')
        self.outfle.setCompleter(self.completer)
        self.btn3 = QPushButton(QIcon.fromTheme("document-save"), ' Save ')
        self.btn3.clicked.connect(lambda: self.outfle.setText(
            QFileDialog.getSaveFileName(self.dock, 'Save', path.expanduser("~"),
            'XML(*.xml)' if self.xmlo.isChecked() is True else 'HTML(*.html)')))
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (QLabel('<b>Output report file path:'),
            self.outfle, self.btn3):
            vboxg2.addWidget(each_widget)

        self.group3 = QGroupBox()
        self.group3.setTitle(' Options ')
        self.group3.setCheckable(True)
        self.group3.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group3.graphicsEffect().setEnabled(False)
        self.group3.toggled.connect(self.toggle_options_group)
        self.qckb1, self.qckb2 = QCheckBox('Recursive'), QCheckBox('Time-less')
        self.qckb3, self.qckb4 = QCheckBox('Force Diff'), QCheckBox('Fast Mode')
        self.qckb5, self.tm = QCheckBox('Save a LOG file to target'), QLabel('')
        self.xmlo = QCheckBox('XML Output instead of HTML')
        self.opeo = QCheckBox('Open Clones Report when done')
        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.mdist, self.hdep, self.output = QSpinBox(), QSpinBox(), QTextEdit()
        self.ign_func = QLineEdit('test, forward, backward, Migration')
        self.mdist.setValue(5)
        self.hdep.setValue(1)
        self.mdist.setToolTip('''<b>Maximum amount of difference between pair of
        sequences in clone pair (5 default).Larger value more false positive''')
        self.hdep.setToolTip('''<b>Computation can be speeded up by increasing
                       this value, but some clones can be missed (1 default)''')
        [a.setChecked(True) for a in (self.qckb1, self.qckb3, self.qckb5,
                                      self.chrt, self.opeo)]
        vboxg3 = QVBoxLayout(self.group3)
        for each_widget in (self.qckb1, self.qckb2, self.qckb3, self.qckb4,
            self.qckb5, self.chrt, self.xmlo, self.opeo,
            QLabel('<b>Max Distance Threshold:'), self.mdist,
            QLabel('<b>Max Hashing Depth:'), self.hdep,
            QLabel('<b>Ignore code block prefix:'), self.ign_func):
            vboxg3.addWidget(each_widget)

        self.group4, self.auto = QGroupBox(), QComboBox()
        self.group4.setTitle(' Automation ')
        self.group4.setCheckable(True)
        self.group4.setToolTip('<font color="red"><b>WARNING:Advanced Setting!')
        self.group4.toggled.connect(lambda: self.group4.hide())
        self.auto.addItems(['Never run automatically', 'Run when File Saved',
            'Run when File Executed', 'Run when Tab Changed',
            'Run when File Opened', 'Run before File Saved'])
        self.auto.currentIndexChanged.connect(self.on_auto_changed)
        QVBoxLayout(self.group4).addWidget(self.auto)

        self.button = QPushButton(' Analyze for Clones ')
        self.button.setMinimumSize(75, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)

        self.butkil = QPushButton(' Force Kill Clones ')
        self.butkil.clicked.connect(lambda: self.process.kill())

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>D.R.Y. principle analyzer'),
            self.group1, self.group2, self.group3, self.group4,
            QLabel('<b>Backend Logs'), self.output, self.tm, self.button,
            self.butkil))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Clones")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
            ).clicked.connect(lambda:
            QMessageBox.information(self.dock, __doc__, HELPMSG))

    def readOutput(self):
        """Read and append output to the logBrowser"""
        self.output.append(str(self.process.readAllStandardOutput()).strip())

    def readErrors(self):
        """Read and append errors to the logBrowser"""
        self.output.append(self.formatErrorMsg(str(
                                        self.process.readAllStandardError())))

    def formatErrorMsg(self, msg):
        """Format error messages in red color"""
        return self.formatMsg(msg, 'red')

    def formatInfoMsg(self, msg):
        """Format informative messages in blue color"""
        return self.formatMsg(msg, 'green')

    def formatMsg(self, msg, color):
        """Format message with the given color"""
        return '<font color="{}">{}</font>'.format(color, msg)

    def make_clon(self):
        ' make clones analyze from contextual sub menu '
        self.outdir.setText(
          self.locator.get_service('explorer').get_current_project_item().path)
        self.run()

    def run(self):
        ' run the actions '
        self.output.clear()
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        self.tm.setText('<center><b>Last Clone: </b>' +
                        datetime.now().isoformat().split('.')[0])
        self.button.setDisabled(True)
        if not len(self.outdir.text()) and not len(self.outfle.text()):
            self.output.append(self.formatErrorMsg('ERROR: FAIL: Target empty'))
            self.button.setEnabled(True)
            return
        # run the subprocesses
        cmd = ' '.join((
            'chrt -i 0' if self.chrt.isChecked() is True else '', 'clonedigger',
            '' if self.qckb1.isChecked() is True else '--no-recursion',
            '--dont-print-time' if self.qckb2.isChecked() is True else '',
            '--force' if self.qckb3.isChecked() is True else '',
            '--fast' if self.qckb4.isChecked() is True else '',
            '--cpd-output' if self.xmlo.isChecked() is True else '',
            '' if self.xmlo.isChecked() is True else '--report-unifiers',
            '--distance-threshold={}'.format(self.mdist.value()),
            '--hashing-depth={}'.format(self.hdep.value()),
            '--ignore-dir="{}"'.format(self.igndir.text()
                if self.ignckb.currentIndex() is 0
                else self.ignmor.toPlainText()),
            '--func-prefixes="{}"'.format(self.ign_func.text()),
            '--output="{}"'.format(self.outfle.text()),
            '--language=python', path.abspath(self.outdir.text()),
        ))
        self.output.append(self.formatInfoMsg('INFO:OK:Command:{}'.format(cmd)))
        self.process.start(cmd)
        if not self.process.waitForStarted():
            self.output.append(self.formatErrorMsg(' ERROR: FAIL: Meh. '))
            self.output.append(self.formatErrorMsg('ERROR:FAIL:{}'.format(cmd)))
            self.button.setEnabled(True)
            return
        self.readOutput()
        self.readErrors()
        self.button.setEnabled(True)

    def _process_finished(self):
        """ finished sucessfully """
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        # write a .log file on target
        if self.qckb5.isChecked() is True:
            log_file = 'ninja_clones.log'
            with open(path.join(str(self.outdir.text()), log_file), 'w') as log:
                self.output.append(self.formatInfoMsg('''INFO: OK: Writing Logs:
                    {}'''.format(path.join(str(self.outdir.text()), log_file))))
                log.write(self.output.toPlainText())
                log.close()
        # open target output
        if self.opeo.isChecked() is True and self.xmlo.isChecked() is False:
            try:
                startfile(self.outfle.text())
            except:
                Popen(["xdg-open", self.outfle.text()])
        self.output.selectAll()
        self.output.setFocus()

    def toggle_options_group(self):
        ' toggle on off the options group '
        if self.group3.isChecked() is True:
            [a.setChecked(True) for a in (self.qckb1, self.qckb3, self.qckb5,
                                          self.chrt, self.opeo)]
            self.mdist.setValue(5)
            self.hdep.setValue(1)
            self.group3.graphicsEffect().setEnabled(False)
        else:
            [a.setChecked(False) for a in (self.qckb1, self.qckb3, self.qckb5,
                                           self.chrt, self.opeo)]
            self.group3.graphicsEffect().setEnabled(True)

    def on_ignore_changed(self):
        'hide or show one widget or another depending what kind of input need'
        if self.ignckb.currentIndex() is 0:
            self.igndir.show()
            self.btn2.show()
            self.ignmor.hide()
        else:
            self.igndir.hide()
            self.btn2.hide()
            self.ignmor.show()

    def on_auto_changed(self):
        ' automation connects '
        if self.auto.currentIndex() is 1:
            self.locator.get_service('editor').fileSaved.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when any File is Saved !')
        elif self.auto.currentIndex() is 2:
            self.locator.get_service('editor').fileExecuted.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when any File is Executed !')
        elif self.auto.currentIndex() is 3:
            self.locator.get_service('editor').currentTabChanged.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when current Tab is Changed')
        elif self.auto.currentIndex() is 4:
            self.locator.get_service('editor').fileOpened.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically when any File is Opened !')
        elif self.auto.currentIndex() is 5:
            self.locator.get_service('editor').beforeFileSaved.connect(lambda:
                self.run())
            QMessageBox.information(self.dock, __doc__,
            '<b>Now Actions will Run Automatically before any File is Saved !')
        self.group4.setDisabled(True)

    def finish(self):
        ' clear when finish '
        self.process.kill()
Ejemplo n.º 7
0
class RatingWidget(QWidget):
    """
    Last panel. Gives point cost of idea set and lists any penalty flags.
    """
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        # cost display
        self.cost = QGroupBox("National ideas")
        costLayout = QFormLayout()

        self.costRating = QLineEdit()
        self.costRating.setReadOnly(True)
        costLayout.addRow(QLabel("Rating:"), self.costRating)

        self.costDisplay = QLineEdit()
        self.costDisplay.setReadOnly(True)
        costLayout.addRow(QLabel("Cost:"), self.costDisplay)

        possibleRatings = QGroupBox("Possible ratings")
        possibleRatingsLayout = QFormLayout()
        for cost, rating in ideaRatings:
            if cost is not None:
                possibleRatingsLayout.addRow(QLabel("Up to %0.1f:" % (cost),), QLabel(rating))
            else:
                possibleRatingsLayout.addRow(QLabel("Above:"), QLabel(rating))
        possibleRatings.setLayout(possibleRatingsLayout)
        costLayout.addRow(possibleRatings)

        breakdown = QGroupBox("Breakdown")
        breakdownLayout = QFormLayout()
        self.breakdownLabels = []
        self.breakdownCosts = []
        for i in range(9):
            breakdownLabel = QLabel()
            self.breakdownLabels.append(breakdownLabel)
            
            breakdownCost = QLineEdit()
            breakdownCost.setReadOnly(True)
            
            self.breakdownCosts.append(breakdownCost)
            breakdownLayout.addRow(breakdownLabel, breakdownCost)

        breakdown.setLayout(breakdownLayout)

        costLayout.addRow(breakdown)

        self.cost.setLayout(costLayout)

        self.cost.setToolTip(costToolTipText)

        # penalty display
        self.penalties = QGroupBox("Penalties")
        penaltiesLayout = QFormLayout()

        # self.penaltiesRating = QLineEdit()
        # self.penaltiesRating.setReadOnly(True)
        # penaltiesLayout.addRow(QLabel("Rating:"), self.penaltiesRating)
        
        self.yellowCardCount = QLineEdit()
        self.yellowCardCount.setReadOnly(True)
        penaltiesLayout.addRow(QLabel("Yellow cards:"), self.yellowCardCount)

        self.yellowCardDisplay = QListView()
        self.yellowCardDisplay.setSelectionMode(QAbstractItemView.NoSelection)
        self.yellowCards = QStringListModel()
        self.yellowCardDisplay.setModel(self.yellowCards)
        penaltiesLayout.addRow(self.yellowCardDisplay)

        self.redCardCount = QLineEdit()
        self.redCardCount.setReadOnly(True)
        penaltiesLayout.addRow(QLabel("Red cards:"), self.redCardCount)

        self.redCardDisplay = QListView()
        self.redCardDisplay.setSelectionMode(QAbstractItemView.NoSelection)
        self.redCards = QStringListModel()
        self.redCardDisplay.setModel(self.redCards)
        penaltiesLayout.addRow(self.redCardDisplay)

        self.penalties.setLayout(penaltiesLayout)

        self.penalties.setToolTip(penaltiesToolTipText)

        layout = QHBoxLayout()

        layout.addWidget(self.cost)
        layout.addWidget(self.penalties)

        self.setLayout(layout)

    def handleCostChanged(self, costs):
        totalCost = sum(costs)
        self.costDisplay.setText("%0.2f" % (totalCost,))
        self.costRating.setText(getIdeaRating(totalCost))
        for i, cost in enumerate(costs):
            self.breakdownCosts[i].setText("%0.2f" % cost)

    def handleIdeaNamesChanged(self, names):
        for i, name in enumerate(names):
            self.breakdownLabels[i].setText(name)

    def handlePenaltiesChanged(self, yellow, red):
        self.yellowCardCount.setText("%d" % (len(yellow),))
        self.yellowCards.setStringList(yellow)
        self.redCardCount.setText("%d" % (len(red),))
        self.redCards.setStringList(red)
Ejemplo n.º 8
0
class Ui_option(object):

    def createLine(self):
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        return line

    def createSquareLabel(self):
        label = QLabel()
        label.setEnabled(False)
        label.setFixedSize(24, 24)
        label.setFrameShape(QFrame.StyledPanel)
        return label

    def addVerticalStretch(self, page_layout):
        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Expanding)
        page_layout.addItem(vert_spacer, page_layout.rowCount(), 0, 1, page_layout.columnCount())

    def createConnSection(self, page_layout, label, combobox, num_column):
        conn_layout = QHBoxLayout()
        conn_layout.setSpacing(5)
        conn_layout.setContentsMargins(0, 0, 0, 0)
        conn_layout.addWidget(label)
        conn_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Fixed, QSizePolicy.Minimum))
        conn_layout.addWidget(combobox, 1)

        page_layout.addLayout(conn_layout, page_layout.rowCount(), 0, 1, num_column)
        page_layout.addWidget(self.createLine(), page_layout.rowCount(), 0, 1, num_column)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, page_layout.rowCount(), 0, 1, num_column)

    def createConnPage(self):
        self.conn_page = QWidget()
        self.conn_page.setObjectName("conn_page")
        self.conn_page.setToolTip(QApplication.translate("option", 
            "<b>Add/Modify/Delete a connection for a MUD server.</b>"
            "<p>Set the IP or hostname and the port of the MUD server.<br/>"
            "You have to define a connection to use all the functionality "
            "related (accounts, aliases, macros and triggers).</p>"))

        page_layout = QGridLayout(self.conn_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 100)

        self.label_conn = QLabel()
        self.label_conn.setText(QApplication.translate("option", "Connection"))
        page_layout.addWidget(self.label_conn, 0, 0)

        self.list_conn = QComboBox()
        self.list_conn.addItem(QApplication.translate("option", "Create New"))
        page_layout.addWidget(self.list_conn, 0, 1, 1, 2)

        self.label_name_conn = QLabel()
        self.label_name_conn.setText(QApplication.translate("option", "Name"))
        page_layout.addWidget(self.label_name_conn, 1, 0)

        self.name_conn = QLineEdit()
        page_layout.addWidget(self.name_conn, 1, 1, 1, 2)

        self.label_host_conn = QLabel()
        self.label_host_conn.setText(QApplication.translate("option", "Host"))
        page_layout.addWidget(self.label_host_conn, 2, 0)

        self.host_conn = QLineEdit()
        page_layout.addWidget(self.host_conn, 2, 1, 1, 2)

        self.label_port_conn = QLabel()
        self.label_port_conn.setText(QApplication.translate("option", "Port"))
        page_layout.addWidget(self.label_port_conn, 3, 0)

        page_layout.addItem(QSpacerItem(80, 20), 3, 1) # horizontal spacer

        self.port_conn = QLineEdit()
        self.port_conn.setMaxLength(8)
        page_layout.addWidget(self.port_conn, 3, 2)

        vert_spacer = QSpacerItem(271,20,QSizePolicy.Minimum,QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, 4, 0, 1, 3)

        buttons_box = QHBoxLayout()
        buttons_box.setSpacing(5)
        buttons_box.setContentsMargins(0, 0, 0, 0)

        self.save_conn = QPushButton()
        self.save_conn.setFixedHeight(28)
        self.save_conn.setIcon(QIcon(":/images/button-save.png"))
        self.save_conn.setText(QApplication.translate("option", "Save"))
        buttons_box.addWidget(self.save_conn)

        self.delete_conn = QPushButton()
        self.delete_conn.setFixedHeight(28)
        self.delete_conn.setIcon(QIcon(":/images/button-cancel.png"))
        self.delete_conn.setText(QApplication.translate("option", "Delete"))
        buttons_box.addWidget(self.delete_conn)

        page_layout.addLayout(buttons_box, 5, 0, 1, 3, Qt.AlignRight)
        self.addVerticalStretch(page_layout)
        return self.conn_page

    def createAccountPage(self):
        self.account_page = QWidget()
        self.account_page.setObjectName("account_page")
        self.account_page.setToolTip(QApplication.translate("option", 
            "<b>Manage the accounts.</b>"
            "<p>Set the Save account flag to activate/disactivate the automatic "
            "saving of the accounts during the connection phase.<br/>After that "
            "the account has been created, you can use it for auto-login by "
            "simply selecting the account in the main window.<br/>You can "
            "also erase an already saved account, or define a custom prompt "
            "(see the relative help box).</p>"))

        page_layout = QGridLayout(self.account_page)
        page_layout.setSpacing(10)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 130)

        self.save_account = QCheckBox()
        self.save_account.setText(QApplication.translate("option", "Save accounts"))
        page_layout.addWidget(self.save_account, 0, 0)

        self.label_conn_account = QLabel()
        self.label_conn_account.setText(QApplication.translate("option", "Connection"))

        self.list_conn_account = QComboBox()
        self.createConnSection(page_layout, self.label_conn_account, self.list_conn_account, 2)

        self.label_account_account = QLabel()
        self.label_account_account.setText(QApplication.translate("option", "Account"))
        page_layout.addWidget(self.label_account_account, 4, 0)

        self.list_account = QComboBox()
        page_layout.addWidget(self.list_account, 4, 1)

        buttons_box = QHBoxLayout()
        buttons_box.setSpacing(5)

        self.change_prompt = QPushButton()
        self.change_prompt.setEnabled(False)
        self.change_prompt.setFixedHeight(28)
        self.change_prompt.setIcon(QIcon(":/images/prompt.png"))
        self.change_prompt.setText(QApplication.translate("option", "Change Prompt"))
        buttons_box.addWidget(self.change_prompt)

        self.delete_account = QPushButton()
        self.delete_account.setEnabled(False)
        self.delete_account.setFixedHeight(28)
        self.delete_account.setIcon(QIcon(":/images/button-cancel.png"))
        self.delete_account.setText(QApplication.translate("option", "Delete"))
        buttons_box.addWidget(self.delete_account)
        page_layout.addLayout(buttons_box, 5, 0, 1, 2, Qt.AlignRight)

        self.box_prompt = QGroupBox()
        self.box_prompt.setTitle(QApplication.translate("option", "Prompt"))
        self.box_prompt.setToolTip(QApplication.translate("option", "<table>"
        "<tr><td colspan=3><b>Prompt format:</b></td></tr>"
        "<tr><td>%h</td><td>-></td><td>Current hit points</td></tr>"
        "<tr><td>%H</td><td>-></td><td>Maximum hit points</td></tr>"
        "<tr><td>%m</td><td>-></td><td>Current mana</td></tr>"
        "<tr><td>%M</td><td>-></td><td>Maximum mana</td></tr>"
        "<tr><td>%v</td><td>-></td><td>Current moves</td></tr>"
        "<tr><td>%V</td><td>-></td><td>Maximum moves</td></tr>"
        "<tr><td>*<td>-></td><td>Represent any char, repeated</td></tr>"
        "<tr><td colspan=2>&nbsp;</td><td>zero or more times</td></tr>"
        "<tr><td colspan=3>&nbsp;</td></tr>"
        "</table>"
        "<table>"
        "<tr><td><b>Example:</b></td></tr>"
        "<tr><td>[  %h/%Hhp %m/%Mmn %v/%Vmv *] ></td></tr>"
        "<tr><td>is a valid representation for:</td></tr>"
        "<tr><td>[  111/111hp 100/100mn 500/500mv 1000tnl] ></td></tr>"
        "</table>"))

        prompt_layout = QGridLayout(self.box_prompt)
        prompt_layout.setSpacing(5)
        prompt_layout.setContentsMargins(5, 5, 5, 5)

        label_normal = QLabel()
        label_normal.setText(QApplication.translate("option", "Normal"))
        prompt_layout.addWidget(label_normal, 0, 0)

        self.normal_prompt = QLineEdit()
        prompt_layout.addWidget(self.normal_prompt, 0, 1)

        label_fight = QLabel()
        label_fight.setText(QApplication.translate("option", "Fight"))
        prompt_layout.addWidget(label_fight, 1, 0)

        self.fight_prompt = QLineEdit()
        prompt_layout.addWidget(self.fight_prompt, 1, 1)

        self.save_prompt = QPushButton()
        self.save_prompt.setFixedHeight(28)
        self.save_prompt.setIcon(QIcon(":/images/button-save.png"))
        self.save_prompt.setText(QApplication.translate("option", "Save"))
        prompt_layout.addWidget(self.save_prompt, 2, 0, 1, 2, Qt.AlignRight)
        page_layout.addWidget(self.box_prompt, 6, 0, 1, 2)

        self.addVerticalStretch(page_layout)
        return self.account_page

    def createAliasPage(self):
        self.alias_page = QWidget()
        self.alias_page.setObjectName("alias_page")
        self.alias_page.setToolTip(QApplication.translate("option", 
            "<b>Add/Modify/Delete an alias.</b>"
            "<p>An alias is a textual shortcut that you can use to increase "
            "the typing speed. <br/>Thus, when you enter the text of the "
            "label you actually send to the server the text of the body.</p>"))

        page_layout = QGridLayout(self.alias_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 80)

        self.label_conn_alias = QLabel()
        self.label_conn_alias.setText(QApplication.translate("option", "Connection"))
        self.list_conn_alias = QComboBox()
        self.createConnSection(page_layout, self.label_conn_alias, self.list_conn_alias, 3)

        self.label_alias_alias = QLabel()
        self.label_alias_alias.setText(QApplication.translate("option", "Alias"))
        page_layout.addWidget(self.label_alias_alias, 3, 0)

        page_layout.addItem(QSpacerItem(80, 20, QSizePolicy.Fixed, QSizePolicy.Minimum), 3, 1)

        self.list_alias = QComboBox()
        self.list_alias.setEnabled(False)
        page_layout.addWidget(self.list_alias, 3, 2)

        self.label_label_alias = QLabel()
        self.label_label_alias.setText(QApplication.translate("option", "Label"))
        page_layout.addWidget(self.label_label_alias, 4, 0)

        page_layout.addItem(QSpacerItem(80, 20, QSizePolicy.Fixed, QSizePolicy.Minimum), 4, 1)

        self.label_alias = QLineEdit()
        self.label_alias.setEnabled(False)
        page_layout.addWidget(self.label_alias, 4, 2)

        self.label_body_alias = QLabel()
        self.label_body_alias.setText(QApplication.translate("option", "Body"))
        page_layout.addWidget(self.label_body_alias, 5, 0)

        self.body_alias = QLineEdit()
        self.body_alias.setEnabled(False)
        page_layout.addWidget(self.body_alias, 5, 1, 1, 2)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, 6, 0, 1, 3)

        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(5)
        buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.save_alias = QPushButton()
        self.save_alias.setFixedHeight(28)
        self.save_alias.setIcon(QIcon(":/images/button-save.png"))
        self.save_alias.setText(QApplication.translate("option", "Save"))
        buttons_layout.addWidget(self.save_alias)

        self.delete_alias = QPushButton()
        self.delete_alias.setFixedHeight(28)
        self.delete_alias.setIcon(QIcon(":/images/button-cancel.png"))
        self.delete_alias.setText(QApplication.translate("option", "Delete"))
        buttons_layout.addWidget(self.delete_alias)
        page_layout.addLayout(buttons_layout, 7, 0, 1, 3, Qt.AlignRight)

        self.addVerticalStretch(page_layout)
        return self.alias_page

    def createMacroPage(self):
        self.macro_page = QWidget()
        self.macro_page.setObjectName("macro_page")
        self.macro_page.setToolTip(QApplication.translate("option", 
            "<b>Add/Modify/Delete a macro.</b>"
            "<p>A macro is a key-based shortcut to send some text to the server."
            "<br/>You can define a key (or a combination of keys, likes CTRL+A) "
            "that if pressed during the game fires the macro, which sends the "
            "command to the server.</p><p><b>NOTE:</b> You cannot use for a "
            "macro a key already used for a standard shortcut.</p>"))

        page_layout = QGridLayout(self.macro_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 80)

        self.label_conn_macro = QLabel()

        self.list_conn_macro = QComboBox()
        self.createConnSection(page_layout, self.label_conn_macro, self.list_conn_macro, 3)

        self.label_macro_macro = QLabel()
        page_layout.addWidget(self.label_macro_macro, 3, 0)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed,QSizePolicy.Minimum)
        page_layout.addItem(horiz_spacer, 3, 1)

        self.list_macro = QComboBox()
        self.list_macro.setEnabled(False)
        page_layout.addWidget(self.list_macro, 3, 2)

        self.label_keys_macro = QLabel()
        page_layout.addWidget(self.label_keys_macro, 4, 0)

        self.register_macro = QPushButton()
        self.register_macro.setEnabled(False)
        self.register_macro.setFixedHeight(28)
        page_layout.addWidget(self.register_macro, 4, 1)

        self.keys_macro = QLineEdit()
        self.keys_macro.setEnabled(False)
        self.keys_macro.setProperty("highlight_color",QVariant("#C8C8C8"))
        page_layout.addWidget(self.keys_macro, 4, 2)

        self.label_command_macro = QLabel()
        page_layout.addWidget(self.label_command_macro, 5, 0)

        self.command_macro = QLineEdit()
        self.command_macro.setEnabled(False)
        page_layout.addWidget(self.command_macro, 5, 1, 1, 2)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, 6, 0, 1, 3)

        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(5)
        buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.save_macro = QPushButton()
        self.save_macro.setFixedHeight(28)
        self.save_macro.setIcon(QIcon(":/images/button-save.png"))
        buttons_layout.addWidget(self.save_macro)

        self.delete_macro = QPushButton()
        self.delete_macro.setFixedHeight(28)
        self.delete_macro.setIcon(QIcon(":/images/button-cancel.png"))
        buttons_layout.addWidget(self.delete_macro)
        page_layout.addLayout(buttons_layout, 7, 0, 1, 3, Qt.AlignRight)
        self.addVerticalStretch(page_layout)

        self.label_conn_macro.setText(QApplication.translate("option", "Connection"))
        self.label_macro_macro.setText(QApplication.translate("option", "Macro"))
        self.label_keys_macro.setText(QApplication.translate("option", "Keys"))
        self.label_command_macro.setText(QApplication.translate("option", "Command"))
        self.register_macro.setText(QApplication.translate("option", "Register"))
        self.save_macro.setText(QApplication.translate("option", "Save"))
        self.delete_macro.setText(QApplication.translate("option", "Delete"))
        return self.macro_page

    def createKeyPad(self):
        def createKey(text, size):
            layout = QVBoxLayout()
            layout.addStretch(1)
            label = QLabel(text)
            label.setAlignment(Qt.AlignHCenter)
            layout.addWidget(label)
            line_input = QLineEdit()
            if size != -1:
                line_input.setFixedWidth(size)
            self.keypad_fields[text] = line_input
            layout.addWidget(line_input)
            return layout

        keypad = QWidget()
        self.keypad_fields = {}
        layout = QGridLayout(keypad)
        layout.setHorizontalSpacing(30)
        layout.setVerticalSpacing(15)
        layout.setContentsMargins(5, 5, 5, 5)
        layout.addLayout(createKey('7', 60), 0, 0)
        layout.addLayout(createKey('8', 60), 0, 1)
        layout.addLayout(createKey('9', 60), 0, 2)

        layout.addLayout(createKey('4', 60), 1, 0)
        layout.addLayout(createKey('5', 60), 1, 1)
        layout.addLayout(createKey('6', 60), 1, 2)

        layout.addLayout(createKey('1', 60), 2, 0)
        layout.addLayout(createKey('2', 60), 2, 1)
        layout.addLayout(createKey('3', 60), 2, 2)

        layout.addLayout(createKey('0', -1), 3, 0, 1, 2)
        layout.addLayout(createKey('.', 60), 3, 2)
        return keypad

    def createKeypadPage(self):
        self.keypad_page = QWidget()
        self.keypad_page.setObjectName("keypad_page")
        self.keypad_page.setToolTip(QApplication.translate("option", 
            "<b>Connect the keypad keys with custom actions</b>"
            "<p>Enter the text in the spaces to connect the correspondent key "
            "in order to use as a shortcut to send the text to the server.</p>"))

        page_layout = QGridLayout(self.keypad_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 80)

        self.label_conn_keypad = QLabel()
        self.list_conn_keypad = QComboBox()
        self.createConnSection(page_layout, self.label_conn_keypad, self.list_conn_keypad, 1)
        page_layout.addWidget(self.createKeyPad(), 3, 0, 1, 1, Qt.AlignRight)
        self.addVerticalStretch(page_layout)

        self.save_keypad = QPushButton()
        self.save_keypad.setFixedHeight(28)
        self.save_keypad.setIcon(QIcon(":/images/button-save.png"))
        self.save_keypad.setText(QApplication.translate("option", "Save"))
        page_layout.addWidget(self.save_keypad, 4, 0, 1, 1, Qt.AlignRight)
        self.label_conn_keypad.setText(QApplication.translate("option", "Connection"))
        return self.keypad_page

    def createTriggerPage(self):
        self.trigger_page = QWidget()
        self.trigger_page.setObjectName("trigger_page")
        self.trigger_page.setToolTip(QApplication.translate("option",
            "<b>Add/Modify/Delete a trigger.</b>"
            "<p>A trigger is an event that happen when some text came from "
            "server.<br/>After has been received a text that match with the "
            "pattern (see the relative help box), the trigger can send another "
            "text to the server or highlight the incoming one.</p>"))

        page_layout = QGridLayout(self.trigger_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(1, 140)

        self.label_conn_trigger = QLabel()

        self.list_conn_trigger = QComboBox()
        self.createConnSection(page_layout, self.label_conn_trigger, self.list_conn_trigger, 2)

        self.label_trigger = QLabel()
        page_layout.addWidget(self.label_trigger, 3, 0, 1, 1)

        self.list_trigger = QComboBox()
        page_layout.addWidget(self.list_trigger, 3, 1, 1, 1)

        tooltip_pattern_trigger = QApplication.translate("option", 
        "<table width=\"350\">"
        "<tr><td colspan=3><b>Pattern special characters:</b></td></tr>"
        "<tr><td>*</td><td>-></td><td width=\"250\">A sequence of any chars</td></tr>"
        "<tr><td>?</td><td>-></td><td width=\"250\">Any single character</td></tr>"
        "<tr><td>%w</td><td>-></td><td width=\"250\">A sequence of alphanumeric chars</td></tr>"
        "<tr><td>%d</td><td>-></td><td width=\"250\">A sequence of numeric characters</td></tr>"
        "<tr><td colspan=3>Every time that you use the special chars %w or %d "
        "you can also put the relative extracted text in the command using the "
        "sintax %number where number represents the positional order of the "
        "special char.</td></tr>"
        "</table><br/>"
        "<table width=\"350\">"
        "<tr><td colspan=2><b>Example:</b></td></tr>"
        "<tr><td>Pattern:</td><td width=\"250\">%w the ogre is fighting against %w</td></tr>"
        "<tr><td>Command:</td><td width=\"250\">kill %2</td></tr>"
        "<tr><td colspan=2>The trigger will fire when an ogre will fight "
        "against an unknown enemy, and as reaction you will fight with the "
        "ogre against his enemy.</td></tr>"
        "</table>")

        self.label_pattern_trigger = QLabel()
        self.label_pattern_trigger.setToolTip(tooltip_pattern_trigger)
        page_layout.addWidget(self.label_pattern_trigger, 4, 0, 1, 1)

        self.pattern_trigger = QLineEdit()
        self.pattern_trigger.setToolTip(tooltip_pattern_trigger)
        page_layout.addWidget(self.pattern_trigger, 4, 1, 1, 1)

        self.case_trigger = QCheckBox()
        page_layout.addWidget(self.case_trigger, 5, 0, 1, 2, Qt.AlignLeft)

        self.label_command_trigger = QLabel()
        self.label_command_trigger.setText(QApplication.translate("option", "Command"))
        page_layout.addWidget(self.label_command_trigger, 6, 0)

        self.command_trigger = QLineEdit()
        page_layout.addWidget(self.command_trigger, 6, 1)

        self.label_color_trigger = QLabel()
        self.label_color_trigger.setText(QApplication.translate("option", "Change color to"))
        page_layout.addWidget(self.label_color_trigger, 7, 0)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        page_layout.addItem(horiz_spacer, 7, 1)

        colors_layout = QHBoxLayout()
        colors_layout.setSpacing(3)

        self.text_color_trigger_button = QPushButton()
        self.text_color_trigger_button.setFixedHeight(28)
        self.text_color_trigger_button.setIcon(QIcon(":/images/button-color.png"))
        colors_layout.addWidget(self.text_color_trigger_button)

        self.text_color_trigger = self.createSquareLabel()
        colors_layout.addWidget(self.text_color_trigger)

        colors_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        colors_layout.addItem(colors_spacer)

        self.bg_color_trigger_button = QPushButton()
        self.bg_color_trigger_button.setFixedHeight(28)
        self.bg_color_trigger_button.setIcon(QIcon(":/images/button-color.png"))
        colors_layout.addWidget(self.bg_color_trigger_button)

        self.bg_color_trigger = self.createSquareLabel()
        colors_layout.addWidget(self.bg_color_trigger)
        page_layout.addLayout(colors_layout, 8, 0, 1, 2)

        horiz_spacer2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        page_layout.addItem(horiz_spacer2, 9, 0, 1, 2)

        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(5)

        self.save_trigger = QPushButton()
        self.save_trigger.setFixedHeight(28)
        self.save_trigger.setIcon(QIcon(":/images/button-save.png"))
        buttons_layout.addWidget(self.save_trigger)

        self.delete_trigger = QPushButton()
        self.delete_trigger.setFixedHeight(28)
        self.delete_trigger.setIcon(QIcon(":/images/button-cancel.png"))
        buttons_layout.addWidget(self.delete_trigger)
        page_layout.addLayout(buttons_layout, 10, 0, 1, 2, Qt.AlignRight)

        self.label_conn_trigger.setText(QApplication.translate("option", "Connection"))
        self.label_trigger.setText(QApplication.translate("option", "Trigger"))
        self.label_pattern_trigger.setText(QApplication.translate("option", "Pattern"))
        self.case_trigger.setText(QApplication.translate("option", "Ignore case"))

        self.text_color_trigger_button.setText(QApplication.translate("option", "Text"))
        self.text_color_trigger.setProperty("label_color", QVariant(True))
        self.bg_color_trigger_button.setText(QApplication.translate("option", "Background"))
        self.bg_color_trigger.setProperty("label_color", QVariant(True))
        self.save_trigger.setText(QApplication.translate("option", "Save"))
        self.delete_trigger.setText(QApplication.translate("option", "Delete"))
        return self.trigger_page

    def createPrefPage(self):
        self.pref_page = QWidget()
        self.pref_page.setObjectName("pref_page")

        page_layout = QVBoxLayout(self.pref_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)

        textBox = QGroupBox()
        textBox.setTitle(QApplication.translate("option", "Text inserted"))
        text_layout = QGridLayout(textBox)
        text_layout.setSpacing(7)
        text_layout.setContentsMargins(10, 10, 10, 10)

        self.echo_color_button = QPushButton()
        self.echo_color_button.setFixedHeight(28)
        self.echo_color_button.setIcon(QIcon(":/images/button-color.png"))
        self.echo_color_button.setText(QApplication.translate("option", "Echo Color"))
        text_layout.addWidget(self.echo_color_button, 0, 0)

        self.echo_color = self.createSquareLabel()
        self.echo_color.setProperty('label_color', QVariant(True))
        text_layout.addWidget(self.echo_color, 0, 3)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        text_layout.addItem(horiz_spacer, 0, 4)

        self.label_cmd_separator = QLabel()
        self.label_cmd_separator.setText(QApplication.translate("option", "Command separator"))
        text_layout.addWidget(self.label_cmd_separator, 1, 0, 1, 2)

        self.cmd_separator = QLineEdit()
        self.cmd_separator.setFixedSize(24, 24)

        font = QtGui.QFont()
        font.setWeight(75)
        font.setBold(True)
        self.cmd_separator.setFont(font)
        self.cmd_separator.setMaxLength(1)
        self.cmd_separator.setAlignment(Qt.AlignCenter)
        text_layout.addWidget(self.cmd_separator, 1, 3)

        horiz_spacer2 = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        text_layout.addItem(horiz_spacer2, 1, 4)

        self.keep_text = QCheckBox()
        self.keep_text.setText(QApplication.translate("option", "Keep text entered"))
        text_layout.addWidget(self.keep_text, 2, 0, 1, 4, Qt.AlignLeft)
        page_layout.addWidget(textBox)

        generalBox = QGroupBox()
        generalBox.setTitle(QApplication.translate("option", "General"))
        general_layout = QVBoxLayout(generalBox)
        general_layout.setSpacing(7)
        general_layout.setContentsMargins(10, 10, 10, 10)

        self.save_log = QCheckBox()
        self.save_log.setText(QApplication.translate("option", "Save log"))
        general_layout.addWidget(self.save_log, 0, Qt.AlignLeft)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        general_layout.addItem(horiz_spacer)
        page_layout.addWidget(generalBox)

        horiz_spacer2 = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        page_layout.addItem(horiz_spacer2)

        self.save_preferences = QPushButton()
        self.save_preferences.setFixedHeight(28)
        self.save_preferences.setIcon(QIcon(":/images/button-save.png"))
        self.save_preferences.setText(QApplication.translate("option", "Save"))
        page_layout.addWidget(self.save_preferences, 0, Qt.AlignRight)
        return self.pref_page

    def populatePages(self):
        self.page_container.addWidget(self.createConnPage())
        self.page_container.addWidget(self.createAccountPage())
        self.page_container.addWidget(self.createAliasPage())
        self.page_container.addWidget(self.createMacroPage())
        self.page_container.addWidget(self.createKeypadPage())
        self.page_container.addWidget(self.createTriggerPage())
        self.page_container.addWidget(self.createPrefPage())

    def createListOption(self):
        def addItem(label, icon_pixmap, width, height):
            item = QListWidgetItem(list_option)
            item.setText(label)
            item.setTextAlignment(Qt.AlignHCenter)
            item.setIcon(QIcon(icon_pixmap))
            item.setSizeHint(QSize(width, height))

        list_option = QListWidget()
        list_option.setAutoFillBackground(True)
        list_option.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        list_option.setTextElideMode(Qt.ElideNone)
        list_option.setMovement(QListView.Static)
        list_option.setFlow(QListView.TopToBottom)
        list_option.setProperty("isWrapping", QVariant(False))
        list_option.setSpacing(3)
        list_option.setViewMode(QListView.IconMode)

        items = []
        items.append((QApplication.translate("option", "Connections"), "connections.png"))
        items.append((QApplication.translate("option", "Accounts"), "accounts.png"))
        items.append((QApplication.translate("option", "Aliases"), "aliases.png"))
        items.append((QApplication.translate("option", "Macros"), "macros.png"))
        items.append((QApplication.translate("option", "Keypad"), "keypad.png"))
        items.append((QApplication.translate("option", "Triggers"), "triggers.png"))
        items.append((QApplication.translate("option", "Preferences"), "preferences.png"))

        max_width = 0
        for label, icon_name in items:
            w = list_option.fontMetrics().boundingRect(label).width()
            if w > max_width:
                max_width = w

        # An empiric method to align element in the center of the QListWidget
        max_width += 15
        total_height = 0

        for label, icon_name in items:
            icon_pixmap = QPixmap(":/images/" + icon_name)
            height = icon_pixmap.height() + list_option.fontMetrics().height() + 3
            total_height += height + 5
            addItem(label, icon_pixmap, max_width, height)

        list_option.setUniformItemSizes(True)
        list_option.setFixedWidth(max_width + 10)
        list_option.setMinimumHeight(total_height)
        return list_option

    def setupUi(self, option):
        option.setWindowTitle(QApplication.translate("option", "Option"))
        main_layout = QGridLayout(option)
        main_layout.setSpacing(5)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setColumnStretch(1, 1)

        self.list_option = self.createListOption()
        main_layout.addWidget(self.list_option, 0, 0)

        self.page_container = QStackedLayout()
        self.page_container.setContentsMargins(0, 0, 0, 0)
        main_layout.addLayout(self.page_container, 0, 1)
        self.populatePages()

        main_layout.addWidget(self.createLine(), 1, 0, 1, 2)
        close_layout = QHBoxLayout()
        close_layout.setContentsMargins(0, 0, 5, 0)
        close_layout.setSpacing(5)

        close_option = QPushButton()
        close_option.setText(QApplication.translate("option", "Close"))
        option.connect(close_option, QtCore.SIGNAL("clicked()"), option.accept)
        close_layout.addWidget(close_option)
        main_layout.addLayout(close_layout, 2, 1, 1, 2, Qt.AlignRight)

        self.list_option.setCurrentRow(0)
        self.page_container.setCurrentIndex(0)

        option.setTabOrder(self.list_option, self.list_conn)
        option.setTabOrder(self.list_conn, self.name_conn)
        option.setTabOrder(self.name_conn, self.host_conn)
        option.setTabOrder(self.host_conn, self.port_conn)
        option.setTabOrder(self.port_conn, self.save_conn)
        option.setTabOrder(self.save_conn, self.delete_conn)
        option.setTabOrder(self.delete_conn, self.list_conn_account)
        option.setTabOrder(self.list_conn_account, self.list_account)
        option.setTabOrder(self.list_account, self.delete_account)
        option.setTabOrder(self.delete_account, self.list_conn_alias)
        option.setTabOrder(self.list_conn_alias, self.list_alias)
        option.setTabOrder(self.list_alias, self.label_alias)
        option.setTabOrder(self.label_alias, self.body_alias)
        option.setTabOrder(self.body_alias, self.save_alias)
        option.setTabOrder(self.save_alias, self.delete_alias)
        option.setTabOrder(self.delete_alias, self.list_conn_macro)
        option.setTabOrder(self.list_conn_macro, self.list_macro)
        option.setTabOrder(self.list_macro, self.register_macro)
        option.setTabOrder(self.register_macro, self.keys_macro)
        option.setTabOrder(self.keys_macro, self.command_macro)
        option.setTabOrder(self.command_macro, self.save_macro)
        option.setTabOrder(self.save_macro, self.delete_macro)
        option.setTabOrder(self.delete_macro, self.echo_color_button)
        option.setTabOrder(self.echo_color_button, self.save_log)
Ejemplo n.º 9
0
    def __init__(self, toolbox):
        super(Spanners, self).__init__(toolbox, 'spanner',
            i18n("Spanners"), symbol='slur_solid',
            tooltip=i18n("Slurs, spanners, etcetera."))

        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        
        box = QGroupBox(i18n("Spanners"))
        box.setToolTip(i18n(
            "These spanners need a music fragment to be selected."))
        grid = QGridLayout()
        grid.setSpacing(0)
        box.setLayout(grid)

        self.spanners = {}

        for num, (name, title, symbol) in enumerate((
            ('slur', i18n("Slur"), 'slur_solid'),
            ('phrasing_slur', i18n("Phrasing Slur"), 'slur_solid'),
            ('beam', i18n("Beam"), 'spanner_beam16'),
            ('trill', i18n("Trill"), 'spanner_trill'),
        )):
            self.spanners[name] = (symbol, title)
            b = ActionButton(self, name, title, symbol)
            row, col = divmod(num, COLUMNS)
            grid.addWidget(b, row, col)
        layout.addWidget(box)
        
        box = QGroupBox(i18n("Arpeggios"))
        box.setToolTip(i18n(
            "Arpeggios are used with chords with multiple notes."))
        grid = QGridLayout()
        grid.setSpacing(0)
        box.setLayout(grid)

        self.arpeggios = {}

        for num, (name, title) in enumerate((
            ('arpeggio_normal', i18n("Arpeggio")),
            ('arpeggio_arrow_up', i18n("Arpeggio with Up Arrow")),
            ('arpeggio_arrow_down', i18n("Arpeggio with Down Arrow")),
            ('arpeggio_bracket', i18n("Bracket Arpeggio")),
            ('arpeggio_parenthesis', i18n("Parenthesis Arpeggio")),
        )):
            self.arpeggios[name] = title
            b = ActionButton(self, name, title, name)
            row, col = divmod(num, COLUMNS)
            grid.addWidget(b, row, col)
        layout.addWidget(box)

        box = QGroupBox(i18n("Glissandos"))
        box.setToolTip(i18n(
            "Glissandos are attached to a note and automatically "
            "extend to the next note."))
        grid = QGridLayout()
        grid.setSpacing(0)
        box.setLayout(grid)

        self.glissandos = {}

        for num, (name, title) in enumerate((
            ('glissando_normal', i18n("Glissando")),
            ('glissando_dashed', i18n("Dashed Glissando")),
            ('glissando_dotted', i18n("Dotted Glissando")),
            ('glissando_zigzag', i18n("Zigzag Glissando")),
            ('glissando_trill', i18n("Trill Glissando")),
        )):
            self.glissandos[name] = title
            b = ActionButton(self, name, title, name)
            row, col = divmod(num, COLUMNS)
            grid.addWidget(b, row, col)
        layout.addWidget(box)
        layout.addStretch()