Exemple #1
0
    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
        configFileKeys = self.qsettings.allKeys()
        for key in default_settings.keys():
            if key not in configFileKeys:
                self.qsettings.setValue(key, default_settings[key])

        # fixup the values of booleans - they do not evaluate correctly when read from the config file
        # TODO come up with a unit test for this
        for key in self.all_keys():
            value = self.get(key)
            if value == 'true':
                self.set(key, True)
            elif value == 'false':
                self.set(key, False)
Exemple #2
0
def main(argv: Sequence[str] = None) -> int:
    argv = argv if argv is not None else sys.argv

    command_line_args = parse_commandline(argv)
    exit_code_str = command_line_args.exit_code
    exit_code = int(exit_code_str)
    if mantid.config['usagereports.enabled'] != '1':
        return exit_code

    # On Windows/macOS the plugin locations need to be known before starting
    # QApplication
    if command_line_args.qtdir is not None:
        QCoreApplication.addLibraryPath(command_line_args.qtdir)

    # Qt resources must be imported before QApplication starts
    importlib.import_module(f'mantidqt.dialogs.errorreports.resources_qt{QT_VERSION[0]}')

    if sys.platform == 'darwin':
        qtutils.force_layer_backing_BigSur()

    from qtpy.QtWidgets import QApplication
    app = QApplication(argv)
    # The strings APPNAME, ORG_DOMAIN, ORGANIZATION are duplicated from workbench.config
    app.setOrganizationName(command_line_args.org_name)
    app.setOrganizationDomain(command_line_args.org_domain)
    app.setApplicationName(command_line_args.application)
    QSettings.setDefaultFormat(QSettings.IniFormat)
    form = CrashReportPage(show_continue_terminate=False)
    presenter = ErrorReporterPresenter(form, exit_code_str, command_line_args.application)
    presenter.show_view()
    app.exec_()

    return exit_code
Exemple #3
0
def repr_settings(settings: QSettings) -> str:
    """works on a QSettings, not a Settings"""
    msg = 'QSettings:\n'
    for key in sorted(settings.allKeys()):
        value = settings.value(key)
        msg += '    %r : %r\n' % (key, value)
    return msg
Exemple #4
0
 def setUpClass(cls):
     QCoreApplication.setApplicationName("test1")
     QCoreApplication.setOrganizationName("org1")
     QSettings.setDefaultFormat(QSettings.IniFormat)
     cls.settings_dir = tempfile.TemporaryDirectory()
     QSettings.setPath(QSettings.IniFormat, QSettings.UserScope,
                       cls.settings_dir.name)
Exemple #5
0
    def __init__(self, log=None):
        super().__init__()
        if log:
            self.log = log.getChild('Conf')
            self.log.setLevel(30)
        else:
            self.log = logging.getLogger()
            self.log.setLevel(99)
        self.log.debug('Initializing')
        self.qsettings = QSettings()
        self.qsettings.setIniCodec('UTF-8')

        self.options = None
        self.option_spec = self.load_option_spec()
        self.options = self.load_options()
        self.full_name = "{} {}".format(QCoreApplication.applicationName(),
                                        QCoreApplication.applicationVersion())

        # options that need fast access are also defined as attributes, which
        # are updated by calling update_attributes()
        # (on paper it's 4 times faster, but I don't think it matters in my case)
        self.logger_table_font = None
        self.logger_table_font_size = None
        self.logger_row_height = None
        self.benchmark_interval = None

        self.update_attributes()
Exemple #6
0
    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, TypeError):
                continue
            if value == 'true':
                self.set(key, True)
            elif value == 'false':
                self.set(key, False)
Exemple #7
0
    def __init__(self):
        super(MainWindowBase, self).__init__()
        # Environment path
        self.env = ""
        # Alignment mode
        self.alignment_mode = 0
        # Entities list
        self.vpoint_list = []
        self.vlink_list = [VLink(VLink.FRAME, 'White', (), color_rgb)]
        # Condition list of context menus
        self.context = _Context()
        # Preference
        self.prefer = Preferences()
        # Set path from command line
        home_dir = QDir.home()
        self.settings = QSettings(home_dir.absoluteFilePath(".pyslvs.ini"),
                                  QSettings.IniFormat, self)
        if ARGUMENTS.c:
            self.set_locate(QDir(ARGUMENTS.c).absolutePath())
        else:
            home_dir.cd("Desktop")
            env = self.settings.value("ENV", home_dir.absolutePath())
            self.set_locate(str(env))

        # Initialize custom UI
        self.__undo_redo()
        self.__appearance()
        self.__alignment()
        self.__free_move()
        self.__options()
        self.__context_menu()
Exemple #8
0
 def __fetchSettings(self):
     settings = QSettings("Equinor", "Ert-Gui")
     geo = settings.value("geometry")
     if geo:
         self.restoreGeometry(geo)
     wnd = settings.value("windowState")
     if wnd:
         self.restoreState(wnd)
    def _read_settings(self):
        self.logger.info("MainWindow._read_settings")

        settings = QSettings(ORGANIZATION_NAME, APPLICATION_NAME)
        pos = settings.value("pos", QPoint(200, 200))
        size = settings.value("size", QSize(400, 400))
        self.resize(size)
        self.move(pos)
Exemple #10
0
 def load_setting(self, key, default_value=None):
     settings = QSettings("QtGuiApplication", "%s_%s" % (self.app_name, self.__class__.__name__))
     setting = settings.value(self.ui_module.__name__ + "/" + key, default_value)
     try:
         setting = setting.toString()
     except:
         pass  #fails in pyside
     return str(setting)
Exemple #11
0
 def load_settings(self):
     settings = QSettings("QtGuiApplication", "%s_%s" % (self.app_name, self.__class__.__name__))
     geometry = settings.value(self.ui_module.__name__ + "/geometry")
     try:
         geometry = geometry.toByteArray()
     except:
         pass  # Fails in PySide
     if geometry:
         self.restoreGeometry(geometry)
 def __init__(self, parent, app_settings):
     super().__init__(parent)
     self._log = logging.getLogger(__name__)
     self._settings = QSettings()
     self._app_settings = app_settings
     self._load_ui()
     # Flag indicating whether the user has requested the GUI settings to be reset.
     # If so, the caller should disable any further settings recording logic
     self.cleared = False
