Properties view: every slot of a component, edited in the editor pane

Right-click a component on the wiresheet or in the tree and Properties takes
over the editor pane, listing every slot the manifest declares rather than the
handful a box paints. Config slots that are not @readonly are white and
editable; everything else is grey.

Rows are built from the slot's facets, read against SedonaDoc/niagara.html:
@trueText/@falseText, @range, @precision, @unit, and @min/@max, which bound
what Save accepts. Three facets it had wrong:

  - null is a value, not an absence. control::WriteFloat pairs 'in' with a
    setNull action and the sample app stores val="null" on four of them, so
    null now shows, parses back, and reads as @nullText where declared.
  - @min/@max on a Buf count characters. TcpDevice.ipAddr is a Buf(17) with
    @max 16; a longer string is refused rather than overrunning the device.
  - an int's implicit range is noise. [-2147483648 - 2147483647] said no more
    than "a whole number", so only byte and short print a range they did not
    declare.

meta gets a row of its own: the '>>' opens its user groups as checkboxes and
its position as x and y, since typing 822411269 into a field sets neither.

Save writes only the rows that moved, as one undoable SlotValueCommand, and
refuses the lot if any row fails its range check. An edited field paints the
view in the canvas's own dirty tint, and every way of leaving asks before
discarding.

The file name on the tree's root row goes red while anything is unwritten,
counting both a dirty document and unsaved fields. Two things this needed:
the nav tree runs on its own style, because a themed Treeview's selected
foreground beats a row tag's; and the tag is added to or removed from the row
rather than recoloured, because reconfiguring a tag does not repaint rows that
are already drawn.

