Beispiel #1
0
 def update_run_at_startup(self):
     if not getattr(sys, 'frozen', False):
         self._logger.debug("Skipping run at startup for non-frozen app!")
         return
     self._logger.info("Updating run at startup setting: ".format(
         str(self._settings.run_at_startup)))
     if Config.IS_WINDOWS:
         reg_settings = QSettings(
             "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
             QSettings.NativeFormat)
         if self._settings.run_at_startup:
             reg_settings.setValue(
                 "TSMApplication", "\"{}\"".format(
                     os.path.abspath(sys.executable).replace("/", "\\")))
         else:
             reg_settings.remove("TSMApplication")
         reg_settings.sync()
     elif Config.IS_MAC:
         if self._settings.run_at_startup:
             app_path = os.path.abspath(
                 os.path.join(os.path.dirname(sys.executable), os.pardir,
                              os.pardir, os.pardir)) + "/"
             os.system(
                 "osascript -e 'tell application \"System Events\" to make login item at end with properties {{path:\"{}\", hidden:false}}'"
                 .format(app_path))
         else:
             os.system(
                 "osascript -e 'tell application \"System Events\" to delete login item \"TSMApplication\"'"
             )
     elif Config.IS_LINUX:
         pass  # Linux users will have to setup that themselves.
     else:
         raise Exception("Unexpected platform")
Beispiel #2
0
 def onReset(self):
     '''
     Delte Settings
     '''
     s = QSettings()
     s.remove("APIS/config_ini")
     self.uiConfigIniFileEdit.clear()
Beispiel #3
0
class SettingBox(QDialog):
    progressBarSpace: QProgressBar
    pushButtonAccount: QPushButton

    def __init__(self, *args, **kwargs):
        self.debug = kwargs.pop('debug', False)

        super().__init__(flags=Qt.Qt.WindowStaysOnTopHint, *args, **kwargs)
        self.tray = SysTray(self)
        self.settings = QSettings()
        self.init_ui()
        self.check_account()

        if self.debug:
            self._reload = self.startTimer(500)

    def timerEvent(self, e):

        """
        :param e:
        :type e: QTimerEvent
        """
        if e.timerId() == self._reload:
            with open('resource/style.qss', 'r') as style:
                self.setStyleSheet(style.read())

    def init_ui(self):
        loadUi('resource/setting.ui', self)

        self.pushButtonAccount.clicked.connect(self.login)
        self.tray.show()

    def check_account(self):
        if self.username:
            self.pushButtonAccount.setText(f"注销:{self.username}")
            self.progressBarSpace.setVisible(True)
            self.progressBarSpace.setDisabled(False)
            self.progressBarSpace.setMaximum(50)
            self.progressBarSpace.setValue(13)
        else:
            self.pushButtonAccount.setText("登录")
            self.progressBarSpace.setVisible(False)
            self.show()

    @property
    def username(self):
        return self.settings.value('username', False)

    def login(self):
        if self.username:
            self.settings.remove('username')
            self.settings.remove('password')
            self.check_account()
        else:
            res = LoginBox(self)
            res.show()

    def closeEvent(self, event: QCloseEvent):
        event.ignore()
        self.hide()
Beispiel #4
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")
Beispiel #5
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")
Beispiel #6
0
 def remove_parameter_preset(self, idx: int) -> None:
     name = list(self._param_preset_list.keys())[idx]
     qsetting = QSettings()
     qsetting.beginGroup(SettingTypeKey.print_param.value)
     qsetting.remove(name)
     qsetting.endGroup()
     self.remove_setting_signal.emit(SettingTypeKey.print_param.value, name)
     return self._param_preset_list.pop(name)
    def deleteSession(self, index):

        session = self._retrieveComboBox.itemData(index)

        if session:
            reg = QSettings()
            reg.remove(session)
            self.accept()
Beispiel #8
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("documentation")
     paths = self.paths.value()
     if paths:
         s.setValue("paths", paths)
     else:
         s.remove("paths")
Beispiel #9
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("documentation")
     paths = self.paths.value()
     if paths:
         s.setValue("paths", paths)
     else:
         s.remove("paths")
Beispiel #10
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("hyphenation")
     paths = self.listedit.value()
     if paths:
         s.setValue("paths", paths)
     else:
         s.remove("paths")