Exemple #13
0
 def __init__(self, settings=None):
     """
         Initialization.
         @param settings: QSettings object passed by the main application
     """
     super(GeneralSettings, self).__init__()
     if settings is not None:
         self._settings = settings
     else:
         self._settings = QSettings()
Exemple #14
0
 def hide_hidden_columns(self):
     hidden_columns = QSettings().value("catalog.columns.hidden") or set()
     header = self.horizontalHeader()
     current_column_names = [
         str(self.model().headerData(i, Qt.Horizontal))
         for i in range(header.count())
     ]
     current_hidden_names = hidden_columns.intersection(
         set(current_column_names))
     for name in current_hidden_names:
         header.setSectionHidden(current_column_names.index(name), True)
Exemple #15
0
 def hide_column(self, header, logicalIndex):
     '''
     Hide a column, adding the column from the list of hidden columns in QSettings
     '''
     hidden_columns = QSettings().value("catalog.columns.hidden") or set()
     if len(hidden_columns) == header.count() - 1:
         msg.notifyMessage(
             "Only one column is left to hide, cannot hide all of them.")
         return
     hidden_columns.add(self._current_column_name(header, logicalIndex))
     QSettings().setValue("catalog.columns.hidden", hidden_columns)
     header.setSectionHidden(logicalIndex, True)
Exemple #16
0
    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)
        self.defaults = defaults
Exemple #17
0
    def openModel(self, fileName):
        print(f'Otwieram: {fileName}')
        self.__m_vtkFboItem.addModel(fileName)

        localFilePath = QUrl(fileName).toLocalFile()

        currentDir = QFileInfo(localFilePath).absoluteDir()
        currentPath = currentDir.absolutePath()

        MySettings = QSettings()
        MySettings.setValue(CanvasHandler.DEFAULT_MODEL_DIR_KEY, currentPath)
        print(currentPath)
Exemple #18
0
    def _on_reset(self):
        """
        Callback for reset button. Prompts user for confirmation, then proceeds
        to reset settings to default values if confirmed, before updating
        controls and applying any changes (emits change signal if any changes).
        """
        mb = QMessageBox(
            QMessageBox.Warning, tr("Reset all settings"),
            tr("This will reset all settings to their default " +
               "values. Are you sure you want to continue?"),
            QMessageBox.Yes | QMessageBox.No)
        mb.setDefaultButton(QMessageBox.No)
        dr = mb.exec_()
        if dr == QMessageBox.Yes:
            # This clears all settings, and recreates only those values
            # initialized with set_default this session.
            Settings.restore_from_defaults()

            # Now we update controls:
            s = QSettings(self.ui)
            keys = list(
                self._initial_values.keys())  # Use copy, as we may modify
            for k in keys:
                # Check if setting is still present
                if s.contains(k):
                    # Present, update to new value (triggers _on_change)
                    v = s.value(k)
                    w = self._lut[k]
                    if isinstance(w, QLineEdit):
                        w.setText(v)
                    elif isinstance(w, QCheckBox):
                        w.setChecked(v.lower() == "true")
                    elif isinstance(w, (QSpinBox, QDoubleSpinBox)):
                        w.setValue(v)
                else:
                    # Setting was removed, remove editor
                    w = self._lut[k]
                    layout = w.parent().layout()
                    label = layout.labelForField(w)
                    layout.removeWidget(w)
                    w.close()
                    if label is not None:
                        layout.removeWidget(label)
                        label.close()
                    del self._lut[k]
                    del self._initial_values[k]
                    self._changes[k] = None
                    # Check whether all editors for tab was removed
                    if layout.count() == 0:
                        wrap = w.parent()
                        self.tabs.removeTab(self.tabs.indexOf(wrap))
            # Finally apply changes (update _initial_values, and emit signal)
            self.apply_changes()
class AboutDialog(QDialog):  # pylint: disable=too-many-instance-attributes
    """Logic for managing about box"""
    def __init__(self, parent, app_settings):
        super().__init__(parent)
        self._log = logging.getLogger(__name__)
        self._settings = QSettings()
        self._app_settings = app_settings
        self._load_ui()
        # Flag indicating whether the user has requested the GUI settings to be reset.
        # If so, the caller should disable any further settings recording logic
        self.cleared = False

    def _load_ui(self):
        """Internal helper method that configures the UI for the dialog"""
        load_ui("about_dlg.ui", self)

        self.title_label = self.findChild(QLabel, "title_label")
        self.title_label.setText(f"Friendly Pics 2 v{__version__}")

        self.runtime_env_label = self.findChild(QLabel, "runtime_env_label")
        if is_mac_app_bundle():
            self.runtime_env_label.setText("Running as MacOS app bundle")
        elif is_pyinstaller_bundle():
            self.runtime_env_label.setText("Running as a pyinstaller binary")
        else:
            self.runtime_env_label.setText(
                "Running under conventional Python environment")

        self.gui_settings_label = self.findChild(QLabel, "gui_settings_label")
        self.gui_settings_label.setText(
            f"<b>GUI Settings:</b> {self._settings.fileName()}")

        self.gui_settings_clear_button = self.findChild(
            QPushButton, "gui_settings_clear_button")
        self.gui_settings_clear_button.clicked.connect(
            self._clear_gui_settings)

        self.app_settings_label = self.findChild(QLabel, "app_settings_label")
        self.app_settings_label.setText(
            f"<b>App Settings:</b> {self._app_settings.path}")

        # Center the about box on the parent window
        parent_geom = self.parent().geometry()
        self.move(parent_geom.center() - self.rect().center())

    @Slot()
    def _clear_gui_settings(self):
        """Callback for when user selects the clear gui settings button"""
        self._settings.clear()
        self._settings.sync()
        self.gui_settings_clear_button.setEnabled(False)
        self.cleared = True
