Merge pull request #188 from pypeclub/feature/96-BM_DaVinci_Resolve_host_R_D

Black Magic DaVinci Resolve Host integration
This commit is contained in:
Milan Kolar 2020-06-05 11:09:56 +02:00 committed by GitHub
commit 4fa2a665e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 1308 additions and 0 deletions

View file

@ -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

View file

@ -0,0 +1 @@

View file

@ -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 Resolves 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 Resolves 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

View file

@ -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"
]

View file

@ -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.")

78
pype/hosts/resolve/lib.py Normal file
View file

@ -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())]

154
pype/hosts/resolve/menu.py Normal file
View file

@ -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_())

View file

@ -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;
}

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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))

View file

@ -0,0 +1 @@

View file

@ -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

View file

@ -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))

View file

@ -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!")

136
pype/hosts/resolve/utils.py Normal file
View file

@ -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")

View file

@ -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("\\", "/")

View file

@ -0,0 +1,17 @@
import pyblish.api
from pype.hosts.resolve.utils import get_resolve_module
class CollectProject(pyblish.api.ContextPlugin):
"""Collect Project object"""
order = pyblish.api.CollectorOrder - 0.1
label = "Collect Project"
hosts = ["resolve"]
def process(self, context):
resolve = get_resolve_module()
PM = resolve.GetProjectManager()
P = PM.GetCurrentProject()
self.log.info(P.GetName())

BIN
res/app_icons/resolve.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 KiB