Beispiel #1
0
class ExperimentalFeatures(preferences.Group):
    def __init__(self, page):
        super(ExperimentalFeatures, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.experimentalFeatures = QCheckBox(toggled=self.changed)
        layout.addWidget(self.experimentalFeatures)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Experimental Features"))
        self.experimentalFeatures.setText(_("Enable Experimental Features"))
        self.experimentalFeatures.setToolTip(
            '<qt>' +
            _("If checked, features that are not yet finished are enabled.\n"
              "You need to restart Frescobaldi to see the changes."))

    def loadSettings(self):
        s = QSettings()
        self.experimentalFeatures.setChecked(
            s.value("experimental-features", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.setValue("experimental-features",
                   self.experimentalFeatures.isChecked())
Beispiel #2
0
class CheckBox(QWidget):
    status_changed = pyqtSignal(bool)

    def __init__(self, caption, checked=False, tooltip=""):
        QWidget.__init__(self)

        self.value = checked

        self.checkbox = QCheckBox(caption)
        self.checkbox.stateChanged.connect(self.__on_change)
        self.checkbox.setToolTip(tooltip)

        hbox = QHBoxLayout()
        hbox.addWidget(self.checkbox)
        hbox.setMargin(0)
        self.setLayout(hbox)
        # self.setContentsMargins(5, 0, 5, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.checkbox.setChecked(self.value)

    def __on_change(self, value):
        self.value = value
        if value == Qt.Unchecked:
            self.status_changed.emit(False)
        else:
            self.status_changed.emit(True)

    def get_value(self):
        return self.checkbox.isChecked()
Beispiel #3
0
class Articulations(tool.Tool):
    """Articulations tool in the quick insert panel toolbox.
    
    """
    def __init__(self, panel):
        super(Articulations, self).__init__(panel)
        self.shorthands = QCheckBox(self)
        self.shorthands.setChecked(True)
        self.layout().addWidget(self.shorthands)
        for cls in (
                ArticulationsGroup,
                OrnamentsGroup,
                SignsGroup,
                OtherGroup,
            ):
            self.layout().addWidget(cls(self))
        self.layout().addStretch(1)
        app.translateUI(self)
        
    def translateUI(self):
        self.shorthands.setText(_("Allow shorthands"))
        self.shorthands.setToolTip(_(
            "Use short notation for some articulations like staccato."))

    def icon(self):
        """Should return an icon for our tab."""
        return symbols.icon("articulation_prall")
    
    def title(self):
        """Should return a title for our tab."""
        return _("Articulations")
  
    def tooltip(self):
	"""Returns a tooltip"""
	return _("Different kinds of articulations and other signs.")
Beispiel #4
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 #5
0
class CheckBox(QWidget):
    status_changed = pyqtSignal(bool)

    def __init__(self, caption, checked=False, tooltip=''):
        QWidget.__init__(self)

        self.value = checked

        self.checkbox = QCheckBox(caption)
        self.checkbox.stateChanged.connect(self.__on_change)
        self.checkbox.setToolTip(tooltip)

        hbox = QHBoxLayout()
        hbox.addWidget(self.checkbox)
        hbox.setMargin(0)
        self.setLayout(hbox)
        #self.setContentsMargins(5, 0, 5, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.checkbox.setChecked(self.value)

    def __on_change(self, value):
        self.value = value
        if value == Qt.Unchecked:
            self.status_changed.emit(False)
        else:
            self.status_changed.emit(True)

    def get_value(self):
        return self.checkbox.isChecked()
Beispiel #6
0
class ViewSettings(preferences.Group):
    def __init__(self, page):
        super(ViewSettings, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.wrapLines = QCheckBox(toggled=self.changed)
        
        layout.addWidget(self.wrapLines)
        app.translateUI(self)
    
    def translateUI(self):
        self.setTitle(_("View Preferences"))
        self.wrapLines.setText(_("Wrap long lines by default"))
        self.wrapLines.setToolTip('<qt>' + _(
            "If enabled, lines that don't fit in the editor width are wrapped "
            "by default. "
            "Note: when the document is displayed by multiple views, they all "
            "share the same line wrapping width, which might look strange."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        self.wrapLines.setChecked(s.value("wrap_lines", False, bool))
    
    def saveSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        s.setValue("wrap_lines", self.wrapLines.isChecked())
Beispiel #7
0
class ExperimentalFeatures(preferences.Group):
    def __init__(self, page):
        super(ExperimentalFeatures, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.experimentalFeatures = QCheckBox(toggled=self.changed)
        layout.addWidget(self.experimentalFeatures)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Experimental Features"))
        self.experimentalFeatures.setText(_("Enable Experimental Features"))
        self.experimentalFeatures.setToolTip('<qt>' + _(
            "If checked, features that are not yet finished are enabled.\n"
            "You need to restart Frescobaldi to see the changes."))
    
    def loadSettings(self):
        s = QSettings()
        self.experimentalFeatures.setChecked(s.value("experimental-features", False, bool))
        
    def saveSettings(self):
        s = QSettings()
        s.setValue("experimental-features", self.experimentalFeatures.isChecked())
Beispiel #8
0
class ViewSettings(preferences.Group):
    def __init__(self, page):
        super(ViewSettings, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

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

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

    def translateUI(self):
        self.setTitle(_("View Preferences"))
        self.wrapLines.setText(_("Wrap long lines by default"))
        self.wrapLines.setToolTip('<qt>' + _(
            "If enabled, lines that don't fit in the editor width are wrapped "
            "by default. "
            "Note: when the document is displayed by multiple views, they all "
            "share the same line wrapping width, which might look strange."))

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

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        s.setValue("wrap_lines", self.wrapLines.isChecked())
Beispiel #9
0
class Prefs(preferences.Group):
    def __init__(self, page):
        super(Prefs, self).__init__(page)

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

        layout = QVBoxLayout()
        self.setLayout(layout)

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

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

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

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

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

    def saveSettings(self):
        s = QSettings()
        s.setValue("midi/close_outputs", self._closeOutputs.isChecked())
        s.setValue("midi/polling_time", self._pollingTime.value())
Beispiel #10
0
 def create_scedit(self, text, option, default=NoDefault, tip=None,
                   without_layout=False):
     label = QLabel(text)
     clayout = ColorLayout(QColor(Qt.black), self)
     clayout.lineedit.setMaximumWidth(80)
     if tip is not None:
         clayout.setToolTip(tip)
     cb_bold = QCheckBox()
     cb_bold.setIcon(get_icon("bold.png"))
     cb_bold.setToolTip(_("Bold"))
     cb_italic = QCheckBox()
     cb_italic.setIcon(get_icon("italic.png"))
     cb_italic.setToolTip(_("Italic"))
     self.scedits[(clayout, cb_bold, cb_italic)] = (option, default)
     if without_layout:
         return label, clayout, cb_bold, cb_italic
     layout = QHBoxLayout()
     layout.addWidget(label)
     layout.addLayout(clayout)
     layout.addSpacing(10)
     layout.addWidget(cb_bold)
     layout.addWidget(cb_italic)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
Beispiel #11
0
    def getArguments(self, parent=None):
        description = "The CSV export requires some information before it starts:"
        dialog = CustomDialog("CSV Export", description, parent)

        default_csv_output_path = self.getDataKWValue("CSV_OUTPUT_PATH",
                                                      default="output.csv")
        output_path_model = PathModel(default_csv_output_path)
        output_path_chooser = PathChooser(output_path_model)

        design_matrix_default = self.getDataKWValue("DESIGN_MATRIX_PATH",
                                                    default="")
        design_matrix_path_model = PathModel(design_matrix_default,
                                             is_required=False,
                                             must_exist=True)
        design_matrix_path_chooser = PathChooser(design_matrix_path_model)

        list_edit = ListEditBox(self.getAllCaseList())

        infer_iteration_check = QCheckBox()
        infer_iteration_check.setChecked(True)
        infer_iteration_check.setToolTip(CSVExportJob.INFER_HELP)

        drop_const_columns_check = QCheckBox()
        drop_const_columns_check.setChecked(False)
        drop_const_columns_check.setToolTip(
            "If checked, exclude columns whose value is the same for every entry"
        )

        dialog.addLabeledOption("Output file path", output_path_chooser)
        dialog.addLabeledOption("Design matrix path",
                                design_matrix_path_chooser)
        dialog.addLabeledOption("List of cases to export", list_edit)
        dialog.addLabeledOption("Infer iteration number",
                                infer_iteration_check)
        dialog.addLabeledOption("Drop constant columns",
                                drop_const_columns_check)

        dialog.addButtons()

        success = dialog.showAndTell()

        if success:
            design_matrix_path = design_matrix_path_model.getPath()
            if design_matrix_path.strip() == "":
                design_matrix_path = None

            case_list = ",".join(list_edit.getItems())

            return [
                output_path_model.getPath(),
                case_list,
                design_matrix_path,
                infer_iteration_check.isChecked(),
                drop_const_columns_check.isChecked(),
            ]

        raise CancelPluginException("User cancelled!")
Beispiel #12
0
class Prefs(preferences.Group):
    def __init__(self, page):
        super(Prefs, self).__init__(page)

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

        layout = QVBoxLayout()
        self.setLayout(layout)

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

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

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

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

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

    def saveSettings(self):
        s = QSettings()
        s.setValue("midi/close_outputs", self._closeOutputs.isChecked())
        s.setValue("midi/polling_time", self._pollingTime.value())
Beispiel #13
0
class Articulations(tool.Tool):
    """Articulations tool in the quick insert panel toolbox.
    
    """
    def __init__(self, panel):
        super(Articulations, self).__init__(panel)
        self.shorthands = QCheckBox(self)
        self.shorthands.setChecked(True)
        self.removemenu = QToolButton(self,
            autoRaise=True,
            popupMode=QToolButton.InstantPopup,
            icon=icons.get('edit-clear'))
        
        mainwindow = panel.parent().mainwindow()
        mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled)
        self.removemenu.setEnabled(mainwindow.hasSelection())
        
        ac = documentactions.DocumentActions.instance(mainwindow).actionCollection
        self.removemenu.addAction(ac.tools_quick_remove_articulations)
        self.removemenu.addAction(ac.tools_quick_remove_ornaments)
        self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts)
        
        layout = QHBoxLayout()
        layout.addWidget(self.shorthands)
        layout.addWidget(self.removemenu)
        layout.addStretch(1)
        
        self.layout().addLayout(layout)
        for cls in (
                ArticulationsGroup,
                OrnamentsGroup,
                SignsGroup,
                OtherGroup,
            ):
            self.layout().addWidget(cls(self))
        self.layout().addStretch(1)
        app.translateUI(self)
        
    def translateUI(self):
        self.shorthands.setText(_("Allow shorthands"))
        self.shorthands.setToolTip(_(
            "Use short notation for some articulations like staccato."))
        self.removemenu.setToolTip(_(
            "Remove articulations etc."))
    
    def icon(self):
        """Should return an icon for our tab."""
        return symbols.icon("articulation_prall")
    
    def title(self):
        """Should return a title for our tab."""
        return _("Articulations")
  
    def tooltip(self):
        """Returns a tooltip"""
        return _("Different kinds of articulations and other signs.")
Beispiel #14
0
class Articulations(tool.Tool):
    """Articulations tool in the quick insert panel toolbox.
    
    """
    def __init__(self, panel):
        super(Articulations, self).__init__(panel)
        self.shorthands = QCheckBox(self)
        self.shorthands.setChecked(True)
        self.removemenu = QToolButton(self,
                                      autoRaise=True,
                                      popupMode=QToolButton.InstantPopup,
                                      icon=icons.get('edit-clear'))

        mainwindow = panel.parent().mainwindow()
        mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled)
        self.removemenu.setEnabled(mainwindow.hasSelection())

        ac = documentactions.DocumentActions.instance(
            mainwindow).actionCollection
        self.removemenu.addAction(ac.tools_quick_remove_articulations)
        self.removemenu.addAction(ac.tools_quick_remove_ornaments)
        self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts)

        layout = QHBoxLayout()
        layout.addWidget(self.shorthands)
        layout.addWidget(self.removemenu)
        layout.addStretch(1)

        self.layout().addLayout(layout)
        for cls in (
                ArticulationsGroup,
                OrnamentsGroup,
                SignsGroup,
                OtherGroup,
        ):
            self.layout().addWidget(cls(self))
        self.layout().addStretch(1)
        app.translateUI(self)

    def translateUI(self):
        self.shorthands.setText(_("Allow shorthands"))
        self.shorthands.setToolTip(
            _("Use short notation for some articulations like staccato."))
        self.removemenu.setToolTip(_("Remove articulations etc."))

    def icon(self):
        """Should return an icon for our tab."""
        return symbols.icon("articulation_prall")

    def title(self):
        """Should return a title for our tab."""
        return _("Articulations")

    def tooltip(self):
        """Returns a tooltip"""
        return _("Different kinds of articulations and other signs.")
Beispiel #15
0
class StaffGroup(_base.Container):
    @staticmethod
    def title(_=_base.translate):
        return _("Staff Group")

    def accepts(self):
        return (StaffGroup, _base.Part)

    def createWidgets(self, layout):
        self.systemStartLabel = QLabel()
        self.systemStart = QComboBox()
        self.systemStartLabel.setBuddy(self.systemStart)
        self.systemStart.setModel(
            listmodel.ListModel(
                (
                    # L10N: Brace like a piano staff
                    (lambda: _("Brace"), 'system_start_brace'),
                    # L10N: Bracket like a choir staff
                    (lambda: _("Bracket"), 'system_start_bracket'),
                    # L10N: Square bracket like a sub-group
                    (lambda: _("Square"), 'system_start_square'),
                ),
                self.systemStart,
                display=listmodel.translate_index(0),
                icon=lambda item: symbols.icon(item[1])))
        self.systemStart.setIconSize(QSize(64, 64))
        self.connectBarLines = QCheckBox(checked=True)

        box = QHBoxLayout()
        box.addWidget(self.systemStartLabel)
        box.addWidget(self.systemStart)
        layout.addLayout(box)
        layout.addWidget(self.connectBarLines)

    def translateWidgets(self):
        self.systemStartLabel.setText(_("Type:"))
        self.connectBarLines.setText(_("Connect Barlines"))
        self.connectBarLines.setToolTip(
            _("If checked, barlines are connected between the staves."))
        self.systemStart.model().update()

    def build(self, data, builder):
        s = self.systemStart.currentIndex()
        b = self.connectBarLines.isChecked()
        if s == 0:
            node = ly.dom.GrandStaff()
            if not b:
                ly.dom.Line("\\remove Span_bar_engraver", node.getWith())
        else:
            node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff()
            if s == 2:
                node.getWith()['systemStartDelimiter'] = ly.dom.Scheme(
                    "'SystemStartSquare")
        data.nodes.append(node)
        data.music = ly.dom.Simr(node)
Beispiel #16
0
class SavingDocument(preferences.Group):
    def __init__(self, page):
        super(SavingDocument, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.stripwsp = QCheckBox(toggled=self.changed)
        self.backup = QCheckBox(toggled=self.changed)
        self.metainfo = QCheckBox(toggled=self.changed)
        layout.addWidget(self.stripwsp)
        layout.addWidget(self.backup)
        layout.addWidget(self.metainfo)

        hbox = QHBoxLayout()
        layout.addLayout(hbox)

        self.basedirLabel = l = QLabel()
        self.basedir = UrlRequester()
        hbox.addWidget(self.basedirLabel)
        hbox.addWidget(self.basedir)
        self.basedir.changed.connect(self.changed)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("When saving documents"))
        self.stripwsp.setText(_("Strip trailing whitespace"))
        self.stripwsp.setToolTip(
            _("If checked, Frescobaldi will remove unnecessary whitespace at the "
              "end of lines (but not inside multi-line strings)."))
        self.backup.setText(_("Keep backup copy"))
        self.backup.setToolTip(
            _("Frescobaldi always backups a file before overwriting it "
              "with a new version.\n"
              "If checked those backup copies are retained."))
        self.metainfo.setText(_("Remember cursor position, bookmarks, etc."))
        self.basedirLabel.setText(_("Default directory:"))
        self.basedirLabel.setToolTip(
            _("The default folder for your LilyPond documents (optional)."))

    def loadSettings(self):
        s = QSettings()
        self.stripwsp.setChecked(
            s.value("strip_trailing_whitespace", False, bool))
        self.backup.setChecked(s.value("backup_keep", False, bool))
        self.metainfo.setChecked(s.value("metainfo", True, bool))
        self.basedir.setPath(s.value("basedir", "", type("")))

    def saveSettings(self):
        s = QSettings()
        s.setValue("strip_trailing_whitespace", self.stripwsp.isChecked())
        s.setValue("backup_keep", self.backup.isChecked())
        s.setValue("metainfo", self.metainfo.isChecked())
        s.setValue("basedir", self.basedir.path())
Beispiel #17
0
class LogTool(preferences.Group):
    def __init__(self, page):
        super(LogTool, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)
        
        self.showlog = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showlog)
        
        self.rawview = QCheckBox(toggled=self.changed)
        layout.addWidget(self.rawview)
        
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("LilyPond Log"))
        self.fontLabel.setText(_("Font:"))
        self.showlog.setText(_("Show log when a job is started"))
        self.rawview.setText(_("Display plain log output"))
        self.rawview.setToolTip(_(
            "If checked, Frescobaldi will not shorten filenames in the log output."""))
    
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("log")
        font = QFont(s.value("fontfamily", "monospace"))
        font.setPointSizeF(float(s.value("fontsize", 9.0)))
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(font.pointSizeF())
        self.showlog.setChecked(s.value("show_on_start", True) not in (False, "false"))
        self.rawview.setChecked(s.value("rawview", True) not in (False, "false"))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("log")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
        s.setValue("show_on_start", self.showlog.isChecked())
        s.setValue("rawview", self.rawview.isChecked())
Beispiel #18
0
    def setup_method_layout(self):
        self.methods = [method() for method in self.methods]

        self.buttons = []
        for i, method in enumerate(self.methods):
            cb = QCheckBox(self.textify(method.name))
            cb.setChecked(i in self.checked)
            cb.stateChanged.connect(self.update_value)
            cb.setToolTip(self.get_tooltip(method))
            self.method_layout.addWidget(cb)
            self.buttons.append(cb)
Beispiel #19
0
def extra_keywords_to_widgets(extra_keyword_definition):
    """Create widgets for extra keyword.

    :param extra_keyword_definition: An extra keyword definition.
    :type extra_keyword_definition: dict

    :return: QCheckBox and The input widget
    :rtype: (QCheckBox, QWidget)
    """
    # Check box
    check_box = QCheckBox(extra_keyword_definition['name'])
    check_box.setToolTip(extra_keyword_definition['description'])
    check_box.setChecked(True)

    # Input widget
    if extra_keyword_definition['type'] == float:
        input_widget = QDoubleSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == int:
        input_widget = QSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == unicode:
        if extra_keyword_definition.get('options'):
            input_widget = QComboBox()
            options = extra_keyword_definition['options']
            for option in options:
                input_widget.addItem(
                    option['name'],
                    option['key'],
                )
            default_option_index = input_widget.findData(
                extra_keyword_definition['default_option'])
            input_widget.setCurrentIndex(default_option_index)
        else:
            input_widget = QLineEdit()
    elif extra_keyword_definition['type'] == datetime:
        input_widget = QDateTimeEdit()
        input_widget.setCalendarPopup(True)
        input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy')
        input_widget.setDateTime(datetime.now())
    else:
        raise Exception
    input_widget.setToolTip(extra_keyword_definition['description'])

    # Signal
    # noinspection PyUnresolvedReferences
    check_box.stateChanged.connect(input_widget.setEnabled)

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

        layout = QGridLayout()
        self.setLayout(layout)

        self.targetPDF = QRadioButton(toggled=page.changed)
        self.targetSVG = QRadioButton(toggled=page.changed)
        self.openDefaultView = QCheckBox(clicked=page.changed)

        layout.addWidget(self.targetPDF, 0, 0)
        layout.addWidget(self.targetSVG, 0, 1)
        layout.addWidget(self.openDefaultView, 1, 0, 1, 5)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Default output format"))
        self.targetPDF.setText(_("PDF"))
        self.targetPDF.setToolTip(
            _("Create PDF (Portable Document Format) documents by default."))
        self.targetSVG.setText(_("SVG"))
        self.targetSVG.setToolTip(
            _("Create SVG (Scalable Vector Graphics) documents by default."))
        self.openDefaultView.setText(
            _("Open default viewer after successful compile"))
        self.openDefaultView.setToolTip(
            _("Shows the PDF or SVG music view when a compile job finishes "
              "successfully."))

    def loadSettings(self):
        s = settings()
        target = s.value("default_output_target", "pdf", type(""))
        if target == "svg":
            self.targetSVG.setChecked(True)
            self.targetPDF.setChecked(False)
        else:
            self.targetSVG.setChecked(False)
            self.targetPDF.setChecked(True)
        self.openDefaultView.setChecked(
            s.value("open_default_view", True, bool))

    def saveSettings(self):
        s = settings()
        if self.targetSVG.isChecked():
            target = "svg"
        else:
            target = "pdf"
        s.setValue("default_output_target", target)
        s.setValue("open_default_view", self.openDefaultView.isChecked())
Beispiel #22
0
class Running(preferences.Group):
    def __init__(self, page):
        super(Running, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.saveDocument = QCheckBox(clicked=self.changed)
        self.deleteFiles = QCheckBox(clicked=self.changed)
        self.embedSourceCode = QCheckBox(clicked=self.changed)
        self.noTranslation = QCheckBox(clicked=self.changed)
        self.includeLabel = QLabel()
        self.include = widgets.listedit.FilePathEdit()
        self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove)
        self.include.changed.connect(self.changed)
        layout.addWidget(self.saveDocument)
        layout.addWidget(self.deleteFiles)
        layout.addWidget(self.embedSourceCode)
        layout.addWidget(self.noTranslation)
        layout.addWidget(self.includeLabel)
        layout.addWidget(self.include)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Running LilyPond"))
        self.saveDocument.setText(_("Save document if possible"))
        self.saveDocument.setToolTip(_(
            "If checked, the document is saved when it is local and modified.\n"
            "Otherwise a temporary file is used to run LilyPond."))
        self.deleteFiles.setText(_("Delete intermediate output files"))
        self.deleteFiles.setToolTip(_(
            "If checked, LilyPond will delete intermediate PostScript files."))
        self.embedSourceCode.setText(_("Embed Source Code files in publish mode"))
        self.embedSourceCode.setToolTip(_(
            "If checked, the LilyPond source files will be embedded in the PDF\n"
            "when LilyPond is started in publish mode.\n"
            "This feature is available since LilyPond 2.19.39."))
        self.noTranslation.setText(_("Run LilyPond with English messages"))
        self.noTranslation.setToolTip(_(
            "If checked, LilyPond's output messages will be in English.\n"
            "This can be useful for bug reports."))
        self.includeLabel.setText(_("LilyPond include path:"))
    
    def loadSettings(self):
        s = settings()
        self.saveDocument.setChecked(s.value("save_on_run", False, bool))
        self.deleteFiles.setChecked(s.value("delete_intermediate_files", True, bool))
        self.embedSourceCode.setChecked(s.value("embed_source_code", False, bool))
        self.noTranslation.setChecked(s.value("no_translation", False, bool))
        include_path = qsettings.get_string_list(s, "include_path")
        self.include.setValue(include_path)
        
    def saveSettings(self):
        s = settings()
        s.setValue("save_on_run", self.saveDocument.isChecked())
        s.setValue("delete_intermediate_files", self.deleteFiles.isChecked())
        s.setValue("embed_source_code", self.embedSourceCode.isChecked())
        s.setValue("no_translation", self.noTranslation.isChecked())
        s.setValue("include_path", self.include.value())
Beispiel #23
0
class StaffGroup(_base.Container):
    @staticmethod
    def title(_=_base.translate):
        return _("Staff Group")

    def accepts(self):
        return (StaffGroup, _base.Part)

    def createWidgets(self, layout):
        self.systemStartLabel = QLabel()
        self.systemStart = QComboBox()
        self.systemStartLabel.setBuddy(self.systemStart)
        self.systemStart.setModel(listmodel.ListModel((
            # L10N: Brace like a piano staff
            (lambda: _("Brace"), 'system_start_brace'),
            # L10N: Bracket like a choir staff
            (lambda: _("Bracket"), 'system_start_bracket'),
            # L10N: Square bracket like a sub-group
            (lambda: _("Square"), 'system_start_square'),
            ), self.systemStart, display=listmodel.translate_index(0),
            icon=lambda item: symbols.icon(item[1])))
        self.systemStart.setIconSize(QSize(64, 64))
        self.connectBarLines = QCheckBox(checked=True)
        
        box = QHBoxLayout()
        box.addWidget(self.systemStartLabel)
        box.addWidget(self.systemStart)
        layout.addLayout(box)
        layout.addWidget(self.connectBarLines)
    
    def translateWidgets(self):
        self.systemStartLabel.setText(_("Type:"))
        self.connectBarLines.setText(_("Connect Barlines"))
        self.connectBarLines.setToolTip(_("If checked, barlines are connected between the staves."))
        self.systemStart.model().update()
    
    def build(self, data, builder):
        s = self.systemStart.currentIndex()
        b = self.connectBarLines.isChecked()
        if s == 0:
            node = ly.dom.GrandStaff()
            if not b:
                ly.dom.Line("\\remove Span_bar_engraver", node.getWith())
        else:
            node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff()
            if s == 2:
                node.getWith()['systemStartDelimiter'] = ly.dom.Scheme("'SystemStartSquare")
        data.nodes.append(node)
        data.music = ly.dom.Simr(node)
Beispiel #24
0
class Target(preferences.Group):
    def __init__(self, page):
        super(Target, self).__init__(page)
        
        layout = QGridLayout()
        self.setLayout(layout)
        
        self.targetPDF = QRadioButton(toggled=page.changed)
        self.targetSVG = QRadioButton(toggled=page.changed)
        self.openDefaultView = QCheckBox(clicked=page.changed)
        
        layout.addWidget(self.targetPDF, 0, 0)
        layout.addWidget(self.targetSVG, 0, 1)
        layout.addWidget(self.openDefaultView, 1, 0, 1, 5)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Default output format"))
        self.targetPDF.setText(_("PDF"))
        self.targetPDF.setToolTip(_(
            "Create PDF (Portable Document Format) documents by default."))
        self.targetSVG.setText(_("SVG"))
        self.targetSVG.setToolTip(_(
            "Create SVG (Scalable Vector Graphics) documents by default."))
        self.openDefaultView.setText(_("Open default viewer after successful compile"))
        self.openDefaultView.setToolTip(_(
            "Shows the PDF or SVG music view when a compile job finishes "
            "successfully."))
    
    def loadSettings(self):
        s = settings()
        target = s.value("default_output_target", "pdf", type(""))
        if target == "svg":
            self.targetSVG.setChecked(True)
            self.targetPDF.setChecked(False)
        else:
            self.targetSVG.setChecked(False)
            self.targetPDF.setChecked(True)
        self.openDefaultView.setChecked(s.value("open_default_view", True, bool))
        
    def saveSettings(self):
        s = settings()
        if self.targetSVG.isChecked():
            target = "svg"
        else:
            target = "pdf"
        s.setValue("default_output_target", target)
        s.setValue("open_default_view", self.openDefaultView.isChecked())
Beispiel #25
0
class SourceExport(preferences.Group):
    def __init__(self, page):
        super(SourceExport, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.numberLines = QCheckBox(toggled=self.changed)
        self.inlineStyleCopy = QCheckBox(toggled=self.changed)
        self.copyHtmlAsPlainText = QCheckBox(toggled=self.changed)
        self.inlineStyleExport = QCheckBox(toggled=self.changed)
        
        layout.addWidget(self.numberLines)
        layout.addWidget(self.inlineStyleCopy)
        layout.addWidget(self.inlineStyleExport)
        layout.addWidget(self.copyHtmlAsPlainText)
        
        app.translateUI(self)
    
    def translateUI(self):
        self.setTitle(_("Source Export Preferences"))
        self.numberLines.setText(_("Show line numbers"))
        self.numberLines.setToolTip('<qt>' + _(
            "If enabled, line numbers are shown in exported HTML or printed "
            "source."))
        self.inlineStyleCopy.setText(_("Use inline style when copying colored HTML"))
        self.inlineStyleCopy.setToolTip('<qt>' + _(
            "If enabled, inline style attributes are used when copying "
            "colored HTML to the clipboard. "
            "Otherwise, a CSS stylesheet is embedded."))
        
        self.inlineStyleExport.setText(_("Use inline style when exporting colored HTML"))
        self.inlineStyleExport.setToolTip('<qt>' + _(
            "If enabled, inline style attributes are used when exporing "
            "colored HTML to a file. "
            "Otherwise, a CSS stylesheet is embedded."))
        self.copyHtmlAsPlainText.setText(_("Copy HTML as plain text"))
        self.copyHtmlAsPlainText.setToolTip('<qt>' + _(
            "If enabled, HTML is copied to the clipboard as plain text. "
            "Use this when you want to type HTML formatted code in a "
            "plain text editing environment."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("source_export")
        self.numberLines.setChecked(s.value("number_lines", False, bool))
        self.inlineStyleCopy.setChecked(s.value("inline_copy", True, bool))
        self.inlineStyleExport.setChecked(s.value("inline_export", False, bool))
        self.copyHtmlAsPlainText.setChecked(s.value("copy_html_as_plain_text", False, bool))
    
    def saveSettings(self):
        s = QSettings()
        s.beginGroup("source_export")
        s.setValue("number_lines", self.numberLines.isChecked())
        s.setValue("inline_copy", self.inlineStyleCopy.isChecked())
        s.setValue("inline_export", self.inlineStyleExport.isChecked())
        s.setValue("copy_html_as_plain_text", self.copyHtmlAsPlainText.isChecked())
Beispiel #26
0
 def create_checkbox(self, text, option, default=NoDefault,
                     tip=None, msg_warning=None, msg_info=None,
                     msg_if_enabled=False):
     checkbox = QCheckBox(text)
     if tip is not None:
         checkbox.setToolTip(tip)
     self.checkboxes[checkbox] = (option, default)
     if msg_warning is not None or msg_info is not None:
         def show_message(is_checked):
             if is_checked or not msg_if_enabled:
                 if msg_warning is not None:
                     QMessageBox.warning(self, self.get_name(),
                                         msg_warning, QMessageBox.Ok)
                 if msg_info is not None:
                     QMessageBox.information(self, self.get_name(),
                                             msg_info, QMessageBox.Ok)
         self.connect(checkbox, SIGNAL("clicked(bool)"), show_message)
     return checkbox
Beispiel #27
0
class ViewSettings(preferences.Group):
    def __init__(self, page):
        super(ViewSettings, self).__init__(page)
        
        layout = QGridLayout(spacing=1)
        self.setLayout(layout)
        
        self.wrapLines = QCheckBox(toggled=self.changed)
        self.numContextLines = QSpinBox(minimum=0, maximum=20, valueChanged=self.changed)
        self.numContextLinesLabel = l = QLabel()
        l.setBuddy(self.numContextLines)
        
        layout.addWidget(self.wrapLines, 0, 0, 1, 1)
        layout.addWidget(self.numContextLinesLabel, 1, 0)
        layout.addWidget(self.numContextLines, 1, 1)
        app.translateUI(self)
    
    def translateUI(self):
        self.setTitle(_("View Preferences"))
        self.wrapLines.setText(_("Wrap long lines by default"))
        self.wrapLines.setToolTip('<qt>' + _(
            "If enabled, lines that don't fit in the editor width are wrapped "
            "by default. "
            "Note: when the document is displayed by multiple views, they all "
            "share the same line wrapping width, which might look strange."))
        self.numContextLinesLabel.setText(_("Number of surrounding lines:"))
        self.numContextLines.setToolTip('<qt>' + _(
            "When jumping between search results or clicking on a link, the "
            "text view tries to scroll as few lines as possible. "
            "Here you can speficy how many surrounding lines at least should "
            "be visible."))
        self.numContextLinesLabel.setToolTip(self.numContextLines.toolTip())

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        self.wrapLines.setChecked(s.value("wrap_lines", False, bool))
        self.numContextLines.setValue(s.value("context_lines", 3, int))
    
    def saveSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        s.setValue("wrap_lines", self.wrapLines.isChecked())
        s.setValue("context_lines", self.numContextLines.value())
Beispiel #28
0
class ViewSettings(preferences.Group):
    def __init__(self, page):
        super(ViewSettings, self).__init__(page)

        layout = QGridLayout(spacing=1)
        self.setLayout(layout)

        self.wrapLines = QCheckBox(toggled=self.changed)
        self.numContextLines = QSpinBox(minimum=0, maximum=20, valueChanged=self.changed)
        self.numContextLinesLabel = l = QLabel()
        l.setBuddy(self.numContextLines)

        layout.addWidget(self.wrapLines, 0, 0, 1, 1)
        layout.addWidget(self.numContextLinesLabel, 1, 0)
        layout.addWidget(self.numContextLines, 1, 1)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("View Preferences"))
        self.wrapLines.setText(_("Wrap long lines by default"))
        self.wrapLines.setToolTip('<qt>' + _(
            "If enabled, lines that don't fit in the editor width are wrapped "
            "by default. "
            "Note: when the document is displayed by multiple views, they all "
            "share the same line wrapping width, which might look strange."))
        self.numContextLinesLabel.setText(_("Number of surrounding lines:"))
        self.numContextLines.setToolTip('<qt>' + _(
            "When jumping between search results or clicking on a link, the "
            "text view tries to scroll as few lines as possible. "
            "Here you can specify how many surrounding lines at least should "
            "be visible."))
        self.numContextLinesLabel.setToolTip(self.numContextLines.toolTip())

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        self.wrapLines.setChecked(s.value("wrap_lines", False, bool))
        self.numContextLines.setValue(s.value("context_lines", 3, int))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("view_preferences")
        s.setValue("wrap_lines", self.wrapLines.isChecked())
        s.setValue("context_lines", self.numContextLines.value())
Beispiel #29
0
class ChordNames(object):
    def createWidgets(self, layout):
        self.chordStyleLabel = QLabel()
        self.chordStyle = QComboBox()
        self.chordStyleLabel.setBuddy(self.chordStyle)
        self.chordStyle.setModel(listmodel.ListModel(chordNameStyles, self.chordStyle,
            display=listmodel.translate))
        self.guitarFrets = QCheckBox()
        
        box = QHBoxLayout()
        box.addWidget(self.chordStyleLabel)
        box.addWidget(self.chordStyle)
        layout.addLayout(box)
        layout.addWidget(self.guitarFrets)
        
    def translateWidgets(self):
        self.chordStyleLabel.setText(_("Chord style:"))
        self.guitarFrets.setText(_("Guitar fret diagrams"))
        self.guitarFrets.setToolTip(_(
            "Show predefined guitar fret diagrams below the chord names "
            "(LilyPond 2.12 and above)."))
        self.chordStyle.model().update()

    def build(self, data, builder):
        p = ly.dom.ChordNames()
        a = data.assign('chordNames')
        ly.dom.Identifier(a.name, p)
        s = ly.dom.ChordMode(a)
        ly.dom.Identifier(data.globalName, s).after = 1
        i = self.chordStyle.currentIndex()
        if i > 0:
            ly.dom.Line('\\{0}Chords'.format(
                ('german', 'semiGerman', 'italian', 'french')[i-1]), s)
        ly.dom.LineComment(_("Chords follow here."), s)
        ly.dom.BlankLine(s)
        data.nodes.append(p)
        if self.guitarFrets.isChecked():
            f = ly.dom.FretBoards()
            ly.dom.Identifier(a.name, f)
            data.nodes.append(f)
            data.includes.append("predefined-guitar-fretboards.ly")
Beispiel #30
0
class ConfigWidget(QWidget):
    
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.liveCheckBox = QCheckBox("Live Source")
        self.liveCheckBox.setToolTip('Act as a live video source')
        layout.addWidget(self.liveCheckBox)
        
        formWidget = QWidget()
        formLayout = QFormLayout()
        formWidget.setLayout(formLayout)
        layout.addWidget(formWidget)
        
        self.patternLabel = QLabel("Pattern")
        self.patternComboBox = QComboBox()
        
        formLayout.addRow(self.patternLabel, self.patternComboBox)
Beispiel #31
0
class ConfigWidget(QWidget):

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

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.liveCheckBox = QCheckBox("Live Source")
        self.liveCheckBox.setToolTip('Act as a live video source')
        layout.addWidget(self.liveCheckBox)

        formWidget = QWidget()
        formLayout = QFormLayout()
        formWidget.setLayout(formLayout)
        layout.addWidget(formWidget)

        self.patternLabel = QLabel("Pattern")
        self.patternComboBox = QComboBox()

        formLayout.addRow(self.patternLabel, self.patternComboBox)
Beispiel #32
0
    def getArguments(self, parent=None):
        description = "The CSV export requires some information before it starts:"
        dialog = CustomDialog("CSV Export", description, parent)

        default_csv_output_path = self.getDataKWValue("CSV_OUTPUT_PATH", default="output.csv")
        output_path_model = PathModel(default_csv_output_path)
        output_path_chooser = PathChooser(output_path_model)

        design_matrix_default = self.getDataKWValue("DESIGN_MATRIX_PATH", default="")
        design_matrix_path_model = PathModel(design_matrix_default, is_required=False, must_exist=True)
        design_matrix_path_chooser = PathChooser(design_matrix_path_model)

        list_edit = ListEditBox(self.getAllCaseList())

        infer_iteration_check = QCheckBox()
        infer_iteration_check.setChecked(True)
        infer_iteration_check.setToolTip(CSVExportJob.INFER_HELP)

        dialog.addLabeledOption("Output file path", output_path_chooser)
        dialog.addLabeledOption("Design Matrix path", design_matrix_path_chooser)
        dialog.addLabeledOption("List of cases to export", list_edit)
        dialog.addLabeledOption("Infer iteration number", infer_iteration_check)

        dialog.addButtons()

        success = dialog.showAndTell()

        if success:
            design_matrix_path = design_matrix_path_model.getPath()
            if design_matrix_path.strip() == "":
                design_matrix_path = None

            case_list = ",".join(list_edit.getItems())

            return [output_path_model.getPath(), case_list, design_matrix_path, infer_iteration_check.isChecked()]

        raise CancelPluginException("User cancelled!")
Beispiel #33
0
    def getArguments(self, parent=None):
        description = "The GEN_DATA RFT CSV export requires some information before it starts:"
        dialog = CustomDialog("Robust CSV Export", description, parent)

        output_path_model = PathModel("output.csv")
        output_path_chooser = PathChooser(output_path_model)

        trajectory_model = PathModel("wellpath", must_be_a_directory=True, must_be_a_file=False, must_exist=True)
        trajectory_chooser = PathChooser(trajectory_model)

        fs_manager = self.ert().getEnkfFsManager()
        all_case_list = fs_manager.getCaseList()
        all_case_list = [case for case in all_case_list if fs_manager.caseHasData(case)]
        list_edit = ListEditBox(all_case_list)

        infer_iteration_check = QCheckBox()
        infer_iteration_check.setChecked(True)
        infer_iteration_check.setToolTip(GenDataRFTCSVExportJob.INFER_HELP)

        dialog.addLabeledOption("Output file path", output_path_chooser)
        dialog.addLabeledOption("Trajectory file", trajectory_chooser)
        dialog.addLabeledOption("List of cases to export", list_edit)
        dialog.addLabeledOption("Infer iteration number", infer_iteration_check)

        dialog.addButtons()

        success = dialog.showAndTell()

        if success:
            case_list = ",".join(list_edit.getItems())
            try:
                return [output_path_model.getPath(), trajectory_model.getPath(), case_list, infer_iteration_check.isChecked()]
            except ValueError:
                pass

        raise CancelPluginException("User cancelled!")
Beispiel #34
0
class Running(preferences.Group):
    def __init__(self, page):
        super(Running, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.saveDocument = QCheckBox(clicked=self.changed)
        self.deleteFiles = QCheckBox(clicked=self.changed)
        self.noTranslation = QCheckBox(clicked=self.changed)
        self.includeLabel = QLabel()
        self.include = widgets.listedit.FilePathEdit()
        self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove)
        self.include.changed.connect(self.changed)
        layout.addWidget(self.saveDocument)
        layout.addWidget(self.deleteFiles)
        layout.addWidget(self.noTranslation)
        layout.addWidget(self.includeLabel)
        layout.addWidget(self.include)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Running LilyPond"))
        self.saveDocument.setText(_("Save document if possible"))
        self.saveDocument.setToolTip(
            _("If checked, the document is saved when it is local and modified.\n"
              "Otherwise a temporary file is used to run LilyPond."))
        self.deleteFiles.setText(_("Delete intermediate output files"))
        self.deleteFiles.setToolTip(
            _("If checked, LilyPond will delete intermediate PostScript files."
              ))
        self.noTranslation.setText(_("Run LilyPond with English messages"))
        self.noTranslation.setToolTip(
            _("If checked, LilyPond's output messages will be in English.\n"
              "This can be useful for bug reports."))
        self.includeLabel.setText(_("LilyPond include path:"))

    def loadSettings(self):
        s = settings()
        self.saveDocument.setChecked(s.value("save_on_run", False, bool))
        self.deleteFiles.setChecked(
            s.value("delete_intermediate_files", True, bool))
        self.noTranslation.setChecked(s.value("no_translation", False, bool))
        include_path = qsettings.get_string_list(s, "include_path")
        self.include.setValue(include_path)

    def saveSettings(self):
        s = settings()
        s.setValue("save_on_run", self.saveDocument.isChecked())
        s.setValue("delete_intermediate_files", self.deleteFiles.isChecked())
        s.setValue("no_translation", self.noTranslation.isChecked())
        s.setValue("include_path", self.include.value())
Beispiel #35
0
class MusicView(preferences.Group):
    def __init__(self, page):
        super(MusicView, self).__init__(page)

        layout = QGridLayout()
        self.setLayout(layout)

        self.newerFilesOnly = QCheckBox(toggled=self.changed)
        layout.addWidget(self.newerFilesOnly, 0, 0, 1, 3)

        self.magnifierSizeLabel = QLabel()
        self.magnifierSizeSlider = QSlider(Qt.Horizontal,
                                           valueChanged=self.changed)
        self.magnifierSizeSlider.setSingleStep(50)
        self.magnifierSizeSlider.setRange(
            *popplerview.MagnifierSettings.sizeRange)
        self.magnifierSizeSpinBox = QSpinBox()
        self.magnifierSizeSpinBox.setRange(
            *popplerview.MagnifierSettings.sizeRange)
        self.magnifierSizeSpinBox.valueChanged.connect(
            self.magnifierSizeSlider.setValue)
        self.magnifierSizeSlider.valueChanged.connect(
            self.magnifierSizeSpinBox.setValue)
        layout.addWidget(self.magnifierSizeLabel, 1, 0)
        layout.addWidget(self.magnifierSizeSlider, 1, 1)
        layout.addWidget(self.magnifierSizeSpinBox, 1, 2)

        self.magnifierScaleLabel = QLabel()
        self.magnifierScaleSlider = QSlider(Qt.Horizontal,
                                            valueChanged=self.changed)
        self.magnifierScaleSlider.setSingleStep(50)
        self.magnifierScaleSlider.setRange(
            *popplerview.MagnifierSettings.scaleRange)
        self.magnifierScaleSpinBox = QSpinBox()
        self.magnifierScaleSpinBox.setRange(
            *popplerview.MagnifierSettings.scaleRange)
        self.magnifierScaleSpinBox.valueChanged.connect(
            self.magnifierScaleSlider.setValue)
        self.magnifierScaleSlider.valueChanged.connect(
            self.magnifierScaleSpinBox.setValue)
        layout.addWidget(self.magnifierScaleLabel, 2, 0)
        layout.addWidget(self.magnifierScaleSlider, 2, 1)
        layout.addWidget(self.magnifierScaleSpinBox, 2, 2)

        self.enableKineticScrolling = QCheckBox(toggled=self.changed)
        layout.addWidget(self.enableKineticScrolling)
        self.showScrollbars = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showScrollbars)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Music View"))
        self.newerFilesOnly.setText(_("Only load updated PDF documents"))
        self.newerFilesOnly.setToolTip(
            _("If checked, Frescobaldi will not open PDF documents that are not\n"
              "up-to-date (i.e. the source file has been modified later)."))
        self.magnifierSizeLabel.setText(_("Magnifier Size:"))
        self.magnifierSizeLabel.setToolTip(
            _("Size of the magnifier glass (Ctrl+Click in the Music View)."))
        # L10N: as in "400 pixels", appended after number in spinbox, note the leading space
        self.magnifierSizeSpinBox.setSuffix(_(" pixels"))
        self.magnifierScaleLabel.setText(_("Magnifier Scale:"))
        self.magnifierScaleLabel.setToolTip(
            _("Magnification of the magnifier."))
        self.magnifierScaleSpinBox.setSuffix(_("percent unit sign", "%"))
        # L10N: "Kinetic Scrolling" is a checkbox label, as in "Enable Kinetic Scrolling"
        self.enableKineticScrolling.setText(_("Kinetic Scrolling"))
        self.showScrollbars.setText(_("Show Scrollbars"))

    def loadSettings(self):
        s = popplerview.MagnifierSettings.load()
        self.magnifierSizeSlider.setValue(s.size)
        self.magnifierScaleSlider.setValue(s.scale)

        s = QSettings()
        s.beginGroup("musicview")
        newerFilesOnly = s.value("newer_files_only", True, bool)
        self.newerFilesOnly.setChecked(newerFilesOnly)
        kineticScrollingActive = s.value("kinetic_scrolling", True, bool)
        self.enableKineticScrolling.setChecked(kineticScrollingActive)
        showScrollbars = s.value("show_scrollbars", True, bool)
        self.showScrollbars.setChecked(showScrollbars)

    def saveSettings(self):
        s = popplerview.MagnifierSettings()
        s.size = self.magnifierSizeSlider.value()
        s.scale = self.magnifierScaleSlider.value()
        s.save()

        s = QSettings()
        s.beginGroup("musicview")
        s.setValue("newer_files_only", self.newerFilesOnly.isChecked())
        s.setValue("kinetic_scrolling",
                   self.enableKineticScrolling.isChecked())
        s.setValue("show_scrollbars", self.showScrollbars.isChecked())
Beispiel #36
0
class LogTool(preferences.Group):
    def __init__(self, page):
        super(LogTool, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.fontLabel = QLabel()
        self.fontChooser = QFontComboBox(currentFontChanged=self.changed)
        self.fontSize = QDoubleSpinBox(valueChanged=self.changed)
        self.fontSize.setRange(6.0, 32.0)
        self.fontSize.setSingleStep(0.5)
        self.fontSize.setDecimals(1)

        box = QHBoxLayout()
        box.addWidget(self.fontLabel)
        box.addWidget(self.fontChooser, 1)
        box.addWidget(self.fontSize)
        layout.addLayout(box)

        self.showlog = QCheckBox(toggled=self.changed)
        layout.addWidget(self.showlog)

        self.rawview = QCheckBox(toggled=self.changed)
        layout.addWidget(self.rawview)

        self.hideauto = QCheckBox(toggled=self.changed)
        layout.addWidget(self.hideauto)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("LilyPond Log"))
        self.fontLabel.setText(_("Font:"))
        self.showlog.setText(_("Show log when a job is started"))
        self.rawview.setText(_("Display plain log output"))
        self.rawview.setToolTip(
            _("If checked, Frescobaldi will not shorten filenames in the log output."
              ""))
        self.hideauto.setText(_("Hide automatic engraving jobs"))
        self.hideauto.setToolTip(
            _("If checked, Frescobaldi will not show the log for automatically\n"
              "started engraving jobs (LilyPond->Auto-engrave)."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("log")
        font = QFont(s.value("fontfamily", "monospace", type("")))
        font.setPointSizeF(s.value("fontsize", 9.0, float))
        with qutil.signalsBlocked(self.fontChooser, self.fontSize):
            self.fontChooser.setCurrentFont(font)
            self.fontSize.setValue(font.pointSizeF())
        self.showlog.setChecked(s.value("show_on_start", True, bool))
        self.rawview.setChecked(s.value("rawview", True, bool))
        self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("log")
        s.setValue("fontfamily", self.fontChooser.currentFont().family())
        s.setValue("fontsize", self.fontSize.value())
        s.setValue("show_on_start", self.showlog.isChecked())
        s.setValue("rawview", self.rawview.isChecked())
        s.setValue("hide_auto_engrave", self.hideauto.isChecked())
Beispiel #37
0
class SourceExport(preferences.Group):
    def __init__(self, page):
        super(SourceExport, self).__init__(page)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        self.numberLines = QCheckBox(toggled=self.changed)
        self.inlineStyleCopy = QCheckBox(toggled=self.changed)
        self.copyHtmlAsPlainText = QCheckBox(toggled=self.changed)
        self.inlineStyleExport = QCheckBox(toggled=self.changed)
        self.copyDocumentBodyOnly = QCheckBox(toggled=self.changed)

        layout.addWidget(self.numberLines)
        layout.addWidget(self.inlineStyleCopy)
        layout.addWidget(self.inlineStyleExport)
        layout.addWidget(self.copyHtmlAsPlainText)
        layout.addWidget(self.copyDocumentBodyOnly)

        app.translateUI(self)
    
    def translateUI(self):
        self.setTitle(_("Source Export Preferences"))
        self.numberLines.setText(_("Show line numbers"))
        self.numberLines.setToolTip('<qt>' + _(
            "If enabled, line numbers are shown in exported HTML or printed "
            "source."))
        self.inlineStyleCopy.setText(_("Use inline style when copying colored HTML"))
        self.inlineStyleCopy.setToolTip('<qt>' + _(
            "If enabled, inline style attributes are used when copying "
            "colored HTML to the clipboard. "
            "Otherwise, a CSS stylesheet is embedded."))
        
        self.inlineStyleExport.setText(_("Use inline style when exporting colored HTML"))
        self.inlineStyleExport.setToolTip('<qt>' + _(
            "If enabled, inline style attributes are used when exporing "
            "colored HTML to a file. "
            "Otherwise, a CSS stylesheet is embedded."))
        self.copyHtmlAsPlainText.setText(_("Copy HTML as plain text"))
        self.copyHtmlAsPlainText.setToolTip('<qt>' + _(
            "If enabled, HTML is copied to the clipboard as plain text. "
            "Use this when you want to type HTML formatted code in a "
            "plain text editing environment."))
        self.copyDocumentBodyOnly.setText(_("Copy <pre> element only"))
        self.copyDocumentBodyOnly.setToolTip('<qt>' + _(
            "If enabled, only the HTML contents, wrapped in a PRE tag, will be "
            "copied to the clipboard instead of a full HTML document with a "
            "header section. "
            "May be used in conjunction with the plain text option, with the "
            "inline style option turned off, to copy highlighted code in a "
            "text editor when an external style sheet is already available."))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("source_export")
        self.numberLines.setChecked(s.value("number_lines", False, bool))
        self.inlineStyleCopy.setChecked(s.value("inline_copy", True, bool))
        self.inlineStyleExport.setChecked(s.value("inline_export", False, bool))
        self.copyHtmlAsPlainText.setChecked(s.value("copy_html_as_plain_text", False, bool))
        self.copyDocumentBodyOnly.setChecked(s.value("copy_document_body_only", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("source_export")
        s.setValue("number_lines", self.numberLines.isChecked())
        s.setValue("inline_copy", self.inlineStyleCopy.isChecked())
        s.setValue("inline_export", self.inlineStyleExport.isChecked())
        s.setValue("copy_html_as_plain_text", self.copyHtmlAsPlainText.isChecked())
        s.setValue("copy_document_body_only", self.copyDocumentBodyOnly.isChecked())
Beispiel #38
0
class Search(QWidget, plugin.MainWindowPlugin):
    def __init__(self, mainwindow):
        super(Search, self).__init__(mainwindow)
        self._currentView = None
        self._positions = None
        self._replace = False  # are we in replace mode?
        
        mainwindow.currentViewChanged.connect(self.viewChanged)
        mainwindow.actionCollection.edit_find_next.triggered.connect(self.findNext)
        mainwindow.actionCollection.edit_find_previous.triggered.connect(self.findPrevious)
        
        # dont inherit looks from view
        self.setFont(QApplication.font())
        self.setPalette(QApplication.palette())
        
        grid = QGridLayout()
        grid.setContentsMargins(4, 0, 4, 0)
        grid.setVerticalSpacing(0)
        self.setLayout(grid)
        
        self.searchEntry = QLineEdit(textChanged=self.slotSearchChanged)
        self.searchLabel = QLabel()
        self.caseCheck = QCheckBox(checked=True, focusPolicy=Qt.NoFocus)
        self.regexCheck = QCheckBox(focusPolicy=Qt.NoFocus)
        self.countLabel = QLabel(alignment=Qt.AlignRight | Qt.AlignVCenter)
        self.countLabel.setMinimumWidth(QApplication.fontMetrics().width("9999"))
        self.closeButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus)
        self.hideAction = QAction(self, triggered=self.slotHide)
        self.hideAction.setShortcut(QKeySequence(Qt.Key_Escape))
        self.hideAction.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton))
        self.closeButton.setDefaultAction(self.hideAction)
        
        grid.addWidget(self.searchLabel, 0, 0)
        grid.addWidget(self.searchEntry, 0, 1)
        grid.addWidget(self.caseCheck, 0, 2)
        grid.addWidget(self.regexCheck, 0, 3)
        grid.addWidget(self.countLabel, 0, 4)
        grid.addWidget(self.closeButton, 0, 5)
        
        self.caseCheck.toggled.connect(self.slotSearchChanged)
        self.regexCheck.toggled.connect(self.slotSearchChanged)
        
        self.replaceEntry = QLineEdit()
        self.replaceLabel = QLabel()
        self.replaceButton = QPushButton(clicked=self.slotReplace)
        self.replaceAllButton = QPushButton(clicked=self.slotReplaceAll)
        
        grid.addWidget(self.replaceLabel, 1, 0)
        grid.addWidget(self.replaceEntry, 1, 1)
        grid.addWidget(self.replaceButton, 1, 2)
        grid.addWidget(self.replaceAllButton, 1, 3)
        
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        app.translateUI(self)
        
    def translateUI(self):
        self.searchLabel.setText(_("Search:"))
        self.caseCheck.setText(_("&Case"))
        self.caseCheck.setToolTip(_("Case Sensitive"))
        self.regexCheck.setText(_("&Regex"))
        self.regexCheck.setToolTip(_("Regular Expression"))
        self.countLabel.setToolTip(_("The total number of matches"))
        self.hideAction.setToolTip(_("Close"))
        self.replaceLabel.setText(_("Replace:"))
        self.replaceButton.setText(_("Re&place"))
        self.replaceButton.setToolTip(_("Replaces the next occurrence of the search term."))
        self.replaceAllButton.setText(_("&All"))
        self.replaceAllButton.setToolTip(_("Replaces all occurrences of the search term in the document or selection."))
    
    def readSettings(self):
        data = textformats.formatData('editor')
        self.searchEntry.setFont(data.font)
        self.replaceEntry.setFont(data.font)
        p = data.palette()
        self.searchEntry.setPalette(p)
        self.replaceEntry.setPalette(p)
         
    def currentView(self):
        return self._currentView and self._currentView()
    
    def setCurrentView(self, view):
        self._currentView = weakref.ref(view) if view else None
        
    def showWidget(self):
        if self.isVisible():
            self.hideWidget()
        view = self.window().currentView()
        self.setCurrentView(view)
        layout = widgets.borderlayout.BorderLayout.get(view)
        layout.addWidget(self, widgets.borderlayout.BOTTOM)
        self.show()
        
    def hideWidget(self):
        view = self.currentView()
        if view:
            viewhighlighter.highlighter(view).clear("search")
            self.hide()
            layout = widgets.borderlayout.BorderLayout.get(view)
            layout.removeWidget(self)
    
    def viewChanged(self, new):
        self.setParent(None)
        self.hideWidget()
        self.setCurrentView(new)
        self.updatePositions()
        
    def slotHide(self):
        view = self.currentView()
        if view:
            self.hideWidget()
            view.setFocus()
        
    def find(self):
        # hide replace stuff
        self.replaceLabel.hide()
        self.replaceEntry.hide()
        self.replaceButton.hide()
        self.replaceAllButton.hide()
        self._replace = False # we are not in replace mode
        visible = self.isVisible()
        if not visible:
            with qutil.signalsBlocked(self.searchEntry):
                self.searchEntry.clear()
        self.showWidget()
        if not visible and self.currentView():
            # pick current word
            cursor = self.currentView().textCursor()
            cursor.movePosition(QTextCursor.StartOfWord)
            cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)
            word = cursor.selection().toPlainText()
            if not re.search(r'\w', word):
                word = ""
            self.searchEntry.setText(word)
            self.searchEntry.selectAll()
        else:
            self.slotSearchChanged()
        self.searchEntry.setFocus()
        
    def replace(self):
        # show replace stuff
        self.replaceLabel.show()
        self.replaceEntry.show()
        self.replaceButton.show()
        self.replaceAllButton.show()
        focus = self.replaceEntry if self.isVisible() and self.searchEntry.text() else self.searchEntry
        self._replace = True # we are in replace mode
        self.showWidget()
        self.slotSearchChanged()
        focus.setFocus()
        
    def slotSearchChanged(self):
        self.updatePositions()
        viewhighlighter.highlighter(self.currentView()).highlight("search", self._positions, 1)

    def updatePositions(self):
        search = self.searchEntry.text()
        view = self.currentView()
        document = view.document()
        self._positions = []
        if search:
            text = document.toPlainText()
            flags = re.MULTILINE | re.DOTALL
            if not self.caseCheck.isChecked():
                flags |= re.IGNORECASE
            if not self.regexCheck.isChecked():
                search = re.escape(search)
            try:
                matches = re.finditer(search, text, flags)
            except re.error:
                pass
            else:
                for m in matches:
                    c = QTextCursor(document)
                    c.setPosition(m.end())
                    c.setPosition(m.start(), QTextCursor.KeepAnchor)
                    self._positions.append(c)
        self.countLabel.setText(unicode(len(self._positions)))
        
    def findNext(self):
        view = self.currentView()
        if view and self._positions:
            positions = [c.position() for c in self._positions]
            index = bisect.bisect_right(positions, view.textCursor().position())
            if index < len(positions):
                view.setTextCursor(self._positions[index])
            else:
                view.setTextCursor(self._positions[0])
            view.ensureCursorVisible()

    def findPrevious(self):
        view = self.currentView()
        positions = [c.position() for c in self._positions]
        if view and positions:
            index = bisect.bisect_left(positions, view.textCursor().position()) - 1
            view.setTextCursor(self._positions[index])
            view.ensureCursorVisible()

    def keyPressEvent(self, ev):
        if ev.key() == Qt.Key_Tab:
            # prevent Tab from reaching the View widget
            self.window().focusNextChild()
            return
        # if in search mode, Up and Down jump between search results
        if not self._replace and self._positions and self.searchEntry.text() and not ev.modifiers():
            if ev.key() == Qt.Key_Up:
                self.findPrevious()
                return
            elif ev.key() ==  Qt.Key_Down:
                self.findNext()
                return
        # use enter or return for search next
        if ev.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.findNext()
            return
        super(Search, self).keyPressEvent(ev)

    def doReplace(self, cursor):
        text = cursor.selection().toPlainText()
        search = self.searchEntry.text()
        replace = self.replaceEntry.text()
        ok = text == self.searchEntry.text()
        if self.regexCheck.isChecked():
            m = re.match(search, text)
            ok = False
            if m:
                try:
                    replace = m.expand(replace)
                    ok = True
                except re.error:
                    pass
        if ok:
            pos = cursor.position()
            cursor.insertText(replace)
            cursor.setPosition(pos, QTextCursor.KeepAnchor)
        return ok
        
    def slotReplace(self):
        view = self.currentView()
        if view and self._positions:
            positions = [c.position() for c in self._positions]
            index = bisect.bisect_left(positions, view.textCursor().position())
            if index >= len(positions):
                index = 0
            if self.doReplace(self._positions[index]):
                viewhighlighter.highlighter(view).highlight("search", self._positions, 1)
                if index < len(positions) - 1:
                    view.setTextCursor(self._positions[index+1])
                else:
                    view.setTextCursor(self._positions[0])
                view.ensureCursorVisible()
    
    def slotReplaceAll(self):
        view = self.currentView()
        if view:
            replaced = False
            cursors = self._positions
            if view.textCursor().hasSelection():
                cursors = [cursor for cursor in cursors if cursortools.contains(view.textCursor(), cursor)]
            view.textCursor().beginEditBlock()
            for cursor in cursors:
                if self.doReplace(cursor):
                    replaced = True
            view.textCursor().endEditBlock()
            if replaced:
                viewhighlighter.highlighter(view).highlight("search", self._positions, 1)
Beispiel #39
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 #40
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        
        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None
        
        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(checked=
            QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()
        
        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')
        
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Reset |
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        top = QHBoxLayout()
        top.addWidget(self.fromVersionLabel)
        top.addWidget(self.fromVersion)
        top.addWidget(self.reason)
        top.addStretch()
        top.addWidget(self.toVersionLabel)
        top.addWidget(self.toVersion)
        
        layout.addLayout(top)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)
        
        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        
    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(_(
            "If checked, the messages of convert-ly are appended as a "
            "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()
    
    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages', self.copyCheck.isChecked())
    
    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)
        
    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
    
    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(htmldiff.htmldiff(
                self._text, text,
                _("Current Document"), _("Converted Document"),
                wrapcolumn=100))
        else:
            self.diff.clear()
    
    def convertedText(self):
        return self._convertedtext or ''
    
    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()
        
    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(_(
                "Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.convert_ly)
        command += ['-f', fromVersion, '-t', toVersion, '-']
        
        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env = util.bytes_environ()
                env[b'LANGUAGE'] = b'C'
            else:
                env = dict(os.environ)
                env['LANGUAGE'] = 'C'
        
        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                    universal_newlines = True,
                    env = env,
                    stdin = subprocess.PIPE,
                    stdout = subprocess.PIPE,
                    stderr = subprocess.PIPE)
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(_(
                    "Could not start {convert_ly}:\n\n"
                    "{message}\n").format(convert_ly = convert_ly, message = e))
                return
            self.messages.setPlainText(err.decode('UTF-8'))
            self.setConvertedText(out.decode('UTF-8'))
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' + _("The document has not been changed."))
Beispiel #41
0
class Printing(preferences.Group):
    def __init__(self, page):
        super(Printing, self).__init__(page)
        
        layout = QGridLayout(spacing=1)
        self.setLayout(layout)
        
        self.messageLabel = QLabel(wordWrap=True)
        self.printCommandLabel = QLabel()
        self.printCommand = widgets.urlrequester.UrlRequester()
        self.printCommand.setFileMode(QFileDialog.ExistingFile)
        self.printCommand.changed.connect(page.changed)
        self.printDialogCheck = QCheckBox(toggled=page.changed)
        self.resolutionLabel = QLabel()
        self.resolution = QComboBox(editable=True, editTextChanged=page.changed)
        self.resolution.addItems("300 600 1200".split())
        self.resolution.lineEdit().setInputMask("9000")

        layout.addWidget(self.messageLabel, 0, 0, 1, 2)
        layout.addWidget(self.printCommandLabel, 1, 0)
        layout.addWidget(self.printCommand, 1, 1)
        layout.addWidget(self.printDialogCheck, 2, 0, 1, 2)
        layout.addWidget(self.resolutionLabel, 3, 0)
        layout.addWidget(self.resolution, 3, 1)
        
        app.translateUI(self)
    
    def translateUI(self):
        self.setTitle(_("Printing Music"))
        self.messageLabel.setText(_(
            "Here you can enter a command to print a PDF or PostScript file. "
            "See the Help page for more information about printing music."))
        self.printCommandLabel.setText(_("Printing command:"))
        self.printCommand.setToolTip('<qt>' + _(
            "The printing command is used to print a PostScript or PDF file. "
            "On Linux you don't need this, but on Windows and Mac OS X you can "
            "provide a command to avoid that PDF documents are being printed "
            "using raster images, which is less optimal.\n"
            "<code>$pdf</code> gets replaced with the PDF filename, or alternatively, "
            "<code>$ps</code> is replaced with the PostScript filename. "
            "<code>$printer</code> is replaced with the printer's name to use."))
        self.printDialogCheck.setText(_("Use Frescobaldi's print dialog"))
        self.printDialogCheck.setToolTip('<qt>' + _(
            "If enabled, Frescobaldi will show the print dialog and create a "
            "PDF or PostScript document containing only the selected pages "
            "to print. Otherwise, the command is called directly and is expected "
            "to show a print dialog itself."))
        self.resolutionLabel.setText(_("Resolution:"))
        self.resolution.setToolTip(_(
            "Set the resolution if Frescobaldi prints using raster images."))
    
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("helper_applications")
        self.printCommand.setPath(s.value("printcommand", "", type("")))
        self.printDialogCheck.setChecked(s.value("printcommand/dialog", False, bool))
        with qutil.signalsBlocked(self.resolution):
            self.resolution.setEditText(format(s.value("printcommand/dpi", 300, int)))
    
    def saveSettings(self):
        s= QSettings()
        s.beginGroup("helper_applications")
        s.setValue("printcommand", self.printCommand.path())
        s.setValue("printcommand/dialog", self.printDialogCheck.isChecked())
        s.setValue("printcommand/dpi", int(self.resolution.currentText()))
class MSSQLSpatialConfigPage(QWizardPage):
    def __init__(self,parent=None,key=None):
        super(MSSQLSpatialConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key

        try:
            (msodbc,msserver,msdsn,mstrust,msdbname,msschema,msusr,mspwd,msconfig,msepsg,mscql) = self.parent.mfr.readMSSQLConfig()
        except:
            (msodbc,msserver,msdsn,mstrust,msdbname,msschema,msusr,mspwd,msconfig,msepsg,mscql) = (None,)*11
        
        self.setTitle('MSSQL Spatial Server Configuration Options')
        self.setSubTitle('Enter the server string (host\instance) name and schema of your MSSQL server. Select "Trust" if using trusted authentication')
       
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        serverLabel = QLabel('MSSQLSpatial Server')
        dbnameLabel = QLabel('MSSQLSpatial DB Name')
        schemaLabel = QLabel('MSSQLSpatial DB Schema')
        trustLabel = QLabel('Trust')
        usrLabel = QLabel('Username')
        pwdLabel = QLabel('Password')
        
        #edit boxes
        self.serverEdit = QLineEdit(msserver) 
        self.serverEdit.setToolTip('Enter MSSQL Server string. Format typically <host-name>\<db-instance>')
        self.dbnameEdit = QLineEdit(msdbname)
        self.dbnameEdit.setToolTip('Enter the name of the MSSQL database')
        self.schemaEdit = QLineEdit(msschema)
        self.schemaEdit.setToolTip('Enter schema name (this is not mandatory but a common default in MSSQL is "dbo")')
        self.trustCheckBox = QCheckBox('YES')
        self.trustCheckBox.setChecked(True if mstrust and mstrust.lower()=='yes' else False)
        self.trustCheckBox.setToolTip('Use MSSQL trusted client authentication')
        self.usrEdit = QLineEdit(msusr)
        self.usrEdit.setToolTip('Enter MSSQL Username')
        self.pwdEdit = QLineEdit('')#mspwd
        self.pwdEdit.setToolTip('Enter MSSQL Password')
        self.pwdEdit.setEchoMode(QLineEdit.Password)

        #self.trustEdit.setValidator(QRegExpValidator(QRegExp("yes|no", re.IGNORECASE), self))
        
        self.registerField(self.key+"server",self.serverEdit)
        self.registerField(self.key+"dbname",self.dbnameEdit)
        self.registerField(self.key+"schema",self.schemaEdit)
        self.registerField(self.key+"trust",self.trustCheckBox)
        self.registerField(self.key+"usr",self.usrEdit)
        self.registerField(self.key+"pwd",self.pwdEdit)

        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        #layout
        grid.addWidget(serverLabel, 1, 0)
        grid.addWidget(self.serverEdit, 1, 2)
        
        grid.addWidget(dbnameLabel, 2, 0)
        grid.addWidget(self.dbnameEdit, 2, 2)
        
        grid.addWidget(schemaLabel, 3, 0)
        grid.addWidget(self.schemaEdit, 3, 2)
        
        grid.addWidget(trustLabel, 4, 0)
        grid.addWidget(self.trustCheckBox, 4, 2)
        
        grid.addWidget(usrLabel, 5, 0)
        grid.addWidget(self.usrEdit, 5, 2)
        
        grid.addWidget(pwdLabel, 6, 0)
        grid.addWidget(self.pwdEdit, 6, 2)

        self.setLayout(grid)
          
    
    def nextId(self):
        if self.testConnection():
            return self.parent.plist.get('final')[0]
        return self.parent.plist.get('ms')[0]

    
    def testConnection(self):
        if not any(f for f in (self.serverEdit.isModified(),self.dbnameEdit.isModified(),self.schemaEdit.isModified(),
                               self.usrEdit.isModified(),self.pwdEdit.isModified())):
            return False
        cs = MSSQLSpatialDataStore.buildConnStr(self.serverEdit.text(),self.dbnameEdit.text(),self.schemaEdit.text(),
                            'yes' if self.trustCheckBox.isChecked() else 'no',self.usrEdit.text(),self.pwdEdit.text())
        ms = MSSQLSpatialDataStore(cs,None)
        ms.applyConfigOptions()
        try:
            ms.initDS(ms.destinationURI(None),False)
            #ms.checkGeoPrivileges(self.usrEdit.text())
        except DSReaderException as dse:
            QMessageBox.warning(self, 'Connection Error', 'Cannot connect to MS data base using parameters provided: '+str(dse), 'OK')
            return False
        return True
Beispiel #43
0
        trajectory_model = PathModel("wellpath",
                                     must_be_a_directory=True,
                                     must_be_a_file=False,
                                     must_exist=True)
        trajectory_chooser = PathChooser(trajectory_model)

        fs_manager = self.ert().getEnkfFsManager()
        all_case_list = fs_manager.getCaseList()
        all_case_list = [
            case for case in all_case_list if fs_manager.caseHasData(case)
        ]
        list_edit = ListEditBox(all_case_list)

        infer_iteration_check = QCheckBox()
        infer_iteration_check.setChecked(True)
        infer_iteration_check.setToolTip(GenDataRFTCSVExportJob.INFER_HELP)

        drop_const_columns_check = QCheckBox()
        drop_const_columns_check.setChecked(False)
        drop_const_columns_check.setToolTip(
            "If checked, exclude columns whose value is the same for every entry"
        )

        dialog.addLabeledOption("Output file path", output_path_chooser)
        dialog.addLabeledOption("Trajectory file", trajectory_chooser)
        dialog.addLabeledOption("List of cases to export", list_edit)
        dialog.addLabeledOption("Infer iteration number",
                                infer_iteration_check)
        dialog.addLabeledOption("Drop constant columns",
                                drop_const_columns_check)
Beispiel #44
0
class Viewer(ViewerBase, ViewerClass):
    trackingChanged = pyqtSignal(bool)
    setLocationTriggered = pyqtSignal()
    updateFeatures = pyqtSignal(bool)
    layerChanged = pyqtSignal(QgsMapLayer)
    clearLine = pyqtSignal()
    closed = pyqtSignal()

    def __init__(self, callbackobject, parent=None):
        """Constructor."""
        super(Viewer, self).__init__(parent)
        self.setupUi(self)
        self.callbackobject = callbackobject
        self.frame = self.webview.page().mainFrame()
        self.actiongroup = QActionGroup(self)
        self.actiongroup.setExclusive(True)
        self.actiongroup.triggered.connect(self.action_triggered)

        self.measuredialog = MeasureDialog(self)

        self.toolbar = QToolBar()
        self.qgisTrackButton = self.toolbar.addAction("QGIS Track")
        self.qgisTrackButton.setIcon(QIcon(":/icons/track"))
        self.qgisTrackButton.setCheckable(True)
        self.qgisTrackButton.setChecked(True)
        self.qgisTrackButton.toggled.connect(self.trackingChanged.emit)

        self.setlocationaction = self.toolbar.addAction("Set location")
        self.setlocationaction.setIcon(QIcon(":/icons/location"))
        self.setlocationaction.triggered.connect(
            self.setLocationTriggered.emit)
        self.setlocationaction.setCheckable(True)

        self.viewfeatures = self.toolbar.addAction("Load QGIS Features")
        self.viewfeatures.setIcon(QIcon(":/icons/features"))
        self.viewfeatures.setCheckable(True)
        self.viewfeatures.setChecked(True)
        self.viewfeatures.toggled.connect(self.updateFeatures.emit)

        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.toolbar.addWidget(spacer)

        self.measureaction = self.toolbar.addAction("measure")
        self.measureaction.setObjectName("Measure")
        self.measureaction.setIcon(QIcon(":/icons/measure"))
        self.measureaction.setCheckable(True)

        self.infoaction = self.toolbar.addAction("Info")
        self.infoaction.setObjectName("Info")
        self.infoaction.setIcon(QIcon(":/icons/info"))
        self.infoaction.setCheckable(True)

        self.selectaction = self.toolbar.addAction("Select")
        self.selectaction.setObjectName("Select")
        self.selectaction.setIcon(QIcon(":/icons/select"))
        self.selectaction.setCheckable(True)

        self.toolbar.addSeparator()

        self.deleteaction = self.toolbar.addAction("Delete")
        self.deleteaction.setIcon(QIcon(":/icons/delete"))
        self.deleteaction.triggered.connect(self.delete_selected)
        self.deleteaction.setEnabled(False)

        self.addaction = self.toolbar.addAction("Add")
        self.addaction.setObjectName("Add")
        self.addaction.setIcon(QIcon(":/icons/add"))
        self.addaction.setCheckable(True)

        self.moveaction = self.toolbar.addAction("Move")
        self.moveaction.setObjectName("Move")
        self.moveaction.setIcon(QIcon(":/icons/move"))
        self.moveaction.setCheckable(True)

        self.actiongroup.addAction(self.moveaction)
        self.actiongroup.addAction(self.addaction)
        self.actiongroup.addAction(self.infoaction)
        self.actiongroup.addAction(self.measureaction)
        self.actiongroup.addAction(self.selectaction)

        self.activelayercombo = QgsMapLayerComboBox()
        self.activelayercombo.layerChanged.connect(self.layer_changed)
        self.activelayeraction = self.toolbar.addWidget(self.activelayercombo)
        self.activelayercombo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.activelayercombo.currentIndexChanged.connect(self.index_changed)

        self.zvaluecheck = QCheckBox()
        self.zvaluecheck.setChecked(True)
        self.zvaluecheck.setText("Copy Z value")
        self.zvaluecheck.setToolTip(
            "Copy Z value from viewer to new features in QGIS. Must have a field named Z to enable"
        )
        self.zvalueaction = self.toolbar.addWidget(self.zvaluecheck)

        self.dockWidgetContents.layout().insertWidget(0, self.toolbar)

        self.webview.settings().setAttribute(QWebSettings.PluginsEnabled, True)
        self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled,
                                             True)
        self.webview.settings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        self.frame.setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.frame.setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.frame.javaScriptWindowObjectCleared.connect(
            self.addcallbackobject)
        self.measuredialog.modeCombo.currentIndexChanged.connect(
            self.action_triggered)
        self.measuredialog.clearButton.clicked.connect(self.clear_line)

        self.earthmine = EarthmineAPI(self.frame)

    def closeEvent(self, event):
        self.closed.emit()
        super(Viewer, self).closeEvent(event)

    def index_changed(self, index):
        if index == -1:
            self.set_button_states(False, False, False, False)

    def clear_line(self):
        self.clearLine.emit()
        self.earthmine.clearLine()

    @property
    def copyZvalue(self):
        layer = self.active_layer
        if not layer:
            return False

        if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType(
        ) == QGis.Point:
            return self.zvaluecheck.isChecked()
        else:
            return False

    @property
    def geom(self):
        return self.measuredialog.geom

    @geom.setter
    def geom(self, value):
        self.measuredialog.geom = value
        self.measuredialog.update_geom_labels()

    @property
    def tracking(self):
        return self.qgisTrackButton.isChecked()

    @property
    def mode(self):
        return self.measuredialog.mode

    @property
    def active_layer(self):
        return self.activelayercombo.currentLayer()

    def layer_changed(self, layer):
        if not layer:
            self.set_button_states(False, False, False, False)
            return

        if layer.type() == QgsMapLayer.VectorLayer:
            enabledselecttools = layer.geometryType() in [
                QGis.Line, QGis.Point
            ]
            enableedittools = layer.isEditable()
            enabledelete = layer.isEditable() and layer.selectedFeatureCount()
            enablemove = layer.geometryType(
            ) == QGis.Point and layer.isEditable()
        else:
            enabledselecttools = False
            enableedittools = False
            enabledelete = False
            enablemove = False

        self.set_button_states(enabledselecttools, enableedittools,
                               enabledelete, enablemove)
        self.action_triggered()
        self.layerChanged.emit(layer)

    def selection_changed(self, layer):
        if layer == self.active_layer:
            enabledelete = layer.isEditable() and layer.selectedFeatureCount()
            self.deleteaction.setEnabled(enabledelete)

    def set_button_states(self, selecttools, edittools, deleteenabled,
                          moveenabled):
        actions = [self.selectaction, self.infoaction]

        for action in actions:
            action.setEnabled(selecttools)

        editactions = [self.deleteaction, self.moveaction, self.addaction]

        for action in editactions:
            action.setEnabled(edittools)

        if edittools:
            self.deleteaction.setEnabled(deleteenabled)
            self.moveaction.setEnabled(moveenabled)

        for action in editactions:
            if action is self.actiongroup.checkedAction(
            ) and not action.isEnabled():
                self.infoaction.toggle()
                break

        layer = self.active_layer
        if not layer:
            enablez = False
        else:
            enablez = layer.type(
            ) == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Point
        self.zvalueaction.setEnabled(enablez)

    @property
    def current_action_color(self):
        action = self.actiongroup.checkedAction()
        color = int("0x00ff00", 16)
        if action == self.measureaction:
            if self.mode == "Vertical":
                color = int("0x0000ff", 16)

        return color

    def action_triggered(self, *args):
        action = self.actiongroup.checkedAction()
        layer = self.activelayercombo.currentLayer()

        self.clear_line()
        if not action:
            return

        if not action == self.measureaction and (
                not layer or not layer.type() == QgsMapLayer.VectorLayer):
            return

        color = self.current_action_color
        actiondata = {}

        if action == self.measureaction:
            self.measuredialog.show()
            actiondata['mode'] = self.mode
            geomtype = None
            layerid = None
        else:
            self.measuredialog.hide()
            geomtype = QGis.vectorGeometryType(layer.geometryType())
            layerid = layer.id()

        data = dict(action=action.objectName(),
                    layer=layerid,
                    geom=geomtype,
                    actiondata=actiondata,
                    color=color)

        self.earthmine.updateAction(data)

    def active_tool(self):
        action = self.actiongroup.checkedAction()
        if not action:
            return None
        return action.objectName()

    def update_current_layer(self, layer):
        self.activelayercombo.setLayer(layer)

    def addcallbackobject(self):
        self.frame.addToJavaScriptWindowObject("qgis", self.callbackobject)

    def loadviewer(self, url):
        self.webview.load(url)
        self.frame.addToJavaScriptWindowObject("qgis", self.callbackobject)

    def startViewer(self, settings):
        self.earthmine.startViewer(settings)

    def set_location(self, point):
        # # NOTE Set location takes WGS84 make sure you have transformed it first before sending
        self.earthmine.setLocation(point.x(), point.y())

    def clear_features(self):
        self.earthmine.clearFeatures()

    def clear_layer_features(self, layerid):
        self.earthmine.clearLayerObjects(layerid)

    def remove_feature(self, layerid, featureid):
        """
        :param features: A dict of layerid, id, lat, lng
        :return:
        """
        self.earthmine.removeFeature(layerid, featureid)

    def load_features(self, layerdata, features):
        """
        :param features: A dict of layerid, id, lat, lng
        :return:
        """
        self.earthmine.loadFeatures(layerdata, features)

    def layer_loaded(self, layerid):
        return self.earthmine.layerLoaded(layerid)

    def clear_selection(self, layerid):
        self.earthmine.clearSelection(layerid)

    def set_selection(self, layerid, featureids, clearlast=True):
        self.earthmine.setSelection(layerid, featureids, clearlast)

    def edit_feature(self, layerid, featureid, nodes):
        self.earthmine.editFeature(layerid, featureid, nodes)

    def delete_selected(self):
        layer = self.active_layer
        layer.deleteSelectedFeatures()
        def populateStatusBar():
            statusBar = self.statusBar()

            w = QCheckBox("Render", self)
            w.setObjectName('renderCheck')
            w.setToolTip("Toggle map rendering")
            w.setChecked(True)
            statusBar.addPermanentWidget(w)

            w = QCheckBox("Marker", self)
            w.setObjectName('markerCheck')
            w.setToolTip("Toggle marker with cursor position from main map")
            w.setChecked(False)
            statusBar.addPermanentWidget(w, 1)

            w = QCheckBox("Extent", self)
            w.setObjectName('extentCheck')
            w.setToolTip("Show extent of main map")
            w.setChecked(False)
            statusBar.addPermanentWidget(w, 1)

            w = QToolButton(self)
            w.setObjectName('highlightBtn')
            w.setToolTip("Highlight extent in main map")
            w.setText("Highlight")
            statusBar.addPermanentWidget(w, 1)

            w = QLabel("Scale factor:", self)
            w.setObjectName('scaleFactorLabel')
            w.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            statusBar.addPermanentWidget(w, 1)

            w = QDoubleSpinBox(self)
            w.setObjectName('scaleFactorSpin')
            w.setToolTip("Current scale factor of main map")
            w.setMinimum(0.0)
            w.setMaximum(1000.0)
            w.setDecimals(3)
            w.setValue(1)
            w.setSingleStep(.05)
            statusBar.addPermanentWidget(w, 1)

            w = QToolButton(self)
            w.setObjectName('scaleBtn')
            w.setToolTip("Set scale for main map")
            w.setText("Scale: ")
            statusBar.addPermanentWidget(w, 1)
class RecordingWidget(QWidget):
    """Widget containing main recording UI for Freeseer"""

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

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        boldFont = QFont()
        boldFont.setBold(True)

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.standbyIcon = QIcon.fromTheme("system-shutdown")
        recordFallbackIcon = QIcon(":/multimedia/record.png")
        self.recordIcon = QIcon.fromTheme("media-record", recordFallbackIcon)
        stopFallbackIcon = QIcon(":/multimedia/stop.png")
        self.stopIcon = QIcon.fromTheme("media-playback-stop", stopFallbackIcon)
        self.pauseIcon = QIcon.fromTheme("media-playback-pause")
        self.resumeIcon = QIcon.fromTheme("media-playback-start")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"), QIcon.Normal, QIcon.Off)

        self.standbyPushButton = QPushButton("Standby")
        self.standbyPushButton.setToolTip("Standby")
        self.standbyPushButton.setMinimumSize(QSize(0, 40))
        self.standbyPushButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.standbyPushButton.setIcon(self.standbyIcon)
        self.standbyPushButton.setCheckable(True)
        self.standbyPushButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyPushButton)

        self.recordPushButton = QPushButton("Record")
        self.recordPushButton.setToolTip("Record")
        self.recordPushButton.setMinimumSize(QSize(0, 40))
        self.recordPushButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.recordPushButton.setIcon(self.recordIcon)
        self.recordPushButton.setHidden(True)
        self.recordPushButton.setEnabled(False)
        self.recordPushButton.setCheckable(True)
        self.recordPushButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordPushButton)
        self.connect(self.recordPushButton, SIGNAL("toggled(bool)"), self.setRecordIcon)

        self.pauseToolButton = QToolButton()
        self.pauseToolButton.setText("Pause")
        self.pauseToolButton.setToolTip("Pause")
        self.pauseToolButton.setIcon(self.pauseIcon)
        self.pauseToolButton.setMinimumSize(QSize(40, 40))
        self.pauseToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.pauseToolButton.setHidden(True)
        self.pauseToolButton.setEnabled(False)
        self.pauseToolButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseToolButton)
        self.connect(self.pauseToolButton, SIGNAL("toggled(bool)"), self.setPauseIcon)

        playbackIcon = QIcon.fromTheme("video-x-generic")
        self.playPushButton = QPushButton()
        self.playPushButton.setText("Play Video")
        self.playPushButton.setToolTip("Play last recorded Video")
        self.playPushButton.setIcon(playbackIcon)
        self.playPushButton.setMinimumSize(QSize(40, 40))
        self.playPushButton.setMaximumSize(QSize(120, 40))
        self.playPushButton.setHidden(True)
        self.playPushButton.setEnabled(False)
        self.playPushButton.setCheckable(True)
        self.controlRow.addWidget(self.playPushButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self, state):
        if state:
            self.recordPushButton.setIcon(self.stopIcon)
        else:
            self.recordPushButton.setIcon(self.recordIcon)

    def setPauseIcon(self, state):
        if state:
            self.pauseToolButton.setIcon(self.resumeIcon)
        else:
            self.pauseToolButton.setIcon(self.pauseIcon)
Beispiel #47
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(
            checked=QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset
                                        | QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)

        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(
            self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a "
              "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages',
                             self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)

    def slotLilyPondVersionChanged(self):
        self.setLilyPondInfo(self.lilyChooser.lilyPondInfo())

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
        self.messages.clear()

    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(
                htmldiff.htmldiff(self._text,
                                  text,
                                  _("Current Document"),
                                  _("Converted Document"),
                                  wrapcolumn=100))
        else:
            self.diff.clear()

    def convertedText(self):
        return self._convertedtext or ''

    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(
                _("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.convert_ly)
        command += ['-f', fromVersion, '-t', toVersion, '-']

        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env = util.bytes_environ()
                env[b'LANGUAGE'] = b'C'
            else:
                env = dict(os.environ)
                env['LANGUAGE'] = 'C'

        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                                        universal_newlines=True,
                                        env=env,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n"
                      "{message}\n").format(convert_ly=convert_ly, message=e))
                return
            self.messages.setPlainText(err.decode('UTF-8'))
            self.setConvertedText(out.decode('UTF-8'))
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' +
                                     _("The document has not been changed."))
Beispiel #48
0
class DockWidgetTitleBar(QWidget):
    def __init__(self, dockWidget, hasCheckState=False, hasReport=False):
        super(DockWidgetTitleBar, self).__init__(dockWidget)
        q = dockWidget
        self.floatButton = DockWidgetTitleBarButton(self)
        self.floatButton.setIcon(q.style().standardIcon(
            QStyle.SP_TitleBarNormalButton, None, q))
        self.floatButton.clicked.connect(self.toggleFloating)
        self.floatButton.setVisible(True)
        self.floatButton.setToolTip(self.tr("Undock"))
        self.closeButton = DockWidgetTitleBarButton(self)
        self.closeButton.setIcon(q.style().standardIcon(
            QStyle.SP_TitleBarCloseButton, None, q))
        self.closeButton.clicked.connect(dockWidget.close)
        self.closeButton.setVisible(True)
        self.closeButton.setToolTip(self.tr("Close"))

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

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

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

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

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

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

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

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

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

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

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

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

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

    def featuresChanged(self, _features):
        parent = self.parentWidget()
        self.closeButton.setVisible(
            self.hasFeature(parent, QDockWidget.DockWidgetClosable))
        self.floatButton.setVisible(
            self.hasFeature(parent, QDockWidget.DockWidgetFloatable))
Beispiel #49
0
class General(preferences.Group):
    def __init__(self, page):
        super(General, self).__init__(page)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        self.langLabel = QLabel()
        self.lang = QComboBox(currentIndexChanged=self.changed)
        grid.addWidget(self.langLabel, 0, 0)
        grid.addWidget(self.lang, 0, 1)
        
        self.styleLabel = QLabel()
        self.styleCombo = QComboBox(currentIndexChanged=self.changed)
        grid.addWidget(self.styleLabel, 1, 0)
        grid.addWidget(self.styleCombo, 1, 1)
        
        self.systemIcons = QCheckBox(toggled=self.changed)
        grid.addWidget(self.systemIcons, 2, 0, 1, 3)
        self.tabsClosable = QCheckBox(toggled=self.changed)
        grid.addWidget(self.tabsClosable, 3, 0, 1, 3)
        self.splashScreen = QCheckBox(toggled=self.changed)
        grid.addWidget(self.splashScreen, 4, 0, 1, 3)
        self.allowRemote = QCheckBox(toggled=self.changed)
        grid.addWidget(self.allowRemote, 5, 0, 1, 3)
        
        grid.setColumnStretch(2, 1)
        
        # fill in the language combo
        self._langs = ["C", ""]
        self.lang.addItems(('', ''))
        langnames = [(language_names.languageName(lang, lang), lang) for lang in po.available()]
        langnames.sort()
        for name, lang in langnames:
            self._langs.append(lang)
            self.lang.addItem(name)
        
        # fill in style combo
        self.styleCombo.addItem('')
        self.styleCombo.addItems(QStyleFactory.keys())
        
        app.translateUI(self)
    
    def loadSettings(self):
        s = QSettings()
        lang = s.value("language", "", type(""))
        try:
            index = self._langs.index(lang)
        except ValueError:
            index = 1
        self.lang.setCurrentIndex(index)
        style = s.value("guistyle", "", type("")).lower()
        styles = [name.lower() for name in QStyleFactory.keys()]
        try:
            index = styles.index(style) + 1
        except ValueError:
            index = 0
        self.styleCombo.setCurrentIndex(index)
        self.systemIcons.setChecked(s.value("system_icons", True, bool))
        self.tabsClosable.setChecked(s.value("tabs_closable", True, bool))
        self.splashScreen.setChecked(s.value("splash_screen", True, bool))
        self.allowRemote.setChecked(remote.enabled())
    
    def saveSettings(self):
        s = QSettings()
        s.setValue("language", self._langs[self.lang.currentIndex()])
        s.setValue("system_icons", self.systemIcons.isChecked())
        s.setValue("tabs_closable", self.tabsClosable.isChecked())
        s.setValue("splash_screen", self.splashScreen.isChecked())
        s.setValue("allow_remote", self.allowRemote.isChecked())
        if self.styleCombo.currentIndex() == 0:
            s.remove("guistyle")
        else:
            s.setValue("guistyle", self.styleCombo.currentText())
        
    def translateUI(self):
        self.setTitle(_("General Preferences"))
        self.langLabel.setText(_("Language:"))
        self.lang.setItemText(0, _("No Translation"))
        self.lang.setItemText(1, _("System Default Language (if available)"))
        self.styleLabel.setText(_("Style:"))
        self.styleCombo.setItemText(0, _("Default"))
        self.systemIcons.setText(_("Use System Icons"))
        self.systemIcons.setToolTip(_(
            "If checked, icons of the desktop icon theme "
            "will be used instead of the bundled icons.\n"
            "This setting takes effect on the next start of {appname}.").format(appname=appinfo.appname))
        self.splashScreen.setText(_("Show Splash Screen on Startup"))
        self.tabsClosable.setText(_("Show Close Button on Document tabs"))
        self.allowRemote.setText(_("Open Files in Running Instance"))
        self.allowRemote.setToolTip(_(
            "If checked, files will be opened in a running Frescobaldi "
            "application if available, instead of starting a new instance."))
class LDSConfigPage(QWizardPage):
    def __init__(self, parent=None,key=None):
        super(LDSConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key#'lds'
        
        try:
            (ldsurl,ldskey,ldssvc,ldsver,ldsfmt,ldscql) = self.parent.mfr.readLDSConfig()
        except:
            (ldsurl,ldskey,ldssvc,ldsver,ldsfmt,ldscql) = (None,)*6
        
        self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options')
        self.setSubTitle('Here you can enter a name for your custom configuration file, your LDS API key and required output. Also select whether you want to configure a proxy or enable password encryption')

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        fileLabel = QLabel('User Config File')
        keyLabel = QLabel('LDS API Key')
        destLabel = QLabel('Output Type')
        internalLabel = QLabel('Save Layer-Config in DB')
        self.warnLabel = QLabel('!!!')
        encryptionLabel = QLabel('Enable Password Protection')
        serviceLabel = QLabel('Service Type')
        versionLabel = QLabel('Service Version')
        
        
        infoLinkLabel = QLabel('<a href="http://www.linz.govt.nz/about-linz/linz-data-service/features/how-to-use-web-services">LDS API Information Page</a>')
        infoLinkLabel.setOpenExternalLinks(True);
        keyLinkLabel = QLabel('<a href="http://data.linz.govt.nz/my/api/">LDS API Key</a>')
        keyLinkLabel.setOpenExternalLinks(True);

        #edit boxes
        self.fileEdit = QLineEdit(self.parent.uchint)
        self.fileEdit.setToolTip('Name of user config file (without .conf suffix)')
        self.keyEdit = QLineEdit(ldskey)
        self.keyEdit.setToolTip('This is your LDS API key. If you have an account you can copy your key from here <a href="http://data.linz.govt.nz/my/api/">http://data.linz.govt.nz/my/api/</a>')
               
        #dropdown
        self.destSelect = QComboBox()
        self.destSelect.setToolTip('Choose from one of four possible output destinations')
        self.destSelect.addItem('')
        for itemkey in ('pg','ms','fg','sl'):
            itemindex = self.parent.plist.get(itemkey)[0]
            itemdata = self.parent.plist.get(itemkey)[1]
            self.destSelect.addItem(itemdata, itemindex)
            if itemdata == self.parent.sechint:
                self.destSelect.setCurrentIndex(itemindex)
                
        self.serviceSelect = QComboBox()
        self.serviceSelect.setToolTip('Choose from WFS (or one day, WMS)')
        for itemkey in ('','WFS','WMS','WMTS'):
            self.serviceSelect.addItem(itemkey)
            self.serviceSelect.setCurrentIndex(0)        
            
        self.versionSelect = QComboBox()
        self.versionSelect.setToolTip('Choose service Version')
        for itemkey in ('','1.0.0','1.1.0','2.0.0'):
            self.versionSelect.addItem(itemkey)
            self.versionSelect.setCurrentIndex(0)
        
        
        self.keyEdit.setValidator(QRegExpValidator(QRegExp("[a-fA-F0-9]{32}", re.IGNORECASE), self))
        
        #checkbox
        self.internalEnable = QCheckBox()
        self.internalEnable.setToolTip('Enable saving layer-config (per layer config and progress settings) internally')
        self.internalEnable.toggle()
        self.internalEnable.setChecked(True)
        self.internalEnable.stateChanged.connect(self.setWarn)
        
        self.encryptionEnable = QCheckBox()
        self.encryptionEnable.setToolTip('Encrypt any passwords saved to user config file')

        
        self.registerField(self.key+"file",self.fileEdit)
        self.registerField(self.key+"apikey",self.keyEdit)
        self.registerField(self.key+"dest",self.destSelect,"currentIndex")
        self.registerField(self.key+"internal",self.internalEnable)
        self.registerField(self.key+"encryption",self.encryptionEnable)

        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        grid.addWidget(fileLabel, 1, 0)
        grid.addWidget(self.fileEdit, 1, 2)
        #grid.addWidget(cfileButton, 1, 3)        
        
        grid.addWidget(keyLabel, 2, 0)
        grid.addWidget(self.keyEdit, 2, 2)
        
        grid.addWidget(destLabel, 3, 0)
        grid.addWidget(self.destSelect, 3, 2)
        
        grid.addWidget(internalLabel, 4, 0)
        grid.addWidget(self.internalEnable, 4, 2)
        #if self.internalEnable.checkState(): grid.addWidget(intwarnLabel, 4, 4)
        
        grid.addWidget(encryptionLabel, 5, 0)
        grid.addWidget(self.encryptionEnable, 5, 2)
        
        svgrid = QGridLayout()
        svgrid.addWidget(serviceLabel, 0, 0) 
        svgrid.addWidget(self.serviceSelect, 0, 2) 
        svgrid.addWidget(versionLabel, 1, 0) 
        svgrid.addWidget(self.versionSelect, 1, 2)
        
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(svgrid)

        #layout       
        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        #vbox.addLayout(hbox)
        vbox.addStretch(1)
        vbox.addWidget(self.warnLabel)
        vbox.addWidget(keyLinkLabel)
        vbox.addWidget(infoLinkLabel)
        
        self.setLayout(vbox)
        
    #def selectConfFile(self):
    #    self.fileEdit.setText(QFileDialog.getOpenFileName())

    def nextId(self):
        #if self.field(self.key+"proxy").toBool():
        return self.parent.plist.get('proxy')[0]
        #return int(self.field(self.key+"dest").toString())
        
    def setWarn(self):
        if self.internalEnable.checkState(): 
            ldslog.warn('Warning, Internal config selected')
            self.warnLabel.setText('!!!')
            QApplication.processEvents()
        else:
            ldslog.warn('External config selected')
            self.warnLabel.setText('^_^')
            QApplication.processEvents()
Beispiel #51
0
        dialog = CustomDialog("Robust CSV Export", description, parent)

        output_path_model = PathModel("output.csv")
        output_path_chooser = PathChooser(output_path_model)

        trajectory_model = PathModel("wellpath", must_be_a_directory=True, must_be_a_file=False, must_exist=True)
        trajectory_chooser = PathChooser(trajectory_model)

        fs_manager = self.ert().getEnkfFsManager()
        all_case_list = fs_manager.getCaseList()
        all_case_list = [case for case in all_case_list if fs_manager.caseHasData(case)]
        list_edit = ListEditBox(all_case_list)

        infer_iteration_check = QCheckBox()
        infer_iteration_check.setChecked(True)
        infer_iteration_check.setToolTip(GenDataRFTCSVExportJob.INFER_HELP)

        dialog.addLabeledOption("Output file path", output_path_chooser)
        dialog.addLabeledOption("Trajectory file", trajectory_chooser)
        dialog.addLabeledOption("List of cases to export", list_edit)
        dialog.addLabeledOption("Infer iteration number", infer_iteration_check)

        dialog.addButtons()

        success = dialog.showAndTell()

        if success:
            case_list = ",".join(list_edit.getItems())
            try:
                return [output_path_model.getPath(), trajectory_model.getPath(), case_list, infer_iteration_check.isChecked()]
            except ValueError:
Beispiel #52
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ""
        self._convertedtext = ""
        self._encoding = None

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(checked=QSettings().value("convert_ly/copy_messages", True) not in (False, "false"))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, "")
        self.tabw.addTab(self.diff, "")

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset | QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)

        layout = QVBoxLayout()
        self.setLayout(layout)

        top = QHBoxLayout()
        top.addWidget(self.fromVersionLabel)
        top.addWidget(self.fromVersion)
        top.addWidget(self.reason)
        top.addStretch()
        top.addWidget(self.toVersionLabel)
        top.addWidget(self.toVersion)

        layout.addLayout(top)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        util.saveDialogSize(self, "convert_ly/dialog/size", QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a " "comment to the end of the document.")
        )
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue("convert_ly/copy_messages", self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData("editor").font
        self.diff.setFont(font)

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()

    def setConvertedText(self, text=""):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(makeHtmlDiff(self._text, text))
        else:
            self.diff.clear()

    def convertedText(self):
        return self._convertedtext or ""

    def setDocument(self, doc):
        v = documentinfo.info(doc).versionString()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or "UTF-8"
        self.setConvertedText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(_("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        convert_ly = os.path.join(info.bindir(), info.convert_ly)

        # on Windows the convert-ly command is not directly executable, but
        # must be started using the LilyPond-provided Python interpreter
        if os.name == "nt":
            if not os.access(convert_ly, os.R_OK) and not convert_ly.endswith(".py"):
                convert_ly += ".py"
            command = [info.python(), convert_ly]
        else:
            command = [convert_ly]
        command += ["-f", fromVersion, "-t", toVersion, "-"]

        # if the user wants english messages, do it also here
        env = None
        if QSettings().value("lilypond_settings/no_translation", False) in (True, "true"):
            env = dict(os.environ)
            env["LANGUAGE"] = "C"

        with util.busyCursor():
            try:
                proc = subprocess.Popen(
                    command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )
                out, err = proc.communicate(self._text.encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n" "{message}\n").format(convert_ly=convert_ly, message=e)
                )
                return
            self.messages.setPlainText(err.decode("UTF-8"))
            self.setConvertedText(out.decode("UTF-8"))
            if not out or self._convertedtext == self._text:
                self.messages.append("\n" + _("The document has not been changed."))
Beispiel #53
0
class RecordingWidget(QWidget):
    """Widget containing main recording UI for Freeseer"""
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        boldFont = QFont()
        boldFont.setBold(True)

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.standbyIcon = QIcon.fromTheme("system-shutdown")
        recordFallbackIcon = QIcon(":/multimedia/record.png")
        self.recordIcon = QIcon.fromTheme("media-record", recordFallbackIcon)
        stopFallbackIcon = QIcon(":/multimedia/stop.png")
        self.stopIcon = QIcon.fromTheme("media-playback-stop",
                                        stopFallbackIcon)
        self.pauseIcon = QIcon.fromTheme("media-playback-pause")
        self.resumeIcon = QIcon.fromTheme("media-playback-start")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"),
                                     QIcon.Normal, QIcon.Off)

        self.standbyPushButton = QPushButton("Standby")
        self.standbyPushButton.setToolTip("Standby")
        self.standbyPushButton.setMinimumSize(QSize(0, 40))
        self.standbyPushButton.setSizePolicy(QSizePolicy.Minimum,
                                             QSizePolicy.Fixed)
        self.standbyPushButton.setIcon(self.standbyIcon)
        self.standbyPushButton.setCheckable(True)
        self.standbyPushButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyPushButton)

        self.autoRecordPushButton = QPushButton("Auto Record")
        self.autoRecordPushButton.setToolTip("Automated Recording")
        self.autoRecordPushButton.setMinimumSize(QSize(40, 40))
        self.autoRecordPushButton.setMaximumSize(QSize(120, 40))
        self.autoRecordPushButton.setCheckable(True)
        self.autoRecordPushButton.setObjectName("autoRecordButton")
        self.controlRow.addWidget(self.autoRecordPushButton)

        self.recordPushButton = QPushButton("Record")
        self.recordPushButton.setToolTip("Record")
        self.recordPushButton.setMinimumSize(QSize(0, 40))
        self.recordPushButton.setSizePolicy(QSizePolicy.Minimum,
                                            QSizePolicy.Fixed)
        self.recordPushButton.setIcon(self.recordIcon)
        self.recordPushButton.setHidden(True)
        self.recordPushButton.setEnabled(False)
        self.recordPushButton.setCheckable(True)
        self.recordPushButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordPushButton)
        self.connect(self.recordPushButton, SIGNAL("toggled(bool)"),
                     self.setRecordIcon)

        self.pauseToolButton = QToolButton()
        self.pauseToolButton.setText("Pause")
        self.pauseToolButton.setToolTip("Pause")
        self.pauseToolButton.setIcon(self.pauseIcon)
        self.pauseToolButton.setMinimumSize(QSize(40, 40))
        self.pauseToolButton.setSizePolicy(QSizePolicy.Maximum,
                                           QSizePolicy.Fixed)
        self.pauseToolButton.setHidden(True)
        self.pauseToolButton.setEnabled(False)
        self.pauseToolButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseToolButton)
        self.connect(self.pauseToolButton, SIGNAL("toggled(bool)"),
                     self.setPauseIcon)

        playbackIcon = QIcon.fromTheme("video-x-generic")
        self.playPushButton = QPushButton()
        self.playPushButton.setText("Play Video")
        self.playPushButton.setToolTip("Play last recorded Video")
        self.playPushButton.setIcon(playbackIcon)
        self.playPushButton.setMinimumSize(QSize(40, 40))
        self.playPushButton.setMaximumSize(QSize(120, 40))
        self.playPushButton.setHidden(True)
        self.playPushButton.setEnabled(False)
        self.playPushButton.setCheckable(True)
        self.controlRow.addWidget(self.playPushButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum,
                                        QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed,
                                       QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self, state):
        if state:
            self.recordPushButton.setIcon(self.stopIcon)
        else:
            self.recordPushButton.setIcon(self.recordIcon)

    def setPauseIcon(self, state):
        if state:
            self.pauseToolButton.setIcon(self.resumeIcon)
        else:
            self.pauseToolButton.setIcon(self.pauseIcon)
