예제 #1
0
 def setAIR2(self, action):
     settings = QSettings(QSettings.UserScope, "astrastudio", "OnAirScreen")
     if action:
         self.Air2Seconds = 0
         self.AirLabel_2.setStyleSheet(
             "color: #000000; background-color: #FF0000")
         self.AirIcon_2.setStyleSheet(
             "color: #000000; background-color: #FF0000")
         self.AirLabel_2.setText(
             "Phone\n%d:%02d" %
             (self.Air2Seconds / 60, self.Air2Seconds % 60))
         self.statusAIR2 = True
         # AIR2 timer
         self.timerAIR2.start(1000)
     else:
         settings.beginGroup("LEDS")
         self.AirIcon_2.setStyleSheet(
             "color:" +
             settings.value('inactivetextcolor', '#555555').toString() +
             ";background-color:" +
             settings.value('inactivebgcolor', '#222222').toString())
         self.AirLabel_2.setStyleSheet(
             "color:" +
             settings.value('inactivetextcolor', '#555555').toString() +
             ";background-color:" +
             settings.value('inactivebgcolor', '#222222').toString())
         settings.endGroup()
         self.statusAIR2 = False
         self.timerAIR2.stop()
예제 #2
0
def preferred():
    """Return the quotes desired by the Frescobaldi user.
    
    Always returns a quote set.
    Only this function depends on Qt and Frescobaldi.
    
    """
    
    from PyQt4.QtCore import QSettings
    import po.setup

    s = QSettings()
    s.beginGroup("typographical_quotes")
    language = s.value("language", "current", type(""))
    
    default = _quotes["C"]
    if language == "current":
        language = po.setup.current()
    elif language == "custom":
        return QuoteSet(
            primary = Quotes(
                left = s.value("primary_left", default.primary.left, type("")),
                right = s.value("primary_right", default.primary.right, type("")),
            ),
            secondary = Quotes(
                left = s.value("secondary_left", default.secondary.left, type("")),
                right = s.value("secondary_right", default.secondary.right, type("")),
            )
        )
    return quotes(language) or default
예제 #3
0
 def _run_git_command(self, cmd, args = []): 
     """
     run a git command and return its output
     as a string list.
     Raise an exception if it returns an error.
     - cmd is the git command (without 'git')
     - args is a string or a list of strings
     """
     from PyQt4.QtCore import QSettings
     s = QSettings()
     s.beginGroup("helper_applications")
     git_cmd = s.value("git", "git", type(""))
     git_cmd = git_cmd if git_cmd else "git"
     cmd = [git_cmd, cmd]
     if isinstance(args, str) or isinstance(args, type("")):
         cmd.append(args)
     else:
         cmd.extend(args)
     pr = subprocess.Popen(' '.join(cmd), cwd = self.rootDir, 
                           shell = True, 
                           stdout = subprocess.PIPE, 
                           stderr = subprocess.PIPE)
     (out, error) = pr.communicate()
     if error:
         raise GitError(str(error))
     result = str(out).split('\n')
     if result[-1] == '':
         result.pop()
     return result
    def onBrowseConnection(self):
        s = QSettings()
        base = "/PostgreSQL/connections"
        s.beginGroup("/PostgreSQL/connections")
        children = s.childGroups()
        connections = {}
        map = {
            "dbname": "database",
            "host": "host",
            "port": "port",
            "service": "service",
            "password": "******",
            "user": "******"
        }
        for g in children:
            s.beginGroup(g)
            cstring = ""
            for k, v in map.items():
                if s.value(v):
                    cstring += k + "=" + s.value(v) + " "
            connections[g] = cstring
            s.endGroup()

        menu = QMenu(self)
        for k in sorted(connections.keys()):
            menu.addAction(k)

        def onMenu(action):
            self.dbConnectionText.setText(connections[action.text()])
            self.reloadBtn.click()

        menu.triggered.connect(onMenu)
        menu.exec_(self.dbConnectionBtn.mapToGlobal(QPoint(0, 0)))
예제 #5
0
def import_setting(file_path, qsettings=None):
    """Import InaSAFE's setting from a file.

    :param file_path: The file to read the imported setting.
    :type file_path: basestring

    :param qsettings: A custom QSettings to use. If it's not defined, it will
        use the default one.
    :type qsettings: qgis.PyQt.QtCore.QSettings

    :returns: A dictionary of the imported settings.
    :rtype: dict
    """
    with open(file_path, 'r') as f:
        inasafe_settings = json.load(f)

    if not qsettings:
        qsettings = QSettings()

    # Clear the previous setting
    qsettings.beginGroup('inasafe')
    qsettings.remove('')
    qsettings.endGroup()

    for key, value in inasafe_settings.items():
        set_setting(key, value, qsettings=qsettings)

    return inasafe_settings
 def getQGISDbs(self):
     """Return all PostGIS connection settings stored in QGIS
     :return: connection dict() with name and other settings
     """
     con_settings = []
     settings = QSettings()
     settings.beginGroup('/PostgreSQL/connections')
     for item in settings.childGroups():
         con = dict()
         con['name'] = unicode(item)
         con['host'] = unicode(settings.value(u'%s/host' % unicode(item)))
         con['port'] = unicode(settings.value(u'%s/port' % unicode(item)))
         con['database'] = unicode(
             settings.value(u'%s/database' % unicode(item)))
         con['username'] = unicode(
             settings.value(u'%s/username' % unicode(item)))
         con['password'] = unicode(
             settings.value(u'%s/password' % unicode(item)))
         con_settings.append(con)
     settings.endGroup()
     dbs = {}
     if len(con_settings) > 0:
         for conn in con_settings:
             dbs[conn['name']] = conn
     return dbs
