mari.utils
Contains small utility functions for use by all other areas of Python functionality.
Miscellaneous Mari scripts.
- class mari.utils.misc.Dialog(parent=None, flags=<WindowType.Dialog: 3>)
Bases:
QDialogA Mari specific dialog.
Will pause the shader compilation when the dialog is shown to make the UI more responsive when working on complexed scenes with low frame rates.
- __init__(parent=None, flags=<WindowType.Dialog: 3>)
Initialize this instance.
- hideEvent(event)
Unpause shader compilation on hide of a modal dialog.
Only pause shader compilation when the dialog is blocking as it would look like a bug if a non-blocking dialog went behind the main window and the compilation was still paused.
- showEvent(event)
Pause shader compilation on show of a modal dialog.
Only pause shader compilation when the dialog is blocking as it would look like a bug if a non-blocking dialog went behind the main window and the compilation was still paused.
- staticMetaObject = PySide6.QtCore.QMetaObject("Dialog" inherits "QDialog": )
- class mari.utils.misc.PushButton(icon, text)
Bases:
QPushButtonSubclass of QPushButton that changes its icon on hover.
A specialised push button that emulates the appeal of a tool bar button, where the state of the button changes on hover to enabled and disabled.
- __init__(icon, text)
Initialize this instance.
- staticMetaObject = PySide6.QtCore.QMetaObject("PushButton" inherits "QPushButton": )
- class mari.utils.misc.PushButtonIconSetter(pushButton, icon)
Bases:
QObjectClass that watches the hover state of a button and changes its icon state.
- __init__(pushButton, icon)
Initialize this instance.
- eventFilter(watched, event)
Event filter to change the button icon on hover.
- staticMetaObject = PySide6.QtCore.QMetaObject("PushButtonIconSetter" inherits "QObject": )
- mari.utils.misc.checkProjectAndGeoValidity()
Check if the current object is a valid UV-based geometry for the example to run on.
- Returns:
True if a project is open and the current geometry is a UV-based geometry.
- mari.utils.misc.createCustomDisplayWidget(display_name, width, height)
Create a widget into which the Display Render CAPI plugins will render.
- Parameters:
display_name – The name of custom display widget
width – The initial width of the widget and its offscreen buffer of custom display widget
height – The initial height of the widget and its offscreen buffer of custom display widget
- Returns:
The QWidget object
- mari.utils.misc.execDialog(dlg)
Execute the given dialog in a modal state and return the result.
This function is a helper for QDialog.exec(), which cannot be called directly because “exec” is a Python keyword.
- Parameters:
dlg – A dialog, or any object with an “exec” function.
- Returns:
The result of the exec() call.
- mari.utils.misc.getExistingDirectory(parent=None, caption='', dir='')
Get an existing directory, selected by the user.
- Parameters:
parent – Parent widget to center the dialog over
caption – Title of the dialog box
dir – Initial working directory of the dialog
- Returns:
The name of the directory selected by the user, or an empty string if the user pressed Cancel
- mari.utils.misc.getOpenFileName(parent=None, caption='', dir='', filter='', selected_filter=None, options=0)
Open an existing file for the user to select.
- Parameters:
parent – Parent widget to center the dialog over
caption – Title of the dialog box
dir – Initial working directory of the dialog. If it includes a file, the file will be selected
filter – Only files that match the given filter are shown
selected_filter – Initial selected filter
options – Qt option flags to indicate how to run the dialog (see U{this page<http://doc.qt.nokia.com/4.5/qfiledialog.html#Option-enum>} for details)
- Returns:
The name of the file selected by the user, or an empty string if the user pressed Cancel
- mari.utils.misc.getSaveFileName(parent=None, caption='', dir='', filter='', selected_filter=None, options=0, save_filename='')
Return a file name to save to, selected by the user.
If both dir and save_filename are supplied, the function combines the two if possible: an absolute path in save_filename will take precedence, but a relative path in save_filename will be appended to dir. Any file name component from save_filename will be appended to the resulting path.
- Parameters:
parent – Parent widget to center the dialog over
caption – Title of the dialog box
dir – Initial working directory of the dialog. If it includes a file, the file will be selected
filter – Only files that match the given filter are shown
selected_filter – Initial selected filter
options – Qt option flags to indicate how to run the dialog (see U{this page<http://doc.qt.nokia.com/4.5/qfiledialog.html#Option-enum>} for details)
save_filename – The default file name to save as. This may include a path if desired
- Returns:
The name of the file selected by the user, or an empty string if the user pressed Cancel
- mari.utils.misc.getUniqueName(name_base, name_list)
Return the given name with modifications to ensure it is unique in the given list.
For example, getUniqueName(‘test’, [‘hello’, ‘test’]) will return ‘test(0)’.
- Parameters:
name_base (str) – The name to check for uniqueness
name_list (list) – A list to check for the name in
- mari.utils.misc.incName(name)
Return or increment the parenthesised number in a channel name.
For example, incName(‘color’) returns ‘color(1)’, and incName(‘color(1)’) returns ‘color(2)’.
- mari.utils.misc.isFileReadable(root, filename)
Perform 3 quick validations to ensure the specified file is readable, not hidden or a system file.
- Parameters:
root – Root path location of file
filename – The name of the file to validate is readable
- Returns:
bool – The file is readable
- mari.utils.misc.mariDisabledIcon(fileName)
Return the corresponding disabled icon, given an icon’s file name.
- Parameters:
fileName – The name of the icon that is requested
- Returns:
The disabled QIcon object
- mari.utils.misc.mariIcon(fileName)
Return the icon, given an icon’s file name.
- Parameters:
fileName – The name of the icon that is requested
- Returns:
The QIcon object
- mari.utils.misc.mariPlainIcon(fileName)
Return the 24x24 icon from the icons folder.
- Parameters:
fileName – The name of the icon that is requested
- Returns:
The QIcon object
- mari.utils.misc.message(text, title='Message', buttons=<StandardButton.Ok: 1024>, icon=Icon.Information, details=None)
Display a simple Qt message box, with no return value.
This is a helper for the standard Qt message box, which is called using the function .exec(). Unfortunately “exec” is a keyword in Python, so we need to use some awkward syntax to get around it.
Note
The parameters are in a different order to the standard Qt call. This is for convenience for users who just want to specify a message.
- Parameters:
title – The title (or caption) of the message box
buttons – The buttons to show (the default is just the “OK” button)
icon – The icon to display on the box (the default is the ‘i’, or information, icon)
details – If specified, this provides extra text to display in a “Show Details” box
See also
messageResult
- Returns:
None
- mari.utils.misc.messageAndLog(text, title='Message', ui=True, console=True, log=True)
Display a message to the UI, Python console, and the logging.
This is used to print the message to all 3 UI, python console and verbose logging.
- Parameters:
text – The text to print out.
title – The title (or caption) of the message box
ui – Toggle to pop up message box
console – Toggle to print to python console
log – Toggle to print to verbose logging
- Returns:
None
- mari.utils.misc.messageResult(text, title='Message', buttons=<StandardButton.Ok: 1024>, icon=Icon.Information, details=None)
Display a simple Qt message box and return the button pressed.
This is a helper for the standard Qt message box, which is called using the function .exec(). Unfortunately “exec” is a keyword in Python, so we need to use some awkward syntax to get around it.
Note
The parameters are in a different order to the standard Qt call. This is for convenience for users who just want to specify a message.
- Parameters:
title – The title (or caption) of the message box
buttons – The buttons to show (the default is just the “OK” button)
icon – The icon to display on the box (the default is the ‘i’, or information, icon)
details – If specified, this provides extra text to display in a “Show Details” box
See also
message
- Returns:
The result of the QMessageBox.exec call
- mari.utils.misc.reloadAll()
Reload all scripts that aren’t built-in or from the system library path.
This function determines the system path by checking where the “os” module comes from.
- mari.utils.misc.setTimer(interval_sec, func, single_shot=True)
Set a once-off or repeating timer to call the given Python function.
Note: you must store the returned object, or it will be deleted and the timer function will not be called.
- Parameters:
interval_sec – Interval before calling the timer function, in seconds
func – The callable (e.g. function) to call after the specified time
single_shot – True to call the timer function once, or False to call repeatedly
Node generator for Mari shader networks.
- class mari.utils.node_generator.Node(name, shortName=None)
Bases:
objectThis class generates an xml description of a shader network node.
- __init__(name, shortName=None)
Initialize this instance.
- addAttrib(name, kind, minimum, maximum, default=None, group='')
Add an attribute to this node with the given name, type, range, default value, and group.
- addInput(name, pos, defaultGlsl=(1, 0, 0, 1))
Add an input to this node with the given name, position, and default GLSL value.
- save(name=None)
Save this node to an XML file with the given name.
- setGlsl(code)
Set the GLSL code for this node.
- setName(name, shortName)
Set the name and short name of this node.
- toString()
Generate an XML string representation of this node.
OpenColorIO (color management) related Mari scripts.
- class mari.utils.ocio.MessageType
Bases:
objectMessage type identifiers for logging and user feedback.
- DEBUG = 1
- ERROR = 4
- INFO = 2
- WARNING = 3
- mari.utils.ocio.activeViewDisplays(config)
Return a list of active view displays for the given OCIO config.
- mari.utils.ocio.analyticalViewEntries(config)
Return all registered analytical view entries applicable to the given OCIO config.
Returns a list of (label, display, view, glsl_declaration, func_name) tuples for each registered entry whose config_matcher matches config. ‘label’ is the combobox string, e.g. ‘sRGB (ACES) - Analytical’.
- Parameters:
config – A PyOpenColorIO.Config object for the currently active OCIO config.
- Returns:
List of (label, display, view, glsl_declaration, func_name) tuples. Empty if no registered entries match the given config.
- mari.utils.ocio.buildLoadPath(path)
Convert a path saved out to disk back into a form usable by the application.
- mari.utils.ocio.buildSavePath(path)
Convert a path into a form suitable for sharing across different platforms and installations.
- mari.utils.ocio.configFileFilter()
Return a filter string.
- mari.utils.ocio.convertExposureToFStop(exposure)
Convert an exposure value to an F-Stop value.
- mari.utils.ocio.convertExposureToGain(exposure)
Convert an exposure value to a gain value.
- mari.utils.ocio.convertGainToExposure(gain)
Convert a gain value to an exposure value.
- mari.utils.ocio.convertGainToFStop(gain)
Convert a gain value to an F-Stop value.
- mari.utils.ocio.defaultInputColorspace(config)
Return the default input colorspace for the given OCIO config.
- mari.utils.ocio.defaultViewDisplay(config, scalar)
Return the default view display for the given OCIO config.
- mari.utils.ocio.loadConfig(path, display_message_box=True, message_box_title='Colorspace')
Load an OpenColorIO configuration from the specified path.
- mari.utils.ocio.lutFileFilter()
Return a filter string.
- mari.utils.ocio.onAnalyticalViewTransformRegistered(callback)
Subscribe to be notified when a new analytical view transform is registered.
Subscribers are called with no arguments immediately after each call to registerAnalyticalViewTransform. Use this to refresh UI that needs to reflect newly added entries.
If entries are already in the registry when this is called, the callback is fired once immediately so that a subscriber that registers after some entries exist does not miss them.
- Parameters:
callback – A callable that takes no arguments.
- mari.utils.ocio.printMessage(type, message)
Print a message to the Mari application log with the specified type.
- mari.utils.ocio.registerAnalyticalViewTransform(config_matcher, display, view, glsl_declaration, func_name, label_suffix='Analytical')
Register a custom analytical GLSL function as an opt-in View Transform combobox entry.
When the active OCIO config matches config_matcher, an extra entry is added to the View Transform dropdown: ‘{view} ({display}) - {label_suffix}’. Selecting it calls func_name (defined in glsl_declaration) on the GPU instead of the normal OCIO LUT path.
Subscribers registered via onAnalyticalViewTransformRegistered are notified immediately after the new entry is appended, allowing live UI to refresh without manual intervention.
Note: entries are config-specific. An entry only appears in the UI when the currently active OCIO config satisfies config_matcher. If no project is open yet, or the open project uses a different config, the entry remains hidden until a matching config is loaded. onAnalyticalViewTransformRegistered handles the timing gap between toolbar initialization and later module imports; it does not bypass config matching.
- Parameters:
config_matcher – A callable(config) -> bool, or a str that is matched as a substring of config.getWorkingDir(). Use a callable for complex logic.
display – OCIO display name, e.g. ‘ACES’.
view – OCIO view name, e.g. ‘sRGB’.
glsl_declaration – GLSL function definition string. The function must have the signature: vec4 func_name(vec4 inVal) { … }
func_name – The GLSL function name to call, e.g. ‘aces_srgb_analytical’.
label_suffix – Text appended after ‘ - ‘ in the combobox label (default: ‘Analytical’).
- mari.utils.ocio.registerFStopCenterChanged(function)
Register a callback function to be called when the F-Stop center preference changes.
Stream redirection (for stdin, etc).
- class mari.utils.redirector.InputStreamRedirector(stream)
Bases:
StreamRedirectorThis class prevents an input stream from reading any line data.
- readline()
Prevent reading any line data from the input stream.
- class mari.utils.redirector.StreamRedirector(stream)
Bases:
objectThis class redirects specific methods of the given stream.
- __init__(stream)
Initialize this instance.
- close()
Close the stream by flushing it.
- stream()
Return the saved stream.
Mari custom help displayer.
- class mari.utils.show_help.CustomHelp
Bases:
objectMari custom help displayer.
This class will display various on-line help for functions in Mari and PySide, and for built-in system modules. If no help is found for the supplied object, it will fall back to the built-in help() function from the pydoc module.
- getURL(obj)
Return the documentation file to look up for the object passed in.
For example, this will return the string ‘mari.projects’ for the projects object in the mari module.
- Returns:
The URL to open, or None if there is no documentation available.
- mari.utils.show_help.getAutoCompletionCandidates(expression)
Return the candidates of auto-completion for the given expression in comma-separated format.
- Returns:
The comma-separated list of candidates for auto-completion of the given expression. If empty, this returns locals() of the __main__ module
Helpers for signal connections in Mari.
- class mari.utils.signal_helpers.SignalBlocker(widget)
Bases:
SignalsBlockerBlocks signals of a widget with a context manager.
- Parameters:
widget (QWidget) – Widget to block signals to/from while this class is active
- __init__(widget)
Initialize this instance.
- class mari.utils.signal_helpers.SignalsBlocker(widgets)
Bases:
objectBlocks signals of widgets with a context manager.
- Parameters:
widgets (list) – Widgets to block signals to/from while this class is active
- __init__(widgets)
Initialize this instance.
- mari.utils.signal_helpers.connect(signal, response)
Connect a Qt or Mari signal to a Python callable.
If the signal connection fails, make sure the signal and response are of the correct types and take compatible parameters.
- Parameters:
signal – A signal (event) to connect with a function call.
response – A Python callable object, such as a function, to call when the signal is triggered.
- Returns:
True or False to indicate whether the connection succeeded.
- Raises:
TypeError – Raised if one of the parameters is of the wrong type.
- mari.utils.signal_helpers.disconnect(signal, response)
Disconnect a Qt or Mari signal from a Python callable.
If the signal disconnection fails, make sure the signal and response were previously connected properly.
- Parameters:
signal – A signal (event) that is connected with a function call.
response – A Python callable object, such as a function, that was previously connected to the signal.
- Returns:
True or False to indicate whether the disconnection succeeded.
- Raises:
TypeError – Raised if one of the parameters is of the wrong type.
UI scripts.
- mari.utils.ui.registerDropDataCallback(callback, mimeType, dropTarget)
Register a callback function to catch an UI’s drop event.
- Parameters:
callback –
- The callback function to call upon a drop event. The callback
function should accept four arguments.
- Signature:
def callback(mimeType, dropTarget, data, contextualInfo)
- returns:
bool indicating whether the drop event has been handled.
- param - mimeType is the string representing the MIME type of the:
dropped data.
- param - dropTarget is the value from mari.app.DropTargetArea:
representing the UI area where the drop event happened.
- param - data is the actual QMimeData data dropped.:
- param - contextualInfo is contextual data of the drop event:
- the position or the item the drop happened onto:
- CANVAS
- Canvas(mari.Canvas): The Canvas instance the drop event
happened onto.
Position(QtCore.QPoint): The position in the canvas.
- SHELF
- Shelf(mari.Shelf): The Shelf instance the drop event
happened onto.
- Index(Index): The index in the Shelf the drop event
happened at.
- IMAGE_MANAGER
- Image(mari.Image): The Image instance the drop event
happened onto. The key is not present if the drop event happened onto an empty area.
- LAYER_STACK
- LayerStack(mari.LayerStack or mari.Channel): The
LayerStack instance the drop event happened onto.
- LayerBelow(mari.Layer): The layer below the drop
position. The key is not present if the drop event happened onto an empty area.
- NODE_GRAPH
- NodeGraph(mari.NodeGraph): The NodeGraph instance the
drop event happened onto.
- Position(QtCore.QPoint): The position in the node
graph.
- param such as:
- the position or the item the drop happened onto:
- CANVAS
- Canvas(mari.Canvas): The Canvas instance the drop event
happened onto.
Position(QtCore.QPoint): The position in the canvas.
- SHELF
- Shelf(mari.Shelf): The Shelf instance the drop event
happened onto.
- Index(Index): The index in the Shelf the drop event
happened at.
- IMAGE_MANAGER
- Image(mari.Image): The Image instance the drop event
happened onto. The key is not present if the drop event happened onto an empty area.
- LAYER_STACK
- LayerStack(mari.LayerStack or mari.Channel): The
LayerStack instance the drop event happened onto.
- LayerBelow(mari.Layer): The layer below the drop
position. The key is not present if the drop event happened onto an empty area.
- NODE_GRAPH
- NodeGraph(mari.NodeGraph): The NodeGraph instance the
drop event happened onto.
- Position(QtCore.QPoint): The position in the node
graph.
- mimeType: The MIME type for which the callback will be called. The callback function should accept three
arguments.
- dropTarget: (mari.app.DropTargetArea) The UI area at which the drop event happened. The accepted values are
mari.app.DropTargetArea.CANVAS
mari.app.DropTargetArea.SHELF
mari.app.DropTargetArea.IMAGE_MANAGER
mari.app.DropTargetArea.LAYER_STACK
mari.app.DropTargetArea.NODE_GRAPH
Example
- def myCallBack(mimeType, dropTarget, mimeData, contextualInfo):
mari.app.log(“Dropping…”) mari.app.log(“MimeType:”+str(mimeType)) mari.app.log(“DropTarget:”+str(dropTarget)) mari.app.log(“Data formats:”+str(mimeData.formats())) mari.app.log(“Data has urls: %d” % (mimeData.hasUrls())) mari.app.log(str(contextualInfo)) return True
mari.utils.ui.registerDropDataCallback(myCallBack, “text/plain”, mari.app.DropTargetArea.NODE_GRAPH)