Skip to content

ops

Blender operators and menus for use with AYON.

BuildWorkfileFromTemplate

Bases: LaunchQtApp

Build Workfile from ayon template settings.

Source code in client/ayon_blender/api/ops.py
447
448
449
450
451
452
453
454
455
class BuildWorkfileFromTemplate(LaunchQtApp):
    """Build Workfile from ayon template settings."""

    bl_idname = "wm.ayon_build_workfile_from_template"
    bl_label = "Build Workfile from Template"
    def execute(self, context):
        from .workfile_template_builder import build_workfile_template
        build_workfile_template()
        return {"FINISHED"}

CreateFirstWorkfileFromTemplate

Bases: LaunchQtApp

Build Workfile from ayon template settings.

Source code in client/ayon_blender/api/ops.py
436
437
438
439
440
441
442
443
444
class CreateFirstWorkfileFromTemplate(LaunchQtApp):
    """Build Workfile from ayon template settings."""

    bl_idname = "wm.ayon_create_first_workfile_from_template"
    bl_label = "Create First Workfile from Template"
    def execute(self, context):
        from .workfile_template_builder import create_first_workfile_from_template
        create_first_workfile_from_template()
        return {"FINISHED"}

CreatePlaceholder

Bases: LaunchQtApp

Create Placeholder from ayon template settings.

Source code in client/ayon_blender/api/ops.py
484
485
486
487
488
489
490
491
492
493
494
class CreatePlaceholder(LaunchQtApp):
    """Create Placeholder from ayon template settings."""

    bl_idname = "wm.ayon_create_placeholder"
    bl_label = "Create Placeholder"
    def execute(self, context):
        from .workfile_template_builder import create_placeholder
        window = create_placeholder()
        BlenderApplication.store_window(self.bl_idname, window)
        self._window = window
        return super().execute(context)

LaunchCreator

Bases: LaunchQtApp

Launch AYON Creator.

Source code in client/ayon_blender/api/ops.py
319
320
321
322
323
324
325
326
327
328
329
330
331
class LaunchCreator(LaunchQtApp):
    """Launch AYON Creator."""

    bl_idname = "wm.ayon_creator"
    bl_label = "Create..."
    _tool_name = "creator"

    def before_window_show(self):
        self._window.refresh()

    def execute(self, context):
        host_tools.show_publisher(tab="create")
        return {"FINISHED"}

LaunchLibrary

Bases: LaunchQtApp

Launch Library Loader.

Source code in client/ayon_blender/api/ops.py
361
362
363
364
365
366
class LaunchLibrary(LaunchQtApp):
    """Launch Library Loader."""

    bl_idname = "wm.library_loader"
    bl_label = "Library..."
    _tool_name = "libraryloader"

LaunchLoader

Bases: LaunchQtApp

Launch AYON Loader.

Source code in client/ayon_blender/api/ops.py
334
335
336
337
338
339
class LaunchLoader(LaunchQtApp):
    """Launch AYON Loader."""

    bl_idname = "wm.ayon_loader"
    bl_label = "Load..."
    _tool_name = "loader"

LaunchManager

Bases: LaunchQtApp

Launch AYON Manager.

Source code in client/ayon_blender/api/ops.py
353
354
355
356
357
358
class LaunchManager(LaunchQtApp):
    """Launch AYON Manager."""

    bl_idname = "wm.ayon_manager"
    bl_label = "Manage..."
    _tool_name = "sceneinventory"

LaunchPublisher

Bases: LaunchQtApp

Launch AYON Publisher.

Source code in client/ayon_blender/api/ops.py
342
343
344
345
346
347
348
349
350
class LaunchPublisher(LaunchQtApp):
    """Launch AYON Publisher."""

    bl_idname = "wm.ayon_publisher"
    bl_label = "Publish..."

    def execute(self, context):
        host_tools.show_publisher(tab="publish")
        return {"FINISHED"}

LaunchQtApp

Bases: Operator

A Base class for operators to launch a Qt app.

