Skip to content

hda_utils

Heper functions for load HDA

SelectFolderPathDialog

Bases: QDialog

Simple dialog to allow a user to select project and folder.

Source code in client/ayon_houdini/api/hda_utils.py
541
542
543
544
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
614
615
class SelectFolderPathDialog(QtWidgets.QDialog):
    """Simple dialog to allow a user to select project and folder."""

    last_width = 300

    def __init__(self, parent=None):
        super(SelectFolderPathDialog, self).__init__(parent)
        self.setWindowTitle("Set project and folder path")
        self.setStyleSheet(load_adapted_stylesheet(self))

        project_widget = QtWidgets.QComboBox()
        project_widget.addItems(self.get_projects())

        filter_widget = QtWidgets.QLineEdit()
        filter_widget.setPlaceholderText("Folder name filter...")

        folder_widget = SimpleFoldersWidget(parent=self)

        accept_button = QtWidgets.QPushButton("Set folder path")

        top_layout = QtWidgets.QHBoxLayout(self)
        top_layout.setContentsMargins(5, 10, 10, 10)
        self._grip = QtWidgets.QSizeGrip(self)
        self._grip.setStyleSheet(
            "QSizeGrip {width: 4px;height: 64px;background-color: #454555;"
            "padding: 2, 0, 2, 0;}\n"
            "QSizeGrip::hover {background-color: #707080}"
        )
        self._grip.setVisible(True)
        top_layout.addWidget(self._grip, 0)

        main_layout = QtWidgets.QVBoxLayout()
        main_layout.addWidget(project_widget, 0)
        main_layout.addWidget(filter_widget, 0)
        main_layout.addWidget(folder_widget, 1)
        main_layout.addWidget(accept_button, 0)

        top_layout.addLayout(main_layout)

        self.project_widget = project_widget
        self.folder_widget = folder_widget

        project_widget.currentTextChanged.connect(self.on_project_changed)
        filter_widget.textChanged.connect(folder_widget.set_name_filter)
        folder_widget.double_clicked.connect(self.accept)
        accept_button.clicked.connect(self.accept)

    def resizeEvent(self, event):
        SelectFolderPathDialog.last_width = event.size().width()
        super().resizeEvent(event)

    def get_selected_folder_path(self) -> str:
        return self.folder_widget.get_selected_folder_path()

    def get_selected_project_name(self) -> str:
        return self.project_widget.currentText()

    def get_projects(self) -> List[str]:
        projects = ayon_api.get_projects(fields=["name"])
        return [p["name"] for p in projects]

    def on_project_changed(self, project_name: str):
        self.folder_widget.set_project_name(project_name)

    def set_project_name(self, project_name: str):
        self.project_widget.setCurrentText(project_name)

        if self.project_widget.currentText() != project_name:
            # Project does not exist
            return

        # Force the set of widget because even though a callback exist on the
        # project widget it may have been initialized to that value and hence
        # detect no change.
        self.folder_widget.set_project_name(project_name)

SelectProductDialog

Bases: QDialog

Simple dialog to allow a user to select a product.

