Beispiel #1
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 #2
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 #3
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 #4
0
class Login(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self)
        self.parent = parent
        self.resize(270, 160)
        self.verticalLayout = QVBoxLayout(self)
        self.label_username = QLabel(self)
        self.verticalLayout.addWidget(self.label_username)
        self.username = QLineEdit(self)
        self.verticalLayout.addWidget(self.username)
        self.label_password = QLabel(self)
        self.verticalLayout.addWidget(self.label_password)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.verticalLayout.addWidget(self.password)
        self.save_password = QCheckBox(self)
        self.verticalLayout.addWidget(self.save_password)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.label_username.setBuddy(self.username)
        self.label_password.setBuddy(self.password)
        self.setWindowIcon(get_icon(MAIL_IMAGE))
        self.setWindowTitle("Gmail Login")
        self.label_username.setText("Username")
        self.label_password.setText("Password")
        self.save_password.setText("Save password")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Beispiel #5
0
class Login(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self)
        self.parent = parent
        self.resize(270, 160)
        self.verticalLayout = QVBoxLayout(self)
        self.label_username = QLabel(self)
        self.verticalLayout.addWidget(self.label_username)
        self.username = QLineEdit(self)
        self.verticalLayout.addWidget(self.username)
        self.label_password = QLabel(self)
        self.verticalLayout.addWidget(self.label_password)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.verticalLayout.addWidget(self.password)
        self.save_password = QCheckBox(self)
        self.verticalLayout.addWidget(self.save_password)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
                QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.label_username.setBuddy(self.username)
        self.label_password.setBuddy(self.password)
        self.setWindowIcon(get_icon(MAIL_IMAGE))
        self.setWindowTitle("Gmail Login")
        self.label_username.setText("Username")
        self.label_password.setText("Password")
        self.save_password.setText("Save password")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Beispiel #6
0
class Banjo(TablaturePart):
    @staticmethod
    def title(_=__builtin__._):
        return _("Banjo")

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

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

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

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

    def setTunings(self, tab):
        if not self.fourStrings.isChecked():
            super(Banjo, self).setTunings(tab)
        else:
            tab.getWith()["stringTunings"] = ly.dom.Scheme(
                "(four-string-banjo {0})".format(self.tunings[self.tuning.currentIndex()][0])
            )
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
 def prepareCheckBox(self, getVec, label):
     operationCheck = QCheckBox()
     operationCheck.setText(label)
     operationCheck.setFixedWidth(100)
     operationCheck.getVec = getVec
     operationCheck.clicked.connect(self.analysisOptionHandler) 
     return operationCheck
Beispiel #10
0
	def populateConfigTable(self):
		self.clearConfigTable()
		list_keys = self.list_keys
		list_values = self.list_values
		search_string = str(self.ui.searchLineEdit.text()).lower()
		
		_metadata_table = self.list_metadata_selected
		_index = 0
		for _key in list_keys:
			_name = _key

			if (search_string.strip() != '') and \
			   (not(search_string in _name.lower())):
				continue

			self.ui.configureTable.insertRow(_index)

			_nameItem = QTableWidgetItem(_name)
			self.ui.configureTable.setItem(_index, 1, _nameItem)

			_yesNo = QCheckBox()
			_id = list_keys.index(_name)
			_value = list_values[_id]
			_yesNo.setChecked(_value)
			_yesNo.setText('')
			_yesNo.stateChanged.connect(self.configTableEdited)
			self.ui.configureTable.setCellWidget(_index, 0, _yesNo)
			
			[value, units] = self.retrieveValueUnits(_name)
			_valueItem = QTableWidgetItem(value)
			self.ui.configureTable.setItem(_index, 2, _valueItem)
			_unitsItem = QTableWidgetItem(units)
			self.ui.configureTable.setItem(_index, 3, _unitsItem)
			
			_index += 1
Beispiel #11
0
    def populateConfigTable(self):
        self.clearConfigTable()
        list_keys = self.list_keys
        list_values = self.list_values
        search_string = str(self.ui.searchLineEdit.text()).lower()

        _metadata_table = self.list_metadata_selected
        _index = 0
        for _key in list_keys:
            _name = _key

            if (search_string.strip() != '') and \
               (not(search_string in _name.lower())):
                continue

            self.ui.configureTable.insertRow(_index)

            _nameItem = QTableWidgetItem(_name)
            self.ui.configureTable.setItem(_index, 1, _nameItem)

            _yesNo = QCheckBox()
            _id = list_keys.index(_name)
            _value = list_values[_id]
            _yesNo.setChecked(_value)
            _yesNo.setText('')
            _yesNo.stateChanged.connect(self.configTableEdited)
            self.ui.configureTable.setCellWidget(_index, 0, _yesNo)

            [value, units] = self.retrieveValueUnits(_name)
            _valueItem = QTableWidgetItem(value)
            self.ui.configureTable.setItem(_index, 2, _valueItem)
            _unitsItem = QTableWidgetItem(units)
            self.ui.configureTable.setItem(_index, 3, _unitsItem)

            _index += 1
Beispiel #12
0
    def create_checkbox ( self, parent, label = '' ):
        """ Returns an adapted checkbox control.
        """
        control = QCheckBox( check_parent( parent ) )
        control.setText( label )

        return control_adapter_for( control )
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.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 #14
0
def simple_dialog(parent, title, message, checkbox_text=None, yes_no=True):
    """
    A simple dialog the enable you show an html message with checkbox.
    :param parent: The parent of the dialog.
    :type parent: QWidget
    :param title: The title of the dialog
    :type title: String
    :param message: The message of the dialog. Use <br>
    to add a new line as it is html.
    :type message: String
    :param checkbox_text: Add a checkbox text, if None,
    the checkbox will not be shown.
    :type checkbox_text: String
    :param yes_no: A boolean to add the Yes No buttons.
    If false, the Ok button is shown.
    :type yes_no: Boolean
    :return: Tuple containing the dialog exec_ result
    and the checkbox result.
    :rtype: Tuple
    """
    simple_dialog = QDialog(
        parent,
        Qt.WindowSystemMenuHint | Qt.WindowTitleHint
    )
    simple_layout = QVBoxLayout(simple_dialog)
    simple_label = QLabel()

    simple_dialog.setWindowTitle(title)
    simple_label.setTextFormat(Qt.RichText)
    simple_label.setText(message)

    simple_layout.addWidget(simple_label)

    if checkbox_text:
        confirm_checkbox = QCheckBox()
        confirm_checkbox.setText(checkbox_text)
        simple_layout.addWidget(confirm_checkbox)
    simple_buttons = QDialogButtonBox()

    if yes_no:
        simple_buttons.setStandardButtons(
            QDialogButtonBox.Yes | QDialogButtonBox.No
        )
        simple_buttons.rejected.connect(simple_dialog.reject)

    else:
        simple_buttons.setStandardButtons(
            QDialogButtonBox.Ok
        )
    simple_buttons.accepted.connect(simple_dialog.accept)

    simple_layout.addWidget(simple_buttons)

    simple_dialog.setModal(True)
    result = simple_dialog.exec_()
    if not checkbox_text is None:
        return result, confirm_checkbox.isChecked()
    else:
        return result, False
Beispiel #15
0
 def unselectAll(self):
     _config_table = self.ui.configureTable
     nbr_row = _config_table.rowCount()
     for r in range(nbr_row):
         _name = self.ui.configureTable.item(r, 1).text()
         _yesNo = QCheckBox()
         _yesNo.setText('')
         self.ui.configureTable.setCellWidget(r, 0, _yesNo)
Beispiel #16
0
	def unselectAll(self):
		_config_table = self.ui.configureTable
		nbr_row = _config_table.rowCount()
		for r in range(nbr_row):
			_name = self.ui.configureTable.item(r,1).text()
			_yesNo = QCheckBox()
			_yesNo.setText('')
			self.ui.configureTable.setCellWidget(r, 0, _yesNo)
