Skip to content

Converter helpers

apply_alarm_flags(widget, obj)

Make the widget follow its channel's alarm severity only where the object's alarm flags say EDM does (edm_qt.EDM_ALARM_PROPS); an object without them never changes colour for alarms. A flag the table doesn't map for the class (a slider's bgAlarm, a bar's indicatorAlarm, a text's bgAlarm) is dropped with a warning.

Source code in pydmconverter/edm/converter_helpers.py
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def apply_alarm_flags(widget, obj: EDMObject) -> None:
    """Make the widget follow its channel's alarm severity only where the
    object's alarm flags say EDM does (edm_qt.EDM_ALARM_PROPS); an object
    without them never changes colour for alarms. A flag the table doesn't map
    for the class (a slider's bgAlarm, a bar's indicatorAlarm, a text's bgAlarm)
    is dropped with a warning.
    """
    if not isinstance(widget, Alarmable):
        return
    name = obj.name.lower()
    props = obj.properties
    flags = EDM_ALARM_PROPS.get(name, {})
    # Only a filled shape has a fill to colour: PyDM would fill an unfilled one,
    # and colour a polyline's arrowheads.
    filled = bool(props.get("fill")) and not isinstance(widget, PyDMDrawingLine)
    on = {qt_prop for flag, qt_prop in flags.items() if props.get(flag) and (flag != "fillAlarm" or filled)}
    if name in EDM_ALARM_BORDER_CLASSES and props.get("useAlarmBorder") and "alarmSensitiveContent" in on:
        on = {"alarmSensitiveBorder"}
    widget.alarm_sensitive_content = "alarmSensitiveContent" in on
    widget.alarm_sensitive_border = "alarmSensitiveBorder" in on
    # Against the table, not what is on: a fillAlarm without a fill loses nothing EDM draws.
    for flag in EDM_ALARM_FLAGS:
        if props.get(flag) and flag not in flags:
            logger.warning(f"{obj.name}: {flag} has no place in the .ui; static colours kept")

apply_channel_roles(widget, obj)