Source code in client/ayon_houdini/api/hda_utils.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
class SelectProductDialog(QtWidgets.QDialog):
    """Simple dialog to allow a user to select a product."""

    def __init__(self, project_name, folder_id, parent=None):
        super(SelectProductDialog, self).__init__(parent)
        self.setWindowTitle("Select a Product")
        self.setStyleSheet(load_adapted_stylesheet(self))

        self.project_name = project_name
        self.folder_id = folder_id

        # Create widgets and layout
        product_types_widget = QtWidgets.QComboBox()
        products_widget = QtWidgets.QListWidget()
        accept_button = QtWidgets.QPushButton("Set product name")

        main_layout = QtWidgets.QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.addWidget(product_types_widget, 0)
        main_layout.addWidget(products_widget, 1)
        main_layout.addWidget(accept_button, 0)

        self.product_types_widget = product_types_widget
        self.products_widget = products_widget

        # Connect Signals
        product_types_widget.currentTextChanged.connect(
            self.on_product_type_changed
        )
        products_widget.itemDoubleClicked.connect(self.accept)
        accept_button.clicked.connect(self.accept)

        # Initialize widgets contents
        product_types_widget.addItems(self.get_product_types())
        product_type = self.get_selected_product_type()
        self.set_product_type(product_type)

    def get_selected_product(self) -> str:
        if self.products_widget.currentItem():
            return self.products_widget.currentItem().text()
        return ""

    def get_selected_product_type(self) -> str:
        return self.product_types_widget.currentText()

    def get_product_types(self) -> List[str]:
        """return default product types."""

        return [
            "*",
            "animation",
            "camera",
            "model",
            "pointcache",
            "usd",
        ]

    def on_product_type_changed(self, product_type: str):
        self.set_product_type(product_type)

    def set_product_type(self, product_type: str):
        self.product_types_widget.setCurrentText(product_type)

        if self.product_types_widget.currentText() != product_type:
            # Product type does not exist
            return

        # Populate products list
        products = self.get_available_products(product_type)
        self.products_widget.clear()
        if products:
            self.products_widget.addItems(products)

    def set_selected_product_name(self, product_name: str):
        matching_items = self.products_widget.findItems(
            product_name, QtCore.Qt.MatchFixedString
        )
        if matching_items:
            self.products_widget.setCurrentItem(matching_items[0])

    def get_available_products(self, product_type):
        if product_type == "*":
            product_type = ""

        product_types = [product_type] if product_type else None

        products = ayon_api.get_products(
            self.project_name,
            folder_ids=[self.folder_id],
            product_types=product_types,
        )

        return list(sorted(product["name"] for product in products))

get_product_types()

return default product types.

Source code in client/ayon_houdini/api/hda_utils.py
735
736
737
738
739
740
741
742
743
744
745
def get_product_types(self) -> List[str]:
    """return default product types."""

    return [
        "*",
        "animation",
        "camera",
        "model",
        "pointcache",
        "usd",
    ]

compute_thumbnail_rect(node)

Compute thumbnail bounding rect based on thumbnail parms

Source code in client/ayon_houdini/api/hda_utils.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def compute_thumbnail_rect(node):
    """Compute thumbnail bounding rect based on thumbnail parms"""
    offset_x = node.evalParm("thumbnail_offsetx")
    offset_y = node.evalParm("thumbnail_offsety")
    width = node.evalParm("thumbnail_size")
    # todo: compute height from aspect of actual image file.
    aspect = 0.5625  # for now assume 16:9
    height = width * aspect

    center = 0.5
    half_width = width * 0.5

    return hou.BoundingRect(
        offset_x + center - half_width,
        offset_y,
        offset_x + center + half_width,
        offset_y + height,
    )

ensure_loader_expression_parm_defaults(node)

Reset representation and file parm to defaults.

The filepath and representation id parms are updated through expressions, however in older versions they were explicitly set so we ensure that the current value is set to the default value with the expression - otherwise the value will be set to the previously explicitly set overridden value.

Silently ignores if the parm does not exist or is already at default.

Parameters:

Name Type Description Default
node OpNode

The node to reset.

required
Source code in client/ayon_houdini/api/hda_utils.py
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
def ensure_loader_expression_parm_defaults(node):
    """Reset `representation` and `file` parm to defaults.

    The filepath and representation id parms are updated through expressions,
    however in older versions they were explicitly set so we ensure that the
    current value is set to the default value with the expression - otherwise
    the value will be set to the previously explicitly set overridden value.

    Silently ignores if the parm does not exist or is already at default.

    Args:
        node (hou.OpNode): The node to reset.

    """
    for parm_name in ["representation", "file"]:
        parm = node.parm(parm_name)
        if parm is None:
            continue

        # TODO: For whatever reason this still returns True even if the
        #  expression does not match the default, so for now we always revert
        # if parm.isAtDefault(compare_expressions=True):
        #     continue

        default_expression = parm.parmTemplate().defaultExpression()
        if not default_expression:
            continue

        default_expression = default_expression[0]

        try:
            current_expression = parm.expression()
            if current_expression == default_expression:
                continue
        except hou.OperationFailed:
            pass

        print(f"Enforcing {parm.path()} to default value")
        locked = parm.isLocked()
        parm.lock(False)
        parm.deleteAllKeyframes()
        parm.revertToDefaults()
        parm.lock(locked)