Source code in client/ayon_blender/api/ops.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class LaunchQtApp(bpy.types.Operator):
    """A Base class for operators to launch a Qt app."""

    _window = Union[QtWidgets.QDialog, ModuleType]
    _tool_name: str = None
    _init_args: Optional[List] = list()
    _init_kwargs: Optional[Dict] = dict()
    bl_idname: str = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.bl_idname is None:
            raise NotImplementedError("Attribute `bl_idname` must be set!")
        print(f"Initialising {self.bl_idname}...")
        GlobalClass.app = BlenderApplication.get_app()

        if not bpy.app.timers.is_registered(_process_app_events):
            bpy.app.timers.register(
                _process_app_events,
                persistent=True
            )

    def execute(self, context):
        """Execute the operator.

        The child class must implement `execute()` where it only has to set
        `self._window` to the desired Qt window and then simply run
        `return super().execute(context)`.
        `self._window` is expected to have a `show` method.
        If the `show` method requires arguments, you can set `self._show_args`
        and `self._show_kwargs`. `args` should be a list, `kwargs` a
        dictionary.
        """

        if self._tool_name is None:
            if self._window is None:
                raise AttributeError("`self._window` is not set.")

        else:
            window = BlenderApplication.get_window(self.bl_idname)
            if window is None:
                window = host_tools.get_tool_by_name(self._tool_name)
                BlenderApplication.store_window(self.bl_idname, window)
            self._window = window

        if not isinstance(self._window, (QtWidgets.QWidget, ModuleType)):
            raise AttributeError(
                "`window` should be a `QWidget or module`. Got: {}".format(
                    str(type(self._window))
                )
            )

        self.before_window_show()

        def pull_to_front(window):
            """Pull window forward to screen.

            If Window is minimized this will un-minimize, then it can be raised
            and activated to the front.
            """
            window.setWindowState(
                (window.windowState() & ~QtCore.Qt.WindowMinimized) |
                QtCore.Qt.WindowActive
            )
            window.raise_()
            window.activateWindow()

        if isinstance(self._window, ModuleType):
            self._window.show()
            pull_to_front(self._window)

            # Pull window to the front
            window = None
            if hasattr(self._window, "window"):
                window = self._window.window
            elif hasattr(self._window, "_window"):
                window = self._window.window

            if window:
                BlenderApplication.store_window(self.bl_idname, window)

        else:
            origin_flags = self._window.windowFlags()
            on_top_flags = origin_flags | QtCore.Qt.WindowStaysOnTopHint
            self._window.setWindowFlags(on_top_flags)
            self._window.show()
            pull_to_front(self._window)

            # if on_top_flags != origin_flags:
            #     self._window.setWindowFlags(origin_flags)
            #     self._window.show()

        return {'FINISHED'}

    def before_window_show(self):
        return

execute(context)

Execute the operator.

The child class must implement execute() where it only has to set self._window to the desired Qt window and then simply run return super().execute(context). self._window is expected to have a show method. If the show method requires arguments, you can set self._show_args and self._show_kwargs. args should be a list, kwargs a dictionary.

Source code in client/ayon_blender/api/ops.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def execute(self, context):
    """Execute the operator.

    The child class must implement `execute()` where it only has to set
    `self._window` to the desired Qt window and then simply run
    `return super().execute(context)`.
    `self._window` is expected to have a `show` method.
    If the `show` method requires arguments, you can set `self._show_args`
    and `self._show_kwargs`. `args` should be a list, `kwargs` a
    dictionary.
    """

    if self._tool_name is None:
        if self._window is None:
            raise AttributeError("`self._window` is not set.")

    else:
        window = BlenderApplication.get_window(self.bl_idname)
        if window is None:
            window = host_tools.get_tool_by_name(self._tool_name)
            BlenderApplication.store_window(self.bl_idname, window)
        self._window = window

    if not isinstance(self._window, (QtWidgets.QWidget, ModuleType)):
        raise AttributeError(
            "`window` should be a `QWidget or module`. Got: {}".format(
                str(type(self._window))
            )
        )

    self.before_window_show()

    def pull_to_front(window):
        """Pull window forward to screen.

        If Window is minimized this will un-minimize, then it can be raised
        and activated to the front.
        """
        window.setWindowState(
            (window.windowState() & ~QtCore.Qt.WindowMinimized) |
            QtCore.Qt.WindowActive
        )
        window.raise_()
        window.activateWindow()

    if isinstance(self._window, ModuleType):
        self._window.show()
        pull_to_front(self._window)

        # Pull window to the front
        window = None
        if hasattr(self._window, "window"):
            window = self._window.window
        elif hasattr(self._window, "_window"):
            window = self._window.window

        if window:
            BlenderApplication.store_window(self.bl_idname, window)

    else:
        origin_flags = self._window.windowFlags()
        on_top_flags = origin_flags | QtCore.Qt.WindowStaysOnTopHint
        self._window.setWindowFlags(on_top_flags)
        self._window.show()
        pull_to_front(self._window)

        # if on_top_flags != origin_flags:
        #     self._window.setWindowFlags(origin_flags)
        #     self._window.show()

    return {'FINISHED'}