Beispiel #11
0
def moveArthurbackendPrint():
    k = "arthurbackend_print"
    oldk = "musicview/" + k
    newk = "printing/" + k
    s = QSettings()
    if s.contains(oldk):
        s.setValue(newk, s.value(oldk))
        s.remove(oldk)
Beispiel #12
0
 def saveSettings(self):
     s = QSettings()
     s.beginGroup("hyphenation")
     paths = self.listedit.value()
     if paths:
         s.setValue("paths", paths)
     else:
         s.remove("paths")
Beispiel #13
0
def BorrarConf(clave=None, sistema=None):
    if not sistema:
        sistema = Constantes.SISTEMA

    settings = QSettings(Constantes.EMPRESA, sistema)
    if clave:
        settings.remove(clave)
    else:
        settings.clear()
Beispiel #14
0
 def write_rois_to_settings(self, rois):
     settings = QSettings()
     settings.remove("regions_of_interest")
     settings.beginWriteArray("regions_of_interest")
     for index, (name, start, end) in enumerate(rois):
         settings.setArrayIndex(index)
         settings.setValue("name", name)
         settings.setValue("start", start)
         settings.setValue("end", end)
     settings.endArray()
Beispiel #15
0
def delete_layout_key(group, key):
    filename = read_settings("User_Settings", 'current_layout_file')
    filename = os.path.join(profiles_folder, filename)
    settings = QSettings(filename, QSettings.NativeFormat)
    settings.beginGroup(group)
    keys = settings.childKeys()
    if key in keys:
        settings.remove(key)
    settings.endGroup()
    return keys
Beispiel #16
0
 def save(self, scheme):
     try:
         shortcuts, default = self._shortcuts[scheme]
     except KeyError:
         return
     s =QSettings()
     key = "shortcuts/{0}/{1}/{2}".format(scheme, self.collection.name, self.name)
     if default:
         s.remove(key)
     else:
         s.setValue(key, shortcuts)
Beispiel #17
0
 def clearAll(settings_key):
     """
     Clear the cache files and the value in QSettings
     Input:
         settings_key[str]: The key in QSettings
     """
     settings = QSettings()
     val = settings.value(settings_key, type=dict)
     for key, val in val.items():
         FileCache.removeCacheFile(val["pickle_path"])
     settings.remove(settings_key)
Beispiel #18
0
 def saveSettings(self):
     s = QSettings()
     s.setValue("language", self._langs[self.lang.currentIndex()])
     s.setValue("system_icons", self.systemIcons.isChecked())
     s.setValue("tabs_closable", self.tabsClosable.isChecked())
     s.setValue("splash_screen", self.splashScreen.isChecked())
     s.setValue("allow_remote", self.allowRemote.isChecked())
     if self.styleCombo.currentIndex() == 0:
         s.remove("guistyle")
     else:
         s.setValue("guistyle", self.styleCombo.currentText())
Beispiel #19
0
 def clearAll(settings_key):
     """
     Clear the cache files and the value in QSettings
     Input:
         settings_key[str]: The key in QSettings
     """
     settings = QSettings()
     val = settings.value(settings_key, type=dict)
     for key, val in val.items():
         FileCache.removeCacheFile(val["pickle_path"])
     settings.remove(settings_key)
Beispiel #20
0
 def saveSettings(self):
     s = QSettings()
     s.setValue("language", self._langs[self.lang.currentIndex()])
     s.setValue("system_icons", self.systemIcons.isChecked())
     s.setValue("tabs_closable", self.tabsClosable.isChecked())
     s.setValue("splash_screen", self.splashScreen.isChecked())
     s.setValue("allow_remote", self.allowRemote.isChecked())
     if self.styleCombo.currentIndex() == 0:
         s.remove("guistyle")
     else:
         s.setValue("guistyle", self.styleCombo.currentText())
Beispiel #21
0
    def unbindMobilePhone(self):
        try:
            settings = QSettings('Secalot', 'Secalot Control Panel')
            settings.remove('mobilePhoneBound')
            settings.remove('removeScreenUID')
            settings.remove('removeScreenKey')

            self.unbindMobilePhoneReady.emit()

        except Exception as e:
            self.errorOccurred.emit(self.tr("A RemoteScreen error occurred."))
Beispiel #22
0
    def deleteServerInfo(self, serverName):
        """Deletes the ThreddsServerInfo object with the given name from
        the underlying settings.

        :param    serverName: The name of the server we have to delete.
        :type     serverName: str
        """
        settings = QSettings()
        settings.beginGroup(self.ThreddsServerGroup)
        settings.remove(serverName)
        settings.endGroup()