get_available_representations(node)

Return the representation list for node.

Parameters:

Name Type Description Default
node Node

Node to query selected version's representations for.

required

Returns:

Type Description

list[str]: representation names for the product version.

Source code in client/ayon_houdini/api/hda_utils.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
def get_available_representations(node):
    """Return the representation list for node.

    Args:
        node (hou.Node): Node to query selected version's representations for.

    Returns:
        list[str]: representation names for the product version.
    """

    project_name = node.evalParm("project_name") or get_current_project_name()
    folder_path = node.evalParm("folder_path")
    product_name = node.evalParm("product_name")
    version = node.evalParm("version")

    if not all([project_name, folder_path, product_name, version]):
        return []

    try:
        version = int(version.strip())
    except ValueError:
        load_message_parm = node.parm("load_message")
        load_message_parm.set(
            f"Invalid version format: '{version}'\n"
            "Make sure to set a valid version number."
        )
        return

    representation_filter = None
    filter_parm = node.parm("representation_filter")
    if filter_parm and not filter_parm.isDisabled() and filter_parm.eval():
        representation_filter = filter_parm.eval().split(" ")

    folder_entity = get_folder_by_path(
        project_name, folder_path=folder_path, fields={"id"}
    )
    product_entity = get_product_by_name(
        project_name,
        product_name=product_name,
        folder_id=folder_entity["id"],
        fields={"id"},
    )
    version_entity = get_version_by_name(
        project_name, version, product_id=product_entity["id"], fields={"id"}
    )
    representations = get_representations(
        project_name,
        version_ids={version_entity["id"]},
        fields={"name"},
        representation_names=representation_filter,
    )
    representations_names = [n["name"] for n in representations]
    return representations_names

get_available_versions(node)

Return the versions list for node.

The versions are sorted with the latest version first and oldest lower version last.

Parameters:

Name Type Description Default
node Node

Node to query selected products' versions for.

required

Returns:

Type Description

list[int]: Version numbers for the product

Source code in client/ayon_houdini/api/hda_utils.py
 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
def get_available_versions(node):
    """Return the versions list for node.

    The versions are sorted with the latest version first and oldest lower
    version last.

    Args:
        node (hou.Node): Node to query selected products' versions for.

    Returns:
        list[int]: Version numbers for the product
    """

    project_name = node.evalParm("project_name") or get_current_project_name()
    folder_path = node.evalParm("folder_path")
    product_name = node.evalParm("product_name")

    if not all([project_name, folder_path, product_name]):
        return []

    folder_entity = get_folder_by_path(
        project_name, folder_path, fields={"id"}
    )
    if not folder_entity:
        return []
    product_entity = get_product_by_name(
        project_name,
        product_name=product_name,
        folder_id=folder_entity["id"],
        fields={"id"},
    )
    if not product_entity:
        return []

    # TODO: Support hero versions
    versions = get_versions(
        project_name,
        product_ids={product_entity["id"]},
        fields={"version"},
        hero=False,
    )
    version_names = [version["version"] for version in versions]
    version_names.reverse()
    return version_names

get_filepath_from_context(context)

Format file path for sequence with $F or .

