Skip to content

Platform API Reference

Josh Tomlinson edited this page Mar 23, 2016 · 37 revisions

The Apps and Engines API

Welcome to the Apps and Engines documentation! This part of the API documentation covers all the classes and methods used when dealing with Engines, Apps and Frameworks.

If you are interested in developing your own apps, engines or frameworks, the base classes needed to be derived from are outlined below. The documentation also covers how to initialize and shut down the Sgtk engine platform.

Launching and accessing the platform

The methods in this sections are used when you want to start up a Sgtk engine. This typically happens first thing once a host application (e.g. Maya or Nuke) has been launched.

A running engine typically needs to be terminated before a new engine can be started. The method for terminating an engine can be found on the engine class itself.

sgtk.platform.start_engine()

Creates an engine and makes it the current engine.

Engine sgtk.platform.start_engine( str engine_name, Sgtk tk, Context context )

  • str engine_name - Name of engine to start.
  • Sgtk tk - Sgtk instance.
  • Context context - Context object.
  • Returns: The newly created engine object.

Example

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> engine = sgtk.platform.start_engine('tk-shotgun', tk, ctx)
>>> engine
<Sgtk Engine 0x10451b690: tk-shotgun, env: shotgun>

sgtk.platform.current_engine()

Returns the currently active engine.

Engine sgtk.platform.current_engine()

  • Returns: The current engine object.

Example

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> sgtk.platform.start_engine('tk-shotgun', tk, ctx)
>>> engine = sgtk.platform.current_engine()
>>> engine
<Sgtk Engine 0x10451b690: tk-shotgun, env: shotgun>

sgtk.platform.restart()

Restarts the currently running Toolkit platform. This includes reloading all configuration files as well as reloading the code for all apps and engines. (The Core API, however, is not reloaded). The call does not take any parameters and does not return any value.

Any open windows will remain open and will use the old code base and settings. In order to access any changes that have happened as part of a reload, you need to start up new app windows (typically done via the Shotgun menu) and these will use the fresh code and configs.

None sgtk.platform.restart()

Example

>>> import sgtk
>>> sgtk.platform.restart()

sgtk.platform.get_engine_path()

Similar to start_engine, but instead of starting an engine, this method returns the path to a suitable engine. This helper method is sometimes useful when initializing Sgtk engines for applications that do not have a built in python interpreter.

str sgtk.platform.get_engine_path( str engine_name, Sgtk tk, Context context )

  • str engine_name - Name of engine to get the path to.
  • Sgtk tk - Sgtk instance.
  • Context context - Context object.
  • Returns: A path string

Example

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> sgtk.platform.get_engine_path('tk-shotgun', tk, ctx)
/studio/sgtk/install/engines/app_store/tk-engine/v0.1.0

Application Base Class

sgtk.platform.Application - Base class for an app in Sgtk. All Toolkit Apps needs to derive from the App base class outlined below. For an example, see https://github.com/shotgunsoftware/tk-multi-starterapp.

Example

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> engine = sgtk.platform.start_engine('tk-shotgun', tk, ctx)
>>> app = engine.apps['tk-shotgun-folders']
>>> app
<Sgtk App 0x10451e190: tk-shotgun-folders, engine: <Sgtk Engine 0x10451b690: tk-shotgun, env: shotgun>>

name property

The short name of the app (e.g. tk-maya-publish)

display_name property

The displayname of the app (e.g. Maya Publish)

description property

A short description of the app

version property

The version of the app (e.g. v0.2.3)

documentation_url property

Return the relevant documentation url for this app.

support_url property

Return the relevant support url for this app.

icon_256 property

Returns a path to the icon associated with this app. The icon is a 256px square png.

disk_location property

The folder on disk where this app is located.

cache_location property

A folder on disk where the app can store temporary data. The cache location is unique to this app and will not be shared with other apps or engines and it is guaranteed to exist on disk.

frameworks property

The frameworks currently installed for this item.

engine property

The engine to which this app is connected.

sgtk property

A shortcut to retrieve the Sgtk API instance from the current engine

shotgun property

A shortcut to retrieve the Shotgun API instance from the current engine

context property

A shortcut to retrieve the context from the current engine

style_constants property

Returns a dictionary of style constants. These can be used to build UIs using standard colors and other style components. All keys returned in this dictionary can also be used inside a style.qss file that lives at the root level of the app, engine or framework. Use a {{DOUBLE_BACKET}} syntax in the stylesheet file, for example:

QWidget
{
    color: {{SG_FOREGROUND_COLOR}};
}

This property returns the values for all constants as a dictionary, for example:

{
  "SG_HIGHLIGHT_COLOR":  "#18A7E3",
  "SG_ALERT_COLOR":      "#FC6246",
  "SG_FOREGROUND_COLOR": "#C8C8C8"
}

init_app()

Implemented by deriving classes in order to initialize the app Called by the engine as it loads the app.

post_engine_init()

Implemented by deriving classes in order to run code after the engine has completely finished initializing itself and all its apps. At this point, the engine has a fully populaed apps dictionary and all loaded apps have been fully initialized and validated.

destroy_app()

