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 __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 __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
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 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))
def get_settings(game_state: GameState = None): settings = QSettings("Don Kirkby", "Zero Play") if game_state is not None: settings.beginGroup('games') settings.beginGroup(game_state.game_name.replace(' ', '_')) 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 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
def read_settings(self): settings = QSettings() settings.beginGroup(SETTINGS_MAIN_SECTION) if settings.value(SETTINGS_USE_CUSTOM_JAVA, SETTINGS_USE_CUSTOM_JAVA_DEFAULT, bool): self.ui.customJavaRadio.setChecked(True) else: self.ui.defaultJavaRadio.setChecked(True) self.ui.customJavaPathEdit.setText(settings.value(SETTINGS_CUSTOM_JAVA_PATH, SETTINGS_CUSTOM_JAVA_PATH_DEFAULT)) if settings.value(SETTINGS_USE_CUSTOM_PLANTUML, SETTINGS_USE_CUSTOM_PLANTUML_DEFAULT, bool): self.ui.customPlantUmlRadio.setChecked(True) else: self.ui.defaultPlantUmlRadio.setChecked(True) self.ui.customPlantUmlEdit.setText(settings.value(SETTINGS_CUSTOM_PLANTUML_PATH, SETTINGS_CUSTOM_PLANTUML_PATH_DEFAULT)) if settings.value(SETTINGS_USE_CUSTOM_GRAPHVIZ, SETTINGS_USE_CUSTOM_GRAPHVIZ_DEFAULT, bool): self.ui.customGraphvizRadio.setChecked(True) else: self.ui.defaultGraphvizRadio.setChecked(True) self.ui.customGraphvizEdit.setText(settings.value(SETTINGS_CUSTOM_GRAPHVIZ_PATH, SETTINGS_CUSTOM_GRAPHVIZ_PATH_DEFAULT)) settings.endGroup()
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 __init__(self, model: Model) -> None: super().__init__() self.model = model self.setWindowTitle(getTitleString('Mod Manager')) self.setMinimumSize(QSize(750, 500)) self.setupMenu() settings = QSettings() if settings.value('mainWindowGeometry'): self.restoreGeometry( settings.value('mainWindowGeometry')) # type: ignore if settings.value('mainWindowState'): self.restoreState( settings.value('mainWindowState')) # type: ignore # TODO: enhancement: add an url handler for 'nxm://' urls # see https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85) # noqa # TODO: enhancement: import settings from the witcher 3 mod manager QApplication.clipboard().dataChanged.connect( self.copyBufferChangedEvent) self.mainwidget = MainWidget(self, model) self.setCentralWidget(self.mainwidget) self.show() self.raise_() self.activateWindow()
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 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 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 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 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 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 sortByColumn(self, col: int, order: Qt.SortOrder, save: bool = True) -> None: # type: ignore if save and col is not None and order is not None: settings = QSettings() settings.setValue('modlistSortColumn', col) settings.setValue('modlistSortOrder', 0 if order == Qt.AscendingOrder else 1) super().sortByColumn(col, order)
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
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)
def open_settings(self): if self.location_dialog is None: self.location_dialog = LocationDialog(self) if self.location_dialog.exec_(): settings = QSettings(self.location_dialog.format(), self.location_dialog.scope(), self.location_dialog.organization(), self.location_dialog.application()) self.set_settings_object(settings) self.fallbacks_action.setEnabled(True)
def update_locations(self): self.locations_table.setUpdatesEnabled(False) self.locations_table.setRowCount(0) for i in range(2): if i == 0: if self.scope() == QSettings.SystemScope: continue actualScope = QSettings.UserScope else: actualScope = QSettings.SystemScope for j in range(2): if j == 0: if not self.application(): continue actualApplication = self.application() else: actualApplication = '' settings = QSettings(self.format(), actualScope, self.organization(), actualApplication) row = self.locations_table.rowCount() self.locations_table.setRowCount(row + 1) item0 = QTableWidgetItem() item0.setText(settings.fileName()) item1 = QTableWidgetItem() disable = not (settings.childKeys() or settings.childGroups()) if row == 0: if settings.isWritable(): item1.setText("Read-write") disable = False else: item1.setText("Read-only") self.button_box.button(QDialogButtonBox.Ok).setDisabled(disable) else: item1.setText("Read-only fallback") if disable: item0.setFlags(item0.flags() & ~Qt.ItemIsEnabled) item1.setFlags(item1.flags() & ~Qt.ItemIsEnabled) self.locations_table.setItem(row, 0, item0) self.locations_table.setItem(row, 1, item1) self.locations_table.setUpdatesEnabled(True)
def write_settings(self): settings = QSettings() settings.beginGroup(SETTINGS_MAIN_SECTION) settings.setValue(SETTINGS_USE_CUSTOM_JAVA, self.ui.customJavaRadio.isChecked()) settings.setValue(SETTINGS_CUSTOM_JAVA_PATH, self.ui.customJavaPathEdit.text()) settings.setValue(SETTINGS_USE_CUSTOM_PLANTUML, self.ui.customPlantUmlRadio.isChecked()) settings.setValue(SETTINGS_CUSTOM_PLANTUML_PATH, self.ui.customPlantUmlEdit.text()) settings.setValue(SETTINGS_USE_CUSTOM_GRAPHVIZ, self.ui.customGraphvizRadio.isChecked()) settings.setValue(SETTINGS_CUSTOM_GRAPHVIZ_PATH, self.ui.customGraphvizEdit.text()) settings.endGroup()
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 saveEvent(self) -> None: settings = QSettings() settings.setValue('settingsWindowGeometry', self.saveGeometry()) settings.setValue('gamePath', self.gamePath.text()) settings.setValue('configPath', self.configPath.text()) settings.setValue('scriptMergerPath', self.scriptMergerPath.text()) settings.setValue('nexusAPIKey', self.nexusAPIKey.text()) settings.setValue('nexusGetInfo', str(self.nexusGetInfo.isChecked())) settings.setValue('nexusCheckUpdates', str(self.nexusCheckUpdates.isChecked())) settings.setValue('nexusCheckClipboard', str(self.nexusCheckClipboard.isChecked())) settings.setValue('debugOutput', str(self.debugOutput.isChecked())) settings.setValue('unhideOutput', str(self.unhideOutput.isChecked())) self.close()