예제 #7
0
 def checkNTPOffset(self):
     settings = QSettings(QSettings.UserScope, "astrastudio", "OnAirScreen")
     settings.beginGroup("NTP")
     ntpcheck = settings.value("ntpcheck", True).toBool()
     ntpserver = str(settings.value("ntpcheckserver", "pool.ntp.org").toString())
     settings.endGroup()
     if not ntpcheck:
         return
     self.timerNTP.stop()
     max_deviation = 0.3
     c = ntplib.NTPClient()
     try:
         response = c.request(ntpserver)
         if response.offset > max_deviation or response.offset < -max_deviation:
             print "offset too big: %f while checking %s" % (response.offset, ntpserver)
             self.showWarning("Clock not NTP synchronized: offset too big")
             self.ntpHadWarning = True
         else:
             if self.ntpHadWarning == True:
                 self.ntpHadWarning = False
                 self.hideWarning()
     except socket.timeout:
         print "timeout checking NTP %s" % ntpserver
         self.showWarning("Clock not NTP synchronized")
         self.ntpHadWarning = True
     except socket.gaierror:
         print "error checking NTP %s" % ntpserver
         self.showWarning("Clock not NTP synchronized")
         self.ntpHadWarning = True
     except:
         print "general error checking NTP %s" % ntpserver
         self.showWarning("Clock not NTP synchronized")
         self.ntpHadWarning = True
     self.timerNTP.start(60000)
예제 #8
0
def addBoundlessRepository():
    """Add Boundless plugin repository to list of the available
       plugin repositories if it is not presented here
    """
    settings = QSettings('Boundless', 'BoundlessConnect')
    repoUrl = settings.value('repoUrl', '', unicode)

    if repoUrl == '':
        setRepositoryUrl()

    if isRepositoryInDirectory():
        return

    settings = QSettings()
    settings.beginGroup(reposGroup)
    hasBoundlessRepository = False
    for repo in settings.childGroups():
        url = settings.value(repo + '/url', '', unicode)
        if url == repoUrl:
            hasBoundlessRepository = True
    # Boundless repository not found, so we add it to the list
    if not hasBoundlessRepository:
        settings.setValue(boundlessRepoName + '/url', repoUrl)
        settings.setValue(boundlessRepoName + '/authcfg', '')
    settings.endGroup()
예제 #9
0
 def setAIR2(self, action):
     settings = QSettings(QSettings.UserScope, "astrastudio", "OnAirScreen")
     if action:
         self.Air2Seconds = 0
         self.AirLabel_2.setStyleSheet("color: #000000; background-color: #FF0000")
         self.AirIcon_2.setStyleSheet("color: #000000; background-color: #FF0000")
         self.AirLabel_2.setText("Phone\n%d:%02d" % (self.Air2Seconds / 60, self.Air2Seconds % 60))
         self.statusAIR2 = True
         # AIR2 timer
         self.timerAIR2.start(1000)
     else:
         settings.beginGroup("LEDS")
         self.AirIcon_2.setStyleSheet(
             "color:"
             + settings.value("inactivetextcolor", "#555555").toString()
             + ";background-color:"
             + settings.value("inactivebgcolor", "#222222").toString()
         )
         self.AirLabel_2.setStyleSheet(
             "color:"
             + settings.value("inactivetextcolor", "#555555").toString()
             + ";background-color:"
             + settings.value("inactivebgcolor", "#222222").toString()
         )
         settings.endGroup()
         self.statusAIR2 = False
         self.timerAIR2.stop()
예제 #10
0
 def setAIR4(self, action):
     settings = QSettings(QSettings.UserScope, "astrastudio", "OnAirScreen")
     if action:
         self.AirLabel_4.setStyleSheet("color: #000000; background-color: #FF0000")
         self.AirIcon_4.setStyleSheet("color: #000000; background-color: #FF0000")
         self.AirLabel_4.setText("Stream\n%d:%02d" % (self.Air4Seconds / 60, self.Air4Seconds % 60))
         self.statusAIR4 = True
         # substract initial second on countdown with display update
         if self.streamTimerMode == 1 and self.Air4Seconds > 1:
             self.updateAIR4Seconds()
         # AIR4 timer
         self.timerAIR4.start(1000)
     else:
         settings.beginGroup("LEDS")
         self.AirIcon_4.setStyleSheet(
             "color:"
             + settings.value("inactivetextcolor", "#555555").toString()
             + ";background-color:"
             + settings.value("inactivebgcolor", "#222222").toString()
         )
         self.AirLabel_4.setStyleSheet(
             "color:"
             + settings.value("inactivetextcolor", "#555555").toString()
             + ";background-color:"
             + settings.value("inactivebgcolor", "#222222").toString()
         )
         settings.endGroup()
         self.statusAIR4 = False
         self.timerAIR4.stop()
예제 #11
0
 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())
예제 #12
0
 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))
예제 #13
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name)

        from qgis.core import QgsDataSourceURI

        uri = QgsDataSourceURI()

        settingsList = ["service", "host", "port", "database", "username", "password"]
        service, host, port, database, username, password = map(lambda x: settings.value(x, "", type=str), settingsList)

        useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
        sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

        settings.endGroup()

        if service:
            uri.setConnection(service, database, username, password, sslmode)
        else:
            uri.setConnection(host, port, database, username, password, sslmode)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        try:
            return self.connectToUri(uri)
        except ConnectionError, e:
            return False
예제 #14
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("documentstructure")
     if self.patternList.value() != documentstructure.default_outline_patterns:
         s.setValue("outline_patterns", self.patternList.value())
     else:
         s.remove("outline_patterns")
예제 #15
0
    def on_removeMissingPushButton_clicked(self):
        '''
        Remove missing databases from QSetttings
        '''
        servers = self.serverWidget.getServers()
        settings = QSettings()
        settings.beginGroup('PostgreSQL/connections')
        candidates = settings.childGroups()
        settings.endGroup()
        removedConn = []
        dbList = []
        try:
            dbList = self.serverWidget.abstractDb.getDbsFromServer()
        except Exception as e:
            QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))

        for candidate in candidates:
            candidateSettings = QSettings()
            candidateSettings.beginGroup('PostgreSQL/connections/' + candidate)
            candidateDb = candidateSettings.value('database')
            if candidateDb not in dbList:
                self.removeConnections(candidate, removedConn)
        if len(removedConn) > 0:
            msg = self.tr(
                '\nThe following databases connections were removed successfully:\n'
            ) + ', '.join(removedConn)
        else:
            msg = self.tr('No connections were removed.')
        QMessageBox.warning(self, self.tr("Warning!"), msg)