Beispiel #23
0
 def save(self, scheme):
     try:
         shortcuts, default = self._shortcuts[scheme]
     except KeyError:
         return
     s =QSettings()
     key = "shortcuts/{0}/{1}/{2}".format(scheme, self.collection.name, self.name)
     if default:
         s.remove(key)
     else:
         s.setValue(key, shortcuts)
Beispiel #24
0
def main():
    """The main routine."""
    environ["LIBOVERLAY_SCROLLBAR"] = "0"
    parser = argparse.ArgumentParser(
                prog=__title__,
                description=__title__ + ' is a 2d RPG game maker.',
                epilog=__copyright__ + ", " + __license__ +".")
    parser.add_argument('-v', '--version', action='store_true', default=False, help='get software version.')
    parser.add_argument('-c', '--clean', action='store_true', default=False, help='cleans software settings.')
    parser.add_argument('-p', '--palette', action='store_true', default=False, help='loads exclusively the palette editor.')
    parser.add_argument('mapfile', nargs='?', default='check_no_map', help='a single .map.json file')
    args = parser.parse_args()

    if args.clean == True:
        settings = QSettings("FGMK", "fgmkEditor")
        for key in settings.allKeys():
            settings.remove(key) #guarantee to eliminate all
        settings.sync() #writes to disk
        exit()

    if args.palette == True:
        a = QApplication([])
        m = palette_editor.main()
        a.processEvents()
        m.show()
        m.raise_()
        exit(a.exec_())

    if args.version == True:
        print(__title__ + "  v " + __version__ )
        exit()

    a = QApplication([])
    start = time()
    splash_pix = Editor.Icon()
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())
    splash.show()
    while time() - start < 1:
        sleep(0.001)
        a.processEvents()

    mw_arg=[]
    if 'mapfile' in args:
        mw_arg = [args.mapfile]

    mw = Editor.MainWindow(mw_arg)
    a.processEvents()
    mw.show()
    splash.finish(mw)
    mw.raise_()
    mw.afterInit()
    exit(a.exec_())
Beispiel #25
0
def setLimitReached(token, resetTime, settings=None):
    if token not in ['av', 'bc', 'fh']:
        raise ValueError(f'Not a valid stock api token: {token}')
    if settings is None:
        settings = QSettings('zero_substance/stockapi', 'structjour')
    token = token + 'limitreached'
    resetTime = pd.Timestamp(resetTime)
    now = pd.Timestamp.now()
    if now > resetTime:
        settings.remove(token)
    else:
        settings.setValue(token, resetTime)
 def remember_login_handler(self):
     """ 自动登录状态改变 """
     client_config_path = os.path.join(BASE_DIR, "dawn/client.ini")
     app_configs = QSettings(client_config_path, QSettings.IniFormat)
     state = self.login_widget.remember_login.checkState()
     if state == Qt.Checked:
         if not self.login_widget.remember_psd.isChecked():
             self.login_widget.remember_psd.setChecked(True)
         self.remember_checked_handler()  # 记住登录,手动调用记住密码
         app_configs.setValue("USER/AUTOLOGIN", 1)
     else:
         # 移除自动登录标记
         app_configs.remove("USER/AUTOLOGIN")
Beispiel #27
0
class PixelWall(QApplication):

    def __init__(self, *args, **kwargs):
        super(PixelWall, self).__init__(*args, **kwargs)
        self.engine = QQmlApplicationEngine(self)
        self.servers = ServerModel(self.engine)
        self.settings = QSettings('OpenServices', 'PixelWall')
        url = self.settings.value('server/url')
        self.engine.setNetworkAccessManagerFactory(NetworkAccessManagerFactory('hetzner.fladi.at', 3128))
        ctxt = self.engine.rootContext()
        ctxt.setContextProperty('app', self)
        ctxt.setContextProperty('url', 'about:blank')
        self.engine.load(QUrl('states.qml'))
        discoverer = Avahi(self.engine, '_pixelwall._tcp')
        discoverer.initialized.connect(self.serverState)
        discoverer.added.connect(self.servers.addService)
        ctxt.setContextProperty('serverModel', self.servers)
        discoverer.run()
        if url:
            self.setUrl(url)
            self.setState('Web')

    def setState(self, state):
        for root in self.engine.rootObjects():
            node = root.findChild(QObject, 'main')
            if node:
                logger.info('Setting state: {}'.format(state))
                node.setProperty('state', state)

    def setUrl(self, url):
        logger.info('Connecting WebView to {}'.format(url))
        ctxt = self.engine.rootContext()
        ctxt.setContextProperty('url', 'https://www.heise.de/')

    @pyqtSlot()
    def reset(self):
        self.settings.remove('server/url')
        self.setState('Servers')

    @pyqtSlot(int)
    def serverSelected(self, index):
        server = self.servers.getIndex(index)
        logger.info('Server selected {}'.format(server))
        url = 'https://{server.host}:{server.port}/'.format(server=server)
        self.settings.setValue('server/url', url)
        self.setUrl(url)
        self.setState('Web')

    @pyqtSlot()
    def serverState(self):
        self.setState('Servers')