Source code in client/ayon_houdini/api/hda_utils.py
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
def get_filepath_from_context(context: dict):
    """Format file path for sequence with $F or <UDIM>."""
    # The path is either a single file or sequence in a folder.
    # Format frame as $F and udim as <UDIM>
    representation = context["representation"]
    frame = representation["context"].get("frame")
    udim = representation["context"].get("udim")
    if frame is not None or udim is not None:
        template: str = representation["attrib"]["template"]
        repre_context: dict = representation["context"]
        if udim is not None:
            repre_context["udim"] = "<UDIM>"
            template = _remove_format_spec(template, "udim")
        if frame is not None:
            # Substitute frame number in sequence with $F with padding
            repre_context["frame"] = "$F{}".format(len(frame))  # e.g. $F4
            template = _remove_format_spec(template, "frame")

        project_name: str = repre_context["project"]["name"]
        anatomy = Anatomy(project_name, project_entity=context["project"])
        repre_context["root"] = anatomy.roots
        path = StringTemplate(template).format(repre_context)
    else:
        path = get_representation_path_from_context(context)

    # Load fails on UNC paths with backslashes and also
    # fails to resolve @sourcename var with backslashed
    # paths correctly. So we force forward slashes
    return os.path.normpath(path).replace("\\", "/")

get_representation_id(project_name, folder_path, product_name, version, representation_name)

Get representation id.

Parameters:

Name Type Description Default
project_name str

Project name

required
folder_path str

Folder name

required
product_name str

Product name

required
version str

Version name as string

required
representation_name str

Representation name

required

Returns:

Name Type Description
str

Representation id or None if not found.

Raises:

Type Description
ValueError

If the entity could not be resolved with input values.

Source code in client/ayon_houdini/api/hda_utils.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
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
473
474
475
476
def get_representation_id(
    project_name,
    folder_path,
    product_name,
    version,
    representation_name,
):
    """Get representation id.

    Args:
        project_name (str): Project name
        folder_path (str): Folder name
        product_name (str): Product name
        version (str): Version name as string
        representation_name (str): Representation name

    Returns:
        str: Representation id or None if not found.

    Raises:
        ValueError: If the entity could not be resolved with input values.

    """
    if not all(
        [project_name, folder_path, product_name, version, representation_name]
    ):
        labels = {
            "project": project_name,
            "folder": folder_path,
            "product": product_name,
            "version": version,
            "representation": representation_name,
        }
        missing = ", ".join(key for key, value in labels.items() if not value)
        raise ValueError(f"Load info incomplete. Found empty: {missing}")

    try:
        version = int(version.strip())
    except ValueError:
        raise ValueError(
            f"Invalid version format: '{version}'\n"
            "Make sure to set a valid version number."
        )

    folder_entity = get_folder_by_path(
        project_name, folder_path=folder_path, fields={"id"}
    )
    if not folder_entity:
        # This may be due to the project not existing - so let's validate
        # that first
        if not get_project(project_name):
            raise ValueError(f"Project not found: '{project_name}'")
        raise ValueError(f"Folder not found: '{folder_path}'")

    product_entity = get_product_by_name(
        project_name,
        product_name=product_name,
        folder_id=folder_entity["id"],
        fields={"id"},
    )
    if not product_entity:
        raise ValueError(f"Product not found: '{product_name}'")

    version_entity = get_version_by_name(
        project_name, version, product_id=product_entity["id"], fields={"id"}
    )
    if not version_entity:
        raise ValueError(f"Version not found: '{version}'")

    representation_entity = get_representation_by_name(
        project_name,
        representation_name,
        version_id=version_entity["id"],
        fields={"id"},
    )
    if not representation_entity:
        raise ValueError(f"Representation not found: '{representation_name}'.")
    return representation_entity["id"]

get_session_cache()

Get a persistent hou.session.ayon_cache dict

Source code in client/ayon_houdini/api/hda_utils.py
81
82
83
84
85
86
def get_session_cache() -> dict:
    """Get a persistent `hou.session.ayon_cache` dict"""
    cache = getattr(hou.session, "ayon_cache", None)
    if cache is None:
        hou.session.ayon_cache = cache = {}
    return cache

is_valid_uuid(value)

Return whether value is a valid UUID