예제 #16
0
    def _initialize(self):
        """
        called in __init__ of msdialogcontroller
        
        """
        settings=QSettings('INRA/INSA', '-'.join([qApp.instance().APPLICATION_NAME_STR,
                                                  qApp.instance().VERSION_STR]))
        
        if isinstance(self.view, MSMatchedFilteredDialog):
            settings.beginGroup("matchedFilteredDialog")
            self.view.lineEdit_2.setText(settings.value("lineEdit_2", "30").toString())
            self.view.lineEdit_4.setText(settings.value("lineEdit_4", "2").toString())       
            self.view.lineEdit_5.setText(settings.value("lineEdit_5", "0.5").toString())
            self.view.lineEdit_6.setText(settings.value("lineEdit_6", "3").toString())
            self.view.lineEdit_3.setText(settings.value("lineEdit_3", "0.1").toString())
            self.view.spinBox.setValue(settings.value("spinBox", 5).toInt()[0])
            settings.endGroup()

        elif isinstance(self.view, MSCentWaveDialog):
            self.view.lineEdit_2.setText("300-3200")
            self.view.lineEdit_4.setText("10-22")       
            self.view.lineEdit_5.setText("1000")
            self.view.lineEdit_6.setText("1.2")
            self.view.spinBox.setValue(10)
            self.view.spinBox_2.setValue(10)
            self.view.checkBox.setChecked(True)
            
        self.view.lineEdit_7.setText("0.8")
        self.view.lineEdit_8.setText("5")
        self.view.lineEdit_9.setText("20")
        self.view.lineEdit_10.setText("0.002")
        self.view.obiwarp.setChecked(True)
        self.view.gb_2.setChecked(False)
        self.view.gb_3.setChecked(False)
예제 #17
0
 def __getOption(self, option):
     if option == 'knownHosts':
         settings = QSettings()
         hosts = {}
         settings.beginGroup('Servers')
         knownHosts = settings.allKeys()
         if not knownHosts:
             return self.defaults[option]
         for name in knownHosts:
             host = settings.value(name)
             hosts[unicode(name)] = [
                 unicode(col.toString()) for col in host.toList()
             ]
         settings.endGroup()
         return hosts
     valueType = type(self.defaults[option])
     QtType = self.types[valueType]
     value = QtType(QSettings().value(option, self.defaults[option]))
     if not value and value == None:
         return None
     if option == 'tabOrder':
         return [unicode(x.toString()) for x in value]
     if option == 'server':
         return [unicode(col.toString()) for col in value]
     if valueType == list:
         return [int(x.toInt()[0]) for x in value]
     if valueType == int:
         return int(value[0])
     return valueType(value)
예제 #18
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("documentation")
     langs = ['default', 'C'] + lilydoc.translations
     s.setValue("language", langs[self.languages.currentIndex()])
     s.setValue("fontfamily", self.fontChooser.currentFont().family())
     s.setValue("fontsize", self.fontSize.value())
예제 #19
0
    def load_directories(self):
        """Load directories of repository registered in settings."""
        self._directories = {}
        settings = QSettings()
        settings.beginGroup(repo_settings_group())

        # Write online directory first to QSettings if needed
        for online_dir_name in self._online_directories:
            repo_present = False
            for repo_name in settings.childGroups():
                url = settings.value(repo_name + '/url', '', type=unicode)
                if url == self._online_directories[online_dir_name]:
                    repo_present = True
                    break
            if not repo_present:
                self.add_directory(online_dir_name,
                                   self._online_directories[online_dir_name])

        for repo_name in settings.childGroups():
            self._directories[repo_name] = {}
            url = settings.value(repo_name + '/url', '', type=unicode)
            self._directories[repo_name]['url'] = url
            auth_cfg = settings.value(repo_name + '/auth_cfg',
                                      '',
                                      type=unicode).strip()
            self._directories[repo_name]['auth_cfg'] = auth_cfg
        settings.endGroup()
예제 #20
0
 def save(self):
     qsettings = QSettings()
     qsettings.beginGroup('preferences')
     qsettings.beginGroup('editor')
     qsettings.setValue('indent', self._spin.value())
     settings.INDENT = self._spin.value()
     qsettings.setValue('marginLine', self._spinMargin.value())
     settings.MARGIN_LINE = self._spinMargin.value()
     pep8mod.MAX_LINE_LENGTH = settings.MARGIN_LINE - 1
     qsettings.setValue('showMarginLine', self._checkShowMargin.isChecked())
     settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked()
     qsettings.setValue('errors', self._checkErrors.isChecked())
     settings.FIND_ERRORS = self._checkErrors.isChecked()
     qsettings.setValue('errorsInLine', self._showErrorsOnLine.isChecked())
     settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked()
     qsettings.setValue('checkStyle', self._checkStyle.isChecked())
     settings.CHECK_STYLE = self._checkStyle.isChecked()
     qsettings.setValue('checkStyleInline',
         self._checkStyleOnLine.isChecked())
     settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked()
     qsettings.setValue('centerOnScroll',
         self._checkCenterScroll.isChecked())
     settings.CENTER_ON_SCROLL = self._checkCenterScroll.isChecked()
     qsettings.setValue('removeTrailingSpaces',
         self._checkTrailing.isChecked())
     settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked()
     qsettings.setValue('showTabsAndSpaces',
         self._checkShowSpaces.isChecked())
     settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked()
     qsettings.endGroup()
     qsettings.endGroup()
     actions.Actions().reset_editor_flags()
예제 #21
0
    def fetch_online_directories(self):
        """Fetch online directory of repositories."""
        downloader = NetworkManager(self.DIRECTORY_URL)
        status, _ = downloader.fetch()
        if status:
            directory_file = QTemporaryFile()
            if directory_file.open():
                directory_file.write(downloader.content)
                directory_file.close()

            with open(directory_file.fileName()) as csv_file:
                reader = csv.DictReader(csv_file, fieldnames=('name', 'url'))
                for row in reader:
                    self._online_directories[row['name']] = row['url'].strip()
            # Save it to cache
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            settings.setValue('online_directories', self._online_directories)
            settings.endGroup()
        else:
            # Just use cache from previous use
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            self._online_directories = settings.value('online_directories', {})
            settings.endGroup()
