class Settings(object): def __init__(self, setting_path: str): self.setting_path = setting_path self.settings = QSettings(setting_path, QSettings.IniFormat) self.settings.setFallbacksEnabled(False) self.set_value(index_filter, []) def int_value(self, item: setting_item): return int(self.value(item)) def float_value(self, item: setting_item): return float(self.value(item)) def boolean_value(self, item: setting_item): value = self.value(item) return value.lower() == 'true' if isinstance(value, str) else bool(value) def list_value(self, item: setting_item): value = self.value(item) return value if isinstance(value, list) else [value] def str_value(self, item: setting_item): return str(self.value(item)) def value(self, item: setting_item): return self.settings.value(f'{item.section}/{item.key}', item.default_value) def set_value(self, item: setting_item, value: Any): self.settings.setValue(f'{item.section}/{item.key}', value)
def __init__(self, main_model: MainModel, notification_controller: NotificationController, running: bool = False): Thread.__init__(self) QObject.__init__(self) self.setName("Algoritmo V5") self.setDaemon(True) self.env_settings = QSettings() self.settings_model: SettingsModel = main_model.settings_model self.refresh: int = (lambda: self.settings_model.get_sync_time()) self.running = running self.notification_controller = notification_controller # set istanza di NetworkModel nei moduli per poter gestire i segnali di errore tree_builder.set_model(main_model.network_model) os_handler.set_network_model(main_model.network_model) os_handler.set_settings_model(main_model.settings_model) self.main_model = main_model self.compare_snap_client = CompareSnapClient() self.strategy: dict[Policy, Strategy] = { Policy.Client: ClientStrategy(), Policy.Manual: ManualStrategy() } self.logger = logging.getLogger("decision_engine") self.condition = Condition()
async def getModInformation(md5hash: str) -> list: settings = QSettings() apikey = str(settings.value('nexusAPIKey', '')) if not apikey: raise NoAPIKeyError() try: info: Response = await getSession().get( f'{__modsUrl}/md5_search/{md5hash}.json', headers={ 'apikey'.encode('ascii'): apikey.strip().encode('ascii', 'backslashreplace') }, timeout=5.0) except HTTPStatusError as e: raise RequestError(request=e.request, response=e.response, kind=str(e)) except HTTPError as e: raise RequestError(request=e.request, response=None, kind=str(e)) if info.status_code == 429: raise RequestLimitReachedError() if info.status_code == 404: raise NotFoundError(f'No file with hash {md5hash} found') if info.status_code == 401: raise UnauthorizedError() if info.status_code != 200: raise ResponseError(f'Unexpected response: Status {info.status_code}') json = info.json() if not isinstance(json, list): raise ResponseContentError( f'Unexpected response: expected list, got {type(json).__name__}') return json
def load_settings(self): self.settings = QSettings() check_state = self.settings.value('view/image_gallery', True, type=bool) self.action_image_gallery.setChecked(check_state) self.image_gallery_triggered()
async def downloadFile(url: str, target: Path) -> None: settings = QSettings() apikey = settings.value('nexusAPIKey', '') if not apikey: raise NoAPIKeyError() await asyncio.get_running_loop().run_in_executor( None, partial(downloadFileSync, url, target, apikey))
async def getModFileUrls(modid: int, fileid: int) -> list: settings = QSettings() apikey = str(settings.value('nexusAPIKey', '')) if not apikey: raise NoAPIKeyError() try: files: Response = await getSession().get( f'{__modsUrl}/{modid}/files/{fileid}/download_link.json', headers={ 'apikey'.encode('ascii'): apikey.strip().encode('ascii', 'backslashreplace') }, timeout=5.0) except HTTPStatusError as e: raise RequestError(request=e.request, response=e.response, kind=str(e)) except HTTPError as e: raise RequestError(request=e.request, response=None, kind=str(e)) if files.status_code == 429: raise RequestLimitReachedError() if files.status_code == 404: raise NotFoundError(f'No mod with id {modid} found') if files.status_code == 403: raise NoPremiumMembershipException() if files.status_code == 401: raise UnauthorizedError() if files.status_code != 200: raise ResponseError(f'Unexpected response: Status {files.status_code}') json = files.json() if not isinstance(json, list): raise ResponseContentError( f'Unexpected response: expected list, got {type(json).__name__}') return json
def get_or_create_folder_id(path: str) -> str: """Ritorna l'id della cartella dove vuoi inserire il file, se non presente ne crea una""" env_settings = QSettings() path_folder = env_settings.value("sync_path") if os.path.isfile(path): dir_path = os.path.dirname(path) else: dir_path = path result = os.path.relpath(dir_path, path_folder) node_name = result.split(os.sep) # Elimino il punto che mette se siamo nello stesso livello node_name = [name for name in node_name if name != "."] current_node = tree_builder.get_tree_from_node_id() index = 0 for name in node_name: trovato = False for node in current_node.get_children(): if node.get_name() == name: current_node = node trovato = True break if not trovato and index < len(node_name): id_new_folder = os_handler.create_folder( name, current_node.get_payload().id) current_node = tree_builder.get_tree_from_node_id(id_new_folder) index = index + 1 return current_node.get_payload().id
async def headerChangedEvent(self) -> None: settings = QSettings() state = self.horizontalHeader().saveState() # call later to work around pyqt5 StopIteration exception asyncio.get_running_loop().call_later( 25 / 1000.0, lambda: settings.setValue('modlistHorizontalHeaderState', state))
def start(ctx, mock=False, clean=False): """start the w3modmanager application""" from tests.framework import _mockdata, _root import w3modmanager import w3modmanager.__main__ _testdata = _root.joinpath('testdata') if clean: print('cleaning up testdata...') rmtree(_testdata, ignore_errors=True) git = which('git') if git: hash = subprocess.run([git, 'rev-parse', '--short=7', 'HEAD'], capture_output=True).stdout if hash: w3modmanager.VERSION_HASH = str(hash, 'utf-8').strip() date = subprocess.run([git, 'show', '-s', '--format=%cI', 'HEAD'], capture_output=True).stdout if date: date = datetime.fromisoformat(str(date, 'utf-8').strip()).astimezone(timezone.utc).isoformat() date = date[:10].replace('-', '.') w3modmanager.VERSION = date if mock: from PySide6.QtCore import QSettings print('setting up testdata...') copy_tree(str(_mockdata), str(_testdata)) QSettings.setDefaultFormat(QSettings.IniFormat) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, str(_testdata.joinpath('settings'))) w3modmanager.__main__.main(_testdata.joinpath('programs'), _testdata.joinpath('documents')) else: w3modmanager.__main__.main()
class LoginScreenTest(default_code.DefaultCode): def setUp(self) -> None: super().setUp() self.model = MainModel() self.env_settings = QSettings() self.env_settings.setValue("Credentials/password", None) self.env_settings.setValue("Credentials/user", None) self.login_controller = LoginController(self.model, None) self.login_test = self.login_controller.login_screen def tearDown(self) -> None: super().tearDown() def test_default(self): self.assertEqual(self.login_test.get_user(), self.login_test.model.get_username()) self.assertEqual(self.login_test.get_psw(), "") @patch('src.model.network_model.NetworkModel.login', return_value=True) def test_login(self, mock_login): self.login_test.login_button.click() mock_login.assert_called_once() def test_login_fail_slot_exists(self): self.login_test.Sl_login_fail() @patch('src.model.network_model.NetworkModel.is_logged', return_value=True) def test_model_changed(self, mock_is_logged): self.login_test.Sl_model_changed() mock_is_logged.assert_called_once()
def __init__(self): super(Watcher, self).__init__() """ Constructor for Watcher class, used to setup some public variables(path) and hidden :param path: the path that the watchdog will observe """ # connect # could be deleted, for now it's just to avoid Exceptions when turning # off self.observer = Observer() env_settings = QSettings() self.path = lambda: env_settings.value("sync_path") # Debug < Info < Warning < Error so setting debug will get everything # I need to create a new logger cuz davide's logger is root log self.logger = logging.getLogger("watchdog") self.logger.setLevel(logging.WARNING) formatter = logging.Formatter( '%(asctime)s:%(levelname)s:%(pathname)s:%(process)d:%(message)s') file_handler = logging.FileHandler('log.mer') file_handler.setFormatter(formatter) self.logger.addHandler(file_handler)
def notifySend(message1, message2, time, sound, parent=None): if os_type == OS.LINUX: notifications_path = '/usr/share/sounds/freedesktop/stereo/' elif os_type in OS.BSD_FAMILY: notifications_path = '/usr/local/share/sounds/freedesktop/stereo/' else: notifications_path = '' if sound == 'ok': file = os.path.join(notifications_path, 'complete.oga') playNotification(str(file)) elif sound == 'fail': file = os.path.join(notifications_path, 'dialog-error.oga') playNotification(str(file)) elif sound == 'warning': file = os.path.join(notifications_path, 'bell.oga') playNotification(str(file)) elif sound == 'critical': file = os.path.join(notifications_path, 'power-plug.oga') playNotification(str(file)) elif sound == 'queue': file = os.path.join(notifications_path, 'dialog-information.oga') playNotification(str(file)) # load settings persepolis_setting = QSettings('persepolis_download_manager', 'persepolis') enable_notification = persepolis_setting.value('settings/notification') time = str(time) message1 = str(message1) message2 = str(message2) # using Qt notification or Native system notification if enable_notification == 'QT notification': parent.system_tray_icon.showMessage(message1, message2, QIcon.fromTheme('persepolis-tray', QIcon(':/persepolis-tray.svg')), 10000) else: if os_type in OS.UNIX_LIKE: subprocess.Popen(['notify-send', '--icon', 'persepolis', '--app-name', 'Persepolis Download Manager', '--expire-time', time, message1, message2], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False) elif os_type == OS.OSX: notifyMac("Persepolis Download Manager", message1, message2) elif os_type == OS.WINDOWS: message = Windows_Notification(parent=parent, time=time, text1=message1, text2=message2, persepolis_setting=persepolis_setting) message.show()
def setUp(self) -> None: super().setUp() self.model = MainModel() self.env_settings = QSettings() self.env_settings.setValue("Credentials/password", None) self.env_settings.setValue("Credentials/user", None) self.login_controller = LoginController(self.model, None) self.login_test = self.login_controller.login_screen
def playNotification(file): # getting user setting from persepolis_setting persepolis_setting = QSettings('persepolis_download_manager', 'persepolis') # enabling or disabling notification sound in persepolis_setting enable_notification = str(persepolis_setting.value('settings/sound')) # volume of notification in persepolis_setting(an integer between 0 to 100) volume_percent = int(persepolis_setting.value('settings/sound-volume')) # Paplay volume value must be between 0 (silent) and 65536 (100% volume) volume = int((65536 * volume_percent) / 100) if enable_notification == 'yes': if os_type in OS.UNIX_LIKE: pipe = subprocess.Popen( ['paplay', '--volume=' + str(volume), str(file)], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False) answer = pipe.wait() if answer != 0: logger.sendToLog( "paplay not installed!Install it for playing sound notification", "WARNING") elif os_type == OS.OSX: pipe = subprocess.Popen([ 'osascript', '-e', 'set', 'volume', 'alert', 'volume', str(volume) ], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False) pipe = subprocess.Popen(['osascript', '-e', 'beep', '3'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False) elif os_type == OS.WINDOWS: CREATE_NO_WINDOW = 0x08000000 subprocess.Popen(['rundll32', 'user32.dll,MessageBeep'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False, creationflags=CREATE_NO_WINDOW)
def __init__(self, create_key): assert (create_key == NetworkModel.__create_key), \ "NetworkModel objects must be created using NetworkModel.get_instance()" super(NetworkModel, self).__init__(None) super(Api, self).__init__() self.api_implementation = ApiImplementation() self.env_settings = QSettings() self.lock = Lock()
def __init__(self, create_key): assert (create_key == FileModel.__create_key), \ "FileModel objects must be created using FileModel.get_instance()" super(FileModel, self).__init__() self.settings = QSettings() path = self.settings.value("sync_path") if os.path.isdir(path): self.tree = tree_builder.get_tree_from_system(path) self.current_folder = LocalDirectory(self.tree) self.previous_folder = None
class Settings(object): def __init__(self) -> None: self._settings = QSettings('Evelyn Reminder', 'Evelyn Desktop') @staticmethod def _key( section: str, option: str ) -> str: return f'{section}/{option}' def set( self, section: str, option: str, value: Any ) -> None: key = self._key(section, option) self._settings.setValue(key, value) def get( self, section: str, option: str, default: Any = None, type_: Optional[Type] = None ) -> Any: # make key for QSettings key = self._key(section, option) # check not present if not self._settings.contains(key): return default # get value value = self._settings.value(key) # parse special values if type_ is bool: return self._parse_bool(value) # check type if not isinstance(value, type_): return default # done return value @staticmethod def _parse_bool( value: str ) -> Optional[bool]: if value == 'true': return True if value == 'false': return False return None
def __init__(self, owner): super(self.__class__, self).__init__() Ui_Setting.__init__(self) self.setupUi(self) self.settings = QSettings('config.ini', QSettings.IniFormat) # self.setWindowModality(Qt.ApplicationModal) self.mainSize = QSize(1500, 1100) self.bookSize = QSize(900, 1020) self.readSize = QSize(1120, 1020) self.userId = "" self.passwd = "" self.gpuInfos = [] self.translate = QTranslator()
def __init__(self, app: QApplication, model: MainModel): # initialize settings self.env_settings = QSettings() self.app = app self.model = model self.view = None self.sync_controller = None self.file_controller = None self.remote_file_controller = None self.settings_controller = None self.notification_controller = None self.watcher = None self.algoritmo = None
def _select_models_path(self): print('Selecting models path... ', end='', flush=True) settings = QSettings() models_path = QFileDialog.getExistingDirectory( parent=self, caption='Select models directory', dir=QStandardPaths.standardLocations( QStandardPaths.AppDataLocation).pop(), ) if models_path != '': settings.setValue(self._models_path_key, str(models_path)) self._models_path = Path(models_path) print(models_path) else: print('canceled')
def read_settings(): """Read application settings. Returns ------- settings : dict Settings values. """ settings = {} settings["recent"] = QSettings().value("recent", []) settings["toolbar"] = QSettings().value("toolbar", True) settings["statusbar"] = QSettings().value("statusbar", True) settings["size"] = QSettings().value("size", QSize(700, 500)) settings["pos"] = QSettings().value("pos", QPoint(100, 100)) return settings
def openSelectedFiles(self): failedToOpen = [] files = set() for index in self.tree.selectionModel().selectedIndexes(): if self.model.fileInfo(index).isFile(): files.add(self.model.fileInfo(index).absoluteFilePath()) for filename in files: QSettings().setValue("triage/recentFile", filename) f = FileContext.openFilename(filename) if not f: failedToOpen.append(filename) continue for data in f.getAllDataViews(): Settings().set_string("analysis.mode", Settings().get_string("triage.analysisMode"), data) Settings().set_bool("triage.preferSummaryView", True, data) if data.view_type != "Raw": linearSweepMode = Settings().get_string("triage.linearSweep") if linearSweepMode == "none": Settings().set_bool("analysis.linearSweep.autorun", False, data) elif linearSweepMode == "partial": Settings().set_bool("analysis.linearSweep.autorun", True, data) Settings().set_bool("analysis.linearSweep.controlFlowGraph", False, data) elif linearSweepMode == "full": Settings().set_bool("analysis.linearSweep.autorun", True, data) Settings().set_bool("analysis.linearSweep.controlFlowGraph", True, data) self.context.openFileContext(f) if len(failedToOpen) > 0: QMessageBox.critical(self, "Error", "Unable to open:\n" + "\n".join(failedToOpen))
def showSettingsDialog(self: Any, firstStart: bool = False) -> SettingsWindow: settings = QSettings() settingswindow = SettingsWindow(self, firstStart) settingswindow.setAttribute(Qt.WA_DeleteOnClose) settingswindow.setModal(True) settingswindow.open() settingswindow.finished.connect(lambda: [ self.model.setPaths(Path(str(settings.value('gamePath'))), Path(str(settings.value('configPath')))), self.mainwidget.startscriptmerger.setEnabled( verifyScriptMergerPath( Path(str(settings.value('scriptMergerPath')))) is not None) ]) return settingswindow
def open_property_list(self): file_name, _ = QFileDialog.getOpenFileName(self, "Open Property List", '', "Property List Files (*.plist)") if file_name: settings = QSettings(file_name, QSettings.NativeFormat) self.set_settings_object(settings) self.fallbacks_action.setEnabled(False)
def copyBufferChangedEvent(self) -> None: if QSettings().value('nexusCheckClipboard', 'False') == 'True': clipboard = QApplication.clipboard().text().splitlines() if len(clipboard) == 1 and isValidNexusModsUrl(clipboard[0]): # TODO: enhancement: only allow one download window at once self.show() self.setWindowState(Qt.WindowActive) self.activateWindow() self.showDownloadModDialog()
def open_registry_path(self): path, ok = QInputDialog.getText(self, "Open Registry Path", "Enter the path in the Windows registry:", QLineEdit.Normal, 'HKEY_CURRENT_USER\\') if ok and path != '': settings = QSettings(path, QSettings.NativeFormat) self.set_settings_object(settings) self.fallbacks_action.setEnabled(False)
def __init__(self): """ Constructor """ self.receive_attempts = 0 self.settings = QSettings("gui.ini", QSettings.IniFormat) self.blurrer = None super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.restore() self.load_weights_options() self.ui.button_source.clicked.connect(self.button_source_clicked) self.ui.button_start.clicked.connect(self.button_start_clicked) self.ui.button_target.clicked.connect(self.button_target_clicked) self.ui.button_abort.clicked.connect(self.button_abort_clicked) self.ui.combo_box_weights.currentIndexChanged.connect( self.setup_blurrer)
def check_node_still_exists(path: str) -> Optional[str]: """Ritorna un id se un nodo รจ presente, None altrimenti""" env_settings = QSettings() path_folder = env_settings.value("sync_path") result = os.path.relpath(path, path_folder) node_name = result.split(os.sep) current_node = tree_builder.get_tree_from_node_id() trovato = False for name in node_name: trovato = False for node in current_node.get_children(): if node.get_name() == name: current_node = node trovato = True break if trovato: return current_node.get_payload().id return None
def handle(self, *args, **kwargs): try: logger.debug(f"call {func.__name__}...") return func(self, *args, **kwargs) except ServerError as e: logger.debug(f"{func.__name__} exit with error: {str(e)}") # e' possibile che sia scaduto il login provo a rifarlo # e ritento la chiamata logger.debug(f"retry {func.__name__} with new login") env_settings = QSettings() user = env_settings.value("Credentials/user") password = env_settings.value("Credentials/password") api_impl = ApiImplementation() api_impl.login(user, password) return func(self, *args, **kwargs)
def load_preset(self): presets_dir = os.path.join(os.path.dirname(__file__), "presets") if not os.path.exists(presets_dir): os.makedirs(presets_dir) file = QFileDialog.getOpenFileName(self, SettingsWindow.LOAD_PRESET_TEXT, presets_dir, "Configuration files (*.ini)")[0] if file: settings = QSettings(file, QSettings.IniFormat) self.set_fields_from_settings(settings)