Exemple #20
0
    def _on_reset(self):
        """
        Callback for reset button. Prompts user for confirmation, then proceeds
        to reset settings to default values if confirmed, before updating
        controls and applying any changes (emits change signal if any changes).
        """
        mb = QMessageBox(QMessageBox.Warning,
                         tr("Reset all settings"),
                         tr("This will reset all settings to their default " +
                            "values. Are you sure you want to continue?"),
                         QMessageBox.Yes | QMessageBox.No)
        mb.setDefaultButton(QMessageBox.No)
        dr = mb.exec_()
        if dr == QMessageBox.Yes:
            # This clears all settings, and recreates only those values
            # initialized with set_default this session.
            Settings.restore_from_defaults()

            # Now we update controls:
            s = QSettings(self.ui)
            keys = list(self._initial_values.keys())  # Use copy, as we may modify
            for k in keys:
                # Check if setting is still present
                if s.contains(k):
                    # Present, update to new value (triggers _on_change)
                    v = s.value(k)
                    w = self._lut[k]
                    if isinstance(w, QLineEdit):
                        w.setText(v)
                    elif isinstance(w, QCheckBox):
                        w.setChecked(v.lower() == "true")
                    elif isinstance(w, (QSpinBox, QDoubleSpinBox)):
                        w.setValue(v)
                else:
                    # Setting was removed, remove editor
                    w = self._lut[k]
                    layout = w.parent().layout()
                    label = layout.labelForField(w)
                    layout.removeWidget(w)
                    w.close()
                    if label is not None:
                        layout.removeWidget(label)
                        label.close()
                    del self._lut[k]
                    del self._initial_values[k]
                    self._changes[k] = None
                    # Check whether all editors for tab was removed
                    if layout.count() == 0:
                        wrap = w.parent()
                        self.tabs.removeTab(self.tabs.indexOf(wrap))
            # Finally apply changes (update _initial_values, and emit signal)
            self.apply_changes()
Exemple #21
0
 def unhide_column(self, header, logicalIndex):
     '''
     Unhide a column, removing the column from the list of hidden columns in QSettings
     '''
     hidden_columns = QSettings().value("catalog.columns.hidden") or set()
     column_name = self._current_column_name(header, logicalIndex)
     try:
         hidden_columns.remove(column_name)
     except KeyError as ex:
         raise (KeyError(
             f"Attempted to unhide non-hidden column name {column_name}."))
     QSettings().setValue("catalog.columns.hidden", hidden_columns)
     header.setSectionHidden(logicalIndex, False)
Exemple #22
0
    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 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 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_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
Exemple #29
0
 def closeEvent(self, event):
     """Window is closed, save state"""
     settings = QSettings("sdt", "locator")
     settings.setValue("MainWindow/geometry", self.saveGeometry())
     settings.setValue("MainWindow/state", self.saveState())
     settings.setValue("Viewer/showPreview", self._viewer.showLocalizations)
     super().closeEvent(event)
Exemple #30
0
def prompt_hostname_gui():
    """Ask user for a hostname, offer recently used values"""
    from qtpy.QtWidgets import QInputDialog
    from qtpy.QtCore import QSettings
    settings = QSettings('allegro', 'allegro_vnc')
    recent = settings.value('recent_hostnames', [])
    hostname, accepted = QInputDialog.getItem(None, 'Enter hostname',
                                              'Hostname:', recent)
    if not accepted:
        return
    recent.insert(0, hostname)
    # Remove duplicates without changing order
    recent = sorted(set(recent), key=recent.index)[:10]
    settings.setValue('recent_hostnames', recent)
    return hostname
Exemple #31
0
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
Exemple #32
0
    def __init__(self, argv: list, company: str, appname: str, Liststr=None):
        """
        Creates instance of QApplication for our application, will autoinit settings

        Args:
            argv (List): [description]
            Liststr ([type], optional): [description]. Defaults to None.
            company (str, optional): Company name for settings saving. Defaults to "QtArgApp".
            appname (str, optional): App name for settings saving. Defaults to "DefaultApp".
        """
        if company is None:
            company = self.__class__.__name__
        QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, str(FOLDER.parent / "settings"))
        self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, company, appname)
        super().__init__(argv)
Exemple #33
0
 def save_state(self):
     '''
     Saves the dock manager state and the main window geometry
     '''
     settings = QSettings("Settings.ini", QSettings.IniFormat)
     settings.setValue("mainWindow/Geometry", self.saveGeometry())
     settings.setValue("mainWindow/State", self.saveState())
     settings.setValue("mainWindow/DockingState", self.dock_manager.save_state())
Exemple #34
0
    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)
Exemple #35
0
 def apply_changes(self):
     """
     Applies changes performed since dialog creation or last apply,
     whichever is most recent. Fires settings_changed Signal as long as
     there has been any changes.
     """
     if len(self._changes) < 1:
         return
     s = QSettings(self.ui)
     for k, v in self._changes.items():
         if k in self._initial_values:   # Avoid readding removed settings
             s.setValue(k, v)
             self._initial_values[k] = v
     self.settings_changed.emit(self._changes)
     self._changes.clear()
     self.apply_btn.setEnabled(False)
Exemple #36
0
    def load_settings(self):
        settings = QSettings()

        # window geometry
        try:
            self.restoreGeometry(settings.value(GEOMETRY_SETTING))
        except:
            logger.debug("error restoring window geometry")

        # window state
        try:
            self.restoreState(settings.value(WINDOWSTATE_SETTING))
        except:
            logger.debug("error restoring window state")

        # filename
        self.filename = settings.value(FILENAME_SETTING)
        if self.filename is not None:
            self.load_file(self.filename)
 def __init__(self, settings=None):
     """
         Initialization.
         @param settings: QSettings object passed by the main application
     """
     super(GeneralSettings, self).__init__()
     if settings is not None:
         self._settings = settings
     else:
         self._settings = QSettings()
Exemple #38
0
 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()
Exemple #39
0
 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()
Exemple #40
0
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)
Exemple #41
0
    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
Exemple #42
0
    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()
Exemple #43
0
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
Exemple #44
0
    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()
Exemple #45
0
 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