Beispiel #28
0
def getLimitReached(token, settings=None):
    if token not in ['av', 'bc', 'fh']:
        raise ValueError(f'Not a valid stock api token: {token}')
    if settings is None:
        settings = QSettings('zero_substance/stockapi', 'structjour')

    resetTime = settings.value(token + 'limitreached', None)
    if resetTime is None: return False

    now = pd.Timestamp.now()
    if now <= resetTime:
        return True
    settings.remove(token + 'limitreached')
    return False
Beispiel #29
0
def renameUseshebang():
    s = QSettings()
    l = s.beginReadArray("lilypondinfo")
    old = []
    for i in range(l):
        s.setArrayIndex(i)
        old.append(s.value("always_use_shebang", None))
    s.endArray()
    s.beginWriteArray("lilypondinfo")
    for i in range(l):
        s.setArrayIndex(i)
        if old[i] is not None:
            s.setValue("useshebang", old[i])
            s.remove("always_use_shebang")
    s.endArray()
Beispiel #30
0
 def saveSettings(self):
     s = QSettings()
     s.setValue("language", self._langs[self.lang.currentIndex()])
     s.setValue("system_icons", self.systemIcons.isChecked())
     s.setValue("tabs_closable", self.tabsClosable.isChecked())
     s.setValue("splash_screen", self.splashScreen.isChecked())
     s.setValue("allow_remote", self.allowRemote.isChecked())
     if self.styleCombo.currentIndex() == 0:
         s.remove("guistyle")
     else:
         s.setValue("guistyle", self.styleCombo.currentText())
     # update all top-level windows, so icon changes are picked up
     for w in QApplication.topLevelWidgets():
         if w.isVisible():
             w.update()
Beispiel #31
0
def restoreSettings(fileName, widget):            

    settings = QSettings(fileName, QSettings.IniFormat)
    
    try:    
        for obj in widget.findChildren(QWidget):
            if obj.metaObject().className() == 'QSpinBox':
                obj.setValue(int(settings.value(obj.objectName())))
            if obj.metaObject().className() == 'QDoubleSpinBox':
                obj.setValue(float(settings.value(obj.objectName())))
            if obj.metaObject().className() == 'QCheckBox':
                obj.setCheckState(int(settings.value(obj.objectName())))
            #if obj.metaObject().className() == 'QLineEdit':
            #    obj.setText(str(settings.value(obj.objectName())))
    except:
        print('Error loading ' + settings.fileName()  + '. A new INI file will be created.')
        settings.remove('') # Clear the Settings.ini file  
    def delete(self, *args):
        try:
            index = self._proxy.mapSelectionToSource(
                self.tableview.selectionModel().selection()).indexes()[0]
            row = index.row()
            items = self.model.takeRow(row)  # QList<QStandardItem>
            key = items[0].data(0)
            val = items[1].data(0)
            if self.debug: self.info.log("delete key:", key)
            if self.debug: self.info.log("delte val", val)
            s = QSettings()
            s.remove(key)

            self.undoList.append((index, items))
            self.btnUndo.setEnabled(True)
        except Exception as e:
            self.info.err(e)
Beispiel #33
0
 def set_start_on_system(cls):
     """Habilita la opción de iniciar la aplicación con el sistema.
     Esta funcionalidad solo se habilita si el sistema es Windows y si se está ejecutando desde
     un .exe
     """
     app_path = QCoreApplication.applicationFilePath()
     if QSysInfo.productType() == "windows" \
     and os.path.basename(app_path) == "capounet_sync.exe":
         settings = QSettings(
             "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
             QSettings.NativeFormat)
         if cls.start_on_system:
             settings.setValue("CAPOUNET SYNC",
                               QDir.toNativeSeparators(app_path))
             settings.sync()
         else:
             settings.remove("CAPOUNET SYNC")