Beispiel #17
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())
    def buildPostProcessorForm(self, theParams):
        """Build Post Processor Tab

        Args:
           * theParams - dictionary containing element of form
        Returns:
           not applicable
        """

        # create postprocessors tab
        myTab = QWidget()
        myFormLayout = QFormLayout(myTab)
        myFormLayout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(myTab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        myValues = {}
        for myLabel, myOptions in theParams.items():
            myInputValues = {}

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in myOptions:
                myGroupBox = QGroupBox()
                myGroupBox.setCheckable(True)
                myGroupBox.setTitle(get_postprocessor_human_name(myLabel))

                # NOTE (gigih): is 'on' always exist??
                myGroupBox.setChecked(myOptions.get('on'))
                myInputValues['on'] = self.bind(myGroupBox, 'checked', bool)

                myLayout = QFormLayout(myGroupBox)
                myGroupBox.setLayout(myLayout)

                # create widget element from 'params'
                myInputValues['params'] = {}
                for myKey, myValue in myOptions['params'].items():
                    myHumanName = get_postprocessor_human_name(myKey)
                    myInputValues['params'][myKey] = self.buildWidget(
                        myLayout, myHumanName, myValue)

                myFormLayout.addRow(myGroupBox, None)

            elif 'on' in myOptions:
                myCheckBox = QCheckBox()
                myCheckBox.setText(get_postprocessor_human_name(myLabel))
                myCheckBox.setChecked(myOptions['on'])

                myInputValues['on'] = self.bind(myCheckBox, 'checked', bool)
                myFormLayout.addRow(myCheckBox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            myValues[myLabel] = myInputValues

        self.values['postprocessors'] = myValues
Beispiel #19
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.")
    def buildPostProcessorForm(self, theParams):
        """Build Post Processor Tab

        Args:
           * theParams - dictionary containing element of form
        Returns:
           not applicable
        """

        # create postprocessors tab
        myTab = QWidget()
        myFormLayout = QFormLayout(myTab)
        myFormLayout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(myTab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        myValues = {}
        for myLabel, myOptions in theParams.items():
            myInputValues = {}

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in myOptions:
                myGroupBox = QGroupBox()
                myGroupBox.setCheckable(True)
                myGroupBox.setTitle(get_postprocessor_human_name(myLabel))

                # NOTE (gigih): is 'on' always exist??
                myGroupBox.setChecked(myOptions.get('on'))
                myInputValues['on'] = self.bind(myGroupBox, 'checked', bool)

                myLayout = QFormLayout(myGroupBox)
                myGroupBox.setLayout(myLayout)

                # create widget element from 'params'
                myInputValues['params'] = {}
                for myKey, myValue in myOptions['params'].items():
                    myHumanName = get_postprocessor_human_name(myKey)
                    myInputValues['params'][myKey] = self.buildWidget(
                        myLayout, myHumanName, myValue)

                myFormLayout.addRow(myGroupBox, None)

            elif 'on' in myOptions:
                myCheckBox = QCheckBox()
                myCheckBox.setText(get_postprocessor_human_name(myLabel))
                myCheckBox.setChecked(myOptions['on'])

                myInputValues['on'] = self.bind(myCheckBox, 'checked', bool)
                myFormLayout.addRow(myCheckBox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            myValues[myLabel] = myInputValues

        self.values['postprocessors'] = myValues
Beispiel #21
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 #22
0
class QuadStatusBar(QHBoxLayout):
    def __init__(self, parent=None ):
        QHBoxLayout.__init__(self, parent)
        self.setContentsMargins(0,4,0,0)
        self.setSpacing(0)

    def showXYCoordinates(self):
        self.zLabel.setHidden(True)
        self.zSpinBox.setHidden(True)
        
    def showXYZCoordinates(self):
        self.zLabel.setHidden(False)
        self.zSpinBox.setHidden(False)
    
    def createQuadViewStatusBar(self,
                                xbackgroundColor, xforegroundColor,
                                ybackgroundColor, yforegroundColor,
                                zbackgroundColor, zforegroundColor):
        self.xLabel, self.xSpinBox = _get_pos_widget('X',
                                                     xbackgroundColor,
                                                     xforegroundColor)
        self.yLabel, self.ySpinBox = _get_pos_widget('Y',
                                                     ybackgroundColor,
                                                     yforegroundColor)
        self.zLabel, self.zSpinBox = _get_pos_widget('Z',
                                                     zbackgroundColor,
                                                     zforegroundColor)

        self.addWidget(self.xLabel)
        self.addWidget(self.xSpinBox)
        self.addWidget(self.yLabel)
        self.addWidget(self.ySpinBox)
        self.addWidget(self.zLabel)
        self.addWidget(self.zSpinBox)

        self.addStretch()

        self.positionCheckBox = QCheckBox()
        self.positionCheckBox.setChecked(True)
        self.positionCheckBox.setCheckable(True)
        self.positionCheckBox.setText("Position")
        self.addWidget(self.positionCheckBox)

        self.addSpacing(20)

        self.timeLabel = QLabel("Time:")
        self.addWidget(self.timeLabel)

        self.timeSpinBox = QSpinBox()
        self.addWidget(self.timeSpinBox)

    def setMouseCoords(self, x, y, z):
        self.xSpinBox.setValue(x)
        self.ySpinBox.setValue(y)
        self.zSpinBox.setValue(z)
class DeletionOptions(QDialog):
    def __init__(self, parent, model):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.model = model
        self._setupUi()
        self.model.view = self
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupUi(self):
        self.setWindowTitle(tr("Deletion Options"))
        self.resize(400, 270)
        self.verticalLayout = QVBoxLayout(self)
        self.msgLabel = QLabel()
        self.verticalLayout.addWidget(self.msgLabel)
        self.linkCheckbox = QCheckBox(tr("Link deleted files"))
        self.verticalLayout.addWidget(self.linkCheckbox)
        text = tr("After having deleted a duplicate, place a link targeting the reference file "
            "to replace the deleted file.")
        self.linkMessageLabel = QLabel(text)
        self.linkMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.linkMessageLabel)
        self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False)
        self.verticalLayout.addWidget(self.linkTypeRadio)
        if not self.model.supports_links():
            self.linkCheckbox.setEnabled(False)
            self.linkTypeRadio.setEnabled(False)
            self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)"))
        self.directCheckbox = QCheckBox(tr("Directly delete files"))
        self.verticalLayout.addWidget(self.directCheckbox)
        text = tr("Instead of sending files to trash, delete them directly. This option is usually "
            "used as a workaround when the normal deletion method doesn't work.")
        self.directMessageLabel = QLabel(text)
        self.directMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.directMessageLabel)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
        self.verticalLayout.addWidget(self.buttonBox)
    
    #--- model --> view
    def update_msg(self, msg):
        self.msgLabel.setText(msg)
    
    def show(self):
        self.linkCheckbox.setChecked(self.model.link_deleted)
        self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0
        self.directCheckbox.setChecked(self.model.direct)
        result = self.exec()
        self.model.link_deleted = self.linkCheckbox.isChecked()
        self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1
        self.model.direct = self.directCheckbox.isChecked()
        return result == QDialog.Accepted
Beispiel #24
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)
class QuadStatusBar(QHBoxLayout):
    def __init__(self, parent=None ):
        QHBoxLayout.__init__(self, parent)
        self.setContentsMargins(0,4,0,0)
        self.setSpacing(0)

    def showXYCoordinates(self):
        self.zLabel.setHidden(True)
        self.zSpinBox.setHidden(True)
        
    def showXYZCoordinates(self):
        self.zLabel.setHidden(False)
        self.zSpinBox.setHidden(False)
    
    def createQuadViewStatusBar(self,
                                xbackgroundColor, xforegroundColor,
                                ybackgroundColor, yforegroundColor,
                                zbackgroundColor, zforegroundColor):
        self.xLabel, self.xSpinBox = _get_pos_widget('X',
                                                     xbackgroundColor,
                                                     xforegroundColor)
        self.yLabel, self.ySpinBox = _get_pos_widget('Y',
                                                     ybackgroundColor,
                                                     yforegroundColor)
        self.zLabel, self.zSpinBox = _get_pos_widget('Z',
                                                     zbackgroundColor,
                                                     zforegroundColor)

        self.addWidget(self.xLabel)
        self.addWidget(self.xSpinBox)
        self.addWidget(self.yLabel)
        self.addWidget(self.ySpinBox)
        self.addWidget(self.zLabel)
        self.addWidget(self.zSpinBox)

        self.addStretch()

        self.positionCheckBox = QCheckBox()
        self.positionCheckBox.setChecked(True)
        self.positionCheckBox.setCheckable(True)
        self.positionCheckBox.setText("Position")
        self.addWidget(self.positionCheckBox)

        self.addSpacing(20)

        self.timeLabel = QLabel("Time:")
        self.addWidget(self.timeLabel)

        self.timeSpinBox = QSpinBox()
        self.addWidget(self.timeSpinBox)

    def setMouseCoords(self, x, y, z):
        self.xSpinBox.setValue(x)
        self.ySpinBox.setValue(y)
        self.zSpinBox.setValue(z)
Beispiel #26
0
	def checkTrueImportedMetadataFromConfigFile(self):
		list_metadata_selected = self.list_metadata_selected
		_config_table = self.ui.configureTable
		nbr_row = _config_table.rowCount()
		for r in range(nbr_row):
			_name = self.ui.configureTable.item(r,1).text()
			_yesNo = QCheckBox()
			if _name in list_metadata_selected:
				_yesNo.setChecked(True)
			_yesNo.setText('')
			self.ui.configureTable.setCellWidget(r, 0, _yesNo)