Source code in client/ayon_houdini/api/hda_utils.py
89
90
91
92
93
94
95
def is_valid_uuid(value) -> bool:
    """Return whether value is a valid UUID"""
    try:
        uuid.UUID(value)
    except ValueError:
        return False
    return True

keep_background_images_linked(node, old_name)

Reconnect background images to node from old name.

Used as callback on node name changes to keep thumbnails linked.

Source code in client/ayon_houdini/api/hda_utils.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def keep_background_images_linked(node, old_name):
    """Reconnect background images to node from old name.

    Used as callback on node name changes to keep thumbnails linked."""
    from ayon_houdini.api.lib import (
        get_background_images,
        set_background_images,
    )

    parent = node.parent()
    images = get_background_images(parent)
    if not images:
        return

    changes = False
    old_path = f"{node.parent().path()}/{old_name}"
    for image in images:
        if image.relativeToPath() == old_path:
            image.setRelativeToPath(node.path())
            changes = True

    if changes:
        set_background_images(parent, images)

load_adapted_stylesheet(widget)

Loads and adapts AYON's stylesheet for Houdini.

This function retrieves AYON's Qt stylesheet, modifies it to convert font sizes from points (pt) to pixels (px), and caches the result for future use.

Houdini seems to handle pixels more gracefully than points on Windows, but using pixels across the board creates more problems, so we keep this fix local until a better solution emerges.

Returns:

Name Type Description
str str

The adapted stylesheet as a string.

Source code in client/ayon_houdini/api/hda_utils.py
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
def load_adapted_stylesheet(widget: QtWidgets.QWidget) -> str:
    """
    Loads and adapts AYON's stylesheet for Houdini.

    This function retrieves AYON's Qt stylesheet, modifies it to convert font
    sizes from points (pt) to pixels (px), and caches the result for future
    use.

    Houdini seems to handle pixels more gracefully than points on Windows, but
    using pixels across the board creates more problems, so we keep this fix
    local until a better solution emerges.

    Returns:
        str: The adapted stylesheet as a string.
    """
    dpr = widget.screen().devicePixelRatio()
    try:
        return load_adapted_stylesheet.cache[dpr]
    except AttributeError:
        setattr(load_adapted_stylesheet, "cache", {})
    except KeyError:
        pass

    # if we arrive here, a new cache entry must be created.
    hou.logging.log(
        hou.logging.LogEntry(
            message=f"load_adapted_stylesheet: new cache entry: {dpr}",
            source="AYON",
        )
    )

    def _convert(match):
        size = int((int(match.group(2)) * 1.1) * hou.ui.globalScaleFactor())
        size = int(size / dpr)
        return f"{match.group(1)}{size}px;"

    css = load_stylesheet()
    css = re.sub(r"(font-size:\s+)(\d+)pt;", _convert, css)  # type: ignore
    load_adapted_stylesheet.cache[dpr] = css

    return load_adapted_stylesheet.cache[dpr]

on_flag_changed(node, **kwargs)

On node flag changed callback.

Updates the brightness of attached thumbnails

Source code in client/ayon_houdini/api/hda_utils.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def on_flag_changed(node, **kwargs):
    """On node flag changed callback.

    Updates the brightness of attached thumbnails
    """
    # Showing thumbnail is disabled so can return early since
    # there should be no thumbnail to update.
    if not node.evalParm("show_thumbnail"):
        return

    # Update node thumbnails brightness with the
    # bypass state of the node.
    parent = node.parent()
    images = lib.get_background_images(parent)
    if not images:
        return

    # This may trigger on a node that can't be bypassed, like `ObjNode` so
    # consider those never bypassed
    is_bypassed = hasattr(node, "isBypassed") and node.isBypassed()
    brightness = 0.3 if is_bypassed else 1.0
    has_changes = False
    node_path = node.path()
    for image in images:
        if image.relativeToPath() == node_path:
            image.setBrightness(brightness)
            has_changes = True

    if has_changes:
        lib.set_background_images(parent, images)

on_thumbnail_show_changed(node)

Callback on thumbnail show parm changed