Beispiel #34
0
def set_documents_dir(dir_name):
    """Set the user's documents directory.

    Save the directory in settings. If settings matches default, remove settings.
    """
    standard_documents_dir = QStandardPaths.writableLocation(
        QStandardPaths.DocumentsLocation)

    group_name = GENERAL_QSETTINGS_GROUP
    settings = QSettings()
    settings.beginGroup(group_name)

    if dir_name == standard_documents_dir:
        settings.remove(QSETTINGS_KEY_DOCUMENTS_FOLDER)
    else:
        settings.setValue(QSETTINGS_KEY_DOCUMENTS_FOLDER, dir_name)

    settings.endGroup()
Beispiel #35
0
def getLimitReached(token, settings=None):

    if token not in ['av', 'bc', 'fh', 'tgo']:
        raise ValueError(f'Not a valid stock api token: {token}')
    if token == 'tgo':
        # Tiingo limit is 500/hr, 20k/month. For now while building it, treat as no limit
        return False
    if settings is None:
        settings = QSettings('zero_substance/stockapi', 'structjour')

    resetTime = settings.value(token + 'limitreached', None)
    if resetTime is None: return False

    now = pd.Timestamp.now()
    if now <= resetTime:
        return True
    settings.remove(token + 'limitreached')
    return False
Beispiel #36
0
    def saveSettings(self, currentKey, namesGroup, removePrefix=None):
        # first save new scheme names
        s = QSettings()
        s.beginGroup(namesGroup)
        for i in range(self.scheme.count()):
            if self.scheme.itemData(i) != 'default':
                s.setValue(self.scheme.itemData(i), self.scheme.itemText(i))

        for scheme in self._schemesToRemove:
            s.remove(scheme)
        s.endGroup()
        if removePrefix:
            for scheme in self._schemesToRemove:
                s.remove("{0}/{1}".format(removePrefix, scheme))
        # then save current
        scheme = self.currentScheme()
        s.setValue(currentKey, scheme)
        # clean up
        self._schemesToRemove = set()
Beispiel #37
0
    def saveSettings(self, currentKey, namesGroup, removePrefix=None):
        # first save new scheme names
        s = QSettings()
        s.beginGroup(namesGroup)
        for i in range(self.scheme.count()):
            if self.scheme.itemData(i) != 'default':
                s.setValue(self.scheme.itemData(i), self.scheme.itemText(i))

        for scheme in self._schemesToRemove:
            s.remove(scheme)
        s.endGroup()
        if removePrefix:
            for scheme in self._schemesToRemove:
                s.remove("{0}/{1}".format(removePrefix, scheme))
        # then save current
        scheme = self.currentScheme()
        s.setValue(currentKey, scheme)
        # clean up
        self._schemesToRemove = set()
Beispiel #38
0
    def load():
        settings = QSettings(Config.filename, QSettings.IniFormat)

        legacy_device = os.path.basename(
            str(settings.value("keyboard-input-device"))).strip()
        Config.input_devices = list(
            set(
                filter(
                    None,
                    str(
                        settings.value(
                            "input-devices",
                            defaultValue=legacy_device)).split(","))))
        Config.icons = settings.value("icons", defaultValue="dark")
        Config.use_tray_icon = Config.to_boolean(
            str(settings.value("use-tray-icon", defaultValue=True)))
        Config.single_instance = Config.to_boolean(
            str(settings.value("single-instance", defaultValue=True)))

        settings.beginGroup("List")
        Config.list_sort_column = settings.value("sort-column",
                                                 defaultValue="name")
        Config.list_sort_order = settings.value("sort-order",
                                                defaultValue="asc")
        settings.endGroup()

        settings.beginGroup("Labels")
        Config.labels_length_unit = settings.value("length-unit",
                                                   defaultValue="mm")
        Config.default_label_width = Config.to_integer(
            settings.value("default-width", defaultValue=None))
        Config.default_label_height = Config.to_integer(
            settings.value("default-height", defaultValue=None))
        Config.label_icon_margin = Config.to_integer(
            settings.value("icon-margin", defaultValue=1))
        settings.endGroup()

        if legacy_device != "":
            settings.remove("keyboard-input-device")
            Config.save()
