vse_toolbox/ui/properties.py

824 lines
26 KiB
Python

# SPDX-License-Identifier: GPL-2.0-or-later
import bpy
import os
from pathlib import Path
import re
from bpy.props import (
BoolProperty,
CollectionProperty,
EnumProperty,
IntProperty,
PointerProperty,
StringProperty,
FloatVectorProperty
)
from bpy.types import PropertyGroup, UIList
from pprint import pprint as pp
from vse_toolbox.bl_utils import get_addon_prefs, get_scene_settings
from vse_toolbox.constants import ASSET_PREVIEWS, TRACKERS, PREVIEWS_DIR
from vse_toolbox.file_utils import norm_str, parse
from vse_toolbox.sequencer_utils import get_strip_sequence_name, get_channel_name
from vse_toolbox import constants
def get_tracker_items(self, context):
return [(norm_str(a.__name__, format=str.upper), a.__name__, "", i) for i, a in enumerate(TRACKERS)]
class CollectionPropertyGroup(PropertyGroup):
def __iter__(self):
return (v for v in self.values())
def props(self):
return [p for p in self.bl_rna.properties if p.identifier not in ('rna_type', 'name')]
def keys(self):
return [k for k in self.bl_rna.properties.keys() if k not in ('rna_type', 'name')]
def values(self):
return [getattr(self, k) for k in self.keys()]
def items(self):
return self.to_dict().items()
def to_dict(self, use_name=True):
if use_name:
return {p.name: getattr(self, p.identifier) for p in self.props()}
else:
return {k: getattr(self, k) for k in self.keys()}
def get_preview_items(self, context):
if self.icon_id:
return [(self.preview, self.tracker_name, '', self.icon_id, 0)]
return []
class Asset(PropertyGroup):
name : StringProperty(default='')
id : StringProperty(default='')
norm_name : StringProperty(default='')
asset_type : StringProperty(default='')
tracker_name : StringProperty(default='')
preview : StringProperty(default='')
previews : EnumProperty(items=get_preview_items)
@property
def label(self):
return f"{self.asset_type} / {self.tracker_name}"
@property
def icon_id(self):
ico = ASSET_PREVIEWS.get(self.preview)
if ico:
return ico.icon_id
class AssetCasting(PropertyGroup):
id : StringProperty(default='')
instance : IntProperty(default=1)
@property
def asset(self):
settings = get_scene_settings()
project = settings.active_project
return project.assets.get(self.id)
def to_dict(self):
return {'id': self.id,
'instance': self.instance,
'name': self.asset.name if self.asset else None,
'_name': self.get('_name')
}
class AssetType(PropertyGroup):
__annotations__ = {}
class MetadataType(PropertyGroup):
#choices = []
choices : CollectionProperty(type=PropertyGroup)#EnumProperty(items=lambda s, c: [(c, c.replace(' ', '_').upper(), '') for c in s['choices']])
field_name : StringProperty()
entity_type : StringProperty()
data_type : StringProperty()
class TaskType(PropertyGroup):
color : FloatVectorProperty(subtype='COLOR')
import_enabled : BoolProperty(default=False)
id : StringProperty(default='')
class Sequence(PropertyGroup):
import_enabled : BoolProperty(default=False)
id : StringProperty(default='')
class TaskStatus(PropertyGroup):
__annotations__ = {}
class Metadata(CollectionPropertyGroup):
__annotations__ = {}
def to_dict(self, use_name=True):
settings = get_scene_settings()
data = {}
for prop in self.props():
name = prop.name
if not use_name:
name = prop.identifier
metadata_type = settings.active_project.metadata_types[prop.name]
value = getattr(self, prop.identifier)
if metadata_type.data_type == 'boolean':
value = 'true' if value else 'false'
data[name] = value
return data
class ShotTasks(PropertyGroup):
__annotations__ = {}
class ShotTask(PropertyGroup):
comment : StringProperty()
class Episode(PropertyGroup):
id : StringProperty(default='')
@property
def active(self):
settings = get_scene_settings()
return self.get(settings.project_name)
class Template(PropertyGroup):
value : StringProperty()
class SpreadsheetExportCell(PropertyGroup):
export_name : StringProperty()
enabled : BoolProperty(default=True)
field_name : StringProperty()
type : EnumProperty(items=[(t, t, "") for t in ('METADATA', 'SHOT', 'ASSET_TYPE', 'TASK_TYPE')])
#sort : BoolProperty(default=True)
def get_cell_items(self, context):
settings = get_scene_settings()
project = settings.active_project
return [(cell, cell, '') for cell in project.get_cell_types().keys()]
class SpreadsheetImportCell(PropertyGroup):
enabled : BoolProperty(default=True)
import_name : EnumProperty(items=get_cell_items)
#type : EnumProperty(items=[(t, t, "") for t in ('METADATA', 'SHOT', 'ASSET_TYPE')])
def get_custom_name_items(self, context):
settings = get_scene_settings()
project = settings.active_project
return [(m.field_name, m.name, '') for m in project.metadata_types if m.entity_type=='ASSET']
class SpreadsheetExport(PropertyGroup):
use_custom_cells: BoolProperty(default=False)
format : EnumProperty(items=[(i, i, '') for i in ('csv', 'xlsx', 'xls', 'Clipboard')])
separator : StringProperty(default='\\n')
delimiter : StringProperty(default=';')
export_path : StringProperty(default='//export')
use_custom_name : BoolProperty(default=False)
custom_name : EnumProperty(items=get_custom_name_items,
description='Use a custom name for asset using a metadata value')
open_folder : BoolProperty(default=False)
show_settings : BoolProperty(default=False)
cells: CollectionProperty(type=SpreadsheetExportCell)
cell_index : IntProperty(name='Spreadsheet Index', default=0)
class SpreadsheetImport(PropertyGroup):
#use_custom_cells: BoolProperty(default=False)
separator : StringProperty(default='\\n')
delimiter : StringProperty(default=',;:')
use_custom_name : BoolProperty(default=False)
custom_name : EnumProperty(items=get_custom_name_items,
description='Use a custom name for asset using a metadata value')
cells: CollectionProperty(type=SpreadsheetImportCell)
cell_index : IntProperty(name='Spreadsheet Index', default=0)
import_casting: BoolProperty(default=True)
import_custom_data: BoolProperty(default=True)
update_edit: BoolProperty(default=True)
def get_task_status_items(self, context):
settings = get_scene_settings()
project = settings.active_project
status_items = [('CURRENT', 'Current', '')]
if project:
status_items += [(t.name, t.name, '') for t in project.task_statuses]
return status_items
def get_task_type_items(self, context):
settings = get_scene_settings()
project = settings.active_project
if not project:
return [('NONE', 'None', '')]
return [(t.name, t.name, '') for t in project.task_types]
class ImportShots(PropertyGroup):
import_source: EnumProperty(items=[(i, i.title(), '') for i in ('DISK', 'TRACKER')])
import_task: EnumProperty(items=[(i, i.title().replace('_', ' '), '')
for i in ('FROM_LIST',)], default='FROM_LIST') #('LAST', 'FROM_LIST', 'ALL')
#sequence_dir_template: StringProperty(
# name="Sequence Template", default="$PROJECT_ROOT/sequences/{sequence}")
#shot_folder_template: StringProperty(
# name="Shot Template", default="$PROJECT_ROOT/sequences/sq{sequence}/sh{shot}")
video_template : StringProperty(
name="Video Path", default="//sources/{sequence}_{shot}_{task}.{ext}")
video_templates : CollectionProperty(type=PropertyGroup)
import_sequence: EnumProperty(items=[(i, i.title().replace('_', ' '), '')
for i in ('FROM_LIST',)], default='FROM_LIST') #('SELECTED_STRIPS', 'FROM_LIST', 'ALL')
previews_folder: StringProperty(
name="Previews Folder", default="//sources", subtype='DIR_PATH')
class UploadToTracker(PropertyGroup):
render_strips: BoolProperty(default=False)
render_strip_template : StringProperty(
name="Movie Path", default="//render/{strip}.{ext}")
task : EnumProperty(items=get_task_type_items)
status : EnumProperty(items=get_task_status_items)
comment : StringProperty()
add_preview : BoolProperty(default=True)
preview_mode : EnumProperty(items=[(m, m.title().replace('_', ' '), '')
for m in ('ONLY_NEW', 'REPLACE', 'ADD')])
set_main_preview : BoolProperty(default=True)
casting : BoolProperty(default=True)
update_frames: BoolProperty(default=True)
custom_data : BoolProperty(default=True)
tasks_comment: BoolProperty(default=True)
def get_episodes_items(self, context):
settings = get_scene_settings()
project = settings.active_project
items = [('/', '/', '', 0)]
if project and project.episodes:
items = [(e, e, '', i) for i, e in enumerate(project.episodes.keys())]
constants.EPISODE_ITEMS[:] = items
return constants.EPISODE_ITEMS
def on_episode_updated(self, context):
settings = get_scene_settings()
os.environ['TRACKER_EPISODE_ID'] = settings.active_episode.id
class Project(PropertyGroup):
id : StringProperty(default='')
show_settings : BoolProperty()
templates : CollectionProperty(type=Template)
shot_start_number : IntProperty(name="Shot Start Number", default=10, min=0)
shot_padding : IntProperty(name="Shot Padding", default=4, min=0, max=10)
sequence_start_number : IntProperty(name="Sequence Start Number", default=10, min=0)
sequence_padding : IntProperty(name="Sequence Padding", default=3, min=0, max=10)
reset_by_sequence : BoolProperty(
name="Reset By Sequence",
description="Reset Start Number for each sequence",
default=False
)
sequence_increment : IntProperty(
name="Sequence Increment", default=10, min=0, step=10)
shot_increment : IntProperty(
name="Shot Increment", default=10, min=0, step=10)
sequence_template : StringProperty(
name="Sequence Name", default="{sequence}")
episode_template : StringProperty(
name="Episode Name", default="{episode}")
shot_template : StringProperty(
name="Shot Name", default="{sequence}_{shot}")
render_video_template : StringProperty(
name="Movie Path", default="//render/{project}.mov")
render_audio_template : StringProperty(
name="Audio Path", default="//render/{project}.wav")
render_video_strip_template : StringProperty(
name="Strip Path", default="//render/shots/{strip}.mov")
render_audio_strip_template: StringProperty(
name="Sound Path", default="//render/sounds/{strip}.wav")
render_video_sequence_template : StringProperty(
name="Sequence Path", default="//render/sequences/{sequence}.mov")
render_audio_sequence_template: StringProperty(
name="Sound Path", default="//render/sounds/{sequence}.wav")
render_single_file: BoolProperty(name="Render Single File", default=False)
render_sequence: BoolProperty(name="Render Sequences", default=False)
render_shot: BoolProperty(name="Render Shots", default=True)
render_selected_only: BoolProperty(name="Render Selected Only", default=True)
render_video: BoolProperty(name="Render Video", default=True)
render_audio: BoolProperty(name="Render Audio", default=False)
render_video_per_sequence: BoolProperty(name="Render video per sequence", default=True)
render_audio_per_sequence: BoolProperty(name="Render audio per sequence", default=False)
render_video_per_strip: BoolProperty(name="Render video per shot", default=True)
render_audio_per_strip: BoolProperty(name="Render audio per shot", default=False)
#render_sound_format: EnumProperty(items=[(e, e, '') for e in ('mp3', 'wav')])
export_edl_template : StringProperty(
name="Edl Path", default="//render/{project}.edl")
episode_name : EnumProperty(items=get_episodes_items, update=on_episode_updated)
episodes : CollectionProperty(type=Episode)
assets : CollectionProperty(type=Asset)
asset_types : CollectionProperty(type=AssetType)
metadata_types : CollectionProperty(type=MetadataType)
task_types : CollectionProperty(type=TaskType)
task_type_index : IntProperty()
task_statuses : CollectionProperty(type=TaskStatus)
sequences : CollectionProperty(type=Sequence)
spreadsheet_import: PointerProperty(type=SpreadsheetImport)
spreadsheet_export: PointerProperty(type=SpreadsheetExport)
type : StringProperty()
upload_to_tracker: PointerProperty(type=UploadToTracker)
import_shots: PointerProperty(type=ImportShots)
@property
def active_episode(self):
return self.episodes.get(self.episode_name)
@property
def format_data(self):
data = {}
data['project'] = norm_str(self.name)
data['project_basename'] = data['project']
if self.active_episode:
data['episode'] = norm_str(self.episode_name)
data['project_basename'] = f"{data['project']}_{data['episode']}"
#for template in self.templates:
# data[template.name] = template.value
return data
def get_cell_types(self):
settings = get_scene_settings()
project = settings.active_project
cell_types = {}
cell_names = ['Sequence', 'Shot', 'Nb Frames', 'Description']
if project.type == 'TVSHOW':
cell_names.insert(0, 'Episode')
cell_types = {cell_name: 'SHOT' for cell_name in cell_names}
for metadata_type in project.metadata_types:
if metadata_type['entity_type'] == "SHOT":
cell_types[metadata_type.name] = 'METADATA'
for asset_type in project.asset_types:
cell_types[asset_type.name] = 'ASSET_TYPE'
for task_type in project.task_types:
cell_types[task_type.name] = 'TASK_TYPE'
return cell_types
def set_spreadsheet(self):
cell_names = ['Sequence', 'Shot', 'Nb Frames', 'Description']
if self.type == 'TVSHOW':
cell_names.insert(0, 'Episode')
# Export SpreadSheet
spreadsheet = self.spreadsheet_export
spreadsheet.cells.clear()
for cell_name in cell_names:
cell = spreadsheet.cells.add()
cell.name = cell_name
cell.export_name = 'Name' if cell_name == 'Shot' else cell_name
cell.field_name = norm_str(cell_name, format=str.upper)
cell.type = "SHOT"
for metadata_type in self.metadata_types:
if not metadata_type['entity_type'] == "SHOT":
continue
cell = spreadsheet.cells.add()
cell.name = metadata_type.name
cell.export_name = metadata_type.name
cell.field_name = metadata_type.field_name
cell.type = "METADATA"
for asset_type in self.asset_types:
cell = spreadsheet.cells.add()
cell.name = asset_type.name
cell.export_name = asset_type.name
cell.field_name = norm_str(asset_type.name, format=str.upper)
cell.type = "ASSET_TYPE"
for task_type in self.task_types:
cell = spreadsheet.cells.add()
cell.name = task_type.name
cell.export_name = task_type.name
cell.field_name = norm_str(task_type.name, format=str.upper)
cell.type = "TASK_TYPE"
def set_strip_metadata(self):
# Clear Metadatas
for attr in list(Metadata.__annotations__.keys()):
if hasattr(Metadata, attr):
delattr(Metadata, attr)
del Metadata.__annotations__[attr]
for metadata_type in self.metadata_types:
if not metadata_type.entity_type == "SHOT":
continue
field_name = metadata_type.field_name
name = metadata_type.name
#if metadata_type.get('choices'):
# prop = #bpy.props.EnumProperty(items=[(c, c, '') for c in ['/'] + metadata_type['choices']], name=name)
#else:
# prop = #bpy.props.StringProperty(name=name)
prop = bpy.props.StringProperty(name=name)
Metadata.__annotations__[field_name] = prop
setattr(Metadata, field_name, prop)
def set_shot_tasks(self):
for task_type in self.task_types:
prop = bpy.props.PointerProperty(type=ShotTask)
ShotTasks.__annotations__[norm_str(task_type.name)] = prop
setattr(ShotTasks, norm_str(task_type.name), prop)
class VSETB_UL_casting(UIList):
order_by_type : BoolProperty(default=False)
def draw_item(self, context, layout, data, item, icon, active_data,
active_propname, index):
settings = get_scene_settings()
project = settings.active_project
asset = item.asset
if asset is None:
layout.label(text=f'Asset not Found ({item.get("_name", "...")})')
return
icon_id = asset.icon_id
params = {'icon_value': icon_id} if icon_id else {'icon': 'BLANK1'}
# Make sure your code supports all 3 layout types
if self.layout_type in {'DEFAULT', 'COMPACT'}:
layout.label(**params)
split = layout.split(factor=0.6)
split.label(text=f"{asset.norm_name.title()}")
split.label(text=f"{asset.asset_type.title()}")
sub = layout.row(align=True)
sub.alignment = 'RIGHT'
sub.prop(item, 'instance', text='')
elif self.layout_type in {'GRID'}:
layout.alignment = 'CENTER'
layout.label(text="")
def draw_filter(self, context, layout):
row = layout.row()
subrow = row.row(align=True)
subrow.prop(self, "filter_name", text="")
subrow.prop(self, "use_filter_invert", text="", icon='ARROW_LEFTRIGHT')
subrow.separator()
subrow.prop(self, "order_by_type", text="Order by Type", icon='MESH_DATA')
def filter_items(self, context, data, propname):
"""Filter and order items in the list."""
helper_funcs = bpy.types.UI_UL_list
filtered = []
ordered = []
items = getattr(data, propname)
# Filtering by name
if self.filter_name:
filtered = helper_funcs.filter_items_by_name(self.filter_name, self.bitflag_filter_item, items, "name",
reverse=self.use_filter_sort_alpha)
# Order by types
if self.order_by_type:
_sort = [(idx, casting_item) for idx, casting_item in enumerate(items)]
sort_items = helper_funcs.sort_items_helper
ordered = sort_items(_sort, lambda x: x[1].asset.label)
return filtered, ordered
class VSETB_UL_spreadsheet_import(UIList):
def draw_item(self, context, layout, data, item, icon, active_data,
active_propname, index):
settings = get_scene_settings()
project = settings.active_project
layout.use_property_split = True
layout.use_property_decorate = False
item_type = project.get_cell_types()[item.import_name]
enabled = True
if item_type == 'METADATA' and not project.spreadsheet_import.import_custom_data:
enabled = False
elif item_type == 'ASSET_TYPE' and not project.spreadsheet_import.import_casting:
enabled = False
elif item.import_name == 'Nb Frames' and not project.spreadsheet_import.update_edit:
enabled = False
layout.enabled = enabled
row = layout.row(align=True)
row.alignment = 'LEFT'
row.prop(item, 'enabled', text='')
row = layout.row(align=True)
row.enabled = item.enabled
row.label(text=item.name)
row.prop(item, 'import_name', text='')
class VSETB_UL_spreadsheet_export(UIList):
def draw_item(self, context, layout, data, item, icon, active_data,
active_propname, index):
settings = get_scene_settings()
project = settings.active_project
layout.use_property_split = True
layout.use_property_decorate = False
row = layout.row(align=True)
row.alignment = 'LEFT'
row.prop(item, 'enabled', text='')
layout.label(text=item.name)
layout.prop(item, 'export_name', text='')
def get_project_items(self, context):
items = [('/', '/', '', 0)]
if self.projects:
items = [(p, p, '', i) for i, p in enumerate(self.projects.keys())]
constants.PROJECT_ITEMS[:] = items
return constants.PROJECT_ITEMS
def on_project_updated(self, context):
settings = get_scene_settings()
settings['episodes'] = 0
#print('Update active Project')
bpy.ops.vse_toolbox.load_assets()
if settings.active_project:
settings.active_project.set_strip_metadata()
os.environ['TRACKER_PROJECT_ID'] = settings.active_project.id
class VSETB_PGT_scene_settings(PropertyGroup):
projects : CollectionProperty(type=Project)
project_name : EnumProperty(items=get_project_items, update=on_project_updated)
tracker_name : EnumProperty(items=get_tracker_items)
toogle_prefs : BoolProperty(
description='Toogle VSE ToolBox Preferences', default=True)
auto_select_strip : BoolProperty(
name='Auto Select Strip',description='Auto select strip', default=True)
channel : EnumProperty(
items=[
('AUDIO', 'Audio', '', 0),
('MOVIE', 'Movie', '', 1),
('SHOTS', 'Shots', '', 2),
('SEQUENCES', 'Sequences', '', 3),
('STAMPS', 'Sequences', '', 4),
]
)
sequence_channel_name : StringProperty(
name="Sequences Channel Name", default="Sequences")
shot_channel_name : StringProperty(
name="Shot Channel Name", default="Shots")
@property
def active_project(self):
settings = get_scene_settings()
return settings.projects.get(settings.project_name)
@property
def active_episode(self):
project = self.active_project
if project:
return project.active_episode
@property
def format_data(self):
data = {}
digit_matches = re.findall(r'(\d+)', bpy.data.filepath)
if len(digit_matches) == 1:
data['version'] = int(digit_matches[-1])
elif len(digit_matches) > 1:
data['increment'] = int(digit_matches[-1])
data['version'] = int(digit_matches[-2])
suffix = Path(bpy.context.scene.render.frame_path()).suffix
data['ext'] = suffix[1:]
return data
class VSETB_PGT_strip_settings(PropertyGroup):
casting : CollectionProperty(type=AssetCasting)
casting_index : IntProperty(name='Casting Index', default=0)
source_name : StringProperty(name='')
metadata : PointerProperty(type=Metadata)
description : StringProperty()
tasks: PointerProperty(type=ShotTasks)
@property
def active_casting(self):
try:
return self.casting[self.casting_index]
except IndexError:
return
@property
def strip(self):
sequences = bpy.context.scene.sequence_editor.sequences_all
return next(s for s in sequences if s.vsetb_strip_settings == self)
@property
def format_data(self):
scn = bpy.context.scene
settings = get_scene_settings()
project = settings.active_project
strip = self.strip
channel = get_channel_name(strip)
if channel == 'Sequences':
data = parse(project.sequence_template, strip.name)
#data['index'] = int(data['index'])
#data['sequence'] = strip.name
data['strip'] = strip.name
#data['shot'] = project.shot_template
elif channel == "Shots":
data = {}
if sequence_strip_name := get_strip_sequence_name(strip):
data = parse(project.sequence_template, sequence_strip_name)
data['sequence_strip'] = sequence_strip_name
data.update(parse(project.shot_template, strip.name))
#data['index'] = int(data['index'])
data['strip'] = strip.name
#data['shot'] = project.shot_template
else:
return {}
return data
classes = (
Asset,
AssetCasting,
SpreadsheetImportCell,
SpreadsheetExportCell,
AssetType,
TaskStatus,
Episode,
Template,
Metadata,
MetadataType,
Sequence,
TaskType,
ShotTasks,
ShotTask,
SpreadsheetImport,
SpreadsheetExport,
ImportShots,
UploadToTracker,
Project,
VSETB_UL_spreadsheet_import,
VSETB_UL_spreadsheet_export,
VSETB_UL_casting,
VSETB_PGT_scene_settings,
VSETB_PGT_strip_settings,
)
from bpy.app.handlers import persistent
@persistent
def load_handler(dummy):
settings = get_scene_settings()
project = settings.active_project
if project:
project.set_strip_metadata()
project.set_shot_tasks()
#settings.active_project.set_spreadsheet()
os.environ['TRACKER_PROJECT_ID'] = settings.active_project.id
for asset in project.assets:
preview_id = asset.preview
preview_path = Path(PREVIEWS_DIR / project.id / preview_id).with_suffix('.png')
if preview_path.exists() and preview_id not in ASSET_PREVIEWS:
ASSET_PREVIEWS.load(preview_id, preview_path.as_posix(), 'IMAGE', True)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.vsetb_settings = PointerProperty(type=VSETB_PGT_scene_settings)
bpy.types.Sequence.vsetb_strip_settings = PointerProperty(type=VSETB_PGT_strip_settings)
#load_metadata_types()
bpy.app.handlers.load_post.append(load_handler)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
del bpy.types.Sequence.vsetb_strip_settings
del bpy.types.Scene.vsetb_settings
bpy.app.handlers.load_post.remove(load_handler)