예제 #22
0
 def _run_git_command(self, cmd, args = []): 
     """
     run a git command and return its output
     as a string list.
     Raise an exception if it returns an error.
     - cmd is the git command (without 'git')
     - args is a string or a list of strings
     """
     from PyQt4.QtCore import QSettings
     s = QSettings()
     s.beginGroup("helper_applications")
     git_cmd = s.value("git", "git", type(""))
     git_cmd = git_cmd if git_cmd else "git"
     cmd = [git_cmd, cmd]
     cmd.extend(args)
     pr = subprocess.Popen(cmd, cwd = self.rootDir,
                           stdout = subprocess.PIPE,
                           stderr = subprocess.PIPE,
                           universal_newlines = True)
     (out, error) = pr.communicate()
     if error:
         raise GitError(error)
     result = out.split('\n')
     if result[-1] == '':
         result.pop()
     return result
예제 #23
0
    def selectOutput(self):
        if isinstance(self.output, OutputDirectory):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            actionSaveToTempFile = QAction(
                self.tr('Save to a temporary file'), self.btnSelect)
            actionSaveToTempFile.triggered.connect(self.saveToTemporaryFile)
            popupMenu.addAction(actionSaveToTempFile)

            actionSaveToFile = QAction(
                self.tr('Save to file...'), self.btnSelect)
            actionSaveToFile.triggered.connect(self.selectFile)
            popupMenu.addAction(actionSaveToFile)

            if isinstance(self.output, OutputVector) \
                    and self.alg.provider.supportsNonFileBasedOutput():
                actionSaveToMemory = QAction(
                    self.tr('Save to memory layer'), self.btnSelect)
                actionSaveToMemory.triggered.connect(self.saveToMemory)
                popupMenu.addAction(actionSaveToMemory)
                actionSaveToPostGIS = QAction(
                    self.tr('Save to PostGIS table...'), self.btnSelect)
                actionSaveToPostGIS.triggered.connect(self.saveToPostGIS)
                settings = QSettings()
                settings.beginGroup('/PostgreSQL/connections/')
                names = settings.childGroups()
                settings.endGroup()
                actionSaveToPostGIS.setEnabled(bool(names))
                popupMenu.addAction(actionSaveToPostGIS)

            popupMenu.exec_(QCursor.pos())
예제 #24
0
class PluginListWidgetModel(QStandardItemModel):
    """This model will create its own items, from the ``QSettings``
    where plugins is set to *load*.
    """
    def __init__(self, parent = None):
        QStandardItemModel.__init__(self, parent)
        self._settings = QSettings()
        self._settings.beginGroup("plugins")
        self.pluginloader = PluginLoader()
        self.pluginloader.pluginsToLoad = self.__checkToLoad()

        for plugin in self.pluginloader.plugins:
            if plugin.load == True:
                item = QStandardItem(plugin.pluginUserString)
                if plugin.icon:
                    item.setIcon(plugin.icon)
                font = item.font()
                font.setPointSize(font.pointSize() + 4)
                item.setFont(font)
                item.setEditable(False)
                item.plugin = plugin
                self.appendRow(item)

    def __checkToLoad(self):
        pluginlist = []

        # When beginGroup is set to plugins, the childgroups will be
        # each of the plugins.
        for plugin in self._settings.childGroups():
            valueString = str(plugin) + "/load"
            value = self._settings.value(valueString, "True").toString()
            if value == "True":
                pluginlist.append(str(plugin))

        return pluginlist
예제 #25
0
class QNewScoreDialog(QDialog, Ui_newScoreDialog):
    '''
    classdocs
    '''
    def __init__(self, parent = None,
                 counter = None, registry = None):
        '''
        Constructor
        '''
        super(QNewScoreDialog, self).__init__(parent)
        self.setupUi(self)
        self.measureTabs.setup(counter, registry,
                               Data.MeasureCount, QComplexCountDialog)
        for name in DefaultKits.DEFAULT_KIT_NAMES:
            self.kitCombobox.addItem(name, userData = QVariant(False))
        self._settings = QSettings()
        self._settings.beginGroup("UserDefaultKits")
        for kitName in self._settings.allKeys():
            self.kitCombobox.addItem(kitName, userData = QVariant(True))

    def getValues(self):
        mc = self.measureTabs.getCounter()
        kitName = unicode(self.kitCombobox.currentText())
        kitIndex = self.kitCombobox.currentIndex()
        isUserKit = self.kitCombobox.itemData(kitIndex).toBool()
        if isUserKit:
            kitString = str(self._settings.value(kitName).toString())
            handle = StringIO(kitString)
            dbfile = fileUtils.dbFileIterator(handle)
            kit = DrumKit.DrumKit()
            kit.read(dbfile)
        else:
            kit = DrumKit.getNamedDefaultKit(kitName)
        return (self.numMeasuresSpinBox.value(), mc, kit)
예제 #26
0
class SettingsINI(object):
	""" Settings INI file implemented for Wifi-Pumpkin"""
	def __init__(self,filename):
		if path.isfile(filename) and filename.endswith('.ini'):
			self.psettings = QSettings(filename,QSettings.IniFormat)

	def get_setting(self,name_group,key,format=str):
		""" Get the value for setting key """
		self.psettings.beginGroup(name_group)
		value = self.psettings.value(key,type=format)
		self.closeGroup()
		return value

	def set_setting(self,name_group,key, value):
		""" Sets the value of setting key to value """
		self.psettings.beginGroup(name_group)
		self.psettings.setValue(key, value)
		self.closeGroup()

	def get_all_childname(self,key):
		""" get list all childskeys on file config.ini """
		return [x.split('/')[1] for x in self.get_all_keys() if x.split('/')[0] == key]

	def get_all_keys(self):
		""" get all keys on settings"""
		return str(self.psettings.allKeys().join("<join>")).split("<join>")

	def closeGroup(self):
		""" close group settings"""
		self.psettings.endGroup()