Also fixes a latent hazard the panel exposed: Del and Backspace are bound
application-wide, so they now stand down while a text field has focus rather
than deleting the component behind it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-05 23:38:03 +03:00
co-authored by Claude Opus 5
parent 5fde6473a0
commit 2db230dec1
8 changed files with 1675 additions and 15 deletions
+203 -7
View File
@@ -5,7 +5,7 @@ component hierarchy as a navigation tree, paints the selected folder's children
wiresheet of draggable component boxes, draws the links between them, and writes box
positions back into each component's `meta` property on save.
Current version: **0.0.0.024** (see [Versioning](#versioning)).
Current version: **0.0.0.048** (see [Versioning](#versioning)).
## Requirements
@@ -49,13 +49,14 @@ not inside the window. Tk always hands it to the system menu bar.
| `schema.py` | Kit manifest loading, slot inheritance, slot visibility rules | no |
| `undo.py` | Undo/redo stack of reversible DOM commands | no |
| `wiresheet.py` | Grid, component boxes, link routing and painting | yes |
| `properties.py` | The Properties view: every slot of one component, read and written | yes |
| `sax_file.py` | Open/save, navigation tree, cascading delete | yes |
| `main.py` | Widgets, menus, event handlers, dialogs, main loop | yes |
| `run.py` | Entry point | yes |
Imports form a DAG — `sax_dom`/`schema` depend on nothing UI-shaped, `wiresheet` and
`sax_file` build on them, `main` wires it together. Event handlers live in `main`,
which is what keeps the graph acyclic.
`sax_file` build on them, `properties` builds on `schema` and `undo`, and `main` wires it
together. Event handlers live in `main`, which is what keeps the graph acyclic.
### Shared state
@@ -70,7 +71,8 @@ invisible to every other module. Every mutation of "the document changed" goes t
`MetaMoveCommand` (a box drag, or a whole Tidy Layout as one step), `AddComponentCommand`
(which also removes the `<kit>` entry placing it may have added) and
`DeleteComponentCommand` (which restores the removed `<link>` entries at their original
indices, reinserting in ascending order so the indices stay valid). Nothing in
indices, reinserting in ascending order so the indices stay valid) and `SlotValueCommand`
(one Save from the Properties view, however many slots it changed). Nothing in
`undo.py` touches Tk; `main` registers a refresh callback at startup, which is what keeps
`sax_file` and `wiresheet` free to push commands without an import cycle.
@@ -131,11 +133,183 @@ walk cannot rewrite the trail it is following.
### The component popup
Right-clicking a component offers the same actions from the wiresheet and from the
navigation tree -- Delete Component, Link Mark, and Link From / Link To naming the marked
component once one is marked. `fill_component_popup` builds both, and its entries close
navigation tree -- Properties, Delete Component, Link Mark, and Link From / Link To naming
the marked component once one is marked. `fill_component_popup` builds both, and its entries close
over the component rather than reading a selection back, which is what lets each popup act
on the row or box that was actually clicked. The tree's root row keeps its own popup.
### The Properties view
**Properties**, from either component popup, **takes over the editor pane** -- the sheet
and the slot table are the same piece of screen, so only one of them is ever the thing
being looked at. The canvas is unpacked, never destroyed, so it keeps its items and its
scroll position and **Close** puts it back exactly as it was. It is still painted while it
is hidden, which costs nothing and means there is no catching up to do when it returns.
Choosing a node in the tree means "show me that sheet", so it stands the view down rather
than leaving the selection looking like it did nothing. So does deleting the component it
is showing, from anywhere -- every delete in the UI goes through `delete_component`,
because `sax_file` does its own view refresh rather than going through `refresh_all_views`.
It lists **every** slot the manifest declares,
in manifest order, each row numbered with the same slot id the wiresheet box uses. The
box's visibility rules do not apply here: they are right for a diagram and wrong for the
one place a value is meant to be changed, so `HvacControl` shows all 47 rows rather than
the 8 its box paints.
The header names the component, its type and its **absolute path** -- the same path a
`<link>` writes, and the one thing on screen that separates this `Cascade` from the three
others in the file. It is read from the document rather than held, so a renamed parent
shows up on the next Refresh.
Each row carries the slot's declared type between its name and its value, written the way
a slot sheet writes it: the manifest stores the primitives bare and everything else already
qualified, so `int` is shown as `sys::int` and `sys::Buf` is left as it stands.
Which rows can be typed into is the slot's own business, not the view's:
| Slot | Field |
|---|---|
| config (`c` flag) and not `@readonly` | white, editable |
| everything else | grey, read-only |
A runtime slot holds a live value that no offline file carries, so nothing here could
usefully write one; a `@readonly` config slot is the manifest saying the same about a
value that *is* persisted. Both read the same way on screen.
Each row is drawn from the slot's facets, so it reads the way the kit author meant it to:
- `@trueText` / `@falseText` turn a bool into its own two words -- `Disabled` / `Enabled`
rather than false / true -- in a dropdown, with a red or green dot beside it.
- **Null is a value, not an absence.** Sedona models it as NaN for a float and a sentinel
for the integer types, and a config slot can genuinely hold it: `control::WriteFloat`
pairs an `in` property with a `setNull` action, and the sample app carries
`<prop name="in" val="null"/>` on four of them. So `null` shows against a blue dot,
types back in as `null`, and reads as `@nullText` where a kit declared one --
`ontrolBaseDriver::DeviceNetwork.status` calls it `Disabled`. `@allowNull false` is the
one case that refuses it, and takes it out of a bool's dropdown.
- `@range` turns an integer slot into a named dropdown; the file still stores the index.
- `@precision` fixes how many decimals a float shows, `@unit` puts the symbol after the
field (`celsius` reads `°C`).
- `@min` / `@max` bound what Save will accept, and are shown as `[0 - 1000]`. A row prints
a range when the manifest declared one, and otherwise only where the **type** supplies a
narrow one: `byte` reads `[0 - 255]` and `short` reads `[0 - 65535]` unfaceted, because
those bounds are worth knowing. An `int`, a `long` or a float prints nothing, since its
full span means no more than "a whole number" and crowds the row to say it -- and an end
those types leave undeclared prints as `-inf` / `+inf` rather than reaching for the
type. This is display only: Save still holds every integer to its type, so an `int` of
`9999999999` is rejected whether or not its row advertised the limit.
- On a **`Buf`** those same two facets count *characters*, not magnitude, and the count is
what the buffer can hold: `TcpDevice.ipAddr` is a `Buf(17)` declaring `@max 16`, the
seventeenth byte being the null terminator. The row reads `[max 16 chars]` and Save
refuses a longer string -- overrunning a Buf is not a display problem, the device gets a
string it has no room for.
The value shown is the file's `<prop>`, or the manifest default when the file carries
none, or the type's zero when the manifest declares none either. Runtime slots reach the
view through that second and third step, which is why they read `0.0` here and `null` on
the wiresheet: the box is reporting what the file says, and this is reporting what the
device would start from.
`meta` gets a row of its own rather than an editable integer: typing 822411269 into a
field is no way to set either of the two unrelated things it packs. The `»` beside it
opens them apart -- the four user group bits as checkboxes, and the position as x and y,
which a drag would otherwise be the only way to set. Both are in grid units, the figure
`meta_scale` multiplies to reach pixels, and each is one byte, so the editor holds them to
0-255. The row shows the groups it summarises and the position beside them.
Saving a changed meta writes the position first and the groups second, because each pass
preserves what the other owns: the position pass keeps the group bits it reads, and the
group pass keeps the position it was just handed.
The table is laid out at its natural width and never stretched. Every widget is gridded
straight into one frame, so grid's own column sizing is what lines the four columns up
across the rows, and no column carries a weight -- widening the view shows more white to
the right of the table instead of walking the fields across it, and narrowing it scrolls
sideways rather than squeezing them. Each scrollbar appears only while it has somewhere to
scroll; `Shift` + wheel scrolls sideways.
### The file name goes red
While anything is unwritten, the file name on the tree's **root row** turns
`DIRTY_NAME_COLOUR`. That row is the only place a file name appears on screen -- a Tk
window title cannot be coloured.
The tag's colour is configured **once**, when the tree is built, and never changed; what
moves is whether the row carries the tag. Reconfiguring a tag does not reliably repaint
rows that are already drawn, so a version that recoloured the tag went red only on the
paths that happened to rebuild the tree -- a Properties Save did, dragging a box did not,
and the two disagreed in a way that looked like the drag was not marking anything dirty at
all. Setting a row's tags repaints that row, so the colour cannot fall behind the state.
`anything_unwritten()` is the whole rule, and it counts **both**: the document being dirty,
and the Properties view holding edits its Save has not been pressed for. A typed value is
as unwritten as a dragged box, and a name that only went red for the second of those would
be telling half the story. So it goes red the moment a field is edited, before anything has
reached the document, and comes back when the edit is typed away, discarded, or saved and
written.
The navigation tree runs on a style of its own, `NAV_TREE_STYLE`, for one reason: a themed
Treeview maps the selected state to `SystemHighlightText`, and **that mapping beats a row
tag's own foreground**. The name turned white-on-blue the moment its row was selected --
which is exactly when the root sheet is the one being looked at, so the red was invisible
in the most ordinary case. The style drops the selected foreground entry altogether and
takes a light selection background instead, so a tag's colour shows in every state and
plain black still reads on the highlight. Scoped to this tree, so the palette keeps the
system selection.
`app_state.refresh_dirty_display()` is the single funnel, called from `mark_dirty` and
`mark_clean` through a callback `main` registers -- the same shape `undo` uses for its view
refresh, and what keeps `app_state` free of any idea that a Properties view exists.
### Unsaved edits in the Properties view
An edited field paints the whole view in **`app_state.DIRTY_TINT`** -- the same colour
the canvas wears when the file is dirty, now one constant rather than two spellings of
`#ffe6e6`, so "there is something here you have not written yet" looks the same wherever
the change was made. The fields themselves keep their own white or grey: whether a value
*can* be typed into is a different thing from whether it *has* been.
Dirtiness is read from the widgets rather than tracked as a flag, so typing a value and
then typing it back leaves the view clean -- it is exactly the set of rows Save would
write. The tint follows the fields live, and comes off on Save and on Refresh.
Every way of leaving the view goes through `close_properties`, so the question is asked
once, in one place: **Close**, picking another sheet in the tree, walking **Back** or
**Forward**, or right-clicking a different component. The box has three answers rather
than two, because "I did not mean to leave" and "leave, I did not want those edits" are
different things and a two-way box makes the user guess which one Cancel is. A Save that
fails its range checks keeps the view open, since leaving then would discard exactly the
values being complained about.
Refusing to leave has to put the tree back on the sheet that is still showing. The
**element** is held for that, not the tree item id, for the same reason the history holds
elements: a rebuild of the tree hands out fresh ids. ttk queues its selection event rather
than dispatching it, so the flag that stops the restoring selection being read as a fresh
choice is cleared from an `after_idle` rather than inline.
Nothing asks when the question has nowhere to go -- the component deleted, a different
file opened. Those go straight to `dismiss_properties`, which is also what the panel's own
Close calls once the question has been put and answered.
Discarded edits are discarded: the panel is destroyed, and the next one is built from the
document, so it opens on the file's values with no tint.
**Save** writes the edited rows into the DOM and pushes them as **one** undoable step, so
a dozen changed slots undo together. Only rows whose text actually moved are written, so a
component keeps exactly the props the file gave it plus the ones edited here -- and if any
edited row fails its range check, *nothing* is written and the view names every offending
row at once. Save changes the document, not the file; `Ctrl`/`Cmd` + `S` still writes the
`.sax`. **Refresh** re-reads every row from the DOM, discarding pending edits, which is
also how the view catches up after an undo.
`Del` and `Backspace` are bound application-wide, so they also reach a field being typed
in. `delete_selected_component` therefore ignores the key while the Properties view is up,
while focus is in another window, and while it is in any widget that owns the keyboard --
an `Entry`, a `TCombobox`, a `Text`. A backspace aimed at a text field must never delete a
component. Save still checks the component is in the document before writing, since an
undo can take it out from under the view.
### Following a link to its other sheet
Right-clicking a wire or a knob offers **Go to Link Wire Sheet "<name>"** alongside Delete
@@ -250,6 +424,27 @@ disturbs the rest of the value.
Wires and knobs are painted behind the component boxes and re-routed on every drag
step, since they are not part of the dragged canvas group.
### Facets this does not act on
Read against `SedonaDoc/niagara.html`, which is what tells Niagara -- and so this view
-- how to model a slot. These are recognised there and deliberately not acted on here:
| Facet | Where it is used | Why not |
|---|---|---|
| `hidden` | 129 slots, every one a `void` action such as `HdwAI.checkType` | The doc says user interfaces should rarely display hidden slots, and the reference tool appears not to. This view shows every slot because that is what it is for; say the word and it will skip them. |
| `fieldWidth` | 3082 slots | A per-slot column count for the text field. Applying it would make the value column ragged; a table reads better with one width. |
| `radix`, `showSeparators`, `multiLine`, `fieldEditor` | unused by any kit under Sedona home | Nothing to render. |
And two things worth knowing about the manifests themselves rather than the code:
- 24 slots declare **`readOnly`** with a capital O. Niagara matches flag names exactly, so
it is not the `readonly` flag and does nothing there either -- it is stored as an
ordinary facet. Every one of them is a runtime slot, so they are already grey here for
the other reason, and honouring the typo would change nothing on screen.
- 118 **config `Buf`** slots omit `@asStr`, so by the letter of `components.html` they
serialise as base64 rather than text. Their names (`text`, `trueText`, `buttonText`) say
otherwise, so they are edited as text here.
## Versioning
`VERSION` lives in `app_state.py` and is shown in the window title.
@@ -266,4 +461,5 @@ step, since they are not part of the dragged canvas group.
outside those three is not reversible.
- `on_canvas_release` snaps using the rounded-rectangle polygon's first coordinate,
which is `x1 + radius` rather than `x1`, so snapping is offset by the corner radius.
- Slot values are display-only; there is no editing of a slot from the wiresheet.
- Slot values are edited from the Properties view only; a wiresheet box row is still
display-only.
+42 -3
View File
@@ -8,7 +8,7 @@ so later rebinding would only ever be seen by the module that did it.
import configparser
import os
VERSION = "0.0.0.036"
VERSION = "0.0.0.048"
PROPERTIES_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "editor.properties")
DEFAULT_GRID_SIZE = 10
DEFAULT_ADD_TIMESTAMP = True
@@ -26,12 +26,43 @@ DEFAULT_LEFT_PANE_WIDTH = 230
MIN_ALLOWED_LEFT_PANE_WIDTH = 120
MAX_ALLOWED_LEFT_PANE_WIDTH = 600
# Called whenever "is there anything unwritten" may have changed, so the file name on
# the tree can follow it. main registers it; anything before that is a no-op.
dirty_display_callback = None
# Widget handles, filled in by main once the UI exists
window = None
canvas = None
tree = None
status_label = None # the window's bottom status bar
# The unsaved-state tint. The wiresheet paints it on the canvas and the Properties view
# paints it on itself, so "there is something here you have not written yet" is one
# colour wherever the change was made.
DIRTY_TINT = "#ffe6e6"
CLEAN_TINT = "white"
# The file name on the tree's root row turns this colour while anything is unwritten,
# which is the one place a file name appears on screen -- a Tk window title cannot be
# coloured.
#
# The tag's colour is configured once and never changed; what moves is whether the row
# carries the tag. Reconfiguring a tag does not reliably repaint rows that are already
# drawn -- which is why the name only ever went red on the paths that happened to rebuild
# the tree, and stayed black after a box was dragged. Setting a row's tags repaints that
# row, so the two states cannot drift apart.
DIRTY_NAME_COLOUR = "#c00000"
DIRTY_NAME_TAG = "unsaved_file"
# A themed Treeview maps the selected state to SystemHighlightText, and that mapping beats
# a row tag's own foreground -- so the file name turned white-on-blue the moment its row
# was selected, which is exactly when the root sheet is the one being looked at. The
# navigation tree therefore runs on a style of its own that drops the selected foreground
# and picks a light selection background instead, so a tag's colour shows in every state
# and black text still reads on the highlight.
NAV_TREE_STYLE = "Nav.Treeview"
NAV_SELECTION_BG = "#cce4f7"
# Status bar tones. A hint that something needs attention later is worth a colour, so a
# placement that leaves the schema out of step is not read as a plain confirmation.
STATUS_INFO_COLOUR = "#333333"
@@ -148,13 +179,20 @@ def clear_status():
set_status("")
def refresh_dirty_display():
"""Nudges whatever shows 'there is something unwritten'. A no-op before the UI exists."""
if dirty_display_callback is not None:
dirty_display_callback()
def mark_dirty():
"""Single funnel for 'the document changed', including the unsaved-state tint."""
global is_dirty
if not is_dirty:
is_dirty = True
if canvas is not None:
canvas.config(bg="#ffe6e6")
canvas.config(bg=DIRTY_TINT)
refresh_dirty_display()
def mark_clean():
@@ -162,7 +200,8 @@ def mark_clean():
global is_dirty
is_dirty = False
if canvas is not None:
canvas.config(bg="white")
canvas.config(bg=CLEAN_TINT)
refresh_dirty_display()
SEDONA_HOME, GRID_SIZE, ADD_TIMESTAMP, BOX_WIDTH, LEFT_PANE_WIDTH = load_preferences()
+215 -2
View File
@@ -8,6 +8,7 @@ from tkinter import filedialog, font as tkfont, messagebox, ttk
import app_state
import manage_kits
import palette
import properties
import sax_file
import schema
import undo
@@ -36,6 +37,10 @@ MIN_WINDOW_HEIGHT = 300
# children, so a session touches few of them; the cap only stops an unbounded list.
HISTORY_LIMIT = 50
# Tk class names of the widgets that own the keyboard while they have focus. Del and
# Backspace mean "edit this text" in each of them, never "delete the selected component".
TEXT_ENTRY_CLASSES = ("Entry", "TEntry", "TCombobox", "Text", "Spinbox", "TSpinbox")
MENU_BACK_LABEL = "Back"
MENU_FORWARD_LABEL = "Forward"
@@ -57,12 +62,167 @@ zoom_label = None
menu_view = None
show_left_column_var = None
# The Properties view takes the editor pane over from the canvas rather than floating
# above it, so at most one of them is on screen and this is which. None means the sheet.
properties_panel = None
# The sheet to put the tree back on when a sheet change is refused because of unsaved
# edits, and the flag that stops the restoring selection from being read as a fresh
# choice. The element is held rather than the tree item id, for the same reason the
# history holds elements: a rebuild of the tree hands out fresh ids.
properties_return_sheet = None
_restoring_selection = False
def anything_unwritten():
"""Whether there is a change no one has written yet, in the document or in a field.
The Properties view counts before its Save: a typed value is as unwritten as a
dragged box, and a file name that only went red on the second of those would be
telling half the story.
"""
if app_state.is_dirty:
return True
return properties_panel is not None and properties_panel.dirty
def refresh_dirty_display():
"""Puts the file name on the tree's root row in red, or back to its usual colour.
The tag is added to or taken off the row rather than having its colour reconfigured.
Reconfiguring a tag does not reliably repaint rows already on screen, so the name
only turned red on the paths that happened to rebuild the tree -- a Properties Save
did, dragging a box did not.
"""
tree = app_state.tree
if tree is None:
return
rows = tree.get_children()
if not rows:
return
root_row = rows[0]
wanted = (app_state.DIRTY_NAME_TAG,) if anything_unwritten() else ()
if tuple(tree.item(root_row, "tags")) != wanted:
tree.item(root_row, tags=wanted)
def refresh_all_views():
"""Rebuilds tree and canvas from the DOM. Registered as undo/redo's view refresh."""
sax_file.refresh_treeview_from_dom(app_state.xml_root_element)
wiresheet.render_current_sheet()
# An undo or a cascading delete can take the component the Properties view is showing
# out of the document underneath it. Nothing it could display then would be true.
if properties_panel is not None and not _component_in_document(properties_panel.comp):
close_properties(force=True)
def _component_in_document(comp):
root = app_state.xml_root_element
return root is not None and any(element is comp for element in root.iter())
def delete_component(comp):
"""Deletes a component, taking its Properties view down with it if one is showing.
Every delete in the UI comes through here. sax_file does its own view refresh rather
than going through refresh_all_views, so the panel would otherwise be left describing
a component the document no longer has.
"""
showing = properties_panel is not None and properties_panel.comp is comp
if sax_file.execute_cascading_deletion(comp) and showing:
close_properties(force=True)
def show_properties(comp):
"""Puts one component's slots in the editor pane, in place of the wiresheet.
The canvas is only unpacked, never destroyed, so the sheet keeps its items and its
scroll position and comes back exactly as it was. It is still painted while it is
hidden -- a Save here repaints it -- which costs nothing and means there is no
catching up to do when it returns.
"""
global properties_panel, properties_return_sheet
if comp is None:
return
# Right-clicking a second component is a way of leaving the first, so it asks about
# unsaved edits exactly as Close does, and a refusal leaves the first one showing.
if not close_properties():
return
properties_return_sheet = app_state.current_sheet_parent
canvas_vscroll.pack_forget()
canvas_hscroll.pack_forget()
app_state.canvas.pack_forget()
properties_panel = properties.build_properties_panel(
frame_editor, comp, on_change=refresh_all_views, on_close=dismiss_properties,
on_dirty_change=refresh_dirty_display,
)
properties_panel.frame.pack(fill=tk.BOTH, expand=True)
app_state.set_status(f"Properties: {comp.get('name', '?')}")
def dismiss_properties(restore_canvas=True):
"""Takes the Properties view down and gives the pane back, asking nothing.
The panel's own Close is what asks; by the time it calls this the question has been
put and answered. Anything that has made the view moot -- the component deleted, the
file closed -- comes straight here too.
"""
global properties_panel
if properties_panel is None:
return
properties_panel.destroy()
properties_panel = None
refresh_dirty_display()
if restore_canvas:
# Repacked in the order the pane was built in, so the scrollbars keep their edges.
canvas_vscroll.pack(side=tk.RIGHT, fill=tk.Y)
canvas_hscroll.pack(side=tk.BOTTOM, fill=tk.X)
app_state.canvas.pack(fill=tk.BOTH, expand=True)
app_state.clear_status()
def close_properties(force=False):
"""Asks about unsaved edits, then takes the view down. True if the pane is now free.
Every way of leaving the Properties view goes through this, so "you have not saved
that" is asked once, in one place, whether the user pressed Close, picked another
sheet, walked the history or opened a different component.
"""
if properties_panel is None:
return True
if force:
dismiss_properties()
return True
return bool(properties_panel.close())
def _restore_tree_selection():
"""Puts the tree back on the sheet that is actually showing, after a refused change."""
global _restoring_selection
item_id = _tree_item_for_element(properties_return_sheet)
if item_id is None:
return
_restoring_selection = True
app_state.tree.selection_set(item_id)
# ttk queues its selection event rather than dispatching it, so the flag has to
# outlive this call or the restoring selection is read as a fresh choice.
app_state.window.after_idle(_clear_restoring_flag)
def _clear_restoring_flag():
global _restoring_selection
_restoring_selection = False
def do_undo(event=None):
label = undo.undo()
@@ -218,6 +378,16 @@ def on_canvas_wheel_zoom(event):
def on_tree_select(event):
"""Triggered when a branch node is clicked in the Navigation view."""
if _restoring_selection:
return
# Choosing a node means "show me that sheet", so the Properties view stands down
# rather than leaving the selection looking like it did nothing. Refusing to leave
# has to put the tree back on the sheet that is still showing.
if not close_properties():
_restore_tree_selection()
return
tree = app_state.tree
selected_items = tree.selection()
if not selected_items:
@@ -380,6 +550,19 @@ def select_link_on_open_sheet(link_elem):
def delete_selected_component(event=None):
"""Deletes the highlighted canvas component (or selected link) and all its descendants recursively."""
# Del is bound application-wide, so it also reaches a Properties field being typed in
# and every other window. A keystroke aimed at a text field must not delete a
# component, and neither must one pressed while the sheet is not even on screen.
if properties_panel is not None:
return
focused = app_state.window.focus_get()
if focused is not None:
if focused.winfo_toplevel() is not app_state.window:
return
if focused.winfo_class() in TEXT_ENTRY_CLASSES:
return
if app_state.selected_link_tag:
delete_selected_link()
return
@@ -389,7 +572,7 @@ def delete_selected_component(event=None):
comp_element = app_state.canvas_comp_map.get(app_state.selected_canvas_tag)
if comp_element is not None:
sax_file.execute_cascading_deletion(comp_element)
delete_component(comp_element)
def on_tree_right_click(event):
@@ -676,9 +859,14 @@ def fill_component_popup(menu, comp):
that was actually clicked.
"""
menu.delete(0, tk.END)
menu.add_command(
label="Properties",
command=lambda: show_properties(comp),
)
menu.add_separator()
menu.add_command(
label="Delete Component",
command=lambda: sax_file.execute_cascading_deletion(comp),
command=lambda: delete_component(comp),
)
menu.add_separator()
menu.add_command(label="Link Mark", command=lambda: set_link_mark(comp))
@@ -1072,6 +1260,8 @@ def _show_sheet_history_entry(position):
def go_back(event=None):
"""View menu and toolbar: step to the previously opened sheet."""
if not close_properties():
return "break"
_prune_sheet_history()
if history_index > 0:
_show_sheet_history_entry(history_index - 1)
@@ -1082,6 +1272,8 @@ def go_back(event=None):
def go_forward(event=None):
"""View menu and toolbar: step back towards the most recently opened sheet."""
if not close_properties():
return "break"
_prune_sheet_history()
if 0 <= history_index < len(sheet_history) - 1:
_show_sheet_history_entry(history_index + 1)
@@ -1099,6 +1291,13 @@ def on_tree_filled():
"""
global _history_file_path
# A different file has no such component, and a rebuild after a delete may have taken
# it. Neither is a moment to ask about edits that now have nowhere to go.
if properties_panel is not None and not _component_in_document(properties_panel.comp):
close_properties(force=True)
# The root row is new after every rebuild, so its colour has to be reapplied.
refresh_dirty_display()
fit_tree_column(app_state.tree)
if app_state.current_file_path != _history_file_path:
@@ -1536,12 +1735,25 @@ left_pane = ttk.PanedWindow(paned_window, orient=tk.VERTICAL)
frame_tree = ttk.Frame(left_pane)
_nav_style = ttk.Style()
_nav_style.map(
app_state.NAV_TREE_STYLE,
# No ("selected", ...) entry: without one the row keeps whatever foreground its tag
# gives it, which is the whole point.
foreground=[("disabled", "SystemGrayText")],
background=[("disabled", "SystemButtonFace"),
("selected", app_state.NAV_SELECTION_BG)],
)
tree = ttk.Treeview(
frame_tree,
show="tree",
selectmode="browse",
height=TREE_REQUESTED_ROWS,
style=app_state.NAV_TREE_STYLE,
)
# Configured once, for the life of the tree. Only the row's tags change after this.
tree.tag_configure(app_state.DIRTY_NAME_TAG, foreground=app_state.DIRTY_NAME_COLOUR)
app_state.tree = tree
attach_tree_scrollbars(frame_tree, tree)
tree.bind("<<TreeviewSelect>>", on_tree_select)
@@ -1777,6 +1989,7 @@ canvas.bind("<Control-Button-5>", do_zoom_out)
paned_window.add(frame_editor, weight=3)
app_state.dirty_display_callback = refresh_dirty_display
undo.set_refresh_callback(refresh_all_views)
sax_file.set_tree_filled_callback(on_tree_filled)
refresh_palette_kits()
+1075
View File
File diff suppressed because it is too large Load Diff
+57
View File
@@ -26,6 +26,34 @@ def restore_children(element, snapshot):
element.append(copy.deepcopy(child))
def set_prop_value(element, name, value):
"""Writes a component's <prop>, creating it in the block the other props sit in.
A .sax keeps every <prop> ahead of the child <comp> elements, and ET.SubElement
would append past them, so a new prop is inserted after the last existing one
instead. That is cosmetic to a parser and not to a human reading the diff.
"""
prop = element.find(f"prop[@name='{name}']")
if prop is not None:
prop.set("val", value)
return prop
prop = ET.Element("prop", name=name, val=value)
last_prop_index = -1
for index, child in enumerate(element):
if child.tag == "prop":
last_prop_index = index
element.insert(last_prop_index + 1, prop)
return prop
def remove_prop(element, name):
"""Drops a component's <prop>, for undoing a value that the file never carried."""
prop = element.find(f"prop[@name='{name}']")
if prop is not None:
element.remove(prop)
def read_meta_property(meta_str):
"""Parses 32-bit meta property integer fields via structured byte extraction rules."""
if meta_str is None or not meta_str:
@@ -77,6 +105,35 @@ def update_meta_property(element, meta_str, raw_x, raw_y):
meta_prop.set("val", str(new_val))
def update_meta_groups(element, meta_str, groups):
"""Rewrites only meta's four user-group bits, leaving the packed position alone.
The mirror of update_meta_property, which rewrites only x and y. Both exist because
meta is one integer carrying two unrelated things, and an editor that touches one of
them must not disturb the other.
"""
raw_x, raw_y, reserved, _, _, _, _, ug_res = read_meta_property(meta_str)
user_group_byte = 0
for bit, on in enumerate(groups[:4]):
if on:
user_group_byte |= (1 << bit)
user_group_byte |= (ug_res & 0x0F) << 4
new_val = (
((raw_x & 0xFF) << 24) |
((raw_y & 0xFF) << 16) |
((reserved & 0xFF) << 8) |
(user_group_byte & 0xFF)
)
meta_prop = element.find("prop[@name='meta']")
if meta_prop is None:
meta_prop = ET.SubElement(element, "prop", name="meta")
meta_prop.set("val", str(new_val))
def find_parent_element(root_elem, child_to_find):
"""Traverses the XML DOM tree recursively to find the parent element of a given element."""
for parent in root_elem.iter():
+2
View File
@@ -61,6 +61,8 @@ def refresh_treeview_from_dom(xml_root):
return
file_name = os.path.basename(app_state.current_file_path)
# Inserted plain. refresh_dirty_display puts the unsaved tag on or off, and runs
# after every rebuild, so a fresh row picks up the right state there.
root_node = tree.insert("", "end", text=file_name, open=True)
app_element = xml_root.find("app")
+50 -2
View File
@@ -87,6 +87,41 @@ def read_summary_facet(slot_element):
return True
def read_all_facets(slot_element):
"""Every facet on a slot, as {name: value} with each one typed by its own tag.
The manifest writes facets as <str name="unit" val="celsius"/>, <int name="max"
val="1000"/> and so on, so the tag is the type. The Properties dialog needs the lot —
unit, precision, min, max, trueText/falseText, range — and there are few enough of
them per slot that carrying the whole dict costs less than a lookup per facet.
"""
facets = {}
facet_element = slot_element.find("facets")
if facet_element is None:
return facets
for child in facet_element:
name = child.get("name")
if not name:
continue
raw = child.get("val", "")
if child.tag == "bool":
facets[name] = (raw.strip().lower() == "true")
elif child.tag == "int":
try:
facets[name] = int(raw)
except ValueError:
facets[name] = raw
elif child.tag in ("float", "double"):
try:
facets[name] = float(raw)
except ValueError:
facets[name] = raw
else:
facets[name] = raw
return facets
def read_readonly_facet(slot_element):
"""Reads a slot's '@readonly' facet. Absent means writable."""
facets = slot_element.find("facets")
@@ -116,10 +151,11 @@ def get_slots_with_inheritance(type_name, kit_schemas):
current_slots.append({
"name": slot.get("name"),
"type": slot.get("type"),
"default": slot.get("default", "false"),
"default": slot.get("default"), # absent means "the type's own zero"
"flags": slot.get("flags", ""),
"readonly": read_readonly_facet(slot),
"summary": read_summary_facet(slot),
"facets": read_all_facets(slot),
"declared_id": int(slot.get("id"))
})
@@ -157,7 +193,8 @@ def compile_schema_registry(manifest_paths):
"default": slot_data["default"],
"flags": slot_data["flags"],
"readonly": slot_data["readonly"],
"summary": slot_data["summary"]
"summary": slot_data["summary"],
"facets": slot_data["facets"]
})
app_state.final_components_registry[type_name] = resolved_type_structure
@@ -240,6 +277,17 @@ def get_all_slots_for_type(type_str):
]
def get_full_slots_for_type(type_str):
"""Every slot of a type, whole, in manifest order — nothing filtered out.
get_slots_for_type hides most of them, which is right for a wiresheet box and wrong
for the Properties dialog: a config slot is only editable somewhere, and this is
that somewhere. Copies are handed out so a caller cannot edit the registry in place.
"""
return [dict(slot) for slot in app_state.final_components_registry.get(type_str, [])
if slot["name"]]
def get_slots_for_type(type_str, linked_slots=()):
"""
Returns the slots worth painting for a given type, prefixed with double-digit
+31 -1
View File
@@ -8,7 +8,7 @@ import graph free of cycles (sax_file and wiresheet both push commands here).
import app_state
import palette
import schema
from sax_dom import restore_children, update_meta_property
from sax_dom import remove_prop, restore_children, set_prop_value, update_meta_property
_undo_stack = []
_redo_stack = []
@@ -137,6 +137,36 @@ class MetaMoveCommand:
update_meta_property(element, old_val, new_x, new_y)
class SlotValueCommand:
"""One Save from the Properties dialog: every slot it changed, as one undoable step.
A change is recorded as the <prop>'s value before and after, with None standing for
"the file had no such prop". Undoing back to None removes the prop again rather than
writing the default out, so a component that only ever carried the props the file
shipped with still carries exactly those.
"""
def __init__(self, changes, label="edit properties"):
# changes: list of (element, prop_name, old_val_or_None, new_val_or_None)
self.changes = changes
self.label = label
def _apply(self, value_index):
for change in self.changes:
element, prop_name = change[0], change[1]
value = change[value_index]
if value is None:
remove_prop(element, prop_name)
else:
set_prop_value(element, prop_name, value)
def undo(self):
self._apply(2)
def redo(self):
self._apply(3)
class AddComponentCommand:
"""Placing a component.