Skip to content

open_source_workfile

Loader action to open source workfiles in Tray Browser.

OpenSourceWorkfileAction

Bases: LoaderSimpleActionPlugin

Open source workfile in its host DCC application.

Source code in client/ayon_applications/plugins/load_actions/open_source_workfile.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
class OpenSourceWorkfileAction(LoaderSimpleActionPlugin):
    """Open source workfile in its host DCC application."""

    label = "Open Source Workfile"
    order = 5
    group_label = None
    icon = {
        "type": "material-symbols",
        "name": "rocket_launch",
        "color": "#d8d8d8",
    }

    # TODO: Allow to customize in settings whether this action is enabled
    # TODO: Allow to customize for which extensions or product types this
    #  action is available.

    def is_compatible(self, selection: LoaderActionSelection) -> bool:
        """Check if any selected version has source workfile."""
        # Only allow if no registered host, like in standalone browser
        if self.host_name:
            return False

        if not selection.versions_selected():
            return False

        for version in selection.get_selected_version_entities():
            if not version["taskId"]:
                continue

            source = version.get("attrib", {}).get("source")

            if not source:
                return False

            if source.startswith("{root"):
                return True

            elif os.path.exists(source):
                # Assume it's a valid source workfile
                return True

        return False

    def execute_simple_action(
            self,
            selection: LoaderActionSelection,
            form_values: dict[str, Any],
    ) -> Optional[LoaderActionResult]:
        """Open source workfile in DCC application."""
        versions = selection.get_selected_version_entities()
        version = versions[0] if versions else None

        if not version:
            return LoaderActionResult(
                "No version selected",
                success=False,
            )

        source_path = version.get("attrib", {}).get("source")
        if not source_path:
            return LoaderActionResult(
                "This version doesn't have source workfile information.",
                success=False,
            )

        workfile_name = os.path.basename(source_path)
        file_ext = os.path.splitext(workfile_name)[1].lower()
        if not file_ext:
            return LoaderActionResult(
                f"Version source '{workfile_name}' has no extension.",
                success=False,
            )

        # Get compatible applications
        task_id = version["taskId"]
        project_name = selection.project_name
        addons_manager = self._context.get_addons_manager()
        compatible_apps = self._get_compatible_apps(
            addons_manager,
            file_ext=file_ext,
            project_name=project_name,
            task_id=task_id
        )
        if not compatible_apps:
            task = ayon_api.get_task_by_id(project_name, task_id)
            return LoaderActionResult(
                f"No compatible applications for {file_ext} "
                f"enabled for context: {project_name} > {task['name']}",
                success=False,
            )

        ayon_app_name = version["data"].get("ayon_app_name")
        selected_app = self._show_app_dialog(
            compatible_apps,
            workfile_name,
            project_name,
            ayon_app_name
        )

        if not selected_app:
            return
        anatomy = selection.get_project_anatomy()
        workfile_path: str = anatomy.fill_root(source_path)
        if not os.path.exists(workfile_path):
            return LoaderActionResult(
                f"Source workfile does not exist at '{workfile_path}'",
                success=False,
            )
        # Launch application
        run_detached_ayon_launcher_process(
            "addon", "applications", "launch-by-id",
            "--project", project_name,
            "--task-id", version["taskId"],
            "--app", selected_app.full_name,
            "--workfile-path", workfile_path,
            "--use-last-workfile", "0",
        )
        return LoaderActionResult(
            f"Launching {selected_app.full_name} "
            f"to open workfile '{workfile_name}'",
            success=True,
        )

    def _get_compatible_apps(
        self,
        addons_manager,
        file_ext,
        project_name,
        task_id,
    ) -> list[Any]:
        """Get compatible applications for file extension."""

        # Find the applications matching the host names
        apps_addon = addons_manager.get("applications")
        if not apps_addon:
            return []
        # host names that can open this extension
        # NOTE: Does not respect project bundle addons.
        host_names: set[str] = set()
        for addon in addons_manager.addons:
            if not isinstance(addon, IHostAddon):
                continue

            try:

                extensions = addon.get_workfile_extensions()
            except Exception:
                self.log.error(
                    f"Failed to get workfile extensions for addon: {addon}",
                    exc_info=True,
                )
                continue

            host_name: str = addon.host_name
            if file_ext in extensions:
                host_names.add(host_name)

        if not host_names:
            return []

        app_items = apps_addon.get_application_items(
            project_name,
            task_id=task_id,
        )

        app_manager = apps_addon.get_applications_manager()

        return self._create_fake_applications(
            app_manager,
            app_items,
            host_names
        )

    def _create_fake_applications(
            self,
            app_manager: ApplicationManager,
            app_items: list[dict[str, Any]],
            host_names: set[str]) -> list[Application]:
        """Fake application objects representing compatible applications.

        Args:
            app_manager (ApplicationManager): Applications manager
                instance from applications addon
            app_items (list[dict[str, Any]]): Application items from
            applications addon
            host_names (set[str]): host names that can open the source workfile

        Returns:
            list[Application]: Fake application objects representing
                compatible applications.
        """
        app_items_by_group = collections.defaultdict(list)
        for app_item in app_items:
            if app_item["host_name"] not in host_names:
                continue
            full_name = app_item["full_name"]
            group_name = full_name.split("/")[0]
            app_items_by_group[group_name].append(app_item)

        output = []
        for group_name, group_app_items in app_items_by_group.items():
            host_name = None
            variants = []
            for app_item in group_app_items:
                variants.append({
                    "name": app_item["full_name"].split("/")[1],
                    "label": app_item["variant_label"],
                    "environment": "{}",
                    "arguments": [],
                    "executables": {},
                })
            group = ApplicationGroup(
                group_name,
                {
                    "enabled": True,
                    "environment": "{}",
                    "host_name": host_name,
                    "variants": variants,
                },
                app_manager
            )
            for variant in group.variants.values():
                output.append(variant)
        return output

    def _show_app_dialog(
            self,
            apps: list[Application],
            workfile_name: str,
            project_name: str,
            source_app_full_name: Optional[str] = None
    ) -> str:
        """Show application selection dialog."""
        dialog = QtWidgets.QDialog()
        icon = QtGui.QIcon(get_app_icon_path())
        dialog.setWindowIcon(icon)
        dialog.setWindowTitle("Open Source Workfile")
        dialog.setMinimumWidth(400)
        dialog.setStyleSheet(load_stylesheet())

        layout = QtWidgets.QVBoxLayout(dialog)

        info = QtWidgets.QLabel(
            "<h3>Open Source Workfile</h3>"
            f"<p><b>Workfile:</b> {workfile_name}</p>"
            f"<p><b>Project:</b> {project_name}</p>"
        )
        info.setTextFormat(QtCore.Qt.RichText)
        layout.addWidget(info)

        app_list = QtWidgets.QListWidget()
        empty_pix = QtGui.QPixmap(128, 128)
        empty_icon = QtGui.QIcon(empty_pix)
        preferred_index = 0
        for i, app in enumerate(apps):
            label = app.full_label or app.name
            icon = empty_icon
            if app.icon:
                icon = get_qt_icon(app.icon)
            # Highlight the app that was used to create the publish so that
            # the user knows it's the recommended one to open with.
            if source_app_full_name and app.full_name == source_app_full_name:
                preferred_index = i
                label += " (used to create publish)"

            item = QtWidgets.QListWidgetItem(label)
            item.setData(QtCore.Qt.DecorationRole, icon)
            item.setData(QtCore.Qt.UserRole, app)
            app_list.addItem(item)

        # Preselect the first entry or the one matching the source app
        app_list.setCurrentRow(preferred_index)

        layout.addWidget(app_list)

        btn_layout = QtWidgets.QHBoxLayout()
        btn_layout.addStretch()
        cancel_btn = QtWidgets.QPushButton("Cancel")
        open_btn = QtWidgets.QPushButton("Open")
        open_btn.setDefault(True)
        btn_layout.addWidget(cancel_btn)
        btn_layout.addWidget(open_btn)
        layout.addLayout(btn_layout)

        open_btn.clicked.connect(dialog.accept)
        cancel_btn.clicked.connect(dialog.reject)
        app_list.itemDoubleClicked.connect(dialog.accept)

        if dialog.exec_() == QtWidgets.QDialog.Accepted:
            item = app_list.currentItem()
            if not item:
                return None

            return item.data(QtCore.Qt.UserRole)
        return None