예제 #27
0
    def exportColoredHtml(self):
        doc = self.currentDocument()
        name, ext = os.path.splitext(os.path.basename(doc.url().path()))
        if name:
            if ext.lower() == ".html":
                name += "_html"
            name += ".html"
        dir = os.path.dirname(doc.url().toLocalFile())
        if dir:
            name = os.path.join(dir, name)
        filename = QFileDialog.getSaveFileName(self, app.caption(_("Export as HTML")),
            name, "{0} (*.html)".format("HTML Files"))
        if not filename:
            return #cancelled

        s = QSettings()
        s.beginGroup("source_export")
        number_lines = s.value("number_lines", False, bool)
        inline_style = s.value("inline_export", False, bool)
        wrap_tag = s.value("wrap_tag", "pre", str)
        wrap_attrib = s.value("wrap_attrib", "id", str)
        wrap_attrib_name = s.value("wrap_attrib_name", "document", str)
        import highlight2html
        html = highlight2html.html_document(doc, inline=inline_style, number_lines=number_lines,
            wrap_tag=wrap_tag, wrap_attrib=wrap_attrib, wrap_attrib_name=wrap_attrib_name)
        try:
            with open(filename, "wb") as f:
                f.write(html.encode('utf-8'))
        except IOError as e:
            msg = _("{message}\n\n{strerror} ({errno})").format(
                message = _("Could not write to: {url}").format(url=filename),
                strerror = e.strerror,
                errno = e.errno)
            QMessageBox.critical(self, app.caption(_("Error")), msg)
예제 #28
0
 def setAIR4(self, action):
     settings = QSettings(QSettings.UserScope, "astrastudio", "OnAirScreen")
     if action:
         self.AirLabel_4.setStyleSheet(
             "color: #000000; background-color: #FF0000")
         self.AirIcon_4.setStyleSheet(
             "color: #000000; background-color: #FF0000")
         self.AirLabel_4.setText(
             "Stream\n%d:%02d" %
             (self.Air4Seconds / 60, self.Air4Seconds % 60))
         self.statusAIR4 = True
         # substract initial second on countdown with display update
         if self.streamTimerMode == 1 and self.Air4Seconds > 1:
             self.updateAIR4Seconds()
         # AIR4 timer
         self.timerAIR4.start(1000)
     else:
         settings.beginGroup("LEDS")
         self.AirIcon_4.setStyleSheet(
             "color:" +
             settings.value('inactivetextcolor', '#555555').toString() +
             ";background-color:" +
             settings.value('inactivebgcolor', '#222222').toString())
         self.AirLabel_4.setStyleSheet(
             "color:" +
             settings.value('inactivetextcolor', '#555555').toString() +
             ";background-color:" +
             settings.value('inactivebgcolor', '#222222').toString())
         settings.endGroup()
         self.statusAIR4 = False
         self.timerAIR4.stop()
    def retrieveAllStoredServerInfo(self):
        """
        Retrieves a list of ThreddsServerInfo objects stored in the
        underlying settings object for this application.

        Uses the Group definition "self.ThreddsServerGroup" to know
        under which 'namespace' are these elements stored. This allows
        us to store other configuration settings under other 'namespaces'
        using the same QSettings object.

        :returns A list of objects which contain information about
                 the thredds servers previously stored in the settings
                 object.
        :rtype   [ThreddsServerInfoObject]
        """
        serverList = []
        settings = QSettings()
        settings.beginGroup(self.ThreddsServerGroup)
        for element in settings.childKeys():
            srv = settings.value(element, None)
            if srv is not None:
                serverList.append(srv);

        settings.endGroup()
        return serverList
예제 #30
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup('scorewiz/instrumentnames')
     s.setValue('enable', self.isChecked())
     s.setValue('first', ('long', 'short')[self.firstSystem.currentIndex()])
     s.setValue('other', ('long', 'short', 'none')[self.otherSystems.currentIndex()])
     s.setValue('language', self._langs[self.language.currentIndex()])
예제 #31
0
    def __init__(self, parent, tablename):
        super(PostgisTableSelector, self).__init__(parent)
        self.connection = None
        self.table = None
        self.schema = None
        self.setupUi(self)
        settings = QSettings()
        settings.beginGroup('/PostgreSQL/connections/')
        names = settings.childGroups()
        settings.endGroup()
        for n in names:
            item = ConnectionItem(n)
            self.treeConnections.addTopLevelItem(item)

        def itemExpanded(item):
            try:
                item.populateSchemas()
            except:
                pass

        self.treeConnections.itemExpanded.connect(itemExpanded)

        self.textTableName.setText(tablename)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
    def delete_repository(self):
        """Delete a repository in the tree widget."""
        selected_item = self.tree_repositories.currentItem()
        if selected_item:
            repo_name = selected_item.text(0)

        if not repo_name:
            return
        # Check if it's the official repository
        settings = QSettings()
        settings.beginGroup(repo_settings_group())
        if settings.value(repo_name +
                          '/url') == self.repository_manager.OFFICIAL_REPO[1]:
            self.message_bar.pushMessage(
                self.tr('You can not remove the official repository!'),
                QgsMessageBar.WARNING, 5)
            return

        warning = self.tr('Are you sure you want to remove the following '
                          'repository?') + '\n' + repo_name
        if QMessageBox.warning(self, self.tr("QGIS Symbology Sharing"),
                               warning, QMessageBox.Yes,
                               QMessageBox.No) == QMessageBox.No:
            return

        settings.remove(repo_name)

        # Refresh tree repository
        self.refresh_tree_repositories()
        self.set_enabled_edit_delete_button(False)
예제 #33
0
class QNewScoreDialog(QDialog, Ui_newScoreDialog):
    '''
    classdocs
    '''
    def __init__(self, parent=None, counter=None, registry=None):
        '''
        Constructor
        '''
        super(QNewScoreDialog, self).__init__(parent)
        self.setupUi(self)
        self.measureTabs.setup(counter, registry, Data.MeasureCount,
                               QComplexCountDialog)
        for name in DefaultKits.DEFAULT_KIT_NAMES:
            self.kitCombobox.addItem(name, userData=QVariant(False))
        self._settings = QSettings()
        self._settings.beginGroup("UserDefaultKits")
        for kitName in self._settings.allKeys():
            self.kitCombobox.addItem(kitName, userData=QVariant(True))

    def getValues(self):
        mc = self.measureTabs.getCounter()
        kitName = unicode(self.kitCombobox.currentText())
        kitIndex = self.kitCombobox.currentIndex()
        isUserKit = self.kitCombobox.itemData(kitIndex).toBool()
        if isUserKit:
            kitString = str(self._settings.value(kitName).toString())
            handle = StringIO(kitString)
            dbfile = fileUtils.dbFileIterator(handle)
            kit = DrumKit.DrumKit()
            kit.read(dbfile)
        else:
            kit = DrumKit.getNamedDefaultKit(kitName)
        return (self.numMeasuresSpinBox.value(), mc, kit)