Beispiel #27
0
 def checkTrueImportedMetadataFromConfigFile(self):
     list_metadata_selected = self.list_metadata_selected
     _config_table = self.ui.configureTable
     nbr_row = _config_table.rowCount()
     for r in range(nbr_row):
         _name = self.ui.configureTable.item(r, 1).text()
         _yesNo = QCheckBox()
         if _name in list_metadata_selected:
             _yesNo.setChecked(True)
         _yesNo.setText('')
         self.ui.configureTable.setCellWidget(r, 0, _yesNo)
Beispiel #28
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())
class NewSensorgroupPage0(QWizardPage):
    """WizardPage to select sensorgroup name, title and importer"""
    def __init__(self, parent, project):
        QWizardPage.__init__(self, parent)
        self.setTitle(QCoreApplication.translate('DataStorageBrowser',
            'Select name, title and data type'))
        self.project = project
        self.mainLayout = QGridLayout()
        self.setLayout(self.mainLayout)

        nameLabel = QLabel(self)
        nameLabel.setText(QCoreApplication.translate('DataStorageBrowser', 'Name'))
        self.mainLayout.addWidget(nameLabel, 0, 0)
        self.nameInput = QLineEdit(self)
        self.nameInput.setText(uniqueName('unnamed', project.keys()))
        self.registerField('name', self.nameInput, 'text')
        self.mainLayout.addWidget(self.nameInput, 0, 1)

        titleLabel = QLabel(self)
        titleLabel.setText(QCoreApplication.translate('DataStorageBrowser', 'Title'))
        self.mainLayout.addWidget(titleLabel, 1, 0)
        self.titleInput = QLineEdit(self)
        self.titleInput.setText('...')
        self.registerField('title', self.titleInput, 'text')
        self.mainLayout.addWidget(self.titleInput, 1, 1)

        typeLabel = QLabel(self)
        typeLabel.setText(QCoreApplication.translate('DataStorageBrowser', 'Data type'))
        self.mainLayout.addWidget(typeLabel, 2, 0)
        self.typeSelect = QComboBox(self)
        self.typeSelect.addItem('CSV')
        self.typeSelect.addItem('Remus')
        self.registerField('type', self.typeSelect, 'currentText')
        self.mainLayout.addWidget(self.typeSelect, 2, 1)

        self.importFilesButton = QCheckBox(self)
        self.importFilesButton.setChecked(True)
        self.importFilesButton.setText(QCoreApplication.translate('DataStorageBrowser',
            'Import files after creation'))
        self.registerField('importFiles', self.importFilesButton, 'checked')
        self.mainLayout.addWidget(self.importFilesButton, 3, 0, 3, 2)


    def validatePage(self):
        n = str(self.field('name').toString())
        if not n:
            return False
        if n in self.project.keys():
            b = QMessageBox.question(self, QCoreApplication.translate('DataStorageBrowser',
                'Sensorgroup already exists!'), QCoreApplication.translate('DataStorageBrowser',
                'A sensorgroup with this name already exists. Do you really want to overwrite it?'),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            return b == QMessageBox.Yes
        return True
    def build_post_processor_form(self, parameters):
        """Build Post Processor Tab.

        :param parameters: A Dictionary containing element of form
        :type parameters: dict
        """
        # create postprocessors tab
        tab = QWidget()
        form_layout = QFormLayout(tab)
        form_layout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(tab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        values = OrderedDict()
        for label, options in parameters.items():
            input_values = OrderedDict()

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in options:
                group_box = QGroupBox()
                group_box.setCheckable(True)
                group_box.setTitle(get_postprocessor_human_name(label))

                # NOTE (gigih): is 'on' always exist??
                # (MB) should always be there
                group_box.setChecked(options.get('on'))
                input_values['on'] = self.bind(group_box, 'checked', bool)

                layout = QFormLayout(group_box)
                group_box.setLayout(layout)

                # create widget element from 'params'
                input_values['params'] = OrderedDict()
                for key, value in options['params'].items():
                    input_values['params'][key] = self.build_widget(
                        layout, key, value)

                form_layout.addRow(group_box, None)

            elif 'on' in options:
                checkbox = QCheckBox()
                checkbox.setText(get_postprocessor_human_name(label))
                checkbox.setChecked(options['on'])

                input_values['on'] = self.bind(checkbox, 'checked', bool)
                form_layout.addRow(checkbox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            values[label] = input_values

        self.values['postprocessors'] = values
    def build_post_processor_form(self, parameters):
        """Build Post Processor Tab.

        :param parameters: A Dictionary containing element of form
        :type parameters: dict
        """
        # create postprocessors tab
        tab = QWidget()
        form_layout = QFormLayout(tab)
        form_layout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(tab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        values = OrderedDict()
        for label, options in parameters.items():
            input_values = OrderedDict()

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in options:
                group_box = QGroupBox()
                group_box.setCheckable(True)
                group_box.setTitle(get_postprocessor_human_name(label))

                # NOTE (gigih): is 'on' always exist??
                # (MB) should always be there
                group_box.setChecked(options.get('on'))
                input_values['on'] = self.bind(group_box, 'checked', bool)

                layout = QFormLayout(group_box)
                group_box.setLayout(layout)

                # create widget element from 'params'
                input_values['params'] = OrderedDict()
                for key, value in options['params'].items():
                    input_values['params'][key] = self.build_widget(
                        layout, key, value)

                form_layout.addRow(group_box, None)

            elif 'on' in options:
                checkbox = QCheckBox()
                checkbox.setText(get_postprocessor_human_name(label))
                checkbox.setChecked(options['on'])

                input_values['on'] = self.bind(checkbox, 'checked', bool)
                form_layout.addRow(checkbox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            values[label] = input_values

        self.values['postprocessors'] = values
Beispiel #32
0
class Dialog(toly_dialog.ToLyDialog):
	
    def __init__(self, parent=None):
        
        self.imp_prgm = "midi2ly"
        self.userg = "midi_import"
        
        self.useAbsCheck = QCheckBox()
        
        self.impChecks = [self.useAbsCheck]
        
        self.useAbsCheck.setObjectName("absolute-mode")
        
        self.impExtra = []
        
        super(Dialog, self).__init__(parent)
        
        app.translateUI(self)
        qutil.saveDialogSize(self, "midi_import/dialog/size", QSize(480, 260))
        
        self.makeCommandLine()
        
        self.loadSettings()
        
    def translateUI(self):
        self.useAbsCheck.setText(_("Pitches in absolute mode"))
        
        self.buttons.button(QDialogButtonBox.Ok).setText(_("Run midi2ly"))
        
        super(Dialog, self).translateUI()
    
    def makeCommandLine(self):
        """Reads the widgets and builds a command line."""
        cmd = ["$midi2ly"]
        if self.useAbsCheck.isChecked():
            cmd.append('-a')

        cmd.append("$filename")
        self.commandLine.setText(' '.join(cmd))
        
    def loadSettings(self):
        """Get users previous settings."""
        self.imp_default = [False]
        self.settings = QSettings()
        self.settings.beginGroup('midi_import')
        super(Dialog, self).loadSettings()
        
    def saveSettings(self):
        """Save users last settings."""
        self.settings = QSettings()
        self.settings.beginGroup('midi_import')
        super(Dialog, self).saveSettings()
Beispiel #33
0
class Dialog(toly_dialog.ToLyDialog):
    def __init__(self, parent=None):

        self.imp_prgm = "midi2ly"
        self.userg = "midi_import"

        self.useAbsCheck = QCheckBox()

        self.impChecks = [self.useAbsCheck]

        self.useAbsCheck.setObjectName("absolute-mode")

        self.impExtra = []

        super(Dialog, self).__init__(parent)

        app.translateUI(self)
        qutil.saveDialogSize(self, "midi_import/dialog/size", QSize(480, 260))

        self.makeCommandLine()

        self.loadSettings()

    def translateUI(self):
        self.useAbsCheck.setText(_("Pitches in absolute mode"))

        self.buttons.button(QDialogButtonBox.Ok).setText(_("Run midi2ly"))

        super(Dialog, self).translateUI()

    def makeCommandLine(self):
        """Reads the widgets and builds a command line."""
        cmd = ["$midi2ly"]
        if self.useAbsCheck.isChecked():
            cmd.append('-a')

        cmd.append("$filename")
        self.commandLine.setText(' '.join(cmd))

    def loadSettings(self):
        """Get users previous settings."""
        self.imp_default = [False]
        self.settings = QSettings()
        self.settings.beginGroup('midi_import')
        super(Dialog, self).loadSettings()

    def saveSettings(self):
        """Save users last settings."""
        self.settings = QSettings()
        self.settings.beginGroup('midi_import')
        super(Dialog, self).saveSettings()
Beispiel #34
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 #35
0
    def populateconfigureTable(self):
        if self.ui.inputErrorLabel.isVisible():
            return
        if self.list_filename == []:
            return
        self.clearConfigureTable()
        #_filename = self.list_filename[0]
        #nxs = LoadEventNexus(Filename=_filename)
        
        nxs = self.list_nxs[0]
        if self.first_load:
            self.first_load = False
            #mt_run = nxs.getRun()
            #self.list_keys = mt_run.keys()
            self.initListMetadata()
            self.retrieveListMetadataPreviouslySelected()

        list_keys = self.list_keys
        list_values = self.list_values
        search_string = str(self.ui.searchLineEdit.text()).lower()

        _index = 0
        for _key in list_keys:
            _name = _key
            if (search_string.strip() != '') and \
               (not(search_string in _name.lower())):
                continue
            
            self.ui.configureTable.insertRow(_index)

            _yesNo = QCheckBox()
            _id = list_keys.index(_name)
            _value = list_values[_id]
            _yesNo.setChecked(_value)
            _yesNo.setText('')
            _yesNo.stateChanged.connect(self.configTableEdited)
            self.ui.configureTable.setCellWidget(_index, 0, _yesNo)

            _nameItem = QTableWidgetItem(_name)
            self.ui.configureTable.setItem(_index, 1, _nameItem)

            [value, units] = self.retrieveValueUnits(nxs.getRun(), 
                                                    _name)
            _valueItem = QTableWidgetItem(value)
            self.ui.configureTable.setItem(_index, 2, _valueItem)
            _unitsItem = QTableWidgetItem(units)
            self.ui.configureTable.setItem(_index, 3, _unitsItem)

            _index += 1
Beispiel #36
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 #37
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 #38
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 #39
0
    def populateconfigureTable(self):
        if self.ui.inputErrorLabel.isVisible():
            return
        if self.list_filename == []:
            return
        self.clearConfigureTable()
        # _filename = self.list_filename[0]
        # nxs = LoadEventNexus(Filename=_filename)

        nxs = self.list_nxs[0]
        if self.first_load:
            self.first_load = False
            # mt_run = nxs.getRun()
            # self.list_keys = mt_run.keys()
            self.initListMetadata()
            self.retrieveListMetadataPreviouslySelected()

        list_keys = self.list_keys
        list_values = self.list_values
        search_string = str(self.ui.searchLineEdit.text()).lower()

        _index = 0
        for _key in list_keys:
            _name = _key
            if (search_string.strip() != "") and (not (search_string in _name.lower())):
                continue

            self.ui.configureTable.insertRow(_index)

            _yesNo = QCheckBox()
            _id = list_keys.index(_name)
            _value = list_values[_id]
            _yesNo.setChecked(_value)
            _yesNo.setText("")
            _yesNo.stateChanged.connect(self.configTableEdited)
            self.ui.configureTable.setCellWidget(_index, 0, _yesNo)

            _nameItem = QTableWidgetItem(_name)
            self.ui.configureTable.setItem(_index, 1, _nameItem)

            [value, units] = self.retrieveValueUnits(nxs.getRun(), _name)
            _valueItem = QTableWidgetItem(value)
            self.ui.configureTable.setItem(_index, 2, _valueItem)
            _unitsItem = QTableWidgetItem(units)
            self.ui.configureTable.setItem(_index, 3, _unitsItem)

            _index += 1
        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)
Beispiel #41
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())
    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 )
    def __init__(self, models):
        QDialog.__init__(self)

        self._ui = Ui_Dialog()
        self._ui.setupUi(self)

        self._model_checkboxes = []

        row = 1
        for model in models:
            branch_name = model.get_new_branch_name() or \
                          model.get_current_branch().name
            mod_count = model.get_modified_count()
            del_count = model.get_deleted_count()
            to_rewrite = run_long_operation("Calculating dependencies",
                                            model.get_to_rewrite_count,
                                            parent=self)
            is_name_modified = model.is_name_modified()

            display_string = ""
            if model.is_fake_model():
                display_string += "New branch."
            else:
                if is_name_modified:
                    display_string += "New name %s." % is_name_modified

                if mod_count:
                    display_string += "%d modified, %d to rewrite." % \
                                      (mod_count, to_rewrite)
                elif del_count:
                    display_string += "%d deleted, %d to rewrite." % \
                                      (del_count, to_rewrite)

            if display_string:
                count_label = QLabel(QString(display_string))
                count_label.setAlignment(Qt.AlignRight)

                checkbox = QCheckBox(self)
                checkbox.setText(QString(branch_name))
                self._ui.branchCountLayout.addWidget(checkbox, row, 0, 1, 2)
                self._ui.branchCountLayout.addWidget(count_label, row, 1, 1, 2)

                self._model_checkboxes.append((checkbox, model))

                row += 1
Beispiel #44
0
def createLabelAndCheckBox(labelText, changedSlot):
    # is it really needed to have 2 widgets ?
    widget = QWidget()

    sub_layout = QHBoxLayout()
    sub_layout.setObjectName('labelAndCheckBoxLayout')

    widget.setLayout(sub_layout)

    checkBox = QCheckBox(widget)
    widget.connect(checkBox, SIGNAL('stateChanged(int)'), changedSlot)
    checkBox.setText(labelText)
    checkBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

    sub_layout.addWidget(checkBox)
    sub_layout.addStretch(100)

    return (widget, checkBox)
Beispiel #45
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 #46
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())
    def create_checkboxes(self):
        """
            Creates the checkboxes used to determine what columns are to be
            displayed or what options should be set to the model (i.e. should
            we display the weekday, etc.)
        """
        # Hiding every columns (even those not listed in AVAILABLE_CHOICES)
        for column, field in enumerate(self._model.get_columns()):
            self.gui.tableView.hideColumn(column)

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

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

        spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gui.checkboxLayout.addItem(spacer_item, 0, count, 1, 1)
        self.refresh_checkboxes(resize=False)
        self.refresh_display_options(resize=False)
Beispiel #48
0
    def valToWidgetContainer(self, attr, val):
        """
        construct a widget container for the specified attribute
        """
        options = self.getRequiredOptionsListForAttribute(attr)
        # the default container type is the more general one
        if type(val) is bool:
            # create a new check box with checked state set to val

            widget = QCheckBox(self)
            widget.setText("")
            widget.setChecked(val)
            self.connect(widget, SIGNAL("stateChanged(int)"),
                         self.reactOnUserInput)
            if self.isErrorKey(attr):
                widget.setStyleSheet(self.ERRORSTYLE.format("QCheckBox"))
            valueCallable = widget.isChecked

        elif options is not None:
            # use a combobox to represent a list of options
            widget = OptionsComboBox(self)
            widget.addItems(options)
            if val is not None:
                widget.setCurrentIndex(options.index(str(val)))
            self.connect(widget, SIGNAL("currentIndexChanged(int)"),
                         self.reactOnUserInput)
            if self.isErrorKey(attr):
                widget.setStyleSheet(self.ERRORSTYLE.format("OptionsComboBox"))
            valueCallable = widget.currentText

        else:
            # use a simple line edit if options are undefined
            widget = QLineEdit(self)
            widget.setText(self.convertToText(val))
            self.connect(widget, SIGNAL("editingFinished()"),
                         self.reactOnUserInput)
            if self.isErrorKey(attr):
                widget.setStyleSheet(self.ERRORSTYLE.format("QLineEdit"))
            valueCallable = widget.text

        return EditableAttributeWidgetContainer(attr, widget, valueCallable)
 def __init__(self, parent, sensorgroup):
     QWizardPage.__init__(self, parent)
     self.setTitle(QCoreApplication.translate('DataStorageBrowser', 'Select type/template of chart'))
     self.setFinalPage(True)
     self.sensorgroup = sensorgroup
     self.mainLayout = QVBoxLayout()
     self.setLayout(self.mainLayout)
     layout0 = QHBoxLayout()
     self.templateSelect = QListWidget(self)
     self.templateSelect.setSelectionMode(QAbstractItemView.SingleSelection)
     layout0.addWidget(self.templateSelect)
     self.templatePreview = QLabel(self)
     self.templatePreview.setScaledContents(True)
     self.templatePreview.setMinimumSize(200, 200)
     self.templatePreview.setMaximumSize(200, 200)
     self.templatePreview.setFrameStyle(QFrame.Panel|QFrame.Sunken)
     layout0.addWidget(self.templatePreview)
     self.mainLayout.addLayout(layout0)
     self.templateInfo = QTextEdit(self)
     self.templateInfo.setReadOnly(True)
     self.templateInfo.setMinimumSize(400, 80)
     self.mainLayout.addWidget(self.templateInfo)
     layout1 = QHBoxLayout()
     nameLabel = QLabel(self)
     nameLabel.setText(QCoreApplication.translate('DataStorageBrowser', 'Chart name:'))
     layout1.addWidget(nameLabel)
     self.nameInput = QLineEdit(self)
     layout1.addWidget(self.nameInput)
     self.mainLayout.addLayout(layout1)
     openChartButton = QCheckBox(self)
     openChartButton.setChecked(True)
     openChartButton.setText(QCoreApplication.translate('DataStorageBrowser', 'Open chart window after creation'))
     self.mainLayout.addWidget(openChartButton)
     for t in chartTemplates:
         self.templateSelect.addItem(t.name)
     self.registerField('templateNumber', self.templateSelect, 'currentRow')
     self.registerField('chartName', self.nameInput, 'text')
     self.registerField('openChart', openChartButton, 'checked')
     self.ownPlugIn = SimuVis4.Globals.plugInManager['DataStorageBrowser']
     self.connect(self.templateSelect, SIGNAL("currentRowChanged(int)"), self.templateChanged)
     self.templateSelect.setCurrentRow(0)
Beispiel #50
0
class Banjo(TablaturePart):
    @staticmethod
    def title(_=_base.translate):
        return _("Banjo")

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

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

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

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

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

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

    def createWidgets(self, layout):
        self.extenderLines = QCheckBox()
        layout.addWidget(self.extenderLines)

    def translateWidgets(self):
        self.extenderLines.setText(_("Use extender lines"))

    def build(self, data, builder):
        a = data.assign('figBass')
        s = ly.dom.FigureMode(a)
        p = ly.dom.FiguredBass()
        ly.dom.Identifier(a.name, p)
        ly.dom.Identifier(data.globalName, s)
        ly.dom.LineComment(_("Figures follow here."), s)
        ly.dom.BlankLine(s)
        if self.extenderLines.isChecked():
            p.getWith()['useBassFigureExtenders'] = ly.dom.Scheme('#t')
        data.nodes.append(p)
Beispiel #52
0
class DocumentList(preferences.Group):
    def __init__(self, page):
        super(DocumentList, self).__init__(page)

        layout = QVBoxLayout()
        self.setLayout(layout)
        self.groupCheck = QCheckBox(toggled=self.changed)
        layout.addWidget(self.groupCheck)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Documents"))
        self.groupCheck.setText(_("Group documents by directory"))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("document_list")
        self.groupCheck.setChecked(s.value("group_by_folder", False, bool))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("document_list")
        s.setValue("group_by_folder", self.groupCheck.isChecked())
Beispiel #53
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 #54
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 #55
0
class previewDlg(QMainWindow):
    '''
    classdocs
    '''
    def __init__(self, parent, comp, basePMCheck, model):
        '''
        Constructor
        '''

        QMainWindow.__init__(self, parent)

        self.basePMCheck = basePMCheck
        #         self.ui = Ui_Previewself.grbPageProperty()
        #         self.ui.setupUi(self)
        self.resize(1000, 700)
        self.setWindowTitle("Preview Dialog")
        self.view = QgsComposerView(self)
        viewLayout = QGridLayout()
        viewLayout.setSpacing(0)
        viewLayout.setMargin(0)
        mHorizontalRuler = QgsComposerRuler(QgsComposerRuler.Horizontal)
        mVerticalRuler = QgsComposerRuler(QgsComposerRuler.Vertical)
        mRulerLayoutFix = QWidget()
        mRulerLayoutFix.setAttribute(Qt.WA_NoMousePropagation)
        mRulerLayoutFix.setBackgroundRole(QPalette.Window)
        mRulerLayoutFix.setFixedSize(mVerticalRuler.rulerSize(),
                                     mHorizontalRuler.rulerSize())
        viewLayout.addWidget(mRulerLayoutFix, 0, 0)
        viewLayout.addWidget(mHorizontalRuler, 0, 1)
        viewLayout.addWidget(mVerticalRuler, 1, 0)

        self.view.setContentsMargins(0, 0, 0, 0)
        self.view.setHorizontalRuler(mHorizontalRuler)
        self.view.setVerticalRuler(mVerticalRuler)
        viewLayout.addWidget(self.view, 1, 1)

        #         self.scene = comp

        self.view.setZoomLevel(1.0)
        self.view.setComposition(comp)
        self.scene = self.view.composition()
        layout = QVBoxLayout()
        hLayout = QHBoxLayout()
        hLayout.addLayout(viewLayout)

        self.mapItem = self.scene.getComposerMapById(0)

        self.view.scale(2.8, 2.8)
        self.view.setPreviewModeEnabled(True)

        self.toolBarAction = self.addToolBar("composer action")
        self.actionMapRefresh = QAction(self)
        self.actionMapRefresh.setObjectName("actionMapRefresh")
        icon3 = QIcon("Resource/Refresh.png")
        self.actionMapRefresh.setIcon(icon3)
        self.actionMapRefresh.setToolTip("Refresh")
        # self.textItemAction.setCheckable(True)
        self.connect(self.actionMapRefresh, SIGNAL("triggered()"),
                     self.actionMapRefresh_triggered)
        self.toolBarAction.addAction(self.actionMapRefresh)

        # # self.templeteCreateAction = QAction(self)
        # # self.templeteCreateAction.setObjectName("createTempleteAction")
        # # icon4 = QIcon("Resource\\templetepointer.png")
        # # self.templeteCreateAction.setIcon(icon4)
        # # self.templeteCreateAction.setToolTip("Create Templete")
        # # self.templeteCreateAction.setCheckable(True)
        # # self.connect(self.templeteCreateAction, SIGNAL("triggered()"), self.createTempleteAction)
        # # self.toolBar.addAction(self.templeteCreateAction)
        # layout.insertWidget(0, self.toolBar)

        #         self.scene.selectedItemChanged.connect(self.selectedItemDisplay)
        self.view.selectedItemChanged.connect(self.selectedItemDisplay)

        self.view.cursorPosChanged.connect(self.cursorPosChangedEvent)
        #         self.connect(self.view, SIGNAL("selectedItemChanged(QgsComposerItem)"),self, SLOT("selectedItemDisplay(QgsComposerItem)"))
        #         self.scene.composerLabelAdded.connect(self.composerLabelAddedEvent)
        self.view.itemRemoved.connect(self.deleteItem)
        # self.connect( self.view, SIGNAL( "actionFinished()" ), self.setSelectionTool)

        #listen out for position updates from the QgsComposerView
        self.propertyWidget = QWidget(self)
        hLayout.addWidget(self.propertyWidget)
        self.propertyWidget.setObjectName("propertyWidget")
        self.propertyWidget.resize(222, 302)
        self.vLayout_3 = QVBoxLayout(self.propertyWidget)
        self.vLayout_3.setObjectName("vLayout_3")
        self.groupBox = QGroupBox(self.propertyWidget)
        self.groupBox.setObjectName("groupBox")
        self.horizontalLayout_2 = QHBoxLayout(self.groupBox)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.frame = QFrame(self.groupBox)
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.verticalLayout = QVBoxLayout(self.frame)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QLabel(self.frame)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)
        self.labelText = QPlainTextEdit(self.frame)
        self.labelText.setObjectName("labelText")
        self.verticalLayout.addWidget(self.labelText)
        self.btnLabelFont = QPushButton(self.frame)
        self.btnLabelFont.setObjectName("btnLabelFont")
        self.verticalLayout.addWidget(self.btnLabelFont)
        self.btnLabelColor = QPushButton(self.frame)
        self.btnLabelColor.setObjectName("btnLabelColor")
        self.verticalLayout.addWidget(self.btnLabelColor)
        self.frame_2 = QFrame(self.frame)
        self.frame_2.setFrameShape(QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QFrame.Raised)
        self.frame_2.setObjectName("frame_2")
        self.horizontalLayout = QHBoxLayout(self.frame_2)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QLabel(self.frame_2)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.spinLabelRotation = QSpinBox(self.frame_2)
        self.spinLabelRotation.setObjectName("spinLabelRotation")
        self.spinLabelRotation.setMinimum(-360)
        self.spinLabelRotation.setMaximum(360)
        self.horizontalLayout.addWidget(self.spinLabelRotation)
        self.verticalLayout.addWidget(self.frame_2)
        self.chbBackgroundEnable = QCheckBox(self.frame)
        self.chbBackgroundEnable.setChecked(True)
        self.chbBackgroundEnable.setObjectName("chbBackgroundEnable")
        self.verticalLayout.addWidget(self.chbBackgroundEnable)
        self.horizontalLayout_2.addWidget(self.frame)
        self.vLayout_3.addWidget(self.groupBox)

        self.resolutionFrame = QFrame(self.frame)
        self.resolutionFrame.setFrameShape(QFrame.StyledPanel)
        self.resolutionFrame.setFrameShadow(QFrame.Raised)
        self.resolutionFrame.setObjectName("resolutionFrame")
        self.horizontalLayout4 = QHBoxLayout(self.resolutionFrame)
        self.horizontalLayout4.setObjectName("horizontalLayout4")
        self.label_resolution = QLabel(self.resolutionFrame)
        self.label_resolution.setObjectName("label_resolution")
        self.label_resolution.setText("Print Resolution (dpi):")
        self.horizontalLayout4.addWidget(self.label_resolution)
        self.spinResolution = QSpinBox(self.resolutionFrame)
        self.spinResolution.setObjectName("spinResolution")
        self.spinResolution.setMinimum(0)
        self.spinResolution.setMaximum(1000)
        self.spinResolution.setValue(300)
        self.horizontalLayout4.addWidget(self.spinResolution)
        #         self.verticalLayout.addWidget(self.frame_2)
        self.vLayout_3.addWidget(self.resolutionFrame)

        self.gbTable = GroupBox(self.propertyWidget)
        self.gbTable.Caption = "Table"
        self.vLayout_3.addWidget(self.gbTable)

        self.mTableView = QTableView(self.gbTable)
        self.gbTable.Add = self.mTableView
        hHeder = self.mTableView.horizontalHeader()
        hHeder.setVisible(False)
        vHeder = self.mTableView.verticalHeader()
        vHeder.setVisible(False)
        # self.mTableView.setFixedHeight(70)
        # self.mTableView.setFixedWidth(comp.paperWidth() - 40)

        # self.stdItemModel = QStandardItemModel()
        # self.

        self.spaceItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                     QSizePolicy.Expanding)
        self.vLayout_3.addItem(self.spaceItem)

        self.groupBox.setTitle("Label Property")
        self.label.setText("Label Text:")
        self.btnLabelFont.setText("Label Font")
        self.btnLabelColor.setText("Label Color")
        self.label_2.setText("Label Rotation:")
        self.chbBackgroundEnable.setText("Background Enable")
        self.groupBox.setEnabled(False)
        self.connect(self.btnLabelFont, SIGNAL("clicked()"),
                     self.btnLabelFontClick)
        self.connect(self.btnLabelColor, SIGNAL("clicked()"),
                     self.btnLabelColorClick)
        self.connect(self.chbBackgroundEnable, SIGNAL("clicked()"),
                     self.chbBackgroundEnableClick)
        self.labelText.textChanged.connect(self.labelTextChanged)
        self.spinLabelRotation.valueChanged.connect(
            self.spinLabelRotationValueChanged)
        layout.addLayout(hLayout)
        #
        self.btnBack = QPushButton()
        self.btnBack.setText("back")
        footerLayout = QHBoxLayout()
        footerLayout.addWidget(self.btnBack)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        footerLayout.addWidget(self.buttonBox)
        layout.addLayout(footerLayout)
        self.setLayout(layout)

        deleteItemKey = QShortcut(QKeySequence(Qt.Key_Delete), self)
        deleteItemKey.activated.connect(self.deleteItem)

        # self.btnBack.clicked.connect(self.back)
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.acceptMethod)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.btnCancel = self.buttonBox.button(QDialogButtonBox.Cancel)
        self.view.setCurrentTool(QgsComposerView.Select)

        self.btnLabelColor.setVisible(False)
        # self.btnBack.setVisible(False)
        self.chbBackgroundEnable.setVisible(False)
        #         self.view.emit(SIGNAL("actionFinished"))

        #         if self.scene.plotStyle() != QgsComposition.Preview:
        #         self.scene.setPlotStyle(QgsComposition.Preview)
        #         self.mapItem.setPreviewMode(QgsComposerMap.Render)
        #         self.mapItem.updateCachedImage()
        #         self.mapItem.setSelected(True)
        self.mComposition = comp
        self.composerMapItem = self.mComposition.composerMapItems()[0]
        self.composerMapItem.setUpdatesEnabled(True)
        self.mStdModel = model

        self.mTableView.setModel(self.mStdModel)
        self.mTableView.setSpan(0, 0, 1, 6)
        self.mTableView.setSpan(1, 0, 1, 2)
        self.mTableView.setSpan(2, 0, 2, 1)
        self.mTableView.setSpan(4, 0, 1, 2)
        self.mTableView.setSpan(5, 0, 1, 2)
        self.mTableView.setSpan(6, 0, 1, 2)

        self.mTableView.setSpan(0, 6, 1, 8)
        self.mTableView.setSpan(1, 7, 1, 4)
        self.mTableView.setSpan(1, 11, 1, 3)
        self.mTableView.setSpan(2, 7, 1, 4)
        self.mTableView.setSpan(2, 11, 1, 3)

    def acceptMethod(self):
        # self.mStdModel.setItem(0, QStandardItem("nnnnnnnn"))
        filePath = QFileDialog.getSaveFileName(
            self, "Save PDF File", QCoreApplication.applicationDirPath(),
            "pdf files(*.pdf )")
        if filePath == "":
            return
        self.mComposition.clearSelection()
        self.mComposition.setPrintResolution(self.spinResolution.value())
        resultPdf = self.mComposition.exportAsPDF(filePath)
        if resultPdf:
            message = QMessageBox.information(self, "Result",
                                              "Successful export PDF")
        else:
            message = QMessageBox.information(self, "Result",
                                              "Don't export PDF")

    def rePresent(self, comp, model):
        self.mComposition = comp
        self.mStdModel = model
        self.view.setComposition(comp)
        self.scene = self.view.composition()

    def back(self):
        self.done(2)

    def spinLabelRotationValueChanged(self, rotationValue):
        self.selectedLabelItem.setItemRotation(rotationValue)

    def cursorPosChangedEvent(self, scenePointF):
        self.scenePoint = scenePointF