LaunchWorkFiles

Bases: LaunchQtApp

Launch AYON Work Files.

Source code in client/ayon_blender/api/ops.py
369
370
371
372
373
374
375
376
377
class LaunchWorkFiles(LaunchQtApp):
    """Launch AYON Work Files."""

    bl_idname = "wm.ayon_workfiles"
    bl_label = "Work Files..."
    _tool_name = "workfiles"

    def execute(self, context):
        return super().execute(context)

MainThreadItem

Structure to store information about callback in main thread.

Item should be used to execute callback in main thread which may be needed for execution of Qt objects.

Item store callback (callable variable), arguments and keyword arguments for the callback. Item hold information about it's process.

Source code in client/ayon_blender/api/ops.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
class MainThreadItem:
    """Structure to store information about callback in main thread.

    Item should be used to execute callback in main thread which may be needed
    for execution of Qt objects.

    Item store callback (callable variable), arguments and keyword arguments
    for the callback. Item hold information about it's process.
    """
    not_set = object()
    sleep_time = 0.1

    def __init__(self, callback, *args, **kwargs):
        self.done = False
        self.exception = self.not_set
        self.result = self.not_set
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def execute(self):
        """Execute callback and store its result.

        Method must be called from main thread. Item is marked as `done`
        when callback execution finished. Store output of callback of exception
        information when callback raises one.
        """
        print("Executing process in main thread")
        if self.done:
            print("- item is already processed")
            return

        callback = self.callback
        args = self.args
        kwargs = self.kwargs
        print("Running callback: {}".format(str(callback)))
        try:
            result = callback(*args, **kwargs)
            self.result = result

        except Exception:
            self.exception = sys.exc_info()

        finally:
            print("Done")
            self.done = True

    def wait(self):
        """Wait for result from main thread.

        This method stops current thread until callback is executed.

        Returns:
            object: Output of callback. May be any type or object.

        Raises:
            Exception: Reraise any exception that happened during callback
                execution.
        """
        while not self.done:
            print(self.done)
            time.sleep(self.sleep_time)

        if self.exception is self.not_set:
            return self.result
        raise self.exception

execute()

Execute callback and store its result.

Method must be called from main thread. Item is marked as done when callback execution finished. Store output of callback of exception information when callback raises one.

Source code in client/ayon_blender/api/ops.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def execute(self):
    """Execute callback and store its result.

    Method must be called from main thread. Item is marked as `done`
    when callback execution finished. Store output of callback of exception
    information when callback raises one.
    """
    print("Executing process in main thread")
    if self.done:
        print("- item is already processed")
        return

    callback = self.callback
    args = self.args
    kwargs = self.kwargs
    print("Running callback: {}".format(str(callback)))
    try:
        result = callback(*args, **kwargs)
        self.result = result

    except Exception:
        self.exception = sys.exc_info()

    finally:
        print("Done")
        self.done = True

wait()

Wait for result from main thread.

This method stops current thread until callback is executed.

Returns:

Name Type Description
object

Output of callback. May be any type or object.

Raises:

Type Description
Exception

Reraise any exception that happened during callback execution.

Source code in client/ayon_blender/api/ops.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def wait(self):
    """Wait for result from main thread.

    This method stops current thread until callback is executed.

    Returns:
        object: Output of callback. May be any type or object.

    Raises:
        Exception: Reraise any exception that happened during callback
            execution.
    """
    while not self.done:
        print(self.done)
        time.sleep(self.sleep_time)

    if self.exception is self.not_set:
        return self.result
    raise self.exception

OpenTemplate

Bases: LaunchQtApp

Build Workfile from ayon template settings.

Source code in client/ayon_blender/api/ops.py
470
471
472
473
474
475
476
477
478
479
480
class OpenTemplate(LaunchQtApp):
    """Build Workfile from ayon template settings."""

    bl_idname = "wm.ayon_open_template"
    bl_label = "Open Template"
    def execute(self, context):
        from .workfile_template_builder import open_template
        window = open_template()
        BlenderApplication.store_window(self.bl_idname, window)
        self._window = window
        return super().execute(context)

TOPBAR_MT_ayon

Bases: Menu

AYON menu.

