Live undo/redo: add/delete component and link, move, property edits
Undo and redo now work against a connected device; each step is sent there through Sox. Deleting a component first reads its whole subtree back (config, unloaded children, links, place among siblings) so undo can recreate it; recreated components take new device ids, which the DOM elements pick up so later steps still reach them. Binary Buf config (a user's cred) is read with read_prop, since the cache decodes every Buf as a Str. Moves, tidy layout, and Properties / page editor / user edits record only what the device accepted. A step that does not fully reach the device warns and clears the history. History is also cleared on every view change in live mode, as opening a sheet rebuilds the DOM from the device. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+187
-3
@@ -10,7 +10,7 @@ import binascii
|
||||
from tkinter import messagebox
|
||||
|
||||
import app_state
|
||||
from sox import BUF_ID, type_id_for_slot
|
||||
from sox import BUF_ID, CONFIG, STR_ID, type_id_for_slot
|
||||
|
||||
|
||||
# Why the last live_* call failed, in words the user can act on. Every failing call sets
|
||||
@@ -41,8 +41,8 @@ def _session():
|
||||
def warn_failure(title, what, detail=None):
|
||||
"""Tells the user, in a dialog and the status bar, that `what` did not reach the device.
|
||||
|
||||
`detail` defaults to last_error. Live mode has no undo, so the dialog is the only
|
||||
record the user gets that the editor and the device may now disagree.
|
||||
`detail` defaults to last_error. Nothing retries a write that failed, so the dialog
|
||||
is the only record the user gets that the editor and the device may now disagree.
|
||||
"""
|
||||
reason = detail if detail is not None else last_error
|
||||
app_state.set_status(f"{what}: {reason}", warn=True)
|
||||
@@ -230,6 +230,190 @@ def live_invoke(element, slot_name, arg=None):
|
||||
return False
|
||||
|
||||
|
||||
# ── Undo: read a subtree back, put it back ──────────────────────
|
||||
|
||||
def read_subtree(element):
|
||||
"""Everything it takes to put `element` and all it holds back on the device.
|
||||
|
||||
Read from the device, not the DOM: the DOM only holds what has been opened, and a
|
||||
placeholder child carries neither config nor children of its own. Requests go one
|
||||
component at a time, at the pace the device sets (see used_kit_names).
|
||||
|
||||
Returns {"tree", "links", "siblings"}, or None with last_error set. A node is
|
||||
{"id", "kit_id", "type_id", "type_name", "name", "values", "element", "children"},
|
||||
where "element" is the DOM element showing it, if any, so a new id can reach it.
|
||||
A link end, and each of "siblings" (the parent's children, in order), is ("node",
|
||||
node), ("elem", element) or ("id", comp_id): a component outside the subtree is
|
||||
followed by its element when it has one, because its id changes if it is itself
|
||||
deleted and put back.
|
||||
"""
|
||||
ds = _session()
|
||||
if ds is None:
|
||||
return None
|
||||
comp_id = _comp_id(element)
|
||||
if comp_id is None:
|
||||
return _fail(f"'{element.get('name', '?')}' has no component id.")
|
||||
|
||||
client = ds.sox_client
|
||||
root = app_state.xml_root_element
|
||||
elements_by_id = {}
|
||||
if root is not None:
|
||||
for elem in root.iter("comp"):
|
||||
if elem.get("id") is not None:
|
||||
elements_by_id.setdefault(elem.get("id"), elem)
|
||||
|
||||
nodes_by_id = {}
|
||||
|
||||
def read(comp):
|
||||
if comp.type_name not in app_state.final_components_registry:
|
||||
raise _SnapshotError(f"No kit manifest describes {comp.type_name}, so "
|
||||
f"'{comp.name}' could not be put back as it was.")
|
||||
children = ds.load_children(comp.id)
|
||||
if len(children) != len(comp.children):
|
||||
raise _SnapshotError(f"Not every child of '{comp.name}' could be read.")
|
||||
client.update([comp], CONFIG)
|
||||
values = dict(comp.values)
|
||||
# The cache reads every Buf as a Str, which loses bytes of a binary one (a
|
||||
# user's cred); those are read again as what they are.
|
||||
for slot in app_state.final_components_registry[comp.type_name]:
|
||||
if ("c" in slot["flags"] and slot["type"] != "void"
|
||||
and _wire_type(slot["type"], slot["facets"].get("asStr") is True) == BUF_ID):
|
||||
values[slot["name"]] = client.read_prop(comp.id, slot["slot_id"], BUF_ID)
|
||||
node = {
|
||||
"id": comp.id,
|
||||
"kit_id": comp.kit_id,
|
||||
"type_id": comp.type_id,
|
||||
"type_name": comp.type_name,
|
||||
"name": comp.name,
|
||||
"values": values,
|
||||
"element": elements_by_id.get(str(comp.id)),
|
||||
"children": [],
|
||||
}
|
||||
nodes_by_id[comp.id] = node
|
||||
node["children"] = [read(child) for child in children]
|
||||
return node
|
||||
|
||||
try:
|
||||
top = client.load(comp_id)
|
||||
if top is None:
|
||||
return _fail(f"'{element.get('name', '?')}' could not be read from the device.")
|
||||
tree = read(top)
|
||||
|
||||
links = []
|
||||
seen = set()
|
||||
for cid in list(nodes_by_id):
|
||||
for lnk in client.read_links(cid):
|
||||
key = (lnk.from_comp_id, lnk.from_slot_id, lnk.to_comp_id, lnk.to_slot_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
links.append((_link_end(lnk.from_comp_id, nodes_by_id, elements_by_id),
|
||||
lnk.from_slot_id,
|
||||
_link_end(lnk.to_comp_id, nodes_by_id, elements_by_id),
|
||||
lnk.to_slot_id))
|
||||
except _SnapshotError as e:
|
||||
return _fail(str(e))
|
||||
except Exception as e:
|
||||
return _fail(f"'{element.get('name', '?')}' could not be read from the device: {e}")
|
||||
|
||||
parent = client.cache_get(top.parent)
|
||||
siblings = [_link_end(cid, nodes_by_id, elements_by_id)
|
||||
for cid in (parent.children if parent is not None else [])]
|
||||
return {"tree": tree, "links": links, "siblings": siblings}
|
||||
|
||||
|
||||
class _SnapshotError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _link_end(comp_id, nodes_by_id, elements_by_id):
|
||||
if comp_id in nodes_by_id:
|
||||
return ("node", nodes_by_id[comp_id])
|
||||
elem = elements_by_id.get(str(comp_id))
|
||||
if elem is not None:
|
||||
return ("elem", elem)
|
||||
return ("id", comp_id)
|
||||
|
||||
|
||||
def _link_end_id(end):
|
||||
kind, ref = end
|
||||
if kind == "node":
|
||||
return ref["id"]
|
||||
if kind == "elem":
|
||||
return _comp_id(ref)
|
||||
return ref
|
||||
|
||||
|
||||
def recreate_subtree(parent_element, snapshot, build_config):
|
||||
"""Adds a subtree from read_subtree back under `parent_element`, with its links.
|
||||
|
||||
The device hands out new ids. Each node, and the DOM element showing it, takes its
|
||||
new id, so whatever refers to them later still finds them. The component goes back
|
||||
to its old place among its siblings.
|
||||
|
||||
`build_config(type_name, device_values=...)` makes an add command's config values.
|
||||
Returns (top_created, complete); when not complete, last_error says what is missing.
|
||||
"""
|
||||
ds = _session()
|
||||
if ds is None:
|
||||
return False, False
|
||||
parent_id = _comp_id(parent_element)
|
||||
if parent_id is None:
|
||||
_fail(f"The parent '{parent_element.get('name', '?')}' has no component id.")
|
||||
return False, False
|
||||
|
||||
client = ds.sox_client
|
||||
tree = snapshot["tree"]
|
||||
|
||||
def create(node, under_id):
|
||||
config = build_config(node["type_name"], device_values=node["values"])
|
||||
comp = client.add(under_id, node["kit_id"], node["type_id"], node["name"], config)
|
||||
node["id"] = comp.id
|
||||
if node["element"] is not None:
|
||||
node["element"].set("id", str(comp.id))
|
||||
|
||||
def create_children(node):
|
||||
for child in node["children"]:
|
||||
create(child, node["id"])
|
||||
create_children(child)
|
||||
|
||||
try:
|
||||
create(tree, parent_id)
|
||||
except Exception as e:
|
||||
_fail(f"The device rejected the add of '{tree['name']}': {e}")
|
||||
return False, False
|
||||
|
||||
try:
|
||||
create_children(tree)
|
||||
for from_end, from_slot, to_end, to_slot in snapshot["links"]:
|
||||
client.link(_link_end_id(from_end), from_slot, _link_end_id(to_end), to_slot)
|
||||
|
||||
# The add put it last; the device's order is the order execution runs in.
|
||||
parent = client.cache_get(parent_id)
|
||||
wanted = [_link_end_id(end) for end in snapshot["siblings"]]
|
||||
if (parent is not None and set(wanted) == set(parent.children)
|
||||
and wanted != parent.children):
|
||||
client.reorder(parent_id, wanted)
|
||||
complete = True
|
||||
except Exception as e:
|
||||
_fail(f"'{tree['name']}' is back on the device, but not all of it: {e}")
|
||||
complete = False
|
||||
|
||||
ds.after_add(tree["id"])
|
||||
return True, complete
|
||||
|
||||
|
||||
def wire_value(type_id, raw):
|
||||
"""A value as the device sent it, in the form encode_value wants for `type_id`."""
|
||||
if type_id == BUF_ID:
|
||||
return bytes(raw) if isinstance(raw, (bytes, bytearray)) else str(raw).encode("utf-8")
|
||||
if type_id == STR_ID:
|
||||
if isinstance(raw, (bytes, bytearray)):
|
||||
return bytes(raw).decode("utf-8", errors="replace").rstrip("\0")
|
||||
return str(raw)
|
||||
return _coerce_value(type_id, str(raw))
|
||||
|
||||
|
||||
# ── Helpers ─────────────────────────────────────────────────────
|
||||
|
||||
def _comp_id(element):
|
||||
|
||||
Reference in New Issue
Block a user