#         i = 100

    def labelTextChanged(self):
        self.selectedLabelItem.beginCommand(
            "Label text changed", QgsComposerMergeCommand.ComposerLabelSetText)
        self.selectedLabelItem.blockSignals(True)
        self.selectedLabelItem.setText(self.labelText.toPlainText())
        self.selectedLabelItem.update()
        self.selectedLabelItem.blockSignals(False)
        self.selectedLabelItem.endCommand()

    def chbBackgroundEnableClick(self):
        if self.chbBackgroundEnable.isChecked():
            self.selectedLabelItem.setBackgroundEnabled(True)
            self.mapItem.updateCachedImage()
        else:
            self.selectedLabelItem.setBackgroundEnabled(False)
            self.mapItem.updateCachedImage()

    def btnLabelFontClick(self):
        dlgFont = QFontDialog(self)
        dlgFont.setCurrentFont(self.selectedLabelItem.font())
        result = dlgFont.exec_()
        if result == 1:
            self.labelFont = dlgFont.selectedFont()
        else:
            self.labelFont = QFont()

        self.selectedLabelItem.setFont(self.labelFont)

    def btnLabelColorClick(self):
        dlgColor = QColorDialog(self)
        dlgColor.setCurrentColor(self.selectedLabelItem.fontColor())
        result = dlgColor.exec_()
        if result == 1:
            self.labelColor = dlgColor.selectedColor()
            self.selectedLabelItem.setFontColor(self.labelColor)

    def createTempleteAction(self):
        if self.templeteCreateAction.isChecked() and self.basePMCheck:
            font = QFont("Arial", 13)
            font.setItalic(True)
            self.compLabel1 = QgsComposerLabel(self.scene)
            self.compLabel1.setFont(font)
            self.compLabel1.setText("South China Sea")
            self.compLabel1.setBackgroundEnabled(False)
            self.compLabel1.setItemPosition(156, 100)
            self.compLabel1.adjustSizeToText()
            self.compLabel1.setItemRotation(60)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel1)

            self.compLabel2 = QgsComposerLabel(self.scene)
            self.compLabel2.setFont(font)
            self.compLabel2.setText("Straits Of Malacca")
            self.compLabel2.setBackgroundEnabled(False)
            self.compLabel2.setItemPosition(35, 100)
            self.compLabel2.adjustSizeToText()
            self.compLabel2.setItemRotation(60)
            self.scene.addItem(self.compLabel2)

            font.setItalic(False)
            self.compLabel3 = QgsComposerLabel(self.scene)
            self.compLabel3.setFont(font)
            self.compLabel3.setBackgroundEnabled(False)
            self.compLabel3.setText("THAILAND")
            self.compLabel3.setItemPosition(68, 60)
            self.compLabel3.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel3)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel4 = QgsComposerLabel(self.scene)
            self.compLabel4.setFont(font)
            self.compLabel4.setBackgroundEnabled(False)
            self.compLabel4.setText("SINGAPORE")
            self.compLabel4.setItemPosition(141, 218)
            self.compLabel4.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel4)
            self.templeteCreateAction.setChecked(False)
            self.compLabel4.setSelected(True)
        elif self.templeteCreateAction.isChecked(
        ) and self.basePMCheck == False:
            font = QFont("Arial", 14)
            font.setItalic(True)
            self.compLabel5 = QgsComposerLabel(self.scene)
            self.compLabel5.setFont(font)
            self.compLabel5.setText("South China Sea")
            self.compLabel5.setBackgroundEnabled(False)
            self.compLabel5.setItemPosition(108, 86)
            self.compLabel5.adjustSizeToText()
            self.compLabel5.setItemRotation(-45)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel5)

            self.compLabel6 = QgsComposerLabel(self.scene)
            self.compLabel6.setFont(font)
            self.compLabel6.setText("Sulu Sea")
            self.compLabel6.setBackgroundEnabled(False)
            self.compLabel6.setItemPosition(236, 38)
            self.compLabel6.adjustSizeToText()
            self.compLabel6.setItemRotation(45)
            self.scene.addItem(self.compLabel6)

            font.setItalic(False)
            self.compLabel7 = QgsComposerLabel(self.scene)
            self.compLabel7.setFont(font)
            self.compLabel7.setBackgroundEnabled(False)
            self.compLabel7.setText("Celebes Sea")
            self.compLabel7.setItemPosition(242, 112)
            self.compLabel7.adjustSizeToText()
            self.compLabel7.setItemRotation(-45)
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel7)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel8 = QgsComposerLabel(self.scene)
            self.compLabel8.setFont(font)
            self.compLabel8.setBackgroundEnabled(False)
            self.compLabel8.setText("INDONESIA\n(Kalimantan)")
            self.compLabel8.setItemPosition(172, 148, 32, 16)
            #             self.compLabel8.setHAlign(Qt.AlignHCenter)
            #             self.compLabel8.setVAlign(Qt.AlignVCenter)
            #             self.compLabel8.setFrameEnabled(False)
            #             self.compLabel8.setItemPosition()
            #             self.compLabel8.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel8)

            self.compLabel9 = QgsComposerLabel(self.scene)
            self.compLabel9.setFont(font)
            self.compLabel9.setBackgroundEnabled(False)
            self.compLabel9.setText("BRUNEI")
            self.compLabel9.setItemPosition(136, 83)
            self.compLabel9.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel9)
            self.templeteCreateAction.setChecked(False)

        pass

    def actionMapRefresh_triggered(self):

        self.view.setCurrentTool(QgsComposerView.AddRectangle)

    def setSelectionTool(self):
        self.view.deleteSelectedItems()
        font = QFont("Arial", 14)
        newLabelItem = QgsComposerLabel(self.scene)
        newLabelItem.setText("QGIS")
        newLabelItem.setFont(font)

        newLabelItem.setItemPosition(self.scenePoint.x(), self.scenePoint.y())
        newLabelItem.adjustSizeToText()

        self.scene.addItem(newLabelItem)
        #         selectItemPoint = self.scene.composerItemAt(self.scenePoint)
        newLabelItem.setSelected(True)
        self.groupBox.setEnabled(True)
        self.selectedLabelItem = newLabelItem
        #         txt = self.selectedLabelItem.text()
        #         textDoc = QTextDocument(txt)
        self.labelText.setPlainText(self.selectedLabelItem.text())
        #         self.scene.setSelectedItem(self.newLabelItem)

        self.view.setCurrentTool(QgsComposerView.Select)
        #         self.selectedLabelItem = self.view.currentTool()
        self.textItemAction.setChecked(False)

    def selectedItemDisplay(self, item):

        if self.scene.plotStyle() != QgsComposition.Preview:
            self.scene.setPlotStyle(QgsComposition.Preview)
            self.mapItem.setPreviewMode(QgsComposerMap.Render)
            self.mapItem.updateCachedImage()
        item._class_ = QgsComposerLabel
        #         selectedItems = self.scene.selectedComposerItems(True)
        #         if isinstance(item, QgsComposerItem):
        #             self.selectedLabelItem = item
        #         if isinstance(item, QGraphicsRectItem):
        #             self.selectedLabelItem = item
        if isinstance(item, QgsComposerLabel):
            self.selectedLabelItem = item
            self.groupBox.setEnabled(True)
            self.labelText.setPlainText(self.selectedLabelItem.text())
            self.spinLabelRotation.setValue(self.selectedLabelItem.rotation())
        else:
            self.groupBox.setEnabled(False)