Beispiel #54
0
class SessionEditor(QDialog):
    def __init__(self, parent=None):
        super(SessionEditor, self).__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        grid = QGridLayout()
        layout.addLayout(grid)
        
        self.name = QLineEdit()
        self.nameLabel = l = QLabel()
        l.setBuddy(self.name)
        grid.addWidget(l, 0, 0)
        grid.addWidget(self.name, 0, 1)
        
        self.autosave = QCheckBox()
        grid.addWidget(self.autosave, 1, 1)
        
        self.basedir = widgets.urlrequester.UrlRequester()
        self.basedirLabel = l = QLabel()
        l.setBuddy(self.basedir)
        grid.addWidget(l, 2, 0)
        grid.addWidget(self.basedir, 2, 1)
        
        self.inclPaths = ip = QGroupBox(self, checkable=True, checked=False)
        ipLayout = QVBoxLayout()
        ip.setLayout(ipLayout)
        
        self.replPaths = QCheckBox()
        ipLayout.addWidget(self.replPaths)
        self.replPaths.toggled.connect(self.toggleReplace)
        
        self.include = widgets.listedit.FilePathEdit()
        self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove)
        ipLayout.addWidget(self.include)
        
        grid.addWidget(ip, 3, 1)
        
        self.revt = QPushButton(self)
        self.clear = QPushButton(self)
        self.revt.clicked.connect(self.revertPaths)
        self.clear.clicked.connect(self.clearPaths)
       
        self.include.layout().addWidget(self.revt, 5, 1)
        self.include.layout().addWidget(self.clear, 6, 1)
        
        layout.addWidget(widgets.Separator())
        self.buttons = b = QDialogButtonBox(self)
        layout.addWidget(b)
        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        userguide.addButton(b, "sessions")
        app.translateUI(self)
        
    def translateUI(self):
        self.nameLabel.setText(_("Name:"))
        self.autosave.setText(_("Always save the list of documents in this session"))
        self.basedirLabel.setText(_("Base directory:"))
        self.inclPaths.setTitle(_("Use session specific include path"))
        self.replPaths.setText(_("Replace global path"))
        self.replPaths.setToolTip(_("When checked, paths in LilyPond preferences are not included."))
        self.revt.setText(_("Copy global path"))
        self.revt.setToolTip(_("Add and edit the path from LilyPond preferences."))
        self.clear.setText(_("Clear"))
        self.clear.setToolTip(_("Remove all paths."))
    
    def load(self, name):
        settings = sessions.sessionGroup(name)
        self.autosave.setChecked(settings.value("autosave", True, bool))
        self.basedir.setPath(settings.value("basedir", "", type("")))
        try:
            paths = settings.value("include-path", [], type(""))
        except TypeError:
            paths = []
        self.include.setValue(paths)
        self.inclPaths.setChecked(settings.value("set-paths", False, bool))
        self.replPaths.setChecked(settings.value("repl-paths", False, bool))
        if not self.replPaths.isChecked():
            self.addDisabledGenPaths()
            self.revt.setEnabled(False)
        # more settings here
        
    def fetchGenPaths(self):
        """Fetch paths from general preferences."""
        s = QSettings()
        s.beginGroup("lilypond_settings")
        try:
            return s.value("include_path", [], type(""))
        except TypeError:
            return []
            
    def addDisabledGenPaths(self):
        """Add global paths, but set as disabled."""
        genPaths = self.fetchGenPaths()
        for p in genPaths:
            i = QListWidgetItem(p, self.include.listBox)
            i.setFlags(Qt.NoItemFlags)
            
    def toggleReplace(self):
        """Called when user changes setting for replace of global paths."""
        if self.replPaths.isChecked():
            items = self.include.items()
            for i in items:
                if not (i.flags() & Qt.ItemIsEnabled): #is not enabled
                  self.include.listBox.takeItem(self.include.listBox.row(i))
            self.revt.setEnabled(True)
        else:
            self.addDisabledGenPaths()
            self.revt.setEnabled(False)
            
    def revertPaths(self):
        """Add global paths (for edit)."""
        genPaths = self.fetchGenPaths()
        for p in genPaths:
            i = QListWidgetItem(p, self.include.listBox)
        
    def clearPaths(self):
        """Remove all active paths."""
        items = self.include.items()
        for i in items:
            if i.flags() & Qt.ItemIsEnabled:
              self.include.listBox.takeItem(self.include.listBox.row(i))
        
    def save(self, name):
        settings = sessions.sessionGroup(name)
        settings.setValue("autosave", self.autosave.isChecked())
        settings.setValue("basedir", self.basedir.path())
        settings.setValue("set-paths", self.inclPaths.isChecked())
        settings.setValue("repl-paths", self.replPaths.isChecked())
        path = [i.text() for i in self.include.items() if i.flags() & Qt.ItemIsEnabled]
        settings.setValue("include-path", path)
        # more settings here
        
    def defaults(self):
        self.autosave.setChecked(True)
        self.basedir.setPath('')
        self.inclPaths.setChecked(False)
        self.replPaths.setChecked(False)
        self.addDisabledGenPaths()
        self.revt.setEnabled(False)
        # more defaults here
        
    def edit(self, name=None):
        self._originalName = name
        if name:
            caption = _("Edit session: {name}").format(name=name)
            self.name.setText(name)
            self.load(name)
        else:
            caption = _("Edit new session")
            self.name.clear()
            self.name.setFocus()
            self.defaults()
        self.setWindowTitle(app.caption(caption))
        if self.exec_():
            # name changed?
            name = self.name.text()
            if self._originalName and name != self._originalName:
                sessions.renameSession(self._originalName, name)
            self.save(name)
            return name

    def done(self, result):
        if not result or self.validate():
            super(SessionEditor, self).done(result)
        
    def validate(self):
        """Checks if the input is acceptable.
        
        If this method returns True, the dialog is accepted when OK is clicked.
        Otherwise a messagebox could be displayed, and the dialog will remain
        visible.
        """
        name = self.name.text().strip()
        self.name.setText(name)
        if not name:
            self.name.setFocus()
            QMessageBox.warning(self, app.caption(_("Warning")),
                _("Please enter a session name."))
            if self._originalName:
                self.name.setText(self._originalName)
            return False
        
        elif name == '-':
            self.name.setFocus()
            QMessageBox.warning(self, app.caption(_("Warning")),
                _("Please do not use the name '{name}'.".format(name="-")))
            return False
        
        elif self._originalName != name and name in sessions.sessionNames():
            self.name.setFocus()
            box = QMessageBox(QMessageBox.Warning, app.caption(_("Warning")),
                _("Another session with the name {name} already exists.\n\n"
                  "Do you want to overwrite it?").format(name=name),
                QMessageBox.Discard | QMessageBox.Cancel, self)
            box.button(QMessageBox.Discard).setText(_("Overwrite"))
            result = box.exec_()
            if result != QMessageBox.Discard:
                return False
            
        return True