예제 #34
0
    def load(self):
        """ populate the mRepositories dict"""
        self.mRepositories = {}
        settings = QSettings()
        settings.beginGroup(reposGroup)
        # first, update repositories in QSettings if needed
        officialRepoPresent = False
        for key in settings.childGroups():
            url = settings.value(key + "/url", "", type=unicode)
            if url == officialRepo[1]:
                officialRepoPresent = True
            if url == officialRepo[2]:
                settings.setValue(key + "/url",
                                  officialRepo[1])  # correct a depreciated url
                officialRepoPresent = True
        if not officialRepoPresent:
            settings.setValue(officialRepo[0] + "/url", officialRepo[1])

        for key in settings.childGroups():
            self.mRepositories[key] = {}
            self.mRepositories[key]["url"] = settings.value(key + "/url",
                                                            "",
                                                            type=unicode)
            self.mRepositories[key]["enabled"] = settings.value(key +
                                                                "/enabled",
                                                                True,
                                                                type=bool)
            self.mRepositories[key]["valid"] = settings.value(key + "/valid",
                                                              True,
                                                              type=bool)
            self.mRepositories[key]["Relay"] = Relay(key)
            self.mRepositories[key]["xmlData"] = None
            self.mRepositories[key]["state"] = 0
            self.mRepositories[key]["error"] = ""
        settings.endGroup()
예제 #35
0
    def _sslError(self, reply, errors):
        # reply.ignoreSslErrors()

        settings = QSettings()
        settings.beginGroup('ssl')
        cert = errors[0].certificate()
        digest = six.text_type(cert.digest().toHex())

        approved = settings.value(digest, False).toBool()

        errorString = '<p>Please, accept the certificate for <b>{}</b></p>'.format(
            cert.subjectInfo(QSslCertificate.CommonName))

        # for err in errors:
        #     errorString += '<li>' + err.errorString() + '</li>'

        # errorString += '</ul>'

        if approved or QMessageBox.warning(
                self._parentWindow, 'SSL Warning', errorString,
                QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes:
            settings.setValue(digest, True)
            reply.ignoreSslErrors()

        settings.endGroup()
예제 #36
0
 def writeSettings(self):
     s = QSettings()
     s.beginGroup('copy_image')
     s.setValue("dpi", self.dpiCombo.currentText())
     s.setValue("papercolor", self.colorButton.color())
     s.setValue("autocrop", self.crop.isChecked())
     s.setValue("antialias", self.antialias.isChecked())
예제 #37
0
def defaultJob(document, preview):
    """Returns a default job for the document."""
    filename, mode, includepath = documentinfo.info(document).jobinfo(True)
    includepath.extend(documentinfo.info(document).includepath())
    i = info(document)
    j = job.Job()
    
    command = [i.command]
    s = QSettings()
    s.beginGroup("lilypond_settings")
    if s.value("delete_intermediate_files", True) not in (False, "false"):
        command.append('-ddelete-intermediate-files')
    else:
        command.append('-dno-delete-intermediate-files')
    command.append('-dpoint-and-click' if preview else '-dno-point-and-click')
    command.append('--pdf')
    command.extend('-I' + path for path in includepath)
    j.directory = os.path.dirname(filename)
    command.append(filename)
    j.command = command
    if s.value("no_translation", False) in (True, "true"):
        j.environment['LANG'] = 'C'
    j.setTitle("{0} {1} [{2}]".format(
        os.path.basename(i.command), i.versionString(), document.documentName()))
    return j
    def delete_repository(self):
        """Delete a repository in the tree widget."""
        selected_item = self.tree_repositories.currentItem()
        if selected_item:
            repo_name = selected_item.text(0)

        if not repo_name:
            return
        # Check if it's the official repository
        settings = QSettings()
        settings.beginGroup(repo_settings_group())
        if settings.value(repo_name + '/url') == self.repository_manager.OFFICIAL_REPO[1]:
            self.message_bar.pushMessage(
                self.tr(
                    'You can not remove the official repository!'),
                QgsMessageBar.WARNING, 5)
            return

        warning = self.tr('Are you sure you want to remove the following '
                          'repository?') + '\n' + repo_name
        if QMessageBox.warning(
                self,
                self.tr("QGIS Symbology Sharing"),
                warning,
                QMessageBox.Yes,
                QMessageBox.No) == QMessageBox.No:
            return

        settings.remove(repo_name)

        # Refresh tree repository
        self.refresh_tree_repositories()
        self.set_enabled_edit_delete_button(False)
예제 #39
0
 def remove(self):
     settings = QSettings()
     settings.beginGroup(
         u"/%s/%s" % (self.connectionSettingsKey(), self.connectionName()))
     settings.remove("")
     self.emit(SIGNAL('deleted'))
     return True
예제 #40
0
 def writeSettings(self):
     s = QSettings()
     s.beginGroup('copy_image')
     s.setValue("dpi", self.dpiCombo.currentText())
     s.setValue("papercolor", self.colorButton.color())
     s.setValue("autocrop", self.crop.isChecked())
     s.setValue("antialias", self.antialias.isChecked())
예제 #41
0
    def retrieveAllStoredServerInfo(self):
        """
        Retrieves a list of ThreddsServerInfo objects stored in the
        underlying settings object for this application.

        Uses the Group definition "self.ThreddsServerGroup" to know
        under which 'namespace' are these elements stored. This allows
        us to store other configuration settings under other 'namespaces'
        using the same QSettings object.

        :returns A list of objects which contain information about
                 the thredds servers previously stored in the settings
                 object.
        :rtype   [ThreddsServerInfoObject]
        """
        serverList = []
        settings = QSettings()
        settings.beginGroup(self.ThreddsServerGroup)
        for element in settings.childKeys():
            srv = settings.value(element, None)
            if srv is not None:
                serverList.append(srv)

        settings.endGroup()
        return serverList
예제 #42
0
    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name)

        from qgis.core import QgsDataSourceURI

        uri = QgsDataSourceURI()

        settingsList = ["service", "host", "port", "database", "username", "password"]
        service, host, port, database, username, password = map(lambda x: settings.value(x, "", type=str), settingsList)

        useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
        sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

        settings.endGroup()

        if service:
            uri.setConnection(service, database, username, password, sslmode)
        else:
            uri.setConnection(host, port, database, username, password, sslmode)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        try:
            return self.connectToUri(uri)
        except ConnectionError as e:
            return False