#         print "debug"
        itemName = self.view.currentTool()
        if itemName == 5:
            item.setText("label")
        pass

    def deleteItem(self):
        self.view.deleteSelectedItems()
class CheckBox(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("CheckBox" +
                           str(len(parent.findChildren(CheckBox))))

        self.hLayout = QHBoxLayout(self)
        self.hLayout.setObjectName("hLayout")
        self.hLayout.setSpacing(0)
        self.hLayout.setContentsMargins(0, 0, 0, 0)

        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)

        self.checkBox = QCheckBox(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        self.checkBox.setObjectName(self.objectName() + "_checkbox")
        sizePolicy.setHeightForWidth(
            self.checkBox.sizePolicy().hasHeightForWidth())
        self.checkBox.setSizePolicy(sizePolicy)
        self.hLayout.addWidget(self.checkBox)
        self.checkBox.setChecked(True)
        self.checkBox.clicked.connect(self.clicked)

    def clicked(self):
        self.emit(SIGNAL("Event_0"), self)

    def get_Caption(self):
        return self.checkBox.text()

    def set_Caption(self, captionStr):
        self.checkBox.setText(captionStr)

    Caption = property(get_Caption, set_Caption, None, None)

    def get_Enabled(self):
        return self.isEnabled()

    def set_Enabled(self, bool):
        self.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def get_Checked(self):
        return self.checkBox.isChecked()

    def set_Checked(self, bool):
        self.checkBox.setChecked(bool)

    Checked = property(get_Checked, set_Checked, None, None)

    def set_LabelWidth(self, width):
        self.checkBox.setMinimumSize(QSize(width, 0))
        self.checkBox.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)