Beispiel #39
0
class PugdebugSettings():

    defaults = {
        'debugger/host': '127.0.0.1',
        'debugger/port_number': 9000,
        'debugger/idekey': 'pugdebug',
        'debugger/break_at_first_line': Qt.Checked,
        'debugger/max_depth': '3',
        'debugger/max_children': '128',
        'debugger/max_data': '512',

        'path/project_root': os.path.expanduser('~'),
        'path/path_mapping': ''
    }

    def __init__(self):
        """Model object to handle application settings

        Sets up initial application settings.

        QSettings promises to work cross-platform.
        """
        QCoreApplication.setOrganizationName("pugdebug")
        QCoreApplication.setOrganizationDomain(
            "http://github.com/robertbasic/pugdebug"
        )
        QCoreApplication.setApplicationName("pugdebug")
        self.application_settings = QSettings()

        self.setup_default_settings()

    def setup_default_settings(self):
        """Set the default values for settings which don't have a value."""
        for key, value in self.defaults.items():
            if not self.has(key):
                self.set(key, value)

    def get(self, key):
        return self.application_settings.value(key)

    def get_default(self, key):
        return self.defaults[key] if key in self.defaults else None

    def has(self, key):
        return self.application_settings.contains(key)

    def set(self, key, value):
        return self.application_settings.setValue(key, value)

    def remove(self, key):
        return self.application_settings.remove(key)

    def add_project(self, project):
        index = self.__get_next_index(project)

        if index is not False:
            self.application_settings.beginWriteArray('projects')
            self.application_settings.setArrayIndex(index)
            self.application_settings.setValue('projects', project)
            self.application_settings.endArray()

    def delete_project(self, project):
        size = self.application_settings.beginReadArray('projects')

        for i in range(0, size):
            self.application_settings.setArrayIndex(i)
            existing_project = self.application_settings.value('projects')

            if existing_project == project:
                self.application_settings.remove('projects')
                break

        self.application_settings.endArray()

        self.__reindex_projects_array()

    def get_projects(self):
        size = self.application_settings.beginReadArray('projects')

        projects = []
        for i in range(0, size):
            self.application_settings.setArrayIndex(i)
            projects.append(self.application_settings.value('projects'))

        self.application_settings.endArray()

        return projects

    def __get_next_index(self, project):
        size = self.application_settings.beginReadArray('projects')

        index = None

        for i in range(0, size):
            self.application_settings.setArrayIndex(i)
            existing_project = self.application_settings.value('projects')

            if existing_project == project:
                index = i
                break

        self.application_settings.endArray()

        return False if index is not None else size

    def __reindex_projects_array(self):
        size = self.application_settings.beginReadArray('projects')

        projects = set()
        for i in range(0, size):
            self.application_settings.setArrayIndex(i)
            project = self.application_settings.value('projects')

            if project is not None:
                projects.add(project)

        self.application_settings.endArray()

        self.application_settings.remove('projects')

        self.application_settings.beginWriteArray('projects')

        i = 0
        for project in projects:
            self.application_settings.setArrayIndex(i)
            self.application_settings.setValue('projects', project)
            i += 1

        self.application_settings.endArray()
