spinetoolbox.helpers

General helper functions and classes.

Module Contents

Classes

LinkType

Graphics scene's link types.

IconListManager

A class to manage icons for icon list widgets.

TransparentIconEngine

Specialization of QIconEngine with transparent background.

CharIconEngine

Specialization of QIconEngine used to draw font-based icons.

ColoredIcon

ColoredIconEngine

ProjectDirectoryIconProvider

QFileIconProvider that provides a Spine icon to the

ChildCyclingKeyPressFilter

Event filter class for catching next and previous child key presses.

QuietLogger

SignalWaiter

A 'traffic light' that allows waiting for a signal to be emitted in another thread.

CustomSyntaxHighlighter

HTMLTagFilter

HTML tag filter.

SealCommand

A 'meta' command that does not store undo data but can be used in mergeWith methods of other commands.

Functions

home_dir()

Returns user's home dir

format_log_message(msg_type, message[, show_datetime])

Adds color tags and optional time stamp to message.

busy_effect(func)

Decorator to change the mouse cursor to 'busy' while a function is processed.

create_dir(base_path[, folder, verbosity])

Create (input/output) directories recursively.

rename_dir(old_dir, new_dir, toolbox, box_title)

Renames directory.

open_url(url)

Opens the given url in the appropriate Web browser for the user's desktop environment,

set_taskbar_icon()

Set application icon to Windows taskbar.

supported_img_formats()

Checks if reading .ico files is supported.

pyside6_version_check()

Check that PySide6 version is at least 6.4.

get_datetime(show[, date])

Returns date and time string for appending into Event Log messages.

copy_files(src_dir, dst_dir[, includes, excludes])

Function for copying files. Does not copy folders.

erase_dir(path[, verbosity])

Deletes a directory and all its contents without prompt.

recursive_overwrite(logger, src, dst[, ignore, silent])

Copies everything from source directory to destination directory recursively.

tuple_itemgetter(itemgetter_func, num_indexes)

Change output of itemgetter to always be a tuple even for a single index.

format_string_list(str_list)

Returns a html unordered list from the given list of strings.

rows_to_row_count_tuples(rows)

Breaks a list of rows into a list of (row, count) tuples corresponding to chunks of successive rows.

object_icon(display_icon)

Creates and returns a QIcon corresponding to display_icon.

color_pixmap(pixmap, color)

make_icon_id(icon_code, color_code)

Takes icon and color codes, and return equivalent integer.

interpret_icon_id(display_icon)

Takes a display icon id and returns an equivalent tuple of icon and color code.

default_icon_id()

Creates a default icon id.

ensure_window_is_on_screen(window, size)

Checks if window is on screen and if not, moves and resizes it to make it visible on the primary screen.

first_non_null(s)

Returns the first element in Iterable s that is not None.

get_save_file_name_in_last_dir(qsettings, key, parent, ...)

Calls QFileDialog.getSaveFileName in the directory that was selected last time the dialog was accepted.

get_open_file_name_in_last_dir(qsettings, key, parent, ...)

try_number_from_string(text)

Tries to convert a string to integer or float.

focused_widget_has_callable(parent, callable_name)

Returns True if the currently focused widget or one of its ancestors has the given callable.

call_on_focused_widget(parent, callable_name)

Calls the given callable on the currently focused widget or one of its ancestors.

select_gams_executable(parent, line_edit)

Opens file browser where user can select a Gams executable (i.e. gams.exe on Windows).

select_julia_executable(parent, line_edit)

Opens file browser where user can select a Julia executable (i.e. julia.exe on Windows).

select_julia_project(parent, line_edit)

Shows file browser and inserts selected julia project dir to give line_edit.

select_python_interpreter(parent, line_edit)

Opens file browser where user can select a python interpreter (i.e. python.exe on Windows).

select_conda_executable(parent, line_edit)

Opens file browser where user can select a conda executable.

is_valid_conda_executable(p)

Checks that given path points to an existing file and the file name starts with 'conda'.

select_certificate_directory(parent, line_edit)

Shows file browser and inserts selected certificate directory to given line edit.

file_is_valid(parent, file_path, msgbox_title[, ...])

Checks that given path is not a directory and it's a file that actually exists.

dir_is_valid(parent, dir_path, msgbox_title)

Checks that given path is a directory. Needed in

make_settings_dict_for_engine(app_settings)

Converts Toolbox settings to a dictionary acceptable by Engine.

make_icon_background(color)

make_icon_toolbar_ss(color)

color_from_index(i, count[, base_hue, saturation, value])

unique_name(prefix, existing)

Creates a unique name in the form prefix (xx) where xx is a counter value.

parse_specification_file(spec_path, logger)

Parses specification file.

load_specification_from_file(spec_path, ...)

Returns an Item specification from a definition file.

specification_from_dict(spec_dict, local_data_dict, ...)

Returns item specification from a dictionary.

plugins_dirs(app_settings)

Loads plugins.

load_plugin_dict(plugin_dir, logger)