Bind the widget's channel to the PV channel_attr names, and warn about each of the object's other PVs, which a .ui has no place for: a PyDM widget reads and writes its one channel, with no readback and no colour rules (drawings aside, which the converter doesn't write yet).

Source code in pydmconverter/edm/converter_helpers.py
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
def apply_channel_roles(widget, obj: EDMObject) -> None:
    """Bind the widget's channel to the PV channel_attr names, and warn about
    each of the object's other PVs, which a .ui has no place for: a PyDM
    widget reads and writes its one channel, with no readback and no colour
    rules (drawings aside, which the converter doesn't write yet).
    """
    roles = channel_roles(obj.name.lower())
    props = obj.properties
    attr = channel_attr(obj)
    if attr is not None:
        widget.channel = props[attr]
        if attr == roles.alarm and isinstance(widget, PyDMLabel):
            # The label keeps its text and only takes the alarm PV's severity.
            widget.display_label_text = True

    readback = roles.readback_attr(props)
    if readback is not None:
        # A readback naming the channel's PV itself loses nothing.
        if not names_the_channel(props[readback], props[attr]):
            logger.warning(
                f"{obj.name}: {readback} {props[readback]} is a readback, which PyDM widgets lack; "
                f"the widget shows and writes {attr} {props[attr]}"
            )
    elif attr is not None and attr == roles.readback:
        logger.warning(f"{obj.name}: {attr} {props[attr]} is its only PV; PyDM writes it, which EDM never does")
    color = roles.color_attr(props)
    if color is not None and color != attr:
        logger.warning(f"{obj.name}: {color} {props[color]} picks rule colours, which the .ui doesn't carry")
    condition = props.get("nullCondition") or "nullEqCtl"
    if roles.null and props.get(roles.null) and condition != "disabled":
        logger.warning(
            f"{obj.name}: {roles.null} {props[roles.null]} switches the text to nullColor ({condition}), "
            "which the .ui doesn't carry"
        )
    for other in EDM_DATA_PV_ATTRS:
        if other not in (attr, readback) and props.get(other):
            logger.warning(f"{obj.name}: {other} {props[other]} has no place in the .ui; dropped")
    if obj.name.lower() in ("xygraphclass", "mzxygraphclass"):
        for tag, effect in XY_GRAPH_UNMAPPED_PVS.items():
            pvs = [pv for _, pv in block_items(props.get(tag)) if pv.strip()]
            if pvs:
                logger.warning(f"{obj.name}: {tag} {', '.join(pvs)} ({effect}) has no place in the .ui; dropped")

apply_widget_post_processing(widget, obj, pydm_widgets, scale, offset_x, offset_y, container_height, parent_pydm_group)

Apply widget-specific post-processing after attribute mapping.

Handles geometry transformation, polyline points, button variants, embedded display filenames, dimension padding, and minimum sizes.

Source code in pydmconverter/edm/converter_helpers.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def apply_widget_post_processing(
    widget, obj, pydm_widgets, scale, offset_x, offset_y, container_height, parent_pydm_group
):
    """
    Apply widget-specific post-processing after attribute mapping.

    Handles geometry transformation, polyline points, button variants,
    embedded display filenames, dimension padding, and minimum sizes.
    """
    # Tab bar population
    if obj.name.lower() == "activechoicebuttonclass" and isinstance(widget, QTabWidget):
        populate_tab_bar(obj, widget)

    # Polyline/polygon point calculation and geometry
    if obj.name.lower() == "activelineclass" and isinstance(widget, (PyDMDrawingPolyline, PyDMDrawingIrregularPolygon)):
        if "xPoints" in obj.properties and "yPoints" in obj.properties:
            x_points = obj.properties["xPoints"]
            y_points = obj.properties["yPoints"]
            try:
                abs_pts = [(int(float(x) * scale), int(float(y) * scale)) for x, y in zip(x_points, y_points)]
            except (TypeError, ValueError) as e:
                # A point that is not a number, e.g. a CVS conflict marker left in the
                # block: keep the header geometry, as the IR target does (ir_adapter._parse_line_points).
                logger.warning(f"{obj.name} at ({obj.x}, {obj.y}) has malformed points ({e}); using its x/y/w/h")
                _set_header_geometry(widget, obj, parent_pydm_group, container_height, scale, offset_x, offset_y)
                return
            pen = int(obj.properties.get("lineWidth", 1))

            arrow_size = 0
            if "arrows" in obj.properties and obj.properties["arrows"] in ("to", "from", "both"):
                arrow_size = int(15 * scale)

            startCoord = (obj.x, obj.y)
            geom, point_strings = geom_and_local_points(abs_pts, startCoord, pen, arrow_size)

            if not geom:
                logger.warning(f"Skipping {type(widget).__name__} with no valid points for {obj.name}")
                return

            widget.points = point_strings
            widget.penWidth = pen
            if widget.penColor is None:
                widget.penColor = (0, 0, 0, 255)

            if isinstance(widget, PyDMDrawingIrregularPolygon):
                if widget.brushColor is not None:
                    widget.brushFill = True
                    logger.info(f"IrregularPolygon has explicit brushColor: {widget.brushColor}")
                else:
                    widget.brushColor = (255, 255, 255, 255)
                    widget.brushFill = True
                    logger.info("Setting default white fill color for IrregularPolygon (no fillColor specified)")

            # PyDM draws the points offset by the pen (PyDMDrawing.get_bounds), so the widget
            # moves back by the pen to put them on EDM's points. A 0 width pen has no border
            # in PyDM and no offset.
            border = pen if pen > 0 else 0
            widget.x = int(geom["x"] + offset_x) - border
            widget.y = int(geom["y"] + offset_y) - border
            widget.width = int(geom["width"])
            widget.height = int(geom["height"])
    elif not (
        obj.name.lower() == "activelineclass" and isinstance(widget, (PyDMDrawingPolyline, PyDMDrawingIrregularPolygon))
    ):
        _set_header_geometry(widget, obj, parent_pydm_group, container_height, scale, offset_x, offset_y)

    # PushButton off/on handling. Labels that differ only in their padding
    # ("Cancel " / "Cancel") get no separate off button.
    if isinstance(widget, PyDMPushButton) and ("offLabel" in obj.properties and "onLabel" not in obj.properties):
        widget.text = obj.properties["offLabel"]
    elif isinstance(widget, PyDMPushButton) and (
        (
            (
                "offLabel" in obj.properties
                and str(obj.properties["offLabel"]).strip() != str(obj.properties["onLabel"]).strip()
            )
            or ("offColor" in obj.properties and obj.properties["offColor"] != obj.properties["onColor"])
        )
        and hasattr(widget, "channel")
        and widget.channel is not None
    ):
        off_button = create_off_button(widget)
        pydm_widgets.append(off_button)

    # Embedded display filename handling
    if isinstance(widget, PyDMEmbeddedDisplay) and obj.name.lower() == "activepipclass":
        if not is_menu_pip(obj):
            # EDM (pip.cc) opens a displayFileName entry only from a menu window.
            widget.filename, file_channel = pip_source_file(obj)
            if file_channel:
                widget.extra_rules.append(filename_rule(file_channel))
            logger.info(f"Set PyDMEmbeddedDisplay filename to: {widget.filename}")
        elif "displayFileName" in obj.properties and obj.properties["displayFileName"]:
            display_filenames = obj.properties["displayFileName"]
            filename_to_set = None
            if isinstance(display_filenames, list) and len(display_filenames) > 0:
                # shown_display_index is an EDM array index, not a list position.
                filename_to_set = dict(block_items(display_filenames)).get(shown_display_index(obj))
            elif isinstance(display_filenames, dict) and len(display_filenames) > 0:
                filename_to_set = display_filenames[0]
            elif isinstance(display_filenames, str):
                filename_to_set = display_filenames

            if isinstance(filename_to_set, str):
                # PyDMEmbeddedDisplay maps the EDM name to its .ui name when serialized.
                widget.filename = filename_to_set
                logger.info(f"Set PyDMEmbeddedDisplay filename to: {widget.filename}")
        else:
            # A menu window opens only its displayFileName entries (pip.cc), never its file.
            widget.filename = None

    # Related display that closes its parent
    if isinstance(widget, PyDMRelatedDisplayButton):
        # EDM (related_display.cc popupDisplay) opens the display in a new window and, for
        # an entry with closeAction set, then closes the parent (from inside an embedded
        # display, its top-level window). PyDM's nearest match is opening in place: with
        # openInNewWindow false the PyDM main window swaps to the new display and keeps the
        # parent in its back history. The property is per button, so every entry must close.
        files = [index for index, name in block_items(obj.properties.get("displayFileName")) if name.strip()]
        closing = closing_display_indices(obj.properties)
        if files and all(index in closing for index in files):
            widget.open_in_new_window = False
        elif closing:
            logger.info(
                f"Related display closes its parent for only some entries ({sorted(closing)} of {files}); "
                "opening all in a new window"
            )

    # Freeze button handling
    if obj.name.lower() == "activefreezebuttonclass":
        freeze_button = create_freeze_button(widget)
        pydm_widgets.append(freeze_button)

    # Multi-slider handling
    if obj.name.lower() == "mmvclass":
        widget.orientation = mmv_orientation(obj)
        generated_sliders = create_multi_sliders(widget, obj)
        pydm_widgets.extend(generated_sliders)

    # Drawing shape dimension padding. PyDM draws the points offset by the pen
    # (PyDMDrawing.get_bounds; the widget starts a pen before the first point) and the
    # stroke reaches pen/2 past the last, so each axis needs span + 1.5 * pen;
    # geom_and_local_points sized the widget span + pen, so add a pen.
    # Under alarm the pen keeps its width (Drawable.style_sheet), so no more is needed.
    if isinstance(widget, (PyDMDrawingLine, PyDMDrawingPolyline, PyDMDrawingIrregularPolygon)):
        pad = widget.penWidth or 1
        min_dim = max(pad * 2, 3)
        widget.width = max(int(widget.width) + pad, min_dim)
        widget.height = max(int(widget.height) + pad, min_dim)

    # Rectangle, circle and arc outlines. EDM centres the pen on the object's rect
    # (XDrawRectangle, XDrawArc); PyDM insets the shape by the pen width
    # (PyDMDrawing.get_bounds), so the widget grows by the pen on every side to put the
    # shape back on EDM's rect. The width is always written: PyDM's construction-time
    # polish otherwise leaves the 2 px of its alarm-border stylesheet rule.
    if obj.name.lower() in EDM_CLOSED_DRAWINGS:
        pen = edm_line_width(obj)
        widget.penWidth = pen
        # With no pen style written PyDM draws no outline and insets nothing.
        if widget.penColor is not None or widget.penStyle is not None:
            x, y, width, height = _compute_geometry(obj, parent_pydm_group, container_height, scale, offset_x, offset_y)
            widget.x, widget.y = int(x) - pen, int(y) - pen
            widget.width, widget.height = int(width) + 2 * pen, int(height) + 2 * pen

    # Text widget padding — Qt renders fonts slightly wider than EDM,
    # so add a small width buffer to prevent text clipping and button text wrapping.
    if isinstance(widget, (PyDMLabel, PyDMLineEdit, PyDMPushButton, PyDMRelatedDisplayButton, PyDMShellCommand)):
        text_pad = max(int(widget.width * 0.05), 4)
        widget.width = widget.width + text_pad
    if isinstance(widget, (PyDMLabel, PyDMLineEdit)):
        widget.width = max(widget.width, 20)
        widget.height = max(widget.height, 14)

    # Auto-size
    if obj.properties.get("autoSize", False) and hasattr(widget, "autoSize"):
        widget.autoSize = True

    if obj.properties.get("showScale") and isinstance(widget, PyDMAnalogIndicator):
        widget.showTicks = True
        widget.showLimits = True
        widget.showUnits = True

    # EDM meter labels become the analog indicator title. pvName and pvLabel
    # types resolve from the PV at runtime, so use the PV name for those.
    if isinstance(widget, PyDMAnalogIndicator):
        label_type = obj.properties.get("labelType", "literal")
        if label_type == "literal":
            title = obj.properties.get("label")
        else:
            title = obj.properties.get("readPv")
        if title:
            widget.title = title

channel_attr(obj)

The tag of the PV the object's widget binds as its channel, or None.

That is the class's data PV (edm_qt.EDM_CHANNEL_ROLES). PyDM colours a widget for alarms only from its own channel, so a class that shows no PV (drawings, static text) binds its alarmPv instead.

Source code in pydmconverter/edm/converter_helpers.py
591
592
593
594
595
596
597
598
599
600
601
602
def channel_attr(obj: EDMObject) -> Optional[str]:
    """The tag of the PV the object's widget binds as its channel, or None.

    That is the class's data PV (edm_qt.EDM_CHANNEL_ROLES). PyDM colours a
    widget for alarms only from its own channel, so a class that shows no PV
    (drawings, static text) binds its alarmPv instead.
    """
    roles = channel_roles(obj.name.lower())
    attr = roles.data_attr(obj.properties)
    if attr is None and roles.alarm and obj.properties.get(roles.alarm):
        attr = roles.alarm
    return attr

convert_attribute_value(edm_attr, value, widget, obj, color_list_dict)

Convert a single EDM attribute value to its PyDM equivalent.

Returns the converted value, or None to signal the attribute should be skipped.

Source code in pydmconverter/edm/converter_helpers.py
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def convert_attribute_value(edm_attr, value, widget, obj, color_list_dict):
    """
    Convert a single EDM attribute value to its PyDM equivalent.

    Returns the converted value, or None to signal the attribute should be skipped.
    """
    if obj.name.lower() == "activelineclass" and edm_attr in ["xPoints", "yPoints", "numPoints"]:
        return None

    if edm_attr == "font":
        value = parse_font_string(value)
    elif edm_attr in ("macro", "symbols"):
        if obj.name.lower() == "activepipclass" and not is_menu_pip(obj):
            # EDM (pip.cc) opens a file or stringPV window with the parent's macros
            # only: symbols belong to the menu entries (openEmbeddedByIndex), so a
            # window left with them by a switch from "menu" ignores them.
            return None
        if isinstance(value, list):
            if isinstance(widget, PyDMEmbeddedDisplay) and is_menu_pip(obj) and value:
                # A menu window pairs symbols[i] with displayFileName[i] by EDM array
                # index (a file may skip indices or start at 1): take the shown one's,
                # even when it is the only entry (symbols { 1 "ID=$(ID)" } is display 1's).
                symbols = dict(block_items(value))
                index = shown_display_index(obj)
                value = parse_edm_macros(symbols[index]) if index in symbols else {}
                logger.info(f"Converted shown display's macros to dict: {value}")
            elif isinstance(widget, PyDMEmbeddedDisplay) and len(value) == 1:
                macro_dict = parse_edm_macros(value[0])
                value = macro_dict
                logger.info(f"Converted single macro to dict: {value}")
            elif isinstance(widget, PyDMRelatedDisplayButton) and obj.properties.get("displayFileName"):
                # EDM (related_display.cc) pairs symbols[i] with displayFileName[i] by array
                # index, and a file may skip indices: one macros entry per filename, in
                # filename order, "{}" for a display with no symbols entry. PyDM's macros
                # is a QStringList paired with filenames by position, so keep it a list.
                symbols = dict(block_items(value))
                parsed_macros = [
                    json.dumps(parse_edm_macros(symbols.get(index, "")))
                    for index, _ in block_items(obj.properties["displayFileName"])
                ]
                value = parsed_macros if parsed_macros else None
                logger.info(f"Converted related display macros to: {value}")
            else:
                parsed_macros = []
                for macro_str in value:
                    macro_dict = parse_edm_macros(macro_str)
                    parsed_macros.append(json.dumps(macro_dict))
                value = "\n".join(parsed_macros) if parsed_macros else None
                logger.info(f"Converted macro list to: {value}")
        elif isinstance(value, str):
            macro_dict = parse_edm_macros(value)
            if isinstance(widget, PyDMEmbeddedDisplay):
                value = macro_dict
            else:
                value = json.dumps(macro_dict) if macro_dict else None
            logger.info(f"Converted macro string to: {value}")
    elif edm_attr == "fillColor":
        original_value = value
        color_tuple = convert_color_property_to_qcolor(value, color_data=color_list_dict)
        logger.info(f"Color conversion: {original_value} -> {color_tuple}")
        if color_tuple:
            value = color_tuple
            logger.info(f"Setting fillColor/brushColor to: {value}")
        else:
            logger.warning(f"Could not convert color {value}, skipping")
            return None
    elif edm_attr == "value":
        if obj.name.lower() not in EDM_TEXT_VALUE_CLASSES:
            return None
        value = get_string_value(value)
    elif edm_attr in COLOR_ATTRIBUTES:
        value = convert_color_property_to_qcolor(value, color_data=color_list_dict)
    elif edm_attr == "plotColor":
        # Trace i is yPv[i] / xPv[i] / plotColor[i] by EDM index; None marks an omitted color.
        value = [
            convert_color_property_to_qcolor(color, color_data=color_list_dict) if color else None
            for color in block_list(value)
        ]
    elif edm_attr in ("xPv", "yPv") and isinstance(value, list):
        value = block_list(value)
    elif edm_attr in ("menuLabel", "commandLabel"):
        # \x18 (CAN character) is a placeholder some files hold for "no label".
        entries = None
        if isinstance(widget, PyDMRelatedDisplayButton):
            entries = obj.properties.get("displayFileName")
        elif isinstance(widget, PyDMShellCommand):
            entries = obj.properties.get("command")
        if entries:
            # EDM (related_display.cc, shell_cmd.cc) pairs label[i] with displayFileName[i]
            # or command[i] by array index, and a file may skip indices; PyDM pairs titles
            # with filenames/commands by position. One title per entry, in entry order: a
            # missing label is EDM's empty one (a blank menu item), and with no label at
            # all PyDM's default titles (the filenames/commands) stand.
            labels = {index: label for index, label in block_items(value) if label != "\x18"}
            value = [labels.get(index, "") for index, _ in block_items(entries)]
            if not any(value):
                return None
        elif isinstance(value, list):
            value = [v for v in value if v != "\x18"]
            if not value:
                return None
        elif value == "\x18":
            return None

    return value

convert_edm_to_pydm_widgets(parser, site=None, color_list_file=None, display_roots=None)

Converts an EDMFileParser object into a collection of PyDM widget instances.

Parameters

parser : EDMFileParser The EDMFileParser instance containing parsed EDM objects and groups. color_list_file : str, optional Explicit path to an EDM colors.list palette used to resolve "index N" colors. Falls back to EDMCOLORFILE, $EDMFILES/colors.list, then /etc/edm/colors.list when omitted. display_roots : str | Sequence[str], optional Absolute directories whose display names become root-relative (see pydmconverter.edm.display_roots). Falls back to PYDMCONVERTER_DISPLAY_ROOTS when omitted.

Returns

Tuple[List, set] A tuple of (pydm_widgets, used_classes). The screen's menu muxes and the loc:// declarations their menu screen shares with the .ui are left on the parser (menu_mux_buttons, menu_loc_declarations) for convert() to write once the .ui is written.

Source code in pydmconverter/edm/converter_helpers.py
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
def convert_edm_to_pydm_widgets(
    parser: EDMFileParser, site=None, color_list_file: str | None = None, display_roots: SearchPaths = None
):
    """
    Converts an EDMFileParser object into a collection of PyDM widget instances.

    Parameters
    ----------
    parser : EDMFileParser
        The EDMFileParser instance containing parsed EDM objects and groups.
    color_list_file : str, optional
        Explicit path to an EDM ``colors.list`` palette used to resolve "index N"
        colors. Falls back to ``EDMCOLORFILE``, ``$EDMFILES/colors.list``, then
        ``/etc/edm/colors.list`` when omitted.
    display_roots : str | Sequence[str], optional
        Absolute directories whose display names become root-relative (see
        pydmconverter.edm.display_roots). Falls back to ``PYDMCONVERTER_DISPLAY_ROOTS``
        when omitted.

    Returns
    -------
    Tuple[List, set]
        A tuple of (pydm_widgets, used_classes). The screen's menu muxes and the
        loc:// declarations their menu screen shares with the .ui are left on the
        parser (``menu_mux_buttons``, ``menu_loc_declarations``) for convert() to
        write once the .ui is written.
    """
    from pydmconverter.sites import get_skip_widgets

    skip_widgets = get_skip_widgets(site)
    # First, so the tab pages and stacked displays built from a menu window copy mapped names.
    map_display_roots(parser.ui, resolve_display_roots(display_roots))

    used_classes = set()
    color_list_filepath = search_color_list(color_list_file)
    color_list_dict = parse_colors_list(color_list_filepath)

    # Pre-process: choice buttons driving menu embedded windows become tabs or switched displays
    pair_menu_pips(parser.ui, color_list_dict, skip_widgets=skip_widgets)

    # Pre-process: remove overlapping text labels on related display buttons
    text_objects = find_objects(parser.ui, "activextextclass")
    for text_object in text_objects:
        if should_delete_overlapping(parser.ui, text_object, "relateddisplayclass"):
            delete_object_in_group(parser.ui, text_object)

    # Traverse and convert
    pydm_widgets, menu_mux_buttons = traverse_group(
        parser.ui,
        color_list_dict,
        used_classes,
        skip_widgets=skip_widgets,
        container_height=parser.ui.height,
        central_widget=parser.ui,
    )

    pydm_widgets = handle_button_polygon_overlaps(pydm_widgets)

    parser.menu_mux_buttons = menu_mux_buttons
    parser.menu_loc_declarations = loc_declarations(parser.ui) if menu_mux_buttons else {}
    return pydm_widgets, used_classes

convert_pointsize(pixel_size, dpi=96)

Convert the edm pizelsize to pydm pointsize (multiply by 0.75)

Source code in pydmconverter/edm/converter_helpers.py
2113
2114
2115
2116
2117
2118
def convert_pointsize(pixel_size, dpi: float = 96):
    """
    Convert the edm pizelsize to pydm pointsize (multiply by 0.75)
    """
    point_size = pixel_size * 72 / dpi
    return math.floor(point_size)

create_button_variant(widget, suffix, variant_type, attr_mappings, original_mappings=None)

Clone a PyDMPushButton into a variant (e.g. "off" or "freeze") with remapped attributes.

Parameters

widget : PyDMPushButton The original button to clone. suffix : str Name suffix for the variant (e.g. "_off", "_freeze"). variant_type : str Type label for the variant flag (e.g. "off", "freeze"). attr_mappings : list of (src, dst) tuples Copies widget.src → variant.dst for each pair. original_mappings : list of (src, dst) tuples, optional Copies widget.src → widget.dst on the original widget for each pair.

Source code in pydmconverter/edm/converter_helpers.py
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
def create_button_variant(
    widget: PyDMPushButton, suffix: str, variant_type: str, attr_mappings: list, original_mappings: list = None
):
    """
    Clone a PyDMPushButton into a variant (e.g. "off" or "freeze") with remapped attributes.

    Parameters
    ----------
    widget : PyDMPushButton
        The original button to clone.
    suffix : str
        Name suffix for the variant (e.g. "_off", "_freeze").
    variant_type : str
        Type label for the variant flag (e.g. "off", "freeze").
    attr_mappings : list of (src, dst) tuples
        Copies widget.src → variant.dst for each pair.
    original_mappings : list of (src, dst) tuples, optional
        Copies widget.src → widget.dst on the original widget for each pair.
    """
    variant = copy.deepcopy(widget)
    variant.name = widget.name + suffix
    for src, dst in attr_mappings:
        if hasattr(widget, src):
            setattr(variant, dst, getattr(widget, src))
    setattr(variant, f"is_{variant_type}_button", True)
    setattr(widget, f"is_{variant_type}_button", False)
    if original_mappings:
        for src, dst in original_mappings:
            if hasattr(widget, src):
                setattr(widget, dst, getattr(widget, src))
    logger.info(f"Created {variant_type}-button: {variant.name} based on {widget.name}")
    return variant

create_freeze_button(widget)

Create a 'freeze' variant of an activefreezebuttonclass button.

Source code in pydmconverter/edm/converter_helpers.py
1375
1376
1377
1378
1379
1380
1381
1382
def create_freeze_button(widget: PyDMPushButton):
    """Create a 'freeze' variant of an activefreezebuttonclass button."""
    return create_button_variant(
        widget,
        "_freeze",
        "freeze",
        attr_mappings=[("frozenLabel", "text"), ("frozen_background_color", "background_color")],
    )

create_multi_sliders(widget, object)

Given a ActiveSlider converted from a mmvclass, create stacked sliders to show each slider indicator. Modifies the size and channel of the current slider. The sliders share the mover's thickness, so each keeps EDM's full track length: horizontal ones stack top to bottom, vertical ones sit side by side.

Source code in pydmconverter/edm/converter_helpers.py
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
def create_multi_sliders(widget: PyDMSlider, object: EDMObject):
    """
    Given a ActiveSlider converted from a mmvclass, create stacked sliders to show each slider indicator.
    Modifies the size and channel of the current slider. The sliders share the
    mover's thickness, so each keeps EDM's full track length: horizontal ones
    stack top to bottom, vertical ones sit side by side.
    """
    vertical = widget.orientation == "vertical"
    i = 1
    prevColor = None
    ctrl_attributes = []
    extra_sliders = []
    while f"ctrl{i}Pv" in object.properties:
        if f"ctrl{i}Color" in object.properties:
            currColor = object.properties[f"ctrl{i}Color"]
        else:
            currColor = prevColor
        ctrl_attributes.append((object.properties[f"ctrl{i}Pv"], currColor))
        prevColor = currColor
        i += 1
    if ctrl_attributes:
        if vertical:
            widget.width = widget.width // len(ctrl_attributes)
        else:
            widget.height = widget.height // len(ctrl_attributes)
        widget.channel = ctrl_attributes[0][0]
        widget.indicatorColor = ctrl_attributes[0][1]
        for j in range(1, len(ctrl_attributes)):
            curr_slider = copy.deepcopy(widget)
            curr_slider.name = widget.name + f"_{j}"
            if vertical:
                curr_slider.x = curr_slider.x + curr_slider.width * j
            else:
                curr_slider.y = curr_slider.y + curr_slider.height * j
            curr_slider.channel = ctrl_attributes[j][0]
            curr_slider.indicatorColor = ctrl_attributes[j][1]
            logger.info(f"Created multi-slider: {curr_slider.name} based on {widget.name}")
            extra_sliders.append(curr_slider)
    return extra_sliders

create_off_button(widget)

Create an 'off' variant of a push button with distinct off/on states.

Source code in pydmconverter/edm/converter_helpers.py
1364
1365
1366
1367
1368
1369
1370
1371
1372
def create_off_button(widget: PyDMPushButton):
    """Create an 'off' variant of a push button with distinct off/on states."""
    return create_button_variant(
        widget,
        "_off",
        "off",
        attr_mappings=[("off_color", "on_color"), ("off_label", "on_label"), ("off_label", "text")],
        original_mappings=[("on_label", "text")],
    )

edm_line_width(obj)

The width EDM draws a rectangle, circle or arc outline with: its lineWidth, 1 by default (rectangle_obj.cc, circle_obj.cc, arc_obj.cc). Width 0 is X11's thinnest line, which is also one pixel wide.

Source code in pydmconverter/edm/converter_helpers.py
375
376
377
378
379
def edm_line_width(obj: EDMObject) -> int:
    """The width EDM draws a rectangle, circle or arc outline with: its lineWidth, 1 by
    default (rectangle_obj.cc, circle_obj.cc, arc_obj.cc). Width 0 is X11's thinnest
    line, which is also one pixel wide."""
    return max(1, int(obj.properties.get("lineWidth", 1)))

find_objects(group, obj_name)

Recursively search through an EDMGroup and its nested groups to find all instances of EDMObjects that match a specified name.

Parameters

group : EDMGroup The EDMGroup instance within which to search for objects. obj_name : str The name of the object to search for (case insensitive)

Returns

List[EDMObject] A list of EDMObject instances that match the specified name. If no matches are found, an empty list is returned.

Source code in pydmconverter/edm/converter_helpers.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
def find_objects(group: EDMGroup, obj_name: str) -> List[EDMObject]:
    """
    Recursively search through an EDMGroup and its nested groups to find all
    instances of EDMObjects that match a specified name.

    Parameters
    ----------
    group : EDMGroup
        The EDMGroup instance within which to search for objects.
    obj_name : str
        The name of the object to search for (case insensitive)

    Returns
    -------
    List[EDMObject]
        A list of EDMObject instances that match the specified name. If no
        matches are found, an empty list is returned.
    """
    objects = []
    for obj in group.objects:
        if isinstance(obj, EDMGroup):
            objects += find_objects(obj, obj_name)
        elif obj.name.lower() == obj_name.lower():
            objects.append(obj)
    return objects

get_arc_widget_type(obj)

Determine if an activearcclass should be PyDMDrawingPie or PyDMDrawingArc.

Returns PyDMDrawingPie if the arc has fill enabled. Otherwise returns PyDMDrawingArc.

Parameters

obj : EDMObject The EDM object to analyze

Returns

type Either PyDMDrawingPie or PyDMDrawingArc

Source code in pydmconverter/edm/converter_helpers.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def get_arc_widget_type(obj: EDMObject) -> type:
    """
    Determine if an activearcclass should be PyDMDrawingPie or PyDMDrawingArc.

    Returns PyDMDrawingPie if the arc has fill enabled.
    Otherwise returns PyDMDrawingArc.

    Parameters
    ----------
    obj : EDMObject
        The EDM object to analyze

    Returns
    -------
    type
        Either PyDMDrawingPie or PyDMDrawingArc
    """
    has_fill, has_fill_color = _has_fill_properties(obj)

    if has_fill or has_fill_color:
        logger.info("Converting filled arc to PyDMDrawingPie")
        return PyDMDrawingPie
    else:
        return PyDMDrawingArc

get_polyline_widget_type(obj)

Determine if an activelineclass should be PyDMDrawingPolyline or PyDMDrawingIrregularPolygon.

Returns PyDMDrawingIrregularPolygon if the polyline is: - Closed (first point == last point OR closePolygon is set) AND - Has fill color

Otherwise returns PyDMDrawingPolyline.

Parameters

obj : EDMObject The EDM object to analyze

Returns

type Either PyDMDrawingIrregularPolygon or PyDMDrawingPolyline

Source code in pydmconverter/edm/converter_helpers.py
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
def get_polyline_widget_type(obj: EDMObject) -> type:
    """
    Determine if an activelineclass should be PyDMDrawingPolyline or PyDMDrawingIrregularPolygon.

    Returns PyDMDrawingIrregularPolygon if the polyline is:
    - Closed (first point == last point OR closePolygon is set) AND
    - Has fill color

    Otherwise returns PyDMDrawingPolyline.

    Parameters
    ----------
    obj : EDMObject
        The EDM object to analyze

    Returns
    -------
    type
        Either PyDMDrawingIrregularPolygon or PyDMDrawingPolyline
    """
    has_fill, has_fill_color = _has_fill_properties(obj)
    is_closed = obj.properties.get("closePolygon") is True

    if not is_closed and "xPoints" in obj.properties and "yPoints" in obj.properties:
        x_pts = obj.properties["xPoints"]
        y_pts = obj.properties["yPoints"]
        if len(x_pts) > 1 and len(y_pts) > 1:
            is_closed = x_pts[0] == x_pts[-1] and y_pts[0] == y_pts[-1]

    if (has_fill or has_fill_color) and is_closed:
        logger.info("Converting closed filled polyline to PyDMDrawingIrregularPolygon")
        return PyDMDrawingIrregularPolygon
    else:
        return PyDMDrawingPolyline

get_string_value(value)

Takes in a value string and joins each element into a string separated by a new line

Source code in pydmconverter/edm/converter_helpers.py
2079
2080
2081
2082
2083
def get_string_value(value: list) -> str:
    """
    Takes in a value string and joins each element into a string separated by a new line
    """
    return "\n".join(value)

handle_button_polygon_overlaps(pydm_widgets)

Detect when PyDMRelatedDisplayButton overlaps with PyDMDrawingIrregularPolygon. Set the button's flat property to True to make it transparent, and ensure the button is placed after the polygon in the widget list (on top in z-order).

Parameters

pydm_widgets : List List of PyDM widget instances

Returns

List Updated list of PyDM widgets with proper ordering and flat property set

Source code in pydmconverter/edm/converter_helpers.py
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
def handle_button_polygon_overlaps(pydm_widgets):
    """
    Detect when PyDMRelatedDisplayButton overlaps with PyDMDrawingIrregularPolygon.
    Set the button's flat property to True to make it transparent, and ensure
    the button is placed after the polygon in the widget list (on top in z-order).

    Parameters
    ----------
    pydm_widgets : List
        List of PyDM widget instances

    Returns
    -------
    List
        Updated list of PyDM widgets with proper ordering and flat property set
    """
    from pydmconverter.widgets import PyDMRelatedDisplayButton, PyDMDrawingIrregularPolygon

    buttons = [(i, w) for i, w in enumerate(pydm_widgets) if isinstance(w, PyDMRelatedDisplayButton)]
    polygons = [(i, w) for i, w in enumerate(pydm_widgets) if isinstance(w, PyDMDrawingIrregularPolygon)]

    buttons_to_move = []

    for btn_idx, button in buttons:
        for poly_idx, polygon in polygons:
            if widgets_overlap(button, polygon):
                logger.info(f"Detected overlap: {button.name} overlaps with {polygon.name}")
                button.flat = True

                if btn_idx < poly_idx:
                    buttons_to_move.append((btn_idx, button))
                    logger.info(f"Button {button.name} will be moved after polygon {polygon.name}")
                break

    if buttons_to_move:
        buttons_to_move.sort(key=lambda x: x[0], reverse=True)

        for btn_idx, button in buttons_to_move:
            pydm_widgets.pop(btn_idx)

        for _, button in reversed(buttons_to_move):
            pydm_widgets.append(button)

    return pydm_widgets

is_menu_pip(obj)

An embedded window whose filePv picks among its displayFileName entries.

Source code in pydmconverter/edm/converter_helpers.py
1712
1713
1714
1715
1716
1717
def is_menu_pip(obj) -> bool:
    """An embedded window whose filePv picks among its displayFileName entries."""
    if not isinstance(obj, EDMObject):
        # Groups carry properties but no class name, so they are never a window.
        return False
    return obj.name.lower() == "activepipclass" and str(obj.properties.get("displaySource", "")).lower() == "menu"

loc_declarations(root)

Map each loc:// variable the converted .ui configures, by its bare address (loc://name), to the address that configures it. Menu muxes are left out: they become the separate .py screen. When several widgets configure a variable differently the richest wins, as in pair_menu_pips: most enum strings, then the first in the file.

Source code in pydmconverter/edm/converter_helpers.py
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
def loc_declarations(root: EDMGroup) -> dict:
    """Map each loc:// variable the converted .ui configures, by its bare
    address (loc://name), to the address that configures it. Menu muxes are
    left out: they become the separate .py screen. When several widgets
    configure a variable differently the richest wins, as in pair_menu_pips:
    most enum strings, then the first in the file."""
    declarations = {}
    for obj, _, _ in _walk_objects(root):
        if isinstance(obj, EDMObject) and obj.name.lower() == "menumuxclass":
            continue
        for value in obj.properties.values():
            for item in _as_list(value):
                if isinstance(item, str) and item.startswith("loc://") and "?" in item:
                    declarations.setdefault(item.split("?", 1)[0], []).append(item)
    return {bare: max(urls, key=lambda url: len(_loc_enum_strings(url))) for bare, urls in declarations.items()}

mmv_orientation(obj)

A multi-mover's direction, "horizontal" or "vertical".

EDM reads it from the numeric orientation (mmover.cc createFromFile). orientStr is the editor's name for the same choice, used here only when orientation is missing. None leaves the slider horizontal, Qt's default.

Source code in pydmconverter/edm/converter_helpers.py
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
def mmv_orientation(obj: EDMObject) -> Optional[str]:
    """A multi-mover's direction, "horizontal" or "vertical".

    EDM reads it from the numeric orientation (mmover.cc createFromFile).
    orientStr is the editor's name for the same choice, used here only when
    orientation is missing. None leaves the slider horizontal, Qt's default.
    """
    orientation = MMV_ORIENTATIONS.get(str(obj.properties.get("orientation", "")).strip())
    if orientation is not None:
        return orientation
    orient_str = str(obj.properties.get("orientStr", "")).lower()
    if orient_str.startswith("horiz"):
        return "horizontal"
    if orient_str.startswith("vert"):
        return "vertical"
    return None

object_vis_range(name, properties)

The (visMin, visMax) an EDM object or group shows between, read with EDM's atof() as the IR reads them (parser_helpers.vis_range).

None when a limit can't be evaluated here, such as one that starts with a macro: the caller drops the visibility rule, so the widget always shows, as in the IR, and a warning says why. PyDM would substitute the macro when it loads the screen, but only as text in the rule expression, which has no atof(): a limit that names a PV would not parse, and the widget would stay hidden.

Source code in pydmconverter/edm/converter_helpers.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def object_vis_range(name: str, properties: dict) -> Optional[Tuple[float, float]]:
    """The (visMin, visMax) an EDM object or group shows between, read with
    EDM's atof() as the IR reads them (parser_helpers.vis_range).

    None when a limit can't be evaluated here, such as one that starts with a
    macro: the caller drops the visibility rule, so the widget always shows, as
    in the IR, and a warning says why. PyDM would substitute the macro when it
    loads the screen, but only as text in the rule expression, which has no
    atof(): a limit that names a PV would not parse, and the widget would stay
    hidden.
    """
    warnings: List[str] = []
    limits = vis_range(properties, warnings)
    for warning in warnings:
        logger.warning(f"{name}: {warning}")
    return limits

pair_menu_pips(root, color_list_dict, skip_widgets=None)

Convert each menu embedded window that a choice button or a menu mux drives.

In EDM the two are separate widgets sharing a LOC\ variable: the choice button writes it (its states are the variable's enum strings) and the window shows displayFileName[value]. When the button sits on top of the window and nothing else uses the variable, the pair becomes one QTabWidget: the choice button carries the pages and the window is removed. Otherwise the button stays a PyDMEnumButton and the window becomes one embedded display per file, shown only at its index, so EDM's layout and every other user of the variable keep working.

A menu mux whose controlPv names the variable writes it too: the generated menu mux screen writes the chosen item's index there. The menu becomes part of that separate .py rather than a widget in the .ui, so it is never a tab bar, and its window always becomes the switched displays. So does a window whose menu buttons write the variable (a combo box of its enum strings), or whose message buttons write display indices to it (_index_writers).

A window whose filePv is a real PV switches on the PV's value the same way: it becomes the switched displays, all hidden until the PV's first value, as EDM opens nothing until then (pip.cc).

skip_widgets is the site's set of EDM classes to drop; pairing rewrites both widgets together, so a site dropping either one leaves the tree untouched.

Source code in pydmconverter/edm/converter_helpers.py
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
def pair_menu_pips(root: EDMGroup, color_list_dict, skip_widgets: set = None) -> None:
    """
    Convert each menu embedded window that a choice button or a menu mux drives.

    In EDM the two are separate widgets sharing a LOC\\ variable: the choice
    button writes it (its states are the variable's enum strings) and the
    window shows displayFileName[value]. When the button sits on top of the
    window and nothing else uses the variable, the pair becomes one QTabWidget:
    the choice button carries the pages and the window is removed. Otherwise
    the button stays a PyDMEnumButton and the window becomes one embedded
    display per file, shown only at its index, so EDM's layout and every other
    user of the variable keep working.

    A menu mux whose controlPv names the variable writes it too: the generated
    menu mux screen writes the chosen item's index there. The menu becomes part
    of that separate .py rather than a widget in the .ui, so it is never a tab
    bar, and its window always becomes the switched displays. So does a window
    whose menu buttons write the variable (a combo box of its enum strings), or
    whose message buttons write display indices to it (_index_writers).

    A window whose filePv is a real PV switches on the PV's value the same way:
    it becomes the switched displays, all hidden until the PV's first value, as
    EDM opens nothing until then (pip.cc).

    skip_widgets is the site's set of EDM classes to drop; pairing rewrites both
    widgets together, so a site dropping either one leaves the tree untouched.
    """
    if skip_widgets and {"activechoicebuttonclass", "activepipclass"} & skip_widgets:
        logger.info("Skipping menu embedded window pairing (site rule)")
        return

    # A site dropping menu muxes or buttons leaves their variables unwritten.
    writes_menus = not skip_widgets or "menumuxclass" not in skip_widgets
    writes_menu_buttons = not skip_widgets or "activemenubuttonclass" not in skip_widgets
    writes_buttons = not skip_widgets or "activemessagebuttonclass" not in skip_widgets

    objects = list(_walk_objects(root))
    # objects holds a reference to every walked object, so keying by id is safe.
    loc_names = {id(obj): _loc_names(obj) for obj, _, _ in objects}
    for pip, parent, hidden in objects:
        if not is_menu_pip(pip):
            continue
        file_pv = pip.properties.get("filePv")
        match = LOC_NAME_PATTERN.search(file_pv) if isinstance(file_pv, str) else None
        # (EDM index, file): the variable's value v shows displayFileName[v], and a
        # file may skip indices or start at 1.
        files = block_items(pip.properties.get("displayFileName"))
        if not files:
            continue
        if not match:
            if _names_a_pv(file_pv):
                _stack_pip_displays(pip, parent, file_pv.strip(), files, None)
            continue
        name = match.group(1)
        users = [(obj, group) for obj, group, _ in objects if obj is not pip and name in loc_names[id(obj)]]
        choices = [
            (obj, group)
            for obj, group in users
            if isinstance(obj, EDMObject) and obj.name.lower() == "activechoicebuttonclass"
        ]
        menus = [obj for obj, _ in users if _menu_writes(obj, name)] if writes_menus else []
        menu_buttons = [obj for obj, _ in users if _menu_button_writes(obj, name)] if writes_menu_buttons else []
        writers = _index_writers(users, name, [index for index, _ in files]) if writes_buttons else []
        if not choices and not menus and not menu_buttons and not writers:
            continue

        # The richest reference defines the variable: most enum strings, then any config at all.
        references = [file_pv] + [
            value
            for obj, _ in users
            for value in obj.properties.values()
            if isinstance(value, str) and (value == f"loc://{name}" or value.startswith(f"loc://{name}?"))
        ]
        definition = max(references, key=lambda url: (len(_loc_enum_strings(url)), "?" in url))

        if "?" not in definition and menus:
            # Nothing configures the variable, so the first menu declares it when
            # the screen runs: an int starting at the menu's initialState
            # (MenuMuxScreen.control_address). Declare it so here, so the
            # displays start where the variable does.
            start = initial_state(menus[0])
            if start is None:
                logger.info(f"loc://{name} starts at a macro's value; its first display starts visible")
            else:
                definition = f"loc://{name}?type=int&init={start}"

        if _loc_init(definition) == -1:
            # A window whose variable starts at -1 writes 0 on its first value
            # rather than popping its menu up (pip.cc), so it opens on entry 0.
            definition = definition.replace("init=-1", "init=0")

        if choices and len(users) == 1 and len(files) > 1 and _fits_tab_bar(pip, parent, hidden, *choices[0]):
            _absorb_pip_into_tabs(pip, parent, choices[0][0], files, definition, color_list_dict)
        else:
            start = _starting_index(_loc_init(definition), [index for index, _ in files])
            _stack_pip_displays(pip, parent, f"loc://{name}", files, start)
            _hand_over_definition(name, definition, users, menu_buttons + writers)

parse_font_string(font_str)

Parse an EDM font string like 'helvetica-bold-r-12.0' into a dictionary for a PyDM widget. This is just an example parser—adjust as needed.

Source code in pydmconverter/edm/converter_helpers.py
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
def parse_font_string(font_str: str) -> dict:
    """
    Parse an EDM font string like 'helvetica-bold-r-12.0'
    into a dictionary for a PyDM widget.
    This is just an example parser—adjust as needed.
    """
    if not font_str:
        font_str = "helvetica-medium-r-12.0"
    parts = font_str.split("-")
    family = parts[0].capitalize()
    bold = "bold" in parts[1].lower()
    italic = "i" in parts[2].lower() or "o" in parts[2].lower()
    size_str = parts[-1]
    # pointsize = convert_pointsize(float(size_str))
    # NOTE: This line is commented because of how I observed fastx displays pointsize. In browser mode, the conversion from pixelsize to pointsize is 0.75. In desktop mode, the conversion is ~0.51
    # TODO: Find which version is accurate to how pydm is used and use that function
    pointsize = convert_pointsize(float(size_str))

    return {
        "family": family,
        "pointsize": pointsize,
        "bold": bold,
        "italic": italic,
        "weight": 50,
    }

pip_source_file(obj)

The file a non-menu embedded window opens (EDM pip.cc) and the channel whose value names it, each None for none.

A "file" window opens its file attribute and shows nothing when that is blank. A "stringPV" window (the default displaySource) reads its filePv as a string (pip_readUpdate) and opens the file the value names, again on every non-blank change. The channel drives the display's Filename rule; a loc:// string variable's initial value is also the file it opens with.

Source code in pydmconverter/edm/converter_helpers.py
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
def pip_source_file(obj: EDMObject) -> Tuple[Optional[str], Optional[str]]:
    """The file a non-menu embedded window opens (EDM pip.cc) and the channel
    whose value names it, each None for none.

    A "file" window opens its file attribute and shows nothing when that is
    blank. A "stringPV" window (the default displaySource) reads its filePv as
    a string (pip_readUpdate) and opens the file the value names, again on
    every non-blank change. The channel drives the display's Filename rule; a
    loc:// string variable's initial value is also the file it opens with.
    """
    if str(obj.properties.get("displaySource", "")).lower() == "file":
        file = obj.properties.get("file")
        if isinstance(file, str) and file.strip():
            return file, None
        logger.info(f"{obj.name} has displaySource file but no file; it shows nothing, as in EDM")
        return None, None
    file_pv = obj.properties.get("filePv")
    if not isinstance(file_pv, str) or not file_pv.strip():
        logger.info(f"{obj.name} has displaySource stringPV but no filePv; it shows nothing, as in EDM")
        return None, None
    file = loc_str_init(file_pv)
    if not file.strip():
        logger.warning(f"{obj.name} opens the file named by {file_pv} at runtime, through a Filename rule")
        return None, file_pv
    return file, file_pv

populate_tab_bar(obj, widget)

Build the pages of a choice button that absorbed a menu embedded window (see pair_menu_pips).

Source code in pydmconverter/edm/converter_helpers.py
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
def populate_tab_bar(obj: EDMObject, widget: QTabWidget) -> None:
    """Build the pages of a choice button that absorbed a menu embedded window (see pair_menu_pips)."""
    spec = obj.properties.get(TAB_PAGES)
    if spec is None:
        # A choice button without a channel to become a PyDMEnumButton.
        logger.warning(f"No tab names found in {obj.name}. Skipping.")
        return
    # The pages switch on their own, so the tab widget needs no channel.
    widget.channel = None
    widget.tab_bar_height = spec["tab_bar_height"]
    widget.tab_bar_left = spec["tab_bar_left"]
    widget.tab_width = spec["tab_width"]
    widget.border_color = spec["border_color"]
    widget.current_index = spec["current_index"]
    widget.select_color = spec["select_color"]
    for index, page in enumerate(spec["pages"]):
        child_widget = QWidget(title=page["title"])
        child_widget.add_child(
            PyDMEmbeddedDisplay(
                name=f"{widget.name}_page{index}",
                x=spec["page_x"],
                y=spec["page_y"],
                width=spec["page_width"],
                height=spec["page_height"],
                filename=page["filename"],
                macros=page["macros"],
                visible=True,
            )
        )
        widget.add_child(child_widget)

resolve_widget_type(obj)

Determine the PyDM widget type for a given EDM object.

Returns the widget type class, or None if unsupported. May mutate obj.properties for special cases (e.g. activechoicebuttonclass without tabs).

Source code in pydmconverter/edm/converter_helpers.py
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
def resolve_widget_type(obj: EDMObject):
    """
    Determine the PyDM widget type for a given EDM object.

    Returns the widget type class, or None if unsupported.
    May mutate obj.properties for special cases (e.g. activechoicebuttonclass without tabs).
    """
    name = obj.name.lower()

    if name == "activelineclass":
        return get_polyline_widget_type(obj)
    if name == "activearcclass":
        return get_arc_widget_type(obj)

    widget_type = EDM_TO_PYDM_WIDGETS.get(name)
    if not widget_type:
        return None

    if name == "activechoicebuttonclass" and TAB_PAGES not in obj.properties:
        attr = channel_attr(obj)
        channel = obj.properties[attr] if attr else None
        if not channel:
            logger.warning(f"Could not find channel in object: {obj.name}")
        else:
            widget_type = PyDMEnumButton
            obj.properties["tab_names"] = None
            obj.properties["hide_on_disconnect_channel"] = channel

    return widget_type

shown_display_index(obj)

The EDM index of the displayFileName/symbols entry an embedded window shows when it opens: a menu window starts at its filePv's initial value (EDM shows displayFileName[value]), any other at its lowest-numbered entry.

Source code in pydmconverter/edm/converter_helpers.py
1720
1721
1722
1723
1724
1725
1726
1727
1728
def shown_display_index(obj: EDMObject) -> int:
    """The EDM index of the displayFileName/symbols entry an embedded window shows
    when it opens: a menu window starts at its filePv's initial value (EDM shows
    displayFileName[value]), any other at its lowest-numbered entry."""
    file_pv = obj.properties.get("filePv")
    index = 0
    if is_menu_pip(obj) and isinstance(file_pv, str) and file_pv.startswith("loc://"):
        index = _loc_init(file_pv)
    return _starting_index(index, [i for i, _ in block_items(obj.properties.get("displayFileName"))])

start_rules_at_loc_inits(ui_element)

Start every Visible or Enable rule that reads only loc:// variables at the value it has for their initial values.

PyDM's local plugin sends a joining listener the variable's value and only then tells it the channel is connected (local_plugin.py add_listener), and the rules engine skips a value from a channel that is not connected yet (rules.py callback_value) and does not evaluate on connecting (callback_conn). So the last rule to join a variable is not evaluated until the value changes, and shows its initial_value, false, rather than what the variable selects. Rules join in document order, and after the widgets' channels when PyDM's Back and Forward bring a display back.

PyDM configures a variable from the first address that joins it with both type and init, so the first declaration in the document wins here too, also over a later one with a different init. A widget joins with its channel and its rules' channels, which PyDM's .ui loader sets in document order (a widget's properties before its children); the channel of a widget without a channel property, such as an embedded display, never joins. Waveform curves are not read.

Source code in pydmconverter/edm/converter_helpers.py
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def start_rules_at_loc_inits(ui_element: ET.Element) -> None:
    """Start every Visible or Enable rule that reads only loc:// variables at
    the value it has for their initial values.

    PyDM's local plugin sends a joining listener the variable's value and only
    then tells it the channel is connected (local_plugin.py add_listener), and
    the rules engine skips a value from a channel that is not connected yet
    (rules.py callback_value) and does not evaluate on connecting
    (callback_conn). So the last rule to join a variable is not evaluated until
    the value changes, and shows its initial_value, false, rather than what the
    variable selects. Rules join in document order, and after the widgets'
    channels when PyDM's Back and Forward bring a display back.

    PyDM configures a variable from the first address that joins it with both
    type and init, so the first declaration in the document wins here too, also
    over a later one with a different init. A widget joins with its channel and
    its rules' channels, which PyDM's .ui loader sets in document order (a
    widget's properties before its children); the channel of a widget without
    a channel property, such as an embedded display, never joins. Waveform
    curves are not read.
    """
    declared = {}
    rule_properties = []
    for widget in ui_element.iter("widget"):
        widget_class = widget.get("class", "")
        if not widget_class.startswith("PyDM"):
            continue
        for prop in widget.findall("property"):
            string = prop.find("string")
            if string is None or not string.text:
                continue
            if prop.get("name") == "channel" and widget_class not in NO_CHANNEL_CLASSES:
                addresses = [string.text]
            elif prop.get("name") == "rules" and widget_class not in NO_RULES_CLASSES:
                try:
                    rules = json.loads(string.text)
                except ValueError:
                    continue
                rule_properties.append((string, rules))
                addresses = [channel.get("channel") for rule in rules for channel in rule.get("channels", [])]
            else:
                continue
            for address in addresses:
                name, value = _loc_variable(address)
                if name is not None and value is not None:
                    declared.setdefault(name, value)

    for string, rules in rule_properties:
        changed = False
        for rule in rules:
            start = _rule_start(rule, declared)
            if start is not None and start != rule.get("initial_value"):
                rule["initial_value"] = start
                changed = True
        if changed:
            # As Rules.to_xml writes it: each rule as _json_object, joined by ", ".
            string.text = json.dumps(rules, ensure_ascii=False)

transform_edm_to_pydm(edm_x, edm_y, edm_width, edm_height, container_height, scale=1.0, offset_x=0, offset_y=0)

Transform coordinates from an EDM coordinate system (bottom-left origin) to a PyDM coordinate system (top-left origin) at the root level.

Source code in pydmconverter/edm/converter_helpers.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def transform_edm_to_pydm(edm_x, edm_y, edm_width, edm_height, container_height, scale=1.0, offset_x=0, offset_y=0):
    """
    Transform coordinates from an EDM coordinate system (bottom-left origin)
    to a PyDM coordinate system (top-left origin) at the root level.
    """
    pydm_x = offset_x + int(edm_x * scale)
    pydm_width = edm_width * scale
    pydm_height = edm_height * scale
    pydm_y = offset_y + int(edm_y * scale)

    logger.debug(
        f"Transform: EDM({edm_x}, {edm_y}, {edm_width}, {edm_height}) -> PyDM({pydm_x}, {pydm_y}, {pydm_width}, {pydm_height})"
    )

    return int(pydm_x), int(pydm_y), int(pydm_width), int(pydm_height)

transform_nested_widget(child_edm_x, child_edm_y, child_edm_width, child_edm_height, parent_edm_x, parent_edm_y, parent_edm_height, scale=1.0)

Transform child widget coordinates relative to its parent. If EDM uses absolute coordinates for nested widgets, subtract parent position.

Source code in pydmconverter/edm/converter_helpers.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def transform_nested_widget(
    child_edm_x,
    child_edm_y,
    child_edm_width,
    child_edm_height,
    parent_edm_x,
    parent_edm_y,
    parent_edm_height,
    scale=1.0,
):
    """
    Transform child widget coordinates relative to its parent.
    If EDM uses absolute coordinates for nested widgets, subtract parent position.
    """
    # Convert to relative coordinates by subtracting parent position
    relative_x = child_edm_x * scale  # - parent_edm_y
    relative_y = child_edm_y * scale  # - parent_edm_x
    child_width = child_edm_width * scale
    child_height = child_edm_height * scale

    return int(relative_x), int(relative_y), int(child_width), int(child_height)

traverse_group(edm_group, color_list_dict, used_classes, skip_widgets=None, parent_pydm_group=None, pydm_widgets=None, container_height=None, scale=1.0, offset_x=0, offset_y=0, central_widget=None, parent_vispvs=None)

Recursively traverse an EDM group and convert each object to a PyDM widget.

Parameters

edm_group : EDMGroup The EDM group to traverse. color_list_dict : dict Parsed color list data for color conversion. used_classes : set Accumulator for tracking which PyDM widget classes are used. skip_widgets : set, optional Set of widget class names (lowercase) to skip during conversion.

Source code in pydmconverter/edm/converter_helpers.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
def traverse_group(
    edm_group: EDMGroup,
    color_list_dict,
    used_classes: set,
    skip_widgets: set = None,
    parent_pydm_group: Optional[PyDMFrame] = None,
    pydm_widgets=None,
    container_height: float = None,
    scale: float = 1.0,
    offset_x: float = 0,
    offset_y: float = 0,
    central_widget: EDMGroup = None,
    parent_vispvs: Optional[List[Tuple[str, int, int, bool]]] = None,
):
    """
    Recursively traverse an EDM group and convert each object to a PyDM widget.

    Parameters
    ----------
    edm_group : EDMGroup
        The EDM group to traverse.
    color_list_dict : dict
        Parsed color list data for color conversion.
    used_classes : set
        Accumulator for tracking which PyDM widget classes are used.
    skip_widgets : set, optional
        Set of widget class names (lowercase) to skip during conversion.
    """
    menu_mux_buttons = []
    if pydm_widgets is None:
        pydm_widgets = []
    if skip_widgets is None:
        skip_widgets = set()

    for obj in edm_group.objects:
        if isinstance(obj, EDMGroup):
            x, y, width, height = _compute_geometry(obj, parent_pydm_group, container_height, scale, offset_x, offset_y)

            logger.debug("Skipped pydm_group")

            vis_invert = bool(obj.properties.get("visInvert", False))
            limits = None
            if "visPv" in obj.properties:
                limits = object_vis_range(f"Group at ({obj.x}, {obj.y})", obj.properties)
            if limits is not None:
                # EDM shows the group while visMin <= value < visMax.
                curr_vispv = [(obj.properties["visPv"], *limits, vis_invert)]
                if obj.properties.get(STARTS_VISIBLE):
                    curr_vispv = [curr_vispv[0] + (True,)]
            else:
                curr_vispv = []

            if "symbolMin" in obj.properties and "symbolMax" in obj.properties and "symbolChannel" in obj.properties:
                symbol_vispv = [
                    (
                        obj.properties["symbolChannel"],
                        obj.properties["symbolMin"],
                        obj.properties["symbolMax"],
                        False,
                    )
                ]
                if "symbolOtherRanges" in obj.properties:
                    # State 0 also shows while no other state's range holds the value.
                    other_ranges = tuple(tuple(other) for other in obj.properties["symbolOtherRanges"])
                    symbol_vispv = [symbol_vispv[0] + (False, other_ranges)]
            else:
                symbol_vispv = []

            # A group's menu muxes keep their EDM screen coordinates and screen
            # order, but set no macros, as in EDM (see _grouped_menu_mux).
            _, group_menu_muxes = traverse_group(
                obj,
                color_list_dict,
                used_classes,
                skip_widgets=skip_widgets,
                pydm_widgets=pydm_widgets,
                container_height=height,
                scale=scale,
                offset_x=0,
                offset_y=0,
                central_widget=central_widget,
                parent_vispvs=(parent_vispvs or []) + curr_vispv + symbol_vispv,
            )
            menu_mux_buttons.extend(_grouped_menu_mux(menu) for menu in group_menu_muxes)

        elif isinstance(obj, EDMObject):
            # Skip widgets based on site rules
            if obj.name.lower() in skip_widgets:
                logger.info(f"Skipping {obj.name} (site rule)")
                continue

            # 1. Resolve widget type
            widget_type = resolve_widget_type(obj)

            if obj.name.lower() == "menumuxclass":
                menu_mux_buttons.append(obj)
            if not widget_type:
                logger.warning(f"Unsupported widget type: {obj.name}. Skipping.")
                log_unsupported_widget(obj.name)
                continue

            # 2. Create widget instance
            widget = widget_type(name=obj.name + str(id(obj)) if hasattr(obj, "name") else f"widget_{id(obj)}")
            used_classes.add(type(widget).__name__)
            logger.info(f"Creating widget: {widget_type.__name__} ({widget.name})")

            if parent_vispvs:
                widget.visPvList = list(parent_vispvs)

            # TextupdateClass widgets always show units in EDM
            if obj.name.lower() in ("textupdateclass", "multilinetextupdateclass", "regtextupdateclass"):
                if "showUnits" not in obj.properties:
                    widget.show_units = True
                    logger.info(f"Set show_units=True for {obj.name} (implicit EDM behavior)")

            # ByteClass: EDM defaults to 16 bits and no labels
            if isinstance(widget, PyDMByteIndicator):
                if "numBits" not in obj.properties:
                    widget.numBits = 16
                    logger.info(f"Set numBits=16 for {obj.name} (EDM default)")
                widget.showLabels = False
                logger.info(f"Set showLabels=False for {obj.name} (EDM has no labels)")

            # 3. Map and convert attributes
            for edm_attr, value in obj.properties.items():
                pydm_attr = EDM_TO_PYDM_ATTRIBUTES.get(edm_attr)
                if not pydm_attr:
                    continue

                value = convert_attribute_value(edm_attr, value, widget, obj, color_list_dict)
                if value is None:
                    continue

                try:
                    setattr(widget, pydm_attr, value)
                    logger.info(f"Set {pydm_attr} to {value} for {widget.name}")
                except Exception as e:
                    raise AttributeConversionError(edm_attr, value, widget.name, cause=e) from e
            # The visibility range as EDM reads visMin/visMax; a limit it can't read here drops the rule.
            if getattr(widget, "visPv", None) is not None:
                limits = object_vis_range(obj.name, obj.properties)
                if limits is None:
                    widget.visPv = None
                else:
                    widget.visMin, widget.visMax = limits
            # Before post-processing: on/off button variants copy the channel and key their rules on it,
            # and the alarm flags with it.
            apply_channel_roles(widget, obj)
            apply_alarm_flags(widget, obj)

            # 4. Post-processing (geometry, button variants, dimension padding, etc.)
            apply_widget_post_processing(
                widget,
                obj,
                pydm_widgets,
                scale,
                offset_x,
                offset_y,
                container_height,
                parent_pydm_group,
            )

            # Widgets built inside a container (tab pages) need their classes declared too.
            nested = list(getattr(widget, "children", []))
            while nested:
                child = nested.pop()
                used_classes.add(type(child).__name__)
                nested.extend(getattr(child, "children", []))

            pydm_widgets.append(widget)
            logger.info(f"Added {widget.name} to root")
        else:
            logger.warning(f"Unknown object type: {type(obj)}. Skipping.")

    return pydm_widgets, menu_mux_buttons

widgets_overlap(widget1, widget2)

Check if two widgets overlap based on their geometry (x, y, width, height).

Parameters

widget1, widget2 : PyDM widget instances Widgets with x, y, width, height attributes

Returns

bool True if widgets overlap, False otherwise

Source code in pydmconverter/edm/converter_helpers.py
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
def widgets_overlap(widget1, widget2) -> bool:
    """
    Check if two widgets overlap based on their geometry (x, y, width, height).

    Parameters
    ----------
    widget1, widget2 : PyDM widget instances
        Widgets with x, y, width, height attributes

    Returns
    -------
    bool
        True if widgets overlap, False otherwise
    """
    x1, y1 = widget1.x, widget1.y
    w1, h1 = widget1.width, widget1.height

    x2, y2 = widget2.x, widget2.y
    w2, h2 = widget2.width, widget2.height

    if x1 + w1 <= x2 or x2 + w2 <= x1:
        return False
    if y1 + h1 <= y2 or y2 + h2 <= y1:
        return False

    return True