execute_simple_action(selection, form_values)

Open source workfile in DCC application.

Source code in client/ayon_applications/plugins/load_actions/open_source_workfile.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 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
def execute_simple_action(
        self,
        selection: LoaderActionSelection,
        form_values: dict[str, Any],
) -> Optional[LoaderActionResult]:
    """Open source workfile in DCC application."""
    versions = selection.get_selected_version_entities()
    version = versions[0] if versions else None

    if not version:
        return LoaderActionResult(
            "No version selected",
            success=False,
        )

    source_path = version.get("attrib", {}).get("source")
    if not source_path:
        return LoaderActionResult(
            "This version doesn't have source workfile information.",
            success=False,
        )

    workfile_name = os.path.basename(source_path)
    file_ext = os.path.splitext(workfile_name)[1].lower()
    if not file_ext:
        return LoaderActionResult(
            f"Version source '{workfile_name}' has no extension.",
            success=False,
        )

    # Get compatible applications
    task_id = version["taskId"]
    project_name = selection.project_name
    addons_manager = self._context.get_addons_manager()
    compatible_apps = self._get_compatible_apps(
        addons_manager,
        file_ext=file_ext,
        project_name=project_name,
        task_id=task_id
    )
    if not compatible_apps:
        task = ayon_api.get_task_by_id(project_name, task_id)
        return LoaderActionResult(
            f"No compatible applications for {file_ext} "
            f"enabled for context: {project_name} > {task['name']}",
            success=False,
        )

    ayon_app_name = version["data"].get("ayon_app_name")
    selected_app = self._show_app_dialog(
        compatible_apps,
        workfile_name,
        project_name,
        ayon_app_name
    )

    if not selected_app:
        return
    anatomy = selection.get_project_anatomy()
    workfile_path: str = anatomy.fill_root(source_path)
    if not os.path.exists(workfile_path):
        return LoaderActionResult(
            f"Source workfile does not exist at '{workfile_path}'",
            success=False,
        )
    # Launch application
    run_detached_ayon_launcher_process(
        "addon", "applications", "launch-by-id",
        "--project", project_name,
        "--task-id", version["taskId"],
        "--app", selected_app.full_name,
        "--workfile-path", workfile_path,
        "--use-last-workfile", "0",
    )
    return LoaderActionResult(
        f"Launching {selected_app.full_name} "
        f"to open workfile '{workfile_name}'",
        success=True,
    )

is_compatible(selection)

Check if any selected version has source workfile.

Source code in client/ayon_applications/plugins/load_actions/open_source_workfile.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def is_compatible(self, selection: LoaderActionSelection) -> bool:
    """Check if any selected version has source workfile."""
    # Only allow if no registered host, like in standalone browser
    if self.host_name:
        return False

    if not selection.versions_selected():
        return False

    for version in selection.get_selected_version_entities():
        if not version["taskId"]:
            continue

        source = version.get("attrib", {}).get("source")

        if not source:
            return False

        if source.startswith("{root"):
            return True

        elif os.path.exists(source):
            # Assume it's a valid source workfile
            return True

    return False