spinetoolbox.helpers
General helper functions and classes.
Module Contents
Classes
Graphics scene's link types. |
|
A class to manage icons for icon list widgets. |
|
Specialization of QIconEngine with transparent background. |
|
Specialization of QIconEngine used to draw font-based icons. |
|
QFileIconProvider that provides a Spine icon to the |
|
Event filter class for catching next and previous child key presses. |
|
A 'traffic light' that allows waiting for a signal to be emitted in another thread. |
|
HTML tag filter. |
|
A 'meta' command that does not store undo data but can be used in mergeWith methods of other commands. |
Functions
|
Returns user's home dir |
|
Adds color tags and optional time stamp to message. |
|
Decorator to change the mouse cursor to 'busy' while a function is processed. |
|
Create (input/output) directories recursively. |
|
Renames directory. |
|
Opens the given url in the appropriate Web browser for the user's desktop environment, |
Set application icon to Windows taskbar. |
|
Checks if reading .ico files is supported. |
|
Check that PySide6 version is at least 6.4. |
|
|
Returns date and time string for appending into Event Log messages. |
|
Function for copying files. Does not copy folders. |
|
Deletes a directory and all its contents without prompt. |
|
Copies everything from source directory to destination directory recursively. |
|
Change output of itemgetter to always be a tuple even for a single index. |
|
Returns a html unordered list from the given list of strings. |
|
Breaks a list of rows into a list of (row, count) tuples corresponding to chunks of successive rows. |
|
Creates and returns a QIcon corresponding to display_icon. |
|
|
|
Takes icon and color codes, and return equivalent integer. |
|
Takes a display icon id and returns an equivalent tuple of icon and color code. |
Creates a default icon id. |
|
|
Checks if window is on screen and if not, moves and resizes it to make it visible on the primary screen. |
Returns the first element in Iterable s that is not None. |
|
|
Calls QFileDialog.getSaveFileName in the directory that was selected last time the dialog was accepted. |
|
|
|
Tries to convert a string to integer or float. |
|
Returns True if the currently focused widget or one of its ancestors has the given callable. |
|
Calls the given callable on the currently focused widget or one of its ancestors. |
|
Opens file browser where user can select a Gams executable (i.e. gams.exe on Windows). |
|
Opens file browser where user can select a Julia executable (i.e. julia.exe on Windows). |
|
Shows file browser and inserts selected julia project dir to give line_edit. |
|
Opens file browser where user can select a python interpreter (i.e. python.exe on Windows). |
|
Opens file browser where user can select a conda executable. |
Checks that given path points to an existing file and the file name starts with 'conda'. |
|
|
Shows file browser and inserts selected certificate directory to given line edit. |
|
Checks that given path is not a directory and it's a file that actually exists. |
|
Checks that given path is a directory. Needed in |
|
Converts Toolbox settings to a dictionary acceptable by Engine. |
|
|
|
|
|
|
|
Creates a unique name in the form prefix (xx) where xx is a counter value. |
|
Parses specification file. |
|
Returns an Item specification from a definition file. |
|
Returns item specification from a dictionary. |
|
Loads plugins. |
|
Loads plugin dict from plugin directory. |
|
Loads plugin's specifications. |
|
Loads specifications' project-specific data. |
|
Concatenates given information into parameter value identifier string. |
|
Disconnects signal for the duration of a 'with' block. |
|
Gives a context manager that waits for the emission of given Qt signal. |
|
Asks for indexed parameter's index name and updates model accordingly. |
|
|
|
Restores UI state from previous session. |
|
Saves UI state for next session. |
|
Finds insertion points for chunks of data using binary search. |
|
Loads project dictionary from project directory. |
|
Loads local project data. |
|
Merges two dictionaries that may contain nested dictionaries recursively. |
|
|
|
|
|
Identifies a database metadata record. |
|
Checks if two paths are equal. |
|
Returns the connection_file path, if it exists on this computer. If the path |
|
|
|
Turns plain strings into rich text. |
|
Turns a sequence of strings into rich text list. |
|
Turns plain strings into rich text and empty strings/Nones to None. |
Attributes
Display string to separate items such as entity names. |
- spinetoolbox.helpers.format_log_message(msg_type, message, show_datetime=True)[source]
Adds color tags and optional time stamp to message.
- Parameters
msg_type (str) – message’s type; accepts only ‘msg’, ‘msg_success’, ‘msg_warning’, or ‘msg_error’
message (str) – message to format
show_datetime (bool) – True to add time stamp, False to omit it
- Returns
formatted message
- Return type
str
- spinetoolbox.helpers.busy_effect(func)[source]
Decorator to change the mouse cursor to ‘busy’ while a function is processed.
- Parameters
func (Callable) – Decorated function.
- spinetoolbox.helpers.create_dir(base_path, folder='', verbosity=False)[source]
Create (input/output) directories recursively.
- Parameters
base_path (str) – Absolute path to wanted dir
folder (str) – (Optional) Folder name. Usually short name of item.
verbosity (bool) – True prints a message that tells if the directory already existed or if it was created.
- Raises
OSError if operation failed. –
- spinetoolbox.helpers.rename_dir(old_dir, new_dir, toolbox, box_title)[source]
Renames directory.
- Parameters
old_dir (str) – Absolute path to directory that will be renamed
new_dir (str) – Absolute path to new directory
toolbox (ToolboxUI) – A toolbox to log messages and ask questions.
box_title (str) – The title of the message boxes, (e.g. “Undoing ‘rename DC1 to DC2’”)
- Returns
True if operation was successful, False otherwise
- Return type
bool
- spinetoolbox.helpers.open_url(url)[source]
Opens the given url in the appropriate Web browser for the user’s desktop environment, and returns true if successful; otherwise returns false.
If the URL is a reference to a local file (i.e., the URL scheme is “file”) then it will be opened with a suitable application instead of a Web browser.
Handle return value on caller side.
- Parameters
url (str) – URL to open
- Returns
True if successful, False otherwise
- Return type
bool
- spinetoolbox.helpers.pyside6_version_check()[source]
Check that PySide6 version is at least 6.4.
qt_version (str) is the Qt version used to compile PySide6. E.g. “6.4.1” qt_version_info (tuple) contains each version component separately e.g. (6, 4, 1)
- spinetoolbox.helpers.get_datetime(show, date=True)[source]
Returns date and time string for appending into Event Log messages.
- Parameters
show (bool) – True returns date and time string. False returns empty string.
date (bool) – Whether or not the date should be included in the result
- Returns
datetime string or empty string if show is False
- Return type
str
- spinetoolbox.helpers.copy_files(src_dir, dst_dir, includes=None, excludes=None)[source]
Function for copying files. Does not copy folders.
- Parameters
src_dir (str) – Source directory
dst_dir (str) – Destination directory
includes (list, optional) – Included files (wildcards accepted)
excludes (list, optional) – Excluded files (wildcards accepted)
- Returns
Number of files copied
- Return type
count (int)
- spinetoolbox.helpers.erase_dir(path, verbosity=False)[source]
Deletes a directory and all its contents without prompt.
- Parameters
path (str) – Path to directory
verbosity (bool) – Print logging messages or not
- Returns
True if operation was successful, False otherwise
- Return type
bool
- spinetoolbox.helpers.recursive_overwrite(logger, src, dst, ignore=None, silent=True)[source]
Copies everything from source directory to destination directory recursively. Overwrites existing files.
- Parameters
logger (LoggerInterface) – Enables e.g. printing to Event Log
src (str) – Source directory
dst (str) – Destination directory
ignore (Callable, optional) – Ignore function
silent (bool) – If False, messages are sent to Event Log, If True, copying is done in silence
- spinetoolbox.helpers.tuple_itemgetter(itemgetter_func, num_indexes)[source]
Change output of itemgetter to always be a tuple even for a single index.
- Parameters
itemgetter_func (Callable) – item getter function
num_indexes (int) – number of indexes
- Returns
getter function that works with a single index
- Return type
Callable
- spinetoolbox.helpers.format_string_list(str_list)[source]
Returns a html unordered list from the given list of strings. Intended to print error logs as returned by spinedb_api.
- Parameters
str_list (list of str) – list of strings to format
- Returns
formatted list
- Return type
str
- spinetoolbox.helpers.rows_to_row_count_tuples(rows)[source]
Breaks a list of rows into a list of (row, count) tuples corresponding to chunks of successive rows.
- Parameters
rows (Iterable of int) – rows
- Returns
row count tuples
- Return type
list of tuple
- class spinetoolbox.helpers.IconListManager(icon_size)[source]
A class to manage icons for icon list widgets.
- Parameters
icon_size (QSize) – icon’s size
- spinetoolbox.helpers.object_icon(display_icon)[source]
Creates and returns a QIcon corresponding to display_icon.
- Parameters
display_icon (int) – icon id
- Returns
requested icon
- Return type
QIcon
- class spinetoolbox.helpers.TransparentIconEngine[source]
Bases:
PySide6.QtGui.QIconEngine
Specialization of QIconEngine with transparent background.
- class spinetoolbox.helpers.CharIconEngine(char, color=None)[source]
Bases:
TransparentIconEngine
Specialization of QIconEngine used to draw font-based icons.
- Parameters
char (str) – character to use as the icon
color (QColor, optional) –
- class spinetoolbox.helpers.ColoredIcon(icon_file_name, icon_color, icon_size, colored=None)[source]
Bases:
PySide6.QtGui.QIcon
- class spinetoolbox.helpers.ColoredIconEngine(icon_file_name, icon_color, icon_size, colored=None)[source]
Bases:
PySide6.QtGui.QIconEngine
- spinetoolbox.helpers.make_icon_id(icon_code, color_code)[source]
Takes icon and color codes, and return equivalent integer.
- Parameters
icon_code (int) – icon’s code
color_code (int) – color code
- Returns
icon id
- Return type
int
- spinetoolbox.helpers.interpret_icon_id(display_icon)[source]
Takes a display icon id and returns an equivalent tuple of icon and color code.
- Parameters
display_icon (int, optional) – icon id
- Returns
icon’s code, color code
- Return type
tuple
- spinetoolbox.helpers.default_icon_id()[source]
Creates a default icon id.
- Returns
default icon’s id
- Return type
int
- class spinetoolbox.helpers.ProjectDirectoryIconProvider[source]
Bases:
PySide6.QtWidgets.QFileIconProvider
QFileIconProvider that provides a Spine icon to the Open Project Dialog when a Spine Toolbox project directory is encountered.
- spinetoolbox.helpers.ensure_window_is_on_screen(window, size)[source]
Checks if window is on screen and if not, moves and resizes it to make it visible on the primary screen.
- Parameters
window (QWidget) – a window to check
size (QSize) – desired window size if the window is moved
- spinetoolbox.helpers.first_non_null(s)[source]
Returns the first element in Iterable s that is not None.
- spinetoolbox.helpers.get_save_file_name_in_last_dir(qsettings, key, parent, caption, given_dir, filter_='')[source]
Calls QFileDialog.getSaveFileName in the directory that was selected last time the dialog was accepted.
- Parameters
qsettings (QSettings) – A QSettings object where the last directory is stored
key (string) – The name of the entry in the above QSettings
parent – Args passed to QFileDialog.getSaveFileName
caption – Args passed to QFileDialog.getSaveFileName
given_dir – Args passed to QFileDialog.getSaveFileName
filter – Args passed to QFileDialog.getSaveFileName
- Returns
filename str: selected filter
- Return type
str
- spinetoolbox.helpers.get_open_file_name_in_last_dir(qsettings, key, parent, caption, given_dir, filter_='')[source]
- spinetoolbox.helpers.try_number_from_string(text)[source]
Tries to convert a string to integer or float.
- Parameters
text (str) – string to convert
- Returns
converted value or text if conversion failed
- Return type
int or float or str
- spinetoolbox.helpers.focused_widget_has_callable(parent, callable_name)[source]
Returns True if the currently focused widget or one of its ancestors has the given callable.
- spinetoolbox.helpers.call_on_focused_widget(parent, callable_name)[source]
Calls the given callable on the currently focused widget or one of its ancestors.
- class spinetoolbox.helpers.ChildCyclingKeyPressFilter[source]
Bases:
PySide6.QtCore.QObject
Event filter class for catching next and previous child key presses. Used in filtering the Ctrl+Tab and Ctrl+Shift+Tab key presses in the Item Properties tab widget.
- spinetoolbox.helpers.select_gams_executable(parent, line_edit)[source]
Opens file browser where user can select a Gams executable (i.e. gams.exe on Windows).
- Parameters
parent (QWidget, optional) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_julia_executable(parent, line_edit)[source]
Opens file browser where user can select a Julia executable (i.e. julia.exe on Windows). Used in SettingsWidget and KernelEditor.
- Parameters
parent (QWidget, optional) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_julia_project(parent, line_edit)[source]
Shows file browser and inserts selected julia project dir to give line_edit. Used in SettingsWidget and KernelEditor.
- Parameters
parent (QWidget, optional) – Parent of QFileDialog
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_python_interpreter(parent, line_edit)[source]
Opens file browser where user can select a python interpreter (i.e. python.exe on Windows). Used in SettingsWidget and KernelEditor.
- Parameters
parent (QWidget) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_conda_executable(parent, line_edit)[source]
Opens file browser where user can select a conda executable.
- Parameters
parent (QWidget) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.is_valid_conda_executable(p)[source]
Checks that given path points to an existing file and the file name starts with ‘conda’.
- Parameters
p (str) – Absolute path to a file
- spinetoolbox.helpers.select_certificate_directory(parent, line_edit)[source]
Shows file browser and inserts selected certificate directory to given line edit.
- Parameters
parent (QWidget, optional) – Parent of QFileDialog
line_edit (QLineEdit) – Line edit where the selected dir path will be inserted
- spinetoolbox.helpers.file_is_valid(parent, file_path, msgbox_title, extra_check=None)[source]
Checks that given path is not a directory and it’s a file that actually exists. In addition, can be used to check if the file name in given file path starts with the given extra_check string. Needed in SettingsWidget and KernelEditor because the QLineEdits are editable. Returns True when file_path is an empty string so that we can use default values (e.g. from line edit place holder text). Returns also True when file_path is just ‘python’ or ‘julia’ so that user’s can use the python or julia in PATH.
- Parameters
parent (QWidget) – Parent widget for the message boxes
file_path (str) – Path to check
msgbox_title (str) – Title for message boxes
extra_check (str, optional) – String that must match the file name of the given file_path (without extension)
- Returns
True if given path is an empty string or if path is valid, False otherwise
- Return type
bool
- spinetoolbox.helpers.dir_is_valid(parent, dir_path, msgbox_title)[source]
Checks that given path is a directory. Needed in SettingsWdiget and KernelEditor because the QLineEdits are editable. Returns True when dir_path is an empty string so that we can use default values (e.g. from line edit place holder text)
- Parameters
parent (QWidget) – Parent widget for the message box
dir_path (str) – Directory path to check
msgbox_title (str) – Message box title
- Returns
True if given path is an empty string or if path is an existing directory, False otherwise
- Return type
bool
- spinetoolbox.helpers.make_settings_dict_for_engine(app_settings)[source]
Converts Toolbox settings to a dictionary acceptable by Engine.
- Parameters
app_settings (QSettings) – Toolbox settings
- Returns
Engine-compatible settings
- Return type
dict
- spinetoolbox.helpers.unique_name(prefix, existing)[source]
Creates a unique name in the form prefix (xx) where xx is a counter value. When prefix already contains a counter (xx), the value xx is updated.
- Parameters
prefix (str) – name prefix
existing (Iterable of str) – existing names
- Returns
unique name
- Return type
str
- spinetoolbox.helpers.parse_specification_file(spec_path, logger)[source]
Parses specification file.
- Parameters
spec_path (str) – path to specification file
logger (LoggerInterface) – a logger
- Returns
specification dict or None if the operation failed
- Return type
dict
- spinetoolbox.helpers.load_specification_from_file(spec_path, local_data_dict, spec_factories, app_settings, logger)[source]
Returns an Item specification from a definition file.
- Parameters
spec_path (str) – Path of the specification definition file
local_data_dict (dict) – specifications local data dict
spec_factories (dict) – Dictionary mapping specification type to ProjectItemSpecificationFactory
app_settings (QSettings) – Toolbox settings
logger (LoggerInterface) – a logger
- Returns
item specification or None if reading the file failed
- Return type
ProjectItemSpecification
- spinetoolbox.helpers.specification_from_dict(spec_dict, local_data_dict, spec_factories, app_settings, logger)[source]
Returns item specification from a dictionary.
- Parameters
spec_dict (dict) – Dictionary with the specification
local_data_dict (dict) – specifications local data
spec_factories (dict) – Dictionary mapping specification name to ProjectItemSpecificationFactory
app_settings (QSettings) – Toolbox settings
logger (LoggerInterface) – a logger
- Returns
specification or None if factory isn’t found.
- Return type
ProjectItemSpecification or NoneType
- spinetoolbox.helpers.plugins_dirs(app_settings)[source]
Loads plugins.
- Parameters
app_settings (QSettings) – Toolbox settings
- Returns
plugin directories
- Return type
list of str
- spinetoolbox.helpers.load_plugin_dict(plugin_dir, logger)[source]
Loads plugin dict from plugin directory.
- Parameters
plugin_dir (str) – path of plugin dir with “plugin.json” in it
logger (LoggerInterface) – a logger
- Returns
plugin dict or None if the operation failed
- Return type
dict
- spinetoolbox.helpers.load_plugin_specifications(plugin_dict, local_data_dict, spec_factories, app_settings, logger)[source]
Loads plugin’s specifications.
- Parameters
plugin_dict (dict) – plugin dict
local_data_dict (dict) – specifications local data dictionary
spec_factories (dict) – Dictionary mapping specification name to ProjectItemSpecificationFactory
app_settings (QSettings) – Toolbox settings
logger (LoggerInterface) – a logger
- Returns
mapping from plugin name to list of specifications or None if the operation failed
- Return type
dict
- spinetoolbox.helpers.load_specification_local_data(config_dir)[source]
Loads specifications’ project-specific data.
- Parameters
config_dir (str or Path) – project config dir
- Returns
specifications local data
- Return type
dict
- spinetoolbox.helpers.DB_ITEM_SEPARATOR = ' ǀ '[source]
Display string to separate items such as entity names.
- spinetoolbox.helpers.parameter_identifier(database, parameter, names, alternative)[source]
Concatenates given information into parameter value identifier string.
- Parameters
database (str, optional) – database’s code name
parameter (str) – parameter’s name
names (list of str) – name of the entity or class that holds the value
alternative (str or NoneType) – name of the value’s alternative
- spinetoolbox.helpers.disconnect(signal, *slots)[source]
Disconnects signal for the duration of a ‘with’ block.
- Parameters
signal (Signal) – signal to disconnect
*slots – slots to disconnect from
- class spinetoolbox.helpers.SignalWaiter(condition=None, timeout=None)[source]
Bases:
PySide6.QtCore.QObject
A ‘traffic light’ that allows waiting for a signal to be emitted in another thread.
- Parameters
condition (function, optional) – receiving the self.args and returning whether to stop waiting.
timeout (float, optional) – timeout in seconds; wait will raise after timeout
- spinetoolbox.helpers.signal_waiter(signal, condition=None, timeout=None)[source]
Gives a context manager that waits for the emission of given Qt signal.
- Parameters
signal (Any) – signal to wait
condition (Callable, optional) – a callable that takes the signal’s parameters and returns True to stop waiting
timeout (float, optional) – timeout in seconds; if None, wait indefinitely
- Yields
SignalWaiter – waiter instance
- class spinetoolbox.helpers.CustomSyntaxHighlighter(*arg, **kwargs)[source]
Bases:
PySide6.QtGui.QSyntaxHighlighter
- spinetoolbox.helpers.inquire_index_name(model, column, title, parent_widget)[source]
Asks for indexed parameter’s index name and updates model accordingly.
- Parameters
model (IndexedValueTableModel or ArrayModel) – a model with header that contains index names
column (int) – column index
title (str) – input dialog’s title
parent_widget (QWidget) – dialog’s parent widget
- spinetoolbox.helpers.restore_ui(window, app_settings, settings_group)[source]
Restores UI state from previous session.
- Parameters
window (QMainWindow) –
app_settings (QSettings) –
settings_group (str) –
- spinetoolbox.helpers.save_ui(window, app_settings, settings_group)[source]
Saves UI state for next session.
- Parameters
window (QMainWindow) –
app_settings (QSettings) –
settings_group (str) –
- spinetoolbox.helpers.bisect_chunks(current_data, new_data, key=None)[source]
Finds insertion points for chunks of data using binary search.
- Parameters
current_data (list) – sorted list where to insert new data
new_data (list) – data to insert
key (Callable, optional) – sort key
- Returns
sorted chunk of new data, insertion position
- Return type
tuple
- spinetoolbox.helpers.load_project_dict(project_config_dir, logger)[source]
Loads project dictionary from project directory.
- Parameters
project_config_dir (str) – project’s .spinetoolbox directory
logger (LoggerInterface) – a logger
- Returns
project dictionary
- Return type
dict
- spinetoolbox.helpers.load_local_project_data(project_config_dir, logger)[source]
Loads local project data.
- Parameters
project_config_dir (Path or str) – project’s .spinetoolbox directory
logger (LoggerInterface) – a logger
- Returns
project’s local data
- Return type
dict
- spinetoolbox.helpers.merge_dicts(source, target)[source]
Merges two dictionaries that may contain nested dictionaries recursively.
- Parameters
source (dict) – dictionary that will be merged to
target
target (dict) – target dictionary
- spinetoolbox.helpers._is_metadata_item(item)[source]
Identifies a database metadata record.
- Parameters
item (dict) – database item
- Returns
True if item is metadata item, False otherwise
- Return type
bool
- class spinetoolbox.helpers.HTMLTagFilter[source]
Bases:
html.parser.HTMLParser
HTML tag filter.
Initialize and reset this instance.
If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters.
- spinetoolbox.helpers.same_path(path1, path2)[source]
Checks if two paths are equal.
This is a lightweight version of os.path.samefile(): it doesn’t check if the paths point to the same file system object but rather takes into account file system case-sensitivity and such.
- Parameters
path1 (str) – a path
path2 (str) – a path
- Returns
True if paths point to the same
- Return type
bool
- spinetoolbox.helpers.solve_connection_file(connection_file, connection_file_dict)[source]
Returns the connection_file path, if it exists on this computer. If the path doesn’t exist, assume that it points to a path on another computer, in which case store the contents of connection_file_dict into a tempfile.
- Parameters
connection_file (str) – Path to a connection file
connection_file_dict (dict) –
- Returns
Path to a connection file on this computer.
- Return type
str
- class spinetoolbox.helpers.SealCommand(command_id=1)[source]
Bases:
PySide6.QtGui.QUndoCommand
A ‘meta’ command that does not store undo data but can be used in mergeWith methods of other commands.
- Parameters
command_id (int) – command id
- spinetoolbox.helpers.plain_to_rich(text)[source]
Turns plain strings into rich text.
- Parameters
text (str) – string to convert
- Returns
rich text string
- Return type
str