Beispiel #57
0
class AffectiveTypeForm(QDialog):
    def __init__(self, sid, parent=None):
        super(AffectiveTypeForm, self).__init__(parent)
        self.sid = sid
        ko = 0
        layout1 = QGridLayout()
        try:
            details = self.pullDetails(self.sid)
            pagetitle = str(details['name']) + ' '
        except:
            details = []
            pagetitle = 'None'

        arr = self.pullClass(self.sid)
        print(arr)
        hold = {}
        for val in arr:
            grp = arr[val][2].split(':')
            self.num = val
            self.c = QCheckBox('cb' + str(val))
            self.c.setText(arr[val][0] + ' - ' + arr[val][1])
            self.c.setObjectName("chk" + str(val))

            if (arr[val][3] == 0):
                self.c.setChecked(True)
            else:
                self.c.setChecked(False)

            self.c.toggled.connect(
                lambda state, x=val, y=self.c: self.chkFunc(x, y))
            self.d = QPushButton()
            self.d.setObjectName("btnx" + str(val))
            self.d.setText(grp[0] + ' to ' + grp[1])
            self.d.setStyleSheet("background-color:" + grp[2] +
                                 "; color: white")
            #self.b = QPushButton()
            #self.b.setObjectName("btn"+str(val))
            #self.b.setText('Terms')
            self.b1 = QPushButton()
            self.b1.setObjectName("btn1" + str(val))
            self.b1.setText('Edit')
            hold["btn" + str(val)] = self.b1
            layout1.addWidget(self.c, ko, 0)
            layout1.addWidget(self.d, ko, 1)
            layout1.addWidget(self.b1, ko, 2)
            ko += 1

        for j in arr:
            self.h = j
            b = "btn" + str(j)
            self.connect(hold[b],
                         SIGNAL("clicked()"),
                         lambda gh=j: self.lunchEditForm(gh, self))

        groupBox1 = QGroupBox('Attitude/Behavior')
        groupBox1.setLayout(layout1)

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

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

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

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

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.lunchAddForm(self.sid, self))
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.setWindowTitle(pagetitle)

    def chkFunc(self, a, b):
        # shost is a QString object
        self.a = a
        self.b = b
        g = Db()

        if b.isChecked() == True:
            y = {'active': 1}
        else:
            y = {'active': 0}

        z = {'id': self.a}
        j = g.update('datas', y, z)

        return j

    def pullClass(self, a):
        self.a = a
        cn = Db()
        datas = cn.selectn('datas', '', '', {'subID': self.a})
        arr = {}

        try:
            for j in datas:
                arr[j['id']] = [
                    j['name'], j['abbrv'], j['description'], j['active']
                ]
        except:
            pass
        return arr

    def pullDetails(self, a):
        self.a = a
        cn = Db()
        datas = cn.selectn('datas', '', 1, {'id': self.a})

        return datas

    def lunchEditForm(self, a, b):
        b.close()
        self.a = a
        self.form = EditForm(self.a)
        self.form.show()

    def lunchAddForm(self, a, b):
        b.close()
        self.a = a
        self.form = AddForm(self.a)
        self.form.show()

    def lunchForm(self):
        self.form = super.AffectiveForm()
        self.form.show()

    def button_close(self, a):
        a.close()
        from frmaffective import AffectiveForm
        self.form = AffectiveForm()
        self.form.show()
