#!/usr/bin/env python3 """Generate lightgui/props.py from the C property tables. Sources (read, never modified): /opt/lightgui/src/props.h -- common_props() + props_for() tables /opt/lightgui_python/lightgui/xframe/palette.py -- the 547 palette kinds The generated file keeps the C tables verbatim (internal GTK-era names, kinds, defaults, ranges, enum labels/values -- proposal SS5.3) and adds: * the generic set on EVERY palette kind (Name + geometry + the C common set, plus the Lazarus BorderSpacing sub-props that have no C counterpart, flagged model-only), * a per-kind custom table, by mapping each palette kind onto the C table for its family (KIND_TABLE below), * a Lazarus display name per prop and a model_only flag (props that are stored in the model and emitted by the generator as comments but do not change the live canvas widget), * an EVENTS list (Lazarus names, per proposal SS4.10), * register_custom_table() so Phase 6 can add the Stock / Instrumentation tables later without touching this generator. Stock (37) and Instrumentation (66) kinds get the generic set only in Phase 2; their per-widget tables are Phase 6 work. Re-run: python3 tools/gen_props.py (from the repo root) """ import re import sys from pathlib import Path REPO = Path(__file__).resolve().parent.parent C_PROPS = Path("/opt/lightgui/src/props.h") # --- curated: palette kind -> C props_for() table name ------------------- # Keyed by palette `kind` (palette.py), not by registry name: GtkButton # and TButton both have kind "Button" and share the table. KIND_TABLE = { "Button": "button", "BitBtn": "button", "AppChooserButton": "button", "FileChooserButton": "button", "FontButton": "button", "LinkButton": "button", "LockButton": "button", "ModelButton": "button", "ToolButton": "button", "ToggleToolButton": "button", "VolumeButton": "button", "EditButton": "button", "ColorButton": "colorbox", "ColorDialogButton": "colorbox", "ColorBox": "colorbox", "ColorListBox": "colorbox", "Label": "label", "AccelLabel": "label", "Inscription": "label", "StaticText": "label", "Entry": "entry", "Edit": "entry", "CalcEdit": "entry", "DateEdit": "entry", "DirectoryEdit": "entry", "FileNameEdit": "entry", "LabeledEdit": "entry", "MaskEdit": "entry", "TimeEdit": "entry", "SearchEntry": "entry", "PasswordEntry": "entry", "EditableLabel": "entry", "CheckButton": "checkbutton", "CheckBox": "checkbutton", "CheckMenuItem": "checkbutton", "RadioButton": "radiobutton", "RadioMenuItem": "radiobutton", "ToggleButton": "togglebutton", "ToggleBox": "togglebutton", "SpeedButton": "togglebutton", "Frame": "frame", "AspectFrame": "frame", "GroupBox": "groupbox", "Panel": "panel", "ButtonPanel": "panel", "ComboBox": "combobox", "ComboBoxText": "combobox", "ComboBoxEx": "combobox", "CheckComboBox": "combobox", "FilterComboBox": "combobox", "DropDown": "combobox", "ListBox": "listbox", "CheckGroup": "listbox", "FileListBox": "listbox", "RadioGroup": "listbox", "CheckListBox": "checklistbox", "MenuButton": "menubutton", "Scale": "scale", "LevelBar": "scale", "TrackBar": "trackbar", "Scrollbar": "scrollbar", "ScrollBar": "scrollbar", "SpinButton": "spinedit", "SpinEdit": "spinedit", "FloatSpinEdit": "spinedit", "UpDown": "spinedit", "TextView": "text", "Memo": "memo", "Image": "image", "Picture": "image", "Shape": "shape", "Notebook": "notebook", "PageControl": "notebook", "TabControl": "notebook", "ScrollBox": "scrollbox", "Splitter": "splitter", "PairSplitter": "splitter", "Statusbar": "statusbar", "StatusBar": "statusbar", "Toolbar": "toolbar", "ToolBar": "toolbar", "ControlBar": "toolbar", "CoolBar": "toolbar", "HeaderControl": "toolbar", "MenuBar": "menubar", "MainMenu": "menubar", "PopupMenu": "menubar", "ProgressBar": "progressbar", "Calendar": "datetimepicker", "DateTimePicker": "datetimepicker", "ListView": "listview", "ShellListView": "listview", "ColumnView": "listview", "GridView": "listview", "IconView": "listview", "TreeView": "treeview", "ShellTreeView": "treeview", "StringGrid": "stringgrid", "DrawGrid": "stringgrid", "ValueListEditor": "stringgrid", "XSpreadsheet": "spreadsheet", "XGraph": "plot", "Switch": "togglebutton", "ScaleButton": "scale", "Menu": "menubar", "MenuItem": "menuitem", "FlowBox": "listbox", "StackSidebar": "listbox", "StackSwitcher": "listbox", "EntryCompletion": "combobox", "Paned": "splitter", "ScrolledWindow": "scrollbox", "PlacesSidebar": "listbox", "ColorChooserWidget": "colorbox", "AboutDialog": "dialog", "AppChooserDialog": "dialog", "Assistant": "dialog", "CalculatorDialog": "dialog", "CalendarDialog": "dialog", "ColorChooserDialog": "dialog", "ColorDialog": "dialog", "Dialog": "dialog", "FileChooserDialog": "dialog", "FindDialog": "dialog", "FontChooserDialog": "dialog", "FontDialog": "dialog", "MessageDialog": "dialog", "OpenDialog": "dialog", "OpenPictureDialog": "dialog", "PageSetupDialog": "dialog", "PrintDialog": "dialog", "PrintUnixDialog": "dialog", "PrinterSetupDialog": "dialog", "ReplaceDialog": "dialog", "SaveDialog": "dialog", "SavePictureDialog": "dialog", "SelectDirectoryDialog": "dialog", "TaskDialog": "dialog", "ShortcutsWindow": "dialog", "Window": "toplevel", "Form": "toplevel", "ApplicationWindow": "toplevel", } # --- extra tables (no C counterpart; small and explicit) ---------------- # C props_for() has no table for dialogs (title) or menu items # (caption). Everything else unmapped keeps the generic set only. EXTRA_TABLES = { "dialog": [ {"name": "title", "kind": "Str", "default": "", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, ], "menuitem": [ {"name": "label", "kind": "Str", "default": "", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, ], } # --- curated: Lazarus display names --------------------------------------- DISPLAY = { "name": "Name", "left": "Left", "top": "Top", "width": "Width", "height": "Height", "background": "Color", "foreground": "Font.Color", "font-name": "Font.Name", "font-size": "Font.Size", "font-bold": "Font.Style.Bold", "font-italic": "Font.Style.Italic", "font-underline": "Font.Style.Underline", "font-strikeout": "Font.Style.StrikeOut", "border-width": "Border.Width", "border-color": "Border.Color", "border-radius": "Border.Radius", "tooltip-text": "Tooltip", "hint": "Hint", "show-hint": "ShowHint", "cursor": "Cursor", "tab-order": "TabOrder", "tab-stop": "TabStop", "min-width": "Constraints.MinWidth", "min-height": "Constraints.MinHeight", "max-width": "Constraints.MaxWidth", "max-height": "Constraints.MaxHeight", "margin-left": "BorderSpacing.Left", "margin-top": "BorderSpacing.Top", "margin-right": "BorderSpacing.Right", "margin-bottom": "BorderSpacing.Bottom", "margin-around": "BorderSpacing.Around", "inner-border": "BorderSpacing.InnerBorder", "cell-align-horizontal": "BorderSpacing.CellAlignHorizontal", "cell-align-vertical": "BorderSpacing.CellAlignVertical", "autosize": "AutoSize", "tag": "Tag", "anchor-top": "Anchors.Top", "anchor-left": "Anchors.Left", "anchor-right": "Anchors.Right", "anchor-bottom": "Anchors.Bottom", "align": "Align", "enabled": "Enabled", "visible": "Visible", "label": "Caption", "text": "Text", "active": "Checked", "value": "Position", "minimum": "Min", "maximum": "Max", "lower": "Min", "upper": "Max", "step-increment": "SmallChange", "page-increment": "LargeChange", "page-size": "PageSize", "step": "Step", "items": "Items", "item-index": "ItemIndex", "selection-mode": "SelectionMode", "password": "PasswordChar", "show-password": "ShowPassword", "placeholder-text": "TextHint", "editable": "ReadOnly", "max-length": "MaxLength", "alignment": "Alignment", "char-case": "CharCase", "numbers-only": "NumbersOnly", "hide-selection": "HideSelection", "auto-select": "AutoSelect", "xalign": "Alignment", "yalign": "Layout", "wrap": "WordWrap", "selectable": "Selectable", "transparent": "Transparent", "show-accel-char": "ShowAccelChar", "focus-control": "FocusControl", "inconsistent": "State", "allow-grayed": "AllowGrayed", "value-checked": "ValueChecked", "value-unchecked": "ValueUnchecked", "group": "Group", "group-index": "GroupIndex", "allow-all-up": "AllowAllUp", "flat": "Flat", "glyph": "Glyph", "kind": "Kind", "layout": "Layout", "modal-result": "ModalResult", "default": "Default", "cancel": "Cancel", "relief": "Relief", "focus-on-click": "FocusOnClick", "style": "Style", "drop-down-count": "DropDownCount", "drop-down-width": "DropDownWidth", "sorted": "Sorted", "read-only": "ReadOnly", "auto-complete": "AutoComplete", "columns": "Columns", "item-height": "ItemHeight", "integral-height": "IntegralHeight", "checked-items": "Checked", "direction": "Direction", "digits": "DecimalPlaces", "draw-value": "DrawValue", "inverted": "Inverted", "page-step": "PageSize", "tick-marks": "TickMarks", "frequency": "Frequency", "show-sel-range": "ShowSelRange", "sel-start": "SelStart", "sel-end": "SelEnd", "orientation": "Kind", "cursor-visible": "CursorVisible", "wrap-mode": "WordWrap", "scroll-bars": "ScrollBars", "want-tabs": "WantTabs", "want-returns": "WantReturns", "label-xalign": "Alignment", "inset": "Inset", "top-inset": "TopInset", "shadow-type": "Bevel", "file": "Picture", "pixel-size": "PixelSize", "stretch": "Stretch", "proportional": "Proportional", "center": "Center", "shape": "Shape", "fill-color": "FillColor", "pen-color": "PenColor", "pen-width": "PenWidth", "pages": "Pages", "page": "ActivePage", "tab-height": "TabHeight", "tab-position": "TabPosition", "tab-width": "TabWidth", "position": "Position", "min-size": "MinSize", "resize-style": "ResizeStyle", "auto-snap": "AutoSnap", "panels": "Panels", "size-grip": "SizeGrip", "toolbar-style": "Style", "show-captions": "ShowCaptions", "button-width": "ButtonWidth", "button-height": "ButtonHeight", "menus": "Menus", "fraction": "Fraction", "show-text": "BarShowText", "pulsing": "Style", "bar-color": "BarColor", "trough-color": "TroughColor", "date": "Date", "show-heading": "ShowHeading", "show-day-names": "ShowDayNames", "show-week-numbers": "ShowWeekNumbers", "grid-color": "GridColor", "selected-fill-color": "SelectedFillColor", "selected-text-color": "SelectedTextColor", "today-color": "TodayColor", "dim-text-color": "DimTextColor", "weekends-color": "WeekendsColor", "disabled-color": "DisabledColor", "color": "Color", "default-color": "DefaultColor", "none-color": "NoneColor", "use-alpha": "UseAlpha", "title": "Title", "headers-visible": "HeadersVisible", "view-style": "ViewStyle", "grid-lines": "GridLines", "row-select": "RowSelect", "multi-select": "MultiSelect", "sort-type": "SortType", "header-height": "HeaderHeight", "indent": "Indent", "show-buttons": "ShowButtons", "show-lines": "ShowLines", "show-root": "ShowRoot", "rows": "RowCount", "fixed-cols": "FixedCols", "fixed-rows": "FixedRows", "default-col-width": "DefaultColWidth", "default-row-height": "DefaultRowHeight", "grid-line-width": "GridLineWidth", "line-color": "LineColor", "border-style": "BorderStyle", "icon": "Icon", "window-state": "WindowState", "resizable": "Resizable", "width-chars": "WidthChars", } # Per-(C-table, prop) display overrides (ComboBox "active" is an # ItemIndex, not a Checked flag; Scale "value" is a Position, etc.). DISPLAY_OVERRIDES = { ("combobox", "active"): "ItemIndex", ("combobox", "text"): "Text", ("listbox", "active"): "ItemIndex", ("checkbutton", "active"): "Checked", ("radiobutton", "active"): "Checked", ("togglebutton", "active"): "Down", ("togglebutton", "text"): "Caption", ("spinedit", "step"): "Increment", ("spinedit", "value"): "Value", ("progressbar", "value"): "Position", ("progressbar", "position"): "Position", ("scale", "value"): "Position", ("trackbar", "value"): "Position", ("scrollbar", "value"): "Position", ("datetimepicker", "date"): "Date", ("frame", "label"): "Caption", ("groupbox", "label"): "Caption", ("panel", "label"): "Caption", ("menubutton", "label"): "Caption", ("colorbox", "color"): "Selected", ("text", "text"): "Text", ("memo", "text"): "Text", ("entry", "text"): "Text", ("entry", "editable"): "ReadOnly", ("text", "editable"): "ReadOnly", ("memo", "editable"): "ReadOnly", } # Props that are stored in the model and emitted by the generator (as # comments where the generated XFrame API has no setter) but do not # change the live canvas widget in this phase. Everything not listed # here is live-applied by Widget.set_prop (state change + canvas # redraw); the canvas draw code reads the live ones. MODEL_ONLY = { "font-underline", "font-strikeout", "cursor", "tab-order", "tab-stop", "margin-left", "margin-top", "margin-right", "margin-bottom", "margin-around", "inner-border", "cell-align-horizontal", "cell-align-vertical", "autosize", "tag", "anchor-top", "anchor-left", "anchor-right", "anchor-bottom", "align", "hint", "show-hint", "tooltip-text", "glyph", "focus-control", "value-checked", "value-unchecked", "group", "group-index", "allow-all-up", "modal-result", "default", "cancel", "kind", "layout", "relief", "focus-on-click", "char-case", "numbers-only", "auto-select", "auto-complete", "hide-selection", "width-chars", "max-length", "sorted", "drop-down-count", "drop-down-width", "style", "columns", "integral-height", "view-style", "sort-type", "min-size", "resize-style", "auto-snap", "numeric", "editor-enabled", "position", "window-state", "resizable", "border-style", "icon", "selectable", "want-tabs", "want-returns", } # (C-table, prop) forced live even though the name is in MODEL_ONLY # above (e.g. Splitter/ProgressBar "position" is drawn; toplevel # "position" is a window-placement hint and stays model-only). LIVE_OVERRIDES = { ("splitter", "position"), ("progressbar", "position"), ("scale", "position"), ("trackbar", "position"), ("scrollbar", "position"), } # (C-table, prop) forced model-only even though the name is not in # MODEL_ONLY above. MODEL_ONLY_OVERRIDES = { ("toplevel", "position"), ("toplevel", "title"), ("entry", "max-length"), ("text", "max-length"), ("memo", "max-length"), } # Lazarus event names (proposal SS4.10): the Inspector shows these, # not GTK signal names. EVENTS = ( "OnClick", "OnChange", "OnKeyPress", "OnKeyDown", "OnKeyUp", "OnMouseDown", "OnMouseUp", "OnMouseMove", "OnDblClick", "OnEnter", "OnExit", "OnResize", "OnChangeBounds", "OnMouseEnter", "OnMouseLeave", "OnMouseWheel", "OnContextPopup", ) # Proposal SS2.1-SS2.10 spot-checks: (C table, required prop names). # The generator fails if the C tables ever stop covering the proposal. REQUIRED = { "button": ["label", "default", "cancel", "kind", "layout", "glyph", "modal-result"], "entry": ["text", "editable", "max-length", "placeholder-text", "password", "alignment", "char-case", "numbers-only", "hide-selection", "auto-select"], "label": ["label", "xalign", "yalign", "wrap", "selectable", "transparent", "focus-control", "show-accel-char"], "checkbutton": ["label", "active", "inconsistent", "allow-grayed", "alignment", "value-checked", "value-unchecked"], "radiobutton": ["label", "active", "group"], "combobox": ["items", "active", "text", "style", "drop-down-count", "drop-down-width", "sorted", "read-only", "max-length"], "listbox": ["items", "selection-mode", "item-index", "sorted", "columns", "item-height", "integral-height"], "checklistbox": ["items", "checked-items", "item-index", "item-height", "sorted"], "scrollbar": ["value", "lower", "upper", "step-increment", "page-increment", "page-size", "orientation", "large-change"], "scale": ["value", "minimum", "maximum", "draw-value", "page-step", "tick-marks", "frequency", "show-sel-range"], "trackbar": ["value", "minimum", "maximum", "step", "page-step", "draw-value", "tick-marks", "frequency"], "text": ["text", "editable", "cursor-visible", "wrap-mode", "max-length", "scroll-bars", "want-tabs", "want-returns", "hide-selection", "alignment"], "memo": ["text", "editable", "cursor-visible", "wrap-mode", "max-length", "scroll-bars", "want-tabs", "want-returns", "hide-selection", "alignment"], } # Extra generic props with no C counterpart (Lazarus BorderSpacing # sub-props, proposal SS1): name, kind, default, lo, hi, enum labels. GENERIC_EXTRAS = [ ("inner-border", "Int", "0", 0, 100000, None), ("cell-align-horizontal", "Enum", "0", 0, 0, "Left|Center|Right"), ("cell-align-vertical", "Enum", "0", 0, 0, "Top|Center|Bottom"), ] # --- parsing /opt/lightgui/src/props.h ------------------------------------ _ENTRY_RE = re.compile( r'\{\s*"(?P[^"]+)"\s*,\s*(?:K|PropKind)::(?P\w+)\s*,\s*"(?P[^"]*)"' r'(?:\s*,\s*(?P-?[\d.]+)\s*,\s*(?P-?[\d.]+)' r'(?:\s*,\s*"(?P[^"]*)"\s*,\s*(?P\w+))?)?\s*\}') _VECTOR_RE = re.compile( r"static const std::vector (\w+) = \{(.*?)\};", re.S) _ENUM_ARR_RE = re.compile( r"inline const int (k\w+Values)\[\] = \{([^}]*)\};") _COMMON_RE = re.compile( r"common_props\(\) \{(.*?)return v;\n\}", re.S) def _parse(text): enums = {} for name, body in _ENUM_ARR_RE.findall(text): enums[name] = [int(v) for v in body.replace(",", " ").split() if v.strip().lstrip("-").isdigit()] def entries(body): out = [] for m in _ENTRY_RE.finditer(body): d = m.groupdict() labels = d["labels"].split("|") if d["labels"] else None values = enums.get(d["values"]) if d["values"] else None out.append({ "name": d["name"], "kind": d["kind"], "default": d["default"], "lo": float(d["lo"]) if d["lo"] is not None else 0.0, "hi": float(d["hi"]) if d["hi"] is not None else 0.0, "labels": labels, "values": values, }) return out common_m = _COMMON_RE.search(text) if not common_m: raise SystemExit("gen_props: common_props() not found in props.h") tables = {"common": entries(common_m.group(1))} for var, body in _VECTOR_RE.findall(text): tables[var] = entries(body) return tables def _model_only(table, name): if (table, name) in LIVE_OVERRIDES: return False if (table, name) in MODEL_ONLY_OVERRIDES: return True return name in MODEL_ONLY def _display(table, name): return DISPLAY_OVERRIDES.get((table, name), DISPLAY.get(name, name)) def _py_str(value): return '"%s"' % value.replace("\\", "\\\\").replace('"', '\\"') def _num(value): if value == int(value): return str(int(value)) return repr(value) def _emit_table(name, table, props): lines = ["%s = (" % name] for p in props: disp = _display(table, p["name"]) mo = _model_only(table, p["name"]) labels = (", ".join(_py_str(x) for x in p["labels"]) if p["labels"] else "") values = (", ".join(str(v) for v in p["values"]) if p["values"] else "") lines.append( ' PropDef(%s, %s, %s, %s, %s, (%s), (%s), %s, %s),' % (_py_str(p["name"]), _py_str(p["kind"]), _py_str(p["default"]), _num(p["lo"]), _num(p["hi"]), labels, values, _py_str(disp), "True" if mo else "False")) lines.append(")") return lines def main(): tables = _parse(C_PROPS.read_text(encoding="utf-8")) for table, required in REQUIRED.items(): have = {p["name"] for p in tables.get(table, [])} missing = [r for r in required if r not in have] if missing: raise SystemExit( "gen_props: C table %r is missing proposal props: %s" % (table, ", ".join(missing))) sys.path.insert(0, str(REPO)) from lightgui.xframe import palette kinds = [e.kind for e in palette.PALETTE] generic_kinds = {e.kind for e in palette.PALETTE if e.section not in ("Stock Market", "Instrumentation")} unknown = sorted({k for k in KIND_TABLE if k not in kinds}) if unknown: raise SystemExit("gen_props: KIND_TABLE kinds not in palette: %s" % ", ".join(unknown)) for k in sorted(k for k in generic_kinds if k not in KIND_TABLE): print("gen_props: NOTE generic kind %r has no custom table " "(generic set only)" % k, file=sys.stderr) out = [] out.append('"""Property tables for the LightGUI Python port.') out.append('') out.append('GENERATED -- do not edit by hand. Run tools/gen_props.py') out.append('to regenerate from /opt/lightgui/src/props.h (C tables,') out.append('canonical) and lightgui/xframe/palette.py (the 547 kinds).') out.append('Curated mappings (kind -> C table, Lazarus display names,') out.append('model-only flags) live in tools/gen_props.py.') out.append('') out.append('Every palette kind gets the generic set (Name, geometry,') out.append('Color, Font, Border, Enabled, Visible, Hint, ShowHint,') out.append('Cursor, TabOrder, TabStop, Constraints, BorderSpacing,') out.append('AutoSize, Tag, Align, Anchors) plus its family custom') out.append('props from proposal SS2.1-SS2.21. Stock / Instrumentation') out.append('kinds get the generic set only in Phase 2; Phase 6 adds') out.append('their tables via register_custom_table().') out.append('') out.append('Internal names stay the C/GTK-era names (proposal SS5.3);') out.append('`display` is the Lazarus name shown in the Inspector.') out.append('`model_only` props are stored on the widget and emitted') out.append('by the generator as comments; they do not change the live') out.append('canvas widget. Note `editable` is inverted ReadOnly') out.append('(ReadOnly = not editable, proposal SS2.2) and `foreground`') out.append('is the font/text colour.') out.append('"""') out.append('') out.append('import re') out.append('from collections import namedtuple') out.append('') out.append('') out.append('PropDef = namedtuple(') out.append(' "PropDef",') out.append(' "name kind default lo hi enum_labels enum_values "') out.append(' "display model_only")') out.append('') out.append('EVENTS = (%s)' % ", ".join(_py_str(e) for e in EVENTS)) out.append('') generic = [ {"name": "name", "kind": "Str", "default": "", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, {"name": "left", "kind": "Int", "default": "0", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, {"name": "top", "kind": "Int", "default": "0", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, {"name": "width", "kind": "Int", "default": "100", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, {"name": "height", "kind": "Int", "default": "30", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, ] generic.extend(tables["common"]) for name, kind, default, lo, hi, labels in GENERIC_EXTRAS: generic.append({"name": name, "kind": kind, "default": default, "lo": float(lo), "hi": float(hi), "labels": labels.split("|") if labels else None, "values": None}) out.extend(_emit_table("GENERIC_PROPS", "common", generic)) out.append('') out.append('GENERIC_NAMES = frozenset(p.name for p in GENERIC_PROPS)') out.append('') tables.update(EXTRA_TABLES) used = [] for kind in kinds: table = KIND_TABLE.get(kind) if table and table not in used: used.append(table) for table in used: out.extend(_emit_table(table.upper() + "_PROPS", table, tables[table])) out.append('') out.append('# palette kind -> custom (non-generic) props tuple') out.append('CUSTOM_PROPS = {') for kind in kinds: table = KIND_TABLE.get(kind) if table: out.append(' %s: %s_PROPS,' % (_py_str(kind), table.upper())) out.append('}') out.append('') out.append('# Registry names (GtkButton, TButton, ...) resolve through') out.append('# the palette; this is the kind-level custom table only.') out.append('_CUSTOM_BY_KIND = dict(CUSTOM_PROPS)') out.append('') out.append('') out.append('def props_for(kind_or_name):') out.append(' """Full table (generic + custom) for a palette kind or') out.append(' a registry name (e.g. "GtkButton" or "Button").') out.append(' Unknown names get the generic set only."""') out.append(' kind = _resolve_kind(kind_or_name)') out.append(' custom = _CUSTOM_BY_KIND.get(kind, ())') out.append(' seen = {p.name for p in custom}') out.append(' return tuple(p for p in GENERIC_PROPS') out.append(' if p.name not in seen) + tuple(custom)') out.append('') out.append('') out.append('def custom_props_for(kind_or_name):') out.append(' """Custom (non-generic) props only, or () if none."""') out.append(' return _CUSTOM_BY_KIND.get(_resolve_kind(kind_or_name), ())') out.append('') out.append('') out.append('def prop_names(kind_or_name):') out.append(' return frozenset(p.name for p in props_for(kind_or_name))') out.append('') out.append('') out.append('def find_prop(kind_or_name, name):') out.append(' for prop in props_for(kind_or_name):') out.append(' if prop.name == name:') out.append(' return prop') out.append(' return None') out.append('') out.append('') out.append('def is_model_only(kind_or_name, name):') out.append(' prop = find_prop(kind_or_name, name)') out.append(' return bool(prop.model_only) if prop is not None else False') out.append('') out.append('') out.append('def register_custom_table(kind, props):') out.append(' """Add/replace the custom table for one palette kind.') out.append(' Phase 6 uses this for the Stock / Instrumentation') out.append(' families; it never touches the generated tables."""') out.append(' _CUSTOM_BY_KIND[str(kind)] = tuple(props)') out.append('') out.append('') out.append('def _resolve_kind(kind_or_name):') out.append(' name = str(kind_or_name)') out.append(' if name in _CUSTOM_BY_KIND or name in _ALL_KINDS:') out.append(' return name') out.append(' try:') out.append(' from lightgui.xframe import palette as _palette') out.append(' entry = _palette.find(name)') out.append(' if entry is not None:') out.append(' return entry.kind') out.append(' except Exception:') out.append(' pass') out.append(' return name') out.append('') out.append('') out.append('def validate(kind_or_name, name, value):') out.append(' """Validate *value* against the table for *kind* and') out.append(' return its canonical string form. Raises ValueError') out.append(' for an unknown prop, a bad bool/int/double, an enum') out.append(' label or value outside its range."""') out.append(' prop = find_prop(kind_or_name, name)') out.append(' if prop is None:') out.append(' raise ValueError("unknown property %r for %r"') out.append(' % (name, kind_or_name))') out.append(' return _canonical(prop, value)') out.append('') out.append('') out.append('def _canonical(prop, value):') out.append(' kind = prop.kind') out.append(' if kind == "Bool":') out.append(' if isinstance(value, bool):') out.append(' return "true" if value else "false"') out.append(' text = str(value).strip().lower()') out.append(' if text in ("true", "1", "yes", "on"):') out.append(' return "true"') out.append(' if text in ("false", "0", "no", "off"):') out.append(' return "false"') out.append(' raise ValueError("not a bool: %r" % (value,))') out.append(' if kind == "Int":') out.append(' try:') out.append(' number = int(str(value).strip())') out.append(' except (TypeError, ValueError):') out.append(' raise ValueError("not an int: %r" % (value,))') out.append(' if prop.lo or prop.hi:') out.append(' if number < prop.lo or number > prop.hi:') out.append(' raise ValueError(') out.append(' "%s out of range %d..%d: %r"') out.append(' % (prop.name, prop.lo, prop.hi, value))') out.append(' return str(number)') out.append(' if kind == "Double":') out.append(' try:') out.append(' number = float(str(value).strip())') out.append(' except (TypeError, ValueError):') out.append(' raise ValueError("not a number: %r" % (value,))') out.append(' if prop.lo or prop.hi:') out.append(' if number < prop.lo or number > prop.hi:') out.append(' raise ValueError(') out.append(' "%s out of range %s..%s: %r"') out.append(' % (prop.name, prop.lo, prop.hi, value))') out.append(' return "%g" % number') out.append(' if kind == "Enum":') out.append(' text = str(value).strip()') out.append(' if prop.enum_labels and text in prop.enum_labels:') out.append(' return str(prop.enum_values[') out.append(' prop.enum_labels.index(text)]') out.append(' if prop.enum_values else text)') out.append(' try:') out.append(' number = int(text)') out.append(' except ValueError:') out.append(' raise ValueError("not an enum value: %r" % (value,))') out.append(' if prop.enum_values and number not in prop.enum_values:') out.append(' raise ValueError("enum value out of range: %r"') out.append(' % (value,))') out.append(' return str(number)') out.append(' if kind == "Color":') out.append(' return _canonical_color(str(value))') out.append(' return "" if value is None else str(value)') out.append('') out.append('') out.append('def _canonical_color(text):') out.append(' text = text.strip()') out.append(' if not text:') out.append(' return ""') out.append(' if text.startswith("#") and len(text) in (4, 7, 9):') out.append(' digits = text[1:]') out.append(' if all(c in "0123456789abcdefABCDEF" for c in digits):') out.append(' return text.lower()') out.append(' match = re.match(r"rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)",') out.append(' text)') out.append(' if match:') out.append(' r, g, b = (int(v) for v in match.groups())') out.append(' if max(r, g, b) <= 255:') out.append(' return "rgb(%d,%d,%d)" % (r, g, b)') out.append(' if text.lower() in _NAMED_COLORS:') out.append(' return text.lower()') out.append(' raise ValueError("not a color: %r" % (text,))') out.append('') out.append('') out.append('_NAMED_COLORS = frozenset([') out.append(' "black", "white", "red", "green", "blue", "yellow",') out.append(' "orange", "purple", "teal", "magenta", "brown", "gray",') out.append(' "grey", "pink", "cyan", "transparent"])') out.append('') out.append('_ALL_KINDS = frozenset(%s)' % _py_list(kinds)) out.append('') (REPO / "lightgui" / "props.py").write_text( "\n".join(out) + "\n", encoding="utf-8") print("gen_props: wrote lightgui/props.py: %d kinds, %d custom tables" % (len(kinds), len(used))) def _py_list(values): return "(%s)" % ", ".join(_py_str(v) for v in values) if __name__ == "__main__": main()