class Preferences(QDialog, Ui_Settings):
    """
    This class is a wrapper for the Ui_Preferences and its controls
    """
    GENERAL = 0
    OSF = 1
    ABOUT = 2

    PROJECT_NAME_COLUMN = 1
    PROJECT_SYNC_COLUMN = 0

    preferences_closed_signal = pyqtSignal()
    containing_folder_updated_signal = pyqtSignal((str,))

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.containing_folder = ''
        self._translate = QCoreApplication.translate

        self.changeFolderButton_2.clicked.connect(self.update_sync_nodes)
        self.changeFolderButton.clicked.connect(self.update_containing_folder)
        self.pushButton.clicked.connect(self.sync_all)
        self.pushButton_2.clicked.connect(self.sync_none)
        self.tabWidget.currentChanged.connect(self.selector)
        self.labelVersion.setText('OSF Sync v{}'.format(osfoffline.__version__))

        if ON_WINDOWS:
            self.winRegistryRunKey = QSettings(WINDOWS_RUN_PATH, QSettings.NativeFormat)
            self.startAtBoot.setChecked(self.winRegistryRunKey.contains('OSF Sync'))
        elif ON_MAC:
            self.startAtBoot.setChecked(os.path.exists(MAC_PLIST_FILE_PATH))

        self.tree_items = []
        self.selected_nodes = []

        self._executor = QtCore.QThread()
        self.node_fetcher = NodeFetcher()

    def on_first_boot(self):
        self.startAtBoot.setChecked(True)

    def update_containing_folder(self):
        self.set_containing_folder(save_setting=True)

    def closeEvent(self, event):

        if set(self.selected_nodes) != set([node.id for tree_item, node in self.tree_items
                                            if tree_item.checkState(self.PROJECT_SYNC_COLUMN) == Qt.Checked]):
            if self.selected_nodes and not self.tree_items:
                return
            else:
                reply = QMessageBox()
                reply.setText('Unsaved changes')
                reply.setIcon(QMessageBox.Warning)
                reply.setInformativeText(language.UNSAVED_CHANGES)
                default = reply.addButton('Exit without saving', QMessageBox.YesRole)
                reply.addButton('Review changes', QMessageBox.NoRole)
                reply.setDefaultButton(default)
                if reply.exec_() != 0:
                    return event.ignore()
        self.reset_tree_widget()

        with Session() as session:
            user = session.query(User).one_or_none()
            if user:
                user.first_boot = False
                session.add(user)
                session.commit()

        if ON_WINDOWS:
            if self.startAtBoot.isChecked():
                self.winRegistryRunKey.setValue('OSF Sync', sys.argv[0])
            else:
                self.winRegistryRunKey.remove('OSF Sync')
        elif ON_MAC:
            if self.startAtBoot.isChecked():
                with open(MAC_PLIST_FILE_PATH, 'w+') as file:
                    file.write(MAC_PLIST_FILE_CONTENTS)
            elif os.path.exists(MAC_PLIST_FILE_PATH):
                os.remove(MAC_PLIST_FILE_PATH)

        event.accept()

    def set_containing_folder(self, save_setting=False):
        with Session() as session:
            user = session.query(User).one()

        logger.warning('Changing containing folder')
        res = QFileDialog.getExistingDirectory(caption='Choose where to place OSF folder')
        if not res:
            return
        containing_folder = os.path.abspath(res)
        folder = os.path.join(containing_folder, 'OSF')

        if save_setting:
            logger.debug('Copy files into new OSF folder.')
            # copy the synced folders from the old to new location
            # so OSF doesn't think they were deleted
            copy_tree(user.folder, folder)

        user.folder = folder

        self.containingFolderTextEdit.setText(self._translate("Preferences", self.containing_folder))
        self.open_window(tab=Preferences.GENERAL)  # todo: dynamically update ui????
        self.containing_folder_updated_signal.emit(folder)

        if save_setting:
            with Session() as session:
                session.add(user)
                session.commit()
            self.update_sync_nodes()

    def update_sync_nodes(self):
        self.selected_nodes = []

        with Session() as session:
            user = session.query(User).one()
            for tree_item, node in self.tree_items:
                checked = tree_item.checkState(self.PROJECT_SYNC_COLUMN) == Qt.Checked
                try:
                    db_node = session.query(Node).filter(Node.id == node.id).one()
                except NoResultFound:
                    db_node = None

                if checked:
                    self.selected_nodes.append(node.id)
                    if not db_node:
                        session.add(
                            Node(id=node.id, title=node.title, user=user, sync=True)
                        )
                    else:
                        db_node.sync = True
                elif db_node:
                    session.delete(db_node)
            session.commit()
        BackgroundHandler().sync_now()
        self.close()

    def sync_all(self):
        for tree_item, node in self.tree_items:
            tree_item.setCheckState(self.PROJECT_SYNC_COLUMN, Qt.Checked)

    def sync_none(self):
        for tree_item, node in self.tree_items:
            tree_item.setCheckState(self.PROJECT_SYNC_COLUMN, Qt.Unchecked)

    def open_window(self, *, tab=GENERAL):
        if self.isVisible():
            self.tabWidget.setCurrentIndex(tab)
            self.selector(tab)
        else:
            self.tabWidget.setCurrentIndex(tab)
            self.selector(tab)
            self.show()
        self.raise_()
        self.activateWindow()

    def selector(self, selected_index):
        with Session() as session:
            user = session.query(User).one()
        if selected_index == self.GENERAL:
            containing_folder = os.path.dirname(user.folder)
            self.containingFolderTextEdit.setText(self._translate("Preferences", containing_folder))
        elif selected_index == self.OSF:
            self.label.setText(self._translate("Preferences", user.full_name))
            self._executor = QtCore.QThread()
            self.reset_tree_widget()
            self.changeFolderButton_2.setEnabled(False)
            self.pushButton.setEnabled(False)
            self.pushButton_2.setEnabled(False)
            self.node_fetcher = NodeFetcher()
            self.treeWidget.setStyleSheet("background-color: grey")
            self.treeWidget.setCursor(QtCore.Qt.BusyCursor)
            self.node_fetcher.finished[list].connect(self.populate_item_tree)
            self.node_fetcher.finished[int].connect(self.item_load_error)
            self.node_fetcher.moveToThread(self._executor)
            self._executor.started.connect(self.node_fetcher.fetch)
            self._executor.start()

    def reset_tree_widget(self):
        self.tree_items.clear()
        self.treeWidget.clear()

    @QtCore.pyqtSlot(list)
    def populate_item_tree(self, nodes):
        _translate = QCoreApplication.translate
        self.selected_nodes = []
        with Session() as session:
            all_selected_nodes = [n.id for n in session.query(Node)]
            for n in session.query(Node):
                if n.parent_id not in all_selected_nodes and n.id not in self.selected_nodes:
                    self.selected_nodes.append(n.id)

        for node in sorted(nodes, key=lambda n: n.title):
            tree_item = QTreeWidgetItem(self.treeWidget)
            tree_item.setCheckState(self.PROJECT_SYNC_COLUMN,
                                    Qt.Checked if node.id in self.selected_nodes else Qt.Unchecked)
            tree_item.setText(self.PROJECT_NAME_COLUMN,
                              _translate('Preferences', '{} - {}'.format(node.title, node.id)))

            self.tree_items.append((tree_item, node))

        self.treeWidget.resizeColumnToContents(self.PROJECT_SYNC_COLUMN)
        self.treeWidget.resizeColumnToContents(self.PROJECT_NAME_COLUMN)
        self.treeWidget.unsetCursor()
        self.treeWidget.setStyleSheet("background-color: white")
        self.changeFolderButton_2.setEnabled(True)
        self.pushButton.setEnabled(True)
        self.pushButton_2.setEnabled(True)

    @QtCore.pyqtSlot(int)
    def item_load_error(self, error_code):
        """If the list of nodes does not load, warn the user, then close prefs panel without saving changes"""
        # TODO: Is there a more elegant way to pass errors across signal or thread boundaries?
        QMessageBox.critical(None,
                             'Error fetching projects',
                             language.ITEM_LOAD_ERROR)
        self.reset_tree_widget()
        self.reject()