Beispiel #58
0
class XFindWidget(QWidget):
    """ """
    __designer_icon__ = resources.find('img/search.png')

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

        # define custom properties
        self._textEdit = None
        self._webView = None
        self._lastCursor = QTextCursor()
        self._lastText = ''

        self._closeButton = QToolButton(self)
        self._closeButton.setIcon(QIcon(resources.find('img/close.png')))
        self._closeButton.setAutoRaise(True)
        self._closeButton.setToolTip('Hide the Find Field.')

        self._searchEdit = XLineEdit(self)
        self._searchEdit.setHint('search for...')

        self._previousButton = QToolButton(self)
        self._previousButton.setIcon(QIcon(resources.find('img/back.png')))
        self._previousButton.setAutoRaise(True)
        self._previousButton.setToolTip('Find Previous')

        self._nextButton = QToolButton(self)
        self._nextButton.setIcon(QIcon(resources.find('img/forward.png')))
        self._nextButton.setAutoRaise(True)
        self._nextButton.setToolTip('Find Next')

        self._caseSensitiveCheckbox = QCheckBox(self)
        self._caseSensitiveCheckbox.setText('Case Sensitive')

        self._wholeWordsCheckbox = QCheckBox(self)
        self._wholeWordsCheckbox.setText('Whole Words Only')

        self._regexCheckbox = QCheckBox(self)
        self._regexCheckbox.setText('Use Regex')

        self._findAction = QAction(self)
        self._findAction.setText('Find...')
        self._findAction.setIcon(QIcon(resources.find('img/search.png')))
        self._findAction.setToolTip('Find in Text')
        self._findAction.setShortcut(QKeySequence('Ctrl+F'))
        self._findAction.setShortcutContext(Qt.WidgetWithChildrenShortcut)

        # layout the widgets
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._closeButton)
        layout.addWidget(self._searchEdit)
        layout.addWidget(self._previousButton)
        layout.addWidget(self._nextButton)
        layout.addWidget(self._caseSensitiveCheckbox)
        layout.addWidget(self._wholeWordsCheckbox)
        layout.addWidget(self._regexCheckbox)

        self.setLayout(layout)

        # create connections
        self._findAction.triggered.connect(self.show)
        self._searchEdit.textChanged.connect(self.findNext)
        self._closeButton.clicked.connect(self.hide)
        self._previousButton.clicked.connect(self.findPrev)
        self._nextButton.clicked.connect(self.findNext)
        self._caseSensitiveCheckbox.clicked.connect(self.findNext)
        self._wholeWordsCheckbox.clicked.connect(self.findNext)
        self._searchEdit.returnPressed.connect(self.findNext)
        self._regexCheckbox.clicked.connect(self.findNext)

    def find(self, flags=0):
        """
        Looks throught the text document based on the current criteria.  The \
        inputed flags will be merged with the generated search flags.
        
        :param      flags | <QTextDocument.FindFlag>
        
        :return     <bool> | success
        """
        # check against the web and text views
        if (not (self._textEdit or self._webView)):
            fg = QColor('darkRed')
            bg = QColor('red').lighter(180)

            palette = self.palette()
            palette.setColor(palette.Text, fg)
            palette.setColor(palette.Base, bg)

            self._searchEdit.setPalette(palette)
            self._searchEdit.setToolTip('No Text Edit is linked.')

            return False

        if (self._caseSensitiveCheckbox.isChecked()):
            flags |= QTextDocument.FindCaseSensitively

        if (self._textEdit and self._wholeWordsCheckbox.isChecked()):
            flags |= QTextDocument.FindWholeWords

        terms = self._searchEdit.text()
        if (terms != self._lastText):
            self._lastCursor = QTextCursor()

        if (self._regexCheckbox.isChecked()):
            terms = QRegExp(terms)

        palette = self.palette()

        # search on a text edit
        if (self._textEdit):
            cursor = self._textEdit.document().find(
                terms, self._lastCursor, QTextDocument.FindFlags(flags))
            found = not cursor.isNull()
            self._lastCursor = cursor
            self._textEdit.setTextCursor(cursor)

        elif (QWebPage):
            flags = QWebPage.FindFlags(flags)
            flags |= QWebPage.FindWrapsAroundDocument

            found = self._webView.findText(terms, flags)

        self._lastText = self._searchEdit.text()

        if (not terms or found):
            fg = palette.color(palette.Text)
            bg = palette.color(palette.Base)
        else:
            fg = QColor('darkRed')
            bg = QColor('red').lighter(180)

        palette.setColor(palette.Text, fg)
        palette.setColor(palette.Base, bg)

        self._searchEdit.setPalette(palette)

        return found

    def findNext(self):
        """
        Looks for the search terms that come up next based on the criteria.
        
        :return     <bool> | success
        """
        return self.find()

    def findPrev(self):
        """
        Looks for the search terms that come up last based on the criteria.
        
        :return     <bool> | success
        """
        return self.find(QTextDocument.FindBackward)

    def setTextEdit(self, textEdit):
        """
        Sets the text edit that this find widget will use to search.
        
        :param      textEdit | <QTextEdit>
        """
        if (self._textEdit):
            self._textEdit.removeAction(self._findAction)

        self._textEdit = textEdit
        if (textEdit):
            textEdit.addAction(self._findAction)

    def setWebView(self, webView):
        """
        Sets the web view edit that this find widget will use to search.
        
        :param      webView | <QWebView>
        """
        if (self._webView):
            self._webView.removeAction(self._findAction)

        self._webView = webView
        if (webView):
            webView.addAction(self._findAction)

    def show(self):
        """
        Sets this widget visible and then makes the find field have focus.
        """
        super(XFindWidget, self).show()

        self._searchEdit.setFocus()

    def textEdit(self):
        """
        Returns the text edit linked with this find widget.
        
        :return     <QTextEdit>
        """
        return self._textEdit

    def webView(self):
        """
        Returns the text edit linked with this find widget.
        
        :return     <QWebView>
        """
        return self._webView