Implemented by deriving classes in order to tear down the app Called by the engine as it is being destroyed.

import_module()

Imports and returns a module inside the python subfolder in a way which is reload-friendly.

module_object application_obj.import_module( str module_name )

Parameters and Return Value

  • str module_name - The name of the module to return. The module name corresponds to the name of a folder in the python sub-folder.
  • Returns: A python module object

Each Sgtk App or Engine can have a python folder which contains additional code. In order to ensure that Sgtk can run multiple versions of the same app, as well as being able to reload app code if it changes, it is recommended that this method is used whenever you want to access code in the python location.

For example, imagine you had the following structure:

tk-multi-myapp
   |- app.py
   |- info.yml
   \- python
       |- __init__.py   <--- Needs to contain 'from . import tk_multi_myapp'
       \- tk_multi_myapp

The above structure is common; app.py is a light weight wrapper and the module tk_multi_myapp module contains the actual code payload. In order to import this in a Sgtk friendly way, you need to run the following when you want to load the payload module inside of app.py:

module_obj = self.import_module("tk_multi_myapp")

get_setting()

Get a value from the app's settings.

setting type application_obj.get_setting( str key, default )

Parameters and Return Value

  • str str key - settings key
  • default - default value to return
  • Returns: Value for the setting.

Example

>>> app.get_setting('entity_types')
['Sequence', 'Shot', 'Asset', 'Task']

get_template()

Returns a template object for a particular template setting in the app configuration. This method will look at the app configuration, determine which template is being referred to in the setting, go into the main platform Template API and fetch that particular template object.

This is a convenience method. Shorthand for self.sgtk.templates[ self.get_setting(key) ].

Template application_obj.get_template( str key )

Parameters and Return Value

  • str key - Settings key.
  • Returns: A Template Object

get_template_by_name()

Note: This is for advanced use cases - Most of the time you should probably use get_template(). Find a particular template, the way it is named in the master config file templates.yml. This method will access the master templates file directly and pull out a specifically named template without using the app config. Note that using this method may result in code which is less portable across studios, since it makes assumptions about how templates are named and defined in the master config. Generally speaking, it is often better to access templates using the app configuration and the get_template() method.

This is a convenience method. Shorthand for self.sgtk.templates[template_name].

Template application_obj.get_template_by_name( str key )

Parameters and Return Value

  • str key - Name of template.
  • Returns: A Template Object

execute_hook_method()

Method for executing external code inside of hooks.

Hooks forms a flexbile way to extend and make toolkit apps or engines configurable. It acts like a setting in that it needs to be configured as part of the app's configuration, but instead of being a simple value, it is a code snippet contained inside a class.

Apps typically provide default hooks to make installation and overriding easy. Each hook is represented by a setting, similar to the ones you access via the get_setting() method, however instead of retrieving a fixed value, you execute code which generates a value.

This method will execute a specific method for a given hook setting. Toolkit will find the actual python hook file and handle initialization and execution for you, by looking at the configuration settings and resolve a path based on this.

Arguments should always be passed in by name. This is to make it easy to add new parameters without breaking backwards compatibility, for example execute_hook_method("validator", "pre_check", name=curr_scene, version=curr_ver).

application_obj.execute_hook_method( str key, str method_name, **kwargs )

Parameters and Return Value

  • str key - The hook as named in settings.
  • str method_name - The name of the hook method to be executed.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

execute_hook()

Convenience method that calls execute_hook_method() with the method_name set to execute.

This method provides backwards compatibility for older hooks where each hook class would only contain a single execute method there were no way to call specific methods.

For more details, see the documentation for execute_hook_method().

application_obj.execute_hook( str key, **kwargs )

Parameters and Return Value

  • str key - The hook as named in settings.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

execute_hook_expression()

Execute an arbitrary hook via an expression. While the methods execute_hook() and execute_hook_method() allows you to execute a particular hook setting as specified in the app configuration manifest, this method allows you to execute a hook directly by passing a hook expression, for example {config}/path/to/my_hook.py.

This is useful if you are doing rapid app development and don't necessarily want to expose a hook as a configuration setting just yet. It is also useful if you have app settings that are nested deep inside of lists or dictionaries. In that case, you cannot use execute_hook(), but instead will have to retrieve the value specifically and then run it.

Supported formats:

  • {$HOOK_PATH}/path/to/foo.py -- expression based around an environment variable.
  • {self}/path/to/foo.py -- looks in the hooks folder in the local app, engine of framework.
  • {config}/path/to/foo.py -- Looks in the hooks folder in the project config.
  • {tk-framework-perforce_v1.x.x}/path/to/foo.py -- looks in the hooks folder of a framework instance that exists in the current environment. Basically, each entry inside the frameworks section in the current environment can be specified here - all these entries are on the form frameworkname_versionpattern, for example tk-framework-widget_v0.1.2 or tk-framework-shotgunutils_v1.3.x.

Supported legacy formats:

  • foo -- Will look for a foo.py file in the project configuration folder.

application_obj.execute_hook_expression( str hook_expression, str method_name, **kwargs )

Parameters and Return Value

  • str hook_expression - The hook expression (see above for supported formats).
  • str method_name - Method inside the hook to execute.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