Beispiel #55
0
class TidySettingsDialog(QDialog):
    " PythonTidy.py script settings dialog "

    def __init__(self, settings, path, parent=None):
        QDialog.__init__(self, parent)

        self.__settings = settings
        self.__path = path

        self.__createLayout()
        self.setWindowTitle("PythonTidy settings")
        return

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

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

        layout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Columns
        colsLabel = QLabel("Columns")
        self.__colsEdit = QLineEdit()
        self.__colsEdit.setText(str(self.__settings.settings["COL_LIMIT"]))
        self.__colsEdit.setToolTip(self.__settings.getDescription("COL_LIMIT"))
        self.__colsEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(colsLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.__colsEdit, 0, 1, 1, 1)
        font = self.__colsEdit.font()
        font.setFamily(GlobalData().skin.baseMonoFontFace)
        self.__colsEdit.setFont(font)

        # Assignment
        assignmentLabel = QLabel("Assignment")
        self.__assignmentEdit = QLineEdit()
        self.__assignmentEdit.setText(self.__settings.settings["ASSIGNMENT"])
        self.__assignmentEdit.setToolTip(
            self.__settings.getDescription("ASSIGNMENT"))
        self.__assignmentEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(assignmentLabel, 0, 3, 1, 1)
        gridLayout.addWidget(self.__assignmentEdit, 0, 4, 1, 1)
        self.__assignmentEdit.setFont(font)

        # Function parameters assignment
        funcAssignLabel = QLabel("Function params\nassignment")
        self.__funcAssignEdit = QLineEdit()
        self.__funcAssignEdit.setText(
            self.__settings.settings["FUNCTION_PARAM_ASSIGNMENT"])
        self.__funcAssignEdit.setToolTip(
            self.__settings.getDescription("FUNCTION_PARAM_ASSIGNMENT"))
        self.__funcAssignEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(funcAssignLabel, 1, 0, 1, 1)
        gridLayout.addWidget(self.__funcAssignEdit, 1, 1, 1, 1)
        self.__funcAssignEdit.setFont(font)

        # Dictionary separator
        dictSepLabel = QLabel("Dictionary separator")
        self.__dictSepEdit = QLineEdit()
        self.__dictSepEdit.setText(self.__settings.settings["DICT_COLON"])
        self.__dictSepEdit.setToolTip(
            self.__settings.getDescription("DICT_COLON"))
        self.__dictSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(dictSepLabel, 1, 3, 1, 1)
        gridLayout.addWidget(self.__dictSepEdit, 1, 4, 1, 1)
        self.__dictSepEdit.setFont(font)

        # Slice separator
        sliceSepLabel = QLabel("Slice separator")
        self.__sliceSepEdit = QLineEdit()
        self.__sliceSepEdit.setText(self.__settings.settings["SLICE_COLON"])
        self.__sliceSepEdit.setToolTip(
            self.__settings.getDescription("SLICE_COLON"))
        self.__sliceSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(sliceSepLabel, 2, 0, 1, 1)
        gridLayout.addWidget(self.__sliceSepEdit, 2, 1, 1, 1)
        self.__sliceSepEdit.setFont(font)

        # Interpreter
        inLabel = QLabel("Interpreter")
        self.__inEdit = QLineEdit()
        self.__inEdit.setText(self.__settings.settings["SHEBANG"])
        self.__inEdit.setToolTip(self.__settings.getDescription("SHEBANG"))
        self.__inEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(inLabel, 2, 3, 1, 1)
        gridLayout.addWidget(self.__inEdit, 2, 4, 1, 1)
        self.__inEdit.setFont(font)

        # Coding spec
        codingLabel = QLabel("Output encoding")
        self.__outCodingEdit = QLineEdit()
        self.__outCodingEdit.setText(self.__settings.settings["CODING"])
        self.__outCodingEdit.setToolTip(
            self.__settings.getDescription("CODING"))
        self.__outCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(codingLabel, 3, 0, 1, 1)
        gridLayout.addWidget(self.__outCodingEdit, 3, 1, 1, 1)
        self.__outCodingEdit.setFont(font)

        # Src coding comment
        srcCodingLabel = QLabel("File encoding\ncomment")
        self.__srcCodingEdit = QLineEdit()
        self.__srcCodingEdit.setText(self.__settings.settings["CODING_SPEC"])
        self.__srcCodingEdit.setToolTip(
            self.__settings.getDescription("CODING_SPEC"))
        self.__srcCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(srcCodingLabel, 3, 3, 1, 1)
        gridLayout.addWidget(self.__srcCodingEdit, 3, 4, 1, 1)
        self.__srcCodingEdit.setFont(font)

        layout.addLayout(gridLayout)

        # Boilerplate
        boilLabel = QLabel("Boilerplate  ")
        boilLabel.setAlignment(Qt.AlignTop)
        self.__boilEdit = QTextEdit()
        self.__boilEdit.setPlainText(self.__settings.settings["BOILERPLATE"])
        self.__boilEdit.setToolTip(
            self.__settings.getDescription("BOILERPLATE"))
        self.__boilEdit.setTabChangesFocus(True)
        self.__boilEdit.setAcceptRichText(False)
        self.__boilEdit.setFont(font)
        self.__boilEdit.textChanged.connect(self.__validate)
        boilLayout = QHBoxLayout()
        boilLayout.addWidget(boilLabel)
        boilLayout.addWidget(self.__boilEdit)
        layout.addLayout(boilLayout)

        # Now check boxes and radio buttons
        cbGridLayout = QGridLayout()
        self.__keepBlanks = QCheckBox("Keep blank lines")
        self.__keepBlanks.setChecked(
            self.__settings.settings["KEEP_BLANK_LINES"])
        self.__keepBlanks.setToolTip(
            self.__settings.getDescription("KEEP_BLANK_LINES"))
        cbGridLayout.addWidget(self.__keepBlanks, 0, 0, 1, 1)

        self.__addBlanks = QCheckBox("Add blank lines around comments")
        self.__addBlanks.setChecked(
            self.__settings.settings["ADD_BLANK_LINES_AROUND_COMMENTS"])
        self.__addBlanks.setToolTip(
            self.__settings.getDescription("ADD_BLANK_LINES_AROUND_COMMENTS"))
        cbGridLayout.addWidget(self.__addBlanks, 0, 2, 1, 1)

        self.__justifyDoc = QCheckBox("Left justify doc strings")
        self.__justifyDoc.setChecked(
            self.__settings.settings["LEFTJUST_DOC_STRINGS"])
        self.__justifyDoc.setToolTip(
            self.__settings.getDescription("LEFTJUST_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__justifyDoc, 1, 0, 1, 1)

        self.__wrapDoc = QCheckBox("Wrap long doc strings")
        self.__wrapDoc.setChecked(self.__settings.settings["WRAP_DOC_STRINGS"])
        self.__wrapDoc.setToolTip(
            self.__settings.getDescription("WRAP_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__wrapDoc, 1, 2, 1, 1)

        self.__recodeStrings = QCheckBox("Try to decode strings")
        self.__recodeStrings.setChecked(
            self.__settings.settings["RECODE_STRINGS"])
        self.__recodeStrings.setToolTip(
            self.__settings.getDescription("RECODE_STRINGS"))
        cbGridLayout.addWidget(self.__recodeStrings, 2, 0, 1, 1)

        self.__splitStrings = QCheckBox("Split long strings")
        self.__splitStrings.setChecked(
            self.__settings.settings["CAN_SPLIT_STRINGS"])
        self.__splitStrings.setToolTip(
            self.__settings.getDescription("CAN_SPLIT_STRINGS"))
        cbGridLayout.addWidget(self.__splitStrings, 2, 2, 1, 1)

        self.__keepUnassignedConst = QCheckBox("Keep unassigned constants")
        self.__keepUnassignedConst.setChecked(
            self.__settings.settings["KEEP_UNASSIGNED_CONSTANTS"])
        self.__keepUnassignedConst.setToolTip(
            self.__settings.getDescription("KEEP_UNASSIGNED_CONSTANTS"))
        cbGridLayout.addWidget(self.__keepUnassignedConst, 3, 0, 1, 1)

        self.__parenTuple = QCheckBox("Parenthesize tuple display")
        self.__parenTuple.setChecked(
            self.__settings.settings["PARENTHESIZE_TUPLE_DISPLAY"])
        self.__parenTuple.setToolTip(
            self.__settings.getDescription("PARENTHESIZE_TUPLE_DISPLAY"))
        cbGridLayout.addWidget(self.__parenTuple, 3, 2, 1, 1)

        self.__javaListDedent = QCheckBox("Java style list dedent")
        self.__javaListDedent.setChecked(
            self.__settings.settings["JAVA_STYLE_LIST_DEDENT"])
        self.__javaListDedent.setToolTip(
            self.__settings.getDescription("JAVA_STYLE_LIST_DEDENT"))
        cbGridLayout.addWidget(self.__javaListDedent, 4, 0, 1, 1)

        layout.addLayout(cbGridLayout)

        # Quotes radio buttons
        quotesGroupbox = QGroupBox("Quotes")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        quotesGroupbox.sizePolicy().hasHeightForWidth() )
        quotesGroupbox.setSizePolicy(sizePolicy)

        layoutQG = QVBoxLayout(quotesGroupbox)
        self.__use1RButton = QRadioButton(
            "Use apostrophes instead of quotes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use1RButton)
        self.__use2RButton = QRadioButton(
            "Use quotes instead of apostrophes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use2RButton)
        self.__useAsIsRButton = QRadioButton("Do not make changes",
                                             quotesGroupbox)
        layoutQG.addWidget(self.__useAsIsRButton)
        use1 = self.__settings.settings["SINGLE_QUOTED_STRINGS"]
        use2 = self.__settings.settings["DOUBLE_QUOTED_STRINGS"]
        if use1:
            self.__use1RButton.setChecked(True)
        elif use2:
            self.__use2RButton.setChecked(True)
        else:
            self.__useAsIsRButton.setChecked(True)
        layout.addWidget(quotesGroupbox)

        fontMetrics = QFontMetrics(font)
        editWidth = fontMetrics.width("iso8859-10  ") + 20
        self.__colsEdit.setFixedWidth(editWidth)
        self.__funcAssignEdit.setFixedWidth(editWidth)
        self.__sliceSepEdit.setFixedWidth(editWidth)
        self.__outCodingEdit.setFixedWidth(editWidth)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__resetButton = buttonBox.addButton("Reset to Default",
                                                 QDialogButtonBox.ActionRole)
        self.__resetButton.setToolTip(
            "Mostly as recommended by PEP 8 / PEP 308")
        self.__resetButton.clicked.connect(self.__reset)
        self.__tidyButton = buttonBox.addButton("Tidy",
                                                QDialogButtonBox.ActionRole)
        self.__tidyButton.setToolTip("Save settings and run PythonTidy")
        self.__tidyButton.setDefault(True)
        self.__tidyButton.clicked.connect(self.__saveAndAccept)
        layout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return

    def __reset(self):
        " Resets the values to default "

        self.__colsEdit.setText(
            str(self.__settings.getDefaultValue("COL_LIMIT")))
        self.__assignmentEdit.setText(
            self.__settings.getDefaultValue("ASSIGNMENT"))
        self.__funcAssignEdit.setText(
            self.__settings.getDefaultValue("FUNCTION_PARAM_ASSIGNMENT"))
        self.__dictSepEdit.setText(
            self.__settings.getDefaultValue("DICT_COLON"))
        self.__sliceSepEdit.setText(
            self.__settings.getDefaultValue("SLICE_COLON"))
        self.__inEdit.setText(self.__settings.getDefaultValue("SHEBANG"))
        self.__outCodingEdit.setText(self.__settings.getDefaultValue("CODING"))
        self.__srcCodingEdit.setText(
            self.__settings.getDefaultValue("CODING_SPEC"))
        self.__boilEdit.setPlainText(
            self.__settings.getDefaultValue("BOILERPLATE"))
        self.__keepBlanks.setChecked(
            self.__settings.getDefaultValue("KEEP_BLANK_LINES"))
        self.__addBlanks.setChecked(
            self.__settings.getDefaultValue("ADD_BLANK_LINES_AROUND_COMMENTS"))
        self.__justifyDoc.setChecked(
            self.__settings.getDefaultValue("LEFTJUST_DOC_STRINGS"))
        self.__wrapDoc.setChecked(
            self.__settings.getDefaultValue("WRAP_DOC_STRINGS"))
        self.__recodeStrings.setChecked(
            self.__settings.getDefaultValue("RECODE_STRINGS"))
        self.__splitStrings.setChecked(
            self.__settings.getDefaultValue("CAN_SPLIT_STRINGS"))
        self.__keepUnassignedConst.setChecked(
            self.__settings.getDefaultValue("KEEP_UNASSIGNED_CONSTANTS"))
        self.__parenTuple.setChecked(
            self.__settings.getDefaultValue("PARENTHESIZE_TUPLE_DISPLAY"))
        self.__javaListDedent.setChecked(
            self.__settings.getDefaultValue("JAVA_STYLE_LIST_DEDENT"))

        use1 = self.__settings.getDefaultValue("SINGLE_QUOTED_STRINGS")
        use2 = self.__settings.getDefaultValue("DOUBLE_QUOTED_STRINGS")
        if use1:
            self.__use1RButton.setChecked(True)
            self.__use2RButton.setChecked(False)
            self.__useAsIsRButton.setChecked(False)
        elif use2:
            self.__use1RButton.setChecked(False)
            self.__use2RButton.setChecked(True)
            self.__useAsIsRButton.setChecked(False)
        else:
            self.__use1RButton.setChecked(False)
            self.__use2RButton.setChecked(False)
            self.__useAsIsRButton.setChecked(True)

        self.__validate()
        return

    @staticmethod
    def __setValid(field, value):
        " Changes the field background depending on the validity "
        if value:
            field.setStyleSheet("")
        else:
            if isinstance(field, QLineEdit):
                typeName = "QLineEdit"
            else:
                typeName = "QTextEdit"
            field.setStyleSheet(typeName + "{ background: #ffa07a; }")
        return

    def __saveAndAccept(self):
        " Saves the changes and accepts the values "
        self.__validate()
        if self.__tidyButton.isEnabled() == False:
            return

        self.__settings.settings["COL_LIMIT"] = int(self.__colsEdit.text())
        self.__settings.settings["ASSIGNMENT"] = self.__assignmentEdit.text()
        self.__settings.settings[
            "FUNCTION_PARAM_ASSIGNMENT"] = self.__funcAssignEdit.text()
        self.__settings.settings["DICT_COLON"] = self.__dictSepEdit.text()
        self.__settings.settings["SLICE_COLON"] = self.__sliceSepEdit.text()
        self.__settings.settings["SHEBANG"] = self.__inEdit.text()
        self.__settings.settings["CODING"] = self.__outCodingEdit.text()
        self.__settings.settings["CODING_SPEC"] = self.__srcCodingEdit.text()
        self.__settings.settings["BOILERPLATE"] = self.__boilEdit.toPlainText()
        self.__settings.settings["KEEP_BLANK_LINES"] = bool(
            self.__keepBlanks.isChecked())
        self.__settings.settings["ADD_BLANK_LINES_AROUND_COMMENTS"] = bool(
            self.__addBlanks.isChecked())
        self.__settings.settings["LEFTJUST_DOC_STRINGS"] = bool(
            self.__justifyDoc.isChecked())
        self.__settings.settings["WRAP_DOC_STRINGS"] = bool(
            self.__wrapDoc.isChecked())
        self.__settings.settings["RECODE_STRINGS"] = bool(
            self.__recodeStrings.isChecked())
        self.__settings.settings["CAN_SPLIT_STRINGS"] = bool(
            self.__splitStrings.isChecked())
        self.__settings.settings["KEEP_UNASSIGNED_CONSTANTS"] = bool(
            self.__keepUnassignedConst.isChecked())
        self.__settings.settings["PARENTHESIZE_TUPLE_DISPLAY"] = bool(
            self.__parenTuple.isChecked())
        self.__settings.settings["JAVA_STYLE_LIST_DEDENT"] = bool(
            self.__javaListDedent.isChecked())

        if self.__use1RButton.isChecked():
            self.__settings.settings["SINGLE_QUOTED_STRINGS"] = True
            self.__settings.settings["DOUBLE_QUOTED_STRINGS"] = False
        elif self.__use2RButton.isChecked():
            self.__settings.settings["SINGLE_QUOTED_STRINGS"] = False
            self.__settings.settings["DOUBLE_QUOTED_STRINGS"] = True
        else:
            self.__settings.settings["SINGLE_QUOTED_STRINGS"] = False
            self.__settings.settings["DOUBLE_QUOTED_STRINGS"] = False

        try:
            self.__settings.saveToFile(self.__path)
        except:
            logging.error( "Error saving PythonTidy settings into " + \
                           self.__path + ". Ignor and continue." )
        self.accept()
        return

    def __validate(self, text=None):
        " Validates input "
        allValid = True
        val = self.__colsEdit.text()
        try:
            intVal = int(val)
            if intVal <= 0:
                allValid = False
                self.__setValid(self.__colsEdit, False)
            else:
                self.__setValid(self.__colsEdit, True)
        except:
            allValid = False
            self.__setValid(self.__colsEdit, False)

        if '=' not in self.__assignmentEdit.text():
            allValid = False
            self.__setValid(self.__assignmentEdit, False)
        else:
            self.__setValid(self.__assignmentEdit, True)

        if '=' not in self.__funcAssignEdit.text():
            allValid = False
            self.__setValid(self.__funcAssignEdit, False)
        else:
            self.__setValid(self.__funcAssignEdit, True)

        if ':' not in self.__dictSepEdit.text():
            allValid = False
            self.__setValid(self.__dictSepEdit, False)
        else:
            self.__setValid(self.__dictSepEdit, True)

        if ':' not in self.__sliceSepEdit.text():
            allValid = False
            self.__setValid(self.__sliceSepEdit, False)
        else:
            self.__setValid(self.__sliceSepEdit, True)

        val = self.__inEdit.text()
        if val.strip() != "" and not val.strip().startswith('#!'):
            allValid = False
            self.__setValid(self.__inEdit, False)
        else:
            self.__setValid(self.__inEdit, True)

        val = self.__srcCodingEdit.text()
        if val.strip() != "" and not val.strip().startswith('#'):
            allValid = False
            self.__setValid(self.__srcCodingEdit, False)
        else:
            self.__setValid(self.__srcCodingEdit, True)

        self.__tidyButton.setEnabled(allValid)
        return
Beispiel #56
0
class Window(QWidget):
    '''
    This is the GUI object.  Any gui-related operations happen here
    '''
    def __init__(self):

        self.internal_net = ''
        self.external_net = ''
        self.unconfigured = True

        self.searchfound = False
        self.foundunenc = False
        self.foundunprot = False
        self.foundprot = False

        if os.path.exists('tapioca.cfg'):
            with open('tapioca.cfg') as f:
                configlines = f.readlines()
            for line in configlines:
                if line.startswith('external_net'):
                    line = line.rstrip()
                    self.external_net = line.split('=')[1]
                if line.startswith('internal_net'):
                    line = line.rstrip()
                    self.internal_net = line.split('=')[1]

        if self.external_net != 'WAN_DEVICE' and self.internal_net != 'LAN_DEVICE':
            self.unconfigured = False

        QWidget.__init__(self)

        self.setWindowTitle('Tapioca')
        app_icon = QIcon()
        app_icon.addFile('cert.ico', QtCore.QSize(32, 32))
        self.setWindowIcon(app_icon)

        self.lblupstream = QLabel('<b>Upstream-network device:</b>')
        self.lblupstreamval = QLabel(self.external_net)
        self.lblupstreamval.setToolTip(
            'Ethernet device used for internet connectivity')
        self.lbllocal = QLabel('<b>Locally-provided-network device:</b>')
        self.lbllocalval = QLabel(self.internal_net)
        self.lbllocalval.setToolTip(
            'Ethernet device used for connectivity to device under test')
        self.spacer = QLabel()
        self.net_status = QLabel()
        self.appname = ''
        self.lblapp = QLabel('<b>Capture session:</b>')
        self.cboapp = QComboBox()
        self.cboapp.setEditable(True)
        self.cboapp.setToolTip(
            'Select an existing session from the dropdown or type a new one')
        #self.leapp = QLineEdit()
        self.btntcpdump = QPushButton('Capture - All traffic with tcpdump')
        self.btntcpdump.setToolTip(
            'Launch tcpdump to capture all traffic without interception')
        self.lbltcpdump = QLabel()
        self.chkrewrite = QCheckBox('Modify mitmproxy traffic')
        self.chkrewrite.setToolTip(
            'Edit mitmproxy rules for traffic modification.\nOnly affects "Verify SSL Validation" and "Full HTTPS inspection" tests'
        )
        self.btnrewrite = QPushButton('Edit modification rules')
        self.btnrewrite.setToolTip('Modify mitmproxy traffic rewriting rules')
        self.btnrewrite.setEnabled(False)
        self.btnssl = QPushButton('Capture - Verify SSL validation')
        self.btnssl.setToolTip(
            'Launch mitmproxy to capture HTTP(S) traffic with an invalid certificate'
        )
        self.lblssltest = QLabel()
        self.btnfull = QPushButton('Capture - Full HTTPS inspection')
        self.btnfull.setToolTip(
            'Launch mitmproxy to capture HTTP(S) traffic with an installed certificate'
        )
        self.lblfull = QLabel()
        self.btnstop = QPushButton('Stop current capture')
        self.allreports = QPushButton('Generate reports')
        self.allreports.setToolTip(
            'Generate reports for all tests performed for this capture')
        self.lblsslresults = QLabel('<b>SSL test results:</b>')
        self.lblsslresultsval = QLabel()
        self.lblcryptoresults = QLabel('<b>Crypto test results:</b>')
        self.lblcryptoresultsval = QLabel()
        self.lblnetresults = QLabel(
            '<b>Network connectivity test results:</b>')
        self.lblnetresultsval = QLabel()

        self.lblsearch = QLabel('<b>Search term:</b>')
        self.searchbox = QLineEdit()
        self.searchbox.setToolTip(
            'Case-insensitive perl-compatible regex pattern')
        self.chksearch = QCheckBox('Search multiple encodings')
        self.chksearch.setToolTip(
            'Search for base64, md5, and sha1 encodings as well - INCOMPATIBLE with Regex'
        )
        self.btnsearch = QPushButton('Search')
        self.btnsearch.setToolTip(
            'Search for term (perl-compatible regex) in all captures')
        self.lblsearchresults = QLabel()
        self.lblsearchfound = QLabel()
        self.lblsearchunprotfound = QLabel()
        self.lblsearchprotfound = QLabel()

        #layout = QVBoxLayout(self)
        layout = QFormLayout(self)
        layout.addRow(self.lblupstream, self.lblupstreamval)
        layout.addRow(self.lbllocal, self.lbllocalval)
        layout.addRow(self.net_status)
        #layout.addRow(self.lblapp, self.leapp)
        layout.addRow(self.lblapp, self.cboapp)
        layout.addRow(self.btntcpdump, self.lbltcpdump)
        layout.addRow(self.btnssl, self.lblssltest)
        layout.addRow(self.btnfull, self.lblfull)
        layout.addRow(self.chkrewrite, self.btnrewrite)
        layout.addRow(self.btnstop)
        layout.addRow(self.spacer)
        layout.addRow(self.spacer)
        layout.addRow(self.lblsearch, self.searchbox)
        layout.addRow(self.chksearch, self.btnsearch)
        layout.addRow(self.lblsearchresults, self.lblsearchfound)
        layout.addRow(self.spacer, self.lblsearchunprotfound)
        layout.addRow(self.spacer, self.lblsearchprotfound)
        layout.addRow(self.allreports)
        layout.addRow(self.lblsslresults, self.lblsslresultsval)
        layout.addRow(self.lblcryptoresults, self.lblcryptoresultsval)
        layout.addRow(self.lblnetresults, self.lblnetresultsval)

        self.setFixedSize(480, 420)
        self.center()

        if self.unconfigured:
            self.net_status.setText(
                '<font color="red"><b>Please enable soft AP or configure networks</b></font>'
            )
            self.disabletests()
            self.disablestop()

        if not self.checklan():
            self.net_status.setText(
                '<font color="red"><b>LAN device %s not found</b></font>' %
                self.internal_net)
            self.disabletests()
            self.disablestop()

    def checklan(self):
        landevice = subprocess.check_output([
            "nmcli device status | grep %s | awk '{print $1}'" %
            self.internal_net
        ],
                                            shell=True)
        if not landevice:
            return False
        else:
            return True

    @QtCore.pyqtSlot()
    def clearsearchresults(self):
        #print('Clearing search results...')
        self.lblsearchresults.setText('')
        self.lblsearchfound.setText('')
        self.lblsearchfound.setCursor(QCursor())
        self.lblsearchfound.setToolTip('')
        self.lblsearchunprotfound.setText('')
        self.lblsearchunprotfound.setCursor(QCursor())
        self.lblsearchunprotfound.setToolTip('')
        self.lblsearchprotfound.setText('')
        self.lblsearchprotfound.setCursor(QCursor())
        self.lblsearchprotfound.setToolTip('')

    @QtCore.pyqtSlot()
    def updatesearchresults(self):
        #print('Updating GUI search results...')
        #print('searchfound: %s' % self.searchfound)
        searchresults = ''
        if self.searchfound:
            self.lblsearchresults.setText('<b>Matches:</b>')
            if self.foundunenc:
                searchresults = 'Unencrypted traffic'
                self.lblsearchfound.setText(searchresults)
                self.lblsearchfound.setCursor(
                    QCursor(QtCore.Qt.PointingHandCursor))
                self.lblsearchfound.setToolTip('Open raw tcpdump capture')
            else:
                self.lblsearchfound.setText('')
                self.lblsearchfound.setCursor(QCursor())
                self.lblsearchfound.setToolTip('')

            if self.foundunprot:
                if searchresults != '':
                    searchresults = searchresults + ', '
                searchresults = 'Unprotected HTTPS traffic'
                self.lblsearchunprotfound.setText(searchresults)
                self.lblsearchunprotfound.setCursor(
                    QCursor(QtCore.Qt.PointingHandCursor))
                self.lblsearchunprotfound.setToolTip(
                    'Open SSL test mitmproxy capture')
            else:
                self.lblsearchunprotfound.setText('')
                self.lblsearchunprotfound.setCursor(QCursor())
                self.lblsearchunprotfound.setToolTip('')

            if self.foundprot:
                if searchresults != '':
                    searchresults = searchresults + ', '
                searchresults = 'Protected HTTPS traffic'
                self.lblsearchprotfound.setText(searchresults)
                self.lblsearchprotfound.setCursor(
                    QCursor(QtCore.Qt.PointingHandCursor))
                self.lblsearchprotfound.setToolTip(
                    'Open full HTTPS inspection mitmproxy capture')
            else:
                self.lblsearchprotfound.setText('')
                self.lblsearchprotfound.setCursor(QCursor())
                self.lblsearchprotfound.setToolTip('')

        else:
            self.lblsearchresults.setText('<b>No match</b>')
            self._clearsearchresult()

        # self.lblsearchfound.setText(searchresults)

    def _clearsearchresult(self):
        self.lblsearchprotfound.setText('')
        self.lblsearchprotfound.setCursor(QCursor())
        self.lblsearchprotfound.setToolTip('')
        self.lblsearchunprotfound.setText('')
        self.lblsearchunprotfound.setCursor(QCursor())
        self.lblsearchunprotfound.setToolTip('')
        self.lblsearchfound.setText('')
        self.lblsearchfound.setCursor(QCursor())
        self.lblsearchfound.setToolTip('')

    @QtCore.pyqtSlot(str)
    def check_addapp(self, appname):
        #print('Checking if %s is already there...') % appname
        appindex = self.cboapp.findText(appname)
        if appindex == -1:
            # Current app hasn't been added to combobox
            #print('Adding app %s' % appname)
            self.cboapp.addItem(appname)

    @QtCore.pyqtSlot()
    def disabletests(self):
        #print('Disabling test buttons')
        self.btntcpdump.setEnabled(False)
        self.btnssl.setEnabled(False)
        self.btnfull.setEnabled(False)

    @QtCore.pyqtSlot()
    def disablestop(self):
        #print('Disabling test buttons')
        self.btnstop.setEnabled(False)

    @QtCore.pyqtSlot()
    def enabletests(self):
        #print('Enabling test buttons again!')
        self.btntcpdump.setEnabled(True)
        self.btnssl.setEnabled(True)
        self.btnfull.setEnabled(True)

    @QtCore.pyqtSlot()
    def center(self):
        frameGm = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

    @QtCore.pyqtSlot(str)
    def getapp(self, appname):
        text, ok = QInputDialog.getText(self, 'Tapioca',
                                        'Enter capture session name:',
                                        QLineEdit.Normal, appname)
        appname = re.sub(r'\W+', '', str(text)).lower()

        if ok:
            appindex = self.cboapp.findText(appname)
            if appindex == -1:
                # New app
                # Create and select item in combobox
                self.cboapp.addItem(appname)
                self.cboapp.setCurrentIndex(self.cboapp.findText(appname))
            else:
                # existing app
                # Just select item in combobox
                self.cboapp.setCurrentIndex(self.cboapp.findText(appname))

        return appname

    def _reset_resultslinks(self):
        self.lblsslresultsval.setText('')
        self.lblsslresultsval.setToolTip('')
        self.lblsslresultsval.setCursor(QCursor())
        self.lblcryptoresultsval.setText('')
        self.lblcryptoresultsval.setToolTip('')
        self.lblcryptoresultsval.setCursor(QCursor())
        self.lblnetresultsval.setText('')
        self.lblnetresultsval.setToolTip('')
        self.lblnetresultsval.setCursor(QCursor())

    @QtCore.pyqtSlot(str)
    def updateStatus(self, test):
        '''
        GUI module updateStatus
        '''
        failures = {}
        #print('--- gui object updateStatus. test: %s' % test)
        test = str(test)
        if test.endswith('COMPLETE') or test.endswith('ERROR'):
            testname, status = str(test).split()
            #print('testname: %s' % testname)
            if testname == 'report':
                #print('*** %s Report done ***' % self.appname)
                failures = allreports.getfailures(self.appname)
                self._reset_resultslinks()
                #print('=== failures: %s ===' % failures)
                for test in failures:
                    #print('- Checking %s' % test)
                    if test == 'ssltest':
                        self.lblsslresultsval.setToolTip(
                            'Open SSL test report')
                        self.lblsslresultsval.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                        if failures[test] is True:
                            #print('failed ssl!')
                            self.lblsslresultsval.setText(
                                '<font color="red">FAILED</font>')
                        elif failures[test] is False:
                            #print('passed ssl')
                            self.lblsslresultsval.setText(
                                '<font color="green">PASSED</font>')
                    elif test == 'crypto':
                        self.lblcryptoresultsval.setToolTip(
                            'Open SSL test report')
                        self.lblcryptoresultsval.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                        if failures[test] is True:
                            self.lblcryptoresultsval.setText(
                                '<font color="red">FAILED</font>')
                        elif failures[test] is False:
                            self.lblcryptoresultsval.setText(
                                '<font color="green">PASSED</font>')
                    elif test == 'net':
                        self.lblnetresultsval.setToolTip(
                            'Open SSL test report')
                        self.lblnetresultsval.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                        if test in failures:
                            self.lblnetresultsval.setText('VIEW')
                        else:
                            self.lblnetresultsval.setText('')

            elif testname == 'search':
                # Let main app object handle this to allow for value passing
                pass
                # self.lblsearchfound.setText(status)
                #print('*** Search complete! ***')
            elif testname == 'openssltest' or testname == 'openfulltest' \
                    or testname == 'opentcpdump' or testname == 'opensslreport' \
                    or testname == 'opencryptoreport' or testname == \
                    'opennetreport':
                # NO need to enable test buttons or so anything else
                pass
            else:
                # Test capture complete
                # Updating individual test status
                #print('gui.updatestatus() re-enabling test buttons')
                self.enabletests()
                #print('*** GUI updateStatus : %s' % test)

                if status == 'COMPLETE':
                    # A test has completed.  Add appname to combobox
                    #print('Finished a test... adding to combobox')
                    self.check_addapp(self.appname)

                if testname == 'tcpdump':
                    self.lbltcpdump.setText(status)
                    if status == 'COMPLETE':
                        self.lbltcpdump.setToolTip(
                            'Open tcpdump capture for %s' % self.appname)
                        self.lbltcpdump.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                    else:
                        self.lbltcpdump.setToolTip('')
                        self.lbltcpdump.setCursor(QCursor())
                elif testname == 'ssltest':
                    self.lblssltest.setText(status)
                    if status == 'COMPLETE':
                        self.lblssltest.setToolTip(
                            'Open mitmproxy SSL test capture for %s' %
                            self.appname)
                        self.lblssltest.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                    else:
                        self.lblssltest.setToolTip('')
                        self.lblssltest.setCursor(QCursor())
                elif testname == 'full':
                    self.lblfull.setText(status)
                    if status == 'COMPLETE':
                        self.lblfull.setToolTip(
                            'Open mitmproxy full inspection capture for %s' %
                            self.appname)
                        self.lblfull.setCursor(
                            QCursor(QtCore.Qt.PointingHandCursor))
                    else:
                        self.lblfull.setToolTip('')
                        self.lblfull.setCursor(QCursor())