예제 #43
0
 def readSettings(self):
     s = QSettings()
     s.beginGroup('copy_image')
     self.dpiCombo.setEditText(s.value("dpi", "100", type("")))
     self.colorButton.setColor(s.value("papercolor", QColor(Qt.white), QColor))
     self.crop.setChecked(s.value("autocrop", False, bool))
     self.antialias.setChecked(s.value("antialias", True, bool))
예제 #44
0
 def __init__(self, rules, flux):
   QDialog.__init__(self)
   self.rules = rules
   self.flux = flux
   
   self.setModal(True)
   self.ui = Ui_ExpertivityDialog()
   self.ui.setupUi(self)
   
   R = len(rules)
   self.ui.tableWidget.setColumnCount(R)
   self.ui.tableWidget.setRowCount(R)
   
   ruleNames = [rule.name[:3] for rule in self.rules]
   self.ui.tableWidget.setHorizontalHeaderLabels(ruleNames)
   self.ui.tableWidget.setVerticalHeaderLabels(ruleNames)
   
   for i in range(R):
     self.ui.tableWidget.setColumnWidth(i, 50)
     
   s = QSettings()
   s.beginGroup('Expertivity')
   for i in range(R):
     s.beginGroup('Row%d' % i)
     for j in range(R):
       if j != i:
         self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(s.value('Column%d' % j, 0, float))))
     s.endGroup()
   s.endGroup()
   
   self.ui.tableWidget.itemChanged.connect(self.recalculateExpertivity)
   self.recalculateExpertivity();
예제 #45
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("documentation")
     langs = ['default', 'C'] + lilydoc.translations
     s.setValue("language", langs[self.languages.currentIndex()])
     s.setValue("fontfamily", self.fontChooser.currentFont().family())
     s.setValue("fontsize", self.fontSize.value())
예제 #46
0
 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())
예제 #47
0
파일: widget.py 프로젝트: Ameobea/orange3
    def __quicktipOnce(self):
        filename = os.path.join(settings.widget_settings_dir(),
                                "user-session-state.ini")
        namespace = ("user-message-history/{0.__module__}.{0.__qualname__}"
                     .format(type(self)))
        session_hist = QSettings(filename, QSettings.IniFormat)
        session_hist.beginGroup(namespace)
        messages = self.UserAdviceMessages

        def _ispending(msg):
            return not session_hist.value(
                "{}/confirmed".format(msg.persistent_id),
                defaultValue=False, type=bool)
        messages = [msg for msg in messages if _ispending(msg)]

        if not messages:
            return

        message = messages[self.__msgchoice % len(messages)]
        self.__msgchoice += 1

        self.__showMessage(message)

        def _userconfirmed():
            session_hist = QSettings(filename, QSettings.IniFormat)
            session_hist.beginGroup(namespace)
            session_hist.setValue(
                "{}/confirmed".format(message.persistent_id), True)
            session_hist.sync()

        self.__msgwidget.accepted.connect(_userconfirmed)
예제 #48
0
    def __quicktipOnce(self):
        filename = os.path.join(settings.widget_settings_dir(),
                                "user-session-state.ini")
        namespace = (
            "user-message-history/{0.__module__}.{0.__qualname__}".format(
                type(self)))
        session_hist = QSettings(filename, QSettings.IniFormat)
        session_hist.beginGroup(namespace)
        messages = self.UserAdviceMessages

        def _ispending(msg):
            return not session_hist.value("{}/confirmed".format(
                msg.persistent_id),
                                          defaultValue=False,
                                          type=bool)

        messages = [msg for msg in messages if _ispending(msg)]

        if not messages:
            return

        message = messages[self.__msgchoice % len(messages)]
        self.__msgchoice += 1

        self.__showMessage(message)

        def _userconfirmed():
            session_hist = QSettings(filename, QSettings.IniFormat)
            session_hist.beginGroup(namespace)
            session_hist.setValue("{}/confirmed".format(message.persistent_id),
                                  True)
            session_hist.sync()

        self.__msgwidget.accepted.connect(_userconfirmed)
예제 #49
0
 def deleteRepository(self, reposName):
     """ delete repository connection """
     if not reposName:
         return
     reposName = reposName.decode('utf-8')
     settings = QSettings()
     settings.beginGroup(reposGroup)
     if settings.value(reposName + "/url", "",
                       type=unicode) == officialRepo[1]:
         iface.pluginManagerInterface().pushMessage(
             self.
             tr("You can't remove the official QGIS Plugin Repository. You can disable it if needed."
                ), QgsMessageBar.WARNING)
         return
     warning = self.tr(
         "Are you sure you want to remove the following repository?"
     ) + "\n" + reposName
     if QMessageBox.warning(iface.mainWindow(),
                            self.tr("QGIS Python Plugin Installer"),
                            warning, QMessageBox.Yes,
                            QMessageBox.No) == QMessageBox.No:
         return
     # delete from the settings, refresh data and repopulate all the widgets
     settings.remove(reposName)
     repositories.remove(reposName)
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
예제 #50
0
def get_proxy():
    """Adaption by source of Plugin Installer - Version 1.0.10"""
    settings = QSettings()
    settings.beginGroup("proxy")
    if settings.value("/proxyEnabled", False, type=bool):
        proxy = QNetworkProxy()
        proxyType = settings.value("/proxyType", 0, type=int)
        if proxyType in ["1", "Socks5Proxy"]:
            proxy.setType(QNetworkProxy.Socks5Proxy)
        elif proxyType in ["2", "NoProxy"]:
            proxy.setType(QNetworkProxy.NoProxy)
        elif proxyType in ["3", "HttpProxy"]:
            proxy.setType(QNetworkProxy.HttpProxy)
        elif proxyType in ["4", "HttpCachingProxy"] and QT_VERSION >= 0X040400:
            proxy.setType(QNetworkProxy.HttpCachingProxy)
        elif proxyType in ["5", "FtpCachingProxy"] and QT_VERSION >= 0X040400:
            proxy.setType(QNetworkProxy.FtpCachingProxy)
        else:
            proxy.setType(QNetworkProxy.DefaultProxy)
        proxy.setHostName(settings.value("/proxyHost"))
        proxy.setPort(settings.value("/proxyPort", type=int))
        proxy.setUser(settings.value("/proxyUser"))
        proxy.setPassword(settings.value("/proxyPassword"))
        settings.endGroup()
        return proxy
