def __init__(self, parent, view=None, usage_reporting_verification_view = None): self.view = view if view else AboutView(parent, self, version_str(), release_date().strip()) self.usage_reporting_verification_view = usage_reporting_verification_view \ if usage_reporting_verification_view else UsageReportingVerificationView(parent, self) self.parent = parent self.view.clbReleaseNotes.clicked.connect(self.action_open_release_notes) self.view.clbSampleDatasets.clicked.connect(self.action_open_download_website) self.view.clbMantidIntroduction.clicked.connect(self.action_open_mantid_introduction) self.view.clbPythonIntroduction.clicked.connect(self.action_open_python_introduction) self.view.clbPythonInMantid.clicked.connect(self.action_open_python_in_mantid) self.view.clbExtendingMantid.clicked.connect(self.action_open_extending_mantid) self.view.lblPrivacyPolicy.linkActivated.connect(self.action_open_external_link) self.view.pbMUD.clicked.connect(self.action_manage_user_directories) self.view.pbClose.clicked.connect(self.action_close) self.setup_facilities_group() # set chkAllowUsageData isUsageReportEnabled = ConfigService.getString(self.USAGE_REPORTING, True) if isUsageReportEnabled == "0": self.view.chkAllowUsageData.setChecked(False) self.view.chkAllowUsageData.stateChanged.connect(self.action_usage_data_changed) # set do not show qSettings = QSettings() qSettings.beginGroup(self.DO_NOT_SHOW_GROUP) doNotShowUntilNextRelease = int(qSettings.value(self.DO_NOT_SHOW, "0")) qSettings.endGroup() self.view.chkDoNotShowUntilNextRelease.setChecked(doNotShowUntilNextRelease) self.view.chkDoNotShowUntilNextRelease.stateChanged.connect(self.action_do_not_show_until_next_release)
def test_get_setting_with_int(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", 10) settings.endGroup() self.assertEqual(get_setting(GROUP, PREFIX, "something", return_type=int), 10)
def get_setting(group, prefix, setting_name, return_type=str): """ Get a setting from the .ini file of mantid settings. NOTE: If you specify an int, but the setting contains a bool, you will get 0 for False and 1 for True, without a warning. Specifying bool will raise a TypeError if anything other than a bool or empty string is found in the settings. Not specifying a type will return a string. If nothing is found then an empty string is returned. :param group: Settings group to pull from. :param prefix: The prefix of the setting, acts like a subgroup. :param setting_name: Name of the setting. :param return_type: The type of the setting to get. :return: The chosen setting. """ settings = QSettings() settings.beginGroup(group) if return_type is bool: setting = settings.value(prefix + setting_name, type=str) if setting == "": pass elif setting == "true": setting = True elif setting == "false": setting = False else: raise TypeError("Unable to convert string into valid bool") else: setting = settings.value(prefix + setting_name, type=return_type) settings.endGroup() return setting
def test_get_setting_with_string(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", "value") settings.endGroup() self.assertEqual(get_setting(GROUP, PREFIX, "something"), "value")
def test_get_setting_with_bool_true(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", True) settings.endGroup() self.assertEqual(get_setting(GROUP, PREFIX, "something", return_type=bool), True)
def test_get_setting_string_specifying_bool(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", "a") settings.endGroup() self.assertRaises(TypeError, get_setting, GROUP, PREFIX, "something", return_type=bool)
def test_get_setting_bool_without_specifying_type(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", True) settings.endGroup() self.assertEqual(get_setting(GROUP, PREFIX, "something"), "true")
def load_default_file(line_edit_field, q_settings_group_key, q_settings_key): settings = QSettings() settings.beginGroup(q_settings_group_key) default_file = settings.value(q_settings_key, "", type=str) settings.endGroup() line_edit_field.setText(default_file)
def _load_property(q_settings_group_key, q_settings_key): settings = QSettings() settings.beginGroup(q_settings_group_key) default_property = settings.value(q_settings_key, "", type=str) settings.endGroup() return default_property
def should_show_on_startup(): """ Determines if the first time dialog should be shown :return: True if the dialog should be shown """ # first check the facility and instrument facility = ConfigService.getString(AboutPresenter.FACILITY) instrument = ConfigService.getString(AboutPresenter.INSTRUMENT) if not facility: return True else: # check we can get the facility and instrument try: facilityInfo = ConfigService.getFacility(facility) instrumentInfo = ConfigService.getInstrument(instrument) logger.information("Default facility '{0}', instrument '{1}'\n".format(facilityInfo.name(), instrumentInfo.name())) except RuntimeError: # failed to find the facility or instrument logger.error("Could not find your default facility '{0}' or instrument '{1}' in facilities.xml, " + "showing please select again.\n".format(facility, instrument)) return True settings = QSettings() settings.beginGroup(AboutPresenter.DO_NOT_SHOW_GROUP) doNotShowUntilNextRelease =int(settings.value(AboutPresenter.DO_NOT_SHOW, '0')) lastVersion = settings.value(AboutPresenter.LAST_VERSION, "") settings.endGroup() if not doNotShowUntilNextRelease: return True # Now check if the version has changed since last time version = release_notes_url() return version != lastVersion
def load_property(q_settings_group_key, q_settings_key, type=str): settings = QSettings() settings.beginGroup(q_settings_group_key) default = False if type == bool else "" default_property = settings.value(q_settings_key, default, type=type) settings.endGroup() return default_property
def test_set_setting_with_string(self): set_setting(GROUP, PREFIX, "something", "value") settings = QSettings() settings.beginGroup(GROUP) returned = settings.value(PREFIX + "something") settings.endGroup() self.assertEqual(returned, "value")
def test_set_setting_with_int(self): set_setting(GROUP, PREFIX, "something", 10) settings = QSettings() settings.beginGroup(GROUP) returned = settings.value(PREFIX + "something", type=int) settings.endGroup() self.assertEqual(returned, 10)
def test_set_setting_with_bool_true(self): set_setting(GROUP, PREFIX, "something", True) settings = QSettings() settings.beginGroup("CustomInterfaces") returned = settings.value("EngineeringDiffraction2/" + "something", type=bool) settings.endGroup() self.assertEqual(returned, True)
def __setitem__(self, key, value): groupings = self._get_groups(key) key = groupings.pop() settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) settings.setValue(key, value) for g in groupings: settings.endGroup()
def clear_defaults(): """ Clear all settings in defaults group. Should only be run once during application start, as it will undo any defaults that have been set. """ settings = QSettings() settings.beginGroup('defaults') settings.remove("") settings.endGroup()
def __contains__(self, key): groupings = self._get_groups(key) key = groupings.pop() settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) r = settings.contains(key) for g in groupings: settings.endGroup() return r
def save_on_closing(self): # make sure the Last Version is updated on closing settings = QSettings() settings.beginGroup(self.DO_NOT_SHOW_GROUP) settings.setValue(self.LAST_VERSION, release_notes_url()) settings.endGroup() self.store_facility(self.view.cb_facility.currentText()) self.action_instrument_changed(self.view.cb_instrument.currentText()) ConfigService.saveConfig(ConfigService.getUserFilename()) self.parent.config_updated()
def action_close(self): # make sure the Last Version is updated on closing settings = QSettings() settings.beginGroup(self.DO_NOT_SHOW_GROUP) settings.setValue(self.LAST_VERSION, release_notes_url()) settings.endGroup() ConfigService.saveConfig(ConfigService.getUserFilename()) self.parent.config_updated() self.view.close()
def restoreSettings(self, s=None): if s is None: s = QSettings() guess = self.parameterTable.guess() s.beginGroup('HangingModel') for key in guess: guess[key] = s.value(key, type=float) s.endGroup() #print('Restoring settings:', guess) self.parameterTable.setGuess(guess)
def write(self, d, group=None, settings=None): if settings is None: settings = QSettings(self) if group is not None: settings.beginGroup(group) for k, v in d.items(): settings.setValue(k, v) if group is not None: settings.endGroup()
def saveSettings(self, s=None): if s is None: s = QSettings() ps = self.parameterTable.guess() s.beginGroup('HangingModel') for key in ps: #print('Saving value:', key) s.setValue(key, ps[key]) s.endGroup()
def save_on_closing(self): # make sure the Last Version is updated on closing settings = QSettings() settings.beginGroup(self.DO_NOT_SHOW_GROUP) settings.setValue(self.PREVIOUS_VERSION, version().major + "." + version().minor) settings.endGroup() self.store_facility(self.view.about_widget.cb_facility.currentText()) self.action_instrument_changed( self.view.about_widget.cb_instrument.currentText()) ConfigService.saveConfig(ConfigService.getUserFilename()) self.parent.config_updated()
def read(self, d, group=None, settings=None): if settings is None: settings = QSettings(self) if group is not None: settings.beginGroup(group) for k, v in d.items(): if isinstance(v, tuple): settings.value(k, v) if group is not None: settings.endGroup()
def save_settings(self): settings = QSettings("openMicroanalysis", "xrayspectrumanalyzergui") # print(settings.fileName()) settings.beginGroup("MainWindow") settings.setValue("geometry", self.saveGeometry()) settings.setValue("window_state", self.saveState()) settings.endGroup() settings.beginGroup("graphic_settings_dock") settings.setValue("visible", self.graphic_settings_dock.isVisible()) settings.endGroup()
def set_setting(group, prefix, setting_name, value): """ Change or add a setting in the mantid .ini file. :param group: Settings group to pull from. :param prefix: Acts like a subgroup. :param setting_name: The key to the setting. :param value: The value of the setting. """ settings = QSettings() settings.beginGroup(group) settings.setValue(prefix + setting_name, value) settings.endGroup()
def __init__(self, parent, view=None, usage_reporting_verification_view=None): self.view = view if view else AboutView(parent, self, str(version()), release_date().strip()) self.usage_reporting_verification_view = usage_reporting_verification_view \ if usage_reporting_verification_view else UsageReportingVerificationView(parent, self) self.parent = parent about_widget = self.view.about_widget about_widget.clb_release_notes.clicked.connect( self.action_open_release_notes) about_widget.clb_sample_datasets.clicked.connect( self.action_open_download_website) about_widget.clb_mantid_introduction.clicked.connect( self.action_open_mantid_introduction) about_widget.clb_python_introduction.clicked.connect( self.action_open_python_introduction) about_widget.clb_python_in_mantid.clicked.connect( self.action_open_python_in_mantid) about_widget.clb_extending_mantid.clicked.connect( self.action_open_extending_mantid) about_widget.lbl_privacy_policy.linkActivated.connect( self.action_open_external_link) about_widget.pb_manage_user_directories.clicked.connect( self.action_manage_user_directories) about_widget.pb_close.clicked.connect(self.action_close) self.setup_facilities_group() # set chk_allow_usage_data isUsageReportEnabled = ConfigService.getString(self.USAGE_REPORTING, True) if isUsageReportEnabled == "0": about_widget.chk_allow_usage_data.setChecked(False) about_widget.chk_allow_usage_data.stateChanged.connect( self.action_usage_data_changed) # set do not show qSettings = QSettings() qSettings.beginGroup(self.DO_NOT_SHOW_GROUP) doNotShowUntilNextRelease = qSettings.value(self.DO_NOT_SHOW, 0, type=int) qSettings.endGroup() about_widget.chk_do_not_show_until_next_release.setChecked( doNotShowUntilNextRelease) about_widget.chk_do_not_show_until_next_release.stateChanged.connect( self.action_do_not_show_until_next_release)
def restore_key_default(self, key): """ Restore a given setting to its default value. """ groupings = self._get_groups(key) groupings.insert(0, 'defaults') inner_key = groupings.pop() settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) default_value = settings.value(inner_key) for g in groupings: settings.endGroup() self[key] = default_value
def load_file(line_edit_field, filter_for_dialog, q_settings_group_key, q_settings_key, func): # Get the last location of the user file settings = QSettings() settings.beginGroup(q_settings_group_key) last_path = settings.value(q_settings_key, "", type=str) settings.endGroup() # Open the dialog open_file_dialog(line_edit_field, filter_for_dialog, last_path) # Save the new location new_path, _ = os.path.split(func()) if new_path: set_setting(q_settings_group_key, q_settings_key, new_path)
def load_file(line_edit_field, filter_for_dialog, q_settings_group_key, q_settings_key, func_to_get_line_edit_val): # Get the last location of the user file settings = QSettings() settings.beginGroup(q_settings_group_key) last_path = settings.value(q_settings_key, "", type=str) settings.endGroup() # Open the dialog open_file_dialog(line_edit_field, filter_for_dialog, last_path) # Save the new location new_path = func_to_get_line_edit_val() if new_path: set_setting(q_settings_group_key, q_settings_key, new_path)
def get_enum_hint(self, key): """ Returns the possible enum hint values if set, otherwise None. """ groupings = self._get_groups(key) groupings.insert(0, 'defaults') key = groupings.pop() key = '_' + key + '_options' # Change key to avoid conflicts settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) value = settings.value(key) for g in groupings: settings.endGroup() return value
def set_default(self, key, value): """ Sets default value by writing into defaults group. """ # If not in normal settings, set it: if key not in self: self[key] = value # Either way, write to defaults group groupings = self._get_groups(key) groupings.insert(0, 'defaults') key = groupings.pop() settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) settings.setValue(key, value) for g in groupings: settings.endGroup()
def set_enum_hint(self, key, options): """ Indicate possible values for a setting. The `options` are not strictly enforced, but can be used to indicate valid values to the user. A typical usecase is to allow the use of a combobox in a dialog to pick a value. """ groupings = self._get_groups(key) groupings.insert(0, 'defaults') key = groupings.pop() key = '_' + key + '_options' # Change key to avoid conflicts settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) if not isinstance(options, list): options = list(options) settings.setValue(key, options) for g in groupings: settings.endGroup()
def __getitem__(self, key): if isinstance(key, tuple): key, t = key else: t = None groupings = self._get_groups(key) if key not in self: groupings.insert(0, 'defaults') key = groupings.pop() settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) ret = settings.value(key) if t and isinstance(t, type) and not isinstance(ret, t): if t is bool: ret = ("true" == ret.lower()) else: ret = t(ret) for g in groupings: settings.endGroup() return ret
def set_setting(self, q_settings_key, value): settings = QSettings() settings.beginGroup(self.__generic_settings) settings.setValue(q_settings_key, value) settings.endGroup()
def set_setting(q_settings_group_key, q_settings_key, value): settings = QSettings() settings.beginGroup(q_settings_group_key) settings.setValue(q_settings_key, value) settings.endGroup()
class UserConfig(object): """Holds user configuration option. Options are assigned a section and a key must only be unique within a section. Uses QSettings for the heavy lifting. All platforms use the Ini format at UserScope """ # The raw QSettings instance qsettings = None def __init__(self, organization, application, defaults=None): """ :param organization: A string name for the organization :param application: A string name for the application name :param defaults: Default configuration values for this instance in the form of nested dict instances """ # Loads the saved settings if found self.qsettings = QSettings(QSettings.IniFormat, QSettings.UserScope, organization, application) # convert the defaults into something that qsettings can handle default_settings = self._flatten_defaults(defaults) # put defaults into qsettings if they weren't there already try: self.set_qsettings_values(default_settings) # the editors/sessiontabs are pickled in config so need to remove them except ValueError: self.qsettings.remove('Editors/SessionTabs') self.set_qsettings_values(default_settings) # fixup the values of booleans - they do not evaluate correctly when read from the config file for key in self.all_keys(): try: value = self.get(key) except KeyError: continue if value == 'true': self.set(key, True) elif value == 'false': self.set(key, False) def set_qsettings_values(self, default_settings): configFileKeys = self.qsettings.allKeys() for key in default_settings.keys(): if key not in configFileKeys: self.qsettings.setValue(key, default_settings[key]) def all_keys(self, group=None): if group is not None: self.qsettings.beginGroup(group) result = self.qsettings.allKeys() self.qsettings.endGroup() else: result = self.qsettings.allKeys() return result @property def filename(self): return self.qsettings.fileName() def get(self, option, second=None): """Return a value for an option. If two arguments are given the first is the group/section and the second is the option within it. ``config.get('main', 'window/size')`` is equivalent to ``config.get('main/window/size')`` If no option is found then a KeyError is raised """ option = self._check_section_option_is_valid(option, second) value = self.qsettings.value(option) # qsettings appears to return None if the option isn't found if value is None: raise KeyError('Unknown config item requested: "{}"'.format(option)) else: return value def has(self, option, second=None): """Return a True if the key exists in the settings. ``config.get('main', 'window/size')`` and ``config.get('main/window/size')`` are equivalent. """ option = self._check_section_option_is_valid(option, second) return option in self.all_keys() def set(self, option, value, extra=None): """Set a value for an option in a given section. Can either supply the fully qualified option or add the section as an additional first argument. ``config.set('main', 'high_dpi_scaling', True)`` is equivalent to ``config.set('main/high_dpi_scaling', True)`` """ if extra is None: option = self._check_section_option_is_valid(option, extra) # value is in the right place else: option = self._check_section_option_is_valid(option, value) value = extra self.qsettings.setValue(option, value) def remove(self, option, second=None): """Removes a key from the settings. Key not existing returns without effect. """ option = self._check_section_option_is_valid(option, second) if self.has(option): self.qsettings.remove(option) # ------------------------------------------------------------------------- # "Private" methods # ------------------------------------------------------------------------- @staticmethod def _flatten_defaults(input_dict): result = {} for key in input_dict: value = input_dict[key] if isinstance(value, dict): value = UserConfig._flatten_defaults(value) for key_inner in value.keys(): result[joinsettings(key, key_inner)] = value[key_inner] else: result[key] = value return result def _check_section_option_is_valid(self, option, second): """ Sanity check the section and option are strings and return the flattened option key """ if second is None: if not is_text_string(option): raise TypeError('Found invalid type ({}) for option ({}) must be a string'.format(type(option), option)) return option else: # fist argument is actually the section/group if not is_text_string(option): raise TypeError('Found invalid type ({}) for section ({}) must be a string'.format(type(option), option)) if not is_text_string(second): raise TypeError('Found invalid type ({}) for option ({}) must be a string'.format(type(second), second)) return joinsettings(option, second)