spinetoolbox.helpers

General helper functions and classes.

authors
  1. Savolainen (VTT)

date

10.1.2018

Module Contents

Classes

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.

Functions

format_log_message(msg_type, message, show_datetime=True)

Adds color tags and optional time stamp to message.

add_message_to_document(document, message)

Adds a message to a document and return the cursor.

busy_effect(func)

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

create_dir(base_path, folder='', verbosity=False)

Create (input/output) directories recursively.

rename_dir(old_dir, new_dir, toolbox, box_title)

Renames directory. Called by ProjectItemModel.set_item_name()

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.

pyside2_version_check()

Check that PySide2 version is 5.14 or 5.15.

spine_engine_version_check()

Check if spine engine package is the correct version and explain how to upgrade if it is not.

get_datetime(show, date=True)

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

copy_files(src_dir, dst_dir, includes=None, excludes=None)

Function for copying files. Does not copy folders.

erase_dir(path, verbosity=False)

Deletes a directory and all its contents without prompt.

recursive_overwrite(logger, src, dst, ignore=None, silent=True)

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

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, caption, given_dir, filter_='')

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, caption, given_dir, filter_='')

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_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).

file_is_valid(parent, file_path, msgbox_title, extra_check=None)

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=0.0, saturation=1.0)

unique_name(prefix, existing)

Creates a unique name in the form “prefix X” where X is a number.

Attributes

_matplotlib_version

spinetoolbox.helpers._matplotlib_version[source]
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.add_message_to_document(document, message)[source]

Adds a message to a document and return the cursor.

Parameters
  • document (QTextDocument) –

  • message (str) –

Returns

QTextCursor

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. Called by ProjectItemModel.set_item_name()

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

Check that PySide2 version is 5.14 or 5.15. Version 5.15 is allowed but it is not promoted yet because user’s may need to update their VC++ runtime libraries on Windows.

qt_version is the Qt version used to compile PySide2 as string. E.g. “5.14.2” qt_version_info is a tuple with each version component of Qt used to compile PySide2. E.g. (5, 14, 2)

spinetoolbox.helpers.spine_engine_version_check()[source]

Check if spine engine package is the correct version and explain how to upgrade if it is not.

Returns

True if Spine Engine is of correct version, False otherwise

Return type

bool

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 (list) – 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(self)[source]

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

_model_data(self, 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: PySide2.QtGui.QIconEngine

Specialization of QIconEngine with transparent background.

pixmap(self, 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(self, painter, rect, mode=None, state=None)[source]
class spinetoolbox.helpers.ColoredIcon(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide2.QtGui.QIcon

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

Bases: PySide2.QtGui.QIconEngine

color(self)[source]
set_colored(self, colored)[source]
pixmap(self, 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: PySide2.QtWidgets.QFileIconProvider

QFileIconProvider that provides a Spine icon to the Open Project Dialog when a Spine Toolbox project directory is encountered.

icon(self, 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: PySide2.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(self, obj, event)[source]
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.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__(self, _)[source]
__call__(self, *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)[source]
spinetoolbox.helpers.unique_name(prefix, existing)[source]

Creates a unique name in the form “prefix X” where X is a number.

Parameters
  • prefix (str) – name prefix

  • existing (Iterable of str) – existing names

Returns

unique name

Return type

str

class spinetoolbox.helpers.SignalWaiter[source]

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

trigger(self)[source]

Signal receiving slot.

wait(self)[source]

Wait for signal to be received.