ensure_folder_exists()

Make sure that the given folder exists on disk.

Convenience method to make it easy for apps and engines to create folders in a standardized fashion. While the creation of high level folder structure such as Shot and Asset folders is typically handled by the folder creation system in Sgtk, Apps tend to need to create leaf-level folders such as publish folders and work areas. These are often created just in time of the operation.

application_obj.ensure_folder_exists( str path )

Parameters and Return Value

  • str path - The path to ensure exists.
  • Returns: Nothing

log_debug()

Uses the current engines logging to log a debug message.

application_obj.log_debug( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_info()

Uses the current engines logging to log a info message.

application_obj.log_info( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_warning()

Uses the current engines logging to log a warning message.

application_obj.log_warning( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_error()

Uses the current engines logging to log a error message.

application_obj.log_error( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_exception()

Uses the current engines logging to log a exception message.

application_obj.log_exception( str msg )

Parameters and Return Value

  • str msg - The message to log.

Using QT inside your app

You can use QT classes inside your app code. Sgtk will handle the import and gracefully manage different platform considerations in the background. Typically, PySide is being used for QT integration, but Sgtk may use PyQT in certain engines. Normally, the code is pretty portable between the two systems and it should be no problem writing code that works with both libraries.

In order to use QT, import it from Sgtk:

from sgtk.platform.qt import QtCore, QtGui

Sgtk will make sure Qt is sourced in the correct way. Keep in mind that many applications (for example Nuke) may not have a functional Qt that can be imported when they run in batch mode.

When creating a dialog, it is important to parent it properly to the host environment. There is nothing stopping you from managing this by yourself, but for maximum compatibility and portabilty, we strongly suggest that you let Sgtk handle it.

When using Sgtk to set up your UI, just let your UI class derive from QtGui.QWidget and pass it to one of the UI factory methods that the engine has. For example:

from sgtk.platform.qt import QtCore, QtGui

# derive from QtGui.QWidget for your UI components.

class AppDialog(QtGui.QWidget):

    def __init__(self, param1, param2):
        QtGui.QWidget.__init__(self)

# the engine is then used to correctly launch this dialog. In your app code
# you can now do create a window using the engine's factory methods.

# display widget in a modeless window:
widget_obj = self.engine.show_dialog("Dialog Title", self, AppDialog, param1, param2)

# display widget in a modal dialog - blocking call
(return_code, widget_obj) = self.engine.show_modal("Dialog Title", self, AppDialog, param1, param2)

What happens in the above calls is that your app widget is parented inside of a Dialog window Sgtk is creating. Sgtk will add additional potential window constructs, menus etc. Whenever the app widget is closed (for example using the close() method), the parent window that is used to wrap the widget will automatically close too.

Modal dialogs and exit codes

If you want to run your widget as a modal dialog, it may be useful to signal success or failure. This is normally done in QT using the methods QDialog.accepted() and QDialog.rejected(), however since the app widget typically derives from QWidget, these methods are not available. Instead, Sgtk will look for a member property called exit_code. Typically, your code for a modal dialog would look something like this:

    def on_ok_button_clicked(self):
        # user clicked ok
        self.exit_code = QtGui.QDialog.Accepted
        self.close()

    def on_cancel_button_clicked(self):
        # user clicked cancel
        self.exit_code = QtGui.QDialog.Rejected
        self.close()

The call to self.engine.show_modal() will return the appropriate status code depending on which button was clicked.

Hiding the Sgtk Title Bar

By default, the standard Sgtk dialog includes a title bar at the top. However, sometimes this is not desirable, especially when the contained widget is quite small. To hide the title bar, just add a property called hide_tk_title_bar to your widget class and set it to a value of True, for example:

class MyWidget(QtGui.QWidget):

    @property
    def hide_tk_title_bar(self):
        return True

    def __init__(self):
        ...

Framework Base Class

Base class for a framework in Sgtk.

Frameworks are automatically imported into the system whenever Sgtk finds a framework defined in the info.yml for an app or an engine. Once imported, it will be available in the frameworks dictionary on the host object. For example, an app or engine (or framework) may have the following definition in its info.yml:

frameworks:
    - {"name": "tk-framework-widget", "version": "v0.1.2"}
    - {"name": "tk-framework-tools", "version": "v0.x.x"}

When Sgtk loads the app, it will verify that the two frameworks are present in the environment and initialize them. Once initialized, the app that needs them can access them via the self.frameworks property:

foo_bar_module = self.frameworks["tk-framework-widget"].import_module("foo_bar")

In order to import a framework module into app or engine code, use the convenience method module_name = sgtk.platform.import_framework(framework_name, module_name). This method is typically executed right in the beginning of the file, before you create any methods or classes:

import os
import sys
import sgtk
widgets = sgtk.platform.import_framework("tk-framework-widget", "widgets")

class MyBrowser(widgets.BrowserWidget):
    ...

If you would like to load the framework instance itself rather than a module which was imported as part of the framework initalization, you can use the followihg method:

import sgtk
fw = sgtk.platform.get_framework("tk-framework-widget")

Note that this only works inside of code which has been imported via the import_module command - e.g. the way we recommend that Sgtk code is being imported into apps. For other scenarios, use the frameworks dictionary in conjunction with the import_module command, as shown above.

Frameworks are imported in an individual fashion, meaning that even though a framework is used in two apps, each app will import its own instance of the framework. This is to ensure stability and encapsulation.

A framework works just like an app or an engine - it has an info.yml manifest, a framework.py file which typically contains a class which derives from the Framework base class, etc.

name property

The short name of the framework (e.g. tk-framework-widget)

display_name property

The displayname of the framework (e.g. Widget Framework)

description property

A short description of the framework

version property

The version of the framework (e.g. v0.2.3)

documentation_url property

Return the relevant documentation url for this framework.

support_url property

Return the relevant support url for this framework.

icon_256 property

Returns a path to the icon associated with this framework. The icon is a 256px square png.

disk_location property

The folder on disk where this framework is located.

cache_location property

A folder on disk where the framework can store temporary data. The cache location is unique to this item and will not be shared with other apps or engines and it is guaranteed to exist on disk.

frameworks property

The frameworks currently installed for this item.

engine property

The engine to which this framework is connected.

sgtk property

A shortcut to retrieve the Sgtk API instance from the current engine

shotgun property

A shortcut to retrieve the Shotgun API instance from the current engine

context property

A shortcut to retrieve the context from the current engine

style_constants property

Returns a dictionary of style constants. These can be used to build UIs using standard colors and other style components. All keys returned in this dictionary can also be used inside a style.qss file that lives at the root level of the app, engine or framework. Use a {{DOUBLE_BACKET}} syntax in the stylesheet file, for example:

QWidget
{
    color: {{SG_FOREGROUND_COLOR}};
}

This property returns the values for all constants as a dictionary, for example:

{
  "SG_HIGHLIGHT_COLOR":  "#18A7E3",
  "SG_ALERT_COLOR":      "#FC6246",
  "SG_FOREGROUND_COLOR": "#C8C8C8"
}

init_framework()

Implemented by deriving classes in order to initialize the app. Called by the engine as it loads the framework.

destroy_framework()

Implemented by deriving classes in order to tear down the framework. Called by the engine as it is being destroyed.

import_module()

Imports and returns a module inside the python subfolder in a way which is reload-friendly.

module_object framework_obj.import_module( str module_name )

Parameters and Return Value

  • str module_name - The name of the module to return. The module name corresponds to the name of a folder in the python sub-folder.
  • Returns: A python module object

Each Sgtk App, Engine or Framework can have a python folder which contains additional code. In order to ensure that Sgtk can run multiple versions of the same framework, as well as being able to reload framework code if it changes, it is recommended that this method is used whenever you want to access code in the python location.

For example, imagine you had the following structure:

tk-framework-widget
   |- framework.py
   |- info.yml
   \- python
       |- __init__.py   <--- Needs to contain 'from . import window, button, scroll_bar'
       |- window
       |- button
       \- scroll_bar

The above structure is common; framework.py is a light weight wrapper and the modules window, button and scroll_bar contain the actual code payload. In order to import this in a Sgtk friendly way, you need to run the following when you want to load the payload module inside of framework.py:

module_obj = self.import_module("tk_multi_myapp")

Note however, that typically frameworks are pulled in by other apps and engines, so running this command directly is unusual. Instead, an app or engine that wants to import a piece of a framework would typically go:

# imports
import sgtk
button = sgtk.platform.import_framework("tk-framework-widget", "button")

# definitions
class MySpecialButton(button.SgtkButton):
    ...etc

get_setting()

Get a value from the framework's settings.

setting type framework_obj.get_setting( str key, default )

Parameters and Return Value

  • str str key - settings key
  • default - default value to return
  • Returns: Value for the setting.

Example

>>> fw.get_setting('entity_types')
['Sequence', 'Shot', 'Asset', 'Task']

get_template()

Returns a template object for a particular template setting in the Framework configuration. This method will look at the app configuration, determine which template is being referred to in the setting, go into the main platform Template API and fetch that particular template object.

This is a convenience method. Shorthand for self.sgtk.templates[ self.get_setting(key) ].

Template framework_obj.get_template( str key )

Parameters and Return Value

  • str key - Settings key.
  • Returns: A Template Object

get_template_by_name()

Note: This is for advanced use cases - Most of the time you should probably use get_template(). Find a particular template, the way it is named in the master config file templates.yml. This method will access the master templates file directly and pull out a specifically named template without using the app config. Note that using this method may result in code which is less portable across studios, since it makes assumptions about how templates are named and defined in the master config. Generally speaking, it is often better to access templates using the app configuration and the get_template() method.

This is a convenience method. Shorthand for self.sgtk.templates[template_name].

Template framework_obj.get_template_by_name( str key )

Parameters and Return Value

  • str key - Name of template.
  • Returns: A Template Object

execute_hook_method()

Method for executing external code inside of hooks.

Hooks forms a flexbile way to extend and make toolkit apps or engines configurable. It acts like a setting in that it needs to be configured as part of the app's configuration, but instead of being a simple value, it is a code snippet contained inside a class.

Apps typically provide default hooks to make installation and overriding easy. Each hook is represented by a setting, similar to the ones you access via the get_setting() method, however instead of retrieving a fixed value, you execute code which generates a value.

This method will execute a specific method for a given hook setting. Toolkit will find the actual python hook file and handle initialization and execution for you, by looking at the configuration settings and resolve a path based on this.

Arguments should always be passed in by name. This is to make it easy to add new parameters without breaking backwards compatibility, for example execute_hook_method("validator", "pre_check", name=curr_scene, version=curr_ver).

application_obj.execute_hook_method( str key, str method_name, **kwargs )

Parameters and Return Value

  • str key - The hook as named in settings.
  • str method_name - The name of the hook method to be executed.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

execute_hook()

Convenience method that calls execute_hook_method() with the method_name set to execute.

This method provides backwards compatibility for older hooks where each hook class would only contain a single execute method there were no way to call specific methods.

For more details, see the documentation for execute_hook_method().

application_obj.execute_hook( str key, **kwargs )

Parameters and Return Value

  • str key - The hook as named in settings.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

execute_hook_expression()

Execute an arbitrary hook via an expression. While the methods execute_hook() and execute_hook_method() allows you to execute a particular hook setting as specified in the app configuration manifest, this method allows you to execute a hook directly by passing a hook expression, for example {config}/path/to/my_hook.py.

This is useful if you are doing rapid app development and don't necessarily want to expose a hook as a configuration setting just yet. It is also useful if you have app settings that are nested deep inside of lists or dictionaries. In that case, you cannot use execute_hook(), but instead will have to retrieve the value specifically and then run it.

Supported formats:

  • {$HOOK_PATH}/path/to/foo.py -- expression based around an environment variable.
  • {self}/path/to/foo.py -- looks in the hooks folder in the local app, engine of framework.
  • {config}/path/to/foo.py -- Looks in the hooks folder in the project config.
  • {engine}/path/to/foo.py -- Looks in the hooks folder of the engine in which an app is running.
  • {tk-framework-perforce_v1.x.x}/path/to/foo.py -- looks in the hooks folder of a framework instance that exists in the current environment. Basically, each entry inside the frameworks section in the current environment can be specified here - all these entries are on the form frameworkname_versionpattern, for example tk-framework-widget_v0.1.2 or tk-framework-shotgunutils_v1.3.x.

Supported legacy formats:

  • foo -- Will look for a foo.py file in the project configuration folder.

application_obj.execute_hook_expression( str hook_expression, str method_name, **kwargs )

Parameters and Return Value

  • str hook_expression - The hook expression (see above for supported formats).
  • str method_name - Method inside the hook to execute.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

ensure_folder_exists()

Make sure that the given folder exists on disk.

Convenience method to make it easy for apps and engines to create folders in a standardized fashion. While the creation of high level folder structure such as Shot and Asset folders is typically handled by the folder creation system in Sgtk, Apps tend to need to create leaf-level folders such as publish folders and work areas. These are often created just in time of the operation.

framework_obj.ensure_folder_exists( str path)

Parameters and Return Value

  • str path - The path to ensure exists.
  • Returns: Nothing

log_debug()

Uses the current engines logging to log a debug message.

framework_obj.log_debug( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_info()

Uses the current engines logging to log a info message.

framework_obj.log_info( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_warning()

Uses the current engines logging to log a warning message.

framework_obj.log_warning( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_error()

Uses the current engines logging to log a error message.

framework_obj.log_error( str msg )

Parameters and Return Value

  • str msg - The message to log.

log_exception()

Uses the current engines logging to log a exception message.

framework_obj.log_exception( str msg )

Parameters and Return Value

  • str msg - The message to log.

Engine Base Class

Base class for an engine in Sgtk.

Example

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> engine = sgtk.platform.start_engine('tk-shotgun', tk, ctx)
<Sgtk Engine 0x10451b690: tk-shotgun, env: shotgun>

name property

The short name of the engine (e.g. tk-maya)

display_name property

The displayname of the engine (e.g. Maya Engine)

description property

A short description of the engine

version property

The version of the engine (e.g. v0.2.3)

instance_name property

The instance name for this engine. The instance name is the entry that is defined in the environment file.

disk_location property

The folder on disk where this engine is located.

cache_location property

A folder on disk where the engine can store temporary data. The cache location is unique to this item and will not be shared with other apps or engines and it is guaranteed to exist on disk.

frameworks property

The frameworks currently installed for this item.

environment property

Dictionary with information about the current environment. Returns the following keys:

  • name - the name of the environment
  • disk_location - the location of the environment file
  • description - a description of the environment

context property

The current context associated with this engine.

style_constants property

Returns a dictionary of style constants. These can be used to build UIs using standard colors and other style components. All keys returned in this dictionary can also be used inside a style.qss file that lives at the root level of the app, engine or framework. Use a {{DOUBLE_BACKET}} syntax in the stylesheet file, for example:

QWidget
{
    color: {{SG_FOREGROUND_COLOR}};
}

This property returns the values for all constants as a dictionary, for example:

{
  "SG_HIGHLIGHT_COLOR":  "#18A7E3",
  "SG_ALERT_COLOR":      "#FC6246",
  "SG_FOREGROUND_COLOR": "#C8C8C8"
}

apps property

Dictionary of apps associated with this engine

panels property

Returns all the panels which have been registered with the engine via the register_panel() method. Returns a dictionary keyed by panel unqiue ids. Each value is a dictionary with keys callback and properties.

shotgun property

Delegates to the Sgtk API instance's shotgun connection, which is lazily created the first time it is requested.

sgtk property

Returns a Sgtk API instance associated with this engine.

commands property

Returns a dictionary representing all the commands that have been registered by apps in this engine. Each dictionary item contains the following keys:

  • callback - function pointer to function to execute for this command.
  • properties - dictionary with free form options - these are typically engine specific and driven by convention.

documentation_url property

Return the relevant documentation url for this engine.

support_url property

Return the relevant support url for this engine.

icon_256 property

Returns a path to the icon associated with this engine. The icon is a 256px square png.

has_ui property

Indicates that the host application that the engine is connected to has a UI enabled. This always returns False for some engines (such as the shell engine) and may vary for some engines, depending if the host application for example is in batch mode or UI mode.

init_engine() *

* Deprecated: This method has now been deprecated and pre_app_init() should be used instead to do any engine initialisation needed before the apps are loaded.

pre_app_init()

Sets up the engine into an operational state. Executed by the system and typically implemented by deriving classes. This method called before any apps are loaded.

post_app_init()

Executed by the system and typically implemented by deriving classes. This method called after all apps have been loaded.

destroy()

Destroy all apps, then call destroy_engine so subclasses can add their own tear down code. This method should not be subclassed.

destroy_engine()

Called when the engine should tear down itself and all its apps. Implemented by deriving classes.

import_module()

Imports and returns a module inside the python subfolder in a way which is reload-friendly.

module_object engine_obj.import_module( str module_name )

Parameters and Return Value

  • str module_name - The name of the module to return. The module name corresponds to the name of a folder in the python sub-folder.
  • Returns: A python module object

Each Sgtk App or Engine can have a python folder which contains additional code. In order to ensure that Sgtk can run multiple versions of the same app, as well as being able to reload app code if it changes, it is recommended that this method is used whenever you want to access code in the python location.

For example, imagine you had the following structure:

tk-multi-myapp
   |- app.py
   |- info.yml
   \- python
       |- __init__.py   <--- Needs to contain 'from . import tk_multi_myapp'
       \- tk_multi_myapp

The above structure is common; app.py is a light weight wrapper and the module tk_multi_myapp module contains the actual code payload. In order to import this in a Sgtk friendly way, you need to run the following when you want to load the payload module inside of app.py:

module_obj = self.import_module("tk_multi_myapp")

register_command()

Register a command with a name and a callback function. Properties can store implementation specific configuration, like if a tooltip is supported. Typically called from the init_app() method of an app.

engine_obj.register_command( str name, function callback, dict properties )

Parameters and Return Value

  • str name
  • function callback
  • dict properties

Example

>>> engine.register_command('my new command', foo)
>>> engine.commands['my new command']
{'callback': <function __main__.foo>, 'properties': {}}

register_panel()

Similar to register_command(), but instead of registering a menu item in the form of a command, this method registers a UI panel. Needs to be called from the init_app() method of an app.

engine_obj.register_panel( function callback, str panel_name = "main", dict properties = None )

Panels need to be registered if they should persist between DCC sessions (e.g. for example 'saved layouts').

Just like with the register_command() method, panel registration should be executed from within the init phase of the app. Once a panel has been registered, it is possible for the engine to correctly restore panel UIs at startup and profile switches.

Not all engines support this feature, but in for example Nuke, a panel can be added to a saved layout. Apps wanting to be able to take advantage of the persistence provided by these saved layouts will need to call register_panel as part of their init_app phase.

In order to show or focus on a panel, use the show_panel() method instead.

Parameters and Return Value

  • function callback - Factory method for showing a panel and returning the panel object
  • str panel_name - A string to distinguish this panel from other panels created by the app. This will be used as part of the unique id for the panel. Defaults to main. If your app creates more than one panel, you need to explicity set one of the panels not to be main in order to ensure uniqueness
  • dict properties - Properties dictionary with panel specific settings.
  • Returns - A unique identifier that can be used to consistently identify the panel across sessions. This identifier should be used to identify the panel in all subsequent calls, e.g. for example show_panel().

get_matching_commands()

Finds all the commands that match the given selectors. Command selector structures are typically found in engine configurations and are typically defined on the following form in yaml:

menu_favourites:
- {app_instance: tk-multi-workfiles, name: Shotgun File Manager...}
- {app_instance: tk-multi-snapshot,  name: Snapshot...}
- {app_instance: tk-multi-workfiles, name: Shotgun Save As...}
- {app_instance: tk-multi-publish,   name: Publish...}

Note that selectors that do not match a command will output a warning.

engine_obj.get_matching_commands( list selectors )

Parameters and Return Value

  • list selectors - A list of command selectors, with each selector having the following structure:
{
  name: command-name,
  app_instance: instance-name
}

An empty name ('') will select all the commands of the given instance-name.

  • Returns - A list of tuples for all commands that match the selectors. Each tuple has the format:
(instance-name, command-name, callback)

Example

>>> favourites = engine.get_setting('menu_favourites')
>>> engine.get_matching_commands(favourites)

get_setting()

Get a value from the engine's settings

engine_obj.get_setting( str key, default )

Parameters and Return Value

  • key - config name
  • default - default value to return
  • Returns: The setting.

Example

>>> engine.get_setting('debug_logging')
False

execute_hook_method()

Method for executing external code inside of hooks.

Hooks forms a flexbile way to extend and make toolkit apps or engines configurable. It acts like a setting in that it needs to be configured as part of the app's configuration, but instead of being a simple value, it is a code snippet contained inside a class.

Apps typically provide default hooks to make installation and overriding easy. Each hook is represented by a setting, similar to the ones you access via the get_setting() method, however instead of retrieving a fixed value, you execute code which generates a value.

This method will execute a specific method for a given hook setting. Toolkit will find the actual python hook file and handle initialization and execution for you, by looking at the configuration settings and resolve a path based on this.

Arguments should always be passed in by name. This is to make it easy to add new parameters without breaking backwards compatibility, for example execute_hook_method("validator", "pre_check", name=curr_scene, version=curr_ver).

application_obj.execute_hook_method( str key, str method_name, **kwargs )

Parameters and Return Value

  • str key - The hook as named in settings.
  • str method_name - The name of the hook method to be executed.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

execute_hook()

Convenience method that calls execute_hook_method() with the method_name set to execute.

This method provides backwards compatibility for older hooks where each hook class would only contain a single execute method there were no way to call specific methods.

For more details, see the documentation for execute_hook_method().

application_obj.execute_hook( str key, **kwargs )

Parameters and Return Value

  • str key - The hook as named in settings.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

execute_hook_expression()

Execute an arbitrary hook via an expression. While the methods execute_hook() and execute_hook_method() allows you to execute a particular hook setting as specified in the app configuration manifest, this method allows you to execute a hook directly by passing a hook expression, for example {config}/path/to/my_hook.py.

This is useful if you are doing rapid app development and don't necessarily want to expose a hook as a configuration setting just yet. It is also useful if you have app settings that are nested deep inside of lists or dictionaries. In that case, you cannot use execute_hook(), but instead will have to retrieve the value specifically and then run it.

Supported formats:

  • {$HOOK_PATH}/path/to/foo.py -- expression based around an environment variable.
  • {self}/path/to/foo.py -- looks in the hooks folder in the local app, engine of framework.
  • {config}/path/to/foo.py -- Looks in the hooks folder in the project config.
  • {tk-framework-perforce_v1.x.x}/path/to/foo.py -- looks in the hooks folder of a framework instance that exists in the current environment. Basically, each entry inside the frameworks section in the current environment can be specified here - all these entries are on the form frameworkname_versionpattern, for example tk-framework-widget_v0.1.2 or tk-framework-shotgunutils_v1.3.x.

Supported legacy formats:

  • foo -- Will look for a foo.py file in the project configuration folder.

application_obj.execute_hook_expression( str hook_expression, str method_name, **kwargs )

Parameters and Return Value

  • str hook_expression - The hook expression (see above for supported formats).
  • str method_name - Method inside the hook to execute.
  • **kwargs - Keyword arguments which are passed to the hook.
  • Returns: The return value of executing the hook.

ensure_folder_exists()

Make sure that the given folder exists on disk.

Convenience method to make it easy for apps and engines to create folders in a standardized fashion. While the creation of high level folder structure such as Shot and Asset folders is typically handled by the folder creation system in Sgtk, Apps tend to need to create leaf-level folders such as publish folders and work areas. These are often created just in time of the operation.

engine_obj.ensure_folder_exists( str path)

Parameters and Return Value

  • str path - The path to ensure exists.
  • Returns: Nothing

execute_in_main_thread()

Helper method to execute a function in the main thread if called from another thread. This can be useful if a worker thread needs to perform an operation that must be done in the main thread such as displaying UI.

Note: If Qt is not available, the function will always be called from the calling thread!

engine_obj.execute_in_main_thread(function func, *args **kwargs):

Parameters and Return Value

  • function func - The function to execute
  • *args and **kwargs - These are passed to the function being executed

Example

>>> from sgtk.platform.qt import QtGui
>>> engine.execute_in_main_thread(QtGui.QMessageBox.information, None, "Hello", "Hello from the main thread!")

Customising Dialog Creation In Derived Engines

Qt dialog & widget management can be quite tricky in different engines/applications. Because of this, Sgtk provides a few overridable methods with the idea being that when developing a new engine, you only need to override the minimum amount necessary.

Making use of these methods in the correct way allows the base Engine class to manage the lifetime of the dialogs and widgets efficiently and safely without you having to worry about it!

The methods available are listed here in the hierarchy in which they are called.

show_dialog()/show_modal()
    _create_dialog_with_widget()
        _get_dialog_parent()
        _create_widget()
        _create_dialog()

For example, if you just need to make sure that all dialogs use a specific parent widget then you only need to override _get_dialog_parent() (e.g. the tk-maya engine)

However, if you need to implement a two-stage creation then you may need to re-implement show_dialog() and show_modal() to call _create_widget() and _create_dialog() directly rather than using the helper method _create_dialog_with_widget() (e.g. the tk-3dsmax engine).

Finally, if the application you are writing an engine for is Qt based then you may not need to override any of these methods (e.g. the tk-nuke engine).

show_dialog()

Displays a dialog on screen.

engine_obj.show_dialog( str title, Bundle bundle, QWidget widget_class, *args **kwargs )

Parameters and Return Value

  • str title - The title of the window
  • Bundle bundle - The app, engine or framework object associated with the UI
  • QWidget widget_class - class to instantiate. Must be derived from QWidget.
  • *args and **kwargs - These are passed to the class constructor
  • Returns: A widget object

show_modal()

Displays a modal dialog on screen and then blocks execution until a user has closed the dialog.

engine_obj.show_modal( str title, Bundle bundle, QWidget widget_class, *args **kwargs )

Parameters and Return Value

  • str title - The title of the window
  • Bundle bundle - The app, engine or framework object associated with the UI
  • QWidget widget_class - class to instantiate. Must be derived from QWidget.
  • *args and **kwargs - These are passed to the class constructor
  • Returns: (A dialog return status, A widget object)

show_panel()

Create a widget docked inside a panel.

engine_obj.show_panel( str panel_id, str title, Bundle bundle, QWidget widget_class, *args **kwargs )

Shows a panel in a way suitable for this engine. Engines should attempt to integrate panel support as seamlessly as possible into the host application. Some engines have extensive panel support and workflows, others have none at all.

If the engine does not specifically implement panel support, the window will be shown as a modeless dialog instead and the call is equivalent to calling show_dialog().

Parameters and Return Value

  • str panel_id - Unique identifier for the panel, as obtained by register_panel().
  • str title - The title of the panel
  • Bundle bundle - The app, engine or framework object associated with the panel
  • QWidget widget_class - class to instantiate. Must be derived from QWidget.
  • *args and **kwargs - These are passed to the class constructor
  • Returns: A panel object

_create_dialog_with_widget()

Creates a managed Sgtk dialog containing an instance of the specified widget.

engine_obj._create_dialog_with_widget( str title, Bundle bundle, QWidget widget_class, *args **kwargs )

Parameters and Return Value

  • str title - The title of the window
  • Bundle bundle - The app, engine or framework object associated with the UI
  • QWidget widget_class - class to instantiate. Must be derived from QWidget.
  • *args and **kwargs - These are passed to the class constructor
  • Returns: (A dialog object, A widget object)

When overriding in a derived engine, be sure to call the base implementations of _create_widget() and _create_dialog() to ensure that all dialogs and widgets are tracked efficiently and safely.

_get_dialog_parent()

Returns the parent to be used for all created dialogs.

engine_obj._get_dialog_parent()

Parameters and Return Value

  • Returns: The QWidget object to be used as the parent for Sgtk dialogs

_create_widget()

Creates a widget to be used inside of an Sgtk dialog. The widget will be tracked and safely released when it is no longer required.

engine_obj._create_widget( QWidget widget_class, *args **kwargs )

Parameters and Return Value

  • QWidget widget_class - class to instantiate. Must be derived from QWidget.
  • *args and **kwargs - These are passed to the class constructor
  • Returns: A widget object

It shouldn't be necessary to override this method.

_create_dialog()

Creates a managed Sgtk dialog containing the specified widget. The dialog will be tracked and safely released when it is no longer required.

engine_obj._create_dialog( str title, Bundle bundle, QWidget widget, QWidget parent )

Parameters and Return Value

  • str title - The title of the window
  • Bundle bundle - The app, engine or framework object associated with the UI
  • QWidget widget - A widget object derived from QWidget.
  • QWidget parent - The parent QWidget object to use for the new dialog
  • Returns: A dialog object

It shouldn't be necessary to override this method.

_define_qt_base()

This method will be called at initialisation time and will allow a user to control various aspects of how QT is being used by Sgtk. The method should return a dictionary with a number of specific keys, outlined below.

  • qt_core - the QtCore module to use
  • qt_gui - the QtGui module to use
  • dialog_base - base class for to use for Sgtk's dialog factory

This method can be overridden by deriving classes which want to control how QT is being imported. The default implementation simply imports from Pyside. This method is called at engine init time. Any app code doing a from sgtk.platform.qt import QtCore, QtGui will receive whatever classes are being returned here.

_initialize_dark_look_and_feel()

Initializes a standard toolkit look and feel using a combination of QPalette and stylesheets.

If your engine is running inside an environment which already has a dark style defined, do not call this method. The Toolkit apps are designed to work well with most dark themes.

However, if you are for example creating your own QApplication instance you can execute this method to but the session into Toolkit's standard dark mode.

This will initialize the plastique style and set it up with a standard dark palette and supporting stylesheet.

Apps and UIs can then extend this further by using further css.

Due to restrictions in QT, this needs to run after a QApplication object has been instantiated.

Clone this wiki locally