Skip to content

ops

Blender operators and menus for use with Avalon.

LaunchCreator

Bases: LaunchQtApp

Launch Avalon Creator.

Source code in client/ayon_blender/api/ops.py
308
309
310
311
312
313
314
315
316
317
318
319
320
class LaunchCreator(LaunchQtApp):
    """Launch Avalon Creator."""

    bl_idname = "wm.avalon_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
350
351
352
353
354
355
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
323
324
325
326
327
328
class LaunchLoader(LaunchQtApp):
    """Launch AYON Loader."""

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

LaunchManager

Bases: LaunchQtApp

Launch Avalon Manager.

Source code in client/ayon_blender/api/ops.py
342
343
344
345
346
347
class LaunchManager(LaunchQtApp):
    """Launch Avalon Manager."""

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

LaunchPublisher

Bases: LaunchQtApp

Launch Avalon Publisher.

Source code in client/ayon_blender/api/ops.py
331
332
333
334
335
336
337
338
339
class LaunchPublisher(LaunchQtApp):
    """Launch Avalon Publisher."""

    bl_idname = "wm.avalon_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
210
211
212
213
214
215
216
217
218
219
220
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
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
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
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 Avalon Work Files.

Source code in client/ayon_blender/api/ops.py
358
359
360
361
362
363
364
365
366
class LaunchWorkFiles(LaunchQtApp):
    """Launch Avalon Work Files."""

    bl_idname = "wm.avalon_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
 92
 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
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
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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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

TOPBAR_MT_avalon

Bases: Menu

Avalon menu.

Source code in client/ayon_blender/api/ops.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
class TOPBAR_MT_avalon(bpy.types.Menu):
    """Avalon menu."""

    bl_idname = "TOPBAR_MT_avalon"
    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("avalon")
        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(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.separator()
        layout.operator(LaunchWorkFiles.bl_idname, text="Work Files...")

draw(context)

Draw the menu in the UI.

Source code in client/ayon_blender/api/ops.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def draw(self, context):
    """Draw the menu in the UI."""

    layout = self.layout

    pcoll = PREVIEW_COLLECTIONS.get("avalon")
    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(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.separator()
    layout.operator(LaunchWorkFiles.bl_idname, text="Work Files...")

VersionUpWorkfile

Bases: LaunchQtApp

Perform Incremental Save Workfile.

Source code in client/ayon_blender/api/ops.py
402
403
404
405
406
407
408
409
410
class VersionUpWorkfile(LaunchQtApp):
    """Perform Incremental Save Workfile."""

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

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

draw_avalon_menu(self, context)

Draw the Avalon menu in the top bar.

Source code in client/ayon_blender/api/ops.py
474
475
476
477
def draw_avalon_menu(self, context):
    """Draw the Avalon menu in the top bar."""

    self.layout.menu(TOPBAR_MT_avalon.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
42
43
44
45
46
47
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
495
496
497
498
499
500
501
502
503
504
505
506
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["avalon"] = pcoll

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

unregister()

Unregister the operators and menu.

Source code in client/ayon_blender/api/ops.py
509
510
511
512
513
514
515
516
def unregister():
    """Unregister the operators and menu."""

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