class LatestCollections(QObject):
    DefaultCollectionName = OpenNumismat.HOME_PATH + "/demo.db"
    SettingsKey = 'collection/latest'
    LatestCount = 7

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

        self.settings = QSettings()

    # Create menu actions
    def actions(self):
        actions = []
        for i in range(LatestCollections.LatestCount):
            key = self.__key(i)
            fileName = self.settings.value(key)
            if fileName:
                title = Collection.fileNameToCollectionName(fileName)
                act = QAction(title, self)
                act.setData(fileName)
                actions.append(act)

        return actions

    # Return latest opened collection file name
    def latest(self):
        fileName = self.settings.value(self.SettingsKey)
        if not fileName:
            fileName = LatestCollections.DefaultCollectionName

        return fileName

    def add(self, fileName):
        # Get stored latest collections
        values = []
        for i in range(LatestCollections.LatestCount):
            val = self.settings.value(self.__key(i))
            if val:
                values.append(val)

        values.insert(0, fileName)
        # Uniqify collections name (order preserving)
        checked = []
        for e in values:
            if e not in checked:
                checked.append(e)
        values = checked

        # Store updated latest collections
        for i in range(len(values)):
            self.settings.setValue(self.__key(i), values[i])

        # Remove unused settings entries
        for i in range(len(values), LatestCollections.LatestCount):
            self.settings.remove(self.__key(i))

        # Store latest collection for auto opening
        self.settings.setValue(self.SettingsKey, fileName)

    def delete(self, fileName):
        for i in range(LatestCollections.LatestCount):
            value = self.settings.value(self.__key(i))
            if value == fileName:
                self.settings.remove(self.__key(i))

    def __key(self, i):
        return self.SettingsKey + str(i + 1)
Beispiel #42
0
def removeGlyphListPath(path):
    settings = QSettings()
    settings.remove("settings/glyphListPath")