pycrossword  0.4
Pure-Python implementation of a crossword puzzle generator and editor
Classes | Functions | Variables
pycross.utils.utils Namespace Reference

Classes

class  JsonHiliter
 Syntax highlighter class for JSON. More...
 
class  QThreadStump
 Customized thread class (based on QThread) that adds progress, error etc. More...
 
class  Task
 
class  TaskSignals
 

Functions

def is_iterable (obj)
 Checks if a given object is iterable (i.e. More...
 
def getosname ()
 Gets the current OS (platform) name. More...
 
def generate_uuid ()
 Generates a random UUID (alphanumeric string). More...
 
def copy_file (path_from, path_to)
 Copies a file into another location. More...
 
def walk_dir (root_path, abs_path=True, recurse=True, dir_process_function=None, file_process_function=None, file_types=None)
 Iterates the files and folder in a given folder, performing some operations on the found files / folders. More...
 
def run_exe (args, external=False, capture_output=True, stdout=subprocess.PIPE, encoding=ENCODING, timeout=None, shell=False, **kwargs)
 Runs an executable and optionally returns the result. More...
 
def datetime_to_str (dt=None, strformat='%Y-%m-%d %H-%M-%S')
 Converts a Python datetime object to a string. More...
 
def timestamp_to_str (ts=None, strformat='%Y-%m-%d %H-%M-%S')
 Converts a timestamp (Unix time) to a string. More...
 
def str_to_datetime (text, strformat='%Y-%m-%d %H-%M-%S')
 Converts a string to a Python datetime object. More...
 
def str_to_timestamp (text, strformat='%Y-%m-%d %H-%M-%S')
 Converts a string to a timestamp (Unix time). More...
 
def get_tempdir ()
 Gets the path to the Temp directory on the system. More...
 
def bytes_human (value, suffix='B')
 Returns a human-formatted file size as a string, e.g. More...
 
def restart_app (closefunction)
 Restarts this app. More...
 
def file_types_registered (filetypes=('xpf', 'ipuz', 'pxjson'))
 Checks if the given file type associations are registered in the OS. More...
 
def register_file_types (filetypes=('xpf', 'ipuz', 'pxjson'), register=True)
 Registers file associations in the current OS for the given file types and application. More...
 
def pluggable (category)
 Plugin decorator for custom plugins. More...
 
def collect_pluggables (parent_object, indent=' ')
 Collects the names and signatures of wrapped methods from a class instance. More...
 
def get_builtins ()
 Collects the names and signatures of builtin Python functions. More...
 
def get_script_members (script)
 Retrieves the names of all variables in the given Python script. More...
 
def make_font (family, size=-1, weight=-1, italic=False, font_unit='pt')
 Constructs a QtGui.QFont object from given font parameters. More...
 
def MsgBox (what, parent=None, title='pyCross', msgtype='info', btn=None, detailedText='', infoText='', execnow=True)
 Displays a GUI message dialog and returns the user's reply. More...
 
def UserInput (dialogtype='text', parent=None, title='pyCross', label='', value=None, textmode='normal', valrange=None, decimals=1, step=1, comboeditable=True, comboitems=[])
 Displays a GUI user input dialog and returns the user's input. More...
 
def clipboard_copy (value, valtype='text')
 Copies a given value / object to the system clipboard. More...
 
def clipboard_get (valtype='text')
 Retrieves the contents of the system clipboard. More...
 
def clipboard_clear ()
 Clears the system clipboard. More...
 
def stylesheet_load (style, dequote=True, strip_sz=True, units=('pt', 'px'))
 Returns a Qt widget's stylesheet as a Python dictionary. More...
 
def stylesheet_dump (d, quoted_keys=('font-family',), add_units={ 'font-size':'pt', 'border':'px', 'border-width':'px'})
 Serializes a Python dictionary representing a widget's style sheet into a string. More...
 
def font_weight_css2qt (weight, default=0)
 Converts CSS font weight constants to Qt font weight constants. More...
 
def font_weight_qt2css (weight, default=0)
 Converts Qt font weight constants to CSS font weight constants. More...
 
def font_from_stylesheet (style, font_unit='pt', default_font=None)
 Constructs a Qt font object (QtGui.QFont) from a Qt style sheet string. More...
 
def font_to_stylesheet (font, style, font_unit='pt')
 Stores a give Qt font in a style sheet string and returns the modified style sheet. More...
 
def color_from_stylesheet (style, tag='background-color', default='black')
 Returns a Qt color object from a Qt style sheet string. More...
 
def color_to_stylesheet (color, style, tag='background-color')
 Stores a Qt color object in a style sheet string and returns the modified style sheet. More...
 
def property_to_stylesheet (propname, propvalue, style)
 Stores a property (attribute) in a style sheet string and returns the modified style sheet. More...
 
def property_from_stylesheet (propname, style, default=None)
 Reads a property from a style sheet string and returns its value. More...
 

Variables

dictionary MSGBOX_BUTTONS
 Button names, their localized names and roles used in MsgBox() function. More...
 
dictionary MSGBOX_TYPES
 Types of MsgBox dialogs used in MsgBox() function. More...
 

Function Documentation

◆ bytes_human()

def pycross.utils.utils.bytes_human (   value,
  suffix = 'B' 
)

Returns a human-formatted file size as a string, e.g.

"1Mi" (1 megabyte), "15GBi" (15 gigabytes) etc.

Parameters
valuefloat the file size value to convert
suffixstr the size suffix, default = 'B' (bytes)
Returns
str string representation of the file size

◆ clipboard_clear()

def pycross.utils.utils.clipboard_clear ( )

Clears the system clipboard.

◆ clipboard_copy()

def pycross.utils.utils.clipboard_copy (   value,
  valtype = 'text' 
)

Copies a given value / object to the system clipboard.

Parameters
valuestr | QtCore.QMimeData | QtGui.QPixmap | QtGui.QImage value to copy
valtypestr type of the value, any of:
  • 'text' (default): text string
  • 'mime': MIME data as a QtCore.QMimeData object
  • 'pixmap': bitmap (pixmap) as a QtGui.QPixmap object
  • 'image': image as a QtGui.QImage object

◆ clipboard_get()

def pycross.utils.utils.clipboard_get (   valtype = 'text')

Retrieves the contents of the system clipboard.

Parameters
valtypestr type of the value, any of:
  • 'text' (default): text string
  • 'mime': MIME data as a QtCore.QMimeData object
  • 'pixmap': bitmap (pixmap) as a QtGui.QPixmap object
  • 'image': image as a QtGui.QImage object
Returns
str | QtCore.QMimeData | QtGui.QPixmap | QtGui.QImage the clipboard contents as a single object

◆ collect_pluggables()

def pycross.utils.utils.collect_pluggables (   parent_object,
  indent = '    ' 
)

Collects the names and signatures of wrapped methods from a class instance.

Used in this app to generate the list of pycross::gui::MainWindow methods that can be overridden in user plugin classes.

Parameters
parent_objectPython object object that defines wrapped methods.
Warning
Only decorated methods will be retrieved by this function! This is done on purpose so that the object may expose only specific methods for plugins.
Parameters
indentstr indentation for method docs, if present
Returns
list of str list of wrapped method signatures, e.g.:
['def foo(arg1, arg2):',
'def bar():',
'def commentedfunc():\n This is comment']

◆ color_from_stylesheet()

def pycross.utils.utils.color_from_stylesheet (   style,
  tag = 'background-color',
  default = 'black' 
)

Returns a Qt color object from a Qt style sheet string.

Parameters
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
tagstr the specific color attribute name in the style sheet
defaultstr default color name used in case of failure
Returns
QtGui.QColor Qt color object constructed from the style sheet
See also
stylesheet_load(), color_to_stylesheet()

◆ color_to_stylesheet()

def pycross.utils.utils.color_to_stylesheet (   color,
  style,
  tag = 'background-color' 
)

Stores a Qt color object in a style sheet string and returns the modified style sheet.

Parameters
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
tagstr the specific color attribute name in the style sheet
Returns
str updated style sheet string
See also
stylesheet_load(), stylesheet_dump(), color_from_stylesheet()

◆ copy_file()

def pycross.utils.utils.copy_file (   path_from,
  path_to 
)

Copies a file into another location.

Parameters
path_fromstr the original file to copy
path_tostr the new file path or directory to copy the file to
Returns
str the path to the newly created (copied) file

◆ datetime_to_str()

def pycross.utils.utils.datetime_to_str (   dt = None,
  strformat = '%Y-%m-%d %H-%M-%S' 
)

Converts a Python datetime object to a string.

Parameters
dtdatetime Python datetime object representing a date and/or time; if None (default), the current date and time will be taken
strformatstr format string compliant to the Python datetime formatting
Returns
str string representation of the date / time

◆ file_types_registered()

def pycross.utils.utils.file_types_registered (   filetypes = ('xpf', 'ipuz', 'pxjson'))

Checks if the given file type associations are registered in the OS.

Parameters
filetypesiterable collection of file extensions to check (without leading dot)
Returns
bool True if the file types are associated with this app, False otherwise TODO: implement for OSX (Darwin)

◆ font_from_stylesheet()

def pycross.utils.utils.font_from_stylesheet (   style,
  font_unit = 'pt',
  default_font = None 
)

Constructs a Qt font object (QtGui.QFont) from a Qt style sheet string.

Parameters
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
font_unitstr font size unit: either 'pt' (points) or 'px' (pixels)
default_fontQtGui.QFont default font used in case of failure
Returns
QtGui.QFont Qt font object
See also
stylesheet_load(), make_font(), font_to_stylesheet()

◆ font_to_stylesheet()

def pycross.utils.utils.font_to_stylesheet (   font,
  style,
  font_unit = 'pt' 
)

Stores a give Qt font in a style sheet string and returns the modified style sheet.

Parameters
fontQtGui.QFont Qt font object
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
font_unitstr font size unit: either 'pt' (points) or 'px' (pixels)
Returns
str updated style sheet string
See also
stylesheet_load(), stylesheet_dump(), font_from_stylesheet()

◆ font_weight_css2qt()

def pycross.utils.utils.font_weight_css2qt (   weight,
  default = 0 
)

Converts CSS font weight constants to Qt font weight constants.

Parameters
weightint font weight in CSS style sheet
defaultint default Qt font weight used on failure to get the corresponding Qt weight value
Returns
int Qt font weight constant, such as QtGui.QFont.Normal or QtGui.QFont.Bold
See also
globalvars::FONT_WEIGHTS, font_weight_qt2css()

◆ font_weight_qt2css()

def pycross.utils.utils.font_weight_qt2css (   weight,
  default = 0 
)

Converts Qt font weight constants to CSS font weight constants.

Parameters
weightint font weight Qt constant, such as QtGui.QFont.Normal or QtGui.QFont.Bold
defaultint default CSS stylesheet font weight used on failure to get the corresponding CSS weight value
Returns
int CSS font weight constant
See also
globalvars::FONT_WEIGHTS, font_weight_css2qt()

◆ generate_uuid()

def pycross.utils.utils.generate_uuid ( )

Generates a random UUID (alphanumeric string).

Returns
str UUID compliant to RFC 4122
See also
Python docs

◆ get_builtins()

def pycross.utils.utils.get_builtins ( )

Collects the names and signatures of builtin Python functions.

Returns
list of str list of names and signatures, e.g. 'sort(iterable, key)'
See also
collect_pluggables()

◆ get_script_members()

def pycross.utils.utils.get_script_members (   script)

Retrieves the names of all variables in the given Python script.

This function collects all variables (builtin, global, local) that the given script references or creates using the Jedi autocompletion package. The resulting list of names can be then used for autocompletion. This app uses this function in the user plugin script editor.

Parameters
scriptstr source script in Python
Returns
list of str list of referenced variables (functions also have signatures, i.e. arguments in brackets)

◆ get_tempdir()

def pycross.utils.utils.get_tempdir ( )

Gets the path to the Temp directory on the system.

Returns
str full path to the system Temp directory

◆ getosname()

def pycross.utils.utils.getosname ( )

Gets the current OS (platform) name.

Returns
str platform name, e.g. 'Windows' or 'Linux'

◆ is_iterable()

def pycross.utils.utils.is_iterable (   obj)

Checks if a given object is iterable (i.e.

contains elements like an array).

Parameters
objthe object to check
Returns
bool True if the object is iterable (array-like) and False otherwise

◆ make_font()

def pycross.utils.utils.make_font (   family,
  size = -1,
  weight = -1,
  italic = False,
  font_unit = 'pt' 
)

Constructs a QtGui.QFont object from given font parameters.

Parameters
familystr font familty name, e.g. 'Arial'
sizeint font size in points or pixels (default = -1: default size)
weightint font weight (default = -1: default size). The following constants can be used:
  • QFont::Thin 0
  • QFont::ExtraLight 12
  • QFont::Light 25
  • QFont::Normal 50
  • QFont::Medium 57
  • QFont::DemiBold 63
  • QFont::Bold 75
  • QFont::ExtraBold 81
  • QFont::Black 87
italicbool True to set the italic style
font_unitstr font size unit: 'pt' = points (default), 'px' = pixels
Returns
QtGui.QFont created font object

◆ MsgBox()

def pycross.utils.utils.MsgBox (   what,
  parent = None,
  title = 'pyCross',
  msgtype = 'info',
  btn = None,
  detailedText = '',
  infoText = '',
  execnow = True 
)

Displays a GUI message dialog and returns the user's reply.

Parameters
whatstr message dialog text (body)
parentQtWidgets.QWidget parent widget for the dialog or None if no parent is required
titlestr dialog title (caption)
msgtypestr dialog type affecting the icon: 'error', 'info', 'ask', 'warn' or '-' (no icon)
btnlist of str list of button names to be placed in the dialog – see MSGBOX_BUTTONS
detailedTextstr additional text below the dialog text to be used for extra explanations, notes etc.
infoTextstr additional text below the dialog text to be used for extra explanations, notes etc.
execnowbool if True (default), the dialog will be executed (displayed) on creation
Returns
str | QtWidgets.QMessageBox user's reply (if execnow is True) as the name of the clicked button or an empty string if cancelled; or the dialog object if execnow is False

◆ pluggable()

def pycross.utils.utils.pluggable (   category)

Plugin decorator for custom plugins.

Searches the Plugin manager for methods (function) in the given category having the same name as the wrapped method and calls the plugin methods in the order as stored in the Plugin manager for that category. Plugin methods can be called:

  • before the original method
  • after the original method
  • instead of the original method, depending on the wraptype attribute of the plugin method ('before', 'after' or 'replace').
    Parameters
    categorystr name of the plugin category (e.g. 'general')
    See also
    utils.pluginmanager, utils.pluginbase

◆ property_from_stylesheet()

def pycross.utils.utils.property_from_stylesheet (   propname,
  style,
  default = None 
)

Reads a property from a style sheet string and returns its value.

Parameters
propnamestr name of the property to store, e.g. 'background-color'
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
defaultstr | int | float default value used in case of failure
Returns
str | int | float the value of the queried property

◆ property_to_stylesheet()

def pycross.utils.utils.property_to_stylesheet (   propname,
  propvalue,
  style 
)

Stores a property (attribute) in a style sheet string and returns the modified style sheet.

Parameters
propnamestr name of the property to store, e.g. 'background-color'
propvaluestr value of the property to store, e.g. 'black'
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
Returns
str updated style sheet string
See also
stylesheet_load(), stylesheet_dump(), property_from_stylesheet()

◆ register_file_types()

def pycross.utils.utils.register_file_types (   filetypes = ('xpf', 'ipuz', 'pxjson'),
  register = True 
)

Registers file associations in the current OS for the given file types and application.

After a call of this method succeeds, files with the indicated extensions can be launched directly with the 'open' verb, that is, by double-clicking or hitting Enter on them in the system file browser. These files will be opened with pycrossword thanks to the system-wide permanent file associations. The mechanism uses the System Registry on Windows and MIME types on Linux.

Parameters
filetypesiterable collection of file extensions to check (without leading dot)
registerbool set True to register the associations, False to unregister TODO: implement for OSX (Darwin)

◆ restart_app()

def pycross.utils.utils.restart_app (   closefunction)

Restarts this app.

Parameters
closefunctioncallable function to close down the app (e.g. gui::MainWindow::on_act_exit)

◆ run_exe()

def pycross.utils.utils.run_exe (   args,
  external = False,
  capture_output = True,
  stdout = subprocess.PIPE,
  encoding = ENCODING,
  timeout = None,
  shell = False,
**  kwargs 
)

Runs an executable and optionally returns the result.

Parameters
argslist | str arguments passed to the executable (a list of args or a single string)
externalbool whether the executable must be called as an external (detached) process; this basically means that the process will be created asynchronously, not blocking the main application process to wait for the result; if False (default), the executable will be called synchronously, waiting for the result and blocking the main process
capture_outputbool whether the console output of the executable must be captured
stdoutfile-like file / stream to channel the STDOUT and STDERR streams to; the default value is subprocess.PIPE, meaning that the output will be returned by the method
encodingstr the string encoding to use for the executable's output (default = UTF8)
timeoutfloat number of seconds to wait until timeout (default = None, i.e. wait infinitely)
shellbool whether the executable must be called via the system shell (default = False)
kwargskeyword arguments additional keyword arguments passed to subprocess.Popen
Returns
subprocess.CompletedProcess completed process results, see Python docs

◆ str_to_datetime()

def pycross.utils.utils.str_to_datetime (   text,
  strformat = '%Y-%m-%d %H-%M-%S' 
)

Converts a string to a Python datetime object.

Parameters
textstr datetime string to convert
strformatstr format string compliant to the Python datetime formatting
Returns
datetime Python datetime object

◆ str_to_timestamp()

def pycross.utils.utils.str_to_timestamp (   text,
  strformat = '%Y-%m-%d %H-%M-%S' 
)

Converts a string to a timestamp (Unix time).

Parameters
textstr datetime string to convert
strformatstr format string compliant to the Python datetime formatting
Returns
float timestamp, i.e. number of seconds since epoch (Unix time)

◆ stylesheet_dump()

def pycross.utils.utils.stylesheet_dump (   d,
  quoted_keys = ('font-family',),
  add_units = {'font-size': 'pt', 'border': 'px', 'border-width': 'px'} 
)

Serializes a Python dictionary representing a widget's style sheet into a string.

This is the reverse of stylesheet_load(). The resulting string is compatible with the Qt style sheets.

Parameters
quoted_keysiterable attribute names whose values must be quoted
add_unitsdict attribute names and their corresponding size units that will be appended to numerical values of those attributes
Returns
str Qt5-compatible style sheet string
See also
stylesheet_load()

◆ stylesheet_load()

def pycross.utils.utils.stylesheet_load (   style,
  dequote = True,
  strip_sz = True,
  units = ('pt', 'px') 
)

Returns a Qt widget's stylesheet as a Python dictionary.

This is the reverse of stylesheet_dump().

Parameters
stylestr the widget style sheet that is retrieved with the styleSheet() method of QtWidgets.QWidget derived classes
dequotebool whether to dequote (strip quotation symbols from) values found in the style sheet (default = True)
strip_szbool whether to drop size units like 'pt' or 'px' and return just the numerical values (default = True)
unitsiterable unit names that can be stripped with the strip_sz option
Returns
dict Python dictionary with style sheet attributes, e.g. ‘{'font-family’: 'Arial', 'font-size': 12, ...}`
See also
stylesheet_dump()

◆ timestamp_to_str()

def pycross.utils.utils.timestamp_to_str (   ts = None,
  strformat = '%Y-%m-%d %H-%M-%S' 
)

Converts a timestamp (Unix time) to a string.

Parameters
tsfloat timestamp, i.e. number of seconds since epoch (Unix time) if None (default), the current timestamp will be taken
strformatstr format string compliant to the Python datetime formatting
Returns
str string representation of the timestamp

◆ UserInput()

def pycross.utils.utils.UserInput (   dialogtype = 'text',
  parent = None,
  title = 'pyCross',
  label = '',
  value = None,
  textmode = 'normal',
  valrange = None,
  decimals = 1,
  step = 1,
  comboeditable = True,
  comboitems = [] 
)

Displays a GUI user input dialog and returns the user's input.

Parameters
dialogtypestr input result type; can be any of:
  • 'text' (default) usual one-line text string
  • 'multitext' multi-line text string
  • 'int' integer numeric value
  • 'float' floating-point numeric value
  • 'item' an item string chosen from a drop-down menu
parentQtWidgets.QWidget parent widget for the dialog or None if no parent is required
titlestr dialog title (caption)
labelstr optional label for the input field
valuestr | int | float default value set in the input field (default = None: empty field)
textmodestr text masking; any of:
  • 'normal' (default) no text masking
  • 'noecho' no text will appear in the input field when typed
  • 'password' masked text (with bullet placeholders)
  • 'passwordonedit' masked text when editing, otherwise normal
valrange2-tuple min/max range of the numerical value, e.g. (1, 100)
decimalsint number of decimals after the floating point, default = 1
stepint step value for the int / float spinbox, default = 1
comboeditablebool if True, the item selection combobox for the 'item' mode will be editable, otherwise non-editable
comboitemslist list of items to choose from in the 'item' input mode
Returns
str | int | float the user's input

◆ walk_dir()

def pycross.utils.utils.walk_dir (   root_path,
  abs_path = True,
  recurse = True,
  dir_process_function = None,
  file_process_function = None,
  file_types = None 
)

Iterates the files and folder in a given folder, performing some operations on the found files / folders.

Parameters
root_pathstr the starting (root) directory path to start searching from
abs_pathbool if True (default), the given root path will be made absolute (relative to the current working directory); if False, it will be left as it is
recursebool whether to recurse into the found subdirectories (default = True)
dir_process_functioncallable callback function for found subdirectories. The callback takes a single argument - the full directory path.
file_process_functioncallable callback function for found files. The callback takes a single argument - the full file path.
file_typesiterable collection of file extensions (without the leading dot) that will be respected when a file is found; if None (default), no file type filtering will be done.

Variable Documentation

◆ MSGBOX_BUTTONS

dictionary pycross.utils.utils.MSGBOX_BUTTONS
Initial value:
1 = {'ok': (_('OK'), QtWidgets.QMessageBox.AcceptRole), 'yes': (_('Yes'), QtWidgets.QMessageBox.YesRole),
2  'no': (_('No'), QtWidgets.QMessageBox.NoRole), 'cancel': (_('Cancel'), QtWidgets.QMessageBox.RejectRole),
3  'yesall': (_('Yes to All'), QtWidgets.QMessageBox.YesRole), 'noall': (_('No to All'), QtWidgets.QMessageBox.NoRole),
4  'apply': (_('Apply'), QtWidgets.QMessageBox.ApplyRole), 'reset': (_('Reset'), QtWidgets.QMessageBox.ResetRole),
5  'open': (_('Open'), QtWidgets.QMessageBox.AcceptRole), 'save': (_('Save'), QtWidgets.QMessageBox.AcceptRole),
6  'close': (_('Close'), QtWidgets.QMessageBox.RejectRole), 'discard': (_('Discard'), QtWidgets.QMessageBox.DestructiveRole),
7  'restoredefaults': (_('Restore Defaults'), QtWidgets.QMessageBox.ResetRole), 'help': (_('Help'), QtWidgets.QMessageBox.HelpRole),
8  'saveall': (_('Save All'), QtWidgets.QMessageBox.AcceptRole), 'abort': (_('Abort'), QtWidgets.QMessageBox.RejectRole),
9  'retry': (_('Retry'), QtWidgets.QMessageBox.AcceptRole), 'ignore': (_('Ignore'), QtWidgets.QMessageBox.AcceptRole)}

Button names, their localized names and roles used in MsgBox() function.

◆ MSGBOX_TYPES

dictionary pycross.utils.utils.MSGBOX_TYPES
Initial value:
1 = {'error': (QtWidgets.QMessageBox.Critical, ['ok']), 'warn': (QtWidgets.QMessageBox.Warning, ['ok']), 'ask': (QtWidgets.QMessageBox.Question, ['yes', 'no']),
2  'info': (QtWidgets.QMessageBox.Information, ['ok']), '-': (QtWidgets.QMessageBox.NoIcon, ['ok'])}

Types of MsgBox dialogs used in MsgBox() function.