diff --git a/pype/harmony/__init__.py b/pype/harmony/__init__.py
deleted file mode 100644
index b3edca7d15..0000000000
--- a/pype/harmony/__init__.py
+++ /dev/null
@@ -1,39 +0,0 @@
-import os
-
-from avalon import api, harmony
-import pyblish.api
-
-
-def install():
- print("Installing Pype config...")
-
- plugins_directory = os.path.join(
- os.path.dirname(os.path.dirname(__file__)), "plugins", "harmony"
- )
-
- pyblish.api.register_plugin_path(
- os.path.join(plugins_directory, "publish")
- )
- api.register_plugin_path(
- api.Loader, os.path.join(plugins_directory, "load")
- )
- api.register_plugin_path(
- api.Creator, os.path.join(plugins_directory, "create")
- )
-
- pyblish.api.register_callback(
- "instanceToggled", on_pyblish_instance_toggled
- )
-
-
-def on_pyblish_instance_toggled(instance, old_value, new_value):
- """Toggle node enabling on instance toggles."""
- func = """function func(args)
- {
- node.setEnable(args[0], args[1])
- }
- func
- """
- harmony.send(
- {"function": func, "args": [instance[0], new_value]}
- )
diff --git a/pype/hooks/resolve/prelaunch.py b/pype/hooks/resolve/prelaunch.py
new file mode 100644
index 0000000000..bddeccf4a3
--- /dev/null
+++ b/pype/hooks/resolve/prelaunch.py
@@ -0,0 +1,67 @@
+import os
+import traceback
+import importlib
+from pype.lib import PypeHook
+from pypeapp import Logger
+from pype.hosts.resolve import utils
+
+
+class ResolvePrelaunch(PypeHook):
+ """
+ This hook will check if current workfile path has Resolve
+ project inside. IF not, it initialize it and finally it pass
+ path to the project by environment variable to Premiere launcher
+ shell script.
+ """
+
+ def __init__(self, logger=None):
+ if not logger:
+ self.log = Logger().get_logger(self.__class__.__name__)
+ else:
+ self.log = logger
+
+ self.signature = "( {} )".format(self.__class__.__name__)
+
+ def execute(self, *args, env: dict = None) -> bool:
+
+ if not env:
+ env = os.environ
+
+ # making sure pyton 3.6 is installed at provided path
+ py36_dir = os.path.normpath(env.get("PYTHON36_RESOLVE", ""))
+ assert os.path.isdir(py36_dir), (
+ "Python 3.6 is not installed at the provided folder path. Either "
+ "make sure the `environments\resolve.json` is having correctly "
+ "set `PYTHON36_RESOLVE` or make sure Python 3.6 is installed "
+ f"in given path. \nPYTHON36_RESOLVE: `{py36_dir}`"
+ )
+ self.log.info(f"Path to Resolve Python folder: `{py36_dir}`...")
+ env["PYTHON36_RESOLVE"] = py36_dir
+
+ # setting utility scripts dir for scripts syncing
+ us_dir = os.path.normpath(env.get("RESOLVE_UTILITY_SCRIPTS_DIR", ""))
+ assert os.path.isdir(us_dir), (
+ "Resolve utility script dir does not exists. Either make sure "
+ "the `environments\resolve.json` is having correctly set "
+ "`RESOLVE_UTILITY_SCRIPTS_DIR` or reinstall DaVinci Resolve. \n"
+ f"RESOLVE_UTILITY_SCRIPTS_DIR: `{us_dir}`"
+ )
+
+ # correctly format path for pre python script
+ pre_py_sc = os.path.normpath(env.get("PRE_PYTHON_SCRIPT", ""))
+ env["PRE_PYTHON_SCRIPT"] = pre_py_sc
+
+ try:
+ __import__("pype.resolve")
+ __import__("pyblish")
+
+ except ImportError as e:
+ print(traceback.format_exc())
+ print("pyblish: Could not load integration: %s " % e)
+
+ else:
+ # Resolve Setup integration
+ importlib.reload(utils)
+ utils.setup(env)
+
+ return True
diff --git a/pype/maya/expected_files.py b/pype/hosts/maya/expected_files.py
similarity index 100%
rename from pype/maya/expected_files.py
rename to pype/hosts/maya/expected_files.py
diff --git a/pype/hosts/resolve/README.markdown b/pype/hosts/resolve/README.markdown
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/pype/hosts/resolve/README.markdown
@@ -0,0 +1 @@
+
diff --git a/pype/hosts/resolve/RESOLVE_API_README.txt b/pype/hosts/resolve/RESOLVE_API_README.txt
new file mode 100644
index 0000000000..139b66bc24
--- /dev/null
+++ b/pype/hosts/resolve/RESOLVE_API_README.txt
@@ -0,0 +1,189 @@
+Updated as of 08 March 2019
+
+--------------------------
+In this package, you will find a brief introduction to the Scripting API for DaVinci Resolve Studio. Apart from this README.txt file, this package contains folders containing the basic import modules for scripting access (DaVinciResolve.py) and some representative examples.
+
+Overview
+--------
+
+As with Blackmagic Design Fusion scripts, user scripts written in Lua and Python programming languages are supported. By default, scripts can be invoked from the Console window in the Fusion page, or via command line. This permission can be changed in Resolve Preferences, to be only from Console, or to be invoked from the local network. Please be aware of the security implications when allowing scripting access from outside of the Resolve application.
+
+
+Using a script
+--------------
+DaVinci Resolve needs to be running for a script to be invoked.
+
+For a Resolve script to be executed from an external folder, the script needs to know of the API location.
+You may need to set the these environment variables to allow for your Python installation to pick up the appropriate dependencies as shown below:
+
+ Mac OS X:
+ RESOLVE_SCRIPT_API="/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting/"
+ RESOLVE_SCRIPT_LIB="/Applications/DaVinci Resolve/DaVinci Resolve.app/Contents/Libraries/Fusion/fusionscript.so"
+ PYTHONPATH="$PYTHONPATH:$RESOLVE_SCRIPT_API/Modules/"
+
+ Windows:
+ RESOLVE_SCRIPT_API="%PROGRAMDATA%\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting\\"
+ RESOLVE_SCRIPT_LIB="C:\\Program Files\\Blackmagic Design\\DaVinci Resolve\\fusionscript.dll"
+ PYTHONPATH="%PYTHONPATH%;%RESOLVE_SCRIPT_API%\\Modules\\"
+
+ Linux:
+ RESOLVE_SCRIPT_API="/opt/resolve/Developer/Scripting/"
+ RESOLVE_SCRIPT_LIB="/opt/resolve/libs/Fusion/fusionscript.so"
+ PYTHONPATH="$PYTHONPATH:$RESOLVE_SCRIPT_API/Modules/"
+ (Note: For standard ISO Linux installations, the path above may need to be modified to refer to /home/resolve instead of /opt/resolve)
+
+As with Fusion scripts, Resolve scripts can also be invoked via the menu and the Console.
+
+On startup, DaVinci Resolve scans the Utility Scripts directory and enumerates the scripts found in the Script application menu. Placing your script in this folder and invoking it from this menu is the easiest way to use scripts. The Utility Scripts folder is located in:
+ Mac OS X: /Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts/Comp/
+ Windows: %APPDATA%\Blackmagic Design\DaVinci Resolve\Fusion\Scripts\Comp\
+ Linux: /opt/resolve/Fusion/Scripts/Comp/ (or /home/resolve/Fusion/Scripts/Comp/ depending on installation)
+
+The interactive Console window allows for an easy way to execute simple scripting commands, to query or modify properties, and to test scripts. The console accepts commands in Python 2.7, Python 3.6 and Lua and evaluates and executes them immediately. For more information on how to use the Console, please refer to the DaVinci Resolve User Manual.
+
+This example Python script creates a simple project:
+ #!/usr/bin/env python
+ import DaVinciResolveScript as dvr_script
+ resolve = dvr_script.scriptapp("Resolve")
+ fusion = resolve.Fusion()
+ projectManager = resolve.GetProjectManager()
+ projectManager.CreateProject("Hello World")
+
+The resolve object is the fundamental starting point for scripting via Resolve. As a native object, it can be inspected for further scriptable properties - using table iteration and `getmetatable` in Lua and dir, help etc in Python (among other methods). A notable scriptable object above is fusion - it allows access to all existing Fusion scripting functionality.
+
+Running DaVinci Resolve in headless mode
+----------------------------------------
+
+DaVinci Resolve can be launched in a headless mode without the user interface using the -nogui command line option. When DaVinci Resolve is launched using this option, the user interface is disabled. However, the various scripting APIs will continue to work as expected.
+
+Basic Resolve API
+-----------------
+
+Some commonly used API functions are described below (*). As with the resolve object, each object is inspectable for properties and functions.
+
+
+Resolve
+ Fusion() --> Fusion # Returns the Fusion object. Starting point for Fusion scripts.
+ GetMediaStorage() --> MediaStorage # Returns media storage object to query and act on media locations.
+ GetProjectManager() --> ProjectManager # Returns project manager object for currently open database.
+ OpenPage(pageName) --> None # Switches to indicated page in DaVinci Resolve. Input can be one of ("media", "edit", "fusion", "color", "fairlight", "deliver").
+ProjectManager
+ CreateProject(projectName) --> Project # Creates and returns a project if projectName (text) is unique, and None if it is not.
+ LoadProject(projectName) --> Project # Loads and returns the project with name = projectName (text) if there is a match found, and None if there is no matching Project.
+ GetCurrentProject() --> Project # Returns the currently loaded Resolve project.
+ SaveProject() --> Bool # Saves the currently loaded project with its own name. Returns True if successful.
+ CreateFolder(folderName) --> Bool # Creates a folder if folderName (text) is unique.
+ GetProjectsInCurrentFolder() --> [project names...] # Returns an array of project names in current folder.
+ GetFoldersInCurrentFolder() --> [folder names...] # Returns an array of folder names in current folder.
+ GotoRootFolder() --> Bool # Opens root folder in database.
+ GotoParentFolder() --> Bool # Opens parent folder of current folder in database if current folder has parent.
+ OpenFolder(folderName) --> Bool # Opens folder under given name.
+ ImportProject(filePath) --> Bool # Imports a project under given file path. Returns true in case of success.
+ ExportProject(projectName, filePath) --> Bool # Exports a project based on given name into provided file path. Returns true in case of success.
+ RestoreProject(filePath) --> Bool # Restores a project under given backup file path. Returns true in case of success.
+Project
+ GetMediaPool() --> MediaPool # Returns the Media Pool object.
+ GetTimelineCount() --> int # Returns the number of timelines currently present in the project.
+ GetTimelineByIndex(idx) --> Timeline # Returns timeline at the given index, 1 <= idx <= project.GetTimelineCount()
+ GetCurrentTimeline() --> Timeline # Returns the currently loaded timeline.
+ SetCurrentTimeline(timeline) --> Bool # Sets given timeline as current timeline for the project. Returns True if successful.
+ GetName() --> string # Returns project name.
+ SetName(projectName) --> Bool # Sets project name if given projectname (text) is unique.
+ GetPresets() --> [presets...] # Returns a table of presets and their information.
+ SetPreset(presetName) --> Bool # Sets preset by given presetName (string) into project.
+ GetRenderJobs() --> [render jobs...] # Returns a table of render jobs and their information.
+ GetRenderPresets() --> [presets...] # Returns a table of render presets and their information.
+ StartRendering(index1, index2, ...) --> Bool # Starts rendering for given render jobs based on their indices. If no parameter is given rendering would start for all render jobs.
+ StartRendering([idxs...]) --> Bool # Starts rendering for given render jobs based on their indices. If no parameter is given rendering would start for all render jobs.
+ StopRendering() --> None # Stops rendering for all render jobs.
+ IsRenderingInProgress() --> Bool # Returns true is rendering is in progress.
+ AddRenderJob() --> Bool # Adds render job to render queue.
+ DeleteRenderJobByIndex(idx) --> Bool # Deletes render job based on given job index (int).
+ DeleteAllRenderJobs() --> Bool # Deletes all render jobs.
+ LoadRenderPreset(presetName) --> Bool # Sets a preset as current preset for rendering if presetName (text) exists.
+ SaveAsNewRenderPreset(presetName) --> Bool # Creates a new render preset by given name if presetName(text) is unique.
+ SetRenderSettings([settings map]) --> Bool # Sets given settings for rendering. Settings map is a map, keys of map are: "SelectAllFrames", "MarkIn", "MarkOut", "TargetDir", "CustomName".
+ GetRenderJobStatus(idx) --> [status info] # Returns job status and completion rendering percentage of the job by given job index (int).
+ GetSetting(settingName) --> string # Returns setting value by given settingName (string) if the setting exist. With empty settingName the function returns a full list of settings.
+ SetSetting(settingName, settingValue) --> Bool # Sets project setting base on given name (string) and value (string).
+ GetRenderFormats() --> [render formats...]# Returns a list of available render formats.
+ GetRenderCodecs(renderFormat) --> [render codecs...] # Returns a list of available codecs for given render format (string).
+ GetCurrentRenderFormatAndCodec() --> [format, codec] # Returns currently selected render format and render codec.
+ SetCurrentRenderFormatAndCodec(format, codec) --> Bool # Sets given render format (string) and render codec (string) as options for rendering.
+MediaStorage
+ GetMountedVolumes() --> [paths...] # Returns an array of folder paths corresponding to mounted volumes displayed in Resolve’s Media Storage.
+ GetSubFolders(folderPath) --> [paths...] # Returns an array of folder paths in the given absolute folder path.
+ GetFiles(folderPath) --> [paths...] # Returns an array of media and file listings in the given absolute folder path. Note that media listings may be logically consolidated entries.
+ RevealInStorage(path) --> None # Expands and displays a given file/folder path in Resolve’s Media Storage.
+ AddItemsToMediaPool(item1, item2, ...) --> [clips...] # Adds specified file/folder paths from Media Store into current Media Pool folder. Input is one or more file/folder paths.
+ AddItemsToMediaPool([items...]) --> [clips...] # Adds specified file/folder paths from Media Store into current Media Pool folder. Input is an array of file/folder paths.
+MediaPool
+ GetRootFolder() --> Folder # Returns the root Folder of Media Pool
+ AddSubFolder(folder, name) --> Folder # Adds a new subfolder under specified Folder object with the given name.
+ CreateEmptyTimeline(name) --> Timeline # Adds a new timeline with given name.
+ AppendToTimeline(clip1, clip2...) --> Bool # Appends specified MediaPoolItem objects in the current timeline. Returns True if successful.
+ AppendToTimeline([clips]) --> Bool # Appends specified MediaPoolItem objects in the current timeline. Returns True if successful.
+ CreateTimelineFromClips(name, clip1, clip2, ...)--> Timeline # Creates a new timeline with specified name, and appends the specified MediaPoolItem objects.
+ CreateTimelineFromClips(name, [clips]) --> Timeline # Creates a new timeline with specified name, and appends the specified MediaPoolItem objects.
+ ImportTimelineFromFile(filePath) --> Timeline # Creates timeline based on parameters within given file.
+ GetCurrentFolder() --> Folder # Returns currently selected Folder.
+ SetCurrentFolder(Folder) --> Bool # Sets current folder by given Folder.
+Folder
+ GetClips() --> [clips...] # Returns a list of clips (items) within the folder.
+ GetName() --> string # Returns user-defined name of the folder.
+ GetSubFolders() --> [folders...] # Returns a list of subfolders in the folder.
+MediaPoolItem
+ GetMetadata(metadataType) --> [[types],[values]] # Returns a value of metadataType. If parameter is not specified returns all set metadata parameters.
+ SetMetadata(metadataType, metadataValue) --> Bool # Sets metadata by given type and value. Returns True if successful.
+ GetMediaId() --> string # Returns a unique ID name related to MediaPoolItem.
+ AddMarker(frameId, color, name, note, duration) --> Bool # Creates a new marker at given frameId position and with given marker information.
+ GetMarkers() --> [markers...] # Returns a list of all markers and their information.
+ AddFlag(color) --> Bool # Adds a flag with given color (text).
+ GetFlags() --> [colors...] # Returns a list of flag colors assigned to the item.
+ GetClipColor() --> string # Returns an item color as a string.
+ GetClipProperty(propertyName) --> [[types],[values]] # Returns property value related to the item based on given propertyName (string). if propertyName is empty then it returns a full list of properties.
+ SetClipProperty(propertyName, propertyValue) --> Bool # Sets into given propertyName (string) propertyValue (string).
+Timeline
+ GetName() --> string # Returns user-defined name of the timeline.
+ SetName(timelineName) --> Bool # Sets timeline name is timelineName (text) is unique.
+ GetStartFrame() --> int # Returns frame number at the start of timeline.
+ GetEndFrame() --> int # Returns frame number at the end of timeline.
+ GetTrackCount(trackType) --> int # Returns a number of track based on specified track type ("audio", "video" or "subtitle").
+ GetItemsInTrack(trackType, index) --> [items...] # Returns an array of Timeline items on the video or audio track (based on trackType) at specified index. 1 <= index <= GetTrackCount(trackType).
+ AddMarker(frameId, color, name, note, duration) --> Bool # Creates a new marker at given frameId position and with given marker information.
+ GetMarkers() --> [markers...] # Returns a list of all markers and their information.
+ ApplyGradeFromDRX(path, gradeMode, item1, item2, ...)--> Bool # Loads a still from given file path (string) and applies grade to Timeline Items with gradeMode (int): 0 - "No keyframes", 1 - "Source Timecode aligned", 2 - "Start Frames aligned".
+ ApplyGradeFromDRX(path, gradeMode, [items]) --> Bool # Loads a still from given file path (string) and applies grade to Timeline Items with gradeMode (int): 0 - "No keyframes", 1 - "Source Timecode aligned", 2 - "Start Frames aligned".
+ GetCurrentTimecode() --> string # Returns a string representing a timecode for current position of the timeline, while on Cut, Edit, Color and Deliver page.
+ GetCurrentVideoItem() --> item # Returns current video timeline item.
+ GetCurrentClipThumbnailImage() --> [width, height, format, data] # Returns raw thumbnail image data (This image data is encoded in base 64 format and the image format is RGB 8 bit) for the current media in the Color Page in the format of dictionary (in Python) and table (in Lua). Information return are "width", "height", "format" and "data". Example is provided in 6_get_current_media_thumbnail.py in Example folder.
+TimelineItem
+ GetName() --> string # Returns a name of the item.
+ GetDuration() --> int # Returns a duration of item.
+ GetEnd() --> int # Returns a position of end frame.
+ GetFusionCompCount() --> int # Returns the number of Fusion compositions associated with the timeline item.
+ GetFusionCompByIndex(compIndex) --> fusionComp # Returns Fusion composition object based on given index. 1 <= compIndex <= timelineItem.GetFusionCompCount()
+ GetFusionCompNames() --> [names...] # Returns a list of Fusion composition names associated with the timeline item.
+ GetFusionCompByName(compName) --> fusionComp # Returns Fusion composition object based on given name.
+ GetLeftOffset() --> int # Returns a maximum extension by frame for clip from left side.
+ GetRightOffset() --> int # Returns a maximum extension by frame for clip from right side.
+ GetStart() --> int # Returns a position of first frame.
+ AddMarker(frameId, color, name, note, duration) --> Bool # Creates a new marker at given frameId position and with given marker information.
+ GetMarkers() --> [markers...] # Returns a list of all markers and their information.
+ GetFlags() --> [colors...] # Returns a list of flag colors assigned to the item.
+ GetClipColor() --> string # Returns an item color as a string.
+ AddFusionComp() --> fusionComp # Adds a new Fusion composition associated with the timeline item.
+ ImportFusionComp(path) --> fusionComp # Imports Fusion composition from given file path by creating and adding a new composition for the item.
+ ExportFusionComp(path, compIndex) --> Bool # Exports Fusion composition based on given index into provided file name path.
+ DeleteFusionCompByName(compName) --> Bool # Deletes Fusion composition by provided name.
+ LoadFusionCompByName(compName) --> fusionComp # Loads Fusion composition by provided name and sets it as active composition.
+ RenameFusionCompByName(oldName, newName) --> Bool # Renames Fusion composition by provided name with new given name.
+ AddVersion(versionName, versionType) --> Bool # Adds a new Version associated with the timeline item. versionType: 0 - local, 1 - remote.
+ DeleteVersionByName(versionName, versionType) --> Bool # Deletes Version by provided name. versionType: 0 - local, 1 - remote.
+ LoadVersionByName(versionName, versionType) --> Bool # Loads Version by provided name and sets it as active Version. versionType: 0 - local, 1 - remote.
+ RenameVersionByName(oldName, newName, versionType)--> Bool # Renames Version by provided name with new given name. versionType: 0 - local, 1 - remote.
+ GetMediaPoolItem() --> MediaPoolItem # Returns a corresponding to the timeline item media pool item if it exists.
+ GetVersionNames(versionType) --> [strings...] # Returns a list of version names by provided versionType: 0 - local, 1 - remote.
+ GetStereoConvergenceValues() --> [offset, value] # Returns a table of keyframe offsets and respective convergence values
+ GetStereoLeftFloatingWindowParams() --> [offset, value] # For the LEFT eye -> returns a table of keyframe offsets and respective floating window params. Value at particular offset includes the left, right, top and bottom floating window values
+ GetStereoRightFloatingWindowParams() --> [offset, value] # For the RIGHT eye -> returns a table of keyframe offsets and respective floating window params. Value at particular offset includes the left, right, top and bottom floating window values
diff --git a/pype/hosts/resolve/__init__.py b/pype/hosts/resolve/__init__.py
new file mode 100644
index 0000000000..72d6314b5e
--- /dev/null
+++ b/pype/hosts/resolve/__init__.py
@@ -0,0 +1,59 @@
+from .pipeline import (
+ install,
+ uninstall,
+ ls,
+ containerise,
+ publish,
+ launch_workfiles_app
+)
+
+from .utils import (
+ setup,
+ get_resolve_module
+)
+
+from .workio import (
+ open_file,
+ save_file,
+ current_file,
+ has_unsaved_changes,
+ file_extensions,
+ work_root
+)
+
+from .lib import (
+ get_project_manager,
+ set_project_manager_to_folder_name
+)
+
+from .menu import launch_pype_menu
+
+__all__ = [
+ # pipeline
+ "install",
+ "uninstall",
+ "ls",
+ "containerise",
+ "reload_pipeline",
+ "publish",
+ "launch_workfiles_app",
+
+ # utils
+ "setup",
+ "get_resolve_module",
+
+ # lib
+ "get_project_manager",
+ "set_project_manager_to_folder_name",
+
+ # menu
+ "launch_pype_menu",
+
+ # workio
+ "open_file",
+ "save_file",
+ "current_file",
+ "has_unsaved_changes",
+ "file_extensions",
+ "work_root"
+]
diff --git a/pype/hosts/resolve/action.py b/pype/hosts/resolve/action.py
new file mode 100644
index 0000000000..31830937c1
--- /dev/null
+++ b/pype/hosts/resolve/action.py
@@ -0,0 +1,54 @@
+# absolute_import is needed to counter the `module has no cmds error` in Maya
+from __future__ import absolute_import
+
+import pyblish.api
+
+
+from ...action import get_errored_instances_from_context
+
+
+class SelectInvalidAction(pyblish.api.Action):
+ """Select invalid clips in Resolve timeline when plug-in failed.
+
+ To retrieve the invalid nodes this assumes a static `get_invalid()`
+ method is available on the plugin.
+
+ """
+ label = "Select invalid"
+ on = "failed" # This action is only available on a failed plug-in
+ icon = "search" # Icon from Awesome Icon
+
+ def process(self, context, plugin):
+
+ try:
+ from pype.hosts.resolve.utils import get_resolve_module
+ resolve = get_resolve_module()
+ self.log.debug(resolve)
+ except ImportError:
+ raise ImportError("Current host is not Resolve")
+
+ errored_instances = get_errored_instances_from_context(context)
+
+ # Apply pyblish.logic to get the instances for the plug-in
+ instances = pyblish.api.instances_by_plugin(errored_instances, plugin)
+
+ # Get the invalid nodes for the plug-ins
+ self.log.info("Finding invalid clips..")
+ invalid = list()
+ for instance in instances:
+ invalid_nodes = plugin.get_invalid(instance)
+ if invalid_nodes:
+ if isinstance(invalid_nodes, (list, tuple)):
+ invalid.extend(invalid_nodes)
+ else:
+ self.log.warning("Plug-in returned to be invalid, "
+ "but has no selectable nodes.")
+
+ # Ensure unique (process each node only once)
+ invalid = list(set(invalid))
+
+ if invalid:
+ self.log.info("Selecting invalid nodes: %s" % ", ".join(invalid))
+ # TODO: select resolve timeline track items in current timeline
+ else:
+ self.log.info("No invalid nodes found.")
diff --git a/pype/hosts/resolve/lib.py b/pype/hosts/resolve/lib.py
new file mode 100644
index 0000000000..2576136df5
--- /dev/null
+++ b/pype/hosts/resolve/lib.py
@@ -0,0 +1,78 @@
+import sys
+from .utils import get_resolve_module
+from pypeapp import Logger
+
+log = Logger().get_logger(__name__, "resolve")
+
+self = sys.modules[__name__]
+self.pm = None
+
+
+def get_project_manager():
+ if not self.pm:
+ resolve = get_resolve_module()
+ self.pm = resolve.GetProjectManager()
+ return self.pm
+
+
+def set_project_manager_to_folder_name(folder_name):
+ """
+ Sets context of Project manager to given folder by name.
+
+ Searching for folder by given name from root folder to nested.
+ If no existing folder by name it will create one in root folder.
+
+ Args:
+ folder_name (str): name of searched folder
+
+ Returns:
+ bool: True if success
+
+ Raises:
+ Exception: Cannot create folder in root
+
+ """
+ # initialize project manager
+ get_project_manager()
+
+ set_folder = False
+
+ # go back to root folder
+ if self.pm.GotoRootFolder():
+ log.info(f"Testing existing folder: {folder_name}")
+ folders = convert_resolve_list_type(
+ self.pm.GetFoldersInCurrentFolder())
+ log.info(f"Testing existing folders: {folders}")
+ # get me first available folder object
+ # with the same name as in `folder_name` else return False
+ if next((f for f in folders if f in folder_name), False):
+ log.info(f"Found existing folder: {folder_name}")
+ set_folder = self.pm.OpenFolder(folder_name)
+
+ if set_folder:
+ return True
+
+ # if folder by name is not existent then create one
+ # go back to root folder
+ log.info(f"Folder `{folder_name}` not found and will be created")
+ if self.pm.GotoRootFolder():
+ try:
+ # create folder by given name
+ self.pm.CreateFolder(folder_name)
+ self.pm.OpenFolder(folder_name)
+ return True
+ except NameError as e:
+ log.error((f"Folder with name `{folder_name}` cannot be created!"
+ f"Error: {e}"))
+ return False
+
+
+def convert_resolve_list_type(resolve_list):
+ """ Resolve is using indexed dictionary as list type.
+ `{1.0: 'vaule'}`
+ This will convert it to normal list class
+ """
+ assert isinstance(resolve_list, dict), (
+ "Input argument should be dict() type")
+
+ return [resolve_list[i] for i in sorted(resolve_list.keys())]
diff --git a/pype/hosts/resolve/menu.py b/pype/hosts/resolve/menu.py
new file mode 100644
index 0000000000..73ea937513
--- /dev/null
+++ b/pype/hosts/resolve/menu.py
@@ -0,0 +1,154 @@
+import os
+import sys
+
+from Qt import QtWidgets, QtCore
+
+from .pipeline import (
+ publish,
+ launch_workfiles_app
+)
+
+from avalon.tools import (
+ creator,
+ loader,
+ sceneinventory,
+ libraryloader
+)
+
+
+def load_stylesheet():
+ path = os.path.join(os.path.dirname(__file__), "menu_style.qss")
+ if not os.path.exists(path):
+ print("Unable to load stylesheet, file not found in resources")
+ return ""
+
+ with open(path, "r") as file_stream:
+ stylesheet = file_stream.read()
+ return stylesheet
+
+
+class Spacer(QtWidgets.QWidget):
+ def __init__(self, height, *args, **kwargs):
+ super(self.__class__, self).__init__(*args, **kwargs)
+
+ self.setFixedHeight(height)
+
+ real_spacer = QtWidgets.QWidget(self)
+ real_spacer.setObjectName("Spacer")
+ real_spacer.setFixedHeight(height)
+
+ layout = QtWidgets.QVBoxLayout(self)
+ layout.setContentsMargins(0, 0, 0, 0)
+ layout.addWidget(real_spacer)
+
+ self.setLayout(layout)
+
+
+class PypeMenu(QtWidgets.QWidget):
+ def __init__(self, *args, **kwargs):
+ super(self.__class__, self).__init__(*args, **kwargs)
+
+ self.setObjectName("PypeMenu")
+
+ self.setWindowFlags(
+ QtCore.Qt.Window
+ | QtCore.Qt.CustomizeWindowHint
+ | QtCore.Qt.WindowTitleHint
+ | QtCore.Qt.WindowCloseButtonHint
+ | QtCore.Qt.WindowStaysOnTopHint
+ )
+
+ self.setWindowTitle("Pype")
+ workfiles_btn = QtWidgets.QPushButton("Workfiles", self)
+ create_btn = QtWidgets.QPushButton("Create", self)
+ publish_btn = QtWidgets.QPushButton("Publish", self)
+ load_btn = QtWidgets.QPushButton("Load", self)
+ inventory_btn = QtWidgets.QPushButton("Inventory", self)
+ libload_btn = QtWidgets.QPushButton("Library", self)
+ rename_btn = QtWidgets.QPushButton("Rename", self)
+ set_colorspace_btn = QtWidgets.QPushButton(
+ "Set colorspace from presets", self
+ )
+ reset_resolution_btn = QtWidgets.QPushButton(
+ "Reset Resolution from peresets", self
+ )
+
+ layout = QtWidgets.QVBoxLayout(self)
+ layout.setContentsMargins(10, 20, 10, 20)
+
+ layout.addWidget(workfiles_btn)
+ layout.addWidget(create_btn)
+ layout.addWidget(publish_btn)
+ layout.addWidget(load_btn)
+ layout.addWidget(inventory_btn)
+
+ layout.addWidget(Spacer(15, self))
+
+ layout.addWidget(libload_btn)
+
+ layout.addWidget(Spacer(15, self))
+
+ layout.addWidget(rename_btn)
+
+ layout.addWidget(Spacer(15, self))
+
+ layout.addWidget(set_colorspace_btn)
+ layout.addWidget(reset_resolution_btn)
+
+ self.setLayout(layout)
+
+ workfiles_btn.clicked.connect(self.on_workfile_clicked)
+ create_btn.clicked.connect(self.on_create_clicked)
+ publish_btn.clicked.connect(self.on_publish_clicked)
+ load_btn.clicked.connect(self.on_load_clicked)
+ inventory_btn.clicked.connect(self.on_inventory_clicked)
+ libload_btn.clicked.connect(self.on_libload_clicked)
+ rename_btn.clicked.connect(self.on_rename_clicked)
+ set_colorspace_btn.clicked.connect(self.on_set_colorspace_clicked)
+ reset_resolution_btn.clicked.connect(self.on_reset_resolution_clicked)
+
+ def on_workfile_clicked(self):
+ print("Clicked Workfile")
+ launch_workfiles_app()
+
+ def on_create_clicked(self):
+ print("Clicked Create")
+ creator.show()
+
+ def on_publish_clicked(self):
+ print("Clicked Publish")
+ publish(None)
+
+ def on_load_clicked(self):
+ print("Clicked Load")
+ loader.show(use_context=True)
+
+ def on_inventory_clicked(self):
+ print("Clicked Inventory")
+ sceneinventory.show()
+
+ def on_libload_clicked(self):
+ print("Clicked Library")
+ libraryloader.show()
+
+ def on_rename_clicked(self):
+ print("Clicked Rename")
+
+ def on_set_colorspace_clicked(self):
+ print("Clicked Set Colorspace")
+
+ def on_reset_resolution_clicked(self):
+ print("Clicked Reset Resolution")
+
+
+def launch_pype_menu():
+ app = QtWidgets.QApplication(sys.argv)
+
+ pype_menu = PypeMenu()
+
+ stylesheet = load_stylesheet()
+ pype_menu.setStyleSheet(stylesheet)
+
+ pype_menu.show()
+
+ sys.exit(app.exec_())
diff --git a/pype/hosts/resolve/menu_style.qss b/pype/hosts/resolve/menu_style.qss
new file mode 100644
index 0000000000..df4fd7e949
--- /dev/null
+++ b/pype/hosts/resolve/menu_style.qss
@@ -0,0 +1,29 @@
+QWidget {
+ background-color: #282828;
+ border-radius: 3;
+}
+
+QPushButton {
+ border: 1px solid #090909;
+ background-color: #201f1f;
+ color: #ffffff;
+ padding: 5;
+}
+
+QPushButton:focus {
+ background-color: "#171717";
+ color: #d0d0d0;
+}
+
+QPushButton:hover {
+ background-color: "#171717";
+ color: #e64b3d;
+}
+
+#PypeMenu {
+ border: 1px solid #fef9ef;
+}
+
+#Spacer {
+ background-color: #282828;
+}
diff --git a/pype/hosts/resolve/pipeline.py b/pype/hosts/resolve/pipeline.py
new file mode 100644
index 0000000000..967aed1436
--- /dev/null
+++ b/pype/hosts/resolve/pipeline.py
@@ -0,0 +1,142 @@
+"""
+Basic avalon integration
+"""
+import os
+# import sys
+from avalon.tools import workfiles
+from avalon import api as avalon
+from pyblish import api as pyblish
+from pypeapp import Logger
+
+log = Logger().get_logger(__name__, "resolve")
+
+# self = sys.modules[__name__]
+
+AVALON_CONFIG = os.environ["AVALON_CONFIG"]
+PARENT_DIR = os.path.dirname(__file__)
+PACKAGE_DIR = os.path.dirname(PARENT_DIR)
+PLUGINS_DIR = os.path.join(PACKAGE_DIR, "plugins")
+
+LOAD_PATH = os.path.join(PLUGINS_DIR, "resolve", "load")
+CREATE_PATH = os.path.join(PLUGINS_DIR, "resolve", "create")
+INVENTORY_PATH = os.path.join(PLUGINS_DIR, "resolve", "inventory")
+
+PUBLISH_PATH = os.path.join(
+ PLUGINS_DIR, "resolve", "publish"
+).replace("\\", "/")
+
+AVALON_CONTAINERS = ":AVALON_CONTAINERS"
+# IS_HEADLESS = not hasattr(cmds, "about") or cmds.about(batch=True)
+
+
+def install():
+ """Install resolve-specific functionality of avalon-core.
+
+ This is where you install menus and register families, data
+ and loaders into resolve.
+
+ It is called automatically when installing via `api.install(resolve)`.
+
+ See the Maya equivalent for inspiration on how to implement this.
+
+ """
+
+ # Disable all families except for the ones we explicitly want to see
+ family_states = [
+ "imagesequence",
+ "mov"
+ ]
+ avalon.data["familiesStateDefault"] = False
+ avalon.data["familiesStateToggled"] = family_states
+
+ log.info("pype.hosts.resolve installed")
+
+ pyblish.register_host("resolve")
+ pyblish.register_plugin_path(PUBLISH_PATH)
+ log.info("Registering DaVinci Resovle plug-ins..")
+
+ avalon.register_plugin_path(avalon.Loader, LOAD_PATH)
+ avalon.register_plugin_path(avalon.Creator, CREATE_PATH)
+ avalon.register_plugin_path(avalon.InventoryAction, INVENTORY_PATH)
+
+
+def uninstall():
+ """Uninstall all tha was installed
+
+ This is where you undo everything that was done in `install()`.
+ That means, removing menus, deregistering families and data
+ and everything. It should be as though `install()` was never run,
+ because odds are calling this function means the user is interested
+ in re-installing shortly afterwards. If, for example, he has been
+ modifying the menu or registered families.
+
+ """
+ pyblish.deregister_host("resolve")
+ pyblish.deregister_plugin_path(PUBLISH_PATH)
+ log.info("Deregistering DaVinci Resovle plug-ins..")
+
+ avalon.deregister_plugin_path(avalon.Loader, LOAD_PATH)
+ avalon.deregister_plugin_path(avalon.Creator, CREATE_PATH)
+ avalon.deregister_plugin_path(avalon.InventoryAction, INVENTORY_PATH)
+
+
+def containerise(obj,
+ name,
+ namespace,
+ context,
+ loader=None,
+ data=None):
+ """Bundle Resolve's object into an assembly and imprint it with metadata
+
+ Containerisation enables a tracking of version, author and origin
+ for loaded assets.
+
+ Arguments:
+ obj (obj): Resolve's object to imprint as container
+ name (str): Name of resulting assembly
+ namespace (str): Namespace under which to host container
+ context (dict): Asset information
+ loader (str, optional): Name of node used to produce this container.
+
+ Returns:
+ obj (obj): containerised object
+
+ """
+ pass
+
+
+def ls():
+ """List available containers.
+
+ This function is used by the Container Manager in Nuke. You'll
+ need to implement a for-loop that then *yields* one Container at
+ a time.
+
+ See the `container.json` schema for details on how it should look,
+ and the Maya equivalent, which is in `avalon.maya.pipeline`
+ """
+ pass
+
+
+def parse_container(container):
+ """Return the container node's full container data.
+
+ Args:
+ container (str): A container node name.
+
+ Returns:
+ dict: The container schema data for this container node.
+
+ """
+ pass
+
+
+def launch_workfiles_app(*args):
+ workdir = os.environ["AVALON_WORKDIR"]
+ workfiles.show(workdir)
+
+
+def publish(parent):
+ """Shorthand to publish from within host"""
+ from avalon.tools import publish
+ return publish.show(parent)
diff --git a/pype/hosts/resolve/plugin.py b/pype/hosts/resolve/plugin.py
new file mode 100644
index 0000000000..628d4bdb26
--- /dev/null
+++ b/pype/hosts/resolve/plugin.py
@@ -0,0 +1,75 @@
+from avalon import api
+# from pype.hosts.resolve import lib as drlib
+from avalon.vendor import qargparse
+
+
+def get_reference_node_parents(ref):
+ """Return all parent reference nodes of reference node
+
+ Args:
+ ref (str): reference node.
+
+ Returns:
+ list: The upstream parent reference nodes.
+
+ """
+ parents = []
+ return parents
+
+
+class SequenceLoader(api.Loader):
+ """A basic SequenceLoader for Resolve
+
+ This will implement the basic behavior for a loader to inherit from that
+ will containerize the reference and will implement the `remove` and
+ `update` logic.
+
+ """
+
+ options = [
+ qargparse.Toggle(
+ "handles",
+ label="Include handles",
+ default=0,
+ help="Load with handles or without?"
+ ),
+ qargparse.Choice(
+ "load_to",
+ label="Where to load clips",
+ items=[
+ "Current timeline",
+ "New timeline"
+ ],
+ default=0,
+ help="Where do you want clips to be loaded?"
+ ),
+ qargparse.Choice(
+ "load_how",
+ label="How to load clips",
+ items=[
+ "original timing",
+ "sequential in order"
+ ],
+ default=0,
+ help="Would you like to place it at orignal timing?"
+ )
+ ]
+
+ def load(
+ self,
+ context,
+ name=None,
+ namespace=None,
+ options=None
+ ):
+ pass
+
+ def update(self, container, representation):
+ """Update an existing `container`
+ """
+ pass
+
+ def remove(self, container):
+ """Remove an existing `container`
+ """
+ pass
diff --git a/pype/hosts/resolve/preload_console.py b/pype/hosts/resolve/preload_console.py
new file mode 100644
index 0000000000..ea1bd4f180
--- /dev/null
+++ b/pype/hosts/resolve/preload_console.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+import time
+from pype.hosts.resolve.utils import get_resolve_module
+from pypeapp import Logger
+
+log = Logger().get_logger(__name__, "resolve")
+
+wait_delay = 2.5
+wait = 0.00
+ready = None
+while True:
+ try:
+ # Create project and set parameters:
+ resolve = get_resolve_module()
+ pm = resolve.GetProjectManager()
+ if pm:
+ ready = None
+ else:
+ ready = True
+ except AttributeError:
+ pass
+
+ if ready is None:
+ time.sleep(wait_delay)
+ log.info(f"Waiting {wait}s for Resolve to have opened Project Manager")
+ wait += wait_delay
+ else:
+ print(f"Preloaded variables: \n\n\tResolve module: "
+ f"`resolve` > {type(resolve)} \n\tProject manager: "
+ f"`pm` > {type(pm)}")
+ break
diff --git a/pype/hosts/resolve/utility_scripts/Pype_menu.py b/pype/hosts/resolve/utility_scripts/Pype_menu.py
new file mode 100644
index 0000000000..1f5cd36277
--- /dev/null
+++ b/pype/hosts/resolve/utility_scripts/Pype_menu.py
@@ -0,0 +1,26 @@
+import os
+import sys
+import avalon.api as avalon
+import pype
+
+from pypeapp import Logger
+
+log = Logger().get_logger(__name__)
+
+
+def main(env):
+ import pype.hosts.resolve as bmdvr
+ # Registers pype's Global pyblish plugins
+ pype.install()
+
+ # activate resolve from pype
+ avalon.install(bmdvr)
+
+ log.info(f"Avalon registred hosts: {avalon.registered_host()}")
+
+ bmdvr.launch_pype_menu()
+
+
+if __name__ == "__main__":
+ result = main(os.environ)
+ sys.exit(not bool(result))
diff --git a/pype/hosts/resolve/utility_scripts/README.markdown b/pype/hosts/resolve/utility_scripts/README.markdown
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/pype/hosts/resolve/utility_scripts/README.markdown
@@ -0,0 +1 @@
+
diff --git a/pype/hosts/resolve/utility_scripts/__dev_compound_clip.py b/pype/hosts/resolve/utility_scripts/__dev_compound_clip.py
new file mode 100644
index 0000000000..fe47008c70
--- /dev/null
+++ b/pype/hosts/resolve/utility_scripts/__dev_compound_clip.py
@@ -0,0 +1,65 @@
+#! python3
+# -*- coding: utf-8 -*-
+
+
+# convert clip def
+def convert_clip(timeline=None):
+ """Convert timeline item (clip) into compound clip pype container
+
+ Args:
+ timeline (MediaPool.Timeline): Object of timeline
+
+ Returns:
+ bool: `True` if success
+
+ Raises:
+ Exception: description
+
+ """
+ pass
+
+
+# decorator function create_current_timeline_media_bin()
+def create_current_timeline_media_bin(timeline=None):
+ """Convert timeline item (clip) into compound clip pype container
+
+ Args:
+ timeline (MediaPool.Timeline): Object of timeline
+
+ Returns:
+ bool: `True` if success
+
+ Raises:
+ Exception: description
+
+ """
+ pass
+
+
+# decorator function get_selected_track_items()
+def get_selected_track_items():
+ """Convert timeline item (clip) into compound clip pype container
+
+ Args:
+ timeline (MediaPool.Timeline): Object of timeline
+
+ Returns:
+ bool: `True` if success
+
+ Raises:
+ Exception: description
+
+ """
+ print("testText")
+
+
+# PypeCompoundClip() class
+class PypeCompoundClip(object):
+ """docstring for ."""
+
+ def __init__(self, arg):
+ super(self).__init__()
+ self.arg = arg
+
+ def create_compound_clip(self):
+ pass
diff --git a/pype/hosts/resolve/utility_scripts/__test_pyblish.py b/pype/hosts/resolve/utility_scripts/__test_pyblish.py
new file mode 100644
index 0000000000..a6fe991025
--- /dev/null
+++ b/pype/hosts/resolve/utility_scripts/__test_pyblish.py
@@ -0,0 +1,57 @@
+import os
+import sys
+import pype
+import importlib
+import pyblish.api
+import pyblish.util
+import avalon.api
+from avalon.tools import publish
+from pypeapp import Logger
+
+log = Logger().get_logger(__name__)
+
+
+def main(env):
+ # Registers pype's Global pyblish plugins
+ pype.install()
+
+ # Register Host (and it's pyblish plugins)
+ host_name = env["AVALON_APP"]
+ # TODO not sure if use "pype." or "avalon." for host import
+ host_import_str = f"pype.{host_name}"
+
+ try:
+ host_module = importlib.import_module(host_import_str)
+ except ModuleNotFoundError:
+ log.error((
+ f"Host \"{host_name}\" can't be imported."
+ f" Import string \"{host_import_str}\" failed."
+ ))
+ return False
+
+ avalon.api.install(host_module)
+
+ # Register additional paths
+ addition_paths_str = env.get("PUBLISH_PATHS") or ""
+ addition_paths = addition_paths_str.split(os.pathsep)
+ for path in addition_paths:
+ path = os.path.normpath(path)
+ if not os.path.exists(path):
+ continue
+
+ pyblish.api.register_plugin_path(path)
+
+ # Register project specific plugins
+ project_name = os.environ["AVALON_PROJECT"]
+ project_plugins_paths = env.get("PYPE_PROJECT_PLUGINS") or ""
+ for path in project_plugins_paths.split(os.pathsep):
+ plugin_path = os.path.join(path, project_name, "plugins")
+ if os.path.exists(plugin_path):
+ pyblish.api.register_plugin_path(plugin_path)
+
+ return publish.show()
+
+
+if __name__ == "__main__":
+ result = main(os.environ)
+ sys.exit(not bool(result))
diff --git a/pype/hosts/resolve/utility_scripts/__test_subprocess.py b/pype/hosts/resolve/utility_scripts/__test_subprocess.py
new file mode 100644
index 0000000000..bdc57bbf00
--- /dev/null
+++ b/pype/hosts/resolve/utility_scripts/__test_subprocess.py
@@ -0,0 +1,35 @@
+#! python3
+# -*- coding: utf-8 -*-
+import os
+from pypeapp import execute, Logger
+from pype.hosts.resolve.utils import get_resolve_module
+
+log = Logger().get_logger("Resolve")
+
+CURRENT_DIR = os.getenv("RESOLVE_UTILITY_SCRIPTS_DIR", "")
+python_dir = os.getenv("PYTHON36_RESOLVE")
+python_exe = os.path.normpath(
+ os.path.join(python_dir, "python.exe")
+)
+
+resolve = get_resolve_module()
+PM = resolve.GetProjectManager()
+P = PM.GetCurrentProject()
+
+log.info(P.GetName())
+
+
+# ______________________________________________________
+# testing subprocessing Scripts
+testing_py = os.path.join(CURRENT_DIR, "ResolvePageSwitcher.py")
+testing_py = os.path.normpath(testing_py)
+log.info(f"Testing path to script: `{testing_py}`")
+
+returncode = execute(
+ [python_exe, os.path.normpath(testing_py)],
+ env=dict(os.environ)
+)
+
+# Check if output file exists
+if returncode != 0:
+ log.error("Executing failed!")
diff --git a/pype/hosts/resolve/utils.py b/pype/hosts/resolve/utils.py
new file mode 100644
index 0000000000..f5add53a6b
--- /dev/null
+++ b/pype/hosts/resolve/utils.py
@@ -0,0 +1,136 @@
+#! python3
+
+"""
+Resolve's tools for setting environment
+"""
+
+import sys
+import os
+import shutil
+
+from pypeapp import Logger
+
+log = Logger().get_logger(__name__, "resolve")
+
+self = sys.modules[__name__]
+self.bmd = None
+
+
+def get_resolve_module():
+ # dont run if already loaded
+ if self.bmd:
+ return self.bmd
+
+ try:
+ """
+ The PYTHONPATH needs to be set correctly for this import
+ statement to work. An alternative is to import the
+ DaVinciResolveScript by specifying absolute path
+ (see ExceptionHandler logic)
+ """
+ import DaVinciResolveScript as bmd
+ except ImportError:
+ if sys.platform.startswith("darwin"):
+ expected_path = ("/Library/Application Support/Blackmagic Design"
+ "/DaVinci Resolve/Developer/Scripting/Modules")
+ elif sys.platform.startswith("win") \
+ or sys.platform.startswith("cygwin"):
+ expected_path = os.path.normpath(
+ os.getenv('PROGRAMDATA') + (
+ "/Blackmagic Design/DaVinci Resolve/Support/Developer"
+ "/Scripting/Modules"
+ )
+ )
+ elif sys.platform.startswith("linux"):
+ expected_path = "/opt/resolve/libs/Fusion/Modules"
+
+ # check if the default path has it...
+ print(("Unable to find module DaVinciResolveScript from "
+ "$PYTHONPATH - trying default locations"))
+
+ module_path = os.path.normpath(
+ os.path.join(
+ expected_path,
+ "DaVinciResolveScript.py"
+ )
+ )
+
+ try:
+ import imp
+ bmd = imp.load_source('DaVinciResolveScript', module_path)
+ except ImportError:
+ # No fallbacks ... report error:
+ log.error(
+ ("Unable to find module DaVinciResolveScript - please "
+ "ensure that the module DaVinciResolveScript is "
+ "discoverable by python")
+ )
+ log.error(
+ ("For a default DaVinci Resolve installation, the "
+ f"module is expected to be located in: {expected_path}")
+ )
+ sys.exit()
+ # assign global var and return
+ self.bmd = bmd.scriptapp("Resolve")
+ return self.bmd
+
+
+def _sync_utility_scripts(env=None):
+ """ Synchronizing basic utlility scripts for resolve.
+
+ To be able to run scripts from inside `Resolve/Workspace/Scripts` menu
+ all scripts has to be accessible from defined folder.
+ """
+ if not env:
+ env = os.environ
+
+ # initiate inputs
+ scripts = {}
+ us_env = env.get("RESOLVE_UTILITY_SCRIPTS_SOURCE_DIR")
+ us_dir = env.get("RESOLVE_UTILITY_SCRIPTS_DIR", "")
+ us_paths = [os.path.join(
+ os.path.dirname(__file__),
+ "utility_scripts"
+ )]
+
+ # collect script dirs
+ if us_env:
+ log.info(f"Utility Scripts Env: `{us_env}`")
+ us_paths = us_env.split(
+ os.pathsep) + us_paths
+
+ # collect scripts from dirs
+ for path in us_paths:
+ scripts.update({path: os.listdir(path)})
+
+ log.info(f"Utility Scripts Dir: `{us_paths}`")
+ log.info(f"Utility Scripts: `{scripts}`")
+
+ # make sure no script file is in folder
+ if next((s for s in os.listdir(us_dir)), None):
+ for s in os.listdir(us_dir):
+ path = os.path.join(us_dir, s)
+ log.info(f"Removing `{path}`...")
+ os.remove(path)
+
+ # copy scripts into Resolve's utility scripts dir
+ for d, sl in scripts.items():
+ # directory and scripts list
+ for s in sl:
+ # script in script list
+ src = os.path.join(d, s)
+ dst = os.path.join(us_dir, s)
+ log.info(f"Copying `{src}` to `{dst}`...")
+ shutil.copy2(src, dst)
+
+
+def setup(env=None):
+ """ Wrapper installer started from pype.hooks.resolve.ResolvePrelaunch()
+ """
+ if not env:
+ env = os.environ
+
+ # synchronize resolve utility scripts
+ _sync_utility_scripts(env)
+
+ log.info("Resolve Pype wrapper has been installed")
diff --git a/pype/hosts/resolve/workio.py b/pype/hosts/resolve/workio.py
new file mode 100644
index 0000000000..e1e30a8734
--- /dev/null
+++ b/pype/hosts/resolve/workio.py
@@ -0,0 +1,92 @@
+"""Host API required Work Files tool"""
+
+import os
+from pypeapp import Logger
+from .lib import (
+ get_project_manager,
+ set_project_manager_to_folder_name
+)
+
+
+log = Logger().get_logger(__name__, "resolve")
+
+exported_projet_ext = ".drp"
+
+
+def file_extensions():
+ return [exported_projet_ext]
+
+
+def has_unsaved_changes():
+ get_project_manager().SaveProject()
+ return False
+
+
+def save_file(filepath):
+ pm = get_project_manager()
+ file = os.path.basename(filepath)
+ fname, _ = os.path.splitext(file)
+ project = pm.GetCurrentProject()
+ name = project.GetName()
+
+ if "Untitled Project" not in name:
+ log.info("Saving project: `{}` as '{}'".format(name, file))
+ pm.ExportProject(name, filepath)
+ else:
+ log.info("Creating new project...")
+ pm.CreateProject(fname)
+ pm.ExportProject(name, filepath)
+
+
+def open_file(filepath):
+ """
+ Loading project
+ """
+ pm = get_project_manager()
+ file = os.path.basename(filepath)
+ fname, _ = os.path.splitext(file)
+ dname, _ = fname.split("_v")
+
+ # deal with current project
+ project = pm.GetCurrentProject()
+ log.info(f"Test `pm`: {pm}")
+ pm.SaveProject()
+
+ try:
+ log.info(f"Test `dname`: {dname}")
+ if not set_project_manager_to_folder_name(dname):
+ raise
+ # load project from input path
+ project = pm.LoadProject(fname)
+ log.info(f"Project {project.GetName()} opened...")
+ return True
+ except AttributeError:
+ log.warning((f"Project with name `{fname}` does not exist! It will "
+ f"be imported from {filepath} and then loaded..."))
+ if pm.ImportProject(filepath):
+ # load project from input path
+ project = pm.LoadProject(fname)
+ log.info(f"Project imported/loaded {project.GetName()}...")
+ return True
+ else:
+ return False
+
+
+def current_file():
+ pm = get_project_manager()
+ current_dir = os.getenv("AVALON_WORKDIR")
+ project = pm.GetCurrentProject()
+ name = project.GetName()
+ fname = name + exported_projet_ext
+ current_file = os.path.join(current_dir, fname)
+ normalised = os.path.normpath(current_file)
+
+ # Unsaved current file
+ if normalised == "":
+ return None
+
+ return normalised
+
+
+def work_root(session):
+ return os.path.normpath(session["AVALON_WORKDIR"]).replace("\\", "/")
diff --git a/pype/modules/clockify/clockify.py b/pype/modules/clockify/clockify.py
index 6d5dc9213c..2ab22702c1 100644
--- a/pype/modules/clockify/clockify.py
+++ b/pype/modules/clockify/clockify.py
@@ -1,7 +1,7 @@
import os
import threading
from pype.api import Logger
-from pypeapp import style
+from avalon import style
from Qt import QtWidgets
from . import ClockifySettings, ClockifyAPI, MessageWidget
diff --git a/pype/modules/clockify/widget_message.py b/pype/modules/clockify/widget_message.py
index 349875b9e5..f919c3f819 100644
--- a/pype/modules/clockify/widget_message.py
+++ b/pype/modules/clockify/widget_message.py
@@ -1,5 +1,5 @@
from Qt import QtCore, QtGui, QtWidgets
-from pypeapp import style
+from avalon import style
class MessageWidget(QtWidgets.QWidget):
diff --git a/pype/modules/clockify/widget_settings.py b/pype/modules/clockify/widget_settings.py
index 027268834c..956bdb1916 100644
--- a/pype/modules/clockify/widget_settings.py
+++ b/pype/modules/clockify/widget_settings.py
@@ -1,6 +1,6 @@
import os
from Qt import QtCore, QtGui, QtWidgets
-from pypeapp import style
+from avalon import style
class ClockifySettings(QtWidgets.QWidget):
diff --git a/pype/modules/ftrack/actions/action_application_loader.py b/pype/modules/ftrack/actions/action_application_loader.py
index 11aac28615..ec7fc53fb6 100644
--- a/pype/modules/ftrack/actions/action_application_loader.py
+++ b/pype/modules/ftrack/actions/action_application_loader.py
@@ -1,7 +1,7 @@
import os
import toml
import time
-from pype.modules.ftrack import AppAction
+from pype.modules.ftrack.lib import AppAction
from avalon import lib
from pype.api import Logger
from pype.lib import get_all_avalon_projects
@@ -72,7 +72,7 @@ def register(session, plugins_presets={}):
for app in apps:
try:
registerApp(app, session, plugins_presets)
- if app_counter%5 == 0:
+ if app_counter % 5 == 0:
time.sleep(0.1)
app_counter += 1
except Exception as exc:
diff --git a/pype/modules/ftrack/actions/action_attributes_remapper.py b/pype/modules/ftrack/actions/action_attributes_remapper.py
deleted file mode 100644
index b5fad7dc45..0000000000
--- a/pype/modules/ftrack/actions/action_attributes_remapper.py
+++ /dev/null
@@ -1,284 +0,0 @@
-import os
-
-import ftrack_api
-from pype.modules.ftrack import BaseAction
-from pype.modules.ftrack.lib.io_nonsingleton import DbConnector
-
-
-class AttributesRemapper(BaseAction):
- '''Edit meta data action.'''
-
- ignore_me = True
- #: Action identifier.
- identifier = 'attributes.remapper'
- #: Action label.
- label = "Pype Doctor"
- variant = '- Attributes Remapper'
- #: Action description.
- description = 'Remaps attributes in avalon DB'
-
- #: roles that are allowed to register this action
- role_list = ["Pypeclub", "Administrator"]
- icon = '{}/ftrack/action_icons/PypeDoctor.svg'.format(
- os.environ.get('PYPE_STATICS_SERVER', '')
- )
-
- db_con = DbConnector()
- keys_to_change = {
- "fstart": "frameStart",
- "startFrame": "frameStart",
- "edit_in": "frameStart",
-
- "fend": "frameEnd",
- "endFrame": "frameEnd",
- "edit_out": "frameEnd",
-
- "handle_start": "handleStart",
- "handle_end": "handleEnd",
- "handles": ["handleEnd", "handleStart"],
-
- "frameRate": "fps",
- "framerate": "fps",
- "resolution_width": "resolutionWidth",
- "resolution_height": "resolutionHeight",
- "pixel_aspect": "pixelAspect"
- }
-
- def discover(self, session, entities, event):
- ''' Validation '''
-
- return True
-
- def interface(self, session, entities, event):
- if event['data'].get('values', {}):
- return
-
- title = 'Select Projects where attributes should be remapped'
-
- items = []
-
- selection_enum = {
- 'label': 'Process type',
- 'type': 'enumerator',
- 'name': 'process_type',
- 'data': [
- {
- 'label': 'Selection',
- 'value': 'selection'
- }, {
- 'label': 'Inverted selection',
- 'value': 'except'
- }
- ],
- 'value': 'selection'
- }
- selection_label = {
- 'type': 'label',
- 'value': (
- 'Selection based variants:
'
- '- `Selection` - '
- 'NOTHING is processed when nothing is selected
'
- '- `Inverted selection` - '
- 'ALL Projects are processed when nothing is selected'
- )
- }
-
- items.append(selection_enum)
- items.append(selection_label)
-
- item_splitter = {'type': 'label', 'value': '---'}
-
- all_projects = session.query('Project').all()
- for project in all_projects:
- item_label = {
- 'type': 'label',
- 'value': '{} ({})'.format(
- project['full_name'], project['name']
- )
- }
- item = {
- 'name': project['id'],
- 'type': 'boolean',
- 'value': False
- }
- if len(items) > 0:
- items.append(item_splitter)
- items.append(item_label)
- items.append(item)
-
- if len(items) == 0:
- return {
- 'success': False,
- 'message': 'Didn\'t found any projects'
- }
- else:
- return {
- 'items': items,
- 'title': title
- }
-
- def launch(self, session, entities, event):
- if 'values' not in event['data']:
- return
-
- values = event['data']['values']
- process_type = values.pop('process_type')
-
- selection = True
- if process_type == 'except':
- selection = False
-
- interface_messages = {}
-
- projects_to_update = []
- for project_id, update_bool in values.items():
- if not update_bool and selection:
- continue
-
- if update_bool and not selection:
- continue
-
- project = session.query(
- 'Project where id is "{}"'.format(project_id)
- ).one()
- projects_to_update.append(project)
-
- if not projects_to_update:
- self.log.debug('Nothing to update')
- return {
- 'success': True,
- 'message': 'Nothing to update'
- }
-
-
- self.db_con.install()
-
- relevant_types = ["project", "asset", "version"]
-
- for ft_project in projects_to_update:
- self.log.debug(
- "Processing project \"{}\"".format(ft_project["full_name"])
- )
-
- self.db_con.Session["AVALON_PROJECT"] = ft_project["full_name"]
- project = self.db_con.find_one({'type': 'project'})
- if not project:
- key = "Projects not synchronized to db"
- if key not in interface_messages:
- interface_messages[key] = []
- interface_messages[key].append(ft_project["full_name"])
- continue
-
- # Get all entities in project collection from MongoDB
- _entities = self.db_con.find({})
- for _entity in _entities:
- ent_t = _entity.get("type", "*unknown type")
- name = _entity.get("name", "*unknown name")
-
- self.log.debug(
- "- {} ({})".format(name, ent_t)
- )
-
- # Skip types that do not store keys to change
- if ent_t.lower() not in relevant_types:
- self.log.debug("-- skipping - type is not relevant")
- continue
-
- # Get data which will change
- updating_data = {}
- source_data = _entity["data"]
-
- for key_from, key_to in self.keys_to_change.items():
- # continue if final key already exists
- if type(key_to) == list:
- for key in key_to:
- # continue if final key was set in update_data
- if key in updating_data:
- continue
-
- # continue if source key not exist or value is None
- value = source_data.get(key_from)
- if value is None:
- continue
-
- self.log.debug(
- "-- changing key {} to {}".format(
- key_from,
- key
- )
- )
-
- updating_data[key] = value
- else:
- if key_to in source_data:
- continue
-
- # continue if final key was set in update_data
- if key_to in updating_data:
- continue
-
- # continue if source key not exist or value is None
- value = source_data.get(key_from)
- if value is None:
- continue
-
- self.log.debug(
- "-- changing key {} to {}".format(key_from, key_to)
- )
- updating_data[key_to] = value
-
- # Pop out old keys from entity
- is_obsolete = False
- for key in self.keys_to_change:
- if key not in source_data:
- continue
- is_obsolete = True
- source_data.pop(key)
-
- # continue if there is nothing to change
- if not is_obsolete and not updating_data:
- self.log.debug("-- nothing to change")
- continue
-
- source_data.update(updating_data)
-
- self.db_con.update_many(
- {"_id": _entity["_id"]},
- {"$set": {"data": source_data}}
- )
-
- self.db_con.uninstall()
-
- if interface_messages:
- self.show_interface_from_dict(
- messages=interface_messages,
- title="Errors during remapping attributes",
- event=event
- )
-
- return True
-
- def show_interface_from_dict(self, event, messages, title=""):
- items = []
-
- for key, value in messages.items():
- if not value:
- continue
- subtitle = {'type': 'label', 'value': '# {}'.format(key)}
- items.append(subtitle)
- if isinstance(value, list):
- for item in value:
- message = {
- 'type': 'label', 'value': '
{}
'.format(item) - } - items.append(message) - else: - message = {'type': 'label', 'value': '{}
'.format(value)} - items.append(message) - - self.show_interface(items=items, title=title, event=event) - -def register(session, plugins_presets={}): - '''Register plugin. Called when used as an plugin.''' - - AttributesRemapper(session, plugins_presets).register() diff --git a/pype/modules/ftrack/actions/action_clean_hierarchical_attributes.py b/pype/modules/ftrack/actions/action_clean_hierarchical_attributes.py index 0319528319..86503ff5bc 100644 --- a/pype/modules/ftrack/actions/action_clean_hierarchical_attributes.py +++ b/pype/modules/ftrack/actions/action_clean_hierarchical_attributes.py @@ -1,7 +1,6 @@ -import os import collections import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.modules.ftrack.lib.avalon_sync import get_avalon_attr @@ -11,9 +10,7 @@ class CleanHierarchicalAttrsAction(BaseAction): variant = "- Clean hierarchical custom attributes" description = "Unset empty hierarchical attribute values." role_list = ["Pypeclub", "Administrator", "Project Manager"] - icon = "{}/ftrack/action_icons/PypeAdmin.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "PypeAdmin.svg") all_project_entities_query = ( "select id, name, parent_id, link" diff --git a/pype/modules/ftrack/actions/action_client_review_sort.py b/pype/modules/ftrack/actions/action_client_review_sort.py index 1909c31759..72387fe695 100644 --- a/pype/modules/ftrack/actions/action_client_review_sort.py +++ b/pype/modules/ftrack/actions/action_client_review_sort.py @@ -1,4 +1,4 @@ -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction try: from functools import cmp_to_key except Exception: diff --git a/pype/modules/ftrack/actions/action_component_open.py b/pype/modules/ftrack/actions/action_component_open.py index aebd543769..5fe8fe831b 100644 --- a/pype/modules/ftrack/actions/action_component_open.py +++ b/pype/modules/ftrack/actions/action_component_open.py @@ -1,10 +1,7 @@ import os import sys -import argparse -import logging import subprocess -import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class ComponentOpen(BaseAction): @@ -15,9 +12,7 @@ class ComponentOpen(BaseAction): # Action label label = 'Open File' # Action icon - icon = '{}/ftrack/action_icons/ComponentOpen.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "ComponentOpen.svg") def discover(self, session, entities, event): ''' Validation ''' @@ -69,42 +64,3 @@ def register(session, plugins_presets={}): '''Register action. Called when used as an event plugin.''' ComponentOpen(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_create_cust_attrs.py b/pype/modules/ftrack/actions/action_create_cust_attrs.py index 6e9827a231..9845cc8876 100644 --- a/pype/modules/ftrack/actions/action_create_cust_attrs.py +++ b/pype/modules/ftrack/actions/action_create_cust_attrs.py @@ -1,9 +1,8 @@ -import os import collections import json import arrow import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.modules.ftrack.lib.avalon_sync import CustAttrIdKey from pype.api import config @@ -114,9 +113,7 @@ class CustomAttributes(BaseAction): description = 'Creates Avalon/Mongo ID for double check' #: roles that are allowed to register this action role_list = ['Pypeclub', 'Administrator'] - icon = '{}/ftrack/action_icons/PypeAdmin.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "PypeAdmin.svg") required_keys = ['key', 'label', 'type'] type_posibilities = [ diff --git a/pype/modules/ftrack/actions/action_create_folders.py b/pype/modules/ftrack/actions/action_create_folders.py index 9146c54fad..e689e0260c 100644 --- a/pype/modules/ftrack/actions/action_create_folders.py +++ b/pype/modules/ftrack/actions/action_create_folders.py @@ -1,5 +1,5 @@ import os -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from avalon import lib as avalonlib from pype.api import config, Anatomy @@ -7,9 +7,7 @@ from pype.api import config, Anatomy class CreateFolders(BaseAction): identifier = "create.folders" label = "Create Folders" - icon = "{}/ftrack/action_icons/CreateFolders.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "CreateFolders.svg") def discover(self, session, entities, event): if len(entities) != 1: diff --git a/pype/modules/ftrack/actions/action_create_project_structure.py b/pype/modules/ftrack/actions/action_create_project_structure.py index 526cf172bf..22190c16db 100644 --- a/pype/modules/ftrack/actions/action_create_project_structure.py +++ b/pype/modules/ftrack/actions/action_create_project_structure.py @@ -1,7 +1,7 @@ import os import re -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.api import config, Anatomy @@ -52,9 +52,7 @@ class CreateProjectFolders(BaseAction): label = "Create Project Structure" description = "Creates folder structure" role_list = ["Pypeclub", "Administrator", "Project Manager"] - icon = "{}/ftrack/action_icons/CreateProjectFolders.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "CreateProjectFolders.svg") pattern_array = re.compile(r"\[.*\]") pattern_ftrack = re.compile(r".*\[[.]*ftrack[.]*") diff --git a/pype/modules/ftrack/actions/action_cust_attr_doctor.py b/pype/modules/ftrack/actions/action_cust_attr_doctor.py deleted file mode 100644 index e67ce4e5bf..0000000000 --- a/pype/modules/ftrack/actions/action_cust_attr_doctor.py +++ /dev/null @@ -1,336 +0,0 @@ -import os -import sys -import json -import argparse -import logging - -import ftrack_api -from pype.modules.ftrack import BaseAction - - -class CustomAttributeDoctor(BaseAction): - - ignore_me = True - #: Action identifier. - identifier = 'custom.attributes.doctor' - #: Action label. - label = "Pype Doctor" - variant = '- Custom Attributes Doctor' - #: Action description. - description = ( - 'Fix hierarchical custom attributes mainly handles, fstart' - ' and fend' - ) - - icon = '{}/ftrack/action_icons/PypeDoctor.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) - hierarchical_ca = ['handleStart', 'handleEnd', 'frameStart', 'frameEnd'] - hierarchical_alternatives = { - 'handleStart': 'handles', - 'handleEnd': 'handles', - "frameStart": "fstart", - "frameEnd": "fend" - } - - # Roles for new custom attributes - read_roles = ['ALL',] - write_roles = ['ALL',] - - data_ca = { - 'handleStart': { - 'label': 'Frame handles start', - 'type': 'number', - 'config': json.dumps({'isdecimal': False}) - }, - 'handleEnd': { - 'label': 'Frame handles end', - 'type': 'number', - 'config': json.dumps({'isdecimal': False}) - }, - 'frameStart': { - 'label': 'Frame start', - 'type': 'number', - 'config': json.dumps({'isdecimal': False}) - }, - 'frameEnd': { - 'label': 'Frame end', - 'type': 'number', - 'config': json.dumps({'isdecimal': False}) - } - } - - def discover(self, session, entities, event): - ''' Validation ''' - - return True - - def interface(self, session, entities, event): - if event['data'].get('values', {}): - return - - title = 'Select Project to fix Custom attributes' - - items = [] - item_splitter = {'type': 'label', 'value': '---'} - - all_projects = session.query('Project').all() - for project in all_projects: - item_label = { - 'type': 'label', - 'value': '{} ({})'.format( - project['full_name'], project['name'] - ) - } - item = { - 'name': project['id'], - 'type': 'boolean', - 'value': False - } - if len(items) > 0: - items.append(item_splitter) - items.append(item_label) - items.append(item) - - if len(items) == 0: - return { - 'success': False, - 'message': 'Didn\'t found any projects' - } - else: - return { - 'items': items, - 'title': title - } - - def launch(self, session, entities, event): - if 'values' not in event['data']: - return - - values = event['data']['values'] - projects_to_update = [] - for project_id, update_bool in values.items(): - if not update_bool: - continue - - project = session.query( - 'Project where id is "{}"'.format(project_id) - ).one() - projects_to_update.append(project) - - if not projects_to_update: - self.log.debug('Nothing to update') - return { - 'success': True, - 'message': 'Nothing to update' - } - - self.security_roles = {} - self.to_process = {} - # self.curent_default_values = {} - existing_attrs = session.query('CustomAttributeConfiguration').all() - self.prepare_custom_attributes(existing_attrs) - - self.projects_data = {} - for project in projects_to_update: - self.process_data(project) - - return True - - def process_data(self, entity): - cust_attrs = entity.get('custom_attributes') - if not cust_attrs: - return - for dst_key, src_key in self.to_process.items(): - if src_key in cust_attrs: - value = cust_attrs[src_key] - entity['custom_attributes'][dst_key] = value - self.session.commit() - - for child in entity.get('children', []): - self.process_data(child) - - def prepare_custom_attributes(self, existing_attrs): - to_process = {} - to_create = [] - all_keys = {attr['key']: attr for attr in existing_attrs} - for key in self.hierarchical_ca: - if key not in all_keys: - self.log.debug( - 'Custom attribute "{}" does not exist at all'.format(key) - ) - to_create.append(key) - if key in self.hierarchical_alternatives: - alt_key = self.hierarchical_alternatives[key] - if alt_key in all_keys: - self.log.debug(( - 'Custom attribute "{}" will use values from "{}"' - ).format(key, alt_key)) - - to_process[key] = alt_key - - obj = all_keys[alt_key] - # if alt_key not in self.curent_default_values: - # self.curent_default_values[alt_key] = obj['default'] - obj['default'] = None - self.session.commit() - - else: - obj = all_keys[key] - new_key = key + '_old' - - if obj['is_hierarchical']: - if new_key not in all_keys: - self.log.info(( - 'Custom attribute "{}" is already hierarchical' - ' and can\'t find old one' - ).format(key) - ) - continue - - to_process[key] = new_key - continue - - # default_value = obj['default'] - # if new_key not in self.curent_default_values: - # self.curent_default_values[new_key] = default_value - - obj['key'] = new_key - obj['label'] = obj['label'] + '(old)' - obj['default'] = None - - self.session.commit() - - to_create.append(key) - to_process[key] = new_key - - self.to_process = to_process - for key in to_create: - data = { - 'key': key, - 'entity_type': 'show', - 'is_hierarchical': True, - 'default': None - } - for _key, _value in self.data_ca.get(key, {}).items(): - if _key == 'type': - _value = self.session.query(( - 'CustomAttributeType where name is "{}"' - ).format(_value)).first() - - data[_key] = _value - - avalon_group = self.session.query( - 'CustomAttributeGroup where name is "avalon"' - ).first() - if avalon_group: - data['group'] = avalon_group - - read_roles = self.get_security_role(self.read_roles) - write_roles = self.get_security_role(self.write_roles) - data['read_security_roles'] = read_roles - data['write_security_roles'] = write_roles - - self.session.create('CustomAttributeConfiguration', data) - self.session.commit() - - # def return_back_defaults(self): - # existing_attrs = self.session.query( - # 'CustomAttributeConfiguration' - # ).all() - # - # for attr_key, default in self.curent_default_values.items(): - # for attr in existing_attrs: - # if attr['key'] != attr_key: - # continue - # attr['default'] = default - # self.session.commit() - # break - - def get_security_role(self, security_roles): - roles = [] - if len(security_roles) == 0 or security_roles[0] == 'ALL': - roles = self.get_role_ALL() - elif security_roles[0] == 'except': - excepts = security_roles[1:] - all = self.get_role_ALL() - for role in all: - if role['name'] not in excepts: - roles.append(role) - if role['name'] not in self.security_roles: - self.security_roles[role['name']] = role - else: - for role_name in security_roles: - if role_name in self.security_roles: - roles.append(self.security_roles[role_name]) - continue - - try: - query = 'SecurityRole where name is "{}"'.format(role_name) - role = self.session.query(query).one() - self.security_roles[role_name] = role - roles.append(role) - except Exception: - self.log.warning( - 'Securit role "{}" does not exist'.format(role_name) - ) - continue - - return roles - - def get_role_ALL(self): - role_name = 'ALL' - if role_name in self.security_roles: - all_roles = self.security_roles[role_name] - else: - all_roles = self.session.query('SecurityRole').all() - self.security_roles[role_name] = all_roles - for role in all_roles: - if role['name'] not in self.security_roles: - self.security_roles[role['name']] = role - return all_roles - - -def register(session, plugins_presets={}): - '''Register plugin. Called when used as an plugin.''' - - CustomAttributeDoctor(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_delete_asset.py b/pype/modules/ftrack/actions/action_delete_asset.py index d4f6eb6594..1074efee3b 100644 --- a/pype/modules/ftrack/actions/action_delete_asset.py +++ b/pype/modules/ftrack/actions/action_delete_asset.py @@ -1,11 +1,10 @@ -import os import collections import uuid from datetime import datetime from queue import Queue from bson.objectid import ObjectId -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.modules.ftrack.lib.io_nonsingleton import DbConnector @@ -18,9 +17,7 @@ class DeleteAssetSubset(BaseAction): label = "Delete Asset/Subsets" #: Action description. description = "Removes from Avalon with all childs and asset from Ftrack" - icon = "{}/ftrack/action_icons/DeleteAsset.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "DeleteAsset.svg") #: roles that are allowed to register this action role_list = ["Pypeclub", "Administrator", "Project Manager"] #: Db connection diff --git a/pype/modules/ftrack/actions/action_delete_old_versions.py b/pype/modules/ftrack/actions/action_delete_old_versions.py index 00432d5c3f..46652b136a 100644 --- a/pype/modules/ftrack/actions/action_delete_old_versions.py +++ b/pype/modules/ftrack/actions/action_delete_old_versions.py @@ -5,7 +5,7 @@ import uuid import clique from pymongo import UpdateOne -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.modules.ftrack.lib.io_nonsingleton import DbConnector from pype.api import Anatomy @@ -22,9 +22,7 @@ class DeleteOldVersions(BaseAction): " archived with only lates versions." ) role_list = ["Pypeclub", "Project Manager", "Administrator"] - icon = "{}/ftrack/action_icons/PypeAdmin.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "PypeAdmin.svg") dbcon = DbConnector() diff --git a/pype/modules/ftrack/actions/action_delivery.py b/pype/modules/ftrack/actions/action_delivery.py index 1dfd3dd5d5..a2048222e5 100644 --- a/pype/modules/ftrack/actions/action_delivery.py +++ b/pype/modules/ftrack/actions/action_delivery.py @@ -8,11 +8,11 @@ from bson.objectid import ObjectId from avalon import pipeline from avalon.vendor import filelink -from avalon.tools.libraryloader.io_nonsingleton import DbConnector from pype.api import Anatomy -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.modules.ftrack.lib.avalon_sync import CustAttrIdKey +from pype.modules.ftrack.lib.io_nonsingleton import DbConnector class Delivery(BaseAction): @@ -21,9 +21,7 @@ class Delivery(BaseAction): label = "Delivery" description = "Deliver data to client" role_list = ["Pypeclub", "Administrator", "Project manager"] - icon = "{}/ftrack/action_icons/Delivery.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "Delivery.svg") db_con = DbConnector() @@ -508,6 +506,7 @@ class Delivery(BaseAction): "message": "Delivery Finished" } + def register(session, plugins_presets={}): '''Register plugin. Called when used as an plugin.''' diff --git a/pype/modules/ftrack/actions/action_djvview.py b/pype/modules/ftrack/actions/action_djvview.py index 32c5824e0f..9708503ad1 100644 --- a/pype/modules/ftrack/actions/action_djvview.py +++ b/pype/modules/ftrack/actions/action_djvview.py @@ -1,11 +1,10 @@ import os import sys -import json import logging import subprocess from operator import itemgetter import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.api import Logger, config log = Logger().get_logger(__name__) @@ -16,9 +15,8 @@ class DJVViewAction(BaseAction): identifier = "djvview-launch-action" label = "DJV View" description = "DJV View Launcher" - icon = '{}/app_icons/djvView.png'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("app_icons", "djvView.png") + type = 'Application' def __init__(self, session, plugins_presets): diff --git a/pype/modules/ftrack/actions/action_job_killer.py b/pype/modules/ftrack/actions/action_job_killer.py index 064d7ed209..ff23da2a54 100644 --- a/pype/modules/ftrack/actions/action_job_killer.py +++ b/pype/modules/ftrack/actions/action_job_killer.py @@ -1,11 +1,5 @@ -import os -import sys -import argparse -import logging import json - -import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class JobKiller(BaseAction): @@ -20,9 +14,7 @@ class JobKiller(BaseAction): description = 'Killing selected running jobs' #: roles that are allowed to register this action role_list = ['Pypeclub', 'Administrator'] - icon = '{}/ftrack/action_icons/PypeAdmin.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "PypeAdmin.svg") def discover(self, session, entities, event): ''' Validation ''' @@ -124,43 +116,3 @@ def register(session, plugins_presets={}): '''Register plugin. Called when used as an plugin.''' JobKiller(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_multiple_notes.py b/pype/modules/ftrack/actions/action_multiple_notes.py index dcdb4c5dc9..c1a5cc6ce0 100644 --- a/pype/modules/ftrack/actions/action_multiple_notes.py +++ b/pype/modules/ftrack/actions/action_multiple_notes.py @@ -1,10 +1,4 @@ -import os -import sys -import argparse -import logging -import ftrack_api - -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class MultipleNotes(BaseAction): @@ -16,9 +10,7 @@ class MultipleNotes(BaseAction): label = 'Multiple Notes' #: Action description. description = 'Add same note to multiple Asset Versions' - icon = '{}/ftrack/action_icons/MultipleNotes.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "MultipleNotes.svg") def discover(self, session, entities, event): ''' Validation ''' @@ -116,42 +108,3 @@ def register(session, plugins_presets={}): '''Register plugin. Called when used as an plugin.''' MultipleNotes(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_prepare_project.py b/pype/modules/ftrack/actions/action_prepare_project.py index 31cc802109..f51a9eb9a6 100644 --- a/pype/modules/ftrack/actions/action_prepare_project.py +++ b/pype/modules/ftrack/actions/action_prepare_project.py @@ -1,7 +1,7 @@ import os import json -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.api import config, Anatomy, project_overrides_dir_path from pype.modules.ftrack.lib.avalon_sync import get_avalon_attr @@ -17,9 +17,7 @@ class PrepareProject(BaseAction): description = 'Set basic attributes on the project' #: roles that are allowed to register this action role_list = ["Pypeclub", "Administrator", "Project manager"] - icon = '{}/ftrack/action_icons/PrepareProject.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "PrepareProject.svg") # Key to store info about trigerring create folder structure create_project_structure_key = "create_folder_structure" diff --git a/pype/modules/ftrack/actions/action_rv.py b/pype/modules/ftrack/actions/action_rv.py index ce2371b5b8..528eeeee07 100644 --- a/pype/modules/ftrack/actions/action_rv.py +++ b/pype/modules/ftrack/actions/action_rv.py @@ -1,17 +1,13 @@ import os -import sys import subprocess -import logging import traceback import json -from pype.api import Logger, config -from pype.modules.ftrack import BaseAction +from pype.api import config +from pype.modules.ftrack.lib import BaseAction, statics_icon import ftrack_api from avalon import io, api -log = Logger().get_logger(__name__) - class RVAction(BaseAction): """ Launch RV action """ @@ -19,9 +15,8 @@ class RVAction(BaseAction): identifier = "rv.launch.action" label = "rv" description = "rv Launcher" - icon = '{}/ftrack/action_icons/RV.png'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "RV.png") + type = 'Application' def __init__(self, session, plugins_presets): @@ -144,7 +139,7 @@ class RVAction(BaseAction): try: items = self.get_interface_items(session, entities) except Exception: - log.error(traceback.format_exc()) + self.log.error(traceback.format_exc()) job["status"] = "failed" else: job["status"] = "done" @@ -238,7 +233,7 @@ class RVAction(BaseAction): try: paths = self.get_file_paths(session, event) except Exception: - log.error(traceback.format_exc()) + self.log.error(traceback.format_exc()) job["status"] = "failed" else: job["status"] = "done" @@ -254,7 +249,7 @@ class RVAction(BaseAction): args.extend(paths) - log.info("Running rv: {}".format(args)) + self.log.info("Running rv: {}".format(args)) subprocess.Popen(args) @@ -332,43 +327,3 @@ def register(session, plugins_presets={}): """Register hooks.""" RVAction(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - import argparse - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_seed.py b/pype/modules/ftrack/actions/action_seed.py index 72625c13e4..d6288a03aa 100644 --- a/pype/modules/ftrack/actions/action_seed.py +++ b/pype/modules/ftrack/actions/action_seed.py @@ -1,6 +1,6 @@ import os from operator import itemgetter -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class SeedDebugProject(BaseAction): @@ -16,9 +16,7 @@ class SeedDebugProject(BaseAction): priority = 100 #: roles that are allowed to register this action role_list = ["Pypeclub"] - icon = "{}/ftrack/action_icons/SeedProject.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) + icon = statics_icon("ftrack", "action_icons", "SeedProject.svg") # Asset names which will be created in `Assets` entity assets = [ @@ -429,6 +427,7 @@ class SeedDebugProject(BaseAction): self.session.commit() return True + def register(session, plugins_presets={}): '''Register plugin. Called when used as an plugin.''' diff --git a/pype/modules/ftrack/actions/action_start_timer.py b/pype/modules/ftrack/actions/action_start_timer.py index 3e5cf0d4c1..6e8fcb29e2 100644 --- a/pype/modules/ftrack/actions/action_start_timer.py +++ b/pype/modules/ftrack/actions/action_start_timer.py @@ -1,5 +1,4 @@ -import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction class StartTimer(BaseAction): diff --git a/pype/modules/ftrack/actions/action_store_thumbnails_to_avalon.py b/pype/modules/ftrack/actions/action_store_thumbnails_to_avalon.py index 180d6ae03c..b399dab7ce 100644 --- a/pype/modules/ftrack/actions/action_store_thumbnails_to_avalon.py +++ b/pype/modules/ftrack/actions/action_store_thumbnails_to_avalon.py @@ -4,7 +4,7 @@ import errno import json from bson.objectid import ObjectId -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.api import Anatomy from pype.modules.ftrack.lib.io_nonsingleton import DbConnector @@ -22,10 +22,7 @@ class StoreThumbnailsToAvalon(BaseAction): description = 'Test action' # roles that are allowed to register this action role_list = ["Pypeclub", "Administrator", "Project Manager"] - - icon = '{}/ftrack/action_icons/PypeAdmin.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "PypeAdmin.svg") thumbnail_key = "AVALON_THUMBNAIL_ROOT" db_con = DbConnector() diff --git a/pype/modules/ftrack/actions/action_sync_to_avalon.py b/pype/modules/ftrack/actions/action_sync_to_avalon.py index 8c6519e4dc..dfe1f2c464 100644 --- a/pype/modules/ftrack/actions/action_sync_to_avalon.py +++ b/pype/modules/ftrack/actions/action_sync_to_avalon.py @@ -1,8 +1,7 @@ -import os import time import traceback -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon from pype.modules.ftrack.lib.avalon_sync import SyncEntitiesFactory @@ -43,9 +42,7 @@ class SyncToAvalonLocal(BaseAction): priority = 200 #: roles that are allowed to register this action role_list = ["Pypeclub"] - icon = '{}/ftrack/action_icons/PypeAdmin.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "PypeAdmin.svg") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) diff --git a/pype/modules/ftrack/actions/action_test.py b/pype/modules/ftrack/actions/action_test.py index 784bf80944..e4936274b3 100644 --- a/pype/modules/ftrack/actions/action_test.py +++ b/pype/modules/ftrack/actions/action_test.py @@ -1,37 +1,19 @@ -import os -import sys -import argparse -import logging -import collections -import json -import re - -import ftrack_api -from avalon import io, inventory, schema -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class TestAction(BaseAction): - '''Edit meta data action.''' + """Action for testing purpose or as base for new actions.""" ignore_me = True - #: Action identifier. + identifier = 'test.action' - #: Action label. label = 'Test action' - #: Action description. description = 'Test action' - #: priority priority = 10000 - #: roles that are allowed to register this action role_list = ['Pypeclub'] - icon = '{}/ftrack/action_icons/TestAction.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "TestAction.svg") def discover(self, session, entities, event): - ''' Validation ''' - return True def launch(self, session, entities, event): @@ -41,45 +23,4 @@ class TestAction(BaseAction): def register(session, plugins_presets={}): - '''Register plugin. Called when used as an plugin.''' - TestAction(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_thumbnail_to_childern.py b/pype/modules/ftrack/actions/action_thumbnail_to_childern.py index e194134694..3c6af10b43 100644 --- a/pype/modules/ftrack/actions/action_thumbnail_to_childern.py +++ b/pype/modules/ftrack/actions/action_thumbnail_to_childern.py @@ -1,11 +1,5 @@ -import os -import sys -import argparse -import logging import json - -import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class ThumbToChildren(BaseAction): @@ -18,9 +12,7 @@ class ThumbToChildren(BaseAction): # Action variant variant = " to Children" # Action icon - icon = '{}/ftrack/action_icons/Thumbnail.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "Thumbnail.svg") def discover(self, session, entities, event): ''' Validation ''' @@ -71,42 +63,3 @@ def register(session, plugins_presets={}): '''Register action. Called when used as an event plugin.''' ThumbToChildren(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_thumbnail_to_parent.py b/pype/modules/ftrack/actions/action_thumbnail_to_parent.py index 86ada64e5a..8710fa9dcf 100644 --- a/pype/modules/ftrack/actions/action_thumbnail_to_parent.py +++ b/pype/modules/ftrack/actions/action_thumbnail_to_parent.py @@ -1,10 +1,5 @@ -import os -import sys -import argparse -import logging import json -import ftrack_api -from pype.modules.ftrack import BaseAction +from pype.modules.ftrack.lib import BaseAction, statics_icon class ThumbToParent(BaseAction): @@ -17,9 +12,7 @@ class ThumbToParent(BaseAction): # Action variant variant = " to Parent" # Action icon - icon = '{}/ftrack/action_icons/Thumbnail.svg'.format( - os.environ.get('PYPE_STATICS_SERVER', '') - ) + icon = statics_icon("ftrack", "action_icons", "Thumbnail.svg") def discover(self, session, entities, event): '''Return action config if triggered on asset versions.''' @@ -93,42 +86,3 @@ def register(session, plugins_presets={}): '''Register action. Called when used as an event plugin.''' ThumbToParent(session, plugins_presets).register() - - -def main(arguments=None): - '''Set up logging and register action.''' - if arguments is None: - arguments = [] - - parser = argparse.ArgumentParser() - # Allow setting of logging level from arguments. - loggingLevels = {} - for level in ( - logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, - logging.ERROR, logging.CRITICAL - ): - loggingLevels[logging.getLevelName(level).lower()] = level - - parser.add_argument( - '-v', '--verbosity', - help='Set the logging output verbosity.', - choices=loggingLevels.keys(), - default='info' - ) - namespace = parser.parse_args(arguments) - - # Set up basic logging - logging.basicConfig(level=loggingLevels[namespace.verbosity]) - - session = ftrack_api.Session() - register(session) - - # Wait for events - logging.info( - 'Registered actions and listening for events. Use Ctrl-C to abort.' - ) - session.event_hub.wait() - - -if __name__ == '__main__': - raise SystemExit(main(sys.argv[1:])) diff --git a/pype/modules/ftrack/actions/action_update_from_v2-2-0.py b/pype/modules/ftrack/actions/action_update_from_v2-2-0.py deleted file mode 100644 index 805072ce5d..0000000000 --- a/pype/modules/ftrack/actions/action_update_from_v2-2-0.py +++ /dev/null @@ -1,189 +0,0 @@ -import os - -from pype.modules.ftrack import BaseAction -from pype.modules.ftrack.lib.io_nonsingleton import DbConnector - - -class PypeUpdateFromV2_2_0(BaseAction): - """This action is to remove silo field from database and changes asset - schema to newer version - - WARNING: it is NOT for situations when you want to switch from avalon-core - to Pype's avalon-core!!! - - """ - #: Action identifier. - identifier = "silos.doctor" - #: Action label. - label = "Pype Update" - variant = "- v2.2.0 to v2.3.0 or higher" - #: Action description. - description = "Use when Pype was updated from v2.2.0 to v2.3.0 or higher" - - #: roles that are allowed to register this action - role_list = ["Pypeclub", "Administrator"] - icon = "{}/ftrack/action_icons/PypeUpdate.svg".format( - os.environ.get("PYPE_STATICS_SERVER", "") - ) - # connector to MongoDB (Avalon mongo) - db_con = DbConnector() - - def discover(self, session, entities, event): - """ Validation """ - if len(entities) != 1: - return False - - if entities[0].entity_type.lower() != "project": - return False - - return True - - def interface(self, session, entities, event): - if event['data'].get('values', {}): - return - - items = [] - item_splitter = {'type': 'label', 'value': '---'} - title = "Updated Pype from v 2.2.0 to v2.3.0 or higher" - - items.append({ - "type": "label", - "value": ( - "NOTE: This doctor action should be used ONLY when Pype" - " was updated from v2.2.0 to v2.3.0 or higher.