Exemple #46
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.settings = QSettings()

        # decimal
        self.decimalLabel = QLabel(self.tr("decimal:"))
        self.decimalComboBox = QComboBox()
        self.decimalLabel.setBuddy(self.decimalComboBox)
        self.decimalComboBox.addItems([",", "."])

        # separator
        self.separatorLabel = QLabel(self.tr("separator:"))
        self.separatorComboBox = QComboBox()
        self.separatorLabel.setBuddy(self.separatorComboBox)
        self.separatorComboBox.addItem("Semicolon ';'", ';')
        self.separatorComboBox.addItem("Comma ','", ',')
        self.separatorComboBox.addItem("Tabulator '\\t'", '\t')
        self.separatorComboBox.addItem("Whitespace ' '", ' ')

        # buttons
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

        # layout
        layout = QGridLayout()
        layout.addWidget(self.decimalLabel, 0, 0)
        layout.addWidget(self.decimalComboBox, 0, 1)
        layout.addWidget(self.separatorLabel, 1, 0)
        layout.addWidget(self.separatorComboBox, 1, 1)
        layout.addWidget(self.buttons, 2, 0, 1, 2)
        self.setLayout(layout)

        # settings
        self.decimalComboBox.setCurrentIndex(
            self.decimalComboBox.findText(
                self.settings.value(DECIMAL_SETTING, ","))
        )
        self.separatorComboBox.setCurrentIndex(
            self.separatorComboBox.findData(
                self.settings.value(SEPARATOR_SETTING, ";"))
        )

        self.setWindowTitle(self.tr("record settings"))
Exemple #47
0
 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
Exemple #48
0
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)
Exemple #49
0
    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()
Exemple #50
0
 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
Exemple #51
0
    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()
Exemple #52
0
 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 _previous_directory_settings(self):
     previous_directories = QSettings()
     previous_directories.beginGroup("CustomInterfaces/SANSRunWindow/AddRuns")
     return previous_directories
