Merge remote-tracking branch 'origin/2.0/develop' into feature/PYPE-316-muster-render-support
25
README.md
|
|
@ -1,23 +1,20 @@
|
|||
The base studio *config* for [Avalon](https://getavalon.github.io/)
|
||||
he base studio _config_ for [Avalon](https://getavalon.github.io/)
|
||||
|
||||
Currently this config is dependent on our customised avalon instalation so it won't work with vanilla avalon core. We're working on open sourcing all of the necessary code though. You can still get inspiration or take our individual validators and scripts which should work just fine in other pipelines.
|
||||
|
||||
|
||||
_This configuration acts as a starting point for all pype club clients wth avalon deployment._
|
||||
|
||||
|
||||
|
||||
### Code convention
|
||||
|
||||
Below are some of the standard practices applied to this repositories.
|
||||
|
||||
- **Etiquette: PEP8**
|
||||
- All code is written in PEP8. It is recommended you use a linter as you work, flake8 and pylinter are both good options.
|
||||
- **Etiquette: Napoleon docstrings**
|
||||
- Any docstrings are made in Google Napoleon format. See [Napoleon](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) for details.
|
||||
- **Etiquette: Semantic Versioning**
|
||||
- This project follows [semantic versioning](http://semver.org).
|
||||
- **Etiquette: Underscore means private**
|
||||
- Anything prefixed with an underscore means that it is internal to wherever it is used. For example, a variable name is only ever used in the parent function or class. A module is not for use by the end-user. In contrast, anything without an underscore is public, but not necessarily part of the API. Members of the API resides in `api.py`.
|
||||
- **API: Idempotence**
|
||||
- A public function must be able to be called twice and produce the exact same result. This means no changing of state without restoring previous state when finishing. For example, if a function requires changing the current selection in Autodesk Maya, it must restore the previous selection prior to completing.
|
||||
- **Etiquette: PEP8**
|
||||
\- All code is written in PEP8. It is recommended you use a linter as you work, flake8 and pylinter are both good options.
|
||||
- **Etiquette: Napoleon docstrings**
|
||||
\- Any docstrings are made in Google Napoleon format. See [Napoleon](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) for details.
|
||||
- **Etiquette: Semantic Versioning**
|
||||
\- This project follows [semantic versioning](http://semver.org).
|
||||
- **Etiquette: Underscore means private**
|
||||
\- Anything prefixed with an underscore means that it is internal to wherever it is used. For example, a variable name is only ever used in the parent function or class. A module is not for use by the end-user. In contrast, anything without an underscore is public, but not necessarily part of the API. Members of the API resides in `api.py`.
|
||||
- **API: Idempotence**
|
||||
\- A public function must be able to be called twice and produce the exact same result. This means no changing of state without restoring previous state when finishing. For example, if a function requires changing the current selection in Autodesk Maya, it must restore the previous selection prior to completing.
|
||||
|
|
|
|||
|
|
@ -40,15 +40,7 @@ class AvalonApps:
|
|||
def show_launcher(self):
|
||||
# if app_launcher don't exist create it/otherwise only show main window
|
||||
if self.app_launcher is None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--demo", action="store_true")
|
||||
parser.add_argument(
|
||||
"--root", default=os.environ["AVALON_PROJECTS"]
|
||||
)
|
||||
kwargs = parser.parse_args()
|
||||
|
||||
root = kwargs.root
|
||||
root = os.path.realpath(root)
|
||||
root = os.path.realpath(os.environ["AVALON_PROJECTS"])
|
||||
io.install()
|
||||
APP_PATH = launcher_lib.resource("qml", "main.qml")
|
||||
self.app_launcher = launcher_widget.Launcher(root, APP_PATH)
|
||||
|
|
|
|||
|
|
@ -193,7 +193,7 @@ class AppAction(BaseHandler):
|
|||
application = avalonlib.get_application(os.environ["AVALON_APP_NAME"])
|
||||
|
||||
data = {
|
||||
"root": os.environ.get("PYPE_STUDIO_PROJECTS_PATH"),
|
||||
"root": os.environ.get("PYPE_STUDIO_PROJECTS_MOUNT"),
|
||||
"project": {
|
||||
"name": entity['project']['full_name'],
|
||||
"code": entity['project']['name']
|
||||
|
|
|
|||
117
pype/nukestudio/__init__.py
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import os
|
||||
import sys
|
||||
from avalon import api as avalon
|
||||
from pyblish import api as pyblish
|
||||
|
||||
from .. import api
|
||||
|
||||
from .menu import install as menu_install
|
||||
|
||||
from .lib import (
|
||||
show,
|
||||
setup,
|
||||
add_to_filemenu
|
||||
)
|
||||
|
||||
|
||||
from pypeapp import Logger
|
||||
|
||||
|
||||
log = Logger().get_logger(__name__, "nukestudio")
|
||||
|
||||
AVALON_CONFIG = os.getenv("AVALON_CONFIG", "pype")
|
||||
|
||||
PARENT_DIR = os.path.dirname(__file__)
|
||||
PACKAGE_DIR = os.path.dirname(PARENT_DIR)
|
||||
PLUGINS_DIR = os.path.join(PACKAGE_DIR, "plugins")
|
||||
|
||||
PUBLISH_PATH = os.path.join(PLUGINS_DIR, "nukestudio", "publish")
|
||||
LOAD_PATH = os.path.join(PLUGINS_DIR, "nukestudio", "load")
|
||||
CREATE_PATH = os.path.join(PLUGINS_DIR, "nukestudio", "create")
|
||||
INVENTORY_PATH = os.path.join(PLUGINS_DIR, "nukestudio", "inventory")
|
||||
|
||||
|
||||
if os.getenv("PYBLISH_GUI", None):
|
||||
pyblish.register_gui(os.getenv("PYBLISH_GUI", None))
|
||||
|
||||
|
||||
def reload_config():
|
||||
"""Attempt to reload pipeline at run-time.
|
||||
|
||||
CAUTION: This is primarily for development and debugging purposes.
|
||||
|
||||
"""
|
||||
|
||||
import importlib
|
||||
|
||||
for module in (
|
||||
"pypeapp",
|
||||
"{}.api".format(AVALON_CONFIG),
|
||||
"{}.templates".format(AVALON_CONFIG),
|
||||
"{}.nukestudio.inventory".format(AVALON_CONFIG),
|
||||
"{}.nukestudio.lib".format(AVALON_CONFIG),
|
||||
"{}.nukestudio.menu".format(AVALON_CONFIG),
|
||||
):
|
||||
log.info("Reloading module: {}...".format(module))
|
||||
try:
|
||||
module = importlib.import_module(module)
|
||||
reload(module)
|
||||
except Exception as e:
|
||||
log.warning("Cannot reload module: {}".format(e))
|
||||
importlib.reload(module)
|
||||
|
||||
|
||||
def install(config):
|
||||
|
||||
# api.set_avalon_workdir()
|
||||
# reload_config()
|
||||
|
||||
# import sys
|
||||
# for path in sys.path:
|
||||
# if path.startswith("C:\\Users\\Public"):
|
||||
# sys.path.remove(path)
|
||||
|
||||
log.info("Registering NukeStudio plug-ins..")
|
||||
pyblish.register_host("nukestudio")
|
||||
pyblish.register_plugin_path(PUBLISH_PATH)
|
||||
avalon.register_plugin_path(avalon.Loader, LOAD_PATH)
|
||||
avalon.register_plugin_path(avalon.Creator, CREATE_PATH)
|
||||
avalon.register_plugin_path(avalon.InventoryAction, INVENTORY_PATH)
|
||||
|
||||
# Disable all families except for the ones we explicitly want to see
|
||||
family_states = [
|
||||
"write",
|
||||
"review"
|
||||
]
|
||||
|
||||
avalon.data["familiesStateDefault"] = False
|
||||
avalon.data["familiesStateToggled"] = family_states
|
||||
|
||||
menu_install()
|
||||
|
||||
# load data from templates
|
||||
api.load_data_from_templates()
|
||||
|
||||
|
||||
def uninstall():
|
||||
log.info("Deregistering NukeStudio plug-ins..")
|
||||
pyblish.deregister_host("nukestudio")
|
||||
pyblish.deregister_plugin_path(PUBLISH_PATH)
|
||||
avalon.deregister_plugin_path(avalon.Loader, LOAD_PATH)
|
||||
avalon.deregister_plugin_path(avalon.Creator, CREATE_PATH)
|
||||
|
||||
# reset data from templates
|
||||
api.reset_data_from_templates()
|
||||
|
||||
|
||||
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`
|
||||
"""
|
||||
return
|
||||
205
pype/nukestudio/lib.py
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
# Standard library
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Pyblish libraries
|
||||
import pyblish.api
|
||||
|
||||
# Host libraries
|
||||
import hiero
|
||||
|
||||
from PySide2 import (QtWidgets, QtGui)
|
||||
|
||||
|
||||
cached_process = None
|
||||
|
||||
|
||||
self = sys.modules[__name__]
|
||||
self._has_been_setup = False
|
||||
self._has_menu = False
|
||||
self._registered_gui = None
|
||||
|
||||
|
||||
def setup(console=False, port=None, menu=True):
|
||||
"""Setup integration
|
||||
|
||||
Registers Pyblish for Hiero plug-ins and appends an item to the File-menu
|
||||
|
||||
Arguments:
|
||||
console (bool): Display console with GUI
|
||||
port (int, optional): Port from which to start looking for an
|
||||
available port to connect with Pyblish QML, default
|
||||
provided by Pyblish Integration.
|
||||
menu (bool, optional): Display file menu in Hiero.
|
||||
"""
|
||||
|
||||
if self._has_been_setup:
|
||||
teardown()
|
||||
|
||||
add_submission()
|
||||
|
||||
if menu:
|
||||
add_to_filemenu()
|
||||
self._has_menu = True
|
||||
|
||||
self._has_been_setup = True
|
||||
print("pyblish: Loaded successfully.")
|
||||
|
||||
|
||||
def show():
|
||||
"""Try showing the most desirable GUI
|
||||
This function cycles through the currently registered
|
||||
graphical user interfaces, if any, and presents it to
|
||||
the user.
|
||||
"""
|
||||
|
||||
return (_discover_gui() or _show_no_gui)()
|
||||
|
||||
|
||||
def _discover_gui():
|
||||
"""Return the most desirable of the currently registered GUIs"""
|
||||
|
||||
# Prefer last registered
|
||||
guis = reversed(pyblish.api.registered_guis())
|
||||
|
||||
for gui in list(guis) + ["pyblish_lite"]:
|
||||
try:
|
||||
gui = __import__(gui).show
|
||||
except (ImportError, AttributeError):
|
||||
continue
|
||||
else:
|
||||
return gui
|
||||
|
||||
|
||||
def teardown():
|
||||
"""Remove integration"""
|
||||
if not self._has_been_setup:
|
||||
return
|
||||
|
||||
if self._has_menu:
|
||||
remove_from_filemenu()
|
||||
self._has_menu = False
|
||||
|
||||
self._has_been_setup = False
|
||||
print("pyblish: Integration torn down successfully")
|
||||
|
||||
|
||||
def remove_from_filemenu():
|
||||
raise NotImplementedError("Implement me please.")
|
||||
|
||||
|
||||
def add_to_filemenu():
|
||||
PublishAction()
|
||||
|
||||
|
||||
class PyblishSubmission(hiero.exporters.FnSubmission.Submission):
|
||||
|
||||
def __init__(self):
|
||||
hiero.exporters.FnSubmission.Submission.__init__(self)
|
||||
|
||||
def addToQueue(self):
|
||||
# Add submission to Hiero module for retrieval in plugins.
|
||||
hiero.submission = self
|
||||
show()
|
||||
|
||||
|
||||
def add_submission():
|
||||
registry = hiero.core.taskRegistry
|
||||
registry.addSubmission("Pyblish", PyblishSubmission)
|
||||
|
||||
|
||||
class PublishAction(QtWidgets.QAction):
|
||||
def __init__(self):
|
||||
QtWidgets.QAction.__init__(self, "Publish", None)
|
||||
self.triggered.connect(self.publish)
|
||||
|
||||
for interest in ["kShowContextMenu/kTimeline",
|
||||
"kShowContextMenukBin",
|
||||
"kShowContextMenu/kSpreadsheet"]:
|
||||
hiero.core.events.registerInterest(interest, self.eventHandler)
|
||||
|
||||
self.setShortcut("Ctrl+Alt+P")
|
||||
|
||||
def publish(self):
|
||||
# Removing "submission" attribute from hiero module, to prevent tasks
|
||||
# from getting picked up when not using the "Export" dialog.
|
||||
if hasattr(hiero, "submission"):
|
||||
del hiero.submission
|
||||
show()
|
||||
|
||||
def eventHandler(self, event):
|
||||
# Add the Menu to the right-click menu
|
||||
event.menu.addAction(self)
|
||||
|
||||
|
||||
def _show_no_gui():
|
||||
"""Popup with information about how to register a new GUI
|
||||
In the event of no GUI being registered or available,
|
||||
this information dialog will appear to guide the user
|
||||
through how to get set up with one.
|
||||
"""
|
||||
|
||||
messagebox = QtWidgets.QMessageBox()
|
||||
messagebox.setIcon(messagebox.Warning)
|
||||
messagebox.setWindowIcon(QtGui.QIcon(os.path.join(
|
||||
os.path.dirname(pyblish.__file__),
|
||||
"icons",
|
||||
"logo-32x32.svg"))
|
||||
)
|
||||
|
||||
spacer = QtWidgets.QWidget()
|
||||
spacer.setMinimumSize(400, 0)
|
||||
spacer.setSizePolicy(QtWidgets.QSizePolicy.Minimum,
|
||||
QtWidgets.QSizePolicy.Expanding)
|
||||
|
||||
layout = messagebox.layout()
|
||||
layout.addWidget(spacer, layout.rowCount(), 0, 1, layout.columnCount())
|
||||
|
||||
messagebox.setWindowTitle("Uh oh")
|
||||
messagebox.setText("No registered GUI found.")
|
||||
|
||||
if not pyblish.api.registered_guis():
|
||||
messagebox.setInformativeText(
|
||||
"In order to show you a GUI, one must first be registered. "
|
||||
"Press \"Show details...\" below for information on how to "
|
||||
"do that.")
|
||||
|
||||
messagebox.setDetailedText(
|
||||
"Pyblish supports one or more graphical user interfaces "
|
||||
"to be registered at once, the next acting as a fallback to "
|
||||
"the previous."
|
||||
"\n"
|
||||
"\n"
|
||||
"For example, to use Pyblish Lite, first install it:"
|
||||
"\n"
|
||||
"\n"
|
||||
"$ pip install pyblish-lite"
|
||||
"\n"
|
||||
"\n"
|
||||
"Then register it, like so:"
|
||||
"\n"
|
||||
"\n"
|
||||
">>> import pyblish.api\n"
|
||||
">>> pyblish.api.register_gui(\"pyblish_lite\")"
|
||||
"\n"
|
||||
"\n"
|
||||
"The next time you try running this, Lite will appear."
|
||||
"\n"
|
||||
"See http://api.pyblish.com/register_gui.html for "
|
||||
"more information.")
|
||||
|
||||
else:
|
||||
messagebox.setInformativeText(
|
||||
"None of the registered graphical user interfaces "
|
||||
"could be found."
|
||||
"\n"
|
||||
"\n"
|
||||
"Press \"Show details\" for more information.")
|
||||
|
||||
messagebox.setDetailedText(
|
||||
"These interfaces are currently registered."
|
||||
"\n"
|
||||
"%s" % "\n".join(pyblish.api.registered_guis()))
|
||||
|
||||
messagebox.setStandardButtons(messagebox.Ok)
|
||||
messagebox.exec_()
|
||||
92
pype/nukestudio/menu.py
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import os
|
||||
from avalon.api import Session
|
||||
from pprint import pprint
|
||||
|
||||
import hiero.core
|
||||
|
||||
try:
|
||||
from PySide.QtGui import *
|
||||
except Exception:
|
||||
from PySide2.QtGui import *
|
||||
from PySide2.QtWidgets import *
|
||||
|
||||
from hiero.ui import findMenuAction
|
||||
|
||||
|
||||
#
|
||||
def install():
|
||||
# here is the best place to add menu
|
||||
from avalon.tools import (
|
||||
creator,
|
||||
publish,
|
||||
workfiles,
|
||||
cbloader,
|
||||
cbsceneinventory,
|
||||
contextmanager,
|
||||
libraryloader
|
||||
)
|
||||
|
||||
menu_name = os.environ['PYPE_STUDIO_NAME']
|
||||
# Grab Hiero's MenuBar
|
||||
M = hiero.ui.menuBar()
|
||||
|
||||
# Add a Menu to the MenuBar
|
||||
file_action = None
|
||||
|
||||
try:
|
||||
check_made_menu = findMenuAction(menu_name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not check_made_menu:
|
||||
menu = M.addMenu(menu_name)
|
||||
else:
|
||||
menu = check_made_menu.menu()
|
||||
|
||||
actions = [{
|
||||
'action': QAction('Set Context', None),
|
||||
'function': contextmanager.show,
|
||||
'icon': QIcon('icons:Position.png')
|
||||
},
|
||||
{
|
||||
'action': QAction('Create...', None),
|
||||
'function': creator.show,
|
||||
'icon': QIcon('icons:ColorAdd.png')
|
||||
},
|
||||
{
|
||||
'action': QAction('Load...', None),
|
||||
'function': cbloader.show,
|
||||
'icon': QIcon('icons:CopyRectangle.png')
|
||||
},
|
||||
{
|
||||
'action': QAction('Publish...', None),
|
||||
'function': publish.show,
|
||||
'icon': QIcon('icons:Output.png')
|
||||
},
|
||||
{
|
||||
'action': QAction('Manage...', None),
|
||||
'function': cbsceneinventory.show,
|
||||
'icon': QIcon('icons:ModifyMetaData.png')
|
||||
},
|
||||
{
|
||||
'action': QAction('Library...', None),
|
||||
'function': libraryloader.show,
|
||||
'icon': QIcon('icons:ColorAdd.png')
|
||||
}]
|
||||
|
||||
|
||||
# Create menu items
|
||||
for a in actions:
|
||||
pprint(a)
|
||||
# create action
|
||||
for k in a.keys():
|
||||
if 'action' in k:
|
||||
action = a[k]
|
||||
elif 'function' in k:
|
||||
action.triggered.connect(a[k])
|
||||
elif 'icon' in k:
|
||||
action.setIcon(a[k])
|
||||
|
||||
# add action to menu
|
||||
menu.addAction(action)
|
||||
hiero.ui.registerAction(action)
|
||||
14
pype/plugins/global/publish/collect_presets.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
from pyblish import api
|
||||
from pypeapp import config
|
||||
|
||||
|
||||
class CollectPresets(api.ContextPlugin):
|
||||
"""Collect Presets."""
|
||||
|
||||
order = api.CollectorOrder
|
||||
label = "Collect Presets"
|
||||
|
||||
def process(self, context):
|
||||
context.data["presets"] = config.get_presets()
|
||||
self.log.info(context.data["presets"])
|
||||
return
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import os
|
||||
import pyblish.api
|
||||
import os
|
||||
import pype.api as pype
|
||||
|
||||
|
||||
class CollectSceneVersion(pyblish.api.ContextPlugin):
|
||||
"""Finds version in the filename or passes the one found in the context
|
||||
Arguments:
|
||||
|
|
@ -16,8 +16,10 @@ class CollectSceneVersion(pyblish.api.ContextPlugin):
|
|||
|
||||
filename = os.path.basename(context.data.get('currentFile'))
|
||||
|
||||
rootVersion = pype.get_version_from_path(filename)
|
||||
if '<shell>' in filename:
|
||||
return
|
||||
|
||||
rootVersion = pype.get_version_from_path(filename)
|
||||
context.data['version'] = rootVersion
|
||||
|
||||
self.log.info('Scene Version: %s' % context.data('version'))
|
||||
|
|
|
|||
|
|
@ -21,11 +21,14 @@ class CollectMayaRenderlayers(pyblish.api.ContextPlugin):
|
|||
# Get render globals node
|
||||
try:
|
||||
render_globals = cmds.ls("renderglobalsMain")[0]
|
||||
for instance in context:
|
||||
self.log.debug(instance.name)
|
||||
if instance.data['family'] == 'workfile':
|
||||
instance.data['publish'] = True
|
||||
except IndexError:
|
||||
self.log.info("Skipping renderlayer collection, no "
|
||||
"renderGlobalsDefault found..")
|
||||
return
|
||||
|
||||
# Get all valid renderlayers
|
||||
# This is how Maya populates the renderlayer display
|
||||
rlm_attribute = "renderLayerManager.renderLayerId"
|
||||
|
|
@ -51,7 +54,7 @@ class CollectMayaRenderlayers(pyblish.api.ContextPlugin):
|
|||
continue
|
||||
|
||||
if layer.endswith("defaultRenderLayer"):
|
||||
layername = "masterLayer"
|
||||
continue
|
||||
else:
|
||||
# Remove Maya render setup prefix `rs_`
|
||||
layername = layer.split("rs_", 1)[-1]
|
||||
|
|
|
|||
|
|
@ -280,7 +280,7 @@ class MayaSubmitDeadline(pyblish.api.InstancePlugin):
|
|||
clean_path = clean_path.replace('python2', 'python3')
|
||||
clean_path = clean_path.replace(
|
||||
os.path.normpath(environment['PYPE_STUDIO_CORE_MOUNT']),
|
||||
os.path.normpath(environment['PYPE_STUDIO_CORE']))
|
||||
os.path.normpath(environment['PYPE_STUDIO_CORE_PATH']))
|
||||
clean_environment[key] = clean_path
|
||||
|
||||
environment = clean_environment
|
||||
|
|
|
|||
24
pype/plugins/nuke/_publish_unused/test_instances.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class IncrementTestPlugin(pyblish.api.ContextPlugin):
|
||||
"""Increment current script version."""
|
||||
|
||||
order = pyblish.api.CollectorOrder + 0.5
|
||||
label = "Test Plugin"
|
||||
hosts = ['nuke']
|
||||
|
||||
def process(self, context):
|
||||
instances = context[:]
|
||||
|
||||
prerender_check = list()
|
||||
families_check = list()
|
||||
for instance in instances:
|
||||
if ("prerender" in str(instance)):
|
||||
prerender_check.append(instance)
|
||||
if instance.data.get("families", None):
|
||||
families_check.append(True)
|
||||
|
||||
if len(prerender_check) != len(families_check):
|
||||
self.log.info(prerender_check)
|
||||
self.log.info(families_check)
|
||||
|
|
@ -17,6 +17,10 @@ class CollectNukeInstances(pyblish.api.ContextPlugin):
|
|||
def process(self, context):
|
||||
asset_data = io.find_one({"type": "asset",
|
||||
"name": api.Session["AVALON_ASSET"]})
|
||||
|
||||
# add handles into context
|
||||
context.data['handles'] = int(asset_data["data"].get("handles", 0))
|
||||
|
||||
self.log.debug("asset_data: {}".format(asset_data["data"]))
|
||||
instances = []
|
||||
# creating instances per write node
|
||||
|
|
@ -51,7 +55,6 @@ class CollectNukeInstances(pyblish.api.ContextPlugin):
|
|||
"family": avalon_knob_data["family"],
|
||||
"avalonKnob": avalon_knob_data,
|
||||
"publish": node.knob('publish').value(),
|
||||
"handles": int(asset_data["data"].get("handles", 0)),
|
||||
"step": 1,
|
||||
"fps": int(nuke.root()['fps'].value())
|
||||
|
||||
|
|
|
|||
|
|
@ -35,10 +35,12 @@ class CollectNukeWrites(pyblish.api.ContextPlugin):
|
|||
output_type = "mov"
|
||||
|
||||
# Get frame range
|
||||
handles = instance.context.data.get('handles', 0)
|
||||
first_frame = int(nuke.root()["first_frame"].getValue())
|
||||
last_frame = int(nuke.root()["last_frame"].getValue())
|
||||
|
||||
if node["use_limit"].getValue():
|
||||
handles = 0
|
||||
first_frame = int(node["first"].getValue())
|
||||
last_frame = int(node["last"].getValue())
|
||||
|
||||
|
|
@ -76,6 +78,7 @@ class CollectNukeWrites(pyblish.api.ContextPlugin):
|
|||
"outputDir": output_dir,
|
||||
"ext": ext,
|
||||
"label": label,
|
||||
"handles": handles,
|
||||
"startFrame": first_frame,
|
||||
"endFrame": last_frame,
|
||||
"outputType": output_type,
|
||||
|
|
|
|||
|
|
@ -16,7 +16,19 @@ class IncrementScriptVersion(pyblish.api.ContextPlugin):
|
|||
assert all(result["success"] for result in context.data["results"]), (
|
||||
"Atomicity not held, aborting.")
|
||||
|
||||
from pype.lib import version_up
|
||||
path = context.data["currentFile"]
|
||||
nuke.scriptSaveAs(version_up(path))
|
||||
self.log.info('Incrementing script version')
|
||||
instances = context[:]
|
||||
|
||||
prerender_check = list()
|
||||
families_check = list()
|
||||
for instance in instances:
|
||||
if ("prerender" in str(instance)) and instance.data.get("families", None):
|
||||
prerender_check.append(instance)
|
||||
if instance.data.get("families", None):
|
||||
families_check.append(True)
|
||||
|
||||
|
||||
if len(prerender_check) != len(families_check):
|
||||
from pype.lib import version_up
|
||||
path = context.data["currentFile"]
|
||||
nuke.scriptSaveAs(version_up(path))
|
||||
self.log.info('Incrementing script version')
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ class ValidateScript(pyblish.api.InstancePlugin):
|
|||
]
|
||||
|
||||
# Value of these attributes can be found on parents
|
||||
hierarchical_attributes = ["fps", "resolution_width", "resolution_height", "pixel_aspect"]
|
||||
hierarchical_attributes = ["fps", "resolution_width", "resolution_height", "pixel_aspect", "handles"]
|
||||
|
||||
missing_attributes = []
|
||||
asset_attributes = {}
|
||||
|
|
|
|||
191
pype/plugins/nukestudio/_unused/collect.py
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
from pyblish import api
|
||||
|
||||
class CollectFramerate(api.ContextPlugin):
|
||||
"""Collect framerate from selected sequence."""
|
||||
|
||||
order = api.CollectorOrder
|
||||
label = "Collect Framerate"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, context):
|
||||
for item in context.data.get("selection", []):
|
||||
context.data["framerate"] = item.sequence().framerate().toFloat()
|
||||
return
|
||||
|
||||
|
||||
class CollectTrackItems(api.ContextPlugin):
|
||||
"""Collect all tasks from submission."""
|
||||
|
||||
order = api.CollectorOrder
|
||||
label = "Collect Track Items"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, context):
|
||||
import os
|
||||
|
||||
submission = context.data.get("submission", None)
|
||||
data = {}
|
||||
|
||||
# Set handles
|
||||
handles = 0
|
||||
if submission:
|
||||
for task in submission.getLeafTasks():
|
||||
|
||||
if task._cutHandles:
|
||||
handles = task._cutHandles
|
||||
self.log.info("__ handles: '{}'".format(handles))
|
||||
|
||||
# Skip audio track items
|
||||
media_type = "core.Hiero.Python.TrackItem.MediaType.kAudio"
|
||||
if str(task._item.mediaType()) == media_type:
|
||||
continue
|
||||
|
||||
item = task._item
|
||||
if item.name() not in data:
|
||||
data[item.name()] = {"item": item, "tasks": [task]}
|
||||
else:
|
||||
data[item.name()]["tasks"].append(task)
|
||||
|
||||
data[item.name()]["startFrame"] = task.outputRange()[0]
|
||||
data[item.name()]["endFrame"] = task.outputRange()[1]
|
||||
else:
|
||||
for item in context.data.get("selection", []):
|
||||
# Skip audio track items
|
||||
# Try/Except is to handle items types, like EffectTrackItem
|
||||
try:
|
||||
media_type = "core.Hiero.Python.TrackItem.MediaType.kVideo"
|
||||
if str(item.mediaType()) != media_type:
|
||||
continue
|
||||
except:
|
||||
continue
|
||||
|
||||
data[item.name()] = {
|
||||
"item": item,
|
||||
"tasks": [],
|
||||
"startFrame": item.timelineIn(),
|
||||
"endFrame": item.timelineOut()
|
||||
}
|
||||
|
||||
for key, value in data.items():
|
||||
|
||||
context.create_instance(
|
||||
name=key,
|
||||
subset="trackItem",
|
||||
asset=value["item"].name(),
|
||||
item=value["item"],
|
||||
family="trackItem",
|
||||
tasks=value["tasks"],
|
||||
startFrame=value["startFrame"] + handles,
|
||||
endFrame=value["endFrame"] - handles,
|
||||
handles=handles
|
||||
)
|
||||
context.create_instance(
|
||||
name=key + "_review",
|
||||
subset="reviewItem",
|
||||
asset=value["item"].name(),
|
||||
item=value["item"],
|
||||
family="trackItem_review",
|
||||
families=["output"],
|
||||
handles=handles,
|
||||
output_path=os.path.abspath(
|
||||
os.path.join(
|
||||
context.data["activeProject"].path(),
|
||||
"..",
|
||||
"workspace",
|
||||
key + ".mov"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class CollectTasks(api.ContextPlugin):
|
||||
"""Collect all tasks from submission."""
|
||||
|
||||
order = api.CollectorOrder + 0.01
|
||||
label = "Collect Tasks"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, context):
|
||||
import os
|
||||
import re
|
||||
|
||||
import hiero.exporters as he
|
||||
import clique
|
||||
|
||||
for parent in context:
|
||||
if "trackItem" != parent.data["family"]:
|
||||
continue
|
||||
|
||||
for task in parent.data["tasks"]:
|
||||
asset_type = None
|
||||
|
||||
hiero_cls = he.FnSymLinkExporter.SymLinkExporter
|
||||
if isinstance(task, hiero_cls):
|
||||
asset_type = "img"
|
||||
movie_formats = [".mov", ".R3D"]
|
||||
ext = os.path.splitext(task.resolvedExportPath())[1]
|
||||
if ext in movie_formats:
|
||||
asset_type = "mov"
|
||||
|
||||
hiero_cls = he.FnTranscodeExporter.TranscodeExporter
|
||||
if isinstance(task, hiero_cls):
|
||||
asset_type = "img"
|
||||
if task.resolvedExportPath().endswith(".mov"):
|
||||
asset_type = "mov"
|
||||
|
||||
hiero_cls = he.FnNukeShotExporter.NukeShotExporter
|
||||
if isinstance(task, hiero_cls):
|
||||
asset_type = "scene"
|
||||
|
||||
hiero_cls = he.FnAudioExportTask.AudioExportTask
|
||||
if isinstance(task, hiero_cls):
|
||||
asset_type = "audio"
|
||||
|
||||
# Skip all non supported export types
|
||||
if not asset_type:
|
||||
continue
|
||||
|
||||
resolved_path = task.resolvedExportPath()
|
||||
|
||||
# Formatting the basename to not include frame padding or
|
||||
# extension.
|
||||
name = os.path.splitext(os.path.basename(resolved_path))[0]
|
||||
name = name.replace(".", "")
|
||||
name = name.replace("#", "")
|
||||
name = re.sub(r"%.*d", "", name)
|
||||
instance = context.create_instance(name=name, parent=parent)
|
||||
|
||||
instance.data["task"] = task
|
||||
instance.data["item"] = parent.data["item"]
|
||||
|
||||
instance.data["family"] = "trackItem.task"
|
||||
instance.data["families"] = [asset_type, "local", "task"]
|
||||
|
||||
label = "{1}/{0} - {2} - local".format(
|
||||
name, parent, asset_type
|
||||
)
|
||||
instance.data["label"] = label
|
||||
|
||||
instance.data["handles"] = parent.data["handles"]
|
||||
|
||||
# Add collection or output
|
||||
if asset_type == "img":
|
||||
collection = None
|
||||
|
||||
if "#" in resolved_path:
|
||||
head = resolved_path.split("#")[0]
|
||||
padding = resolved_path.count("#")
|
||||
tail = resolved_path.split("#")[-1]
|
||||
|
||||
collection = clique.Collection(
|
||||
head=head, padding=padding, tail=tail
|
||||
)
|
||||
|
||||
if "%" in resolved_path:
|
||||
collection = clique.parse(
|
||||
resolved_path, pattern="{head}{padding}{tail}"
|
||||
)
|
||||
|
||||
instance.data["collection"] = collection
|
||||
else:
|
||||
instance.data["output_path"] = resolved_path
|
||||
14
pype/plugins/nukestudio/_unused/collect_submission.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class CollectSubmission(pyblish.api.ContextPlugin):
|
||||
"""Collect submisson children."""
|
||||
|
||||
order = pyblish.api.CollectorOrder - 0.1
|
||||
|
||||
def process(self, context):
|
||||
import hiero
|
||||
|
||||
if hasattr(hiero, "submission"):
|
||||
context.data["submission"] = hiero.submission
|
||||
self.log.debug("__ submission: {}".format(context.data["submission"]))
|
||||
124
pype/plugins/nukestudio/_unused/extract_tasks.py
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class ExtractTasks(api.InstancePlugin):
|
||||
"""Extract tasks."""
|
||||
|
||||
order = api.ExtractorOrder
|
||||
label = "Tasks"
|
||||
hosts = ["nukestudio"]
|
||||
families = ["trackItem.task"]
|
||||
optional = True
|
||||
|
||||
def filelink(self, src, dst):
|
||||
import filecmp
|
||||
import os
|
||||
import shutil
|
||||
|
||||
import filelink
|
||||
|
||||
# Compare files to check whether they are the same.
|
||||
if os.path.exists(dst) and filecmp.cmp(src, dst):
|
||||
return
|
||||
|
||||
# Remove existing destination file.
|
||||
if os.path.exists(dst):
|
||||
os.remove(dst)
|
||||
|
||||
try:
|
||||
filelink.create(src, dst, filelink.HARDLINK)
|
||||
self.log.debug("Linking: \"{0}\" to \"{1}\"".format(src, dst))
|
||||
except WindowsError as e:
|
||||
if e.winerror == 17:
|
||||
self.log.warning(
|
||||
"File linking failed due to: \"{0}\". "
|
||||
"Resorting to copying instead.".format(e)
|
||||
)
|
||||
shutil.copy(src, dst)
|
||||
else:
|
||||
raise e
|
||||
|
||||
def process(self, instance):
|
||||
import time
|
||||
import os
|
||||
|
||||
import hiero.core.nuke as nuke
|
||||
import hiero.exporters as he
|
||||
import clique
|
||||
|
||||
task = instance.data["task"]
|
||||
|
||||
hiero_cls = he.FnSymLinkExporter.SymLinkExporter
|
||||
if isinstance(task, hiero_cls):
|
||||
src = os.path.join(
|
||||
task.filepath(),
|
||||
task.fileName()
|
||||
)
|
||||
# Filelink each image file
|
||||
if "img" in instance.data["families"]:
|
||||
collection = clique.parse(src + " []")
|
||||
for f in os.listdir(os.path.dirname(src)):
|
||||
f = os.path.join(os.path.dirname(src), f)
|
||||
|
||||
frame_offset = task.outputRange()[0] - task.inputRange()[0]
|
||||
input_range = (
|
||||
int(task.inputRange()[0]), int(task.inputRange()[1]) + 1
|
||||
)
|
||||
for index in range(*input_range):
|
||||
dst = task.resolvedExportPath() % (index + frame_offset)
|
||||
self.filelink(src % index, dst)
|
||||
# Filelink movie file
|
||||
if "mov" in instance.data["families"]:
|
||||
dst = task.resolvedExportPath()
|
||||
self.filelink(src, dst)
|
||||
|
||||
hiero_cls = he.FnTranscodeExporter.TranscodeExporter
|
||||
if isinstance(task, hiero_cls):
|
||||
task.startTask()
|
||||
while task.taskStep():
|
||||
time.sleep(1)
|
||||
|
||||
script_path = task._scriptfile
|
||||
log_path = script_path.replace(".nk", ".log")
|
||||
log_file = open(log_path, "w")
|
||||
process = nuke.executeNukeScript(script_path, log_file, True)
|
||||
|
||||
self.poll(process)
|
||||
|
||||
log_file.close()
|
||||
|
||||
if not task._preset.properties()["keepNukeScript"]:
|
||||
os.remove(script_path)
|
||||
os.remove(log_path)
|
||||
|
||||
hiero_cls = he.FnNukeShotExporter.NukeShotExporter
|
||||
if isinstance(task, hiero_cls):
|
||||
task.startTask()
|
||||
while task.taskStep():
|
||||
time.sleep(1)
|
||||
|
||||
hiero_cls = he.FnAudioExportTask.AudioExportTask
|
||||
if isinstance(task, hiero_cls):
|
||||
task.startTask()
|
||||
while task.taskStep():
|
||||
time.sleep(1)
|
||||
|
||||
# Fill collection with output
|
||||
if "img" in instance.data["families"]:
|
||||
collection = instance.data["collection"]
|
||||
path = os.path.dirname(collection.format())
|
||||
for f in os.listdir(path):
|
||||
file_path = os.path.join(path, f).replace("\\", "/")
|
||||
if collection.match(file_path):
|
||||
collection.add(file_path)
|
||||
|
||||
def poll(self, process):
|
||||
import time
|
||||
|
||||
returnCode = process.poll()
|
||||
|
||||
# if the return code hasn't been set, Nuke is still running
|
||||
if returnCode is None:
|
||||
time.sleep(1)
|
||||
|
||||
self.poll(process)
|
||||
27
pype/plugins/nukestudio/_unused/validate_resolved_paths.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
from pyblish import api
|
||||
|
||||
class ValidateResolvedPaths(api.ContextPlugin):
|
||||
"""Validate there are no overlapping resolved paths."""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
label = "Resolved Paths"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, context):
|
||||
import os
|
||||
import collections
|
||||
|
||||
paths = []
|
||||
for instance in context:
|
||||
if "trackItem.task" == instance.data["family"]:
|
||||
paths.append(
|
||||
os.path.abspath(instance.data["task"].resolvedExportPath())
|
||||
)
|
||||
|
||||
duplicates = []
|
||||
for item, count in collections.Counter(paths).items():
|
||||
if count > 1:
|
||||
duplicates.append(item)
|
||||
|
||||
msg = "Duplicate output paths found: {0}".format(duplicates)
|
||||
assert not duplicates, msg
|
||||
57
pype/plugins/nukestudio/_unused/validate_task.py
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class ValidateOutputRange(api.InstancePlugin):
|
||||
"""Validate the output range of the task.
|
||||
|
||||
This compares the output range and clip associated with the task, so see
|
||||
whether there is a difference. This difference indicates that the user has
|
||||
selected to export the clip length for the task which is very uncommon to
|
||||
do.
|
||||
"""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
families = ["trackItem.task"]
|
||||
label = "Output Range"
|
||||
hosts = ["nukestudio"]
|
||||
optional = True
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
task = instance.data["task"]
|
||||
item = instance.data["parent"]
|
||||
|
||||
output_range = task.outputRange()
|
||||
first_frame = int(item.data["item"].source().sourceIn())
|
||||
last_frame = int(item.data["item"].source().sourceOut())
|
||||
clip_duration = last_frame - first_frame + 1
|
||||
|
||||
difference = clip_duration - output_range[1]
|
||||
failure_message = (
|
||||
'Looks like you are rendering the clip length for the task '
|
||||
'rather than the cut length. If this is intended, just uncheck '
|
||||
'this validator after resetting, else adjust the export range in '
|
||||
'the "Handles" section of the export dialog.'
|
||||
)
|
||||
assert difference, failure_message
|
||||
|
||||
|
||||
class ValidateImageSequence(api.InstancePlugin):
|
||||
"""Validate image sequence output path is setup correctly."""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
families = ["trackItem.task", "img"]
|
||||
match = api.Subset
|
||||
label = "Image Sequence"
|
||||
hosts = ["nukestudio"]
|
||||
optional = True
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
resolved_path = instance.data["task"].resolvedExportPath()
|
||||
|
||||
msg = (
|
||||
"Image sequence output is missing a padding. Please add \"####\" "
|
||||
"or \"%04d\" to the output templates."
|
||||
)
|
||||
assert "#" in resolved_path or "%" in resolved_path, msg
|
||||
13
pype/plugins/nukestudio/publish/collect_active_project.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class CollectActiveProject(pyblish.api.ContextPlugin):
|
||||
"""Inject the active project into context"""
|
||||
|
||||
order = pyblish.api.CollectorOrder - 0.2
|
||||
|
||||
def process(self, context):
|
||||
import hiero
|
||||
|
||||
context.data["activeProject"] = hiero.ui.activeSequence().project()
|
||||
self.log.info("activeProject: {}".format(context.data["activeProject"]))
|
||||
43
pype/plugins/nukestudio/publish/collect_clips.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class CollectClips(api.ContextPlugin):
|
||||
"""Collect all Track items selection."""
|
||||
|
||||
order = api.CollectorOrder
|
||||
label = "Collect Clips"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, context):
|
||||
data = {}
|
||||
for item in context.data.get("selection", []):
|
||||
self.log.info("__ item: {}".format(item))
|
||||
# Skip audio track items
|
||||
# Try/Except is to handle items types, like EffectTrackItem
|
||||
try:
|
||||
media_type = "core.Hiero.Python.TrackItem.MediaType.kVideo"
|
||||
if str(item.mediaType()) != media_type:
|
||||
continue
|
||||
except:
|
||||
continue
|
||||
|
||||
data[item.name()] = {
|
||||
"item": item,
|
||||
"tasks": [],
|
||||
"startFrame": item.timelineIn(),
|
||||
"endFrame": item.timelineOut()
|
||||
}
|
||||
|
||||
for key, value in data.items():
|
||||
family = "clip"
|
||||
context.create_instance(
|
||||
name=key,
|
||||
subset="{0}{1}".format(family, 'Default'),
|
||||
asset=value["item"].name(),
|
||||
item=value["item"],
|
||||
family=family,
|
||||
tasks=value["tasks"],
|
||||
startFrame=value["startFrame"],
|
||||
endFrame=value["endFrame"],
|
||||
handles=0
|
||||
)
|
||||
27
pype/plugins/nukestudio/publish/collect_colorspace.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class CollectProjectColorspace(pyblish.api.ContextPlugin):
|
||||
"""get active project color settings"""
|
||||
|
||||
order = pyblish.api.CollectorOrder + 0.1
|
||||
label = "Project's color settings"
|
||||
def process(self, context):
|
||||
import hiero
|
||||
|
||||
project = context.data["activeProject"]
|
||||
colorspace = {}
|
||||
colorspace["useOCIOEnvironmentOverride"] = project.useOCIOEnvironmentOverride()
|
||||
colorspace["lutSetting16Bit"] = project.lutSetting16Bit()
|
||||
colorspace["lutSetting8Bit"] = project.lutSetting8Bit()
|
||||
colorspace["lutSettingFloat"] = project.lutSettingFloat()
|
||||
colorspace["lutSettingLog"] = project.lutSettingLog()
|
||||
colorspace["lutSettingViewer"] = project.lutSettingViewer()
|
||||
colorspace["lutSettingWorkingSpace"] = project.lutSettingWorkingSpace()
|
||||
colorspace["lutUseOCIOForExport"] = project.lutUseOCIOForExport()
|
||||
colorspace["ocioConfigName"] = project.ocioConfigName()
|
||||
colorspace["ocioConfigPath"] = project.ocioConfigPath()
|
||||
|
||||
context.data["colorspace"] = colorspace
|
||||
|
||||
self.log.info("context.data[colorspace]: {}".format(context.data["colorspace"]))
|
||||
14
pype/plugins/nukestudio/publish/collect_current_file.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class CollectCurrentFile(pyblish.api.ContextPlugin):
|
||||
"""Inject the current working file into context"""
|
||||
|
||||
order = pyblish.api.CollectorOrder
|
||||
|
||||
def process(self, context):
|
||||
"""Todo, inject the current working file"""
|
||||
|
||||
project = context.data('activeProject')
|
||||
context.set_data('currentFile', value=project.path())
|
||||
self.log.info("currentFile: {}".format(context.data["currentFile"]))
|
||||
13
pype/plugins/nukestudio/publish/collect_framerate.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from pyblish import api
|
||||
|
||||
class CollectFramerate(api.ContextPlugin):
|
||||
"""Collect framerate from selected sequence."""
|
||||
|
||||
order = api.CollectorOrder
|
||||
label = "Collect Framerate"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, context):
|
||||
for item in context.data.get("selection", []):
|
||||
context.data["framerate"] = item.sequence().framerate().toFloat()
|
||||
return
|
||||
72
pype/plugins/nukestudio/publish/collect_hierarchy_context.py
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import pyblish.api
|
||||
from avalon import api
|
||||
|
||||
|
||||
class CollectHierarchyContext(pyblish.api.ContextPlugin):
|
||||
"""Collecting hierarchy context from `parents` and `hierarchy` data
|
||||
present in `clip` family instances coming from the request json data file
|
||||
|
||||
It will add `hierarchical_context` into each instance for integrate
|
||||
plugins to be able to create needed parents for the context if they
|
||||
don't exist yet
|
||||
"""
|
||||
|
||||
label = "Collect Hierarchy Context"
|
||||
order = pyblish.api.CollectorOrder + 0.1
|
||||
|
||||
def update_dict(self, ex_dict, new_dict):
|
||||
for key in ex_dict:
|
||||
if key in new_dict and isinstance(ex_dict[key], dict):
|
||||
new_dict[key] = self.update_dict(ex_dict[key], new_dict[key])
|
||||
else:
|
||||
new_dict[key] = ex_dict[key]
|
||||
return new_dict
|
||||
|
||||
def process(self, context):
|
||||
json_data = context.data.get("jsonData", None)
|
||||
temp_context = {}
|
||||
for instance in json_data['instances']:
|
||||
if instance['family'] in 'projectfile':
|
||||
continue
|
||||
|
||||
in_info = {}
|
||||
name = instance['name']
|
||||
# suppose that all instances are Shots
|
||||
in_info['entity_type'] = 'Shot'
|
||||
|
||||
instance_pyblish = [
|
||||
i for i in context.data["instances"] if i.data['asset'] in name][0]
|
||||
in_info['custom_attributes'] = {
|
||||
'fend': instance_pyblish.data['endFrame'],
|
||||
'fstart': instance_pyblish.data['startFrame'],
|
||||
'fps': instance_pyblish.data['fps']
|
||||
}
|
||||
|
||||
in_info['tasks'] = instance['tasks']
|
||||
|
||||
parents = instance.get('parents', [])
|
||||
|
||||
actual = {name: in_info}
|
||||
|
||||
for parent in reversed(parents):
|
||||
next_dict = {}
|
||||
parent_name = parent["entityName"]
|
||||
next_dict[parent_name] = {}
|
||||
next_dict[parent_name]["entity_type"] = parent["entityType"]
|
||||
next_dict[parent_name]["childs"] = actual
|
||||
actual = next_dict
|
||||
|
||||
temp_context = self.update_dict(temp_context, actual)
|
||||
self.log.debug(temp_context)
|
||||
|
||||
# TODO: 100% sure way of get project! Will be Name or Code?
|
||||
project_name = api.Session["AVALON_PROJECT"]
|
||||
final_context = {}
|
||||
final_context[project_name] = {}
|
||||
final_context[project_name]['entity_type'] = 'Project'
|
||||
final_context[project_name]['childs'] = temp_context
|
||||
|
||||
# adding hierarchy context to instance
|
||||
context.data["hierarchyContext"] = final_context
|
||||
self.log.debug("context.data[hierarchyContext] is: {}".format(
|
||||
context.data["hierarchyContext"]))
|
||||
13
pype/plugins/nukestudio/publish/collect_host.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class CollectHost(pyblish.api.ContextPlugin):
|
||||
"""Inject the host into context"""
|
||||
|
||||
order = pyblish.api.CollectorOrder
|
||||
|
||||
def process(self, context):
|
||||
import pyblish.api
|
||||
|
||||
context.set_data("host", pyblish.api.current_host())
|
||||
self.log.info("current host: {}".format(pyblish.api.current_host()))
|
||||
12
pype/plugins/nukestudio/publish/collect_host_version.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class CollectHostVersion(pyblish.api.ContextPlugin):
|
||||
"""Inject the hosts version into context"""
|
||||
|
||||
order = pyblish.api.CollectorOrder
|
||||
|
||||
def process(self, context):
|
||||
import nuke
|
||||
|
||||
context.set_data('hostVersion', value=nuke.NUKE_VERSION_STRING)
|
||||
30
pype/plugins/nukestudio/publish/collect_metadata.py
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class CollectClipMetadata(api.InstancePlugin):
|
||||
"""Collect Metadata from selected track items."""
|
||||
|
||||
order = api.CollectorOrder + 0.01
|
||||
label = "Collect Metadata"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, instance):
|
||||
item = instance.data["item"]
|
||||
ti_metadata = self.metadata_to_string(dict(item.metadata()))
|
||||
ms_metadata = self.metadata_to_string(
|
||||
dict(item.source().mediaSource().metadata()))
|
||||
|
||||
instance.data["clipMetadata"] = ti_metadata
|
||||
instance.data["mediaSourceMetadata"] = ms_metadata
|
||||
|
||||
self.log.info(instance.data["clipMetadata"])
|
||||
self.log.info(instance.data["mediaSourceMetadata"])
|
||||
return
|
||||
|
||||
def metadata_to_string(self, metadata):
|
||||
data = dict()
|
||||
for k, v in metadata.items():
|
||||
if v not in ["-", ""]:
|
||||
data[str(k)] = v
|
||||
|
||||
return data
|
||||
15
pype/plugins/nukestudio/publish/collect_selection.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import pyblish.api
|
||||
|
||||
import hiero
|
||||
|
||||
class CollectSelection(pyblish.api.ContextPlugin):
|
||||
"""Inject the selection in the context."""
|
||||
|
||||
order = pyblish.api.CollectorOrder - 0.1
|
||||
label = "Selection"
|
||||
|
||||
def process(self, context):
|
||||
selection = getattr(hiero, "selection")
|
||||
|
||||
self.log.debug("selection: {}".format(selection))
|
||||
context.data["selection"] = hiero.selection
|
||||
45
pype/plugins/nukestudio/publish/collect_subsets.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class CollectClipSubsets(api.InstancePlugin):
|
||||
"""Collect Subsets from selected Clips, Tags, Preset."""
|
||||
|
||||
order = api.CollectorOrder + 0.01
|
||||
label = "Collect Subsets"
|
||||
hosts = ["nukestudio"]
|
||||
families = ['clip']
|
||||
|
||||
def process(self, instance):
|
||||
tags = instance.data.get('tags', None)
|
||||
presets = instance.context.data['presets'][
|
||||
instance.context.data['host']]
|
||||
if tags:
|
||||
self.log.info(tags)
|
||||
|
||||
if presets:
|
||||
self.log.info(presets)
|
||||
|
||||
# get presets and tags
|
||||
# iterate tags and get task family
|
||||
# iterate tags and get host family
|
||||
# iterate tags and get handles family
|
||||
|
||||
instance = instance.context.create_instance(instance_name)
|
||||
|
||||
instance.data.update({
|
||||
"subset": subset_name,
|
||||
"stagingDir": staging_dir,
|
||||
"task": task,
|
||||
"representation": ext[1:],
|
||||
"host": host,
|
||||
"asset": asset_name,
|
||||
"label": label,
|
||||
"name": name,
|
||||
# "hierarchy": hierarchy,
|
||||
# "parents": parents,
|
||||
"family": family,
|
||||
"families": [families, 'ftrack'],
|
||||
"publish": True,
|
||||
# "files": files_list
|
||||
})
|
||||
instances.append(instance)
|
||||
30
pype/plugins/nukestudio/publish/collect_tags.py
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class CollectClipTags(api.InstancePlugin):
|
||||
"""Collect Tags from selected track items."""
|
||||
|
||||
order = api.CollectorOrder
|
||||
label = "Collect Tags"
|
||||
hosts = ["nukestudio"]
|
||||
families = ['clip']
|
||||
|
||||
def process(self, instance):
|
||||
tags = instance.data["item"].tags()
|
||||
|
||||
tags_d = []
|
||||
if tags:
|
||||
for t in tags:
|
||||
tag_data = {
|
||||
"name": t.name(),
|
||||
"object": t,
|
||||
"metadata": t.metadata(),
|
||||
"inTime": t.inTime(),
|
||||
"outTime": t.outTime(),
|
||||
}
|
||||
tags_d.append(tag_data)
|
||||
|
||||
instance.data["tags"] = tags_d
|
||||
|
||||
self.log.info(instance.data["tags"])
|
||||
return
|
||||
101
pype/plugins/nukestudio/publish/extract_review.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class ExtractReview(api.InstancePlugin):
|
||||
"""Extracts movie for review"""
|
||||
|
||||
order = api.ExtractorOrder
|
||||
label = "NukeStudio Review"
|
||||
optional = True
|
||||
hosts = ["nukestudio"]
|
||||
families = ["review"]
|
||||
|
||||
def process(self, instance):
|
||||
import os
|
||||
import time
|
||||
|
||||
import hiero.core
|
||||
from hiero.exporters.FnExportUtil import writeSequenceAudioWithHandles
|
||||
|
||||
nukeWriter = hiero.core.nuke.ScriptWriter()
|
||||
|
||||
item = instance.data["item"]
|
||||
|
||||
handles = instance.data["handles"]
|
||||
|
||||
sequence = item.parent().parent()
|
||||
|
||||
output_path = os.path.abspath(
|
||||
os.path.join(
|
||||
instance.context.data["currentFile"], "..", "workspace"
|
||||
)
|
||||
)
|
||||
|
||||
# Generate audio
|
||||
audio_file = os.path.join(
|
||||
output_path, "{0}.wav".format(instance.data["name"])
|
||||
)
|
||||
|
||||
writeSequenceAudioWithHandles(
|
||||
audio_file,
|
||||
sequence,
|
||||
item.timelineIn(),
|
||||
item.timelineOut(),
|
||||
handles,
|
||||
handles
|
||||
)
|
||||
|
||||
# Generate Nuke script
|
||||
root_node = hiero.core.nuke.RootNode(
|
||||
item.timelineIn() - handles,
|
||||
item.timelineOut() + handles,
|
||||
fps=sequence.framerate()
|
||||
)
|
||||
|
||||
root_node.addProjectSettings(instance.context.data["colorspace"])
|
||||
|
||||
nukeWriter.addNode(root_node)
|
||||
|
||||
item.addToNukeScript(
|
||||
script=nukeWriter,
|
||||
includeRetimes=True,
|
||||
retimeMethod="Frame",
|
||||
startHandle=handles,
|
||||
endHandle=handles
|
||||
)
|
||||
|
||||
movie_path = os.path.join(
|
||||
output_path, "{0}.mov".format(instance.data["name"])
|
||||
)
|
||||
write_node = hiero.core.nuke.WriteNode(movie_path.replace("\\", "/"))
|
||||
self.log.info("__ write_node: {0}".format(write_node))
|
||||
write_node.setKnob("file_type", "mov")
|
||||
write_node.setKnob("colorspace", instance.context.data["colorspace"]["lutSettingFloat"])
|
||||
write_node.setKnob("meta_codec", "ap4h")
|
||||
write_node.setKnob("mov64_codec", "ap4h")
|
||||
write_node.setKnob("mov64_bitrate", 400000)
|
||||
write_node.setKnob("mov64_bitrate_tolerance", 40000000)
|
||||
write_node.setKnob("mov64_quality_min", 2)
|
||||
write_node.setKnob("mov64_quality_max", 31)
|
||||
write_node.setKnob("mov64_gop_size", 12)
|
||||
write_node.setKnob("mov64_b_frames", 0)
|
||||
write_node.setKnob("raw", True )
|
||||
write_node.setKnob("mov64_audiofile", audio_file.replace("\\", "/"))
|
||||
write_node.setKnob("mov32_fps", sequence.framerate())
|
||||
nukeWriter.addNode(write_node)
|
||||
|
||||
nukescript_path = movie_path.replace(".mov", ".nk")
|
||||
nukeWriter.writeToDisk(nukescript_path)
|
||||
|
||||
process = hiero.core.nuke.executeNukeScript(
|
||||
nukescript_path,
|
||||
open(movie_path.replace(".mov", ".log"), "w")
|
||||
)
|
||||
|
||||
while process.poll() is None:
|
||||
time.sleep(0.5)
|
||||
|
||||
assert os.path.exists(movie_path), "Creating review failed."
|
||||
|
||||
instance.data["output_path"] = movie_path
|
||||
instance.data["review_family"] = "mov"
|
||||
132
pype/plugins/nukestudio/publish/integrate_assumed_destination.py
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import pyblish.api
|
||||
import os
|
||||
|
||||
from avalon import io, api
|
||||
|
||||
|
||||
class IntegrateAssumedDestination(pyblish.api.InstancePlugin):
|
||||
"""Generate the assumed destination path where the file will be stored"""
|
||||
|
||||
label = "Integrate Assumed Destination"
|
||||
order = pyblish.api.IntegratorOrder - 0.05
|
||||
families = ["clip", "projectfile"]
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
self.create_destination_template(instance)
|
||||
|
||||
template_data = instance.data["assumedTemplateData"]
|
||||
# template = instance.data["template"]
|
||||
|
||||
anatomy = instance.context.data['anatomy']
|
||||
# template = anatomy.publish.path
|
||||
anatomy_filled = anatomy.format(template_data)
|
||||
mock_template = anatomy_filled.publish.path
|
||||
|
||||
# For now assume resources end up in a "resources" folder in the
|
||||
# published folder
|
||||
mock_destination = os.path.join(os.path.dirname(mock_template),
|
||||
"resources")
|
||||
|
||||
# Clean the path
|
||||
mock_destination = os.path.abspath(os.path.normpath(mock_destination))
|
||||
|
||||
# Define resource destination and transfers
|
||||
resources = instance.data.get("resources", list())
|
||||
transfers = instance.data.get("transfers", list())
|
||||
for resource in resources:
|
||||
|
||||
# Add destination to the resource
|
||||
source_filename = os.path.basename(resource["source"])
|
||||
destination = os.path.join(mock_destination, source_filename)
|
||||
|
||||
# Force forward slashes to fix issue with software unable
|
||||
# to work correctly with backslashes in specific scenarios
|
||||
# (e.g. escape characters in PLN-151 V-Ray UDIM)
|
||||
destination = destination.replace("\\", "/")
|
||||
|
||||
resource['destination'] = destination
|
||||
|
||||
# Collect transfers for the individual files of the resource
|
||||
# e.g. all individual files of a cache or UDIM textures.
|
||||
files = resource['files']
|
||||
for fsrc in files:
|
||||
fname = os.path.basename(fsrc)
|
||||
fdest = os.path.join(mock_destination, fname)
|
||||
transfers.append([fsrc, fdest])
|
||||
|
||||
instance.data["resources"] = resources
|
||||
instance.data["transfers"] = transfers
|
||||
|
||||
def create_destination_template(self, instance):
|
||||
"""Create a filepath based on the current data available
|
||||
|
||||
Example template:
|
||||
{root}/{project}/{silo}/{asset}/publish/{subset}/v{version:0>3}/
|
||||
{subset}.{representation}
|
||||
Args:
|
||||
instance: the instance to publish
|
||||
|
||||
Returns:
|
||||
file path (str)
|
||||
"""
|
||||
|
||||
# get all the stuff from the database
|
||||
subset_name = instance.data["subset"]
|
||||
self.log.info(subset_name)
|
||||
asset_name = instance.data["asset"]
|
||||
project_name = api.Session["AVALON_PROJECT"]
|
||||
|
||||
project = io.find_one({"type": "project",
|
||||
"name": project_name},
|
||||
projection={"config": True, "data": True})
|
||||
|
||||
template = project["config"]["template"]["publish"]
|
||||
# anatomy = instance.context.data['anatomy']
|
||||
|
||||
asset = io.find_one({"type": "asset",
|
||||
"name": asset_name,
|
||||
"parent": project["_id"]})
|
||||
|
||||
assert asset, ("No asset found by the name '{}' "
|
||||
"in project '{}'".format(asset_name, project_name))
|
||||
silo = asset['silo']
|
||||
|
||||
subset = io.find_one({"type": "subset",
|
||||
"name": subset_name,
|
||||
"parent": asset["_id"]})
|
||||
|
||||
# assume there is no version yet, we start at `1`
|
||||
version = None
|
||||
version_number = 1
|
||||
if subset is not None:
|
||||
version = io.find_one({"type": "version",
|
||||
"parent": subset["_id"]},
|
||||
sort=[("name", -1)])
|
||||
|
||||
# if there is a subset there ought to be version
|
||||
if version is not None:
|
||||
version_number += version["name"]
|
||||
|
||||
if instance.data.get('version'):
|
||||
version_number = int(instance.data.get('version'))
|
||||
|
||||
hierarchy = asset['data']['parents']
|
||||
if hierarchy:
|
||||
# hierarchy = os.path.sep.join(hierarchy)
|
||||
hierarchy = os.path.join(*hierarchy)
|
||||
|
||||
template_data = {"root": api.Session["AVALON_PROJECTS"],
|
||||
"project": {"name": project_name,
|
||||
"code": project['data']['code']},
|
||||
"silo": silo,
|
||||
"family": instance.data['family'],
|
||||
"asset": asset_name,
|
||||
"subset": subset_name,
|
||||
"version": version_number,
|
||||
"hierarchy": hierarchy,
|
||||
"representation": "TEMP"}
|
||||
|
||||
instance.data["assumedTemplateData"] = template_data
|
||||
self.log.info(template_data)
|
||||
instance.data["template"] = template
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class IntegrateFtrackComponentOverwrite(pyblish.api.InstancePlugin):
|
||||
"""
|
||||
Set `component_overwrite` to True on all instances `ftrackComponentsList`
|
||||
"""
|
||||
|
||||
order = pyblish.api.IntegratorOrder + 0.49
|
||||
label = 'Overwrite ftrack created versions'
|
||||
families = ["clip"]
|
||||
optional = True
|
||||
active = False
|
||||
|
||||
def process(self, instance):
|
||||
component_list = instance.data['ftrackComponentsList']
|
||||
|
||||
for cl in component_list:
|
||||
cl['component_overwrite'] = True
|
||||
self.log.debug('Component {} overwriting'.format(
|
||||
cl['component_data']['name']))
|
||||
140
pype/plugins/nukestudio/publish/integrate_hierarchy_avalon.py
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import pyblish.api
|
||||
from avalon import io
|
||||
|
||||
|
||||
class IntegrateHierarchyToAvalon(pyblish.api.ContextPlugin):
|
||||
"""
|
||||
Create entities in ftrack based on collected data from premiere
|
||||
|
||||
"""
|
||||
|
||||
order = pyblish.api.IntegratorOrder - 0.1
|
||||
label = 'Integrate Hierarchy To Avalon'
|
||||
families = ['clip']
|
||||
|
||||
def process(self, context):
|
||||
if "hierarchyContext" not in context.data:
|
||||
return
|
||||
|
||||
self.db = io
|
||||
if not self.db.Session:
|
||||
self.db.install()
|
||||
|
||||
input_data = context.data["hierarchyContext"]
|
||||
self.import_to_avalon(input_data)
|
||||
|
||||
def import_to_avalon(self, input_data, parent=None):
|
||||
|
||||
for name in input_data:
|
||||
self.log.info('input_data[name]: {}'.format(input_data[name]))
|
||||
entity_data = input_data[name]
|
||||
entity_type = entity_data['entity_type']
|
||||
|
||||
data = {}
|
||||
# Process project
|
||||
if entity_type.lower() == 'project':
|
||||
entity = self.db.find_one({'type': 'project'})
|
||||
# TODO: should be in validator?
|
||||
assert (entity is not None), "Didn't find project in DB"
|
||||
|
||||
# get data from already existing project
|
||||
for key, value in entity.get('data', {}).items():
|
||||
data[key] = value
|
||||
|
||||
self.av_project = entity
|
||||
# Raise error if project or parent are not set
|
||||
elif self.av_project is None or parent is None:
|
||||
raise AssertionError(
|
||||
"Collected items are not in right order!"
|
||||
)
|
||||
# Else process assset
|
||||
else:
|
||||
entity = self.db.find_one({'type': 'asset', 'name': name})
|
||||
# Create entity if doesn't exist
|
||||
if entity is None:
|
||||
if self.av_project['_id'] == parent['_id']:
|
||||
silo = None
|
||||
elif parent['silo'] is None:
|
||||
silo = parent['name']
|
||||
else:
|
||||
silo = parent['silo']
|
||||
entity = self.create_avalon_asset(name, silo)
|
||||
self.log.info('entity: {}'.format(entity))
|
||||
self.log.info('data: {}'.format(entity.get('data', {})))
|
||||
self.log.info('____1____')
|
||||
data['entityType'] = entity_type
|
||||
# TASKS
|
||||
tasks = entity_data.get('tasks', [])
|
||||
if tasks is not None or len(tasks) > 0:
|
||||
data['tasks'] = tasks
|
||||
parents = []
|
||||
visualParent = None
|
||||
data = input_data[name]
|
||||
if self.av_project['_id'] != parent['_id']:
|
||||
visualParent = parent['_id']
|
||||
parents.extend(parent.get('data', {}).get('parents', []))
|
||||
parents.append(parent['name'])
|
||||
data['visualParent'] = visualParent
|
||||
data['parents'] = parents
|
||||
|
||||
self.db.update_many(
|
||||
{'_id': entity['_id']},
|
||||
{'$set': {
|
||||
'data': data,
|
||||
}})
|
||||
|
||||
entity = self.db.find_one({'type': 'asset', 'name': name})
|
||||
self.log.info('entity: {}'.format(entity))
|
||||
self.log.info('data: {}'.format(entity.get('data', {})))
|
||||
self.log.info('____2____')
|
||||
|
||||
# Else get data from already existing
|
||||
else:
|
||||
self.log.info('entity: {}'.format(entity))
|
||||
self.log.info('data: {}'.format(entity.get('data', {})))
|
||||
self.log.info('________')
|
||||
for key, value in entity.get('data', {}).items():
|
||||
data[key] = value
|
||||
|
||||
data['entityType'] = entity_type
|
||||
# TASKS
|
||||
tasks = entity_data.get('tasks', [])
|
||||
if tasks is not None or len(tasks) > 0:
|
||||
data['tasks'] = tasks
|
||||
parents = []
|
||||
visualParent = None
|
||||
# do not store project's id as visualParent (silo asset)
|
||||
|
||||
if self.av_project['_id'] != parent['_id']:
|
||||
visualParent = parent['_id']
|
||||
parents.extend(parent.get('data', {}).get('parents', []))
|
||||
parents.append(parent['name'])
|
||||
data['visualParent'] = visualParent
|
||||
data['parents'] = parents
|
||||
|
||||
# CUSTOM ATTRIBUTES
|
||||
for k, val in entity_data.get('custom_attributes', {}).items():
|
||||
data[k] = val
|
||||
|
||||
# Update entity data with input data
|
||||
self.db.update_many(
|
||||
{'_id': entity['_id']},
|
||||
{'$set': {
|
||||
'data': data,
|
||||
}})
|
||||
|
||||
if 'childs' in entity_data:
|
||||
self.import_to_avalon(entity_data['childs'], entity)
|
||||
|
||||
def create_avalon_asset(self, name, silo):
|
||||
item = {
|
||||
'schema': 'avalon-core:asset-2.0',
|
||||
'name': name,
|
||||
'silo': silo,
|
||||
'parent': self.av_project['_id'],
|
||||
'type': 'asset',
|
||||
'data': {}
|
||||
}
|
||||
entity_id = self.db.insert_one(item).inserted_id
|
||||
|
||||
return self.db.find_one({'_id': entity_id})
|
||||
155
pype/plugins/nukestudio/publish/integrate_hierarchy_ftrack.py
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import pyblish.api
|
||||
|
||||
|
||||
class IntegrateHierarchyToFtrack(pyblish.api.ContextPlugin):
|
||||
"""
|
||||
Create entities in ftrack based on collected data from premiere
|
||||
Example of entry data:
|
||||
{
|
||||
"ProjectXS": {
|
||||
"entity_type": "Project",
|
||||
"custom_attributes": {
|
||||
"fps": 24,...
|
||||
},
|
||||
"tasks": [
|
||||
"Compositing",
|
||||
"Lighting",... *task must exist as task type in project schema*
|
||||
],
|
||||
"childs": {
|
||||
"sq01": {
|
||||
"entity_type": "Sequence",
|
||||
...
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
order = pyblish.api.IntegratorOrder
|
||||
label = 'Integrate Hierarchy To Ftrack'
|
||||
families = ["clip"]
|
||||
optional = False
|
||||
|
||||
def process(self, context):
|
||||
self.context = context
|
||||
if "hierarchyContext" not in context.data:
|
||||
return
|
||||
|
||||
self.ft_project = None
|
||||
self.session = context.data["ftrackSession"]
|
||||
|
||||
input_data = context.data["hierarchyContext"]
|
||||
|
||||
# adding ftrack types from presets
|
||||
ftrack_types = context.data['ftrackTypes']
|
||||
|
||||
self.import_to_ftrack(input_data, ftrack_types)
|
||||
|
||||
def import_to_ftrack(self, input_data, ftrack_types, parent=None):
|
||||
for entity_name in input_data:
|
||||
entity_data = input_data[entity_name]
|
||||
entity_type = entity_data['entity_type'].capitalize()
|
||||
|
||||
if entity_type.lower() == 'project':
|
||||
query = 'Project where full_name is "{}"'.format(entity_name)
|
||||
entity = self.session.query(query).one()
|
||||
self.ft_project = entity
|
||||
self.task_types = self.get_all_task_types(entity)
|
||||
|
||||
elif self.ft_project is None or parent is None:
|
||||
raise AssertionError(
|
||||
"Collected items are not in right order!"
|
||||
)
|
||||
|
||||
# try to find if entity already exists
|
||||
else:
|
||||
query = '{} where name is "{}" and parent_id is "{}"'.format(
|
||||
entity_type, entity_name, parent['id']
|
||||
)
|
||||
try:
|
||||
entity = self.session.query(query).one()
|
||||
except Exception:
|
||||
entity = None
|
||||
|
||||
# Create entity if not exists
|
||||
if entity is None:
|
||||
entity = self.create_entity(
|
||||
name=entity_name,
|
||||
type=entity_type,
|
||||
parent=parent
|
||||
)
|
||||
# self.log.info('entity: {}'.format(dict(entity)))
|
||||
# CUSTOM ATTRIBUTES
|
||||
custom_attributes = entity_data.get('custom_attributes', [])
|
||||
instances = [
|
||||
i for i in self.context.data["instances"] if i.data['asset'] in entity['name']]
|
||||
for key in custom_attributes:
|
||||
assert (key in entity['custom_attributes']), (
|
||||
'Missing custom attribute')
|
||||
|
||||
entity['custom_attributes'][key] = custom_attributes[key]
|
||||
for instance in instances:
|
||||
instance.data['ftrackShotId'] = entity['id']
|
||||
|
||||
self.session.commit()
|
||||
|
||||
# TASKS
|
||||
tasks = entity_data.get('tasks', [])
|
||||
existing_tasks = []
|
||||
tasks_to_create = []
|
||||
for child in entity['children']:
|
||||
if child.entity_type.lower() == 'task':
|
||||
existing_tasks.append(child['name'])
|
||||
# existing_tasks.append(child['type']['name'])
|
||||
|
||||
for task in tasks:
|
||||
if task in existing_tasks:
|
||||
print("Task {} already exists".format(task))
|
||||
continue
|
||||
tasks_to_create.append(task)
|
||||
|
||||
for task in tasks_to_create:
|
||||
self.create_task(
|
||||
name=task,
|
||||
task_type=ftrack_types[task],
|
||||
parent=entity
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
if 'childs' in entity_data:
|
||||
self.import_to_ftrack(
|
||||
entity_data['childs'], ftrack_types, entity)
|
||||
|
||||
def get_all_task_types(self, project):
|
||||
tasks = {}
|
||||
proj_template = project['project_schema']
|
||||
temp_task_types = proj_template['_task_type_schema']['types']
|
||||
|
||||
for type in temp_task_types:
|
||||
if type['name'] not in tasks:
|
||||
tasks[type['name']] = type
|
||||
|
||||
return tasks
|
||||
|
||||
def create_task(self, name, task_type, parent):
|
||||
task = self.session.create('Task', {
|
||||
'name': name,
|
||||
'parent': parent
|
||||
})
|
||||
# TODO not secured!!! - check if task_type exists
|
||||
self.log.info(task_type)
|
||||
self.log.info(self.task_types)
|
||||
task['type'] = self.task_types[task_type]
|
||||
|
||||
self.session.commit()
|
||||
|
||||
return task
|
||||
|
||||
def create_entity(self, name, type, parent):
|
||||
entity = self.session.create(type, {
|
||||
'name': name,
|
||||
'parent': parent
|
||||
})
|
||||
self.session.commit()
|
||||
|
||||
return entity
|
||||
42
pype/plugins/nukestudio/publish/validate_names.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class ValidateNames(api.InstancePlugin):
|
||||
"""Validate sequence, video track and track item names.
|
||||
|
||||
When creating output directories with the name of an item, ending with a
|
||||
whitespace will fail the extraction.
|
||||
Exact matching to optimize processing.
|
||||
"""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
families = ["clip"]
|
||||
match = api.Exact
|
||||
label = "Names"
|
||||
hosts = ["nukestudio"]
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
item = instance.data["item"]
|
||||
|
||||
msg = "Track item \"{0}\" ends with a whitespace."
|
||||
assert not item.name().endswith(" "), msg.format(item.name())
|
||||
|
||||
msg = "Video track \"{0}\" ends with a whitespace."
|
||||
msg = msg.format(item.parent().name())
|
||||
assert not item.parent().name().endswith(" "), msg
|
||||
|
||||
msg = "Sequence \"{0}\" ends with a whitespace."
|
||||
msg = msg.format(item.parent().parent().name())
|
||||
assert not item.parent().parent().name().endswith(" "), msg
|
||||
|
||||
|
||||
class ValidateNamesFtrack(ValidateNames):
|
||||
"""Validate sequence, video track and track item names.
|
||||
|
||||
Because we are matching the families exactly, we need this plugin to
|
||||
accommodate for the ftrack family addition.
|
||||
"""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
families = ["clip", "ftrack"]
|
||||
52
pype/plugins/nukestudio/publish/validate_projectroot.py
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class RepairProjectRoot(api.Action):
|
||||
|
||||
label = "Repair"
|
||||
icon = "wrench"
|
||||
on = "failed"
|
||||
|
||||
def process(self, context, plugin):
|
||||
import os
|
||||
|
||||
workspace = os.path.join(
|
||||
os.path.dirname(context.data["currentFile"]),
|
||||
"workspace"
|
||||
).replace("\\", "/")
|
||||
|
||||
if not os.path.exists(workspace):
|
||||
os.makedirs(workspace)
|
||||
|
||||
context.data["activeProject"].setProjectRoot(workspace)
|
||||
|
||||
# Need to manually fix the tasks "_projectRoot" attribute, because
|
||||
# setting the project root is not enough.
|
||||
submission = context.data.get("submission", None)
|
||||
if submission:
|
||||
for task in submission.getLeafTasks():
|
||||
task._projectRoot = workspace
|
||||
|
||||
|
||||
class ValidateProjectRoot(api.ContextPlugin):
|
||||
"""Validate the project root to the workspace directory."""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
label = "Project Root"
|
||||
hosts = ["nukestudio"]
|
||||
actions = [RepairProjectRoot]
|
||||
|
||||
def process(self, context):
|
||||
import os
|
||||
|
||||
workspace = os.path.join(
|
||||
os.path.dirname(context.data["currentFile"]),
|
||||
"workspace"
|
||||
).replace("\\", "/")
|
||||
project_root = context.data["activeProject"].projectRoot()
|
||||
|
||||
failure_message = (
|
||||
'The project root needs to be "{0}", its currently: "{1}"'
|
||||
).format(workspace, project_root)
|
||||
|
||||
assert project_root == workspace, failure_message
|
||||
46
pype/plugins/nukestudio/publish/validate_track_item.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
from pyblish import api
|
||||
|
||||
class ValidateClip(api.InstancePlugin):
|
||||
"""Validate the track item to the sequence.
|
||||
|
||||
Exact matching to optimize processing.
|
||||
"""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
families = ["clip"]
|
||||
match = api.Exact
|
||||
label = "Validate Track Item"
|
||||
hosts = ["nukestudio"]
|
||||
optional = True
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
item = instance.data["item"]
|
||||
self.log.info("__ item: {}".format(item))
|
||||
media_source = item.source().mediaSource()
|
||||
self.log.info("__ media_source: {}".format(media_source))
|
||||
|
||||
msg = (
|
||||
'A setting does not match between track item "{0}" and sequence '
|
||||
'"{1}".'.format(item.name(), item.sequence().name()) +
|
||||
'\n\nSetting: "{0}".''\n\nTrack item: "{1}".\n\nSequence: "{2}".'
|
||||
)
|
||||
|
||||
# Validate format settings.
|
||||
fmt = item.sequence().format()
|
||||
assert fmt.width() == media_source.width(), msg.format(
|
||||
"width", fmt.width(), media_source.width()
|
||||
)
|
||||
assert fmt.height() == media_source.height(), msg.format(
|
||||
"height", fmt.height(), media_source.height()
|
||||
)
|
||||
assert fmt.pixelAspect() == media_source.pixelAspect(), msg.format(
|
||||
"pixelAspect", fmt.pixelAspect(), media_source.pixelAspect()
|
||||
)
|
||||
|
||||
# Validate framerate setting.
|
||||
sequence = item.sequence()
|
||||
source_framerate = media_source.metadata()["foundry.source.framerate"]
|
||||
assert sequence.framerate() == source_framerate, msg.format(
|
||||
"framerate", source_framerate, sequence.framerate()
|
||||
)
|
||||
21
pype/plugins/nukestudio/publish/validate_viewer_lut.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
from pyblish import api
|
||||
|
||||
|
||||
class ValidateViewerLut(api.ContextPlugin):
|
||||
"""Validate viewer lut in NukeStudio is the same as in Nuke."""
|
||||
|
||||
order = api.ValidatorOrder
|
||||
label = "Viewer LUT"
|
||||
hosts = ["nukestudio"]
|
||||
optional = True
|
||||
|
||||
def process(self, context):
|
||||
import nuke
|
||||
import hiero
|
||||
|
||||
# nuke_lut = nuke.ViewerProcess.node()["current"].value()
|
||||
nukestudio_lut = context.data["activeProject"].lutSettingViewer()
|
||||
self.log.info("__ nukestudio_lut: {}".format(nukestudio_lut))
|
||||
|
||||
msg = "Viewer LUT can only be RGB"
|
||||
assert "RGB" in nukestudio_lut, msg
|
||||
88
pype/plugins/standalonepublish/publish/collect_context.py
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import os
|
||||
import pyblish.api
|
||||
from avalon import (
|
||||
io,
|
||||
api as avalon
|
||||
)
|
||||
import json
|
||||
import logging
|
||||
import clique
|
||||
|
||||
|
||||
log = logging.getLogger("collector")
|
||||
|
||||
|
||||
class CollectContextDataSAPublish(pyblish.api.ContextPlugin):
|
||||
"""
|
||||
Collecting temp json data sent from a host context
|
||||
and path for returning json data back to hostself.
|
||||
|
||||
Setting avalon session into correct context
|
||||
|
||||
Args:
|
||||
context (obj): pyblish context session
|
||||
|
||||
"""
|
||||
|
||||
label = "Collect Context - SA Publish"
|
||||
order = pyblish.api.CollectorOrder - 0.49
|
||||
|
||||
def process(self, context):
|
||||
# get json paths from os and load them
|
||||
io.install()
|
||||
input_json_path = os.environ.get("SAPUBLISH_INPATH")
|
||||
output_json_path = os.environ.get("SAPUBLISH_OUTPATH")
|
||||
|
||||
context.data["stagingDir"] = os.path.dirname(input_json_path)
|
||||
context.data["returnJsonPath"] = output_json_path
|
||||
|
||||
with open(input_json_path, "r") as f:
|
||||
in_data = json.load(f)
|
||||
|
||||
project_name = in_data['project']
|
||||
asset_name = in_data['asset']
|
||||
family = in_data['family']
|
||||
subset = in_data['subset']
|
||||
|
||||
project = io.find_one({'type': 'project'})
|
||||
asset = io.find_one({
|
||||
'type': 'asset',
|
||||
'name': asset_name
|
||||
})
|
||||
context.data['project'] = project
|
||||
context.data['asset'] = asset
|
||||
|
||||
instance = context.create_instance(subset)
|
||||
|
||||
instance.data.update({
|
||||
"subset": family + subset,
|
||||
"asset": asset_name,
|
||||
"label": family + subset,
|
||||
"name": family + subset,
|
||||
"family": family,
|
||||
"families": [family, 'ftrack'],
|
||||
})
|
||||
self.log.info("collected instance: {}".format(instance.data))
|
||||
|
||||
instance.data["files"] = list()
|
||||
instance.data['destination_list'] = list()
|
||||
instance.data['representations'] = list()
|
||||
|
||||
for component in in_data['representations']:
|
||||
# instance.add(node)
|
||||
component['destination'] = component['files']
|
||||
collections, remainder = clique.assemble(component['files'])
|
||||
if collections:
|
||||
self.log.debug(collections)
|
||||
range = collections[0].format('{range}')
|
||||
instance.data['startFrame'] = range.split('-')[0]
|
||||
instance.data['endFrame'] = range.split('-')[1]
|
||||
|
||||
|
||||
instance.data["files"].append(component)
|
||||
instance.data["representations"].append(component)
|
||||
|
||||
# "is_thumbnail": component['thumbnail'],
|
||||
# "is_preview": component['preview']
|
||||
|
||||
self.log.info(in_data)
|
||||
40
pype/plugins/standalonepublish/publish/collect_ftrack_api.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import os
|
||||
import pyblish.api
|
||||
|
||||
try:
|
||||
import ftrack_api_old as ftrack_api
|
||||
except Exception:
|
||||
import ftrack_api
|
||||
|
||||
|
||||
class CollectFtrackApi(pyblish.api.ContextPlugin):
|
||||
""" Collects an ftrack session and the current task id. """
|
||||
|
||||
order = pyblish.api.CollectorOrder
|
||||
label = "Collect Ftrack Api"
|
||||
|
||||
def process(self, context):
|
||||
|
||||
# Collect session
|
||||
session = ftrack_api.Session()
|
||||
context.data["ftrackSession"] = session
|
||||
|
||||
# Collect task
|
||||
|
||||
project = os.environ.get('AVALON_PROJECT', '')
|
||||
asset = os.environ.get('AVALON_ASSET', '')
|
||||
task = os.environ.get('AVALON_TASK', None)
|
||||
|
||||
if task:
|
||||
result = session.query('Task where\
|
||||
project.full_name is "{0}" and\
|
||||
name is "{1}" and\
|
||||
parent.name is "{2}"'.format(project, task, asset)).one()
|
||||
context.data["ftrackTask"] = result
|
||||
else:
|
||||
result = session.query('TypedContext where\
|
||||
project.full_name is "{0}" and\
|
||||
name is "{1}"'.format(project, asset)).one()
|
||||
context.data["ftrackEntity"] = result
|
||||
|
||||
self.log.info(result)
|
||||
17
pype/plugins/standalonepublish/publish/collect_templates.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
|
||||
import pype.api as pype
|
||||
from pypeapp import Anatomy
|
||||
|
||||
import pyblish.api
|
||||
|
||||
|
||||
class CollectTemplates(pyblish.api.ContextPlugin):
|
||||
"""Inject the current working file into context"""
|
||||
|
||||
order = pyblish.api.CollectorOrder
|
||||
label = "Collect Templates"
|
||||
|
||||
def process(self, context):
|
||||
# pype.load_data_from_templates()
|
||||
context.data['anatomy'] = Anatomy()
|
||||
self.log.info("Anatomy templates collected...")
|
||||
12
pype/plugins/standalonepublish/publish/collect_time.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import pyblish.api
|
||||
from avalon import api
|
||||
|
||||
|
||||
class CollectTime(pyblish.api.ContextPlugin):
|
||||
"""Store global time at the time of publish"""
|
||||
|
||||
label = "Collect Current Time"
|
||||
order = pyblish.api.CollectorOrder
|
||||
|
||||
def process(self, context):
|
||||
context.data["time"] = api.time()
|
||||
448
pype/plugins/standalonepublish/publish/integrate.py
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
import os
|
||||
import logging
|
||||
import shutil
|
||||
|
||||
import errno
|
||||
import pyblish.api
|
||||
from avalon import api, io
|
||||
from avalon.vendor import filelink
|
||||
import clique
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IntegrateAsset(pyblish.api.InstancePlugin):
|
||||
"""Resolve any dependency issies
|
||||
|
||||
This plug-in resolves any paths which, if not updated might break
|
||||
the published file.
|
||||
|
||||
The order of families is important, when working with lookdev you want to
|
||||
first publish the texture, update the texture paths in the nodes and then
|
||||
publish the shading network. Same goes for file dependent assets.
|
||||
"""
|
||||
|
||||
label = "Integrate Asset"
|
||||
order = pyblish.api.IntegratorOrder
|
||||
families = ["animation",
|
||||
"camera",
|
||||
"look",
|
||||
"mayaAscii",
|
||||
"model",
|
||||
"pointcache",
|
||||
"vdbcache",
|
||||
"setdress",
|
||||
"assembly",
|
||||
"layout",
|
||||
"rig",
|
||||
"vrayproxy",
|
||||
"yetiRig",
|
||||
"yeticache",
|
||||
"nukescript",
|
||||
# "review",
|
||||
"workfile",
|
||||
"scene",
|
||||
"ass"]
|
||||
exclude_families = ["clip"]
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
if [ef for ef in self.exclude_families
|
||||
if instance.data["family"] in ef]:
|
||||
return
|
||||
|
||||
self.register(instance)
|
||||
|
||||
self.log.info("Integrating Asset in to the database ...")
|
||||
self.integrate(instance)
|
||||
|
||||
def register(self, instance):
|
||||
# Required environment variables
|
||||
PROJECT = api.Session["AVALON_PROJECT"]
|
||||
ASSET = instance.data.get("asset") or api.Session["AVALON_ASSET"]
|
||||
LOCATION = api.Session["AVALON_LOCATION"]
|
||||
|
||||
context = instance.context
|
||||
# Atomicity
|
||||
#
|
||||
# Guarantee atomic publishes - each asset contains
|
||||
# an identical set of members.
|
||||
# __
|
||||
# / o
|
||||
# / \
|
||||
# | o |
|
||||
# \ /
|
||||
# o __/
|
||||
#
|
||||
assert all(result["success"] for result in context.data["results"]), (
|
||||
"Atomicity not held, aborting.")
|
||||
|
||||
# Assemble
|
||||
#
|
||||
# |
|
||||
# v
|
||||
# ---> <----
|
||||
# ^
|
||||
# |
|
||||
#
|
||||
# stagingdir = instance.data.get("stagingDir")
|
||||
# assert stagingdir, ("Incomplete instance \"%s\": "
|
||||
# "Missing reference to staging area." % instance)
|
||||
|
||||
# extra check if stagingDir actually exists and is available
|
||||
|
||||
# self.log.debug("Establishing staging directory @ %s" % stagingdir)
|
||||
|
||||
# Ensure at least one file is set up for transfer in staging dir.
|
||||
files = instance.data.get("files", [])
|
||||
assert files, "Instance has no files to transfer"
|
||||
assert isinstance(files, (list, tuple)), (
|
||||
"Instance 'files' must be a list, got: {0}".format(files)
|
||||
)
|
||||
|
||||
project = io.find_one({"type": "project"})
|
||||
|
||||
asset = io.find_one({"type": "asset",
|
||||
"name": ASSET,
|
||||
"parent": project["_id"]})
|
||||
|
||||
assert all([project, asset]), ("Could not find current project or "
|
||||
"asset '%s'" % ASSET)
|
||||
|
||||
subset = self.get_subset(asset, instance)
|
||||
|
||||
# get next version
|
||||
latest_version = io.find_one({"type": "version",
|
||||
"parent": subset["_id"]},
|
||||
{"name": True},
|
||||
sort=[("name", -1)])
|
||||
|
||||
next_version = 1
|
||||
if latest_version is not None:
|
||||
next_version += latest_version["name"]
|
||||
|
||||
self.log.info("Verifying version from assumed destination")
|
||||
|
||||
# assumed_data = instance.data["assumedTemplateData"]
|
||||
# assumed_version = assumed_data["version"]
|
||||
# if assumed_version != next_version:
|
||||
# raise AttributeError("Assumed version 'v{0:03d}' does not match"
|
||||
# "next version in database "
|
||||
# "('v{1:03d}')".format(assumed_version,
|
||||
# next_version))
|
||||
|
||||
self.log.debug("Next version: v{0:03d}".format(next_version))
|
||||
|
||||
version_data = self.create_version_data(context, instance)
|
||||
version = self.create_version(subset=subset,
|
||||
version_number=next_version,
|
||||
locations=[LOCATION],
|
||||
data=version_data)
|
||||
|
||||
self.log.debug("Creating version ...")
|
||||
version_id = io.insert_one(version).inserted_id
|
||||
instance.data['version'] = version['name']
|
||||
# Write to disk
|
||||
# _
|
||||
# | |
|
||||
# _| |_
|
||||
# ____\ /
|
||||
# |\ \ / \
|
||||
# \ \ v \
|
||||
# \ \________.
|
||||
# \|________|
|
||||
#
|
||||
root = api.registered_root()
|
||||
hierarchy = ""
|
||||
parents = io.find_one({
|
||||
"type": 'asset',
|
||||
"name": ASSET
|
||||
})['data']['parents']
|
||||
if parents and len(parents) > 0:
|
||||
# hierarchy = os.path.sep.join(hierarchy)
|
||||
hierarchy = os.path.join(*parents)
|
||||
|
||||
template_data = {"root": root,
|
||||
"project": {"name": PROJECT,
|
||||
"code": project['data']['code']},
|
||||
"silo": asset['silo'],
|
||||
"asset": ASSET,
|
||||
"family": instance.data['family'],
|
||||
"subset": subset["name"],
|
||||
"version": int(version["name"]),
|
||||
"hierarchy": hierarchy}
|
||||
|
||||
template_publish = project["config"]["template"]["publish"]
|
||||
anatomy = instance.context.data['anatomy']
|
||||
|
||||
# Find the representations to transfer amongst the files
|
||||
# Each should be a single representation (as such, a single extension)
|
||||
representations = []
|
||||
destination_list = []
|
||||
if 'transfers' not in instance.data:
|
||||
instance.data['transfers'] = []
|
||||
|
||||
for idx, repre in enumerate(instance.data["representations"]):
|
||||
|
||||
# Collection
|
||||
# _______
|
||||
# |______|\
|
||||
# | |\|
|
||||
# | ||
|
||||
# | ||
|
||||
# | ||
|
||||
# |_______|
|
||||
#
|
||||
|
||||
files = repre['files']
|
||||
|
||||
if len(files) > 1:
|
||||
src_collections, remainder = clique.assemble(files)
|
||||
self.log.debug("dst_collections: {}".format(str(src_collections)))
|
||||
src_collection = src_collections[0]
|
||||
# Assert that each member has identical suffix
|
||||
src_head = src_collection.format("{head}")
|
||||
src_tail = ext = src_collection.format("{tail}")
|
||||
|
||||
test_dest_files = list()
|
||||
for i in [1, 2]:
|
||||
template_data["representation"] = src_tail[1:]
|
||||
template_data["frame"] = src_collection.format(
|
||||
"{padding}") % i
|
||||
anatomy_filled = anatomy.format(template_data)
|
||||
test_dest_files.append(anatomy_filled["publish"]["path"])
|
||||
|
||||
dst_collections, remainder = clique.assemble(test_dest_files)
|
||||
dst_collection = dst_collections[0]
|
||||
dst_head = dst_collection.format("{head}")
|
||||
dst_tail = dst_collection.format("{tail}")
|
||||
|
||||
instance.data["representations"][idx]['published_path'] = dst_collection.format()
|
||||
|
||||
for i in src_collection.indexes:
|
||||
src_padding = src_collection.format("{padding}") % i
|
||||
src_file_name = "{0}{1}{2}".format(
|
||||
src_head, src_padding, src_tail)
|
||||
dst_padding = dst_collection.format("{padding}") % i
|
||||
dst = "{0}{1}{2}".format(dst_head, dst_padding, dst_tail)
|
||||
|
||||
# src = os.path.join(stagingdir, src_file_name)
|
||||
src = src_file_name
|
||||
self.log.debug("source: {}".format(src))
|
||||
|
||||
instance.data["transfers"].append([src, dst])
|
||||
|
||||
else:
|
||||
# Single file
|
||||
# _______
|
||||
# | |\
|
||||
# | |
|
||||
# | |
|
||||
# | |
|
||||
# |_______|
|
||||
#
|
||||
fname = files[0]
|
||||
# assert not os.path.isabs(fname), (
|
||||
# "Given file name is a full path"
|
||||
# )
|
||||
# _, ext = os.path.splitext(fname)
|
||||
|
||||
template_data["representation"] = repre['representation']
|
||||
|
||||
# src = os.path.join(stagingdir, fname)
|
||||
src = fname
|
||||
anatomy_filled = anatomy.format(template_data)
|
||||
dst = anatomy_filled["publish"]["path"]
|
||||
|
||||
instance.data["transfers"].append([src, dst])
|
||||
template = anatomy.templates["publish"]["path"]
|
||||
instance.data["representations"][idx]['published_path'] = dst
|
||||
|
||||
representation = {
|
||||
"schema": "pype:representation-2.0",
|
||||
"type": "representation",
|
||||
"parent": version_id,
|
||||
"name": repre['representation'],
|
||||
"data": {'path': dst, 'template': template},
|
||||
"dependencies": instance.data.get("dependencies", "").split(),
|
||||
|
||||
# Imprint shortcut to context
|
||||
# for performance reasons.
|
||||
"context": {
|
||||
"root": root,
|
||||
"project": {"name": PROJECT,
|
||||
"code": project['data']['code']},
|
||||
# 'task': api.Session["AVALON_TASK"],
|
||||
"silo": asset['silo'],
|
||||
"asset": ASSET,
|
||||
"family": instance.data['family'],
|
||||
"subset": subset["name"],
|
||||
"version": version["name"],
|
||||
"hierarchy": hierarchy,
|
||||
# "representation": repre['representation']
|
||||
}
|
||||
}
|
||||
|
||||
destination_list.append(dst)
|
||||
instance.data['destination_list'] = destination_list
|
||||
representations.append(representation)
|
||||
|
||||
self.log.info("Registering {} items".format(len(representations)))
|
||||
|
||||
io.insert_many(representations)
|
||||
|
||||
def integrate(self, instance):
|
||||
"""Move the files
|
||||
|
||||
Through `instance.data["transfers"]`
|
||||
|
||||
Args:
|
||||
instance: the instance to integrate
|
||||
"""
|
||||
|
||||
transfers = instance.data.get("transfers", list())
|
||||
|
||||
for src, dest in transfers:
|
||||
self.log.info("Copying file .. {} -> {}".format(src, dest))
|
||||
self.copy_file(src, dest)
|
||||
|
||||
# Produce hardlinked copies
|
||||
# Note: hardlink can only be produced between two files on the same
|
||||
# server/disk and editing one of the two will edit both files at once.
|
||||
# As such it is recommended to only make hardlinks between static files
|
||||
# to ensure publishes remain safe and non-edited.
|
||||
hardlinks = instance.data.get("hardlinks", list())
|
||||
for src, dest in hardlinks:
|
||||
self.log.info("Hardlinking file .. {} -> {}".format(src, dest))
|
||||
self.hardlink_file(src, dest)
|
||||
|
||||
def copy_file(self, src, dst):
|
||||
""" Copy given source to destination
|
||||
|
||||
Arguments:
|
||||
src (str): the source file which needs to be copied
|
||||
dst (str): the destination of the sourc file
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
dirname = os.path.dirname(dst)
|
||||
try:
|
||||
os.makedirs(dirname)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EEXIST:
|
||||
pass
|
||||
else:
|
||||
self.log.critical("An unexpected error occurred.")
|
||||
raise
|
||||
|
||||
shutil.copy(src, dst)
|
||||
|
||||
def hardlink_file(self, src, dst):
|
||||
|
||||
dirname = os.path.dirname(dst)
|
||||
try:
|
||||
os.makedirs(dirname)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EEXIST:
|
||||
pass
|
||||
else:
|
||||
self.log.critical("An unexpected error occurred.")
|
||||
raise
|
||||
|
||||
filelink.create(src, dst, filelink.HARDLINK)
|
||||
|
||||
def get_subset(self, asset, instance):
|
||||
|
||||
subset = io.find_one({"type": "subset",
|
||||
"parent": asset["_id"],
|
||||
"name": instance.data["subset"]})
|
||||
|
||||
if subset is None:
|
||||
subset_name = instance.data["subset"]
|
||||
self.log.info("Subset '%s' not found, creating.." % subset_name)
|
||||
|
||||
_id = io.insert_one({
|
||||
"schema": "avalon-core:subset-2.0",
|
||||
"type": "subset",
|
||||
"name": subset_name,
|
||||
"data": {},
|
||||
"parent": asset["_id"]
|
||||
}).inserted_id
|
||||
|
||||
subset = io.find_one({"_id": _id})
|
||||
|
||||
return subset
|
||||
|
||||
def create_version(self, subset, version_number, locations, data=None):
|
||||
""" Copy given source to destination
|
||||
|
||||
Args:
|
||||
subset (dict): the registered subset of the asset
|
||||
version_number (int): the version number
|
||||
locations (list): the currently registered locations
|
||||
|
||||
Returns:
|
||||
dict: collection of data to create a version
|
||||
"""
|
||||
# Imprint currently registered location
|
||||
version_locations = [location for location in locations if
|
||||
location is not None]
|
||||
|
||||
return {"schema": "avalon-core:version-2.0",
|
||||
"type": "version",
|
||||
"parent": subset["_id"],
|
||||
"name": version_number,
|
||||
"locations": version_locations,
|
||||
"data": data}
|
||||
|
||||
def create_version_data(self, context, instance):
|
||||
"""Create the data collection for the version
|
||||
|
||||
Args:
|
||||
context: the current context
|
||||
instance: the current instance being published
|
||||
|
||||
Returns:
|
||||
dict: the required information with instance.data as key
|
||||
"""
|
||||
|
||||
families = []
|
||||
current_families = instance.data.get("families", list())
|
||||
instance_family = instance.data.get("family", None)
|
||||
|
||||
if instance_family is not None:
|
||||
families.append(instance_family)
|
||||
families += current_families
|
||||
|
||||
self.log.debug("Registered root: {}".format(api.registered_root()))
|
||||
# # create relative source path for DB
|
||||
# try:
|
||||
# source = instance.data['source']
|
||||
# except KeyError:
|
||||
# source = context.data["currentFile"]
|
||||
#
|
||||
# relative_path = os.path.relpath(source, api.registered_root())
|
||||
# source = os.path.join("{root}", relative_path).replace("\\", "/")
|
||||
|
||||
source = "standalone"
|
||||
|
||||
# self.log.debug("Source: {}".format(source))
|
||||
version_data = {"families": families,
|
||||
"time": context.data["time"],
|
||||
"author": context.data["user"],
|
||||
"source": source,
|
||||
"comment": context.data.get("comment"),
|
||||
"machine": context.data.get("machine"),
|
||||
"fps": context.data.get("fps")}
|
||||
|
||||
# Include optional data if present in
|
||||
optionals = [
|
||||
"startFrame", "endFrame", "step", "handles", "sourceHashes"
|
||||
]
|
||||
for key in optionals:
|
||||
if key in instance.data:
|
||||
version_data[key] = instance.data[key]
|
||||
|
||||
return version_data
|
||||
315
pype/plugins/standalonepublish/publish/integrate_ftrack_api.py
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
import os
|
||||
import sys
|
||||
import pyblish.api
|
||||
import clique
|
||||
|
||||
|
||||
class IntegrateFtrackApi(pyblish.api.InstancePlugin):
|
||||
""" Commit components to server. """
|
||||
|
||||
order = pyblish.api.IntegratorOrder+0.499
|
||||
label = "Integrate Ftrack Api"
|
||||
families = ["ftrack"]
|
||||
|
||||
def query(self, entitytype, data):
|
||||
""" Generate a query expression from data supplied.
|
||||
|
||||
If a value is not a string, we'll add the id of the entity to the
|
||||
query.
|
||||
|
||||
Args:
|
||||
entitytype (str): The type of entity to query.
|
||||
data (dict): The data to identify the entity.
|
||||
exclusions (list): All keys to exclude from the query.
|
||||
|
||||
Returns:
|
||||
str: String query to use with "session.query"
|
||||
"""
|
||||
queries = []
|
||||
if sys.version_info[0] < 3:
|
||||
for key, value in data.iteritems():
|
||||
if not isinstance(value, (basestring, int)):
|
||||
self.log.info("value: {}".format(value))
|
||||
if "id" in value.keys():
|
||||
queries.append(
|
||||
"{0}.id is \"{1}\"".format(key, value["id"])
|
||||
)
|
||||
else:
|
||||
queries.append("{0} is \"{1}\"".format(key, value))
|
||||
else:
|
||||
for key, value in data.items():
|
||||
if not isinstance(value, (str, int)):
|
||||
self.log.info("value: {}".format(value))
|
||||
if "id" in value.keys():
|
||||
queries.append(
|
||||
"{0}.id is \"{1}\"".format(key, value["id"])
|
||||
)
|
||||
else:
|
||||
queries.append("{0} is \"{1}\"".format(key, value))
|
||||
|
||||
query = (
|
||||
"select id from " + entitytype + " where " + " and ".join(queries)
|
||||
)
|
||||
self.log.debug(query)
|
||||
return query
|
||||
|
||||
def process(self, instance):
|
||||
|
||||
session = instance.context.data["ftrackSession"]
|
||||
if instance.context.data.get("ftrackTask"):
|
||||
task = instance.context.data["ftrackTask"]
|
||||
name = task['full_name']
|
||||
parent = task["parent"]
|
||||
elif instance.context.data.get("ftrackEntity"):
|
||||
task = None
|
||||
name = instance.context.data.get("ftrackEntity")['name']
|
||||
parent = instance.context.data.get("ftrackEntity")
|
||||
|
||||
info_msg = "Created new {entity_type} with data: {data}"
|
||||
info_msg += ", metadata: {metadata}."
|
||||
|
||||
# Iterate over components and publish
|
||||
for data in instance.data.get("ftrackComponentsList", []):
|
||||
|
||||
# AssetType
|
||||
# Get existing entity.
|
||||
assettype_data = {"short": "upload"}
|
||||
assettype_data.update(data.get("assettype_data", {}))
|
||||
self.log.debug("data: {}".format(data))
|
||||
|
||||
assettype_entity = session.query(
|
||||
self.query("AssetType", assettype_data)
|
||||
).first()
|
||||
|
||||
# Create a new entity if none exits.
|
||||
if not assettype_entity:
|
||||
assettype_entity = session.create("AssetType", assettype_data)
|
||||
self.log.debug(
|
||||
"Created new AssetType with data: ".format(assettype_data)
|
||||
)
|
||||
|
||||
# Asset
|
||||
# Get existing entity.
|
||||
asset_data = {
|
||||
"name": name,
|
||||
"type": assettype_entity,
|
||||
"parent": parent,
|
||||
}
|
||||
asset_data.update(data.get("asset_data", {}))
|
||||
|
||||
asset_entity = session.query(
|
||||
self.query("Asset", asset_data)
|
||||
).first()
|
||||
|
||||
self.log.info("asset entity: {}".format(asset_entity))
|
||||
|
||||
# Extracting metadata, and adding after entity creation. This is
|
||||
# due to a ftrack_api bug where you can't add metadata on creation.
|
||||
asset_metadata = asset_data.pop("metadata", {})
|
||||
|
||||
# Create a new entity if none exits.
|
||||
if not asset_entity:
|
||||
asset_entity = session.create("Asset", asset_data)
|
||||
self.log.debug(
|
||||
info_msg.format(
|
||||
entity_type="Asset",
|
||||
data=asset_data,
|
||||
metadata=asset_metadata
|
||||
)
|
||||
)
|
||||
|
||||
# Adding metadata
|
||||
existing_asset_metadata = asset_entity["metadata"]
|
||||
existing_asset_metadata.update(asset_metadata)
|
||||
asset_entity["metadata"] = existing_asset_metadata
|
||||
|
||||
# AssetVersion
|
||||
# Get existing entity.
|
||||
assetversion_data = {
|
||||
"version": 0,
|
||||
"asset": asset_entity,
|
||||
}
|
||||
if task:
|
||||
assetversion_data['task'] = task
|
||||
|
||||
assetversion_data.update(data.get("assetversion_data", {}))
|
||||
|
||||
assetversion_entity = session.query(
|
||||
self.query("AssetVersion", assetversion_data)
|
||||
).first()
|
||||
|
||||
# Extracting metadata, and adding after entity creation. This is
|
||||
# due to a ftrack_api bug where you can't add metadata on creation.
|
||||
assetversion_metadata = assetversion_data.pop("metadata", {})
|
||||
|
||||
# Create a new entity if none exits.
|
||||
if not assetversion_entity:
|
||||
assetversion_entity = session.create(
|
||||
"AssetVersion", assetversion_data
|
||||
)
|
||||
self.log.debug(
|
||||
info_msg.format(
|
||||
entity_type="AssetVersion",
|
||||
data=assetversion_data,
|
||||
metadata=assetversion_metadata
|
||||
)
|
||||
)
|
||||
|
||||
# Adding metadata
|
||||
existing_assetversion_metadata = assetversion_entity["metadata"]
|
||||
existing_assetversion_metadata.update(assetversion_metadata)
|
||||
assetversion_entity["metadata"] = existing_assetversion_metadata
|
||||
|
||||
# Have to commit the version and asset, because location can't
|
||||
# determine the final location without.
|
||||
session.commit()
|
||||
|
||||
# Component
|
||||
# Get existing entity.
|
||||
component_data = {
|
||||
"name": "main",
|
||||
"version": assetversion_entity
|
||||
}
|
||||
component_data.update(data.get("component_data", {}))
|
||||
|
||||
component_entity = session.query(
|
||||
self.query("Component", component_data)
|
||||
).first()
|
||||
|
||||
component_overwrite = data.get("component_overwrite", False)
|
||||
location = data.get("component_location", session.pick_location())
|
||||
|
||||
# Overwrite existing component data if requested.
|
||||
if component_entity and component_overwrite:
|
||||
|
||||
origin_location = session.query(
|
||||
"Location where name is \"ftrack.origin\""
|
||||
).one()
|
||||
|
||||
# Removing existing members from location
|
||||
components = list(component_entity.get("members", []))
|
||||
components += [component_entity]
|
||||
for component in components:
|
||||
for loc in component["component_locations"]:
|
||||
if location["id"] == loc["location_id"]:
|
||||
location.remove_component(
|
||||
component, recursive=False
|
||||
)
|
||||
|
||||
# Deleting existing members on component entity
|
||||
for member in component_entity.get("members", []):
|
||||
session.delete(member)
|
||||
del(member)
|
||||
|
||||
session.commit()
|
||||
|
||||
# Reset members in memory
|
||||
if "members" in component_entity.keys():
|
||||
component_entity["members"] = []
|
||||
|
||||
# Add components to origin location
|
||||
try:
|
||||
collection = clique.parse(data["component_path"])
|
||||
except ValueError:
|
||||
# Assume its a single file
|
||||
# Changing file type
|
||||
name, ext = os.path.splitext(data["component_path"])
|
||||
component_entity["file_type"] = ext
|
||||
|
||||
origin_location.add_component(
|
||||
component_entity, data["component_path"]
|
||||
)
|
||||
else:
|
||||
# Changing file type
|
||||
component_entity["file_type"] = collection.format("{tail}")
|
||||
|
||||
# Create member components for sequence.
|
||||
for member_path in collection:
|
||||
|
||||
size = 0
|
||||
try:
|
||||
size = os.path.getsize(member_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
name = collection.match(member_path).group("index")
|
||||
|
||||
member_data = {
|
||||
"name": name,
|
||||
"container": component_entity,
|
||||
"size": size,
|
||||
"file_type": os.path.splitext(member_path)[-1]
|
||||
}
|
||||
|
||||
component = session.create(
|
||||
"FileComponent", member_data
|
||||
)
|
||||
origin_location.add_component(
|
||||
component, member_path, recursive=False
|
||||
)
|
||||
component_entity["members"].append(component)
|
||||
|
||||
# Add components to location.
|
||||
location.add_component(
|
||||
component_entity, origin_location, recursive=True
|
||||
)
|
||||
|
||||
data["component"] = component_entity
|
||||
msg = "Overwriting Component with path: {0}, data: {1}, "
|
||||
msg += "location: {2}"
|
||||
self.log.info(
|
||||
msg.format(
|
||||
data["component_path"],
|
||||
component_data,
|
||||
location
|
||||
)
|
||||
)
|
||||
|
||||
# Extracting metadata, and adding after entity creation. This is
|
||||
# due to a ftrack_api bug where you can't add metadata on creation.
|
||||
component_metadata = component_data.pop("metadata", {})
|
||||
|
||||
# Create new component if none exists.
|
||||
new_component = False
|
||||
if not component_entity:
|
||||
component_entity = assetversion_entity.create_component(
|
||||
data["component_path"],
|
||||
data=component_data,
|
||||
location=location
|
||||
)
|
||||
data["component"] = component_entity
|
||||
msg = "Created new Component with path: {0}, data: {1}"
|
||||
msg += ", metadata: {2}, location: {3}"
|
||||
self.log.info(
|
||||
msg.format(
|
||||
data["component_path"],
|
||||
component_data,
|
||||
component_metadata,
|
||||
location
|
||||
)
|
||||
)
|
||||
new_component = True
|
||||
|
||||
# Adding metadata
|
||||
existing_component_metadata = component_entity["metadata"]
|
||||
existing_component_metadata.update(component_metadata)
|
||||
component_entity["metadata"] = existing_component_metadata
|
||||
|
||||
# if component_data['name'] = 'ftrackreview-mp4-mp4':
|
||||
# assetversion_entity["thumbnail_id"]
|
||||
|
||||
# Setting assetversion thumbnail
|
||||
if data.get("thumbnail", False):
|
||||
assetversion_entity["thumbnail_id"] = component_entity["id"]
|
||||
|
||||
# Inform user about no changes to the database.
|
||||
if (component_entity and not component_overwrite and
|
||||
not new_component):
|
||||
data["component"] = component_entity
|
||||
self.log.info(
|
||||
"Found existing component, and no request to overwrite. "
|
||||
"Nothing has been changed."
|
||||
)
|
||||
else:
|
||||
# Commit changes.
|
||||
session.commit()
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
import pyblish.api
|
||||
import os
|
||||
import json
|
||||
|
||||
|
||||
class IntegrateFtrackInstance(pyblish.api.InstancePlugin):
|
||||
"""Collect ftrack component data
|
||||
|
||||
Add ftrack component list to instance.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
order = pyblish.api.IntegratorOrder + 0.48
|
||||
label = 'Integrate Ftrack Component'
|
||||
families = ["ftrack"]
|
||||
|
||||
family_mapping = {'camera': 'cam',
|
||||
'look': 'look',
|
||||
'mayaAscii': 'scene',
|
||||
'model': 'geo',
|
||||
'rig': 'rig',
|
||||
'setdress': 'setdress',
|
||||
'pointcache': 'cache',
|
||||
'write': 'img',
|
||||
'render': 'render',
|
||||
'nukescript': 'comp',
|
||||
'review': 'mov'}
|
||||
|
||||
def process(self, instance):
|
||||
self.log.debug('instance {}'.format(instance))
|
||||
|
||||
if instance.data.get('version'):
|
||||
version_number = int(instance.data.get('version'))
|
||||
|
||||
family = instance.data['family'].lower()
|
||||
|
||||
asset_type = ''
|
||||
asset_type = self.family_mapping[family]
|
||||
|
||||
componentList = []
|
||||
ft_session = instance.context.data["ftrackSession"]
|
||||
|
||||
components = instance.data['representations']
|
||||
|
||||
for comp in components:
|
||||
self.log.debug('component {}'.format(comp))
|
||||
# filename, ext = os.path.splitext(file)
|
||||
# self.log.debug('dest ext: ' + ext)
|
||||
|
||||
# ext = comp['Context']
|
||||
|
||||
if comp['thumbnail']:
|
||||
location = ft_session.query(
|
||||
'Location where name is "ftrack.server"').one()
|
||||
component_data = {
|
||||
"name": "thumbnail" # Default component name is "main".
|
||||
}
|
||||
elif comp['preview']:
|
||||
if not instance.data.get('startFrameReview'):
|
||||
instance.data['startFrameReview'] = instance.data['startFrame']
|
||||
if not instance.data.get('endFrameReview'):
|
||||
instance.data['endFrameReview'] = instance.data['endFrame']
|
||||
location = ft_session.query(
|
||||
'Location where name is "ftrack.server"').one()
|
||||
component_data = {
|
||||
# Default component name is "main".
|
||||
"name": "ftrackreview-mp4",
|
||||
"metadata": {'ftr_meta': json.dumps({
|
||||
'frameIn': int(instance.data['startFrameReview']),
|
||||
'frameOut': int(instance.data['endFrameReview']),
|
||||
'frameRate': 25.0})}
|
||||
}
|
||||
else:
|
||||
component_data = {
|
||||
"name": comp['representation'] # Default component name is "main".
|
||||
}
|
||||
location = ft_session.query(
|
||||
'Location where name is "ftrack.unmanaged"').one()
|
||||
|
||||
self.log.debug('location {}'.format(location))
|
||||
|
||||
componentList.append({"assettype_data": {
|
||||
"short": asset_type,
|
||||
},
|
||||
"asset_data": {
|
||||
"name": instance.data["subset"],
|
||||
},
|
||||
"assetversion_data": {
|
||||
"version": version_number,
|
||||
},
|
||||
"component_data": component_data,
|
||||
"component_path": comp['published_path'],
|
||||
'component_location': location,
|
||||
"component_overwrite": False,
|
||||
"thumbnail": comp['thumbnail']
|
||||
}
|
||||
)
|
||||
|
||||
self.log.debug('componentsList: {}'.format(str(componentList)))
|
||||
instance.data["ftrackComponentsList"] = componentList
|
||||
|
|
@ -0,0 +1,436 @@
|
|||
import os
|
||||
import logging
|
||||
import shutil
|
||||
import clique
|
||||
|
||||
import errno
|
||||
import pyblish.api
|
||||
from avalon import api, io
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IntegrateFrames(pyblish.api.InstancePlugin):
|
||||
"""Resolve any dependency issies
|
||||
|
||||
This plug-in resolves any paths which, if not updated might break
|
||||
the published file.
|
||||
|
||||
The order of families is important, when working with lookdev you want to
|
||||
first publish the texture, update the texture paths in the nodes and then
|
||||
publish the shading network. Same goes for file dependent assets.
|
||||
"""
|
||||
|
||||
label = "Integrate Frames"
|
||||
order = pyblish.api.IntegratorOrder
|
||||
families = [
|
||||
"imagesequence",
|
||||
"render",
|
||||
"write",
|
||||
"source",
|
||||
'review']
|
||||
|
||||
family_targets = [".frames", ".local", ".review", "review", "imagesequence", "render", "source"]
|
||||
exclude_families = ["clip"]
|
||||
|
||||
def process(self, instance):
|
||||
if [ef for ef in self.exclude_families
|
||||
if instance.data["family"] in ef]:
|
||||
return
|
||||
|
||||
families = [f for f in instance.data["families"]
|
||||
for search in self.family_targets
|
||||
if search in f]
|
||||
|
||||
if not families:
|
||||
return
|
||||
|
||||
self.register(instance)
|
||||
|
||||
# self.log.info("Integrating Asset in to the database ...")
|
||||
# self.log.info("instance.data: {}".format(instance.data))
|
||||
if instance.data.get('transfer', True):
|
||||
self.integrate(instance)
|
||||
|
||||
def register(self, instance):
|
||||
|
||||
# Required environment variables
|
||||
PROJECT = api.Session["AVALON_PROJECT"]
|
||||
ASSET = instance.data.get("asset") or api.Session["AVALON_ASSET"]
|
||||
LOCATION = api.Session["AVALON_LOCATION"]
|
||||
|
||||
context = instance.context
|
||||
# Atomicity
|
||||
#
|
||||
# Guarantee atomic publishes - each asset contains
|
||||
# an identical set of members.
|
||||
# __
|
||||
# / o
|
||||
# / \
|
||||
# | o |
|
||||
# \ /
|
||||
# o __/
|
||||
#
|
||||
assert all(result["success"] for result in context.data["results"]), (
|
||||
"Atomicity not held, aborting.")
|
||||
|
||||
# Assemble
|
||||
#
|
||||
# |
|
||||
# v
|
||||
# ---> <----
|
||||
# ^
|
||||
# |
|
||||
#
|
||||
# stagingdir = instance.data.get("stagingDir")
|
||||
# assert stagingdir, ("Incomplete instance \"%s\": "
|
||||
# "Missing reference to staging area." % instance)
|
||||
|
||||
# extra check if stagingDir actually exists and is available
|
||||
|
||||
# self.log.debug("Establishing staging directory @ %s" % stagingdir)
|
||||
|
||||
project = io.find_one({"type": "project"})
|
||||
|
||||
asset = io.find_one({"type": "asset",
|
||||
"name": ASSET,
|
||||
"parent": project["_id"]})
|
||||
|
||||
assert all([project, asset]), ("Could not find current project or "
|
||||
"asset '%s'" % ASSET)
|
||||
|
||||
subset = self.get_subset(asset, instance)
|
||||
|
||||
# get next version
|
||||
latest_version = io.find_one({"type": "version",
|
||||
"parent": subset["_id"]},
|
||||
{"name": True},
|
||||
sort=[("name", -1)])
|
||||
|
||||
next_version = 1
|
||||
if latest_version is not None:
|
||||
next_version += latest_version["name"]
|
||||
|
||||
self.log.info("Verifying version from assumed destination")
|
||||
|
||||
# assumed_data = instance.data["assumedTemplateData"]
|
||||
# assumed_version = assumed_data["version"]
|
||||
# if assumed_version != next_version:
|
||||
# raise AttributeError("Assumed version 'v{0:03d}' does not match"
|
||||
# "next version in database "
|
||||
# "('v{1:03d}')".format(assumed_version,
|
||||
# next_version))
|
||||
|
||||
if instance.data.get('version'):
|
||||
next_version = int(instance.data.get('version'))
|
||||
|
||||
instance.data['version'] = next_version
|
||||
|
||||
self.log.debug("Next version: v{0:03d}".format(next_version))
|
||||
|
||||
version_data = self.create_version_data(context, instance)
|
||||
version = self.create_version(subset=subset,
|
||||
version_number=next_version,
|
||||
locations=[LOCATION],
|
||||
data=version_data)
|
||||
|
||||
self.log.debug("Creating version ...")
|
||||
version_id = io.insert_one(version).inserted_id
|
||||
|
||||
# Write to disk
|
||||
# _
|
||||
# | |
|
||||
# _| |_
|
||||
# ____\ /
|
||||
# |\ \ / \
|
||||
# \ \ v \
|
||||
# \ \________.
|
||||
# \|________|
|
||||
#
|
||||
root = api.registered_root()
|
||||
hierarchy = ""
|
||||
parents = io.find_one({"type": 'asset', "name": ASSET})[
|
||||
'data']['parents']
|
||||
if parents and len(parents) > 0:
|
||||
# hierarchy = os.path.sep.join(hierarchy)
|
||||
hierarchy = os.path.join(*parents)
|
||||
|
||||
template_data = {"root": root,
|
||||
"project": {"name": PROJECT,
|
||||
"code": project['data']['code']},
|
||||
"silo": asset['silo'],
|
||||
"task": api.Session["AVALON_TASK"],
|
||||
"asset": ASSET,
|
||||
"family": instance.data['family'],
|
||||
"subset": subset["name"],
|
||||
"version": int(version["name"]),
|
||||
"hierarchy": hierarchy}
|
||||
|
||||
# template_publish = project["config"]["template"]["publish"]
|
||||
anatomy = instance.context.data['anatomy']
|
||||
|
||||
# Find the representations to transfer amongst the files
|
||||
# Each should be a single representation (as such, a single extension)
|
||||
representations = []
|
||||
destination_list = []
|
||||
|
||||
if 'transfers' not in instance.data:
|
||||
instance.data['transfers'] = []
|
||||
|
||||
# for repre in instance.data["representations"]:
|
||||
for idx, repre in enumerate(instance.data["representations"]):
|
||||
# Collection
|
||||
# _______
|
||||
# |______|\
|
||||
# | |\|
|
||||
# | ||
|
||||
# | ||
|
||||
# | ||
|
||||
# |_______|
|
||||
#
|
||||
|
||||
files = repre['files']
|
||||
|
||||
if len(files) > 1:
|
||||
|
||||
src_collections, remainder = clique.assemble(files)
|
||||
self.log.debug("dst_collections: {}".format(str(src_collections)))
|
||||
src_collection = src_collections[0]
|
||||
# Assert that each member has identical suffix
|
||||
src_head = src_collection.format("{head}")
|
||||
src_tail = ext = src_collection.format("{tail}")
|
||||
|
||||
test_dest_files = list()
|
||||
for i in [1, 2]:
|
||||
template_data["representation"] = repre['representation']
|
||||
template_data["frame"] = src_collection.format(
|
||||
"{padding}") % i
|
||||
anatomy_filled = anatomy.format(template_data)
|
||||
test_dest_files.append(anatomy_filled["render"]["path"])
|
||||
|
||||
dst_collections, remainder = clique.assemble(test_dest_files)
|
||||
dst_collection = dst_collections[0]
|
||||
dst_head = dst_collection.format("{head}")
|
||||
dst_tail = dst_collection.format("{tail}")
|
||||
|
||||
instance.data["representations"][idx]['published_path'] = dst_collection.format()
|
||||
|
||||
for i in src_collection.indexes:
|
||||
src_padding = src_collection.format("{padding}") % i
|
||||
src_file_name = "{0}{1}{2}".format(
|
||||
src_head, src_padding, src_tail)
|
||||
dst_padding = dst_collection.format("{padding}") % i
|
||||
dst = "{0}{1}{2}".format(dst_head, dst_padding, dst_tail)
|
||||
|
||||
# src = os.path.join(stagingdir, src_file_name)
|
||||
src = src_file_name
|
||||
self.log.debug("source: {}".format(src))
|
||||
|
||||
instance.data["transfers"].append([src, dst])
|
||||
|
||||
else:
|
||||
# Single file
|
||||
# _______
|
||||
# | |\
|
||||
# | |
|
||||
# | |
|
||||
# | |
|
||||
# |_______|
|
||||
#
|
||||
|
||||
template_data.pop("frame", None)
|
||||
|
||||
fname = files[0]
|
||||
|
||||
self.log.info("fname: {}".format(fname))
|
||||
|
||||
# assert not os.path.isabs(fname), (
|
||||
# "Given file name is a full path"
|
||||
# )
|
||||
# _, ext = os.path.splitext(fname)
|
||||
|
||||
template_data["representation"] = repre['representation']
|
||||
|
||||
# src = os.path.join(stagingdir, fname)
|
||||
src = src_file_name
|
||||
|
||||
anatomy_filled = anatomy.format(template_data)
|
||||
dst = anatomy_filled["render"]["path"]
|
||||
|
||||
instance.data["transfers"].append([src, dst])
|
||||
instance.data["representations"][idx]['published_path'] = dst
|
||||
|
||||
if repre['ext'] not in ["jpeg", "jpg", "mov", "mp4", "wav"]:
|
||||
template_data["frame"] = "#" * int(anatomy_filled["render"]["padding"])
|
||||
|
||||
anatomy_filled = anatomy.format(template_data)
|
||||
path_to_save = anatomy_filled["render"]["path"]
|
||||
template = anatomy.templates["render"]["path"]
|
||||
|
||||
self.log.debug("path_to_save: {}".format(path_to_save))
|
||||
|
||||
representation = {
|
||||
"schema": "pype:representation-2.0",
|
||||
"type": "representation",
|
||||
"parent": version_id,
|
||||
"name": repre['representation'],
|
||||
"data": {'path': path_to_save, 'template': template},
|
||||
"dependencies": instance.data.get("dependencies", "").split(),
|
||||
|
||||
# Imprint shortcut to context
|
||||
# for performance reasons.
|
||||
"context": {
|
||||
"root": root,
|
||||
"project": {
|
||||
"name": PROJECT,
|
||||
"code": project['data']['code']
|
||||
},
|
||||
"task": api.Session["AVALON_TASK"],
|
||||
"silo": asset['silo'],
|
||||
"asset": ASSET,
|
||||
"family": instance.data['family'],
|
||||
"subset": subset["name"],
|
||||
"version": int(version["name"]),
|
||||
"hierarchy": hierarchy,
|
||||
"representation": repre['representation']
|
||||
}
|
||||
}
|
||||
|
||||
destination_list.append(dst)
|
||||
instance.data['destination_list'] = destination_list
|
||||
representations.append(representation)
|
||||
|
||||
self.log.info("Registering {} items".format(len(representations)))
|
||||
io.insert_many(representations)
|
||||
|
||||
def integrate(self, instance):
|
||||
"""Move the files
|
||||
|
||||
Through `instance.data["transfers"]`
|
||||
|
||||
Args:
|
||||
instance: the instance to integrate
|
||||
"""
|
||||
|
||||
transfers = instance.data["transfers"]
|
||||
|
||||
for src, dest in transfers:
|
||||
src = os.path.normpath(src)
|
||||
dest = os.path.normpath(dest)
|
||||
if src in dest:
|
||||
continue
|
||||
|
||||
self.log.info("Copying file .. {} -> {}".format(src, dest))
|
||||
self.copy_file(src, dest)
|
||||
|
||||
def copy_file(self, src, dst):
|
||||
""" Copy given source to destination
|
||||
|
||||
Arguments:
|
||||
src (str): the source file which needs to be copied
|
||||
dst (str): the destination of the sourc file
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
dirname = os.path.dirname(dst)
|
||||
try:
|
||||
os.makedirs(dirname)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EEXIST:
|
||||
pass
|
||||
else:
|
||||
self.log.critical("An unexpected error occurred.")
|
||||
raise
|
||||
|
||||
shutil.copy(src, dst)
|
||||
|
||||
def get_subset(self, asset, instance):
|
||||
|
||||
subset = io.find_one({"type": "subset",
|
||||
"parent": asset["_id"],
|
||||
"name": instance.data["subset"]})
|
||||
|
||||
if subset is None:
|
||||
subset_name = instance.data["subset"]
|
||||
self.log.info("Subset '%s' not found, creating.." % subset_name)
|
||||
|
||||
_id = io.insert_one({
|
||||
"schema": "pype:subset-2.0",
|
||||
"type": "subset",
|
||||
"name": subset_name,
|
||||
"data": {},
|
||||
"parent": asset["_id"]
|
||||
}).inserted_id
|
||||
|
||||
subset = io.find_one({"_id": _id})
|
||||
|
||||
return subset
|
||||
|
||||
def create_version(self, subset, version_number, locations, data=None):
|
||||
""" Copy given source to destination
|
||||
|
||||
Args:
|
||||
subset (dict): the registered subset of the asset
|
||||
version_number (int): the version number
|
||||
locations (list): the currently registered locations
|
||||
|
||||
Returns:
|
||||
dict: collection of data to create a version
|
||||
"""
|
||||
# Imprint currently registered location
|
||||
version_locations = [location for location in locations if
|
||||
location is not None]
|
||||
|
||||
return {"schema": "pype:version-2.0",
|
||||
"type": "version",
|
||||
"parent": subset["_id"],
|
||||
"name": version_number,
|
||||
"locations": version_locations,
|
||||
"data": data}
|
||||
|
||||
def create_version_data(self, context, instance):
|
||||
"""Create the data collection for the version
|
||||
|
||||
Args:
|
||||
context: the current context
|
||||
instance: the current instance being published
|
||||
|
||||
Returns:
|
||||
dict: the required information with instance.data as key
|
||||
"""
|
||||
|
||||
families = []
|
||||
current_families = instance.data.get("families", list())
|
||||
instance_family = instance.data.get("family", None)
|
||||
|
||||
if instance_family is not None:
|
||||
families.append(instance_family)
|
||||
families += current_families
|
||||
|
||||
# try:
|
||||
# source = instance.data['source']
|
||||
# except KeyError:
|
||||
# source = context.data["currentFile"]
|
||||
#
|
||||
# relative_path = os.path.relpath(source, api.registered_root())
|
||||
# source = os.path.join("{root}", relative_path).replace("\\", "/")
|
||||
|
||||
source = "standalone"
|
||||
|
||||
version_data = {"families": families,
|
||||
"time": context.data["time"],
|
||||
"author": context.data["user"],
|
||||
"source": source,
|
||||
"comment": context.data.get("comment")}
|
||||
|
||||
# Include optional data if present in
|
||||
optionals = ["startFrame", "endFrame", "step",
|
||||
"handles", "colorspace", "fps", "outputDir"]
|
||||
|
||||
for key in optionals:
|
||||
if key in instance.data:
|
||||
version_data[key] = instance.data.get(key, None)
|
||||
|
||||
return version_data
|
||||
12
pype/standalonepublish/__init__.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
from .standalonepublish_module import StandAlonePublishModule
|
||||
from .app import (
|
||||
show,
|
||||
cli
|
||||
)
|
||||
__all__ = [
|
||||
"show",
|
||||
"cli"
|
||||
]
|
||||
|
||||
def tray_init(tray_widget, main_widget):
|
||||
return StandAlonePublishModule(main_widget, tray_widget)
|
||||
5
pype/standalonepublish/__main__.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from . import cli
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
sys.exit(cli(sys.argv[1:]))
|
||||
241
pype/standalonepublish/app.py
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
import os
|
||||
import sys
|
||||
import json
|
||||
from subprocess import Popen
|
||||
from pype import lib as pypelib
|
||||
from avalon.vendor.Qt import QtWidgets, QtCore
|
||||
from avalon import api, style, schema
|
||||
from avalon.tools import lib as parentlib
|
||||
from .widgets import *
|
||||
# Move this to pype lib?
|
||||
from avalon.tools.libraryloader.io_nonsingleton import DbConnector
|
||||
|
||||
module = sys.modules[__name__]
|
||||
module.window = None
|
||||
|
||||
class Window(QtWidgets.QDialog):
|
||||
"""Main window of Standalone publisher.
|
||||
|
||||
:param parent: Main widget that cares about all GUIs
|
||||
:type parent: QtWidgets.QMainWindow
|
||||
"""
|
||||
_db = DbConnector()
|
||||
_jobs = {}
|
||||
valid_family = False
|
||||
valid_components = False
|
||||
initialized = False
|
||||
WIDTH = 1100
|
||||
HEIGHT = 500
|
||||
NOT_SELECTED = '< Nothing is selected >'
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super(Window, self).__init__(parent=parent)
|
||||
self._db.install()
|
||||
|
||||
self.setWindowTitle("Standalone Publish")
|
||||
self.setFocusPolicy(QtCore.Qt.StrongFocus)
|
||||
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
|
||||
self.setStyleSheet(style.load_stylesheet())
|
||||
|
||||
# Validators
|
||||
self.valid_parent = False
|
||||
|
||||
# statusbar - added under asset_widget
|
||||
label_message = QtWidgets.QLabel()
|
||||
label_message.setFixedHeight(20)
|
||||
|
||||
# assets widget
|
||||
widget_assets_wrap = QtWidgets.QWidget()
|
||||
widget_assets_wrap.setContentsMargins(0, 0, 0, 0)
|
||||
widget_assets = AssetWidget(self)
|
||||
|
||||
layout_assets = QtWidgets.QVBoxLayout(widget_assets_wrap)
|
||||
layout_assets.addWidget(widget_assets)
|
||||
layout_assets.addWidget(label_message)
|
||||
|
||||
# family widget
|
||||
widget_family = FamilyWidget(self)
|
||||
|
||||
# components widget
|
||||
widget_components = ComponentsWidget(self)
|
||||
|
||||
# Body
|
||||
body = QtWidgets.QSplitter()
|
||||
body.setContentsMargins(0, 0, 0, 0)
|
||||
body.setSizePolicy(
|
||||
QtWidgets.QSizePolicy.Expanding,
|
||||
QtWidgets.QSizePolicy.Expanding
|
||||
)
|
||||
body.setOrientation(QtCore.Qt.Horizontal)
|
||||
body.addWidget(widget_assets_wrap)
|
||||
body.addWidget(widget_family)
|
||||
body.addWidget(widget_components)
|
||||
body.setStretchFactor(body.indexOf(widget_assets_wrap), 2)
|
||||
body.setStretchFactor(body.indexOf(widget_family), 3)
|
||||
body.setStretchFactor(body.indexOf(widget_components), 5)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.addWidget(body)
|
||||
|
||||
self.resize(self.WIDTH, self.HEIGHT)
|
||||
|
||||
# signals
|
||||
widget_assets.selection_changed.connect(self.on_asset_changed)
|
||||
|
||||
self.label_message = label_message
|
||||
self.widget_assets = widget_assets
|
||||
self.widget_family = widget_family
|
||||
self.widget_components = widget_components
|
||||
|
||||
self.echo("Connected to Database")
|
||||
|
||||
# on start
|
||||
self.on_start()
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
''' Returns DB object for MongoDB I/O
|
||||
'''
|
||||
return self._db
|
||||
|
||||
def on_start(self):
|
||||
''' Things must be done when initilized.
|
||||
'''
|
||||
# Refresh asset input in Family widget
|
||||
self.on_asset_changed()
|
||||
self.widget_components.validation()
|
||||
# Initializing shadow widget
|
||||
self.shadow_widget = ShadowWidget(self)
|
||||
self.shadow_widget.setVisible(False)
|
||||
|
||||
def resizeEvent(self, event=None):
|
||||
''' Helps resize shadow widget
|
||||
'''
|
||||
position_x = (self.frameGeometry().width()-self.shadow_widget.frameGeometry().width())/2
|
||||
position_y = (self.frameGeometry().height()-self.shadow_widget.frameGeometry().height())/2
|
||||
self.shadow_widget.move(position_x, position_y)
|
||||
w = self.frameGeometry().width()
|
||||
h = self.frameGeometry().height()
|
||||
self.shadow_widget.resize(QtCore.QSize(w, h))
|
||||
if event:
|
||||
super().resizeEvent(event)
|
||||
|
||||
def get_avalon_parent(self, entity):
|
||||
''' Avalon DB entities helper - get all parents (exclude project).
|
||||
'''
|
||||
parent_id = entity['data']['visualParent']
|
||||
parents = []
|
||||
if parent_id is not None:
|
||||
parent = self.db.find_one({'_id': parent_id})
|
||||
parents.extend(self.get_avalon_parent(parent))
|
||||
parents.append(parent['name'])
|
||||
return parents
|
||||
|
||||
def echo(self, message):
|
||||
''' Shows message in label that disappear in 5s
|
||||
:param message: Message that will be displayed
|
||||
:type message: str
|
||||
'''
|
||||
self.label_message.setText(str(message))
|
||||
def clear_text():
|
||||
''' Helps prevent crash if this Window object
|
||||
is deleted before 5s passed
|
||||
'''
|
||||
try:
|
||||
self.label_message.set_text("")
|
||||
except:
|
||||
pass
|
||||
QtCore.QTimer.singleShot(5000, lambda: clear_text())
|
||||
|
||||
def on_asset_changed(self):
|
||||
'''Callback on asset selection changed
|
||||
|
||||
Updates the task view.
|
||||
|
||||
'''
|
||||
selected = self.widget_assets.get_selected_assets()
|
||||
if len(selected) == 1:
|
||||
self.valid_parent = True
|
||||
asset = self.db.find_one({"_id": selected[0], "type": "asset"})
|
||||
self.widget_family.change_asset(asset['name'])
|
||||
else:
|
||||
self.valid_parent = False
|
||||
self.widget_family.change_asset(self.NOT_SELECTED)
|
||||
self.widget_family.on_data_changed()
|
||||
|
||||
def keyPressEvent(self, event):
|
||||
''' Handling Ctrl+V KeyPress event
|
||||
Can handle:
|
||||
- files/folders in clipboard (tested only on Windows OS)
|
||||
- copied path of file/folder in clipboard ('c:/path/to/folder')
|
||||
'''
|
||||
if event.key() == QtCore.Qt.Key_V and event.modifiers() == QtCore.Qt.ControlModifier:
|
||||
clip = QtWidgets.QApplication.clipboard()
|
||||
self.widget_components.process_mime_data(clip)
|
||||
super().keyPressEvent(event)
|
||||
|
||||
def working_start(self, msg=None):
|
||||
''' Shows shadowed foreground with message
|
||||
:param msg: Message that will be displayed
|
||||
(set to `Please wait...` if `None` entered)
|
||||
:type msg: str
|
||||
'''
|
||||
if msg is None:
|
||||
msg = 'Please wait...'
|
||||
self.shadow_widget.message = msg
|
||||
self.shadow_widget.setVisible(True)
|
||||
self.resizeEvent()
|
||||
QtWidgets.QApplication.processEvents()
|
||||
|
||||
def working_stop(self):
|
||||
''' Hides shadowed foreground
|
||||
'''
|
||||
if self.shadow_widget.isVisible():
|
||||
self.shadow_widget.setVisible(False)
|
||||
|
||||
def set_valid_family(self, valid):
|
||||
''' Sets `valid_family` attribute for validation
|
||||
|
||||
.. note::
|
||||
if set to `False` publishing is not possible
|
||||
'''
|
||||
self.valid_family = valid
|
||||
# If widget_components not initialized yet
|
||||
if hasattr(self, 'widget_components'):
|
||||
self.widget_components.validation()
|
||||
|
||||
def collect_data(self):
|
||||
''' Collecting necessary data for pyblish from child widgets
|
||||
'''
|
||||
data = {}
|
||||
data.update(self.widget_assets.collect_data())
|
||||
data.update(self.widget_family.collect_data())
|
||||
data.update(self.widget_components.collect_data())
|
||||
|
||||
return data
|
||||
|
||||
def show(parent=None, debug=False):
|
||||
try:
|
||||
module.window.close()
|
||||
del module.window
|
||||
except (RuntimeError, AttributeError):
|
||||
pass
|
||||
|
||||
with parentlib.application():
|
||||
window = Window(parent)
|
||||
window.show()
|
||||
|
||||
module.window = window
|
||||
|
||||
|
||||
def cli(args):
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("project")
|
||||
parser.add_argument("asset")
|
||||
|
||||
args = parser.parse_args(args)
|
||||
# project = args.project
|
||||
# asset = args.asset
|
||||
|
||||
show()
|
||||
154
pype/standalonepublish/publish.py
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import os
|
||||
import sys
|
||||
import json
|
||||
import tempfile
|
||||
import random
|
||||
import string
|
||||
|
||||
from avalon import io
|
||||
from avalon import api as avalon
|
||||
from avalon.tools import publish as av_publish
|
||||
|
||||
import pype
|
||||
from pypeapp import execute
|
||||
|
||||
import pyblish.api
|
||||
|
||||
|
||||
# Registers Global pyblish plugins
|
||||
# pype.install()
|
||||
# Registers Standalone pyblish plugins
|
||||
PUBLISH_PATH = os.path.sep.join(
|
||||
[pype.PLUGINS_DIR, 'standalonepublish', 'publish']
|
||||
)
|
||||
pyblish.api.register_plugin_path(PUBLISH_PATH)
|
||||
|
||||
# # Registers Standalone pyblish plugins
|
||||
# PUBLISH_PATH = os.path.sep.join(
|
||||
# [pype.PLUGINS_DIR, 'ftrack', 'publish']
|
||||
# )
|
||||
# pyblish.api.register_plugin_path(PUBLISH_PATH)
|
||||
|
||||
|
||||
def set_context(project, asset, app):
|
||||
''' Sets context for pyblish (must be done before pyblish is launched)
|
||||
:param project: Name of `Project` where instance should be published
|
||||
:type project: str
|
||||
:param asset: Name of `Asset` where instance should be published
|
||||
:type asset: str
|
||||
'''
|
||||
os.environ["AVALON_PROJECT"] = project
|
||||
io.Session["AVALON_PROJECT"] = project
|
||||
os.environ["AVALON_ASSET"] = asset
|
||||
io.Session["AVALON_ASSET"] = asset
|
||||
|
||||
io.install()
|
||||
|
||||
av_project = io.find_one({'type': 'project'})
|
||||
av_asset = io.find_one({
|
||||
"type": 'asset',
|
||||
"name": asset
|
||||
})
|
||||
|
||||
parents = av_asset['data']['parents']
|
||||
hierarchy = ''
|
||||
if parents and len(parents) > 0:
|
||||
hierarchy = os.path.sep.join(parents)
|
||||
|
||||
os.environ["AVALON_HIERARCHY"] = hierarchy
|
||||
io.Session["AVALON_HIERARCHY"] = hierarchy
|
||||
|
||||
os.environ["AVALON_PROJECTCODE"] = av_project['data'].get('code', '')
|
||||
io.Session["AVALON_PROJECTCODE"] = av_project['data'].get('code', '')
|
||||
|
||||
io.Session["current_dir"] = os.path.normpath(os.getcwd())
|
||||
|
||||
os.environ["AVALON_APP"] = app
|
||||
io.Session["AVALON_APP"] = app
|
||||
|
||||
io.uninstall()
|
||||
|
||||
|
||||
def publish(data, gui=True):
|
||||
# cli pyblish seems like better solution
|
||||
return cli_publish(data, gui)
|
||||
# # this uses avalon pyblish launch tool
|
||||
# avalon_api_publish(data, gui)
|
||||
|
||||
|
||||
def avalon_api_publish(data, gui=True):
|
||||
''' Launches Pyblish (GUI by default)
|
||||
:param data: Should include data for pyblish and standalone collector
|
||||
:type data: dict
|
||||
:param gui: Pyblish will be launched in GUI mode if set to True
|
||||
:type gui: bool
|
||||
'''
|
||||
io.install()
|
||||
|
||||
# Create hash name folder in temp
|
||||
chars = "".join( [random.choice(string.ascii_letters) for i in range(15)] )
|
||||
staging_dir = tempfile.mkdtemp(chars)
|
||||
|
||||
# create also json and fill with data
|
||||
json_data_path = staging_dir + os.path.basename(staging_dir) + '.json'
|
||||
with open(json_data_path, 'w') as outfile:
|
||||
json.dump(data, outfile)
|
||||
|
||||
args = [
|
||||
"-pp", os.pathsep.join(pyblish.api.registered_paths())
|
||||
]
|
||||
|
||||
os.environ["PYBLISH_HOSTS"] = "shell"
|
||||
os.environ["SAPUBLISH_INPATH"] = json_data_path
|
||||
|
||||
if gui:
|
||||
av_publish.show()
|
||||
else:
|
||||
returncode = execute([
|
||||
sys.executable, "-u", "-m", "pyblish"
|
||||
] + args, env=os.environ)
|
||||
|
||||
io.uninstall()
|
||||
|
||||
|
||||
def cli_publish(data, gui=True):
|
||||
io.install()
|
||||
|
||||
# Create hash name folder in temp
|
||||
chars = "".join( [random.choice(string.ascii_letters) for i in range(15)] )
|
||||
staging_dir = tempfile.mkdtemp(chars)
|
||||
|
||||
# create json for return data
|
||||
return_data_path = (
|
||||
staging_dir + os.path.basename(staging_dir) + 'return.json'
|
||||
)
|
||||
# create also json and fill with data
|
||||
json_data_path = staging_dir + os.path.basename(staging_dir) + '.json'
|
||||
with open(json_data_path, 'w') as outfile:
|
||||
json.dump(data, outfile)
|
||||
|
||||
args = [
|
||||
"-pp", os.pathsep.join(pyblish.api.registered_paths())
|
||||
]
|
||||
|
||||
if gui:
|
||||
args += ["gui"]
|
||||
|
||||
os.environ["PYBLISH_HOSTS"] = "shell"
|
||||
os.environ["SAPUBLISH_INPATH"] = json_data_path
|
||||
os.environ["SAPUBLISH_OUTPATH"] = return_data_path
|
||||
|
||||
returncode = execute([
|
||||
sys.executable, "-u", "-m", "pyblish"
|
||||
] + args, env=os.environ)
|
||||
|
||||
result = {}
|
||||
if os.path.exists(json_data_path):
|
||||
with open(json_data_path, "r") as f:
|
||||
result = json.load(f)
|
||||
|
||||
io.uninstall()
|
||||
# TODO: check if was pyblish successful
|
||||
# if successful return True
|
||||
print('Check result here')
|
||||
return False
|
||||
14
pype/standalonepublish/resources/__init__.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import os
|
||||
|
||||
|
||||
resource_path = os.path.dirname(__file__)
|
||||
|
||||
|
||||
def get_resource(*args):
|
||||
""" Serves to simple resources access
|
||||
|
||||
:param \*args: should contain *subfolder* names and *filename* of
|
||||
resource from resources folder
|
||||
:type \*args: list
|
||||
"""
|
||||
return os.path.normpath(os.path.join(resource_path, *args))
|
||||
9
pype/standalonepublish/resources/edit.svg
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 129 129" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 129 129" fill="#ffffff" width="32px" height="32px">
|
||||
<g>
|
||||
<g>
|
||||
<path d="m119.2,114.3h-109.4c-2.3,0-4.1,1.9-4.1,4.1s1.9,4.1 4.1,4.1h109.5c2.3,0 4.1-1.9 4.1-4.1s-1.9-4.1-4.2-4.1z"/>
|
||||
<path d="m5.7,78l-.1,19.5c0,1.1 0.4,2.2 1.2,3 0.8,0.8 1.8,1.2 2.9,1.2l19.4-.1c1.1,0 2.1-0.4 2.9-1.2l67-67c1.6-1.6 1.6-4.2 0-5.9l-19.2-19.4c-1.6-1.6-4.2-1.6-5.9-1.77636e-15l-13.4,13.5-53.6,53.5c-0.7,0.8-1.2,1.8-1.2,2.9zm71.2-61.1l13.5,13.5-7.6,7.6-13.5-13.5 7.6-7.6zm-62.9,62.9l49.4-49.4 13.5,13.5-49.4,49.3-13.6,.1 .1-13.5z"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 730 B |
BIN
pype/standalonepublish/resources/file.png
Normal file
|
After Width: | Height: | Size: 803 B |
BIN
pype/standalonepublish/resources/files.png
Normal file
|
After Width: | Height: | Size: 484 B |
BIN
pype/standalonepublish/resources/houdini.png
Normal file
|
After Width: | Height: | Size: 257 KiB |
BIN
pype/standalonepublish/resources/image_file.png
Normal file
|
After Width: | Height: | Size: 5 KiB |
BIN
pype/standalonepublish/resources/image_files.png
Normal file
|
After Width: | Height: | Size: 8.4 KiB |
14
pype/standalonepublish/resources/information.svg
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- Generator: Adobe Illustrator 18.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 330 330" fill="#ffffff" style="enable-background:new 0 0 330 330;" xml:space="preserve">
|
||||
<g>
|
||||
<path d="M165,0C74.019,0,0,74.02,0,165.001C0,255.982,74.019,330,165,330s165-74.018,165-164.999C330,74.02,255.981,0,165,0z
|
||||
M165,300c-74.44,0-135-60.56-135-134.999C30,90.562,90.56,30,165,30s135,60.562,135,135.001C300,239.44,239.439,300,165,300z"/>
|
||||
<path d="M164.998,70c-11.026,0-19.996,8.976-19.996,20.009c0,11.023,8.97,19.991,19.996,19.991
|
||||
c11.026,0,19.996-8.968,19.996-19.991C184.994,78.976,176.024,70,164.998,70z"/>
|
||||
<path d="M165,140c-8.284,0-15,6.716-15,15v90c0,8.284,6.716,15,15,15c8.284,0,15-6.716,15-15v-90C180,146.716,173.284,140,165,140z
|
||||
"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1 KiB |
BIN
pype/standalonepublish/resources/maya.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
12
pype/standalonepublish/resources/menu.svg
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 56 56" style="enable-background:new 0 0 56 56;" xml:space="preserve">
|
||||
<g>
|
||||
<path d="M28,0C12.561,0,0,12.561,0,28s12.561,28,28,28s28-12.561,28-28S43.439,0,28,0z M28,54C13.663,54,2,42.336,2,28
|
||||
S13.663,2,28,2s26,11.664,26,26S42.337,54,28,54z"/>
|
||||
<path d="M40,16H16c-0.553,0-1,0.448-1,1s0.447,1,1,1h24c0.553,0,1-0.448,1-1S40.553,16,40,16z"/>
|
||||
<path d="M40,27H16c-0.553,0-1,0.448-1,1s0.447,1,1,1h24c0.553,0,1-0.448,1-1S40.553,27,40,27z"/>
|
||||
<path d="M40,38H16c-0.553,0-1,0.448-1,1s0.447,1,1,1h24c0.553,0,1-0.448,1-1S40.553,38,40,38z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 823 B |
BIN
pype/standalonepublish/resources/nuke.png
Normal file
|
After Width: | Height: | Size: 48 KiB |
BIN
pype/standalonepublish/resources/premiere.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
19
pype/standalonepublish/resources/preview.svg
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 690 200" fill="#777777" style="enable-background:new 0 0 690 200;" xml:space="preserve">
|
||||
<g>
|
||||
<path d="
|
||||
M30,10
|
||||
h630 a20,20 0 0 1 20,20
|
||||
v140 a20,20 0 0 1 -20,20
|
||||
h-630 a20,20 0 0 1 -20,-20
|
||||
v-140 a20,20 0 0 1 20,-20 z
|
||||
|
||||
M17,37
|
||||
v126 a20,20 0 0 0 20,20
|
||||
h616 a20,20 0 0 0 20,-20
|
||||
v-126 a20,20 0 0 0 -20,-20
|
||||
h-616 a20,20 0 0 0 -20,20 z"/>
|
||||
<text style='font-family:Trebuchet MS;font-size:140px;' x="70" y="155" class="small">PREVIEW</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 661 B |
19
pype/standalonepublish/resources/thumbnail.svg
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 890 200" fill="#777777" style="enable-background:new 0 0 890 200;" xml:space="preserve">
|
||||
<g>
|
||||
<path d="
|
||||
M30,10
|
||||
h830 a20,20 0 0 1 20,20
|
||||
v140 a20,20 0 0 1 -20,20
|
||||
h-830 a20,20 0 0 1 -20,-20
|
||||
v-140 a20,20 0 0 1 20,-20 z
|
||||
|
||||
M17,37
|
||||
v126 a20,20 0 0 0 20,20
|
||||
h816 a20,20 0 0 0 20,-20
|
||||
v-126 a20,20 0 0 0 -20,-20
|
||||
h-816 a20,20 0 0 0 -20,20 z"/>
|
||||
<text style='font-family:Trebuchet MS;font-size:140px;' x="70" y="155" class="small">THUMBNAIL</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 663 B |
23
pype/standalonepublish/resources/trash.svg
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
width="482.428px" height="482.429px" viewBox="0 0 482.428 482.429" fill="#ffffff" style="enable-background:new 0 0 482.428 482.429;"
|
||||
xml:space="preserve">
|
||||
<g>
|
||||
<path d="M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098
|
||||
c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117
|
||||
h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828
|
||||
C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879
|
||||
C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096
|
||||
c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266
|
||||
c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979
|
||||
V115.744z"/>
|
||||
<path d="M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07
|
||||
c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z"/>
|
||||
<path d="M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07
|
||||
c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z"/>
|
||||
<path d="M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07
|
||||
c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
BIN
pype/standalonepublish/resources/video_file.png
Normal file
|
After Width: | Height: | Size: 120 B |
18
pype/standalonepublish/standalonepublish_module.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
from .app import show
|
||||
from .widgets import QtWidgets
|
||||
|
||||
|
||||
class StandAlonePublishModule:
|
||||
def __init__(self, main_parent=None, parent=None):
|
||||
self.main_parent = main_parent
|
||||
self.parent_widget = parent
|
||||
|
||||
def tray_menu(self, parent_menu):
|
||||
self.run_action = QtWidgets.QAction(
|
||||
"Publish", parent_menu
|
||||
)
|
||||
self.run_action.triggered.connect(self.show)
|
||||
parent_menu.addAction(self.run_action)
|
||||
|
||||
def show(self):
|
||||
show(self.main_parent, False)
|
||||
34
pype/standalonepublish/widgets/__init__.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
from avalon.vendor.Qt import *
|
||||
from avalon.vendor import qtawesome as awesome
|
||||
from avalon import style
|
||||
|
||||
HelpRole = QtCore.Qt.UserRole + 2
|
||||
FamilyRole = QtCore.Qt.UserRole + 3
|
||||
ExistsRole = QtCore.Qt.UserRole + 4
|
||||
PluginRole = QtCore.Qt.UserRole + 5
|
||||
|
||||
from ..resources import get_resource
|
||||
from .button_from_svgs import SvgResizable, SvgButton
|
||||
|
||||
from .model_node import Node
|
||||
from .model_tree import TreeModel
|
||||
from .model_asset import AssetModel
|
||||
from .model_filter_proxy_exact_match import ExactMatchesFilterProxyModel
|
||||
from .model_filter_proxy_recursive_sort import RecursiveSortFilterProxyModel
|
||||
from .model_tasks_template import TasksTemplateModel
|
||||
from .model_tree_view_deselectable import DeselectableTreeView
|
||||
|
||||
from .widget_asset_view import AssetView
|
||||
from .widget_asset import AssetWidget
|
||||
from .widget_family_desc import FamilyDescriptionWidget
|
||||
from .widget_family import FamilyWidget
|
||||
|
||||
from .widget_drop_empty import DropEmpty
|
||||
from .widget_component_item import ComponentItem
|
||||
from .widget_components_list import ComponentsList
|
||||
|
||||
from .widget_drop_frame import DropDataFrame
|
||||
|
||||
from .widget_components import ComponentsWidget
|
||||
|
||||
from.widget_shadow import ShadowWidget
|
||||
113
pype/standalonepublish/widgets/button_from_svgs.py
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
from xml.dom import minidom
|
||||
|
||||
from . import QtGui, QtCore, QtWidgets
|
||||
from PyQt5 import QtSvg, QtXml
|
||||
|
||||
|
||||
class SvgResizable(QtSvg.QSvgWidget):
|
||||
clicked = QtCore.Signal()
|
||||
|
||||
def __init__(self, filepath, width=None, height=None, fill=None):
|
||||
super().__init__()
|
||||
self.xmldoc = minidom.parse(filepath)
|
||||
itemlist = self.xmldoc.getElementsByTagName('svg')
|
||||
for element in itemlist:
|
||||
if fill:
|
||||
element.setAttribute('fill', str(fill))
|
||||
# TODO auto scale if only one is set
|
||||
if width is not None and height is not None:
|
||||
self.setMaximumSize(width, height)
|
||||
self.setMinimumSize(width, height)
|
||||
xml_string = self.xmldoc.toxml()
|
||||
svg_bytes = bytearray(xml_string, encoding='utf-8')
|
||||
|
||||
self.load(svg_bytes)
|
||||
|
||||
def change_color(self, color):
|
||||
element = self.xmldoc.getElementsByTagName('svg')[0]
|
||||
element.setAttribute('fill', str(color))
|
||||
xml_string = self.xmldoc.toxml()
|
||||
svg_bytes = bytearray(xml_string, encoding='utf-8')
|
||||
self.load(svg_bytes)
|
||||
|
||||
def mousePressEvent(self, event):
|
||||
self.clicked.emit()
|
||||
|
||||
|
||||
class SvgButton(QtWidgets.QFrame):
|
||||
clicked = QtCore.Signal()
|
||||
def __init__(
|
||||
self, filepath, width=None, height=None, fills=[],
|
||||
parent=None, checkable=True
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.checkable = checkable
|
||||
self.checked = False
|
||||
|
||||
xmldoc = minidom.parse(filepath)
|
||||
element = xmldoc.getElementsByTagName('svg')[0]
|
||||
c_actual = '#777777'
|
||||
if element.hasAttribute('fill'):
|
||||
c_actual = element.getAttribute('fill')
|
||||
self.store_fills(fills, c_actual)
|
||||
|
||||
self.installEventFilter(self)
|
||||
self.svg_widget = SvgResizable(filepath, width, height, self.c_normal)
|
||||
xmldoc = minidom.parse(filepath)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(self)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.svg_widget)
|
||||
|
||||
if width is not None and height is not None:
|
||||
self.setMaximumSize(width, height)
|
||||
self.setMinimumSize(width, height)
|
||||
|
||||
def store_fills(self, fills, actual):
|
||||
if len(fills) == 0:
|
||||
fills = [actual, actual, actual, actual]
|
||||
elif len(fills) == 1:
|
||||
fills = [fills[0], fills[0], fills[0], fills[0]]
|
||||
elif len(fills) == 2:
|
||||
fills = [fills[0], fills[1], fills[1], fills[1]]
|
||||
elif len(fills) == 3:
|
||||
fills = [fills[0], fills[1], fills[2], fills[2]]
|
||||
self.c_normal = fills[0]
|
||||
self.c_hover = fills[1]
|
||||
self.c_active = fills[2]
|
||||
self.c_active_hover = fills[3]
|
||||
|
||||
def eventFilter(self, object, event):
|
||||
if event.type() == QtCore.QEvent.Enter:
|
||||
self.hoverEnterEvent(event)
|
||||
return True
|
||||
elif event.type() == QtCore.QEvent.Leave:
|
||||
self.hoverLeaveEvent(event)
|
||||
return True
|
||||
elif event.type() == QtCore.QEvent.MouseButtonRelease:
|
||||
self.mousePressEvent(event)
|
||||
return False
|
||||
|
||||
def change_checked(self, hover=True):
|
||||
if self.checkable:
|
||||
self.checked = not self.checked
|
||||
if hover:
|
||||
self.hoverEnterEvent()
|
||||
else:
|
||||
self.hoverLeaveEvent()
|
||||
|
||||
def hoverEnterEvent(self, event=None):
|
||||
color = self.c_hover
|
||||
if self.checked:
|
||||
color = self.c_active_hover
|
||||
self.svg_widget.change_color(color)
|
||||
|
||||
def hoverLeaveEvent(self, event=None):
|
||||
color = self.c_normal
|
||||
if self.checked:
|
||||
color = self.c_active
|
||||
self.svg_widget.change_color(color)
|
||||
|
||||
def mousePressEvent(self, event=None):
|
||||
self.clicked.emit()
|
||||
158
pype/standalonepublish/widgets/model_asset.py
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import logging
|
||||
from . import QtCore, QtGui
|
||||
from . import TreeModel, Node
|
||||
from . import style, awesome
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _iter_model_rows(model,
|
||||
column,
|
||||
include_root=False):
|
||||
"""Iterate over all row indices in a model"""
|
||||
indices = [QtCore.QModelIndex()] # start iteration at root
|
||||
|
||||
for index in indices:
|
||||
|
||||
# Add children to the iterations
|
||||
child_rows = model.rowCount(index)
|
||||
for child_row in range(child_rows):
|
||||
child_index = model.index(child_row, column, index)
|
||||
indices.append(child_index)
|
||||
|
||||
if not include_root and not index.isValid():
|
||||
continue
|
||||
|
||||
yield index
|
||||
|
||||
|
||||
class AssetModel(TreeModel):
|
||||
"""A model listing assets in the silo in the active project.
|
||||
|
||||
The assets are displayed in a treeview, they are visually parented by
|
||||
a `visualParent` field in the database containing an `_id` to a parent
|
||||
asset.
|
||||
|
||||
"""
|
||||
|
||||
COLUMNS = ["label"]
|
||||
Name = 0
|
||||
Deprecated = 2
|
||||
ObjectId = 3
|
||||
|
||||
DocumentRole = QtCore.Qt.UserRole + 2
|
||||
ObjectIdRole = QtCore.Qt.UserRole + 3
|
||||
|
||||
def __init__(self, parent):
|
||||
super(AssetModel, self).__init__(parent=parent)
|
||||
self.parent_widget = parent
|
||||
self.refresh()
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
return self.parent_widget.db
|
||||
|
||||
def _add_hierarchy(self, parent=None):
|
||||
|
||||
# Find the assets under the parent
|
||||
find_data = {
|
||||
"type": "asset"
|
||||
}
|
||||
if parent is None:
|
||||
find_data['$or'] = [
|
||||
{'data.visualParent': {'$exists': False}},
|
||||
{'data.visualParent': None}
|
||||
]
|
||||
else:
|
||||
find_data["data.visualParent"] = parent['_id']
|
||||
|
||||
assets = self.db.find(find_data).sort('name', 1)
|
||||
for asset in assets:
|
||||
# get label from data, otherwise use name
|
||||
data = asset.get("data", {})
|
||||
label = data.get("label", asset['name'])
|
||||
tags = data.get("tags", [])
|
||||
|
||||
# store for the asset for optimization
|
||||
deprecated = "deprecated" in tags
|
||||
|
||||
node = Node({
|
||||
"_id": asset['_id'],
|
||||
"name": asset["name"],
|
||||
"label": label,
|
||||
"type": asset['type'],
|
||||
"tags": ", ".join(tags),
|
||||
"deprecated": deprecated,
|
||||
"_document": asset
|
||||
})
|
||||
self.add_child(node, parent=parent)
|
||||
|
||||
# Add asset's children recursively
|
||||
self._add_hierarchy(node)
|
||||
|
||||
def refresh(self):
|
||||
"""Refresh the data for the model."""
|
||||
|
||||
self.clear()
|
||||
if (
|
||||
self.db.active_project() is None or
|
||||
self.db.active_project() == ''
|
||||
):
|
||||
return
|
||||
self.beginResetModel()
|
||||
self._add_hierarchy(parent=None)
|
||||
self.endResetModel()
|
||||
|
||||
def flags(self, index):
|
||||
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
|
||||
|
||||
def data(self, index, role):
|
||||
|
||||
if not index.isValid():
|
||||
return
|
||||
|
||||
node = index.internalPointer()
|
||||
if role == QtCore.Qt.DecorationRole: # icon
|
||||
|
||||
column = index.column()
|
||||
if column == self.Name:
|
||||
|
||||
# Allow a custom icon and custom icon color to be defined
|
||||
data = node["_document"]["data"]
|
||||
icon = data.get("icon", None)
|
||||
color = data.get("color", style.colors.default)
|
||||
|
||||
if icon is None:
|
||||
# Use default icons if no custom one is specified.
|
||||
# If it has children show a full folder, otherwise
|
||||
# show an open folder
|
||||
has_children = self.rowCount(index) > 0
|
||||
icon = "folder" if has_children else "folder-o"
|
||||
|
||||
# Make the color darker when the asset is deprecated
|
||||
if node.get("deprecated", False):
|
||||
color = QtGui.QColor(color).darker(250)
|
||||
|
||||
try:
|
||||
key = "fa.{0}".format(icon) # font-awesome key
|
||||
icon = awesome.icon(key, color=color)
|
||||
return icon
|
||||
except Exception as exception:
|
||||
# Log an error message instead of erroring out completely
|
||||
# when the icon couldn't be created (e.g. invalid name)
|
||||
log.error(exception)
|
||||
|
||||
return
|
||||
|
||||
if role == QtCore.Qt.ForegroundRole: # font color
|
||||
if "deprecated" in node.get("tags", []):
|
||||
return QtGui.QColor(style.colors.light).darker(250)
|
||||
|
||||
if role == self.ObjectIdRole:
|
||||
return node.get("_id", None)
|
||||
|
||||
if role == self.DocumentRole:
|
||||
return node.get("_document", None)
|
||||
|
||||
return super(AssetModel, self).data(index, role)
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
from . import QtCore
|
||||
|
||||
|
||||
class ExactMatchesFilterProxyModel(QtCore.QSortFilterProxyModel):
|
||||
"""Filter model to where key column's value is in the filtered tags"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(ExactMatchesFilterProxyModel, self).__init__(*args, **kwargs)
|
||||
self._filters = set()
|
||||
|
||||
def setFilters(self, filters):
|
||||
self._filters = set(filters)
|
||||
|
||||
def filterAcceptsRow(self, source_row, source_parent):
|
||||
|
||||
# No filter
|
||||
if not self._filters:
|
||||
return True
|
||||
|
||||
else:
|
||||
model = self.sourceModel()
|
||||
column = self.filterKeyColumn()
|
||||
idx = model.index(source_row, column, source_parent)
|
||||
data = model.data(idx, self.filterRole())
|
||||
if data in self._filters:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
from . import QtCore
|
||||
|
||||
|
||||
class RecursiveSortFilterProxyModel(QtCore.QSortFilterProxyModel):
|
||||
"""Filters to the regex if any of the children matches allow parent"""
|
||||
def filterAcceptsRow(self, row, parent):
|
||||
|
||||
regex = self.filterRegExp()
|
||||
if not regex.isEmpty():
|
||||
pattern = regex.pattern()
|
||||
model = self.sourceModel()
|
||||
source_index = model.index(row, self.filterKeyColumn(), parent)
|
||||
if source_index.isValid():
|
||||
|
||||
# Check current index itself
|
||||
key = model.data(source_index, self.filterRole())
|
||||
if re.search(pattern, key, re.IGNORECASE):
|
||||
return True
|
||||
|
||||
# Check children
|
||||
rows = model.rowCount(source_index)
|
||||
for i in range(rows):
|
||||
if self.filterAcceptsRow(i, source_index):
|
||||
return True
|
||||
|
||||
# Otherwise filter it
|
||||
return False
|
||||
|
||||
return super(RecursiveSortFilterProxyModel,
|
||||
self).filterAcceptsRow(row, parent)
|
||||
56
pype/standalonepublish/widgets/model_node.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import logging
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Node(dict):
|
||||
"""A node that can be represented in a tree view.
|
||||
|
||||
The node can store data just like a dictionary.
|
||||
|
||||
>>> data = {"name": "John", "score": 10}
|
||||
>>> node = Node(data)
|
||||
>>> assert node["name"] == "John"
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, data=None):
|
||||
super(Node, self).__init__()
|
||||
|
||||
self._children = list()
|
||||
self._parent = None
|
||||
|
||||
if data is not None:
|
||||
assert isinstance(data, dict)
|
||||
self.update(data)
|
||||
|
||||
def childCount(self):
|
||||
return len(self._children)
|
||||
|
||||
def child(self, row):
|
||||
|
||||
if row >= len(self._children):
|
||||
log.warning("Invalid row as child: {0}".format(row))
|
||||
return
|
||||
|
||||
return self._children[row]
|
||||
|
||||
def children(self):
|
||||
return self._children
|
||||
|
||||
def parent(self):
|
||||
return self._parent
|
||||
|
||||
def row(self):
|
||||
"""
|
||||
Returns:
|
||||
int: Index of this node under parent"""
|
||||
if self._parent is not None:
|
||||
siblings = self.parent().children()
|
||||
return siblings.index(self)
|
||||
|
||||
def add_child(self, child):
|
||||
"""Add a child to this node"""
|
||||
child._parent = self
|
||||
self._children.append(child)
|
||||
65
pype/standalonepublish/widgets/model_tasks_template.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
from . import QtCore, TreeModel
|
||||
from . import Node
|
||||
from . import awesome, style
|
||||
|
||||
|
||||
class TasksTemplateModel(TreeModel):
|
||||
"""A model listing the tasks combined for a list of assets"""
|
||||
|
||||
COLUMNS = ["Tasks"]
|
||||
|
||||
def __init__(self):
|
||||
super(TasksTemplateModel, self).__init__()
|
||||
self.selectable = False
|
||||
self._icons = {
|
||||
"__default__": awesome.icon("fa.folder-o",
|
||||
color=style.colors.default)
|
||||
}
|
||||
|
||||
def set_tasks(self, tasks):
|
||||
"""Set assets to track by their database id
|
||||
|
||||
Arguments:
|
||||
asset_ids (list): List of asset ids.
|
||||
|
||||
"""
|
||||
|
||||
self.clear()
|
||||
|
||||
# let cleared task view if no tasks are available
|
||||
if len(tasks) == 0:
|
||||
return
|
||||
|
||||
self.beginResetModel()
|
||||
|
||||
icon = self._icons["__default__"]
|
||||
for task in tasks:
|
||||
node = Node({
|
||||
"Tasks": task,
|
||||
"icon": icon
|
||||
})
|
||||
|
||||
self.add_child(node)
|
||||
|
||||
self.endResetModel()
|
||||
|
||||
def flags(self, index):
|
||||
if self.selectable is False:
|
||||
return QtCore.Qt.ItemIsEnabled
|
||||
else:
|
||||
return (
|
||||
QtCore.Qt.ItemIsEnabled |
|
||||
QtCore.Qt.ItemIsSelectable
|
||||
)
|
||||
|
||||
def data(self, index, role):
|
||||
|
||||
if not index.isValid():
|
||||
return
|
||||
|
||||
# Add icon to the first column
|
||||
if role == QtCore.Qt.DecorationRole:
|
||||
if index.column() == 0:
|
||||
return index.internalPointer()['icon']
|
||||
|
||||
return super(TasksTemplateModel, self).data(index, role)
|
||||
122
pype/standalonepublish/widgets/model_tree.py
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
from . import QtCore
|
||||
from . import Node
|
||||
|
||||
|
||||
class TreeModel(QtCore.QAbstractItemModel):
|
||||
|
||||
COLUMNS = list()
|
||||
NodeRole = QtCore.Qt.UserRole + 1
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super(TreeModel, self).__init__(parent)
|
||||
self._root_node = Node()
|
||||
|
||||
def rowCount(self, parent):
|
||||
if parent.isValid():
|
||||
node = parent.internalPointer()
|
||||
else:
|
||||
node = self._root_node
|
||||
|
||||
return node.childCount()
|
||||
|
||||
def columnCount(self, parent):
|
||||
return len(self.COLUMNS)
|
||||
|
||||
def data(self, index, role):
|
||||
|
||||
if not index.isValid():
|
||||
return None
|
||||
|
||||
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
|
||||
|
||||
node = index.internalPointer()
|
||||
column = index.column()
|
||||
|
||||
key = self.COLUMNS[column]
|
||||
return node.get(key, None)
|
||||
|
||||
if role == self.NodeRole:
|
||||
return index.internalPointer()
|
||||
|
||||
def setData(self, index, value, role=QtCore.Qt.EditRole):
|
||||
"""Change the data on the nodes.
|
||||
|
||||
Returns:
|
||||
bool: Whether the edit was successful
|
||||
"""
|
||||
|
||||
if index.isValid():
|
||||
if role == QtCore.Qt.EditRole:
|
||||
|
||||
node = index.internalPointer()
|
||||
column = index.column()
|
||||
key = self.COLUMNS[column]
|
||||
node[key] = value
|
||||
|
||||
# passing `list()` for PyQt5 (see PYSIDE-462)
|
||||
self.dataChanged.emit(index, index, list())
|
||||
|
||||
# must return true if successful
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def setColumns(self, keys):
|
||||
assert isinstance(keys, (list, tuple))
|
||||
self.COLUMNS = keys
|
||||
|
||||
def headerData(self, section, orientation, role):
|
||||
|
||||
if role == QtCore.Qt.DisplayRole:
|
||||
if section < len(self.COLUMNS):
|
||||
return self.COLUMNS[section]
|
||||
|
||||
super(TreeModel, self).headerData(section, orientation, role)
|
||||
|
||||
def flags(self, index):
|
||||
return (
|
||||
QtCore.Qt.ItemIsEnabled |
|
||||
QtCore.Qt.ItemIsSelectable
|
||||
)
|
||||
|
||||
def parent(self, index):
|
||||
|
||||
node = index.internalPointer()
|
||||
parent_node = node.parent()
|
||||
|
||||
# If it has no parents we return invalid
|
||||
if parent_node == self._root_node or not parent_node:
|
||||
return QtCore.QModelIndex()
|
||||
|
||||
return self.createIndex(parent_node.row(), 0, parent_node)
|
||||
|
||||
def index(self, row, column, parent):
|
||||
"""Return index for row/column under parent"""
|
||||
|
||||
if not parent.isValid():
|
||||
parentNode = self._root_node
|
||||
else:
|
||||
parentNode = parent.internalPointer()
|
||||
|
||||
childItem = parentNode.child(row)
|
||||
if childItem:
|
||||
return self.createIndex(row, column, childItem)
|
||||
else:
|
||||
return QtCore.QModelIndex()
|
||||
|
||||
def add_child(self, node, parent=None):
|
||||
if parent is None:
|
||||
parent = self._root_node
|
||||
|
||||
parent.add_child(node)
|
||||
|
||||
def column_name(self, column):
|
||||
"""Return column key by index"""
|
||||
|
||||
if column < len(self.COLUMNS):
|
||||
return self.COLUMNS[column]
|
||||
|
||||
def clear(self):
|
||||
self.beginResetModel()
|
||||
self._root_node = Node()
|
||||
self.endResetModel()
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
from . import QtWidgets, QtCore
|
||||
|
||||
|
||||
class DeselectableTreeView(QtWidgets.QTreeView):
|
||||
"""A tree view that deselects on clicking on an empty area in the view"""
|
||||
|
||||
def mousePressEvent(self, event):
|
||||
|
||||
index = self.indexAt(event.pos())
|
||||
if not index.isValid():
|
||||
# clear the selection
|
||||
self.clearSelection()
|
||||
# clear the current index
|
||||
self.setCurrentIndex(QtCore.QModelIndex())
|
||||
|
||||
QtWidgets.QTreeView.mousePressEvent(self, event)
|
||||
274
pype/standalonepublish/widgets/widget_asset.py
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
import contextlib
|
||||
from . import QtWidgets, QtCore
|
||||
from . import RecursiveSortFilterProxyModel, AssetModel, AssetView
|
||||
from . import awesome, style
|
||||
|
||||
@contextlib.contextmanager
|
||||
def preserve_expanded_rows(tree_view,
|
||||
column=0,
|
||||
role=QtCore.Qt.DisplayRole):
|
||||
"""Preserves expanded row in QTreeView by column's data role.
|
||||
|
||||
This function is created to maintain the expand vs collapse status of
|
||||
the model items. When refresh is triggered the items which are expanded
|
||||
will stay expanded and vise versa.
|
||||
|
||||
Arguments:
|
||||
tree_view (QWidgets.QTreeView): the tree view which is
|
||||
nested in the application
|
||||
column (int): the column to retrieve the data from
|
||||
role (int): the role which dictates what will be returned
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
|
||||
model = tree_view.model()
|
||||
|
||||
expanded = set()
|
||||
|
||||
for index in _iter_model_rows(model,
|
||||
column=column,
|
||||
include_root=False):
|
||||
if tree_view.isExpanded(index):
|
||||
value = index.data(role)
|
||||
expanded.add(value)
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if not expanded:
|
||||
return
|
||||
|
||||
for index in _iter_model_rows(model,
|
||||
column=column,
|
||||
include_root=False):
|
||||
value = index.data(role)
|
||||
state = value in expanded
|
||||
if state:
|
||||
tree_view.expand(index)
|
||||
else:
|
||||
tree_view.collapse(index)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def preserve_selection(tree_view,
|
||||
column=0,
|
||||
role=QtCore.Qt.DisplayRole,
|
||||
current_index=True):
|
||||
"""Preserves row selection in QTreeView by column's data role.
|
||||
|
||||
This function is created to maintain the selection status of
|
||||
the model items. When refresh is triggered the items which are expanded
|
||||
will stay expanded and vise versa.
|
||||
|
||||
tree_view (QWidgets.QTreeView): the tree view nested in the application
|
||||
column (int): the column to retrieve the data from
|
||||
role (int): the role which dictates what will be returned
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
|
||||
model = tree_view.model()
|
||||
selection_model = tree_view.selectionModel()
|
||||
flags = selection_model.Select | selection_model.Rows
|
||||
|
||||
if current_index:
|
||||
current_index_value = tree_view.currentIndex().data(role)
|
||||
else:
|
||||
current_index_value = None
|
||||
|
||||
selected_rows = selection_model.selectedRows()
|
||||
if not selected_rows:
|
||||
yield
|
||||
return
|
||||
|
||||
selected = set(row.data(role) for row in selected_rows)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if not selected:
|
||||
return
|
||||
|
||||
# Go through all indices, select the ones with similar data
|
||||
for index in _iter_model_rows(model,
|
||||
column=column,
|
||||
include_root=False):
|
||||
|
||||
value = index.data(role)
|
||||
state = value in selected
|
||||
if state:
|
||||
tree_view.scrollTo(index) # Ensure item is visible
|
||||
selection_model.select(index, flags)
|
||||
|
||||
if current_index_value and value == current_index_value:
|
||||
tree_view.setCurrentIndex(index)
|
||||
|
||||
|
||||
class AssetWidget(QtWidgets.QWidget):
|
||||
"""A Widget to display a tree of assets with filter
|
||||
|
||||
To list the assets of the active project:
|
||||
>>> # widget = AssetWidget()
|
||||
>>> # widget.refresh()
|
||||
>>> # widget.show()
|
||||
|
||||
"""
|
||||
|
||||
assets_refreshed = QtCore.Signal() # on model refresh
|
||||
selection_changed = QtCore.Signal() # on view selection change
|
||||
current_changed = QtCore.Signal() # on view current index change
|
||||
|
||||
def __init__(self, parent):
|
||||
super(AssetWidget, self).__init__(parent=parent)
|
||||
self.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
self.parent_widget = parent
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(4)
|
||||
|
||||
# Project
|
||||
self.combo_projects = QtWidgets.QComboBox()
|
||||
self._set_projects()
|
||||
self.combo_projects.currentTextChanged.connect(self.on_project_change)
|
||||
# Tree View
|
||||
model = AssetModel(self)
|
||||
proxy = RecursiveSortFilterProxyModel()
|
||||
proxy.setSourceModel(model)
|
||||
proxy.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
|
||||
view = AssetView()
|
||||
view.setModel(proxy)
|
||||
|
||||
# Header
|
||||
header = QtWidgets.QHBoxLayout()
|
||||
|
||||
icon = awesome.icon("fa.refresh", color=style.colors.light)
|
||||
refresh = QtWidgets.QPushButton(icon, "")
|
||||
refresh.setToolTip("Refresh items")
|
||||
|
||||
filter = QtWidgets.QLineEdit()
|
||||
filter.textChanged.connect(proxy.setFilterFixedString)
|
||||
filter.setPlaceholderText("Filter assets..")
|
||||
|
||||
header.addWidget(filter)
|
||||
header.addWidget(refresh)
|
||||
|
||||
# Layout
|
||||
layout.addWidget(self.combo_projects)
|
||||
layout.addLayout(header)
|
||||
layout.addWidget(view)
|
||||
|
||||
# Signals/Slots
|
||||
selection = view.selectionModel()
|
||||
selection.selectionChanged.connect(self.selection_changed)
|
||||
selection.currentChanged.connect(self.current_changed)
|
||||
refresh.clicked.connect(self.refresh)
|
||||
|
||||
self.refreshButton = refresh
|
||||
self.model = model
|
||||
self.proxy = proxy
|
||||
self.view = view
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
return self.parent_widget.db
|
||||
|
||||
def collect_data(self):
|
||||
project = self.db.find_one({'type': 'project'})
|
||||
asset = self.db.find_one({'_id': self.get_active_asset()})
|
||||
data = {
|
||||
'project': project['name'],
|
||||
'asset': asset['name'],
|
||||
'parents': self.get_parents(asset)
|
||||
}
|
||||
return data
|
||||
|
||||
def get_parents(self, entity):
|
||||
output = []
|
||||
if entity.get('data', {}).get('visualParent', None) is None:
|
||||
return output
|
||||
parent = self.db.find_one({'_id': entity['data']['visualParent']})
|
||||
output.append(parent['name'])
|
||||
output.extend(self.get_parents(parent))
|
||||
return output
|
||||
|
||||
def _set_projects(self):
|
||||
projects = list()
|
||||
for project in self.db.projects():
|
||||
projects.append(project['name'])
|
||||
|
||||
self.combo_projects.clear()
|
||||
if len(projects) > 0:
|
||||
self.combo_projects.addItems(projects)
|
||||
self.db.activate_project(projects[0])
|
||||
|
||||
def on_project_change(self):
|
||||
projects = list()
|
||||
for project in self.db.projects():
|
||||
projects.append(project['name'])
|
||||
project_name = self.combo_projects.currentText()
|
||||
if project_name in projects:
|
||||
self.db.activate_project(project_name)
|
||||
self.refresh()
|
||||
|
||||
def _refresh_model(self):
|
||||
self.model.refresh()
|
||||
self.assets_refreshed.emit()
|
||||
|
||||
def refresh(self):
|
||||
self._refresh_model()
|
||||
|
||||
def get_active_asset(self):
|
||||
"""Return the asset id the current asset."""
|
||||
current = self.view.currentIndex()
|
||||
return current.data(self.model.ObjectIdRole)
|
||||
|
||||
def get_active_index(self):
|
||||
return self.view.currentIndex()
|
||||
|
||||
def get_selected_assets(self):
|
||||
"""Return the assets' ids that are selected."""
|
||||
selection = self.view.selectionModel()
|
||||
rows = selection.selectedRows()
|
||||
return [row.data(self.model.ObjectIdRole) for row in rows]
|
||||
|
||||
def select_assets(self, assets, expand=True):
|
||||
"""Select assets by name.
|
||||
|
||||
Args:
|
||||
assets (list): List of asset names
|
||||
expand (bool): Whether to also expand to the asset in the view
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
# TODO: Instead of individual selection optimize for many assets
|
||||
|
||||
assert isinstance(assets,
|
||||
(tuple, list)), "Assets must be list or tuple"
|
||||
|
||||
# Clear selection
|
||||
selection_model = self.view.selectionModel()
|
||||
selection_model.clearSelection()
|
||||
|
||||
# Select
|
||||
mode = selection_model.Select | selection_model.Rows
|
||||
for index in _iter_model_rows(self.proxy,
|
||||
column=0,
|
||||
include_root=False):
|
||||
data = index.data(self.model.NodeRole)
|
||||
name = data['name']
|
||||
if name in assets:
|
||||
selection_model.select(index, mode)
|
||||
|
||||
if expand:
|
||||
self.view.expand(index)
|
||||
|
||||
# Set the currently active index
|
||||
self.view.setCurrentIndex(index)
|
||||
16
pype/standalonepublish/widgets/widget_asset_view.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from . import QtCore
|
||||
from . import DeselectableTreeView
|
||||
|
||||
|
||||
class AssetView(DeselectableTreeView):
|
||||
"""Item view.
|
||||
|
||||
This implements a context menu.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super(AssetView, self).__init__()
|
||||
self.setIndentation(15)
|
||||
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
|
||||
self.setHeaderHidden(True)
|
||||
294
pype/standalonepublish/widgets/widget_component_item.py
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
import os
|
||||
from . import QtCore, QtGui, QtWidgets
|
||||
from . import SvgButton
|
||||
from . import get_resource
|
||||
from avalon import style
|
||||
|
||||
|
||||
class ComponentItem(QtWidgets.QFrame):
|
||||
C_NORMAL = '#777777'
|
||||
C_HOVER = '#ffffff'
|
||||
C_ACTIVE = '#4BB543'
|
||||
C_ACTIVE_HOVER = '#4BF543'
|
||||
signal_remove = QtCore.Signal(object)
|
||||
signal_thumbnail = QtCore.Signal(object)
|
||||
signal_preview = QtCore.Signal(object)
|
||||
signal_repre_change = QtCore.Signal(object, object)
|
||||
|
||||
def __init__(self, parent, main_parent):
|
||||
super().__init__()
|
||||
self.has_valid_repre = True
|
||||
self.actions = []
|
||||
self.resize(290, 70)
|
||||
self.setMinimumSize(QtCore.QSize(0, 70))
|
||||
self.parent_list = parent
|
||||
self.parent_widget = main_parent
|
||||
# Font
|
||||
font = QtGui.QFont()
|
||||
font.setFamily("DejaVu Sans Condensed")
|
||||
font.setPointSize(9)
|
||||
font.setBold(True)
|
||||
font.setWeight(50)
|
||||
font.setKerning(True)
|
||||
|
||||
# Main widgets
|
||||
frame = QtWidgets.QFrame(self)
|
||||
frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
|
||||
frame.setFrameShadow(QtWidgets.QFrame.Raised)
|
||||
|
||||
layout_main = QtWidgets.QHBoxLayout(frame)
|
||||
layout_main.setSpacing(2)
|
||||
layout_main.setContentsMargins(2, 2, 2, 2)
|
||||
|
||||
# Image + Info
|
||||
frame_image_info = QtWidgets.QFrame(frame)
|
||||
|
||||
# Layout image info
|
||||
layout = QtWidgets.QVBoxLayout(frame_image_info)
|
||||
layout.setSpacing(2)
|
||||
layout.setContentsMargins(2, 2, 2, 2)
|
||||
|
||||
self.icon = QtWidgets.QLabel(frame)
|
||||
self.icon.setMinimumSize(QtCore.QSize(22, 22))
|
||||
self.icon.setMaximumSize(QtCore.QSize(22, 22))
|
||||
self.icon.setText("")
|
||||
self.icon.setScaledContents(True)
|
||||
|
||||
self.btn_action_menu = SvgButton(
|
||||
get_resource('menu.svg'), 22, 22,
|
||||
[self.C_NORMAL, self.C_HOVER],
|
||||
frame_image_info, False
|
||||
)
|
||||
|
||||
self.action_menu = QtWidgets.QMenu()
|
||||
|
||||
expanding_sizePolicy = QtWidgets.QSizePolicy(
|
||||
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
|
||||
)
|
||||
expanding_sizePolicy.setHorizontalStretch(0)
|
||||
expanding_sizePolicy.setVerticalStretch(0)
|
||||
|
||||
layout.addWidget(self.icon, alignment=QtCore.Qt.AlignCenter)
|
||||
layout.addWidget(self.btn_action_menu, alignment=QtCore.Qt.AlignCenter)
|
||||
|
||||
layout_main.addWidget(frame_image_info)
|
||||
|
||||
# Name + representation
|
||||
self.name = QtWidgets.QLabel(frame)
|
||||
self.file_info = QtWidgets.QLabel(frame)
|
||||
self.ext = QtWidgets.QLabel(frame)
|
||||
|
||||
self.name.setFont(font)
|
||||
self.file_info.setFont(font)
|
||||
self.ext.setFont(font)
|
||||
|
||||
self.file_info.setStyleSheet('padding-left:3px;')
|
||||
|
||||
expanding_sizePolicy.setHeightForWidth(self.name.sizePolicy().hasHeightForWidth())
|
||||
|
||||
frame_name_repre = QtWidgets.QFrame(frame)
|
||||
|
||||
self.file_info.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
|
||||
self.ext.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
|
||||
self.name.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(frame_name_repre)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.name, alignment=QtCore.Qt.AlignLeft)
|
||||
layout.addWidget(self.file_info, alignment=QtCore.Qt.AlignLeft)
|
||||
layout.addWidget(self.ext, alignment=QtCore.Qt.AlignRight)
|
||||
|
||||
frame_name_repre.setSizePolicy(
|
||||
QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding
|
||||
)
|
||||
|
||||
# Repre + icons
|
||||
frame_repre_icons = QtWidgets.QFrame(frame)
|
||||
|
||||
frame_repre = QtWidgets.QFrame(frame_repre_icons)
|
||||
|
||||
label_repre = QtWidgets.QLabel()
|
||||
label_repre.setText('Representation:')
|
||||
|
||||
self.input_repre = QtWidgets.QLineEdit()
|
||||
self.input_repre.setMaximumWidth(50)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(frame_repre)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
layout.addWidget(label_repre, alignment=QtCore.Qt.AlignLeft)
|
||||
layout.addWidget(self.input_repre, alignment=QtCore.Qt.AlignLeft)
|
||||
|
||||
frame_icons = QtWidgets.QFrame(frame_repre_icons)
|
||||
|
||||
self.preview = SvgButton(
|
||||
get_resource('preview.svg'), 64, 18,
|
||||
[self.C_NORMAL, self.C_HOVER, self.C_ACTIVE, self.C_ACTIVE_HOVER],
|
||||
frame_icons
|
||||
)
|
||||
|
||||
self.thumbnail = SvgButton(
|
||||
get_resource('thumbnail.svg'), 84, 18,
|
||||
[self.C_NORMAL, self.C_HOVER, self.C_ACTIVE, self.C_ACTIVE_HOVER],
|
||||
frame_icons
|
||||
)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(frame_icons)
|
||||
layout.setSpacing(6)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.thumbnail)
|
||||
layout.addWidget(self.preview)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(frame_repre_icons)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
layout.addWidget(frame_repre, alignment=QtCore.Qt.AlignLeft)
|
||||
layout.addWidget(frame_icons, alignment=QtCore.Qt.AlignRight)
|
||||
|
||||
frame_middle = QtWidgets.QFrame(frame)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(frame_middle)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(4, 0, 4, 0)
|
||||
layout.addWidget(frame_name_repre)
|
||||
layout.addWidget(frame_repre_icons)
|
||||
|
||||
layout.setStretchFactor(frame_name_repre, 1)
|
||||
layout.setStretchFactor(frame_repre_icons, 1)
|
||||
|
||||
layout_main.addWidget(frame_middle)
|
||||
|
||||
self.remove = SvgButton(
|
||||
get_resource('trash.svg'), 22, 22,
|
||||
[self.C_NORMAL, self.C_HOVER],
|
||||
frame, False
|
||||
)
|
||||
|
||||
layout_main.addWidget(self.remove)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(2, 2, 2, 2)
|
||||
layout.addWidget(frame)
|
||||
|
||||
self.preview.setToolTip('Mark component as Preview')
|
||||
self.thumbnail.setToolTip('Component will be selected as thumbnail')
|
||||
|
||||
# self.frame.setStyleSheet("border: 1px solid black;")
|
||||
|
||||
def set_context(self, data):
|
||||
self.btn_action_menu.setVisible(False)
|
||||
self.in_data = data
|
||||
self.remove.clicked.connect(self._remove)
|
||||
self.thumbnail.clicked.connect(self._thumbnail_clicked)
|
||||
self.preview.clicked.connect(self._preview_clicked)
|
||||
self.input_repre.textChanged.connect(self._handle_duplicate_repre)
|
||||
name = data['name']
|
||||
representation = data['representation']
|
||||
ext = data['ext']
|
||||
file_info = data['file_info']
|
||||
thumb = data['thumb']
|
||||
prev = data['prev']
|
||||
icon = data['icon']
|
||||
|
||||
resource = None
|
||||
if icon is not None:
|
||||
resource = get_resource('{}.png'.format(icon))
|
||||
|
||||
if resource is None or not os.path.isfile(resource):
|
||||
if data['is_sequence']:
|
||||
resource = get_resource('files.png')
|
||||
else:
|
||||
resource = get_resource('file.png')
|
||||
|
||||
pixmap = QtGui.QPixmap(resource)
|
||||
self.icon.setPixmap(pixmap)
|
||||
|
||||
self.name.setText(name)
|
||||
self.input_repre.setText(representation)
|
||||
self.ext.setText('( {} )'.format(ext))
|
||||
if file_info is None:
|
||||
self.file_info.setVisible(False)
|
||||
else:
|
||||
self.file_info.setText('[{}]'.format(file_info))
|
||||
|
||||
self.thumbnail.setVisible(thumb)
|
||||
self.preview.setVisible(prev)
|
||||
|
||||
def add_action(self, action_name):
|
||||
if action_name.lower() == 'split':
|
||||
for action in self.actions:
|
||||
if action.text() == 'Split to frames':
|
||||
return
|
||||
new_action = QtWidgets.QAction('Split to frames', self)
|
||||
new_action.triggered.connect(self.split_sequence)
|
||||
elif action_name.lower() == 'merge':
|
||||
for action in self.actions:
|
||||
if action.text() == 'Merge components':
|
||||
return
|
||||
new_action = QtWidgets.QAction('Merge components', self)
|
||||
new_action.triggered.connect(self.merge_sequence)
|
||||
else:
|
||||
print('unknown action')
|
||||
return
|
||||
self.action_menu.addAction(new_action)
|
||||
self.actions.append(new_action)
|
||||
if not self.btn_action_menu.isVisible():
|
||||
self.btn_action_menu.setVisible(True)
|
||||
self.btn_action_menu.clicked.connect(self.show_actions)
|
||||
self.action_menu.setStyleSheet(style.load_stylesheet())
|
||||
|
||||
def set_repre_name_valid(self, valid):
|
||||
self.has_valid_repre = valid
|
||||
if valid:
|
||||
self.input_repre.setStyleSheet("")
|
||||
else:
|
||||
self.input_repre.setStyleSheet("border: 1px solid red;")
|
||||
|
||||
def split_sequence(self):
|
||||
self.parent_widget.split_items(self)
|
||||
|
||||
def merge_sequence(self):
|
||||
self.parent_widget.merge_items(self)
|
||||
|
||||
def show_actions(self):
|
||||
position = QtGui.QCursor().pos()
|
||||
self.action_menu.popup(position)
|
||||
|
||||
def _remove(self):
|
||||
self.signal_remove.emit(self)
|
||||
|
||||
def _thumbnail_clicked(self):
|
||||
self.signal_thumbnail.emit(self)
|
||||
|
||||
def _preview_clicked(self):
|
||||
self.signal_preview.emit(self)
|
||||
|
||||
def _handle_duplicate_repre(self, repre_name):
|
||||
self.signal_repre_change.emit(self, repre_name)
|
||||
|
||||
def is_thumbnail(self):
|
||||
return self.thumbnail.checked
|
||||
|
||||
def change_thumbnail(self, hover=True):
|
||||
self.thumbnail.change_checked(hover)
|
||||
|
||||
def is_preview(self):
|
||||
return self.preview.checked
|
||||
|
||||
def change_preview(self, hover=True):
|
||||
self.preview.change_checked(hover)
|
||||
|
||||
def collect_data(self):
|
||||
data = {
|
||||
'ext': self.in_data['ext'],
|
||||
'label': self.name.text(),
|
||||
'representation': self.input_repre.text(),
|
||||
'files': self.in_data['files'],
|
||||
'thumbnail': self.is_thumbnail(),
|
||||
'preview': self.is_preview()
|
||||
}
|
||||
return data
|
||||
128
pype/standalonepublish/widgets/widget_components.py
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
from . import QtWidgets, QtCore, QtGui
|
||||
from . import DropDataFrame
|
||||
|
||||
from .. import publish
|
||||
|
||||
|
||||
class ComponentsWidget(QtWidgets.QWidget):
|
||||
def __init__(self, parent):
|
||||
super().__init__()
|
||||
self.initialized = False
|
||||
self.valid_components = False
|
||||
self.valid_family = False
|
||||
self.valid_repre_names = False
|
||||
|
||||
body = QtWidgets.QWidget()
|
||||
self.parent_widget = parent
|
||||
self.drop_frame = DropDataFrame(self)
|
||||
|
||||
buttons = QtWidgets.QWidget()
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(buttons)
|
||||
|
||||
self.btn_browse = QtWidgets.QPushButton('Browse')
|
||||
self.btn_browse.setToolTip('Browse for file(s).')
|
||||
self.btn_browse.setFocusPolicy(QtCore.Qt.NoFocus)
|
||||
|
||||
self.btn_publish = QtWidgets.QPushButton('Publish')
|
||||
self.btn_publish.setToolTip('Publishes data.')
|
||||
self.btn_publish.setFocusPolicy(QtCore.Qt.NoFocus)
|
||||
|
||||
layout.addWidget(self.btn_browse, alignment=QtCore.Qt.AlignLeft)
|
||||
layout.addWidget(self.btn_publish, alignment=QtCore.Qt.AlignRight)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(body)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.drop_frame)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.setSpacing(0)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(body)
|
||||
|
||||
self.btn_browse.clicked.connect(self._browse)
|
||||
self.btn_publish.clicked.connect(self._publish)
|
||||
self.initialized = True
|
||||
|
||||
def validation(self):
|
||||
if self.initialized is False:
|
||||
return
|
||||
valid = (
|
||||
self.parent_widget.valid_family and
|
||||
self.valid_components and
|
||||
self.valid_repre_names
|
||||
)
|
||||
self.btn_publish.setEnabled(valid)
|
||||
|
||||
def set_valid_components(self, valid):
|
||||
self.valid_components = valid
|
||||
self.validation()
|
||||
|
||||
def set_valid_repre_names(self, valid):
|
||||
self.valid_repre_names = valid
|
||||
self.validation()
|
||||
|
||||
def process_mime_data(self, mime_data):
|
||||
self.drop_frame.process_ent_mime(mime_data)
|
||||
|
||||
def collect_data(self):
|
||||
return self.drop_frame.collect_data()
|
||||
|
||||
def _browse(self):
|
||||
options = [
|
||||
QtWidgets.QFileDialog.DontResolveSymlinks,
|
||||
QtWidgets.QFileDialog.DontUseNativeDialog
|
||||
]
|
||||
folders = False
|
||||
if folders:
|
||||
# browse folders specifics
|
||||
caption = "Browse folders to publish image sequences"
|
||||
file_mode = QtWidgets.QFileDialog.Directory
|
||||
options.append(QtWidgets.QFileDialog.ShowDirsOnly)
|
||||
else:
|
||||
# browse files specifics
|
||||
caption = "Browse files to publish"
|
||||
file_mode = QtWidgets.QFileDialog.ExistingFiles
|
||||
|
||||
# create the dialog
|
||||
file_dialog = QtWidgets.QFileDialog(parent=self, caption=caption)
|
||||
file_dialog.setLabelText(QtWidgets.QFileDialog.Accept, "Select")
|
||||
file_dialog.setLabelText(QtWidgets.QFileDialog.Reject, "Cancel")
|
||||
file_dialog.setFileMode(file_mode)
|
||||
|
||||
# set the appropriate options
|
||||
for option in options:
|
||||
file_dialog.setOption(option)
|
||||
|
||||
# browse!
|
||||
if not file_dialog.exec_():
|
||||
return
|
||||
|
||||
# process the browsed files/folders for publishing
|
||||
paths = file_dialog.selectedFiles()
|
||||
self.drop_frame._process_paths(paths)
|
||||
|
||||
def working_start(self, msg=None):
|
||||
if hasattr(self, 'parent_widget'):
|
||||
self.parent_widget.working_start(msg)
|
||||
|
||||
def working_stop(self):
|
||||
if hasattr(self, 'parent_widget'):
|
||||
self.parent_widget.working_stop()
|
||||
|
||||
def _publish(self):
|
||||
self.working_start('Pyblish is running')
|
||||
try:
|
||||
data = self.parent_widget.collect_data()
|
||||
publish.set_context(
|
||||
data['project'], data['asset'], 'standalonepublish'
|
||||
)
|
||||
result = publish.publish(data)
|
||||
# Clear widgets from components list if publishing was successful
|
||||
if result:
|
||||
self.drop_frame.components_list.clear_widgets()
|
||||
self.drop_frame._refresh_view()
|
||||
finally:
|
||||
self.working_stop()
|
||||
89
pype/standalonepublish/widgets/widget_components_list.py
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
from . import QtCore, QtGui, QtWidgets
|
||||
|
||||
|
||||
class ComponentsList(QtWidgets.QTableWidget):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent=parent)
|
||||
|
||||
self._main_column = 0
|
||||
|
||||
self.setColumnCount(1)
|
||||
self.setSelectionBehavior(
|
||||
QtWidgets.QAbstractItemView.SelectRows
|
||||
)
|
||||
self.setSelectionMode(
|
||||
QtWidgets.QAbstractItemView.ExtendedSelection
|
||||
)
|
||||
self.setVerticalScrollMode(
|
||||
QtWidgets.QAbstractItemView.ScrollPerPixel
|
||||
)
|
||||
self.verticalHeader().hide()
|
||||
|
||||
try:
|
||||
self.verticalHeader().setResizeMode(
|
||||
QtWidgets.QHeaderView.ResizeToContents
|
||||
)
|
||||
except Exception:
|
||||
self.verticalHeader().setSectionResizeMode(
|
||||
QtWidgets.QHeaderView.ResizeToContents
|
||||
)
|
||||
|
||||
self.horizontalHeader().setStretchLastSection(True)
|
||||
self.horizontalHeader().hide()
|
||||
|
||||
def count(self):
|
||||
return self.rowCount()
|
||||
|
||||
def add_widget(self, widget, row=None):
|
||||
if row is None:
|
||||
row = self.count()
|
||||
|
||||
self.insertRow(row)
|
||||
self.setCellWidget(row, self._main_column, widget)
|
||||
|
||||
self.resizeRowToContents(row)
|
||||
|
||||
return row
|
||||
|
||||
def remove_widget(self, row):
|
||||
self.removeRow(row)
|
||||
|
||||
def move_widget(self, widget, newRow):
|
||||
oldRow = self.indexOfWidget(widget)
|
||||
if oldRow:
|
||||
self.insertRow(newRow)
|
||||
# Collect the oldRow after insert to make sure we move the correct
|
||||
# widget.
|
||||
oldRow = self.indexOfWidget(widget)
|
||||
|
||||
self.setCellWidget(newRow, self._main_column, widget)
|
||||
self.resizeRowToContents(oldRow)
|
||||
|
||||
# Remove the old row
|
||||
self.removeRow(oldRow)
|
||||
|
||||
def clear_widgets(self):
|
||||
'''Remove all widgets.'''
|
||||
self.clear()
|
||||
self.setRowCount(0)
|
||||
|
||||
def widget_index(self, widget):
|
||||
index = None
|
||||
for row in range(self.count()):
|
||||
candidateWidget = self.widget_at(row)
|
||||
if candidateWidget == widget:
|
||||
index = row
|
||||
break
|
||||
|
||||
return index
|
||||
|
||||
def widgets(self):
|
||||
widgets = []
|
||||
for row in range(self.count()):
|
||||
widget = self.widget_at(row)
|
||||
widgets.append(widget)
|
||||
|
||||
return widgets
|
||||
|
||||
def widget_at(self, row):
|
||||
return self.cellWidget(row, self._main_column)
|
||||
52
pype/standalonepublish/widgets/widget_drop_empty.py
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import os
|
||||
import logging
|
||||
import clique
|
||||
from . import QtWidgets, QtCore, QtGui
|
||||
|
||||
|
||||
class DropEmpty(QtWidgets.QWidget):
|
||||
|
||||
def __init__(self, parent):
|
||||
'''Initialise DataDropZone widget.'''
|
||||
super().__init__(parent)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
|
||||
BottomCenterAlignment = QtCore.Qt.AlignBottom | QtCore.Qt.AlignHCenter
|
||||
TopCenterAlignment = QtCore.Qt.AlignTop | QtCore.Qt.AlignHCenter
|
||||
|
||||
font = QtGui.QFont()
|
||||
font.setFamily("DejaVu Sans Condensed")
|
||||
font.setPointSize(26)
|
||||
font.setBold(True)
|
||||
font.setWeight(50)
|
||||
font.setKerning(True)
|
||||
|
||||
self._label = QtWidgets.QLabel('Drag & Drop')
|
||||
self._label.setFont(font)
|
||||
self._label.setStyleSheet(
|
||||
'background-color: rgb(255, 255, 255, 0);'
|
||||
)
|
||||
|
||||
font.setPointSize(12)
|
||||
self._sub_label = QtWidgets.QLabel('(drop files here)')
|
||||
self._sub_label.setFont(font)
|
||||
self._sub_label.setStyleSheet(
|
||||
'background-color: rgb(255, 255, 255, 0);'
|
||||
)
|
||||
|
||||
layout.addWidget(self._label, alignment=BottomCenterAlignment)
|
||||
layout.addWidget(self._sub_label, alignment=TopCenterAlignment)
|
||||
|
||||
def paintEvent(self, event):
|
||||
super().paintEvent(event)
|
||||
painter = QtGui.QPainter(self)
|
||||
pen = QtGui.QPen()
|
||||
pen.setWidth(1);
|
||||
pen.setBrush(QtCore.Qt.darkGray);
|
||||
pen.setStyle(QtCore.Qt.DashLine);
|
||||
painter.setPen(pen)
|
||||
painter.drawRect(
|
||||
10, 10,
|
||||
self.rect().width()-15, self.rect().height()-15
|
||||
)
|
||||
427
pype/standalonepublish/widgets/widget_drop_frame.py
Normal file
|
|
@ -0,0 +1,427 @@
|
|||
import os
|
||||
import re
|
||||
import clique
|
||||
import subprocess
|
||||
from pypeapp import config
|
||||
from . import QtWidgets, QtCore
|
||||
from . import DropEmpty, ComponentsList, ComponentItem
|
||||
|
||||
|
||||
class DropDataFrame(QtWidgets.QFrame):
|
||||
def __init__(self, parent):
|
||||
super().__init__()
|
||||
self.parent_widget = parent
|
||||
self.presets = config.get_presets()['standalone_publish']
|
||||
|
||||
self.setAcceptDrops(True)
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
self.components_list = ComponentsList(self)
|
||||
layout.addWidget(self.components_list)
|
||||
|
||||
self.drop_widget = DropEmpty(self)
|
||||
|
||||
sizePolicy = QtWidgets.QSizePolicy(
|
||||
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
|
||||
sizePolicy.setHorizontalStretch(0)
|
||||
sizePolicy.setVerticalStretch(0)
|
||||
sizePolicy.setHeightForWidth(self.drop_widget.sizePolicy().hasHeightForWidth())
|
||||
self.drop_widget.setSizePolicy(sizePolicy)
|
||||
|
||||
layout.addWidget(self.drop_widget)
|
||||
|
||||
self._refresh_view()
|
||||
|
||||
def dragEnterEvent(self, event):
|
||||
event.setDropAction(QtCore.Qt.CopyAction)
|
||||
event.accept()
|
||||
|
||||
def dragLeaveEvent(self, event):
|
||||
event.accept()
|
||||
|
||||
def dropEvent(self, event):
|
||||
self.process_ent_mime(event)
|
||||
event.accept()
|
||||
|
||||
def process_ent_mime(self, ent):
|
||||
paths = []
|
||||
if ent.mimeData().hasUrls():
|
||||
paths = self._processMimeData(ent.mimeData())
|
||||
else:
|
||||
# If path is in clipboard as string
|
||||
try:
|
||||
path = ent.text()
|
||||
if os.path.exists(path):
|
||||
paths.append(path)
|
||||
else:
|
||||
print('Dropped invalid file/folder')
|
||||
except Exception:
|
||||
pass
|
||||
if paths:
|
||||
self._process_paths(paths)
|
||||
|
||||
def _processMimeData(self, mimeData):
|
||||
paths = []
|
||||
|
||||
for path in mimeData.urls():
|
||||
local_path = path.toLocalFile()
|
||||
if os.path.isfile(local_path) or os.path.isdir(local_path):
|
||||
paths.append(local_path)
|
||||
else:
|
||||
print('Invalid input: "{}"'.format(local_path))
|
||||
return paths
|
||||
|
||||
def _add_item(self, data, actions=[]):
|
||||
# Assign to self so garbage collector wont remove the component
|
||||
# during initialization
|
||||
new_component = ComponentItem(self.components_list, self)
|
||||
new_component.set_context(data)
|
||||
self.components_list.add_widget(new_component)
|
||||
|
||||
new_component.signal_remove.connect(self._remove_item)
|
||||
new_component.signal_preview.connect(self._set_preview)
|
||||
new_component.signal_thumbnail.connect(
|
||||
self._set_thumbnail
|
||||
)
|
||||
new_component.signal_repre_change.connect(self.repre_name_changed)
|
||||
for action in actions:
|
||||
new_component.add_action(action)
|
||||
|
||||
if len(self.components_list.widgets()) == 1:
|
||||
self.parent_widget.set_valid_repre_names(True)
|
||||
self._refresh_view()
|
||||
|
||||
def _set_thumbnail(self, in_item):
|
||||
checked_item = None
|
||||
for item in self.components_list.widgets():
|
||||
if item.is_thumbnail():
|
||||
checked_item = item
|
||||
break
|
||||
if checked_item is None or checked_item == in_item:
|
||||
in_item.change_thumbnail()
|
||||
else:
|
||||
checked_item.change_thumbnail(False)
|
||||
in_item.change_thumbnail()
|
||||
|
||||
def _set_preview(self, in_item):
|
||||
checked_item = None
|
||||
for item in self.components_list.widgets():
|
||||
if item.is_preview():
|
||||
checked_item = item
|
||||
break
|
||||
if checked_item is None or checked_item == in_item:
|
||||
in_item.change_preview()
|
||||
else:
|
||||
checked_item.change_preview(False)
|
||||
in_item.change_preview()
|
||||
|
||||
def _remove_item(self, in_item):
|
||||
valid_repre = in_item.has_valid_repre is True
|
||||
|
||||
self.components_list.remove_widget(
|
||||
self.components_list.widget_index(in_item)
|
||||
)
|
||||
self._refresh_view()
|
||||
if valid_repre:
|
||||
return
|
||||
for item in self.components_list.widgets():
|
||||
if item.has_valid_repre:
|
||||
continue
|
||||
self.repre_name_changed(item, item.input_repre.text())
|
||||
|
||||
def _refresh_view(self):
|
||||
_bool = len(self.components_list.widgets()) == 0
|
||||
self.components_list.setVisible(not _bool)
|
||||
self.drop_widget.setVisible(_bool)
|
||||
|
||||
self.parent_widget.set_valid_components(not _bool)
|
||||
|
||||
def _process_paths(self, in_paths):
|
||||
self.parent_widget.working_start()
|
||||
paths = self._get_all_paths(in_paths)
|
||||
collections, remainders = clique.assemble(paths)
|
||||
for collection in collections:
|
||||
self._process_collection(collection)
|
||||
for remainder in remainders:
|
||||
self._process_remainder(remainder)
|
||||
self.parent_widget.working_stop()
|
||||
|
||||
def _get_all_paths(self, paths):
|
||||
output_paths = []
|
||||
for path in paths:
|
||||
path = os.path.normpath(path)
|
||||
if os.path.isfile(path):
|
||||
output_paths.append(path)
|
||||
elif os.path.isdir(path):
|
||||
s_paths = []
|
||||
for s_item in os.listdir(path):
|
||||
s_path = os.path.sep.join([path, s_item])
|
||||
s_paths.append(s_path)
|
||||
output_paths.extend(self._get_all_paths(s_paths))
|
||||
else:
|
||||
print('Invalid path: "{}"'.format(path))
|
||||
return output_paths
|
||||
|
||||
def _process_collection(self, collection):
|
||||
file_base = os.path.basename(collection.head)
|
||||
folder_path = os.path.dirname(collection.head)
|
||||
if file_base[-1] in ['.', '_']:
|
||||
file_base = file_base[:-1]
|
||||
file_ext = collection.tail
|
||||
repr_name = file_ext.replace('.', '')
|
||||
range = collection.format('{ranges}')
|
||||
|
||||
actions = []
|
||||
|
||||
data = {
|
||||
'files': [file for file in collection],
|
||||
'name': file_base,
|
||||
'ext': file_ext,
|
||||
'file_info': range,
|
||||
'representation': repr_name,
|
||||
'folder_path': folder_path,
|
||||
'is_sequence': True,
|
||||
'actions': actions
|
||||
}
|
||||
self._process_data(data)
|
||||
|
||||
def _get_ranges(self, indexes):
|
||||
if len(indexes) == 1:
|
||||
return str(indexes[0])
|
||||
ranges = []
|
||||
first = None
|
||||
last = None
|
||||
for index in indexes:
|
||||
if first is None:
|
||||
first = index
|
||||
last = index
|
||||
elif (last+1) == index:
|
||||
last = index
|
||||
else:
|
||||
if first == last:
|
||||
range = str(first)
|
||||
else:
|
||||
range = '{}-{}'.format(first, last)
|
||||
ranges.append(range)
|
||||
first = index
|
||||
last = index
|
||||
if first == last:
|
||||
range = str(first)
|
||||
else:
|
||||
range = '{}-{}'.format(first, last)
|
||||
ranges.append(range)
|
||||
return ', '.join(ranges)
|
||||
|
||||
def _process_remainder(self, remainder):
|
||||
filename = os.path.basename(remainder)
|
||||
folder_path = os.path.dirname(remainder)
|
||||
file_base, file_ext = os.path.splitext(filename)
|
||||
repr_name = file_ext.replace('.', '')
|
||||
file_info = None
|
||||
|
||||
files = []
|
||||
files.append(remainder)
|
||||
|
||||
actions = []
|
||||
|
||||
data = {
|
||||
'files': files,
|
||||
'name': file_base,
|
||||
'ext': file_ext,
|
||||
'representation': repr_name,
|
||||
'folder_path': folder_path,
|
||||
'is_sequence': False,
|
||||
'actions': actions
|
||||
}
|
||||
data['file_info'] = self.get_file_info(data)
|
||||
|
||||
self._process_data(data)
|
||||
|
||||
def get_file_info(self, data):
|
||||
output = None
|
||||
if data['ext'] == '.mov':
|
||||
try:
|
||||
# ffProbe must be in PATH
|
||||
filepath = data['files'][0]
|
||||
args = ['ffprobe', '-show_streams', filepath]
|
||||
p = subprocess.Popen(
|
||||
args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
shell=True
|
||||
)
|
||||
datalines=[]
|
||||
for line in iter(p.stdout.readline, b''):
|
||||
line = line.decode("utf-8").replace('\r\n', '')
|
||||
datalines.append(line)
|
||||
|
||||
find_value = 'codec_name'
|
||||
for line in datalines:
|
||||
if line.startswith(find_value):
|
||||
output = line.replace(find_value + '=', '')
|
||||
break
|
||||
except Exception as e:
|
||||
pass
|
||||
return output
|
||||
|
||||
def _process_data(self, data):
|
||||
ext = data['ext']
|
||||
icon = 'default'
|
||||
for ico, exts in self.presets['extensions'].items():
|
||||
if ext in exts:
|
||||
icon = ico
|
||||
break
|
||||
# Add 's' to icon_name if is sequence (image -> images)
|
||||
if data['is_sequence']:
|
||||
icon += 's'
|
||||
data['icon'] = icon
|
||||
data['thumb'] = (
|
||||
ext in self.presets['extensions']['image_file'] or
|
||||
ext in self.presets['extensions']['video_file']
|
||||
)
|
||||
data['prev'] = ext in self.presets['extensions']['video_file']
|
||||
|
||||
actions = []
|
||||
new_is_seq = data['is_sequence']
|
||||
|
||||
found = False
|
||||
for item in self.components_list.widgets():
|
||||
if data['ext'] != item.in_data['ext']:
|
||||
continue
|
||||
if data['folder_path'] != item.in_data['folder_path']:
|
||||
continue
|
||||
|
||||
ex_is_seq = item.in_data['is_sequence']
|
||||
|
||||
# If both are single files
|
||||
if not new_is_seq and not ex_is_seq:
|
||||
if data['name'] == item.in_data['name']:
|
||||
found = True
|
||||
break
|
||||
paths = data['files']
|
||||
paths.extend(item.in_data['files'])
|
||||
c, r = clique.assemble(paths)
|
||||
if len(c) == 0:
|
||||
continue
|
||||
a_name = 'merge'
|
||||
item.add_action(a_name)
|
||||
if a_name not in actions:
|
||||
actions.append(a_name)
|
||||
|
||||
# If new is sequence and ex is single file
|
||||
elif new_is_seq and not ex_is_seq:
|
||||
if data['name'] not in item.in_data['name']:
|
||||
continue
|
||||
ex_file = item.in_data['files'][0]
|
||||
|
||||
a_name = 'merge'
|
||||
item.add_action(a_name)
|
||||
if a_name not in actions:
|
||||
actions.append(a_name)
|
||||
continue
|
||||
|
||||
# If new is single file existing is sequence
|
||||
elif not new_is_seq and ex_is_seq:
|
||||
if item.in_data['name'] not in data['name']:
|
||||
continue
|
||||
a_name = 'merge'
|
||||
item.add_action(a_name)
|
||||
if a_name not in actions:
|
||||
actions.append(a_name)
|
||||
|
||||
# If both are sequence
|
||||
else:
|
||||
if data['name'] != item.in_data['name']:
|
||||
continue
|
||||
if data['files'] == item.in_data['files']:
|
||||
found = True
|
||||
break
|
||||
a_name = 'merge'
|
||||
item.add_action(a_name)
|
||||
if a_name not in actions:
|
||||
actions.append(a_name)
|
||||
|
||||
if new_is_seq:
|
||||
actions.append('split')
|
||||
|
||||
if found is False:
|
||||
new_repre = self.handle_new_repre_name(data['representation'])
|
||||
data['representation'] = new_repre
|
||||
self._add_item(data, actions)
|
||||
|
||||
def handle_new_repre_name(self, repre_name):
|
||||
renamed = False
|
||||
for item in self.components_list.widgets():
|
||||
if repre_name == item.input_repre.text():
|
||||
check_regex = '_\w+$'
|
||||
result = re.findall(check_regex, repre_name)
|
||||
next_num = 2
|
||||
if len(result) == 1:
|
||||
repre_name = repre_name.replace(result[0], '')
|
||||
next_num = int(result[0].replace('_', ''))
|
||||
next_num += 1
|
||||
repre_name = '{}_{}'.format(repre_name, next_num)
|
||||
renamed = True
|
||||
break
|
||||
if renamed:
|
||||
return self.handle_new_repre_name(repre_name)
|
||||
return repre_name
|
||||
|
||||
def repre_name_changed(self, in_item, repre_name):
|
||||
is_valid = True
|
||||
if repre_name.strip() == '':
|
||||
in_item.set_repre_name_valid(False)
|
||||
is_valid = False
|
||||
else:
|
||||
for item in self.components_list.widgets():
|
||||
if item == in_item:
|
||||
continue
|
||||
if item.input_repre.text() == repre_name:
|
||||
item.set_repre_name_valid(False)
|
||||
in_item.set_repre_name_valid(False)
|
||||
is_valid = False
|
||||
global_valid = is_valid
|
||||
if is_valid:
|
||||
in_item.set_repre_name_valid(True)
|
||||
for item in self.components_list.widgets():
|
||||
if item.has_valid_repre:
|
||||
continue
|
||||
self.repre_name_changed(item, item.input_repre.text())
|
||||
for item in self.components_list.widgets():
|
||||
if not item.has_valid_repre:
|
||||
global_valid = False
|
||||
break
|
||||
self.parent_widget.set_valid_repre_names(global_valid)
|
||||
|
||||
def merge_items(self, in_item):
|
||||
self.parent_widget.working_start()
|
||||
items = []
|
||||
in_paths = in_item.in_data['files']
|
||||
paths = in_paths
|
||||
for item in self.components_list.widgets():
|
||||
if item.in_data['files'] == in_paths:
|
||||
items.append(item)
|
||||
continue
|
||||
copy_paths = paths.copy()
|
||||
copy_paths.extend(item.in_data['files'])
|
||||
collections, remainders = clique.assemble(copy_paths)
|
||||
if len(collections) == 1 and len(remainders) == 0:
|
||||
paths.extend(item.in_data['files'])
|
||||
items.append(item)
|
||||
for item in items:
|
||||
self._remove_item(item)
|
||||
self._process_paths(paths)
|
||||
self.parent_widget.working_stop()
|
||||
|
||||
def split_items(self, item):
|
||||
self.parent_widget.working_start()
|
||||
paths = item.in_data['files']
|
||||
self._remove_item(item)
|
||||
for path in paths:
|
||||
self._process_remainder(path)
|
||||
self.parent_widget.working_stop()
|
||||
|
||||
def collect_data(self):
|
||||
data = {'representations' : []}
|
||||
for item in self.components_list.widgets():
|
||||
data['representations'].append(item.collect_data())
|
||||
return data
|
||||
288
pype/standalonepublish/widgets/widget_family.py
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
import os
|
||||
import sys
|
||||
import inspect
|
||||
import json
|
||||
from collections import namedtuple
|
||||
|
||||
from . import QtWidgets, QtCore
|
||||
from . import HelpRole, FamilyRole, ExistsRole, PluginRole
|
||||
from . import FamilyDescriptionWidget
|
||||
|
||||
from pypeapp import config
|
||||
|
||||
|
||||
class FamilyWidget(QtWidgets.QWidget):
|
||||
|
||||
stateChanged = QtCore.Signal(bool)
|
||||
data = dict()
|
||||
_jobs = dict()
|
||||
Separator = "---separator---"
|
||||
|
||||
def __init__(self, parent):
|
||||
super().__init__(parent)
|
||||
# Store internal states in here
|
||||
self.state = {"valid": False}
|
||||
self.parent_widget = parent
|
||||
|
||||
body = QtWidgets.QWidget()
|
||||
lists = QtWidgets.QWidget()
|
||||
|
||||
container = QtWidgets.QWidget()
|
||||
|
||||
list_families = QtWidgets.QListWidget()
|
||||
input_asset = QtWidgets.QLineEdit()
|
||||
input_asset.setEnabled(False)
|
||||
input_asset.setStyleSheet("color: #BBBBBB;")
|
||||
input_subset = QtWidgets.QLineEdit()
|
||||
input_result = QtWidgets.QLineEdit()
|
||||
input_result.setStyleSheet("color: gray;")
|
||||
input_result.setEnabled(False)
|
||||
|
||||
# region Menu for default subset names
|
||||
btn_subset = QtWidgets.QPushButton()
|
||||
btn_subset.setFixedWidth(18)
|
||||
btn_subset.setFixedHeight(20)
|
||||
menu_subset = QtWidgets.QMenu(btn_subset)
|
||||
btn_subset.setMenu(menu_subset)
|
||||
|
||||
# endregion
|
||||
name_layout = QtWidgets.QHBoxLayout()
|
||||
name_layout.addWidget(input_subset)
|
||||
name_layout.addWidget(btn_subset)
|
||||
name_layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(container)
|
||||
|
||||
header = FamilyDescriptionWidget(self)
|
||||
layout.addWidget(header)
|
||||
|
||||
layout.addWidget(QtWidgets.QLabel("Family"))
|
||||
layout.addWidget(list_families)
|
||||
layout.addWidget(QtWidgets.QLabel("Asset"))
|
||||
layout.addWidget(input_asset)
|
||||
layout.addWidget(QtWidgets.QLabel("Subset"))
|
||||
layout.addLayout(name_layout)
|
||||
layout.addWidget(input_result)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
options = QtWidgets.QWidget()
|
||||
|
||||
layout = QtWidgets.QGridLayout(options)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(lists)
|
||||
layout.addWidget(container)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(body)
|
||||
layout.addWidget(lists)
|
||||
layout.addWidget(options, 0, QtCore.Qt.AlignLeft)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
layout = QtWidgets.QVBoxLayout(self)
|
||||
layout.addWidget(body)
|
||||
|
||||
input_subset.textChanged.connect(self.on_data_changed)
|
||||
input_asset.textChanged.connect(self.on_data_changed)
|
||||
list_families.currentItemChanged.connect(self.on_selection_changed)
|
||||
list_families.currentItemChanged.connect(header.set_item)
|
||||
|
||||
self.stateChanged.connect(self._on_state_changed)
|
||||
|
||||
self.input_subset = input_subset
|
||||
self.menu_subset = menu_subset
|
||||
self.btn_subset = btn_subset
|
||||
self.list_families = list_families
|
||||
self.input_asset = input_asset
|
||||
self.input_result = input_result
|
||||
|
||||
self.refresh()
|
||||
|
||||
def collect_data(self):
|
||||
plugin = self.list_families.currentItem().data(PluginRole)
|
||||
family = plugin.family.rsplit(".", 1)[-1]
|
||||
data = {
|
||||
'family': family,
|
||||
'subset': self.input_subset.text()
|
||||
}
|
||||
return data
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
return self.parent_widget.db
|
||||
|
||||
def change_asset(self, name):
|
||||
self.input_asset.setText(name)
|
||||
|
||||
def _on_state_changed(self, state):
|
||||
self.state['valid'] = state
|
||||
self.parent_widget.set_valid_family(state)
|
||||
|
||||
def _build_menu(self, default_names):
|
||||
"""Create optional predefined subset names
|
||||
|
||||
Args:
|
||||
default_names(list): all predefined names
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
# Get and destroy the action group
|
||||
group = self.btn_subset.findChild(QtWidgets.QActionGroup)
|
||||
if group:
|
||||
group.deleteLater()
|
||||
|
||||
state = any(default_names)
|
||||
self.btn_subset.setEnabled(state)
|
||||
if state is False:
|
||||
return
|
||||
|
||||
# Build new action group
|
||||
group = QtWidgets.QActionGroup(self.btn_subset)
|
||||
for name in default_names:
|
||||
if name == self.Separator:
|
||||
self.menu_subset.addSeparator()
|
||||
continue
|
||||
action = group.addAction(name)
|
||||
self.menu_subset.addAction(action)
|
||||
|
||||
group.triggered.connect(self._on_action_clicked)
|
||||
|
||||
def _on_action_clicked(self, action):
|
||||
self.input_subset.setText(action.text())
|
||||
|
||||
def _on_data_changed(self):
|
||||
item = self.list_families.currentItem()
|
||||
subset_name = self.input_subset.text()
|
||||
asset_name = self.input_asset.text()
|
||||
|
||||
# Get the assets from the database which match with the name
|
||||
assets_db = self.db.find(filter={"type": "asset"}, projection={"name": 1})
|
||||
assets = [asset for asset in assets_db if asset_name in asset["name"]]
|
||||
if item is None:
|
||||
return
|
||||
if assets:
|
||||
# Get plugin and family
|
||||
plugin = item.data(PluginRole)
|
||||
if plugin is None:
|
||||
return
|
||||
family = plugin.family.rsplit(".", 1)[-1]
|
||||
|
||||
# Get all subsets of the current asset
|
||||
asset_ids = [asset["_id"] for asset in assets]
|
||||
subsets = self.db.find(filter={"type": "subset",
|
||||
"name": {"$regex": "{}*".format(family),
|
||||
"$options": "i"},
|
||||
"parent": {"$in": asset_ids}}) or []
|
||||
|
||||
# Get all subsets' their subset name, "Default", "High", "Low"
|
||||
existed_subsets = [sub["name"].split(family)[-1]
|
||||
for sub in subsets]
|
||||
|
||||
if plugin.defaults and isinstance(plugin.defaults, list):
|
||||
defaults = plugin.defaults[:] + [self.Separator]
|
||||
lowered = [d.lower() for d in plugin.defaults]
|
||||
for sub in [s for s in existed_subsets
|
||||
if s.lower() not in lowered]:
|
||||
defaults.append(sub)
|
||||
else:
|
||||
defaults = existed_subsets
|
||||
|
||||
self._build_menu(defaults)
|
||||
|
||||
# Update the result
|
||||
if subset_name:
|
||||
subset_name = subset_name[0].upper() + subset_name[1:]
|
||||
self.input_result.setText("{}{}".format(family, subset_name))
|
||||
|
||||
item.setData(ExistsRole, True)
|
||||
self.echo("Ready ..")
|
||||
else:
|
||||
self._build_menu([])
|
||||
item.setData(ExistsRole, False)
|
||||
if asset_name != self.parent_widget.NOT_SELECTED:
|
||||
self.echo("'%s' not found .." % asset_name)
|
||||
|
||||
# Update the valid state
|
||||
valid = (
|
||||
subset_name.strip() != "" and
|
||||
asset_name.strip() != "" and
|
||||
item.data(QtCore.Qt.ItemIsEnabled) and
|
||||
item.data(ExistsRole)
|
||||
)
|
||||
self.stateChanged.emit(valid)
|
||||
|
||||
def on_data_changed(self, *args):
|
||||
|
||||
# Set invalid state until it's reconfirmed to be valid by the
|
||||
# scheduled callback so any form of creation is held back until
|
||||
# valid again
|
||||
self.stateChanged.emit(False)
|
||||
self.schedule(self._on_data_changed, 500, channel="gui")
|
||||
|
||||
def on_selection_changed(self, *args):
|
||||
plugin = self.list_families.currentItem().data(PluginRole)
|
||||
if plugin is None:
|
||||
return
|
||||
|
||||
if plugin.defaults and isinstance(plugin.defaults, list):
|
||||
default = plugin.defaults[0]
|
||||
else:
|
||||
default = "Default"
|
||||
|
||||
self.input_subset.setText(default)
|
||||
|
||||
self.on_data_changed()
|
||||
|
||||
def keyPressEvent(self, event):
|
||||
"""Custom keyPressEvent.
|
||||
|
||||
Override keyPressEvent to do nothing so that Maya's panels won't
|
||||
take focus when pressing "SHIFT" whilst mouse is over viewport or
|
||||
outliner. This way users don't accidently perform Maya commands
|
||||
whilst trying to name an instance.
|
||||
|
||||
"""
|
||||
|
||||
def refresh(self):
|
||||
has_families = False
|
||||
presets = config.get_presets().get('standalone_publish', {})
|
||||
|
||||
for creator in presets.get('families', {}).values():
|
||||
creator = namedtuple("Creator", creator.keys())(*creator.values())
|
||||
|
||||
label = creator.label or creator.family
|
||||
item = QtWidgets.QListWidgetItem(label)
|
||||
item.setData(QtCore.Qt.ItemIsEnabled, True)
|
||||
item.setData(HelpRole, creator.help or "")
|
||||
item.setData(FamilyRole, creator.family)
|
||||
item.setData(PluginRole, creator)
|
||||
item.setData(ExistsRole, False)
|
||||
self.list_families.addItem(item)
|
||||
|
||||
has_families = True
|
||||
|
||||
if not has_families:
|
||||
item = QtWidgets.QListWidgetItem("No registered families")
|
||||
item.setData(QtCore.Qt.ItemIsEnabled, False)
|
||||
self.list_families.addItem(item)
|
||||
|
||||
self.list_families.setCurrentItem(self.list_families.item(0))
|
||||
|
||||
def echo(self, message):
|
||||
if hasattr(self.parent_widget, 'echo'):
|
||||
self.parent_widget.echo(message)
|
||||
|
||||
def schedule(self, func, time, channel="default"):
|
||||
try:
|
||||
self._jobs[channel].stop()
|
||||
except (AttributeError, KeyError):
|
||||
pass
|
||||
|
||||
timer = QtCore.QTimer()
|
||||
timer.setSingleShot(True)
|
||||
timer.timeout.connect(func)
|
||||
timer.start(time)
|
||||
|
||||
self._jobs[channel] = timer
|
||||
101
pype/standalonepublish/widgets/widget_family_desc.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import os
|
||||
import sys
|
||||
import inspect
|
||||
import json
|
||||
|
||||
from . import QtWidgets, QtCore, QtGui
|
||||
from . import HelpRole, FamilyRole, ExistsRole, PluginRole
|
||||
from . import awesome
|
||||
from pype.vendor import six
|
||||
from pype import lib as pypelib
|
||||
|
||||
|
||||
class FamilyDescriptionWidget(QtWidgets.QWidget):
|
||||
"""A family description widget.
|
||||
|
||||
Shows a family icon, family name and a help description.
|
||||
Used in creator header.
|
||||
|
||||
_________________
|
||||
| ____ |
|
||||
| |icon| FAMILY |
|
||||
| |____| help |
|
||||
|_________________|
|
||||
|
||||
"""
|
||||
|
||||
SIZE = 35
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super(FamilyDescriptionWidget, self).__init__(parent=parent)
|
||||
|
||||
# Header font
|
||||
font = QtGui.QFont()
|
||||
font.setBold(True)
|
||||
font.setPointSize(14)
|
||||
|
||||
layout = QtWidgets.QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
icon = QtWidgets.QLabel()
|
||||
icon.setSizePolicy(QtWidgets.QSizePolicy.Maximum,
|
||||
QtWidgets.QSizePolicy.Maximum)
|
||||
|
||||
# Add 4 pixel padding to avoid icon being cut off
|
||||
icon.setFixedWidth(self.SIZE + 4)
|
||||
icon.setFixedHeight(self.SIZE + 4)
|
||||
icon.setStyleSheet("""
|
||||
QLabel {
|
||||
padding-right: 5px;
|
||||
}
|
||||
""")
|
||||
|
||||
label_layout = QtWidgets.QVBoxLayout()
|
||||
label_layout.setSpacing(0)
|
||||
|
||||
family = QtWidgets.QLabel("family")
|
||||
family.setFont(font)
|
||||
family.setAlignment(QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft)
|
||||
|
||||
help = QtWidgets.QLabel("help")
|
||||
help.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
|
||||
|
||||
label_layout.addWidget(family)
|
||||
label_layout.addWidget(help)
|
||||
|
||||
layout.addWidget(icon)
|
||||
layout.addLayout(label_layout)
|
||||
|
||||
self.help = help
|
||||
self.family = family
|
||||
self.icon = icon
|
||||
|
||||
def set_item(self, item):
|
||||
"""Update elements to display information of a family item.
|
||||
|
||||
Args:
|
||||
family (dict): A family item as registered with name, help and icon
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
if not item:
|
||||
return
|
||||
|
||||
# Support a font-awesome icon
|
||||
plugin = item.data(PluginRole)
|
||||
icon = getattr(plugin, "icon", "info-circle")
|
||||
assert isinstance(icon, six.string_types)
|
||||
icon = awesome.icon("fa.{}".format(icon), color="white")
|
||||
pixmap = icon.pixmap(self.SIZE, self.SIZE)
|
||||
pixmap = pixmap.scaled(self.SIZE, self.SIZE)
|
||||
|
||||
# Parse a clean line from the Creator's docstring
|
||||
docstring = plugin.help or ""
|
||||
|
||||
help = docstring.splitlines()[0] if docstring else ""
|
||||
|
||||
self.icon.setPixmap(pixmap)
|
||||
self.family.setText(item.data(FamilyRole))
|
||||
self.help.setText(help)
|
||||
40
pype/standalonepublish/widgets/widget_shadow.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
from . import QtWidgets, QtCore, QtGui
|
||||
|
||||
|
||||
class ShadowWidget(QtWidgets.QWidget):
|
||||
def __init__(self, parent):
|
||||
self.parent_widget = parent
|
||||
super().__init__(parent)
|
||||
w = self.parent_widget.frameGeometry().width()
|
||||
h = self.parent_widget.frameGeometry().height()
|
||||
self.resize(QtCore.QSize(w, h))
|
||||
palette = QtGui.QPalette(self.palette())
|
||||
palette.setColor(palette.Background, QtCore.Qt.transparent)
|
||||
self.setPalette(palette)
|
||||
self.message = ''
|
||||
|
||||
font = QtGui.QFont()
|
||||
font.setFamily("DejaVu Sans Condensed")
|
||||
font.setPointSize(40)
|
||||
font.setBold(True)
|
||||
font.setWeight(50)
|
||||
font.setKerning(True)
|
||||
self.font = font
|
||||
|
||||
def paintEvent(self, event):
|
||||
painter = QtGui.QPainter()
|
||||
painter.begin(self)
|
||||
painter.setFont(self.font)
|
||||
painter.setRenderHint(QtGui.QPainter.Antialiasing)
|
||||
painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor(0, 0, 0, 127)))
|
||||
painter.drawText(
|
||||
QtCore.QRectF(
|
||||
0.0,
|
||||
0.0,
|
||||
self.parent_widget.frameGeometry().width(),
|
||||
self.parent_widget.frameGeometry().height()
|
||||
),
|
||||
QtCore.Qt.AlignCenter|QtCore.Qt.AlignCenter,
|
||||
self.message
|
||||
)
|
||||
painter.end()
|
||||
1108
setup/nukestudio/hiero_plugin_path/HieroPlayer/PlayerPresets.hrox
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
# This action adds itself to the Spreadsheet View context menu allowing the contents of the Spreadsheet be exported as a CSV file.
|
||||
# Usage: Right-click in Spreadsheet > "Export as .CSV"
|
||||
# Note: This only prints the text data that is visible in the active Spreadsheet View.
|
||||
# If you've filtered text, only the visible text will be printed to the CSV file
|
||||
# Usage: Copy to ~/.hiero/Python/StartupUI
|
||||
import hiero.core.events
|
||||
import hiero.ui
|
||||
import os, csv
|
||||
try:
|
||||
from PySide.QtGui import *
|
||||
from PySide.QtCore import *
|
||||
except:
|
||||
from PySide2.QtGui import *
|
||||
from PySide2.QtWidgets import *
|
||||
from PySide2.QtCore import *
|
||||
|
||||
|
||||
### Magic Widget Finding Methods - This stuff crawls all the PySide widgets, looking for an answer
|
||||
def findWidget(w):
|
||||
global foundryWidgets
|
||||
if 'Foundry' in w.metaObject().className():
|
||||
foundryWidgets += [w]
|
||||
|
||||
for c in w.children():
|
||||
findWidget(c)
|
||||
return foundryWidgets
|
||||
|
||||
|
||||
def getFoundryWidgetsWithClassName(filter=None):
|
||||
global foundryWidgets
|
||||
foundryWidgets = []
|
||||
widgets = []
|
||||
app = QApplication.instance()
|
||||
for w in app.topLevelWidgets():
|
||||
findWidget(w)
|
||||
|
||||
filteredWidgets = foundryWidgets
|
||||
if filter:
|
||||
filteredWidgets = []
|
||||
for widget in foundryWidgets:
|
||||
if filter in widget.metaObject().className():
|
||||
filteredWidgets += [widget]
|
||||
return filteredWidgets
|
||||
|
||||
|
||||
# When right click, get the Sequence Name
|
||||
def activeSpreadsheetTreeView():
|
||||
"""
|
||||
Does some PySide widget Magic to detect the Active Spreadsheet TreeView.
|
||||
"""
|
||||
spreadsheetViews = getFoundryWidgetsWithClassName(
|
||||
filter='SpreadsheetTreeView')
|
||||
for spreadSheet in spreadsheetViews:
|
||||
if spreadSheet.hasFocus():
|
||||
activeSpreadSheet = spreadSheet
|
||||
return activeSpreadSheet
|
||||
return None
|
||||
|
||||
|
||||
#### Adds "Export .CSV" action to the Spreadsheet Context menu ####
|
||||
class SpreadsheetExportCSVAction(QAction):
|
||||
def __init__(self):
|
||||
QAction.__init__(self, "Export as .CSV", None)
|
||||
self.triggered.connect(self.exportCSVFromActiveSpreadsheetView)
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kSpreadsheet",
|
||||
self.eventHandler)
|
||||
self.setIcon(QIcon("icons:FBGridView.png"))
|
||||
|
||||
def eventHandler(self, event):
|
||||
# Insert the action to the Export CSV menu
|
||||
event.menu.addAction(self)
|
||||
|
||||
#### The guts!.. Writes a CSV file from a Sequence Object ####
|
||||
def exportCSVFromActiveSpreadsheetView(self):
|
||||
|
||||
# Get the active QTreeView from the active Spreadsheet
|
||||
spreadsheetTreeView = activeSpreadsheetTreeView()
|
||||
|
||||
if not spreadsheetTreeView:
|
||||
return 'Unable to detect the active TreeView.'
|
||||
seq = hiero.ui.activeView().sequence()
|
||||
if not seq:
|
||||
print 'Unable to detect the active Sequence from the activeView.'
|
||||
return
|
||||
|
||||
# The data model of the QTreeView
|
||||
model = spreadsheetTreeView.model()
|
||||
|
||||
csvSavePath = os.path.join(QDir.homePath(), 'Desktop',
|
||||
seq.name() + '.csv')
|
||||
savePath, filter = QFileDialog.getSaveFileName(
|
||||
None,
|
||||
caption="Export Spreadsheet to .CSV as...",
|
||||
dir=csvSavePath,
|
||||
filter="*.csv")
|
||||
print 'Saving To: ' + str(savePath)
|
||||
|
||||
# Saving was cancelled...
|
||||
if len(savePath) == 0:
|
||||
return
|
||||
|
||||
# Get the Visible Header Columns from the QTreeView
|
||||
|
||||
#csvHeader = ['Event', 'Status', 'Shot Name', 'Reel', 'Track', 'Speed', 'Src In', 'Src Out','Src Duration', 'Dst In', 'Dst Out', 'Dst Duration', 'Clip', 'Clip Media']
|
||||
|
||||
# Get a CSV writer object
|
||||
f = open(savePath, 'w')
|
||||
csvWriter = csv.writer(
|
||||
f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
|
||||
|
||||
# This is a list of the Column titles
|
||||
csvHeader = []
|
||||
|
||||
for col in range(0, model.columnCount()):
|
||||
if not spreadsheetTreeView.isColumnHidden(col):
|
||||
csvHeader += [model.headerData(col, Qt.Horizontal)]
|
||||
|
||||
# Write the Header row to the CSV file
|
||||
csvWriter.writerow(csvHeader)
|
||||
|
||||
# Go through each row/column and print
|
||||
for row in range(model.rowCount()):
|
||||
row_data = []
|
||||
for col in range(model.columnCount()):
|
||||
if not spreadsheetTreeView.isColumnHidden(col):
|
||||
row_data.append(
|
||||
model.index(row, col, QModelIndex()).data(
|
||||
Qt.DisplayRole))
|
||||
|
||||
# Write row to CSV file...
|
||||
csvWriter.writerow(row_data)
|
||||
|
||||
f.close()
|
||||
# Conveniently show the CSV file in the native file browser...
|
||||
QDesktopServices.openUrl(
|
||||
QUrl('file:///%s' % (os.path.dirname(savePath))))
|
||||
|
||||
|
||||
# Add the action...
|
||||
csvActions = SpreadsheetExportCSVAction()
|
||||
19
setup/nukestudio/hiero_plugin_path/Python/Startup/Startup.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import traceback
|
||||
|
||||
# activate nukestudio from pype
|
||||
import avalon.api
|
||||
import pype.nukestudio
|
||||
avalon.api.install(pype.nukestudio)
|
||||
|
||||
try:
|
||||
__import__("pype.nukestudio")
|
||||
__import__("pyblish")
|
||||
|
||||
except ImportError as e:
|
||||
print traceback.format_exc()
|
||||
print("pyblish: Could not load integration: %s " % e)
|
||||
|
||||
else:
|
||||
# Setup integration
|
||||
import pype.nukestudio.lib
|
||||
pype.nukestudio.lib.setup()
|
||||
|
|
@ -0,0 +1,369 @@
|
|||
# MIT License
|
||||
#
|
||||
# Copyright (c) 2018 Daniel Flehner Heen (Storm Studios)
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
import hiero.core
|
||||
from hiero.core import util
|
||||
|
||||
import opentimelineio as otio
|
||||
|
||||
|
||||
marker_color_map = {
|
||||
"magenta": otio.schema.MarkerColor.MAGENTA,
|
||||
"red": otio.schema.MarkerColor.RED,
|
||||
"yellow": otio.schema.MarkerColor.YELLOW,
|
||||
"green": otio.schema.MarkerColor.GREEN,
|
||||
"cyan": otio.schema.MarkerColor.CYAN,
|
||||
"blue": otio.schema.MarkerColor.BLUE,
|
||||
}
|
||||
|
||||
|
||||
class OTIOExportTask(hiero.core.TaskBase):
|
||||
|
||||
def __init__(self, initDict):
|
||||
"""Initialize"""
|
||||
hiero.core.TaskBase.__init__(self, initDict)
|
||||
|
||||
def name(self):
|
||||
return str(type(self))
|
||||
|
||||
def get_rate(self, item):
|
||||
num, den = item.framerate().toRational()
|
||||
rate = float(num) / float(den)
|
||||
|
||||
if rate.is_integer():
|
||||
return rate
|
||||
|
||||
return round(rate, 2)
|
||||
|
||||
def get_clip_ranges(self, trackitem):
|
||||
# Is clip an audio file? Use sequence frame rate
|
||||
if not trackitem.source().mediaSource().hasVideo():
|
||||
rate_item = trackitem.sequence()
|
||||
|
||||
else:
|
||||
rate_item = trackitem.source()
|
||||
|
||||
source_rate = self.get_rate(rate_item)
|
||||
|
||||
# Reversed video/audio
|
||||
if trackitem.playbackSpeed() < 0:
|
||||
start = trackitem.sourceOut()
|
||||
|
||||
else:
|
||||
start = trackitem.sourceIn()
|
||||
|
||||
source_start_time = otio.opentime.RationalTime(
|
||||
start,
|
||||
source_rate
|
||||
)
|
||||
source_duration = otio.opentime.RationalTime(
|
||||
trackitem.duration(),
|
||||
source_rate
|
||||
)
|
||||
|
||||
source_range = otio.opentime.TimeRange(
|
||||
start_time=source_start_time,
|
||||
duration=source_duration
|
||||
)
|
||||
|
||||
available_range = None
|
||||
hiero_clip = trackitem.source()
|
||||
if not hiero_clip.mediaSource().isOffline():
|
||||
start_time = otio.opentime.RationalTime(
|
||||
hiero_clip.mediaSource().startTime(),
|
||||
source_rate
|
||||
)
|
||||
duration = otio.opentime.RationalTime(
|
||||
hiero_clip.mediaSource().duration(),
|
||||
source_rate
|
||||
)
|
||||
available_range = otio.opentime.TimeRange(
|
||||
start_time=start_time,
|
||||
duration=duration
|
||||
)
|
||||
|
||||
return source_range, available_range
|
||||
|
||||
def add_gap(self, trackitem, otio_track, prev_out):
|
||||
gap_length = trackitem.timelineIn() - prev_out
|
||||
if prev_out != 0:
|
||||
gap_length -= 1
|
||||
|
||||
rate = self.get_rate(trackitem.sequence())
|
||||
gap = otio.opentime.TimeRange(
|
||||
duration=otio.opentime.RationalTime(
|
||||
gap_length,
|
||||
rate
|
||||
)
|
||||
)
|
||||
otio_gap = otio.schema.Gap(source_range=gap)
|
||||
otio_track.append(otio_gap)
|
||||
|
||||
def get_marker_color(self, tag):
|
||||
icon = tag.icon()
|
||||
pat = 'icons:Tag(?P<color>\w+)\.\w+'
|
||||
|
||||
res = re.search(pat, icon)
|
||||
if res:
|
||||
color = res.groupdict().get('color')
|
||||
if color.lower() in marker_color_map:
|
||||
return marker_color_map[color.lower()]
|
||||
|
||||
return otio.schema.MarkerColor.RED
|
||||
|
||||
def add_markers(self, hiero_item, otio_item):
|
||||
for tag in hiero_item.tags():
|
||||
if not tag.visible():
|
||||
continue
|
||||
|
||||
if tag.name() == 'Copy':
|
||||
# Hiero adds this tag to a lot of clips
|
||||
continue
|
||||
|
||||
frame_rate = self.get_rate(hiero_item)
|
||||
|
||||
marked_range = otio.opentime.TimeRange(
|
||||
start_time=otio.opentime.RationalTime(
|
||||
tag.inTime(),
|
||||
frame_rate
|
||||
),
|
||||
duration=otio.opentime.RationalTime(
|
||||
int(tag.metadata().dict().get('tag.length', '0')),
|
||||
frame_rate
|
||||
)
|
||||
)
|
||||
|
||||
marker = otio.schema.Marker(
|
||||
name=tag.name(),
|
||||
color=self.get_marker_color(tag),
|
||||
marked_range=marked_range,
|
||||
metadata={
|
||||
'Hiero': tag.metadata().dict()
|
||||
}
|
||||
)
|
||||
|
||||
otio_item.markers.append(marker)
|
||||
|
||||
def add_clip(self, trackitem, otio_track, itemindex):
|
||||
hiero_clip = trackitem.source()
|
||||
|
||||
# Add Gap if needed
|
||||
prev_item = (
|
||||
itemindex and trackitem.parent().items()[itemindex - 1] or
|
||||
trackitem
|
||||
)
|
||||
|
||||
if prev_item == trackitem and trackitem.timelineIn() > 0:
|
||||
self.add_gap(trackitem, otio_track, 0)
|
||||
|
||||
elif (
|
||||
prev_item != trackitem and
|
||||
prev_item.timelineOut() != trackitem.timelineIn()
|
||||
):
|
||||
self.add_gap(trackitem, otio_track, prev_item.timelineOut())
|
||||
|
||||
# Create Clip
|
||||
source_range, available_range = self.get_clip_ranges(trackitem)
|
||||
|
||||
otio_clip = otio.schema.Clip()
|
||||
otio_clip.name = trackitem.name()
|
||||
otio_clip.source_range = source_range
|
||||
|
||||
# Add media reference
|
||||
media_reference = otio.schema.MissingReference()
|
||||
if not hiero_clip.mediaSource().isOffline():
|
||||
source = hiero_clip.mediaSource()
|
||||
media_reference = otio.schema.ExternalReference()
|
||||
media_reference.available_range = available_range
|
||||
|
||||
path, name = os.path.split(source.fileinfos()[0].filename())
|
||||
media_reference.target_url = os.path.join(path, name)
|
||||
media_reference.name = name
|
||||
|
||||
otio_clip.media_reference = media_reference
|
||||
|
||||
# Add Time Effects
|
||||
playbackspeed = trackitem.playbackSpeed()
|
||||
if playbackspeed != 1:
|
||||
if playbackspeed == 0:
|
||||
time_effect = otio.schema.FreezeFrame()
|
||||
|
||||
else:
|
||||
time_effect = otio.schema.LinearTimeWarp(
|
||||
time_scalar=playbackspeed
|
||||
)
|
||||
otio_clip.effects.append(time_effect)
|
||||
|
||||
# Add tags as markers
|
||||
if self._preset.properties()["includeTags"]:
|
||||
self.add_markers(trackitem.source(), otio_clip)
|
||||
|
||||
otio_track.append(otio_clip)
|
||||
|
||||
# Add Transition if needed
|
||||
if trackitem.inTransition() or trackitem.outTransition():
|
||||
self.add_transition(trackitem, otio_track)
|
||||
|
||||
def add_transition(self, trackitem, otio_track):
|
||||
transitions = []
|
||||
|
||||
if trackitem.inTransition():
|
||||
if trackitem.inTransition().alignment().name == 'kFadeIn':
|
||||
transitions.append(trackitem.inTransition())
|
||||
|
||||
if trackitem.outTransition():
|
||||
transitions.append(trackitem.outTransition())
|
||||
|
||||
for transition in transitions:
|
||||
alignment = transition.alignment().name
|
||||
|
||||
if alignment == 'kFadeIn':
|
||||
in_offset_frames = 0
|
||||
out_offset_frames = (
|
||||
transition.timelineOut() - transition.timelineIn()
|
||||
) + 1
|
||||
|
||||
elif alignment == 'kFadeOut':
|
||||
in_offset_frames = (
|
||||
trackitem.timelineOut() - transition.timelineIn()
|
||||
) + 1
|
||||
out_offset_frames = 0
|
||||
|
||||
elif alignment == 'kDissolve':
|
||||
in_offset_frames = (
|
||||
transition.inTrackItem().timelineOut() -
|
||||
transition.timelineIn()
|
||||
)
|
||||
out_offset_frames = (
|
||||
transition.timelineOut() -
|
||||
transition.outTrackItem().timelineIn()
|
||||
)
|
||||
|
||||
else:
|
||||
# kUnknown transition is ignored
|
||||
continue
|
||||
|
||||
rate = trackitem.source().framerate().toFloat()
|
||||
in_time = otio.opentime.RationalTime(in_offset_frames, rate)
|
||||
out_time = otio.opentime.RationalTime(out_offset_frames, rate)
|
||||
|
||||
otio_transition = otio.schema.Transition(
|
||||
name=alignment, # Consider placing Hiero name in metadata
|
||||
transition_type=otio.schema.TransitionTypes.SMPTE_Dissolve,
|
||||
in_offset=in_time,
|
||||
out_offset=out_time,
|
||||
metadata={}
|
||||
)
|
||||
|
||||
if alignment == 'kFadeIn':
|
||||
otio_track.insert(-2, otio_transition)
|
||||
|
||||
else:
|
||||
otio_track.append(otio_transition)
|
||||
|
||||
def add_tracks(self):
|
||||
for track in self._sequence.items():
|
||||
if isinstance(track, hiero.core.AudioTrack):
|
||||
kind = otio.schema.TrackKind.Audio
|
||||
|
||||
else:
|
||||
kind = otio.schema.TrackKind.Video
|
||||
|
||||
otio_track = otio.schema.Track(kind=kind)
|
||||
otio_track.name = track.name()
|
||||
|
||||
for itemindex, trackitem in enumerate(track):
|
||||
if isinstance(trackitem.source(), hiero.core.Clip):
|
||||
self.add_clip(trackitem, otio_track, itemindex)
|
||||
|
||||
self.otio_timeline.tracks.append(otio_track)
|
||||
|
||||
# Add tags as markers
|
||||
if self._preset.properties()["includeTags"]:
|
||||
self.add_markers(self._sequence, self.otio_timeline.tracks)
|
||||
|
||||
def create_OTIO(self):
|
||||
self.otio_timeline = otio.schema.Timeline()
|
||||
self.otio_timeline.name = self._sequence.name()
|
||||
|
||||
self.add_tracks()
|
||||
|
||||
def startTask(self):
|
||||
self.create_OTIO()
|
||||
|
||||
def taskStep(self):
|
||||
return False
|
||||
|
||||
def finishTask(self):
|
||||
try:
|
||||
exportPath = self.resolvedExportPath()
|
||||
|
||||
# Check file extension
|
||||
if not exportPath.lower().endswith(".otio"):
|
||||
exportPath += ".otio"
|
||||
|
||||
# check export root exists
|
||||
dirname = os.path.dirname(exportPath)
|
||||
util.filesystem.makeDirs(dirname)
|
||||
|
||||
# write otio file
|
||||
otio.adapters.write_to_file(self.otio_timeline, exportPath)
|
||||
|
||||
# Catch all exceptions and log error
|
||||
except Exception as e:
|
||||
self.setError("failed to write file {f}\n{e}".format(
|
||||
f=exportPath,
|
||||
e=e)
|
||||
)
|
||||
|
||||
hiero.core.TaskBase.finishTask(self)
|
||||
|
||||
def forcedAbort(self):
|
||||
pass
|
||||
|
||||
|
||||
class OTIOExportPreset(hiero.core.TaskPresetBase):
|
||||
def __init__(self, name, properties):
|
||||
"""Initialise presets to default values"""
|
||||
hiero.core.TaskPresetBase.__init__(self, OTIOExportTask, name)
|
||||
|
||||
self.properties()["includeTags"] = True
|
||||
self.properties().update(properties)
|
||||
|
||||
def supportedItems(self):
|
||||
return hiero.core.TaskPresetBase.kSequence
|
||||
|
||||
def addCustomResolveEntries(self, resolver):
|
||||
resolver.addResolver(
|
||||
"{ext}",
|
||||
"Extension of the file to be output",
|
||||
lambda keyword, task: "otio"
|
||||
)
|
||||
|
||||
def supportsAudio(self):
|
||||
return True
|
||||
|
||||
|
||||
hiero.core.taskRegistry.registerTask(OTIOExportPreset, OTIOExportTask)
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import hiero.ui
|
||||
import OTIOExportTask
|
||||
|
||||
try:
|
||||
# Hiero >= 11.x
|
||||
from PySide2 import QtCore
|
||||
from PySide2.QtWidgets import QCheckBox
|
||||
from hiero.ui.FnTaskUIFormLayout import TaskUIFormLayout as FormLayout
|
||||
|
||||
except ImportError:
|
||||
# Hiero <= 10.x
|
||||
from PySide import QtCore # lint:ok
|
||||
from PySide.QtGui import QCheckBox, QFormLayout # lint:ok
|
||||
|
||||
FormLayout = QFormLayout # lint:ok
|
||||
|
||||
|
||||
class OTIOExportUI(hiero.ui.TaskUIBase):
|
||||
def __init__(self, preset):
|
||||
"""Initialize"""
|
||||
hiero.ui.TaskUIBase.__init__(
|
||||
self,
|
||||
OTIOExportTask.OTIOExportTask,
|
||||
preset,
|
||||
"OTIO Exporter"
|
||||
)
|
||||
|
||||
def includeMarkersCheckboxChanged(self, state):
|
||||
# Slot to handle change of checkbox state
|
||||
self._preset.properties()["includeTags"] = state == QtCore.Qt.Checked
|
||||
|
||||
def populateUI(self, widget, exportTemplate):
|
||||
layout = widget.layout()
|
||||
formLayout = FormLayout()
|
||||
|
||||
# Hiero ~= 10.0v4
|
||||
if layout is None:
|
||||
layout = formLayout
|
||||
widget.setLayout(layout)
|
||||
|
||||
else:
|
||||
layout.addLayout(formLayout)
|
||||
|
||||
# Checkboxes for whether the OTIO should contain markers or not
|
||||
self.includeMarkersCheckbox = QCheckBox()
|
||||
self.includeMarkersCheckbox.setToolTip(
|
||||
"Enable to include Tags as markers in the exported OTIO file."
|
||||
)
|
||||
self.includeMarkersCheckbox.setCheckState(QtCore.Qt.Unchecked)
|
||||
|
||||
if self._preset.properties()["includeTags"]:
|
||||
self.includeMarkersCheckbox.setCheckState(QtCore.Qt.Checked)
|
||||
|
||||
self.includeMarkersCheckbox.stateChanged.connect(
|
||||
self.includeMarkersCheckboxChanged
|
||||
)
|
||||
|
||||
# Add Checkbox to layout
|
||||
formLayout.addRow("Include Tags:", self.includeMarkersCheckbox)
|
||||
|
||||
|
||||
hiero.ui.taskUIRegistry.registerTaskUI(
|
||||
OTIOExportTask.OTIOExportPreset,
|
||||
OTIOExportUI
|
||||
)
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
# MIT License
|
||||
#
|
||||
# Copyright (c) 2018 Daniel Flehner Heen (Storm Studios)
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
from OTIOExportTask import OTIOExportTask
|
||||
from OTIOExportUI import OTIOExportUI
|
||||
|
||||
__all__ = [
|
||||
'OTIOExportTask',
|
||||
'OTIOExportUI'
|
||||
]
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
"""Puts the selection project into 'hiero.selection'"""
|
||||
|
||||
import hiero
|
||||
|
||||
|
||||
def selectionChanged(event):
|
||||
hiero.selection = event.sender.selection()
|
||||
|
||||
hiero.core.events.registerInterest('kSelectionChanged', selectionChanged)
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
# setFrameRate - adds a Right-click menu to the Project Bin view, allowing multiple BinItems (Clips/Sequences) to have their frame rates set.
|
||||
# Install in: ~/.hiero/Python/StartupUI
|
||||
# Requires 1.5v1 or later
|
||||
|
||||
import hiero.core
|
||||
import hiero.ui
|
||||
try:
|
||||
from PySide.QtGui import *
|
||||
from PySide.QtCore import *
|
||||
except:
|
||||
from PySide2.QtGui import *
|
||||
from PySide2.QtCore import *
|
||||
from PySide2.QtWidgets import *
|
||||
|
||||
# Dialog for setting a Custom frame rate.
|
||||
class SetFrameRateDialog(QDialog):
|
||||
|
||||
def __init__(self,itemSelection=None,parent=None):
|
||||
super(SetFrameRateDialog, self).__init__(parent)
|
||||
self.setWindowTitle("Set Custom Frame Rate")
|
||||
self.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )
|
||||
layout = QFormLayout()
|
||||
self._itemSelection = itemSelection
|
||||
|
||||
self._frameRateField = QLineEdit()
|
||||
self._frameRateField.setToolTip('Enter custom frame rate here.')
|
||||
self._frameRateField.setValidator(QDoubleValidator(1, 99, 3, self))
|
||||
self._frameRateField.textChanged.connect(self._textChanged)
|
||||
layout.addRow("Enter fps: ",self._frameRateField)
|
||||
|
||||
# Standard buttons for Add/Cancel
|
||||
self._buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
|
||||
self._buttonbox.accepted.connect(self.accept)
|
||||
self._buttonbox.rejected.connect(self.reject)
|
||||
self._buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)
|
||||
layout.addRow("",self._buttonbox)
|
||||
self.setLayout(layout)
|
||||
|
||||
def _updateOkButtonState(self):
|
||||
# Cancel is always an option but only enable Ok if there is some text.
|
||||
currentFramerate = float(self.currentFramerateString())
|
||||
enableOk = False
|
||||
enableOk = ((currentFramerate > 0.0) and (currentFramerate <= 250.0))
|
||||
print 'enabledOk',enableOk
|
||||
self._buttonbox.button(QDialogButtonBox.Ok).setEnabled(enableOk)
|
||||
|
||||
def _textChanged(self, newText):
|
||||
self._updateOkButtonState()
|
||||
|
||||
# Returns the current frame rate as a string
|
||||
def currentFramerateString(self):
|
||||
return str(self._frameRateField.text())
|
||||
|
||||
# Presents the Dialog and sets the Frame rate from a selection
|
||||
def showDialogAndSetFrameRateFromSelection(self):
|
||||
|
||||
if self._itemSelection is not None:
|
||||
if self.exec_():
|
||||
# For the Undo loop...
|
||||
|
||||
# Construct an TimeBase object for setting the Frame Rate (fps)
|
||||
fps = hiero.core.TimeBase().fromString(self.currentFramerateString())
|
||||
|
||||
|
||||
# Set the frame rate for the selected BinItmes
|
||||
for item in self._itemSelection:
|
||||
item.setFramerate(fps)
|
||||
return
|
||||
|
||||
# This is just a convenience method for returning QActions with a title, triggered method and icon.
|
||||
def makeAction(title, method, icon = None):
|
||||
action = QAction(title,None)
|
||||
action.setIcon(QIcon(icon))
|
||||
|
||||
# We do this magic, so that the title string from the action is used to set the frame rate!
|
||||
def methodWrapper():
|
||||
method(title)
|
||||
|
||||
action.triggered.connect( methodWrapper )
|
||||
return action
|
||||
|
||||
# Menu which adds a Set Frame Rate Menu to Project Bin view
|
||||
class SetFrameRateMenu:
|
||||
|
||||
def __init__(self):
|
||||
self._frameRateMenu = None
|
||||
self._frameRatesDialog = None
|
||||
|
||||
|
||||
# ant: Could use hiero.core.defaultFrameRates() here but messes up with string matching because we seem to mix decimal points
|
||||
self.frameRates = ['8','12','12.50','15','23.98','24','25','29.97','30','48','50','59.94','60']
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kBin", self.binViewEventHandler)
|
||||
|
||||
self.menuActions = []
|
||||
|
||||
def createFrameRateMenus(self,selection):
|
||||
selectedClipFPS = [str(bi.activeItem().framerate()) for bi in selection if (isinstance(bi,hiero.core.BinItem) and hasattr(bi,'activeItem'))]
|
||||
selectedClipFPS = hiero.core.util.uniquify(selectedClipFPS)
|
||||
sameFrameRate = len(selectedClipFPS)==1
|
||||
self.menuActions = []
|
||||
for fps in self.frameRates:
|
||||
if fps in selectedClipFPS:
|
||||
if sameFrameRate:
|
||||
self.menuActions+=[makeAction(fps,self.setFrameRateFromMenuSelection, icon="icons:Ticked.png")]
|
||||
else:
|
||||
self.menuActions+=[makeAction(fps,self.setFrameRateFromMenuSelection, icon="icons:remove active.png")]
|
||||
else:
|
||||
self.menuActions+=[makeAction(fps,self.setFrameRateFromMenuSelection, icon=None)]
|
||||
|
||||
# Now add Custom... menu
|
||||
self.menuActions+=[makeAction('Custom...',self.setFrameRateFromMenuSelection, icon=None)]
|
||||
|
||||
frameRateMenu = QMenu("Set Frame Rate")
|
||||
for a in self.menuActions:
|
||||
frameRateMenu.addAction(a)
|
||||
|
||||
return frameRateMenu
|
||||
|
||||
def setFrameRateFromMenuSelection(self, menuSelectionFPS):
|
||||
|
||||
selectedBinItems = [bi.activeItem() for bi in self._selection if (isinstance(bi,hiero.core.BinItem) and hasattr(bi,'activeItem'))]
|
||||
currentProject = selectedBinItems[0].project()
|
||||
|
||||
with currentProject.beginUndo("Set Frame Rate"):
|
||||
if menuSelectionFPS == 'Custom...':
|
||||
self._frameRatesDialog = SetFrameRateDialog(itemSelection = selectedBinItems )
|
||||
self._frameRatesDialog.showDialogAndSetFrameRateFromSelection()
|
||||
|
||||
else:
|
||||
for b in selectedBinItems:
|
||||
b.setFramerate(hiero.core.TimeBase().fromString(menuSelectionFPS))
|
||||
|
||||
return
|
||||
|
||||
# This handles events from the Project Bin View
|
||||
def binViewEventHandler(self,event):
|
||||
if not hasattr(event.sender, 'selection'):
|
||||
# Something has gone wrong, we should only be here if raised
|
||||
# by the Bin view which gives a selection.
|
||||
return
|
||||
|
||||
# Reset the selection to None...
|
||||
self._selection = None
|
||||
s = event.sender.selection()
|
||||
|
||||
# Return if there's no Selection. We won't add the Menu.
|
||||
if s == None:
|
||||
return
|
||||
# Filter the selection to BinItems
|
||||
self._selection = [item for item in s if isinstance(item, hiero.core.BinItem)]
|
||||
if len(self._selection)==0:
|
||||
return
|
||||
# Creating the menu based on items selected, to highlight which frame rates are contained
|
||||
|
||||
self._frameRateMenu = self.createFrameRateMenus(self._selection)
|
||||
|
||||
# Insert the Set Frame Rate Button before the Set Media Colour Transform Action
|
||||
for action in event.menu.actions():
|
||||
if str(action.text()) == "Set Media Colour Transform":
|
||||
event.menu.insertMenu(action, self._frameRateMenu)
|
||||
break
|
||||
|
||||
# Instantiate the Menu to get it to register itself.
|
||||
SetFrameRateMenu = SetFrameRateMenu()
|
||||
|
|
@ -0,0 +1,352 @@
|
|||
# version_up_everywhere.py
|
||||
# Adds action to enable a Clip/Shot to be Min/Max/Next/Prev versioned in all shots used in a Project.
|
||||
#
|
||||
# Usage:
|
||||
# 1) Copy file to <HIERO_PLUGIN_PATH>/Python/Startup
|
||||
# 2) Right-click on Clip(s) or Bins containing Clips in in the Bin View, or on Shots in the Timeline/Spreadsheet
|
||||
# 3) Set Version for all Shots > OPTION to update the version in all shots where the Clip is used in the Project.
|
||||
|
||||
import hiero.core
|
||||
try:
|
||||
from PySide.QtGui import *
|
||||
from PySide.QtCore import *
|
||||
except:
|
||||
from PySide2.QtGui import *
|
||||
from PySide2.QtWidgets import *
|
||||
from PySide2.QtCore import *
|
||||
|
||||
|
||||
def whereAmI(self, searchType='TrackItem'):
|
||||
"""returns a list of TrackItem or Sequnece objects in the Project which contain this Clip.
|
||||
By default this will return a list of TrackItems where the Clip is used in its project.
|
||||
You can also return a list of Sequences by specifying the searchType to be 'Sequence'.
|
||||
Should consider putting this into hiero.core.Clip by default?
|
||||
|
||||
Example usage:
|
||||
|
||||
shotsForClip = clip.whereAmI('TrackItem')
|
||||
sequencesForClip = clip.whereAmI('Sequence')
|
||||
"""
|
||||
proj = self.project()
|
||||
|
||||
if ('TrackItem' not in searchType) and ('Sequence' not in searchType):
|
||||
print "searchType argument must be 'TrackItem' or 'Sequence'"
|
||||
return None
|
||||
|
||||
# If user specifies a TrackItem, then it will return
|
||||
searches = hiero.core.findItemsInProject(proj, searchType)
|
||||
|
||||
if len(searches) == 0:
|
||||
print 'Unable to find %s in any items of type: %s' % (str(self),
|
||||
str(searchType))
|
||||
return None
|
||||
|
||||
# Case 1: Looking for Shots (trackItems)
|
||||
clipUsedIn = []
|
||||
if isinstance(searches[0], hiero.core.TrackItem):
|
||||
for shot in searches:
|
||||
# We have to wrap this in a try/except because it's possible through the Python API for a Shot to exist without a Clip in the Bin
|
||||
try:
|
||||
|
||||
# For versioning to work, we must look to the BinItem that a Clip is wrapped in.
|
||||
if shot.source().binItem() == self.binItem():
|
||||
clipUsedIn.append(shot)
|
||||
|
||||
# If we throw an exception here its because the Shot did not have a Source Clip in the Bin.
|
||||
except RuntimeError:
|
||||
hiero.core.log.info(
|
||||
'Unable to find Parent Clip BinItem for Shot: %s, Source:%s'
|
||||
% (shot, shot.source()))
|
||||
pass
|
||||
|
||||
# Case 1: Looking for Shots (trackItems)
|
||||
elif isinstance(searches[0], hiero.core.Sequence):
|
||||
for seq in searches:
|
||||
# Iterate tracks > shots...
|
||||
tracks = seq.items()
|
||||
for track in tracks:
|
||||
shots = track.items()
|
||||
for shot in shots:
|
||||
if shot.source().binItem() == self.binItem():
|
||||
clipUsedIn.append(seq)
|
||||
|
||||
return clipUsedIn
|
||||
|
||||
|
||||
# Add whereAmI method to Clip object
|
||||
hiero.core.Clip.whereAmI = whereAmI
|
||||
|
||||
|
||||
#### MAIN VERSION EVERYWHERE GUBBINS #####
|
||||
class VersionAllMenu(object):
|
||||
|
||||
# These are a set of action names we can use for operating on multiple Clip/TrackItems
|
||||
eMaxVersion = "Max Version"
|
||||
eMinVersion = "Min Version"
|
||||
eNextVersion = "Next Version"
|
||||
ePreviousVersion = "Previous Version"
|
||||
|
||||
# This is the title used for the Version Menu title. It's long isn't it?
|
||||
actionTitle = "Set Version for all Shots"
|
||||
|
||||
def __init__(self):
|
||||
self._versionEverywhereMenu = None
|
||||
self._versionActions = []
|
||||
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kBin",
|
||||
self.binViewEventHandler)
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kTimeline",
|
||||
self.binViewEventHandler)
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kSpreadsheet",
|
||||
self.binViewEventHandler)
|
||||
|
||||
def showVersionUpdateReportFromShotManifest(self, sequenceShotManifest):
|
||||
"""This just displays an info Message box, based on a Sequence[Shot] manifest dictionary"""
|
||||
|
||||
# Now present an info dialog, explaining where shots were updated
|
||||
updateReportString = "The following Versions were updated:\n"
|
||||
for seq in sequenceShotManifest.keys():
|
||||
updateReportString += "%s:\n Shots:\n" % (seq.name())
|
||||
for shot in sequenceShotManifest[seq]:
|
||||
updateReportString += ' %s\n (New Version: %s)\n' % (
|
||||
shot.name(), shot.currentVersion().name())
|
||||
updateReportString += '\n'
|
||||
|
||||
infoBox = QMessageBox(hiero.ui.mainWindow())
|
||||
infoBox.setIcon(QMessageBox.Information)
|
||||
|
||||
if len(sequenceShotManifest) <= 0:
|
||||
infoBox.setText("No Shot Versions were updated")
|
||||
infoBox.setInformativeText(
|
||||
"Clip could not be found in any Shots in this Project")
|
||||
else:
|
||||
infoBox.setText(
|
||||
"Versions were updated in %i Sequences of this Project." %
|
||||
(len(sequenceShotManifest)))
|
||||
infoBox.setInformativeText("Show Details for more info.")
|
||||
infoBox.setDetailedText(updateReportString)
|
||||
|
||||
infoBox.exec_()
|
||||
|
||||
def makeVersionActionForSingleClip(self, version):
|
||||
"""This is used to populate the QAction list of Versions when a single Clip is selected in the BinView.
|
||||
It also triggers the Version Update action based on the version passed to it.
|
||||
(Not sure if this is good design practice, but it's compact!)"""
|
||||
action = QAction(version.name(), None)
|
||||
action.setData(lambda: version)
|
||||
|
||||
def updateAllTrackItems():
|
||||
currentClip = version.item()
|
||||
trackItems = currentClip.whereAmI()
|
||||
if not trackItems:
|
||||
return
|
||||
|
||||
proj = currentClip.project()
|
||||
|
||||
# A Sequence-Shot manifest dictionary
|
||||
sequenceShotManifest = {}
|
||||
|
||||
# Make this all undo-able in a single Group undo
|
||||
with proj.beginUndo(
|
||||
"Update All Versions for %s" % currentClip.name()):
|
||||
for shot in trackItems:
|
||||
seq = shot.parentSequence()
|
||||
if seq not in sequenceShotManifest.keys():
|
||||
sequenceShotManifest[seq] = [shot]
|
||||
else:
|
||||
sequenceShotManifest[seq] += [shot]
|
||||
shot.setCurrentVersion(version)
|
||||
|
||||
# We also should update the current Version of the selected Clip for completeness...
|
||||
currentClip.binItem().setActiveVersion(version)
|
||||
|
||||
# Now disaplay a Dialog which informs the user of where and what was changed
|
||||
self.showVersionUpdateReportFromShotManifest(sequenceShotManifest)
|
||||
|
||||
action.triggered.connect(updateAllTrackItems)
|
||||
return action
|
||||
|
||||
# This is just a convenience method for returning QActions with a title, triggered method and icon.
|
||||
def makeAction(self, title, method, icon=None):
|
||||
action = QAction(title, None)
|
||||
action.setIcon(QIcon(icon))
|
||||
|
||||
# We do this magic, so that the title string from the action is used to trigger the version change
|
||||
def methodWrapper():
|
||||
method(title)
|
||||
|
||||
action.triggered.connect(methodWrapper)
|
||||
return action
|
||||
|
||||
def clipSelectionFromView(self, view):
|
||||
"""Helper method to return a list of Clips in the Active View"""
|
||||
selection = hiero.ui.activeView().selection()
|
||||
|
||||
if len(selection) == 0:
|
||||
return None
|
||||
|
||||
if isinstance(view, hiero.ui.BinView):
|
||||
# We could have a mixture of Bins and Clips selected, so sort of the Clips and Clips inside Bins
|
||||
clipItems = [
|
||||
item.activeItem() for item in selection
|
||||
if hasattr(item, "activeItem")
|
||||
and isinstance(item.activeItem(), hiero.core.Clip)
|
||||
]
|
||||
|
||||
# We'll also append Bins here, and see if can find Clips inside
|
||||
bins = [
|
||||
item for item in selection if isinstance(item, hiero.core.Bin)
|
||||
]
|
||||
|
||||
# We search inside of a Bin for a Clip which is not already in clipBinItems
|
||||
if len(bins) > 0:
|
||||
# Grab the Clips inside of a Bin and append them to a list
|
||||
for bin in bins:
|
||||
clips = hiero.core.findItemsInBin(bin, 'Clip')
|
||||
for clip in clips:
|
||||
if clip not in clipItems:
|
||||
clipItems.append(clip)
|
||||
|
||||
elif isinstance(view,
|
||||
(hiero.ui.TimelineEditor, hiero.ui.SpreadsheetView)):
|
||||
# Here, we have shots. To get to the Clip froma TrackItem, just call source()
|
||||
clipItems = [
|
||||
item.source() for item in selection if hasattr(item, "source")
|
||||
and isinstance(item, hiero.core.TrackItem)
|
||||
]
|
||||
|
||||
return clipItems
|
||||
|
||||
# This generates the Version Up Everywhere menu
|
||||
def createVersionEveryWhereMenuForView(self, view):
|
||||
|
||||
versionEverywhereMenu = QMenu(self.actionTitle)
|
||||
self._versionActions = []
|
||||
# We look to the activeView for a selection of Clips
|
||||
clips = self.clipSelectionFromView(view)
|
||||
|
||||
# And bail if nothing is found
|
||||
if len(clips) == 0:
|
||||
return versionEverywhereMenu
|
||||
|
||||
# Now, if we have just one Clip selected, we'll form a special menu, which lists all versions
|
||||
if len(clips) == 1:
|
||||
|
||||
# Get a reversed list of Versions, so that bigger ones appear at top
|
||||
versions = list(reversed(clips[0].binItem().items()))
|
||||
for version in versions:
|
||||
self._versionActions += [
|
||||
self.makeVersionActionForSingleClip(version)
|
||||
]
|
||||
|
||||
elif len(clips) > 1:
|
||||
# We will add Max/Min/Prev/Next options, which can be called on a TrackItem, without the need for a Version object
|
||||
self._versionActions += [
|
||||
self.makeAction(
|
||||
self.eMaxVersion,
|
||||
self.setTrackItemVersionForClipSelection,
|
||||
icon=None)
|
||||
]
|
||||
self._versionActions += [
|
||||
self.makeAction(
|
||||
self.eMinVersion,
|
||||
self.setTrackItemVersionForClipSelection,
|
||||
icon=None)
|
||||
]
|
||||
self._versionActions += [
|
||||
self.makeAction(
|
||||
self.eNextVersion,
|
||||
self.setTrackItemVersionForClipSelection,
|
||||
icon=None)
|
||||
]
|
||||
self._versionActions += [
|
||||
self.makeAction(
|
||||
self.ePreviousVersion,
|
||||
self.setTrackItemVersionForClipSelection,
|
||||
icon=None)
|
||||
]
|
||||
|
||||
for act in self._versionActions:
|
||||
versionEverywhereMenu.addAction(act)
|
||||
|
||||
return versionEverywhereMenu
|
||||
|
||||
def setTrackItemVersionForClipSelection(self, versionOption):
|
||||
|
||||
view = hiero.ui.activeView()
|
||||
if not view:
|
||||
return
|
||||
|
||||
clipSelection = self.clipSelectionFromView(view)
|
||||
|
||||
if len(clipSelection) == 0:
|
||||
return
|
||||
|
||||
proj = clipSelection[0].project()
|
||||
|
||||
# Create a Sequence-Shot Manifest, to report to users where a Shot was updated
|
||||
sequenceShotManifest = {}
|
||||
|
||||
with proj.beginUndo("Update multiple Versions"):
|
||||
for clip in clipSelection:
|
||||
|
||||
# Look to see if it exists in a TrackItem somewhere...
|
||||
shotUsage = clip.whereAmI('TrackItem')
|
||||
|
||||
# Next, depending on the versionOption, make the appropriate update
|
||||
# There's probably a more neat/compact way of doing this...
|
||||
for shot in shotUsage:
|
||||
|
||||
# This step is done for reporting reasons
|
||||
seq = shot.parentSequence()
|
||||
if seq not in sequenceShotManifest.keys():
|
||||
sequenceShotManifest[seq] = [shot]
|
||||
else:
|
||||
sequenceShotManifest[seq] += [shot]
|
||||
|
||||
if versionOption == self.eMaxVersion:
|
||||
shot.maxVersion()
|
||||
elif versionOption == self.eMinVersion:
|
||||
shot.minVersion()
|
||||
elif versionOption == self.eNextVersion:
|
||||
shot.nextVersion()
|
||||
elif versionOption == self.ePreviousVersion:
|
||||
shot.prevVersion()
|
||||
|
||||
# Finally, for completeness, set the Max/Min version of the Clip too (if chosen)
|
||||
# Note: It doesn't make sense to do Next/Prev on a Clip here because next/prev means different things for different Shots
|
||||
if versionOption == self.eMaxVersion:
|
||||
clip.binItem().maxVersion()
|
||||
elif versionOption == self.eMinVersion:
|
||||
clip.binItem().minVersion()
|
||||
|
||||
# Now disaplay a Dialog which informs the user of where and what was changed
|
||||
self.showVersionUpdateReportFromShotManifest(sequenceShotManifest)
|
||||
|
||||
# This handles events from the Project Bin View
|
||||
def binViewEventHandler(self, event):
|
||||
|
||||
if not hasattr(event.sender, 'selection'):
|
||||
# Something has gone wrong, we should only be here if raised
|
||||
# by the Bin view which gives a selection.
|
||||
return
|
||||
selection = event.sender.selection()
|
||||
|
||||
# Return if there's no Selection. We won't add the Localise Menu.
|
||||
if selection == None:
|
||||
return
|
||||
|
||||
view = hiero.ui.activeView()
|
||||
# Only add the Menu if Bins or Sequences are selected (this ensures menu isn't added in the Tags Pane)
|
||||
if len(selection) > 0:
|
||||
self._versionEverywhereMenu = self.createVersionEveryWhereMenuForView(
|
||||
view)
|
||||
hiero.ui.insertMenuAction(
|
||||
self._versionEverywhereMenu.menuAction(),
|
||||
event.menu,
|
||||
after="foundry.menu.version")
|
||||
return
|
||||
|
||||
|
||||
# Instantiate the Menu to get it to register itself.
|
||||
VersionAllMenu = VersionAllMenu()
|
||||
|
|
@ -0,0 +1,844 @@
|
|||
# PimpMySpreadsheet 1.0, Antony Nasce, 23/05/13.
|
||||
# Adds custom spreadsheet columns and right-click menu for setting the Shot Status, and Artist Shot Assignement.
|
||||
# gStatusTags is a global dictionary of key(status)-value(icon) pairs, which can be overridden with custom icons if required
|
||||
# Requires Hiero 1.7v2 or later.
|
||||
# Install Instructions: Copy to ~/.hiero/Python/StartupUI
|
||||
|
||||
import hiero.core
|
||||
import hiero.ui
|
||||
|
||||
try:
|
||||
from PySide.QtGui import *
|
||||
from PySide.QtCore import *
|
||||
except:
|
||||
from PySide2.QtGui import *
|
||||
from PySide2.QtWidgets import *
|
||||
from PySide2.QtCore import *
|
||||
|
||||
# Set to True, if you wat 'Set Status' right-click menu, False if not
|
||||
kAddStatusMenu = True
|
||||
|
||||
# Set to True, if you wat 'Assign Artist' right-click menu, False if not
|
||||
kAssignArtistMenu = True
|
||||
|
||||
# Global list of Artist Name Dictionaries
|
||||
# Note: Override this to add different names, icons, department, IDs.
|
||||
gArtistList = [{
|
||||
'artistName': 'John Smith',
|
||||
'artistIcon': 'icons:TagActor.png',
|
||||
'artistDepartment': '3D',
|
||||
'artistID': 0
|
||||
}, {
|
||||
'artistName': 'Savlvador Dali',
|
||||
'artistIcon': 'icons:TagActor.png',
|
||||
'artistDepartment': 'Roto',
|
||||
'artistID': 1
|
||||
}, {
|
||||
'artistName': 'Leonardo Da Vinci',
|
||||
'artistIcon': 'icons:TagActor.png',
|
||||
'artistDepartment': 'Paint',
|
||||
'artistID': 2
|
||||
}, {
|
||||
'artistName': 'Claude Monet',
|
||||
'artistIcon': 'icons:TagActor.png',
|
||||
'artistDepartment': 'Comp',
|
||||
'artistID': 3
|
||||
}, {
|
||||
'artistName': 'Pablo Picasso',
|
||||
'artistIcon': 'icons:TagActor.png',
|
||||
'artistDepartment': 'Animation',
|
||||
'artistID': 4
|
||||
}]
|
||||
|
||||
# Global Dictionary of Status Tags.
|
||||
# Note: This can be overwritten if you want to add a new status cellType or custom icon
|
||||
# Override the gStatusTags dictionary by adding your own 'Status':'Icon.png' key-value pairs.
|
||||
# Add new custom keys like so: gStatusTags['For Client'] = 'forClient.png'
|
||||
gStatusTags = {
|
||||
'Approved': 'icons:status/TagApproved.png',
|
||||
'Unapproved': 'icons:status/TagUnapproved.png',
|
||||
'Ready To Start': 'icons:status/TagReadyToStart.png',
|
||||
'Blocked': 'icons:status/TagBlocked.png',
|
||||
'On Hold': 'icons:status/TagOnHold.png',
|
||||
'In Progress': 'icons:status/TagInProgress.png',
|
||||
'Awaiting Approval': 'icons:status/TagAwaitingApproval.png',
|
||||
'Omitted': 'icons:status/TagOmitted.png',
|
||||
'Final': 'icons:status/TagFinal.png'
|
||||
}
|
||||
|
||||
|
||||
# The Custom Spreadsheet Columns
|
||||
class CustomSpreadsheetColumns(QObject):
|
||||
"""
|
||||
A class defining custom columns for Hiero's spreadsheet view. This has a similar, but
|
||||
slightly simplified, interface to the QAbstractItemModel and QItemDelegate classes.
|
||||
"""
|
||||
global gStatusTags
|
||||
global gArtistList
|
||||
|
||||
# Ideally, we'd set this list on a Per Item basis, but this is expensive for a large mixed selection
|
||||
standardColourSpaces = [
|
||||
'linear', 'sRGB', 'rec709', 'Cineon', 'Gamma1.8', 'Gamma2.2',
|
||||
'Panalog', 'REDLog', 'ViperLog'
|
||||
]
|
||||
arriColourSpaces = [
|
||||
'Video - Rec709', 'LogC - Camera Native', 'Video - P3', 'ACES',
|
||||
'LogC - Film', 'LogC - Wide Gamut'
|
||||
]
|
||||
r3dColourSpaces = [
|
||||
'Linear', 'Rec709', 'REDspace', 'REDlog', 'PDlog685', 'PDlog985',
|
||||
'CustomPDlog', 'REDgamma', 'SRGB', 'REDlogFilm', 'REDgamma2',
|
||||
'REDgamma3'
|
||||
]
|
||||
gColourSpaces = standardColourSpaces + arriColourSpaces + r3dColourSpaces
|
||||
|
||||
currentView = hiero.ui.activeView()
|
||||
|
||||
# This is the list of Columns available
|
||||
gCustomColumnList = [
|
||||
{
|
||||
'name': 'Tags',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'Colourspace',
|
||||
'cellType': 'dropdown'
|
||||
},
|
||||
{
|
||||
'name': 'Notes',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'FileType',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'Shot Status',
|
||||
'cellType': 'dropdown'
|
||||
},
|
||||
{
|
||||
'name': 'Thumbnail',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'MediaType',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'Width',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'Height',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'Pixel Aspect',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
{
|
||||
'name': 'Artist',
|
||||
'cellType': 'dropdown'
|
||||
},
|
||||
{
|
||||
'name': 'Department',
|
||||
'cellType': 'readonly'
|
||||
},
|
||||
]
|
||||
|
||||
def numColumns(self):
|
||||
"""
|
||||
Return the number of custom columns in the spreadsheet view
|
||||
"""
|
||||
return len(self.gCustomColumnList)
|
||||
|
||||
def columnName(self, column):
|
||||
"""
|
||||
Return the name of a custom column
|
||||
"""
|
||||
return self.gCustomColumnList[column]['name']
|
||||
|
||||
def getTagsString(self, item):
|
||||
"""
|
||||
Convenience method for returning all the Notes in a Tag as a string
|
||||
"""
|
||||
tagNames = []
|
||||
tags = item.tags()
|
||||
for tag in tags:
|
||||
tagNames += [tag.name()]
|
||||
tagNameString = ','.join(tagNames)
|
||||
return tagNameString
|
||||
|
||||
def getNotes(self, item):
|
||||
"""
|
||||
Convenience method for returning all the Notes in a Tag as a string
|
||||
"""
|
||||
notes = ''
|
||||
tags = item.tags()
|
||||
for tag in tags:
|
||||
note = tag.note()
|
||||
if len(note) > 0:
|
||||
notes += tag.note() + ', '
|
||||
return notes[:-2]
|
||||
|
||||
def getData(self, row, column, item):
|
||||
"""
|
||||
Return the data in a cell
|
||||
"""
|
||||
currentColumn = self.gCustomColumnList[column]
|
||||
if currentColumn['name'] == 'Tags':
|
||||
return self.getTagsString(item)
|
||||
|
||||
if currentColumn['name'] == 'Colourspace':
|
||||
try:
|
||||
colTransform = item.sourceMediaColourTransform()
|
||||
except:
|
||||
colTransform = '--'
|
||||
return colTransform
|
||||
|
||||
if currentColumn['name'] == 'Notes':
|
||||
try:
|
||||
note = self.getNotes(item)
|
||||
except:
|
||||
note = ''
|
||||
return note
|
||||
|
||||
if currentColumn['name'] == 'FileType':
|
||||
fileType = '--'
|
||||
M = item.source().mediaSource().metadata()
|
||||
if M.hasKey('foundry.source.type'):
|
||||
fileType = M.value('foundry.source.type')
|
||||
elif M.hasKey('media.input.filereader'):
|
||||
fileType = M.value('media.input.filereader')
|
||||
return fileType
|
||||
|
||||
if currentColumn['name'] == 'Shot Status':
|
||||
status = item.status()
|
||||
if not status:
|
||||
status = "--"
|
||||
return str(status)
|
||||
|
||||
if currentColumn['name'] == 'MediaType':
|
||||
M = item.mediaType()
|
||||
return str(M).split('MediaType')[-1].replace('.k', '')
|
||||
|
||||
if currentColumn['name'] == 'Thumbnail':
|
||||
return str(item.eventNumber())
|
||||
|
||||
if currentColumn['name'] == 'Width':
|
||||
return str(item.source().format().width())
|
||||
|
||||
if currentColumn['name'] == 'Height':
|
||||
return str(item.source().format().height())
|
||||
|
||||
if currentColumn['name'] == 'Pixel Aspect':
|
||||
return str(item.source().format().pixelAspect())
|
||||
|
||||
if currentColumn['name'] == 'Artist':
|
||||
if item.artist():
|
||||
name = item.artist()['artistName']
|
||||
return name
|
||||
else:
|
||||
return '--'
|
||||
|
||||
if currentColumn['name'] == 'Department':
|
||||
if item.artist():
|
||||
dep = item.artist()['artistDepartment']
|
||||
return dep
|
||||
else:
|
||||
return '--'
|
||||
|
||||
return ""
|
||||
|
||||
def setData(self, row, column, item, data):
|
||||
"""
|
||||
Set the data in a cell - unused in this example
|
||||
"""
|
||||
|
||||
return None
|
||||
|
||||
def getTooltip(self, row, column, item):
|
||||
"""
|
||||
Return the tooltip for a cell
|
||||
"""
|
||||
currentColumn = self.gCustomColumnList[column]
|
||||
if currentColumn['name'] == 'Tags':
|
||||
return str([item.name() for item in item.tags()])
|
||||
|
||||
if currentColumn['name'] == 'Notes':
|
||||
return str(self.getNotes(item))
|
||||
return ""
|
||||
|
||||
def getFont(self, row, column, item):
|
||||
"""
|
||||
Return the tooltip for a cell
|
||||
"""
|
||||
return None
|
||||
|
||||
def getBackground(self, row, column, item):
|
||||
"""
|
||||
Return the background colour for a cell
|
||||
"""
|
||||
if not item.source().mediaSource().isMediaPresent():
|
||||
return QColor(80, 20, 20)
|
||||
return None
|
||||
|
||||
def getForeground(self, row, column, item):
|
||||
"""
|
||||
Return the text colour for a cell
|
||||
"""
|
||||
#if column == 1:
|
||||
# return QColor(255, 64, 64)
|
||||
return None
|
||||
|
||||
def getIcon(self, row, column, item):
|
||||
"""
|
||||
Return the icon for a cell
|
||||
"""
|
||||
currentColumn = self.gCustomColumnList[column]
|
||||
if currentColumn['name'] == 'Colourspace':
|
||||
return QIcon("icons:LUT.png")
|
||||
|
||||
if currentColumn['name'] == 'Shot Status':
|
||||
status = item.status()
|
||||
if status:
|
||||
return QIcon(gStatusTags[status])
|
||||
|
||||
if currentColumn['name'] == 'MediaType':
|
||||
mediaType = item.mediaType()
|
||||
if mediaType == hiero.core.TrackItem.kVideo:
|
||||
return QIcon("icons:VideoOnly.png")
|
||||
elif mediaType == hiero.core.TrackItem.kAudio:
|
||||
return QIcon("icons:AudioOnly.png")
|
||||
|
||||
if currentColumn['name'] == 'Artist':
|
||||
try:
|
||||
return QIcon(item.artist()['artistIcon'])
|
||||
except:
|
||||
return None
|
||||
return None
|
||||
|
||||
def getSizeHint(self, row, column, item):
|
||||
"""
|
||||
Return the size hint for a cell
|
||||
"""
|
||||
currentColumnName = self.gCustomColumnList[column]['name']
|
||||
|
||||
if currentColumnName == 'Thumbnail':
|
||||
return QSize(90, 50)
|
||||
|
||||
return QSize(50, 50)
|
||||
|
||||
def paintCell(self, row, column, item, painter, option):
|
||||
"""
|
||||
Paint a custom cell. Return True if the cell was painted, or False to continue
|
||||
with the default cell painting.
|
||||
"""
|
||||
currentColumn = self.gCustomColumnList[column]
|
||||
if currentColumn['name'] == 'Tags':
|
||||
if option.state & QStyle.State_Selected:
|
||||
painter.fillRect(option.rect, option.palette.highlight())
|
||||
iconSize = 20
|
||||
r = QRect(option.rect.x(),
|
||||
option.rect.y() + (option.rect.height() - iconSize) / 2,
|
||||
iconSize, iconSize)
|
||||
tags = item.tags()
|
||||
if len(tags) > 0:
|
||||
painter.save()
|
||||
painter.setClipRect(option.rect)
|
||||
for tag in item.tags():
|
||||
M = tag.metadata()
|
||||
if not (M.hasKey('tag.status')
|
||||
or M.hasKey('tag.artistID')):
|
||||
QIcon(tag.icon()).paint(painter, r, Qt.AlignLeft)
|
||||
r.translate(r.width() + 2, 0)
|
||||
painter.restore()
|
||||
return True
|
||||
|
||||
if currentColumn['name'] == 'Thumbnail':
|
||||
imageView = None
|
||||
pen = QPen()
|
||||
r = QRect(option.rect.x() + 2, (option.rect.y() +
|
||||
(option.rect.height() - 46) / 2),
|
||||
85, 46)
|
||||
if not item.source().mediaSource().isMediaPresent():
|
||||
imageView = QImage("icons:Offline.png")
|
||||
pen.setColor(QColor(Qt.red))
|
||||
|
||||
if item.mediaType() == hiero.core.TrackItem.MediaType.kAudio:
|
||||
imageView = QImage("icons:AudioOnly.png")
|
||||
#pen.setColor(QColor(Qt.green))
|
||||
painter.fillRect(r, QColor(45, 59, 45))
|
||||
|
||||
if option.state & QStyle.State_Selected:
|
||||
painter.fillRect(option.rect, option.palette.highlight())
|
||||
|
||||
tags = item.tags()
|
||||
painter.save()
|
||||
painter.setClipRect(option.rect)
|
||||
|
||||
if not imageView:
|
||||
try:
|
||||
imageView = item.thumbnail(item.sourceIn())
|
||||
pen.setColor(QColor(20, 20, 20))
|
||||
# If we're here, we probably have a TC error, no thumbnail, so get it from the source Clip...
|
||||
except:
|
||||
pen.setColor(QColor(Qt.red))
|
||||
|
||||
if not imageView:
|
||||
try:
|
||||
imageView = item.source().thumbnail()
|
||||
pen.setColor(QColor(Qt.yellow))
|
||||
except:
|
||||
imageView = QImage("icons:Offline.png")
|
||||
pen.setColor(QColor(Qt.red))
|
||||
|
||||
QIcon(QPixmap.fromImage(imageView)).paint(painter, r,
|
||||
Qt.AlignCenter)
|
||||
painter.setPen(pen)
|
||||
painter.drawRoundedRect(r, 1, 1)
|
||||
painter.restore()
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def createEditor(self, row, column, item, view):
|
||||
"""
|
||||
Create an editing widget for a custom cell
|
||||
"""
|
||||
self.currentView = view
|
||||
|
||||
currentColumn = self.gCustomColumnList[column]
|
||||
if currentColumn['cellType'] == 'readonly':
|
||||
cle = QLabel()
|
||||
cle.setEnabled(False)
|
||||
cle.setVisible(False)
|
||||
return cle
|
||||
|
||||
if currentColumn['name'] == 'Colourspace':
|
||||
cb = QComboBox()
|
||||
for colourspace in self.gColourSpaces:
|
||||
cb.addItem(colourspace)
|
||||
cb.currentIndexChanged.connect(self.colourspaceChanged)
|
||||
return cb
|
||||
|
||||
if currentColumn['name'] == 'Shot Status':
|
||||
cb = QComboBox()
|
||||
cb.addItem('')
|
||||
for key in gStatusTags.keys():
|
||||
cb.addItem(QIcon(gStatusTags[key]), key)
|
||||
cb.addItem('--')
|
||||
cb.currentIndexChanged.connect(self.statusChanged)
|
||||
|
||||
return cb
|
||||
|
||||
if currentColumn['name'] == 'Artist':
|
||||
cb = QComboBox()
|
||||
cb.addItem('')
|
||||
for artist in gArtistList:
|
||||
cb.addItem(artist['artistName'])
|
||||
cb.addItem('--')
|
||||
cb.currentIndexChanged.connect(self.artistNameChanged)
|
||||
return cb
|
||||
return None
|
||||
|
||||
def setModelData(self, row, column, item, editor):
|
||||
return False
|
||||
|
||||
def dropMimeData(self, row, column, item, data, items):
|
||||
"""
|
||||
Handle a drag and drop operation - adds a Dragged Tag to the shot
|
||||
"""
|
||||
for thing in items:
|
||||
if isinstance(thing, hiero.core.Tag):
|
||||
item.addTag(thing)
|
||||
return None
|
||||
|
||||
def colourspaceChanged(self, index):
|
||||
"""
|
||||
This method is called when Colourspace widget changes index.
|
||||
"""
|
||||
index = self.sender().currentIndex()
|
||||
colourspace = self.gColourSpaces[index]
|
||||
selection = self.currentView.selection()
|
||||
project = selection[0].project()
|
||||
with project.beginUndo("Set Colourspace"):
|
||||
items = [
|
||||
item for item in selection
|
||||
if (item.mediaType() == hiero.core.TrackItem.MediaType.kVideo)
|
||||
]
|
||||
for trackItem in items:
|
||||
trackItem.setSourceMediaColourTransform(colourspace)
|
||||
|
||||
def statusChanged(self, arg):
|
||||
"""
|
||||
This method is called when Shot Status widget changes index.
|
||||
"""
|
||||
view = hiero.ui.activeView()
|
||||
selection = view.selection()
|
||||
status = self.sender().currentText()
|
||||
project = selection[0].project()
|
||||
with project.beginUndo("Set Status"):
|
||||
# A string of '--' characters denotes clear the status
|
||||
if status != '--':
|
||||
for trackItem in selection:
|
||||
trackItem.setStatus(status)
|
||||
else:
|
||||
for trackItem in selection:
|
||||
tTags = trackItem.tags()
|
||||
for tag in tTags:
|
||||
if tag.metadata().hasKey('tag.status'):
|
||||
trackItem.removeTag(tag)
|
||||
break
|
||||
|
||||
def artistNameChanged(self, arg):
|
||||
"""
|
||||
This method is called when Artist widget changes index.
|
||||
"""
|
||||
view = hiero.ui.activeView()
|
||||
selection = view.selection()
|
||||
name = self.sender().currentText()
|
||||
project = selection[0].project()
|
||||
with project.beginUndo("Assign Artist"):
|
||||
# A string of '--' denotes clear the assignee...
|
||||
if name != '--':
|
||||
for trackItem in selection:
|
||||
trackItem.setArtistByName(name)
|
||||
else:
|
||||
for trackItem in selection:
|
||||
tTags = trackItem.tags()
|
||||
for tag in tTags:
|
||||
if tag.metadata().hasKey('tag.artistID'):
|
||||
trackItem.removeTag(tag)
|
||||
break
|
||||
|
||||
|
||||
def _getArtistFromID(self, artistID):
|
||||
""" getArtistFromID -> returns an artist dictionary, by their given ID"""
|
||||
global gArtistList
|
||||
artist = [
|
||||
element for element in gArtistList
|
||||
if element['artistID'] == int(artistID)
|
||||
]
|
||||
if not artist:
|
||||
return None
|
||||
return artist[0]
|
||||
|
||||
|
||||
def _getArtistFromName(self, artistName):
|
||||
""" getArtistFromID -> returns an artist dictionary, by their given ID """
|
||||
global gArtistList
|
||||
artist = [
|
||||
element for element in gArtistList
|
||||
if element['artistName'] == artistName
|
||||
]
|
||||
if not artist:
|
||||
return None
|
||||
return artist[0]
|
||||
|
||||
|
||||
def _artist(self):
|
||||
"""_artist -> Returns the artist dictionary assigned to this shot"""
|
||||
artist = None
|
||||
tags = self.tags()
|
||||
for tag in tags:
|
||||
if tag.metadata().hasKey('tag.artistID'):
|
||||
artistID = tag.metadata().value('tag.artistID')
|
||||
artist = self.getArtistFromID(artistID)
|
||||
return artist
|
||||
|
||||
|
||||
def _updateArtistTag(self, artistDict):
|
||||
# A shot will only have one artist assigned. Check if one exists and set accordingly
|
||||
|
||||
artistTag = None
|
||||
tags = self.tags()
|
||||
for tag in tags:
|
||||
if tag.metadata().hasKey('tag.artistID'):
|
||||
artistTag = tag
|
||||
break
|
||||
|
||||
if not artistTag:
|
||||
artistTag = hiero.core.Tag('Artist')
|
||||
artistTag.setIcon(artistDict['artistIcon'])
|
||||
artistTag.metadata().setValue('tag.artistID',
|
||||
str(artistDict['artistID']))
|
||||
artistTag.metadata().setValue('tag.artistName',
|
||||
str(artistDict['artistName']))
|
||||
artistTag.metadata().setValue('tag.artistDepartment',
|
||||
str(artistDict['artistDepartment']))
|
||||
self.sequence().editFinished()
|
||||
self.addTag(artistTag)
|
||||
self.sequence().editFinished()
|
||||
return
|
||||
|
||||
artistTag.setIcon(artistDict['artistIcon'])
|
||||
artistTag.metadata().setValue('tag.artistID', str(artistDict['artistID']))
|
||||
artistTag.metadata().setValue('tag.artistName',
|
||||
str(artistDict['artistName']))
|
||||
artistTag.metadata().setValue('tag.artistDepartment',
|
||||
str(artistDict['artistDepartment']))
|
||||
self.sequence().editFinished()
|
||||
return
|
||||
|
||||
|
||||
def _setArtistByName(self, artistName):
|
||||
""" setArtistByName(artistName) -> sets the artist tag on a TrackItem by a given artistName string"""
|
||||
global gArtistList
|
||||
|
||||
artist = self.getArtistFromName(artistName)
|
||||
if not artist:
|
||||
print 'Artist name: %s was not found in the gArtistList.' % str(
|
||||
artistName)
|
||||
return
|
||||
|
||||
# Do the update.
|
||||
self.updateArtistTag(artist)
|
||||
|
||||
|
||||
def _setArtistByID(self, artistID):
|
||||
""" setArtistByID(artistID) -> sets the artist tag on a TrackItem by a given artistID integer"""
|
||||
global gArtistList
|
||||
|
||||
artist = self.getArtistFromID(artistID)
|
||||
if not artist:
|
||||
print 'Artist name: %s was not found in the gArtistList.' % str(
|
||||
artistID)
|
||||
return
|
||||
|
||||
# Do the update.
|
||||
self.updateArtistTag(artist)
|
||||
|
||||
|
||||
# Inject status getter and setter methods into hiero.core.TrackItem
|
||||
hiero.core.TrackItem.artist = _artist
|
||||
hiero.core.TrackItem.setArtistByName = _setArtistByName
|
||||
hiero.core.TrackItem.setArtistByID = _setArtistByID
|
||||
hiero.core.TrackItem.getArtistFromName = _getArtistFromName
|
||||
hiero.core.TrackItem.getArtistFromID = _getArtistFromID
|
||||
hiero.core.TrackItem.updateArtistTag = _updateArtistTag
|
||||
|
||||
|
||||
def _status(self):
|
||||
"""status -> Returns the Shot status. None if no Status is set."""
|
||||
|
||||
status = None
|
||||
tags = self.tags()
|
||||
for tag in tags:
|
||||
if tag.metadata().hasKey('tag.status'):
|
||||
status = tag.metadata().value('tag.status')
|
||||
return status
|
||||
|
||||
|
||||
def _setStatus(self, status):
|
||||
"""setShotStatus(status) -> Method to set the Status of a Shot.
|
||||
Adds a special kind of status Tag to a TrackItem
|
||||
Example: myTrackItem.setStatus('Final')
|
||||
|
||||
@param status - a string, corresponding to the Status name
|
||||
"""
|
||||
global gStatusTags
|
||||
|
||||
# Get a valid Tag object from the Global list of statuses
|
||||
if not status in gStatusTags.keys():
|
||||
print 'Status requested was not a valid Status string.'
|
||||
return
|
||||
|
||||
# A shot should only have one status. Check if one exists and set accordingly
|
||||
statusTag = None
|
||||
tags = self.tags()
|
||||
for tag in tags:
|
||||
if tag.metadata().hasKey('tag.status'):
|
||||
statusTag = tag
|
||||
break
|
||||
|
||||
if not statusTag:
|
||||
statusTag = hiero.core.Tag('Status')
|
||||
statusTag.setIcon(gStatusTags[status])
|
||||
statusTag.metadata().setValue('tag.status', status)
|
||||
self.addTag(statusTag)
|
||||
|
||||
statusTag.setIcon(gStatusTags[status])
|
||||
statusTag.metadata().setValue('tag.status', status)
|
||||
|
||||
self.sequence().editFinished()
|
||||
return
|
||||
|
||||
|
||||
# Inject status getter and setter methods into hiero.core.TrackItem
|
||||
hiero.core.TrackItem.setStatus = _setStatus
|
||||
hiero.core.TrackItem.status = _status
|
||||
|
||||
|
||||
# This is a convenience method for returning QActions with a triggered method based on the title string
|
||||
def titleStringTriggeredAction(title, method, icon=None):
|
||||
action = QAction(title, None)
|
||||
action.setIcon(QIcon(icon))
|
||||
|
||||
# We do this magic, so that the title string from the action is used to set the status
|
||||
def methodWrapper():
|
||||
method(title)
|
||||
|
||||
action.triggered.connect(methodWrapper)
|
||||
return action
|
||||
|
||||
|
||||
# Menu which adds a Set Status Menu to Timeline and Spreadsheet Views
|
||||
class SetStatusMenu(QMenu):
|
||||
def __init__(self):
|
||||
QMenu.__init__(self, "Set Status", None)
|
||||
|
||||
global gStatusTags
|
||||
self.statuses = gStatusTags
|
||||
self._statusActions = self.createStatusMenuActions()
|
||||
|
||||
# Add the Actions to the Menu.
|
||||
for act in self.menuActions:
|
||||
self.addAction(act)
|
||||
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kTimeline",
|
||||
self.eventHandler)
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kSpreadsheet",
|
||||
self.eventHandler)
|
||||
|
||||
def createStatusMenuActions(self):
|
||||
self.menuActions = []
|
||||
for status in self.statuses:
|
||||
self.menuActions += [
|
||||
titleStringTriggeredAction(
|
||||
status,
|
||||
self.setStatusFromMenuSelection,
|
||||
icon=gStatusTags[status])
|
||||
]
|
||||
|
||||
def setStatusFromMenuSelection(self, menuSelectionStatus):
|
||||
selectedShots = [
|
||||
item for item in self._selection
|
||||
if (isinstance(item, hiero.core.TrackItem))
|
||||
]
|
||||
selectedTracks = [
|
||||
item for item in self._selection
|
||||
if (isinstance(item, (hiero.core.VideoTrack,
|
||||
hiero.core.AudioTrack)))
|
||||
]
|
||||
|
||||
# If we have a Track Header Selection, no shots could be selected, so create shotSelection list
|
||||
if len(selectedTracks) >= 1:
|
||||
for track in selectedTracks:
|
||||
selectedShots += [
|
||||
item for item in track.items()
|
||||
if (isinstance(item, hiero.core.TrackItem))
|
||||
]
|
||||
|
||||
# It's possible no shots exist on the Track, in which case nothing is required
|
||||
if len(selectedShots) == 0:
|
||||
return
|
||||
|
||||
currentProject = selectedShots[0].project()
|
||||
|
||||
with currentProject.beginUndo("Set Status"):
|
||||
# Shots selected
|
||||
for shot in selectedShots:
|
||||
shot.setStatus(menuSelectionStatus)
|
||||
|
||||
# This handles events from the Project Bin View
|
||||
def eventHandler(self, event):
|
||||
if not hasattr(event.sender, 'selection'):
|
||||
# Something has gone wrong, we should only be here if raised
|
||||
# by the Timeline/Spreadsheet view which gives a selection.
|
||||
return
|
||||
|
||||
# Set the current selection
|
||||
self._selection = event.sender.selection()
|
||||
|
||||
# Return if there's no Selection. We won't add the Menu.
|
||||
if len(self._selection) == 0:
|
||||
return
|
||||
|
||||
event.menu.addMenu(self)
|
||||
|
||||
|
||||
# Menu which adds a Set Status Menu to Timeline and Spreadsheet Views
|
||||
class AssignArtistMenu(QMenu):
|
||||
def __init__(self):
|
||||
QMenu.__init__(self, "Assign Artist", None)
|
||||
|
||||
global gArtistList
|
||||
self.artists = gArtistList
|
||||
self._artistsActions = self.createAssignArtistMenuActions()
|
||||
|
||||
# Add the Actions to the Menu.
|
||||
for act in self.menuActions:
|
||||
self.addAction(act)
|
||||
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kTimeline",
|
||||
self.eventHandler)
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kSpreadsheet",
|
||||
self.eventHandler)
|
||||
|
||||
def createAssignArtistMenuActions(self):
|
||||
self.menuActions = []
|
||||
for artist in self.artists:
|
||||
self.menuActions += [
|
||||
titleStringTriggeredAction(
|
||||
artist['artistName'],
|
||||
self.setArtistFromMenuSelection,
|
||||
icon=artist['artistIcon'])
|
||||
]
|
||||
|
||||
def setArtistFromMenuSelection(self, menuSelectionArtist):
|
||||
selectedShots = [
|
||||
item for item in self._selection
|
||||
if (isinstance(item, hiero.core.TrackItem))
|
||||
]
|
||||
selectedTracks = [
|
||||
item for item in self._selection
|
||||
if (isinstance(item, (hiero.core.VideoTrack,
|
||||
hiero.core.AudioTrack)))
|
||||
]
|
||||
|
||||
# If we have a Track Header Selection, no shots could be selected, so create shotSelection list
|
||||
if len(selectedTracks) >= 1:
|
||||
for track in selectedTracks:
|
||||
selectedShots += [
|
||||
item for item in track.items()
|
||||
if (isinstance(item, hiero.core.TrackItem))
|
||||
]
|
||||
|
||||
# It's possible no shots exist on the Track, in which case nothing is required
|
||||
if len(selectedShots) == 0:
|
||||
return
|
||||
|
||||
currentProject = selectedShots[0].project()
|
||||
|
||||
with currentProject.beginUndo("Assign Artist"):
|
||||
# Shots selected
|
||||
for shot in selectedShots:
|
||||
shot.setArtistByName(menuSelectionArtist)
|
||||
|
||||
# This handles events from the Project Bin View
|
||||
def eventHandler(self, event):
|
||||
if not hasattr(event.sender, 'selection'):
|
||||
# Something has gone wrong, we should only be here if raised
|
||||
# by the Timeline/Spreadsheet view which gives a selection.
|
||||
return
|
||||
|
||||
# Set the current selection
|
||||
self._selection = event.sender.selection()
|
||||
|
||||
# Return if there's no Selection. We won't add the Menu.
|
||||
if len(self._selection) == 0:
|
||||
return
|
||||
|
||||
event.menu.addMenu(self)
|
||||
|
||||
|
||||
# Add the 'Set Status' context menu to Timeline and Spreadsheet
|
||||
if kAddStatusMenu:
|
||||
setStatusMenu = SetStatusMenu()
|
||||
|
||||
if kAssignArtistMenu:
|
||||
assignArtistMenu = AssignArtistMenu()
|
||||
|
||||
# Register our custom columns
|
||||
hiero.ui.customColumn = CustomSpreadsheetColumns()
|
||||
142
setup/nukestudio/hiero_plugin_path/Python/StartupUI/Purge.py
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
# Purge Unused Clips - Removes any unused Clips from a Project
|
||||
# Usage: Copy to ~/.hiero/Python/StartupUI
|
||||
# Demonstrates the use of hiero.core.find_items module.
|
||||
# Usage: Right-click on an item in the Bin View > "Purge Unused Clips"
|
||||
# Result: Any Clips not used in a Sequence in the active project will be removed
|
||||
# Requires Hiero 1.5v1 or later.
|
||||
# Version 1.1
|
||||
|
||||
import hiero
|
||||
import hiero.core.find_items
|
||||
try:
|
||||
from PySide.QtGui import *
|
||||
from PySide.QtCore import *
|
||||
except:
|
||||
from PySide2.QtGui import *
|
||||
from PySide2.QtWidgets import *
|
||||
from PySide2.QtCore import *
|
||||
|
||||
|
||||
class PurgeUnusedAction(QAction):
|
||||
def __init__(self):
|
||||
QAction.__init__(self, "Purge Unused Clips", None)
|
||||
self.triggered.connect(self.PurgeUnused)
|
||||
hiero.core.events.registerInterest("kShowContextMenu/kBin",
|
||||
self.eventHandler)
|
||||
self.setIcon(QIcon('icons:TagDelete.png'))
|
||||
|
||||
# Method to return whether a Bin is empty...
|
||||
def binIsEmpty(self, b):
|
||||
numBinItems = 0
|
||||
bItems = b.items()
|
||||
empty = False
|
||||
|
||||
if len(bItems) == 0:
|
||||
empty = True
|
||||
return empty
|
||||
else:
|
||||
for b in bItems:
|
||||
if isinstance(b, hiero.core.BinItem) or isinstance(
|
||||
b, hiero.core.Bin):
|
||||
numBinItems += 1
|
||||
if numBinItems == 0:
|
||||
empty = True
|
||||
|
||||
return empty
|
||||
|
||||
def PurgeUnused(self):
|
||||
|
||||
#Get selected items
|
||||
item = self.selectedItem
|
||||
proj = item.project()
|
||||
|
||||
# Build a list of Projects
|
||||
SEQS = hiero.core.findItems(proj, "Sequences")
|
||||
|
||||
# Build a list of Clips
|
||||
CLIPSTOREMOVE = hiero.core.findItems(proj, "Clips")
|
||||
|
||||
if len(SEQS) == 0:
|
||||
# Present Dialog Asking if User wants to remove Clips
|
||||
msgBox = QMessageBox()
|
||||
msgBox.setText("Purge Unused Clips")
|
||||
msgBox.setInformativeText(
|
||||
"You have no Sequences in this Project. Do you want to remove all Clips (%i) from Project: %s?"
|
||||
% (len(CLIPSTOREMOVE), proj.name()))
|
||||
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
|
||||
msgBox.setDefaultButton(QMessageBox.Ok)
|
||||
ret = msgBox.exec_()
|
||||
if ret == QMessageBox.Cancel:
|
||||
print 'Not purging anything.'
|
||||
elif ret == QMessageBox.Ok:
|
||||
with proj.beginUndo('Purge Unused Clips'):
|
||||
BINS = []
|
||||
for clip in CLIPSTOREMOVE:
|
||||
BI = clip.binItem()
|
||||
B = BI.parentBin()
|
||||
BINS += [B]
|
||||
print 'Removing:', BI
|
||||
try:
|
||||
B.removeItem(BI)
|
||||
except:
|
||||
print 'Unable to remove: ' + BI
|
||||
return
|
||||
|
||||
# For each sequence, iterate through each track Item, see if the Clip is in the CLIPS list.
|
||||
# Remaining items in CLIPS will be removed
|
||||
|
||||
for seq in SEQS:
|
||||
|
||||
#Loop through selected and make folders
|
||||
for track in seq:
|
||||
for trackitem in track:
|
||||
|
||||
if trackitem.source() in CLIPSTOREMOVE:
|
||||
CLIPSTOREMOVE.remove(trackitem.source())
|
||||
|
||||
# Present Dialog Asking if User wants to remove Clips
|
||||
msgBox = QMessageBox()
|
||||
msgBox.setText("Purge Unused Clips")
|
||||
msgBox.setInformativeText("Remove %i unused Clips from Project %s?" %
|
||||
(len(CLIPSTOREMOVE), proj.name()))
|
||||
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
|
||||
msgBox.setDefaultButton(QMessageBox.Ok)
|
||||
ret = msgBox.exec_()
|
||||
|
||||
if ret == QMessageBox.Cancel:
|
||||
print 'Cancel'
|
||||
return
|
||||
elif ret == QMessageBox.Ok:
|
||||
BINS = []
|
||||
with proj.beginUndo('Purge Unused Clips'):
|
||||
# Delete the rest of the Clips
|
||||
for clip in CLIPSTOREMOVE:
|
||||
BI = clip.binItem()
|
||||
B = BI.parentBin()
|
||||
BINS += [B]
|
||||
print 'Removing:', BI
|
||||
try:
|
||||
B.removeItem(BI)
|
||||
except:
|
||||
print 'Unable to remove: ' + BI
|
||||
|
||||
def eventHandler(self, event):
|
||||
if not hasattr(event.sender, 'selection'):
|
||||
# Something has gone wrong, we shouldn't only be here if raised
|
||||
# by the Bin view which will give a selection.
|
||||
return
|
||||
|
||||
self.selectedItem = None
|
||||
s = event.sender.selection()
|
||||
|
||||
if len(s) >= 1:
|
||||
self.selectedItem = s[0]
|
||||
title = "Purge Unused Clips"
|
||||
self.setText(title)
|
||||
event.menu.addAction(self)
|
||||
|
||||
return
|
||||
|
||||
|
||||
# Instantiate the action to get it to register itself.
|
||||
PurgeUnusedAction = PurgeUnusedAction()
|
||||