Source code in client/ayon_houdini/api/hda_utils.py
374
375
376
def on_thumbnail_show_changed(node):
    """Callback on thumbnail show parm changed"""
    update_thumbnail(node)

on_thumbnail_size_changed(node)

Callback on thumbnail offset or size parms changed

Source code in client/ayon_houdini/api/hda_utils.py
379
380
381
382
383
384
385
def on_thumbnail_size_changed(node):
    """Callback on thumbnail offset or size parms changed"""
    thumbnail = lib.get_node_thumbnail(node)
    if thumbnail:
        rect = compute_thumbnail_rect(node)
        thumbnail.setRect(rect)
        lib.set_node_thumbnail(node, thumbnail)

select_folder_path(node)

Show dialog to select folder path.

When triggered it opens a dialog that shows the available folder paths within a given project.

Note

This function should be refactored. It currently shows the available folder paths within the current project only.

Parameters:

Name Type Description Default
node OpNode

The HDA node.

required
Source code in client/ayon_houdini/api/hda_utils.py
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
def select_folder_path(node):
    """Show dialog to select folder path.

    When triggered it opens a dialog that shows the available
    folder paths within a given project.

    Note:
        This function should be refactored.
        It currently shows the available
          folder paths within the current project only.

    Args:
        node (hou.OpNode): The HDA node.
    """
    cursor_pos = QtGui.QCursor.pos()

    main_window = lib.get_main_window()

    project_name = node.evalParm("project_name")
    folder_path = node.evalParm("folder_path")

    dialog = SelectFolderPathDialog(parent=main_window)
    dialog.set_project_name(project_name)
    if folder_path:
        # We add a small delay to the setting of the selected folder
        # because the folder widget's set project logic itself also runs
        # with a bit of a delay, and unfortunately otherwise the project
        # has not been selected yet and thus selection does not work.
        def _select_folder_path():
            dialog.folder_widget.set_selected_folder_path(folder_path)

        QtCore.QTimer.singleShot(100, _select_folder_path)

    dialog.setStyleSheet(load_adapted_stylesheet(dialog))

    # Make it appear like a pop-up near cursor - use session's last width
    dialog.setMinimumWidth(300)
    dialog.setFixedHeight(600)
    dialog.resize(SelectFolderPathDialog.last_width, 600)
    dialog.setWindowFlags(QtCore.Qt.Popup)
    pos = dialog.mapToGlobal(
        cursor_pos - QtCore.QPoint(SelectFolderPathDialog.last_width, 0)
    )
    dialog.move(pos)

    result = dialog.exec_()
    if result != QtWidgets.QDialog.Accepted:
        return

    # Set project
    selected_project_name = dialog.get_selected_project_name()
    if selected_project_name == get_current_project_name():
        selected_project_name = "$AYON_PROJECT_NAME"

    project_parm = node.parm("project_name")
    project_parm.set(selected_project_name)
    project_parm.pressButton()  # allow any callbacks to trigger

    # Set folder path
    selected_folder_path = dialog.get_selected_folder_path()
    if not selected_folder_path:
        # Do nothing if user accepted with nothing selected
        return

    if selected_folder_path == get_current_folder_path():
        selected_folder_path = "$AYON_FOLDER_PATH"

    folder_parm = node.parm("folder_path")
    folder_parm.set(selected_folder_path)
    folder_parm.pressButton()  # allow any callbacks to trigger

select_product_name(node)

Show a modal pop-up dialog to allow user to select a product name under the current folder entity as defined on the node's parameters.

Applies the chosen value to the product_name parm on the node.