Source code in client/ayon_blender/api/ops.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
class TOPBAR_MT_ayon(bpy.types.Menu):
    """AYON menu."""

    bl_idname = "TOPBAR_MT_AYON"
    bl_label = os.environ.get("AYON_MENU_LABEL")

    def draw(self, context):
        """Draw the menu in the UI."""

        layout = self.layout

        pcoll = PREVIEW_COLLECTIONS.get("ayon")
        if pcoll:
            pyblish_menu_icon = pcoll["pyblish_menu_icon"]
            pyblish_menu_icon_id = pyblish_menu_icon.icon_id
        else:
            pyblish_menu_icon_id = 0

        folder_path = get_current_folder_path()
        task_name = get_current_task_name()
        context_label = f"{folder_path}, {task_name}"
        context_label_item = layout.row()
        context_label_item.operator(
            LaunchWorkFiles.bl_idname, text=context_label
        )
        context_label_item.enabled = False
        project_name = get_current_project_name()
        project_settings = get_project_settings(project_name)
        if project_settings["core"]["tools"]["ayon_menu"].get(
            "version_up_current_workfile"):
                layout.separator()
                layout.operator(
                    VersionUpWorkfile.bl_idname,
                    text="Version Up Workfile"
                )
                wm = bpy.context.window_manager
                keyconfigs = wm.keyconfigs
                keymap = keyconfigs.addon.keymaps.new(name='Window', space_type='EMPTY')
                keymap.keymap_items.new(
                    VersionUpWorkfile.bl_idname, 'S',
                    'PRESS', ctrl=True, alt=True
                )
                bpy.context.window_manager.keyconfigs.addon.keymaps.update()

        layout.separator()
        layout.operator(LaunchWorkFiles.bl_idname, text="Work Files...")

        layout.separator()
        layout.operator(LaunchCreator.bl_idname, text="Create...")
        layout.operator(LaunchLoader.bl_idname, text="Load...")
        layout.operator(
            LaunchPublisher.bl_idname,
            text="Publish...",
            icon_value=pyblish_menu_icon_id,
        )
        layout.operator(LaunchManager.bl_idname, text="Manage...")
        layout.operator(LaunchLibrary.bl_idname, text="Library...")
        layout.separator()
        layout.operator(SetFrameRange.bl_idname, text="Set Frame Range")
        layout.operator(SetResolution.bl_idname, text="Set Resolution")
        layout.operator(SetUnitScale.bl_idname, text="Set Unit Scale")
        layout.operator(CreateRenderSetup.bl_idname,
                        text="Create Render Setup")

        layout.separator()
        layout.menu(
            TOPBAR_MT_ayon_Templated_Workfile.bl_idname,
            text="Templated Workfile"
        )

draw(context)

Draw the menu in the UI.

Source code in client/ayon_blender/api/ops.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def draw(self, context):
    """Draw the menu in the UI."""

    layout = self.layout

    pcoll = PREVIEW_COLLECTIONS.get("ayon")
    if pcoll:
        pyblish_menu_icon = pcoll["pyblish_menu_icon"]
        pyblish_menu_icon_id = pyblish_menu_icon.icon_id
    else:
        pyblish_menu_icon_id = 0

    folder_path = get_current_folder_path()
    task_name = get_current_task_name()
    context_label = f"{folder_path}, {task_name}"
    context_label_item = layout.row()
    context_label_item.operator(
        LaunchWorkFiles.bl_idname, text=context_label
    )
    context_label_item.enabled = False
    project_name = get_current_project_name()
    project_settings = get_project_settings(project_name)
    if project_settings["core"]["tools"]["ayon_menu"].get(
        "version_up_current_workfile"):
            layout.separator()
            layout.operator(
                VersionUpWorkfile.bl_idname,
                text="Version Up Workfile"
            )
            wm = bpy.context.window_manager
            keyconfigs = wm.keyconfigs
            keymap = keyconfigs.addon.keymaps.new(name='Window', space_type='EMPTY')
            keymap.keymap_items.new(
                VersionUpWorkfile.bl_idname, 'S',
                'PRESS', ctrl=True, alt=True
            )
            bpy.context.window_manager.keyconfigs.addon.keymaps.update()

    layout.separator()
    layout.operator(LaunchWorkFiles.bl_idname, text="Work Files...")

    layout.separator()
    layout.operator(LaunchCreator.bl_idname, text="Create...")
    layout.operator(LaunchLoader.bl_idname, text="Load...")
    layout.operator(
        LaunchPublisher.bl_idname,
        text="Publish...",
        icon_value=pyblish_menu_icon_id,
    )
    layout.operator(LaunchManager.bl_idname, text="Manage...")
    layout.operator(LaunchLibrary.bl_idname, text="Library...")
    layout.separator()
    layout.operator(SetFrameRange.bl_idname, text="Set Frame Range")
    layout.operator(SetResolution.bl_idname, text="Set Resolution")
    layout.operator(SetUnitScale.bl_idname, text="Set Unit Scale")
    layout.operator(CreateRenderSetup.bl_idname,
                    text="Create Render Setup")

    layout.separator()
    layout.menu(
        TOPBAR_MT_ayon_Templated_Workfile.bl_idname,
        text="Templated Workfile"
    )