Beispiel #59
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()
class BaseSectionWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.resize(400,80)

        self.sectionNameEdit = QLineEdit(self)
        self.sectionNameEdit.setGeometry(QRect(0,5,110,30))
        self.sectionNameEdit.setPlaceholderText("Section name")
        self.sectionNameEdit.setToolTip("Name of new section")

        self.sizeEdit = QDoubleSpinBox(self)
        self.sizeEdit.setGeometry(QRect(115,5,65,30))
        self.sizeEdit.setMaximum(100.0)
        self.sizeEdit.setToolTip("Size of section in percent")

        self.colorLabel = ColorChooser(self)
        self.colorLabel.setGeometry(QRect(185,8,25,25))

        self.displayedNameCheckBox = QCheckBox(self)
        self.displayedNameCheckBox.setGeometry(215, 5, 185, 30)
        self.displayedNameCheckBox.setText("Change displayed name")
        self.displayedNameCheckBox.setStyleSheet("font-size:11px;")

        self.displayedNameEdit = QLineEdit(self)
        self.displayedNameEdit.setGeometry(QRect(235,5,120,30))
        self.displayedNameEdit.setPlaceholderText("Displayed name")
        self.displayedNameEdit.setToolTip("Displayed name of new section")
        self.displayedNameEdit.setVisible(False)

        self.removeButton = QPushButton(self)
        self.removeButton.setGeometry(QRect(385,5,35,30))
        self.removeButton.setToolTip("Remove section")
        pixmap = QPixmap("./removeIcon.png")
        buttonIcon = QIcon(pixmap)
        self.removeButton.setIcon(buttonIcon)
        self.removeButton.setIconSize(QSize(25,25))

        self.connect(self.displayedNameCheckBox, QtCore.SIGNAL("clicked()"), self.changeDisplayedName)
        self.connect(self.removeButton, QtCore.SIGNAL("clicked()"), QtCore.SIGNAL("remove()"))
        self.connect(self.sizeEdit, QtCore.SIGNAL("valueChanged(double)"), self.changeSizeValue)

    def changeSizeValue(self):
        self.emit(QtCore.SIGNAL("sizeValueChanged(QWidget*)"), self)

    def changeDisplayedName(self):
        if self.displayedNameCheckBox.isChecked():
            self.displayedNameEdit.setVisible(True)
            self.displayedNameCheckBox.setText("")
        else:
            self.displayedNameEdit.setVisible((False))
            self.displayedNameCheckBox.setText("Change displayed name")

    def getName(self):
        return self.sectionNameEdit.text()

    def setSize(self, size):
        self.sizeEdit.setValue(size)

    def getSize(self):
        return self.sizeEdit.value()

    def getSectionData(self):
        name = self.sectionNameEdit.text()
        size = self.sizeEdit.text()
        color = self.colorLabel.getSelectedColor()
        displayedNameFlag = self.displayedNameCheckBox.isChecked()
        displayedName = self.displayedNameEdit.text()
        return [name, size, color, displayedNameFlag, displayedName]