Source code in client/ayon_houdini/api/hda_utils.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def select_product_name(node):
    """Show a modal pop-up dialog to allow user to select a product name
    under the current folder entity as defined on the node's parameters.

    Applies the chosen value to the `product_name` parm on the node."""

    cursor_pos = QtGui.QCursor.pos()

    project_name = node.evalParm("project_name")
    folder_path = node.evalParm("folder_path")
    product_parm = node.parm("product_name")

    folder_entity = ayon_api.get_folder_by_path(
        project_name, folder_path, fields={"id"}
    )
    if not folder_entity:
        return

    dialog = SelectProductDialog(
        project_name, folder_entity["id"], parent=lib.get_main_window()
    )
    dialog.set_selected_product_name(product_parm.eval())

    dialog.resize(300, 600)
    dialog.setWindowFlags(QtCore.Qt.Popup)
    pos = dialog.mapToGlobal(cursor_pos - QtCore.QPoint(300, 0))
    dialog.move(pos)
    result = dialog.exec_()

    if result != QtWidgets.QDialog.Accepted:
        return
    selected_product = dialog.get_selected_product()

    if selected_product:
        product_parm.set(selected_product)
        product_parm.pressButton()  # allow any callbacks to trigger

set_node_representation_from_context(node, context, ensure_expression_defaults=True)

Update project, folder, product, version, representation name parms.

Parameters:

Name Type Description Default
node Node

Node to update

required
context dict

Context of representation

required
ensure_expression_defaults bool

Ensure expression defaults.

True
Source code in client/ayon_houdini/api/hda_utils.py
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
def set_node_representation_from_context(
    node, context, ensure_expression_defaults=True
):
    """Update project, folder, product, version, representation name parms.

    Arguments:
        node (hou.Node): Node to update
        context (dict): Context of representation
        ensure_expression_defaults (bool): Ensure expression defaults.

    """
    # TODO: Avoid 'duplicate' taking over the expression if originally
    #       it was $OS and by duplicating, e.g. the `folder` does not exist
    #       anymore since it is now `hero1` instead of `hero`
    # TODO: Support hero versions
    version = str(context["version"]["version"])

    # We only set the values if the value does not match the currently
    # evaluated result of the other parms, so that if the project name
    # value was dynamically set by the user with an expression or alike
    # then if it still matches the value of the current representation id
    # we preserve it. In essence, only update the value if the current
    # *evaluated* value of the parm differs.
    parms = {
        "project_name": context["project"]["name"],
        "folder_path": context["folder"]["path"],
        "product_name": context["product"]["name"],
        "version": version,
        "representation_name": context["representation"]["name"],
    }
    parms = {
        key: value
        for key, value in parms.items()
        if node.evalParm(key) != value
    }
    node.setParms(parms)

    if ensure_expression_defaults:
        ensure_loader_expression_parm_defaults(node)

set_node_thumbnail(node, thumbnail)

Update node thumbnail to thumbnail

Source code in client/ayon_houdini/api/hda_utils.py
345
346
347
348
349
350
351
def set_node_thumbnail(node, thumbnail: str):
    """Update node thumbnail to thumbnail"""
    if thumbnail is None:
        lib.set_node_thumbnail(node, None)

    rect = compute_thumbnail_rect(node)
    lib.set_node_thumbnail(node, thumbnail, rect)

set_to_latest_version(node)

Callback on product name change

Refresh version and representation parameters value by setting their value to the latest version and representation of the selected product.

Parameters:

Name Type Description Default
node OpNode

The HDA node.

required
Source code in client/ayon_houdini/api/hda_utils.py
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
def set_to_latest_version(node):
    """Callback on product name change

    Refresh version and representation parameters value by setting
    their value to the latest version and representation of
    the selected product.

    Args:
        node (hou.OpNode): The HDA node.
    """

    versions = get_available_versions(node)
    if versions:
        node.parm("version").set(str(versions[0]))

    representations = get_available_representations(node)
    if representations:
        node.parm("representation_name").set(representations[0])
    else:
        node.parm("representation_name").set("")

setup_flag_changed_callback(node)

Register flag changed callback (for thumbnail brightness)

Source code in client/ayon_houdini/api/hda_utils.py
479
480
481
def setup_flag_changed_callback(node):
    """Register flag changed callback (for thumbnail brightness)"""
    node.addEventCallback((hou.nodeEventType.FlagChanged,), on_flag_changed)