Exemple #54
0
class MfixGui(QtGui.QMainWindow):
    """
    Main window class handling all gui interactions
    """

    def __init__(self, app, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        # reference to qapp instance
        self.app = app

        # load ui file
        self.customWidgets = {
            "LineEdit": LineEdit,
            "CheckBox": CheckBox,
            "ComboBox": ComboBox,
            "DoubleSpinBox": DoubleSpinBox,
            "SpinBox": SpinBox,
        }
        self.ui = uic.loadUi(os.path.join("uifiles", "gui.ui"), self)

        # load settings
        self.settings = QSettings("MFIX", "MFIX")

        # set title and icon
        self.setWindowTitle("MFIX")
        self.setWindowIcon(get_icon("mfix.png"))

        # build keyword documentation from namelist docstrings
        self.keyword_doc = buildKeywordDoc(os.path.join(SCRIPT_DIRECTORY, os.pardir, "model"))

        self.project = ProjectManager(self, self.keyword_doc)

        # --- data ---
        self.modebuttondict = {
            "modeler": self.ui.pushButtonModeler,
            "workflow": self.ui.pushButtonWorkflow,
            "developer": self.ui.pushButtonDeveloper,
        }

        self.booleanbtndict = {
            "union": self.ui.toolbutton_geometry_union,
            "intersection": self.ui.toolbutton_geometry_intersect,
            "difference": self.ui.toolbutton_geometry_difference,
        }
        self.animation_speed = 400
        self.animating = False
        self.stack_animation = None

        # --- icons ---
        # loop through all widgets, because I am lazy
        for widget in widget_iter(self.ui):
            if isinstance(widget, QtGui.QToolButton):
                name = str(widget.objectName())
                if "add" in name:
                    widget.setIcon(get_icon("add.png"))
                elif "delete" in name or "remove" in name:
                    widget.setIcon(get_icon("remove.png"))
                elif "copy" in name:
                    widget.setIcon(get_icon("copy.png"))

        self.ui.toolbutton_new.setIcon(get_icon("newfolder.png"))
        self.ui.toolbutton_open.setIcon(get_icon("openfolder.png"))
        self.ui.toolbutton_save.setIcon(get_icon("save.png"))

        self.ui.toolbutton_compile.setIcon(get_icon("build.png"))
        self.ui.toolbutton_run.setIcon(get_icon("play.png"))
        self.ui.toolbutton_restart.setIcon(get_icon("restart.png"))
        self.ui.toolbutton_interact.setIcon(get_icon("flash.png"))

        self.ui.toolbutton_add_geometry.setIcon(get_icon("geometry.png"))
        self.ui.toolbutton_add_filter.setIcon(get_icon("filter.png"))
        self.ui.toolbutton_geometry_union.setIcon(get_icon("union.png"))
        self.ui.toolbutton_geometry_intersect.setIcon(get_icon("intersect.png"))
        self.ui.toolbutton_geometry_difference.setIcon(get_icon("difference.png"))

        self.ui.toolButtonTFMSolidsDatabase.setIcon(get_icon("download.png"))

        # --- Connect Signals to Slots---
        # open/save/new project
        self.ui.toolbutton_open.pressed.connect(self.open_project)
        self.ui.toolbutton_save.pressed.connect(self.save_project)

        # mode (modeler, workflow, developer)
        for mode, btn in self.modebuttondict.items():
            btn.released.connect(make_callback(self.mode_changed, mode))

        # navigation tree
        self.ui.treewidget_model_navigation.itemSelectionChanged.connect(self.navigation_changed)

        # build/run/connect MFIX
        self.ui.build_mfix_button.pressed.connect(self.build_mfix)
        self.ui.run_mfix_button.pressed.connect(self.run_mfix)
        self.ui.connect_mfix_button.pressed.connect(self.connect_mfix)
        self.ui.clear_output_button.pressed.connect(self.clear_output)

        # --- Threads ---
        self.build_thread = BuildThread(self)
        self.run_thread = RunThread(self)
        self.clear_thread = ClearThread(self)

        def make_handler(qtextbrowser):
            " make a closure to read stdout from external process "

            def handle_line(line):
                " closure to read stdout from external process "

                log = logging.getLogger(__name__)
                log.debug(str(line).strip())
                cursor = qtextbrowser.textCursor()
                cursor.movePosition(cursor.End)
                cursor.insertText(line)
                qtextbrowser.ensureCursorVisible()

            return handle_line

        self.build_thread.line_printed.connect(make_handler(self.ui.command_output))
        self.run_thread.line_printed.connect(make_handler(self.ui.command_output))
        self.clear_thread.line_printed.connect(make_handler(self.ui.command_output))

        # --- setup simple widgets ---
        self.__setup_simple_keyword_widgets()

        # --- vtk setup ---
        self.__setup_vtk_widget()

        # --- workflow setup ---
        if NodeWidget is not None:
            self.__setup_workflow_widget()

        # --- default ---
        self.mode_changed("modeler")
        self.change_pane("geometry")

        # autoload last project
        if self.get_project_dir():
            self.open_project(self.get_project_dir())

    def __setup_simple_keyword_widgets(self):
        """
        Look for and connect simple keyword widgets to the project manager.
        Keyword informtation from the namelist doc strings is added to each
        keyword widget. The widget must be named: *_keyword_<keyword> where
        <keyword> is the actual keyword. For example:
        lineedit_keyword_run_name
        """

        # loop through all widgets looking for *_keyword_<keyword>
        for widget in widget_iter(self.ui):
            name_list = str(widget.objectName()).lower().split("_")

            if "keyword" in name_list:
                keyword = "_".join(name_list[name_list.index("keyword") + 1 :])

                # set the key attribute to the keyword
                widget.key = keyword

                # add info from keyword documentation
                if keyword in self.keyword_doc:
                    widget.setdtype(self.keyword_doc[keyword]["dtype"])

                    if "required" in self.keyword_doc[keyword]:
                        widget.setValInfo(req=self.keyword_doc[keyword]["required"] == "true")
                    if "validrange" in self.keyword_doc[keyword]:
                        if "max" in self.keyword_doc[keyword]["validrange"]:
                            widget.setValInfo(_max=self.keyword_doc[keyword]["validrange"]["max"])
                        if "min" in self.keyword_doc[keyword]["validrange"]:
                            widget.setValInfo(_min=self.keyword_doc[keyword]["validrange"]["min"])

                    if "initpython" in self.keyword_doc[keyword]:
                        widget.default(self.keyword_doc[keyword]["initpython"])

                    if isinstance(widget, QtGui.QComboBox) and widget.count() < 1:
                        widget.addItems(list(self.keyword_doc[keyword]["valids"].keys()))

                # register the widget with the project manager
                self.project.register_widget(widget, [keyword])

                # connect to unsaved method
                widget.value_updated.connect(self.unsaved)

    def __setup_vtk_widget(self):
        " setup the vtk widget "

        self.vtkwidget = VtkWidget(self.project, parent=self)
        self.ui.horizontalLayoutModelGraphics.addWidget(self.vtkwidget)

        # register with project manager
        self.project.register_widget(
            self.vtkwidget, ["xmin", "xlength", "ymin", "ylength", "zmin", "zlength", "imax", "jmax", "kmax"]
        )

    def __setup_workflow_widget(self):

        self.nodeChart = NodeWidget(showtoolbar=False)
        # Build defualt node library
        self.nodeChart.nodeLibrary.buildDefualtLibrary()
        self.ui.horizontalLayoutPyqtnode.addWidget(self.nodeChart)

    def get_project_dir(self):
        " get the current project directory"

        last_dir = self.settings.value("project_dir")
        if last_dir:
            return last_dir
        else:
            return None

    def mode_changed(self, mode):
        " change the Modeler, Workflow, Developer tab"

        current_index = 0
        for i in range(self.ui.stackedwidget_mode.count()):
            widget = self.ui.stackedwidget_mode.widget(i)
            if mode == str(widget.objectName()):
                current_index = i
                break

        for key, btn in self.modebuttondict.items():
            btn.setChecked(mode == key)

        self.animate_stacked_widget(
            self.ui.stackedwidget_mode, self.ui.stackedwidget_mode.currentIndex(), current_index, "horizontal"
        )

    # --- modeler pane navigation ---
    def change_pane(self, name):
        """ change to the specified pane """

        clist = self.ui.treewidget_model_navigation.findItems(
            name, QtCore.Qt.MatchContains | QtCore.Qt.MatchRecursive, 0
        )

        for item in clist:
            if str(item.text(0)).lower() == name.lower():
                break

        self.ui.treewidget_model_navigation.setCurrentItem(item)
        self.navigation_changed()

    def navigation_changed(self):
        """ an item in the tree was selected, change panes """
        current_selection = self.ui.treewidget_model_navigation.selectedItems()

        if current_selection:

            text = str(current_selection[-1].text(0))
            text = "_".join(text.lower().split(" "))

            current_index = 0
            for i in range(self.ui.stackedWidgetTaskPane.count()):
                widget = self.ui.stackedWidgetTaskPane.widget(i)
                if text == str(widget.objectName()):
                    current_index = i
                    break

            self.animate_stacked_widget(
                self.ui.stackedWidgetTaskPane, self.ui.stackedWidgetTaskPane.currentIndex(), current_index
            )

    # --- animation methods ---
    def animate_stacked_widget(
        self, stackedwidget, from_, to, direction="vertical", line=None, to_btn=None, btn_layout=None
    ):
        """ animate changing of qstackedwidget """

        # check to see if already animating
        if self.animating and self.stack_animation is not None:
            self.stack_animation.stop()

        from_widget = stackedwidget.widget(from_)
        to_widget = stackedwidget.widget(to)

        # get from geometry
        width = from_widget.frameGeometry().width()
        height = from_widget.frameGeometry().height()

        # offset
        # bottom to top
        if direction == "vertical" and from_ < to:
            offsetx = 0
            offsety = height
        # top to bottom
        elif direction == "vertical" and from_ > to:
            offsetx = 0
            offsety = -height
        elif direction == "horizontal" and from_ < to:
            offsetx = width
            offsety = 0
        elif direction == "horizontal" and from_ > to:
            offsetx = -width
            offsety = 0
        else:
            return

        # move to widget and show
        # set the geometry of the next widget
        to_widget.setGeometry(0 + offsetx, 0 + offsety, width, height)
        to_widget.show()
        to_widget.raise_()

        # animate
        # from widget
        animnow = QtCore.QPropertyAnimation(from_widget, "pos")
        animnow.setDuration(self.animation_speed)
        animnow.setEasingCurve(QtCore.QEasingCurve.InOutQuint)
        animnow.setStartValue(QtCore.QPoint(0, 0))
        animnow.setEndValue(QtCore.QPoint(0 - offsetx, 0 - offsety))

        # to widget
        animnext = QtCore.QPropertyAnimation(to_widget, "pos")
        animnext.setDuration(self.animation_speed)
        animnext.setEasingCurve(QtCore.QEasingCurve.InOutQuint)
        animnext.setStartValue(QtCore.QPoint(0 + offsetx, 0 + offsety))
        animnext.setEndValue(QtCore.QPoint(0, 0))

        # line
        animline = None
        if line is not None and to_btn is not None:
            animline = QtCore.QPropertyAnimation(line, "pos")
            animline.setDuration(self.animation_speed)
            animline.setEasingCurve(QtCore.QEasingCurve.InOutQuint)
            animline.setStartValue(QtCore.QPoint(line.geometry().x(), line.geometry().y()))
            animline.setEndValue(QtCore.QPoint(to_btn.geometry().x(), line.geometry().y()))

        # animation group
        self.stack_animation = QtCore.QParallelAnimationGroup()
        self.stack_animation.addAnimation(animnow)
        self.stack_animation.addAnimation(animnext)
        if animline is not None:
            self.stack_animation.addAnimation(animline)
        self.stack_animation.finished.connect(
            make_callback(self.animate_stacked_widget_finished, stackedwidget, from_, to, btn_layout, line)
        )
        self.stack_animation.stateChanged.connect(
            make_callback(self.animate_stacked_widget_finished, stackedwidget, from_, to, btn_layout, line)
        )

        self.animating = True
        self.stack_animation.start()

    def animate_stacked_widget_finished(self, widget, from_, to, btn_layout=None, line=None):
        """ cleanup after animation """
        if self.stack_animation.state() == QtCore.QAbstractAnimation.Stopped:
            widget.setCurrentIndex(to)
            from_widget = widget.widget(from_)
            from_widget.hide()
            from_widget.move(0, 0)

            if btn_layout is not None and line is not None:
                btn_layout.addItem(btn_layout.takeAt(btn_layout.indexOf(line)), 1, to)

            self.animating = False

    # --- helper methods ---
    def message(
        self,
        title="Warning",
        icon="warning",
        text="This is a warning.",
        buttons=["ok"],
        default="ok",
        infoText=None,
        detailedtext=None,
    ):
        """
        Create a message box:
        title = 'title'
        icon = 'warning' or 'info'
        text = 'test to show'
        buttons = ['ok',...] where value is 'ok', 'yes', 'no', 'cancel',
            'discard'
        default = 'ok' the default selected button
        infotext = 'extended information text'
        detailedtext = 'Some details'
        """
        msgBox = QtGui.QMessageBox(self)
        msgBox.setWindowTitle(title)

        # Icon
        if icon == "warning":
            icon = QtGui.QMessageBox.Warning
        else:
            icon = QtGui.QMessageBox.Information

        msgBox.setIcon(icon)

        # Text
        msgBox.setText(text)

        if infoText:
            msgBox.setInformativeText(infoText)

        if detailedtext:
            msgBox.setDetailedText(detailedtext)

        # buttons
        qbuttonDict = {
            "ok": QtGui.QMessageBox.Ok,
            "yes": QtGui.QMessageBox.Yes,
            "no": QtGui.QMessageBox.No,
            "cancel": QtGui.QMessageBox.Cancel,
            "discard": QtGui.QMessageBox.Discard,
        }
        for button in buttons:
            msgBox.addButton(qbuttonDict[button])

            if button == default:
                msgBox.setDefaultButton(qbuttonDict[button])

        ret = msgBox.exec_()

        for key, value in qbuttonDict.items():
            if value == ret:
                result = key
                break

        return result

    def print_internal(self, text):
        if not text.endswith("\n"):
            text += "\n"
        LOG.debug(str(text).strip())
        cursor = self.ui.command_output.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(text)
        cursor.movePosition(cursor.End)
        vbar = self.ui.command_output.verticalScrollBar()
        vbar.triggerAction(QtGui.QAbstractSlider.SliderToMaximum)
        self.ui.command_output.ensureCursorVisible()

    # --- mfix methods ---
    def set_mpi(self):
        " set MPI checkbox if more than one node selected "
        nodesi = int(self.ui.nodes_i.text())
        nodesj = int(self.ui.nodes_j.text())
        nodesk = int(self.ui.nodes_k.text())
        if max(nodesi, nodesj, nodesk) > 1:
            self.ui.dmp_button.setChecked(True)

    def set_nodes(self):
        " set all nodes to one if MPI checkbox is unchecked "
        if self.ui.dmp_button.isChecked():
            self.ui.nodes_i.setValue(1)
            self.ui.nodes_j.setValue(1)
            self.ui.nodes_k.setValue(1)

    def make_build_cmd(self):
        """ build mfix """
        mfix_home = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        dmp = "--dmp" if self.ui.dmp_button.isChecked() else ""
        smp = "--smp" if self.ui.smp_button.isChecked() else ""
        return os.path.join(mfix_home, "configure_mfix --python %s %s && make -j pymfix" % (smp, dmp))

    def build_mfix(self):
        """ build mfix """
        self.build_thread.start_command(self.make_build_cmd(), self.get_project_dir())

    def clear_output(self):
        """ build mfix """
        self.run_thread.start_command(
            'echo "Removing:";' " ls *.LOG *.OUT *.RES *.SP? *.pvd *vtp;" " rm -f *.LOG *.OUT *.RES *.SP? *.pvd *vtp",
            self.get_project_dir(),
        )

    def run_mfix(self):
        """ build mfix """
        if not self.ui.dmp_button.isChecked():
            pymfix_exe = os.path.join(self.get_project_dir(), "pymfix")
        else:
            nodesi = int(self.ui.nodes_i.text())
            nodesj = int(self.ui.nodes_j.text())
            nodesk = int(self.ui.nodes_k.text())
            total = nodesi * nodesj * nodesk
            pymfix_exe = "mpirun -np {} ./pymfix NODESI={} NODESJ={} NODESK={}".format(total, nodesi, nodesj, nodesk)

        build_and_run_cmd = "{} && {}".format(self.make_build_cmd(), pymfix_exe)
        self.run_thread.start_command(build_and_run_cmd, self.get_project_dir())

    def update_residuals(self):
        self.ui.residuals.setText(self.updater.residuals)
        if self.updater.job_done:
            self.ui.mfix_browser.setHTML("")

    def connect_mfix(self):
        """ connect to running instance of mfix """
        url = "http://{}:{}".format(self.ui.mfix_host.text(), self.ui.mfix_port.text())
        log = logging.getLogger(__name__)
        log.debug("trying to connect to {}".format(url))
        qurl = QUrl(url)
        self.ui.mfix_browser.load(qurl)

        self.updater = UpdateResidualsThread()
        self.updater.sig.connect(self.update_residuals)
        self.updater.start()

        self.change_pane("interact")

    # --- open/save/new ---
    def save_project(self):
        # make sure the button is not down
        self.ui.toolbutton_save.setDown(False)

        project_dir = self.settings.value("project_dir")

        # export geometry
        self.vtkwidget.export_stl(os.path.join(project_dir, "geometry.stl"))

        self.setWindowTitle("MFIX - %s" % project_dir)
        self.project.writeDatFile(os.path.join(project_dir, "mfix.dat"))

    def unsaved(self):
        project_dir = self.settings.value("project_dir")
        self.setWindowTitle("MFIX - %s *" % project_dir)

    def new_project(self, project_dir=None):
        if not project_dir:
            project_dir = str(
                QtGui.QFileDialog.getExistingDirectory(
                    self, "Create Project in Directory", "", QtGui.QFileDialog.ShowDirsOnly
                )
            )
        if len(project_dir) < 1:
            return
        try:
            shutil.copyfile("mfix.dat.template", os.path.join(project_dir, "mfix.dat"))
        except IOError:
            self.message(
                title="Warning",
                icon="warning",
                text=("You do not have write access to this " "directory.\n"),
                buttons=["ok"],
                default="ok",
            )
            return
        self.open_project(project_dir)

    def open_project(self, project_dir=None):
        """
        Open MFiX Project
        """
        # make sure the button is not left down
        self.ui.toolbutton_open.setDown(False)

        if not project_dir:
            project_dir = str(
                QtGui.QFileDialog.getExistingDirectory(
                    self, "Open Project Directory", "", QtGui.QFileDialog.ShowDirsOnly
                )
            )

        if len(project_dir) < 1:
            return

        writable = True
        try:
            import tempfile

            testfile = tempfile.TemporaryFile(dir=project_dir)
            testfile.close()
        except IOError:
            writable = False

        if not writable:
            self.message(
                title="Warning",
                icon="warning",
                text=("You do not have write access to this " "directory.\n"),
                buttons=["ok"],
                default="ok",
            )
            return

        mfix_dat = os.path.abspath(os.path.join(project_dir, "mfix.dat"))

        if not os.path.exists(mfix_dat):
            self.message(
                title="Warning",
                icon="warning",
                text=("mfix.dat file does not exist in this " "directory.\n"),
                buttons=["ok"],
                default="ok",
            )
            return

        self.settings.setValue("project_dir", project_dir)
        self.setWindowTitle("MFIX - %s" % project_dir)

        # read the file
        with open(mfix_dat, "r") as mfix_dat_file:
            src = mfix_dat_file.read()
        self.ui.mfix_dat_source.setPlainText(src)
        # self.mode_changed('developer')

        self.project.load_mfix_dat(mfix_dat)

        self.ui.energy_eq.setChecked(self.project["energy_eq"])
Exemple #55
0
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
    defaults = 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)
        self.defaults = defaults

    def all_keys(self):
        return self.qsettings.allKeys()

    @property
    def filename(self):
        return self.qsettings.fileName()

    def get(self, section, option):
        """
        Return a value for an option in a given section. If not
        specified in the saved settings then the initial
        defaults are consulted. If no option is found then
        a KeyError is raised
        :param section: A string section name
        :param option: A string option name
        :return: The value of the option
        """
        value = self.qsettings.value(self._settings_path(section, option))
        if not value:
            value = self._get_default_or_raise(section, option)

        return value

    def set(self, section, option, value):
        """
        Set a value for an option in a given section.
        :param section: A string section name
        :param option: A string option name
        :param value: The value of the setting
        """
        self.qsettings.setValue(self._settings_path(section, option), value)

    # -------------------------------------------------------------------------
    # "Private" methods
    # -------------------------------------------------------------------------

    def _check_section_option_is_valid(self, section, option):
        """
        Sanity check the section and option are strings
        """
        if not is_text_string(section):
            raise RuntimeError("section is not a text string")
        if not is_text_string(option):
            raise RuntimeError("option is not a text string")

    def _get_default_or_raise(self, section, option):
        """
        Returns the value listed in the defaults if it exists
        :param section: A string denoting the section (not checked)
        :param option: A string denoting the option name
        :return: The value of the default
        :raises KeyError: if the item does not exist
        """
        value = None
        if self.defaults and section in self.defaults:
            try:
                value = self.defaults[section][option]
            except KeyError:
                raise KeyError("Unknown config item requested: " +
                               self._settings_path(section, option))
        return value

    def _settings_path(self, section, option):
        """
        Private method to construct a path to the given option with the
        section
        :param section: The name of the section
        :param option: The name of the option
        :return: A path to the location within the QSettings instance
        """
        self._check_section_option_is_valid(section, option)
        return section + "/" + option