TOPBAR_MT_ayon_Templated_Workfile

Bases: Menu

AYON submenu example.

Source code in client/ayon_blender/api/ops.py
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
class TOPBAR_MT_ayon_Templated_Workfile(bpy.types.Menu):
    """AYON submenu example."""

    bl_idname = "TOPBAR_MT_AYON_TEMPLATED_WORKFILE"
    bl_label = "Templated Workfile"

    def draw(self, context):
        layout = self.layout
        layout.operator(
            CreateFirstWorkfileFromTemplate.bl_idname,
            text="Create First Workfile from Template"
        )
        layout.operator(
            BuildWorkfileFromTemplate.bl_idname,
            text="Build Workfile from Template"
        )
        # layout.operator(
        #     UpdateWorkfileFromTemplate.bl_idname,
        #     text="Update Workfile from Template"
        # )
        layout.separator()
        layout.operator(
            OpenTemplate.bl_idname,
            text="Open Template"
        )
        layout.operator(
            CreatePlaceholder.bl_idname,
            text="Create Placeholder"
        )
        layout.operator(
            UpdatePlaceholder.bl_idname,
            text="Update Placeholder"
        )

UpdatePlaceholder

Bases: LaunchQtApp

Update Placeholder from ayon template settings.

Source code in client/ayon_blender/api/ops.py
497
498
499
500
501
502
503
504
505
506
507
class UpdatePlaceholder(LaunchQtApp):
    """Update Placeholder from ayon template settings."""

    bl_idname = "wm.ayon_update_placeholder"
    bl_label = "Update Placeholder"
    def execute(self, context):
        from .workfile_template_builder import update_placeholder
        window = update_placeholder()
        BlenderApplication.store_window(self.bl_idname, window)
        self._window = window
        return super().execute(context)

VersionUpWorkfile

Bases: LaunchQtApp

Perform Incremental Save Workfile.

Source code in client/ayon_blender/api/ops.py
425
426
427
428
429
430
431
432
433
class VersionUpWorkfile(LaunchQtApp):
    """Perform Incremental Save Workfile."""

    bl_idname = "wm.ayon_version_up_workfile"
    bl_label = "Version Up Workfile"

    def execute(self, context):
        version_up_current_workfile()
        return {"FINISHED"}

draw_ayon_menu(self, context)

Draw the AYON menu in the top bar.

Source code in client/ayon_blender/api/ops.py
615
616
617
618
def draw_ayon_menu(self, context):
    """Draw the AYON menu in the top bar."""

    self.layout.menu(TOPBAR_MT_ayon.bl_idname)

execute_function_in_main_thread(f)

Decorator to move a function call into main thread items

Source code in client/ayon_blender/api/ops.py
44
45
46
47
48
49
def execute_function_in_main_thread(f):
    """Decorator to move a function call into main thread items"""
    def wrapper(*args, **kwargs):
        mti = MainThreadItem(f, *args, **kwargs)
        execute_in_main_thread(mti)
    return wrapper

register()

Register the operators and menu.

Source code in client/ayon_blender/api/ops.py
644
645
646
647
648
649
650
651
652
653
654
655
def register():
    "Register the operators and menu."

    pcoll = bpy.utils.previews.new()
    pyblish_icon_file = Path(__file__).parent / "icons" / "pyblish-32x32.png"
    pcoll.load("pyblish_menu_icon", str(pyblish_icon_file.absolute()), 'IMAGE')
    PREVIEW_COLLECTIONS["ayon"] = pcoll

    BlenderApplication.get_app()
    for cls in classes:
        bpy.utils.register_class(cls)
    bpy.types.TOPBAR_MT_editor_menus.append(draw_ayon_menu)

unregister()

Unregister the operators and menu.

Source code in client/ayon_blender/api/ops.py
658
659
660
661
662
663
664
665
def unregister():
    """Unregister the operators and menu."""

    pcoll = PREVIEW_COLLECTIONS.pop("ayon")
    bpy.utils.previews.remove(pcoll)
    bpy.types.TOPBAR_MT_editor_menus.remove(draw_ayon_menu)
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)