예제 #51
0
 def loadSettings(self):
     s = QSettings()
     s.beginGroup("helper_applications")
     self.printCommand.setPath(s.value("printcommand", "", type("")))
     self.printDialogCheck.setChecked(s.value("printcommand/dialog", False, bool))
     with qutil.signalsBlocked(self.resolution):
         self.resolution.setEditText(format(s.value("printcommand/dpi", 300, int)))
예제 #52
0
 def addRepository(self):
     """ add new repository connection """
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(Qt.Checked)
     if not dlg.exec_():
         return
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"]:
             iface.pluginManagerInterface().pushMessage(
                 self.tr(
                     "Unable to add another repository with the same URL!"),
                 QgsMessageBar.WARNING)
             return
     settings = QSettings()
     settings.beginGroup(reposGroup)
     reposName = dlg.editName.text()
     reposURL = dlg.editURL.text().strip()
     if reposName in repositories.all():
         reposName = reposName + "(2)"
     # add to settings
     settings.setValue(reposName + "/url", reposURL)
     settings.setValue(reposName + "/enabled",
                       bool(dlg.checkBoxEnabled.checkState()))
     # refresh lists and populate widgets
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
예제 #53
0
class PluginListWidgetModel(QStandardItemModel):
    """This model will create its own items, from the ``QSettings``
    where plugins is set to *load*.
    """
    def __init__(self, parent=None):
        QStandardItemModel.__init__(self, parent)
        self._settings = QSettings()
        self._settings.beginGroup("plugins")
        self.pluginloader = PluginLoader()
        self.pluginloader.pluginsToLoad = self.__checkToLoad()

        for plugin in self.pluginloader.plugins:
            if plugin.load == True:
                item = QStandardItem(plugin.pluginUserString)
                if plugin.icon:
                    item.setIcon(plugin.icon)
                font = item.font()
                font.setPointSize(font.pointSize() + 4)
                item.setFont(font)
                item.setEditable(False)
                item.plugin = plugin
                self.appendRow(item)

    def __checkToLoad(self):
        pluginlist = []

        # When beginGroup is set to plugins, the childgroups will be
        # each of the plugins.
        for plugin in self._settings.childGroups():
            valueString = str(plugin) + "/load"
            value = self._settings.value(valueString, "True").toString()
            if value == "True":
                pluginlist.append(str(plugin))

        return pluginlist
예제 #54
0
파일: qnotero.py 프로젝트: dsqmoore/qnotero
    def saveState(self):
        """Save the settings"""

        settings = QSettings("cogscinl", "qnotero")
        settings.beginGroup("Qnotero")
        saveConfig(settings)
        settings.endGroup()
예제 #55
0
파일: qnotero.py 프로젝트: dsqmoore/qnotero
    def restoreState(self):
        """Restore the settings"""

        settings = QSettings("cogscinl", "qnotero")
        settings.beginGroup("Qnotero")
        restoreConfig(settings)
        settings.endGroup()
예제 #56
0
    def load(self):
        """ populate the mRepositories dict"""
        self.mRepositories = {}
        settings = QSettings()
        settings.beginGroup(reposGroup)
        # first, update repositories in QSettings if needed
        officialRepoPresent = False
        for key in settings.childGroups():
            url = settings.value(key + "/url", "", type=unicode)
            if url == officialRepo[1]:
                officialRepoPresent = True
            if url == officialRepo[2]:
                settings.setValue(key + "/url", officialRepo[1]) # correct a depreciated url
                officialRepoPresent = True
        if not officialRepoPresent:
            settings.setValue(officialRepo[0] + "/url", officialRepo[1])

        for key in settings.childGroups():
            self.mRepositories[key] = {}
            self.mRepositories[key]["url"] = settings.value(key + "/url", "", type=unicode)
            self.mRepositories[key]["authcfg"] = settings.value(key + "/authcfg", "", type=unicode)
            self.mRepositories[key]["enabled"] = settings.value(key + "/enabled", True, type=bool)
            self.mRepositories[key]["valid"] = settings.value(key + "/valid", True, type=bool)
            self.mRepositories[key]["Relay"] = Relay(key)
            self.mRepositories[key]["xmlData"] = None
            self.mRepositories[key]["state"] = 0
            self.mRepositories[key]["error"] = ""
        settings.endGroup()
예제 #57
0
 def loadSettings(self):
     """Loads the settings from config."""
     s = QSettings()
     s.beginGroup("sidebar")
     line_numbers = s.value("line_numbers", self._line_numbers, bool)
     self.setLineNumbersVisible(line_numbers)
     folding = s.value("folding", self._folding, bool)
     self.setFoldingVisible(folding)
예제 #58
0
파일: tools.py 프로젝트: shimpe/frescobaldi
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("documentstructure")
     if self.patternList.value(
     ) != documentstructure.default_outline_patterns:
         s.setValue("outline_patterns", self.patternList.value())
     else:
         s.remove("outline_patterns")
예제 #59
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup('scorewiz/instrumentnames')
     s.setValue('enable', self.isChecked())
     s.setValue('first', ('long', 'short')[self.firstSystem.currentIndex()])
     s.setValue('other',
                ('long', 'short', 'none')[self.otherSystems.currentIndex()])
     s.setValue('language', self._langs[self.language.currentIndex()])