Exemple #56
0
    def __init__(self, app, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        # reference to qapp instance
        self.app = app

        # load ui file
        self.customWidgets = {
            "LineEdit": LineEdit,
            "CheckBox": CheckBox,
            "ComboBox": ComboBox,
            "DoubleSpinBox": DoubleSpinBox,
            "SpinBox": SpinBox,
        }
        self.ui = uic.loadUi(os.path.join("uifiles", "gui.ui"), self)

        # load settings
        self.settings = QSettings("MFIX", "MFIX")

        # set title and icon
        self.setWindowTitle("MFIX")
        self.setWindowIcon(get_icon("mfix.png"))

        # build keyword documentation from namelist docstrings
        self.keyword_doc = buildKeywordDoc(os.path.join(SCRIPT_DIRECTORY, os.pardir, "model"))

        self.project = ProjectManager(self, self.keyword_doc)

        # --- data ---
        self.modebuttondict = {
            "modeler": self.ui.pushButtonModeler,
            "workflow": self.ui.pushButtonWorkflow,
            "developer": self.ui.pushButtonDeveloper,
        }

        self.booleanbtndict = {
            "union": self.ui.toolbutton_geometry_union,
            "intersection": self.ui.toolbutton_geometry_intersect,
            "difference": self.ui.toolbutton_geometry_difference,
        }
        self.animation_speed = 400
        self.animating = False
        self.stack_animation = None

        # --- icons ---
        # loop through all widgets, because I am lazy
        for widget in widget_iter(self.ui):
            if isinstance(widget, QtGui.QToolButton):
                name = str(widget.objectName())
                if "add" in name:
                    widget.setIcon(get_icon("add.png"))
                elif "delete" in name or "remove" in name:
                    widget.setIcon(get_icon("remove.png"))
                elif "copy" in name:
                    widget.setIcon(get_icon("copy.png"))

        self.ui.toolbutton_new.setIcon(get_icon("newfolder.png"))
        self.ui.toolbutton_open.setIcon(get_icon("openfolder.png"))
        self.ui.toolbutton_save.setIcon(get_icon("save.png"))

        self.ui.toolbutton_compile.setIcon(get_icon("build.png"))
        self.ui.toolbutton_run.setIcon(get_icon("play.png"))
        self.ui.toolbutton_restart.setIcon(get_icon("restart.png"))
        self.ui.toolbutton_interact.setIcon(get_icon("flash.png"))

        self.ui.toolbutton_add_geometry.setIcon(get_icon("geometry.png"))
        self.ui.toolbutton_add_filter.setIcon(get_icon("filter.png"))
        self.ui.toolbutton_geometry_union.setIcon(get_icon("union.png"))
        self.ui.toolbutton_geometry_intersect.setIcon(get_icon("intersect.png"))
        self.ui.toolbutton_geometry_difference.setIcon(get_icon("difference.png"))

        self.ui.toolButtonTFMSolidsDatabase.setIcon(get_icon("download.png"))

        # --- Connect Signals to Slots---
        # open/save/new project
        self.ui.toolbutton_open.pressed.connect(self.open_project)
        self.ui.toolbutton_save.pressed.connect(self.save_project)

        # mode (modeler, workflow, developer)
        for mode, btn in self.modebuttondict.items():
            btn.released.connect(make_callback(self.mode_changed, mode))

        # navigation tree
        self.ui.treewidget_model_navigation.itemSelectionChanged.connect(self.navigation_changed)

        # build/run/connect MFIX
        self.ui.build_mfix_button.pressed.connect(self.build_mfix)
        self.ui.run_mfix_button.pressed.connect(self.run_mfix)
        self.ui.connect_mfix_button.pressed.connect(self.connect_mfix)
        self.ui.clear_output_button.pressed.connect(self.clear_output)

        # --- Threads ---
        self.build_thread = BuildThread(self)
        self.run_thread = RunThread(self)
        self.clear_thread = ClearThread(self)

        def make_handler(qtextbrowser):
            " make a closure to read stdout from external process "

            def handle_line(line):
                " closure to read stdout from external process "

                log = logging.getLogger(__name__)
                log.debug(str(line).strip())
                cursor = qtextbrowser.textCursor()
                cursor.movePosition(cursor.End)
                cursor.insertText(line)
                qtextbrowser.ensureCursorVisible()

            return handle_line

        self.build_thread.line_printed.connect(make_handler(self.ui.command_output))
        self.run_thread.line_printed.connect(make_handler(self.ui.command_output))
        self.clear_thread.line_printed.connect(make_handler(self.ui.command_output))

        # --- setup simple widgets ---
        self.__setup_simple_keyword_widgets()

        # --- vtk setup ---
        self.__setup_vtk_widget()

        # --- workflow setup ---
        if NodeWidget is not None:
            self.__setup_workflow_widget()

        # --- default ---
        self.mode_changed("modeler")
        self.change_pane("geometry")

        # autoload last project
        if self.get_project_dir():
            self.open_project(self.get_project_dir())
    def closeEvent(self, event):
        """
            Executed when the application closes
        """
        if False:
            reply = QMessageBox.question(self, 'Message',
                                               "Are you sure you want to quit this application?",
                                               QMessageBox.Yes, QMessageBox.No)

            if reply == QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

        # Save application settings
        if self._clear_and_restart:
            self._clear_and_restart = False
            QSettings().clear()
        else:
            settings = QSettings()

            settings.setValue("instrument_name", self._instrument)
            settings.setValue("last_file", self._filename)
            settings.setValue("recent_files", self._recent_files)
            settings.setValue("last_directory", str(self._last_directory))
            settings.setValue("last_export_directory", str(self._last_export_directory))
    def __init__(self, instrument=None, instrument_list=None):
        QMainWindow.__init__(self)
        self.ui = load_ui(__file__, 'ui/reduction_main.ui', baseinstance=self)

        if STARTUP_WARNING:
            message = "The reduction application has problems starting:\n\n"
            message += STARTUP_WARNING
            QMessageBox.warning(self, "WARNING", message)

        # Application settings
        settings = QSettings()

        # Name handle for the instrument
        if instrument is None:
            instrument = unicode(settings.value("instrument_name", ''))
            if instrument_list is not None and instrument not in instrument_list:
                instrument = None

        self._instrument = instrument
        self._facility = None

        # List of allowed instrument
        self._instrument_list = instrument_list

        # Reduction interface
        self._interface = None

        # Recent files
        self._recent_files = settings.value("recent_files", [])
        if self._recent_files is None:  # An empty list saved to QSettings comes back as 'None'
            self._recent_files = []

        # Folder to open files in
        self._last_directory = unicode(settings.value("last_directory", '.'))
        self._last_export_directory = unicode(settings.value("last_export_directory", '.'))

        # Current file name
        self._filename = None

        # Cluster credentials and options
        self._cluster_details_set = False
        self._number_of_nodes = 1
        self._cores_per_node = 16
        self._compute_resources = ['Fermi']
        if CAN_REDUCE and hasattr(ConfigService.Instance().getFacility(), "computeResources"):
            self._compute_resources = ConfigService.Instance().getFacility().computeResources()

        # Internal flag for clearing all settings and restarting the application
        self._clear_and_restart = False

        # General settings shared by all widgets
        self.general_settings = GeneralSettings(settings)

        # Event connections
        if not CAN_REDUCE:
            self.reduce_button.hide()
        self.export_button.clicked.connect(self._export)
        self.reduce_button.clicked.connect(self.reduce_clicked)
        self.save_button.clicked.connect(self._save)
        self.interface_chk.clicked.connect(self._interface_choice)

        self.interface_chk.setChecked(self.general_settings.advanced)

        self.general_settings.progress.connect(self._progress_updated)
Exemple #59
0
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()