Loads plugin dict from plugin directory.

load_plugin_specifications(plugin_dict, ...)

Loads plugin's specifications.

load_specification_local_data(config_dir)

Loads specifications' project-specific data.

parameter_identifier(database, parameter, names, ...)

Concatenates given information into parameter value identifier string.

disconnect(signal, *slots)

Disconnects signal for the duration of a 'with' block.

signal_waiter(signal[, condition, timeout])

Gives a context manager that waits for the emission of given Qt signal.

inquire_index_name(model, column, title, parent_widget)

Asks for indexed parameter's index name and updates model accordingly.

preferred_row_height(widget[, factor])

restore_ui(window, app_settings, settings_group)

Restores UI state from previous session.

save_ui(window, app_settings, settings_group)

Saves UI state for next session.

bisect_chunks(current_data, new_data[, key])

Finds insertion points for chunks of data using binary search.

load_project_dict(project_config_dir, logger)

Loads project dictionary from project directory.

load_local_project_data(project_config_dir, logger)

Loads local project data.

merge_dicts(source, target)

Merges two dictionaries that may contain nested dictionaries recursively.

fix_lightness_color(color[, lightness])

scrolling_to_bottom(widget[, tolerance])

_is_metadata_item(item)

Identifies a database metadata record.

same_path(path1, path2)

Checks if two paths are equal.

solve_connection_file(connection_file, ...)

Returns the connection_file path, if it exists on this computer. If the path

remove_first(lst, items)

plain_to_rich(text)

Turns plain strings into rich text.

list_to_rich_text(data)

Turns a sequence of strings into rich text list.

plain_to_tool_tip(text)

Turns plain strings into rich text and empty strings/Nones to None.

Attributes

_matplotlib_version

DB_ITEM_SEPARATOR

Display string to separate items such as entity names.

spinetoolbox.helpers._matplotlib_version[source]
class spinetoolbox.helpers.LinkType[source]

Bases: enum.Enum

Graphics scene’s link types.

CONNECTION = 'connection'[source]
JUMP = 'jump'[source]
spinetoolbox.helpers.home_dir()[source]

Returns user’s home dir

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.set_taskbar_icon()[source]

Set application icon to Windows taskbar.

spinetoolbox.helpers.supported_img_formats()[source]

Checks if reading .ico files is supported.

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

init_model()[source]

Init model that can be used to display all icons in a list.

_model_data(index, role)[source]

Creates pixmaps as they’re requested by the data() method, to reduce loading time.

Parameters
  • index (QModelIndex) – index to the model

  • role (int) – data role

Returns

role-dependent model data

Return type

Any

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.

pixmap(size=QSize(512, 512), mode=None, state=None)[source]
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) –

paint(painter, rect, mode=None, state=None)[source]
class spinetoolbox.helpers.ColoredIcon(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide6.QtGui.QIcon

set_colored(colored)[source]
color(mode=QIcon.Normal)[source]
class spinetoolbox.helpers.ColoredIconEngine(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide6.QtGui.QIconEngine

color(mode=QIcon.Normal)[source]
set_colored(colored)[source]
_do_make_pixmap(mode, state)[source]
_make_pixmap(mode, state)[source]
pixmap(size, mode, state)[source]
spinetoolbox.helpers.color_pixmap(pixmap, color)[source]
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.

icon(info)[source]

Returns an icon for the file described by info.

Parameters

info (QFileInfo) – File (or directory) info

Returns

Icon for a file system resource with the given info

Return type

QIcon

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.

eventFilter(obj, event)[source]
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

class spinetoolbox.helpers.QuietLogger[source]
__getattr__(_)[source]
__call__(*args, **kwargs)[source]
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.make_icon_background(color)[source]
spinetoolbox.helpers.make_icon_toolbar_ss(color)[source]
spinetoolbox.helpers.color_from_index(i, count, base_hue=0.0, saturation=1.0, value=1.0)[source]
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

trigger(*args)[source]

Signal receiving slot.

wait()[source]

Wait for signal to be received.

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

property formats[source]
set_style(style)[source]
yield_formats(text)[source]
highlightBlock(text)[source]
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.preferred_row_height(widget, factor=1.5)[source]
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.fix_lightness_color(color, lightness=240)[source]
spinetoolbox.helpers.scrolling_to_bottom(widget, tolerance=1)[source]
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.

drain()[source]
handle_data(data)[source]
handle_starttag(tag, attrs)[source]
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

spinetoolbox.helpers.remove_first(lst, items)[source]
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

redo()[source]
id()[source]
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

spinetoolbox.helpers.list_to_rich_text(data)[source]

Turns a sequence of strings into rich text list.

Parameters

data (Sequence of str) – iterable to convert

Returns

rich text string

Return type

str

spinetoolbox.helpers.plain_to_tool_tip(text)[source]

Turns plain strings into rich text and empty strings/Nones to None.

Parameters

text (str, optional) – string to convert

Returns

rich text string or None

Return type

str or NoneType