-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFusion_System_Blocks.py
More file actions
2069 lines (1717 loc) · 72.2 KB
/
Copy pathFusion_System_Blocks.py
File metadata and controls
2069 lines (1717 loc) · 72.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
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
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import json
import os
import sys
import traceback
from typing import Any
import adsk.core
import adsk.fusion
# Add src directory to path so we can import our modules
SRC_PATH = os.path.join(os.path.dirname(__file__), "src")
if SRC_PATH not in sys.path:
sys.path.insert(0, SRC_PATH)
import diagram_data # noqa: E402
# Add repo root to path for core library
REPO_ROOT = os.path.dirname(__file__)
if REPO_ROOT not in sys.path:
sys.path.insert(0, REPO_ROOT)
# Import the core library for validation and action planning (hard dependency)
from fsb_core.bridge_actions import BridgeAction, BridgeEvent # noqa: E402
from fsb_core.delta import apply_patch, is_trivial_patch # noqa: E402
from fsb_core.requirements import validate_requirements # noqa: E402
from fsb_core.serialization import ( # noqa: E402
dict_to_graph,
flatten_connections_for_js,
)
from fsb_core.version_control import SnapshotStore # noqa: E402
# Import logging utilities
try:
from fusion_addin.logging_util import (
cleanup_old_logs,
get_log_file_path,
get_logger,
log_environment_info,
setup_logging,
)
_logger = get_logger("main")
LOGGING_AVAILABLE = True
except ImportError:
LOGGING_AVAILABLE = False
_logger = None
# Import diagnostics module
try:
from fusion_addin.diagnostics import (
cleanup_any_remaining_temp_objects,
run_diagnostics_and_show_result,
)
DIAGNOSTICS_AVAILABLE = True
except ImportError:
DIAGNOSTICS_AVAILABLE = False
APP = adsk.core.Application.get()
UI = APP.userInterface
ATTR_GROUP = "systemBlocks"
SNAPSHOT_ATTR_NAME = "snapshots"
# Keep handler references on the owning Fusion object so command-scoped
# handlers are released with the command instead of leaking for the full session.
_handler_fallback_refs: dict[int, list[Any]] = {}
# Pending CAD link data — stored when sendInfoToHTML may arrive
# before the palette web-view is ready after being restored.
_pending_cad_link: dict | None = None
# Global snapshot store for version control (Issue #31).
# _snapshot_store_scope records which document scope the store was loaded
# for (None = default slot, otherwise the named-document slug) so that
# _persist_snapshot_store can refuse to write one document's history into
# another document's attribute.
_snapshot_store = SnapshotStore(max_snapshots=50)
_snapshot_store_scope: str | None = None
# Conservative cap for the serialized snapshot store. Fusion attribute
# values have finite size limits; exceeding them makes the write fail and
# silently drops the whole history, so we trim oldest snapshots instead.
_SNAPSHOT_STORE_MAX_BYTES = 1_500_000
# Workspace-activation handler reference so stop() can unregister it from
# Fusion's event (releasing only the Python reference leaves the handler
# registered, stacking duplicates across add-in restarts).
_workspace_activated_handler: Any | None = None
def _log_runtime_error(message: str, exc: Exception | None = None) -> None:
"""Log backend errors to both the add-in logger and Fusion, when available."""
if LOGGING_AVAILABLE:
if exc is None:
_logger.error(message)
else:
_logger.exception("%s: %s", message, exc)
try:
if APP and hasattr(APP, "log"):
APP.log(f"[FusionSystemBlocks] {message}")
except Exception:
pass
def _retain_handler(owner: Any, handler: Any) -> Any:
"""Keep a handler alive for the lifetime of its owning Fusion object."""
if owner is None or handler is None:
return handler
try:
handlers = getattr(owner, "_system_blocks_handlers", None)
if handlers is None:
handlers = []
owner._system_blocks_handlers = handlers
handlers.append(handler)
except Exception:
# Some Fusion proxy objects reject Python attributes; fall back to a
# per-owner registry and clear it on the owner's destroy event.
_handler_fallback_refs.setdefault(id(owner), []).append(handler)
return handler
def _release_handlers(owner: Any) -> None:
"""Drop retained handlers when their owner command or UI object is done."""
if owner is None:
return
try:
handlers = getattr(owner, "_system_blocks_handlers", None)
if handlers is not None:
handlers.clear()
except Exception:
pass
_handler_fallback_refs.pop(id(owner), None)
def _bridge_event_name(event_type: BridgeEvent | str) -> str:
"""Normalize bridge event names to the canonical payload.type string."""
return event_type.value if isinstance(event_type, BridgeEvent) else str(event_type)
def _send_bridge_event(
event_type: BridgeEvent | str,
data: dict[str, Any] | None = None,
) -> bool:
"""Send a structured Python → JS event payload through Fusion's bridge."""
event_name = _bridge_event_name(event_type)
try:
palette = UI.palettes.itemById("SystemBlocksPalette")
except Exception:
palette = None
if not palette:
return False
payload = {
"type": event_name,
"data": data or {},
}
palette.sendInfoToHTML(event_name, json.dumps(payload))
return True
def _snapshot_attr_name(slug: str | None = None) -> str:
"""Return the Fusion attribute name for the current snapshot scope."""
if slug:
return f"{SNAPSHOT_ATTR_NAME}_{_slug_from_label(slug)}"
return SNAPSHOT_ATTR_NAME
def _load_snapshot_store(slug: str | None = None) -> SnapshotStore:
"""Restore persisted snapshots for the current Fusion document scope."""
root_comp = get_root_component()
if not root_comp:
return SnapshotStore(max_snapshots=50)
attr_name = _snapshot_attr_name(slug)
try:
for attr in root_comp.attributes:
if attr.groupName == ATTR_GROUP and attr.name == attr_name:
data = json.loads(attr.value)
if isinstance(data, list):
return SnapshotStore.from_list(data, max_snapshots=50)
break
except Exception as exc:
_log_runtime_error(
f"Failed to load snapshot store for scope '{attr_name}'",
exc,
)
return SnapshotStore(max_snapshots=50)
def _set_snapshot_store(slug: str | None = None) -> SnapshotStore:
"""Load and activate the snapshot store for the given document scope.
All handlers must go through this helper (rather than assigning
``_snapshot_store`` directly) so ``_snapshot_store_scope`` stays in
sync with the store's actual origin.
"""
global _snapshot_store, _snapshot_store_scope
_snapshot_store = _load_snapshot_store(slug)
_snapshot_store_scope = _slug_from_label(slug) if slug else None
return _snapshot_store
def _persist_snapshot_store(slug: str | None = None) -> bool:
"""Persist the current snapshot store with the active Fusion document."""
# Guard against cross-scope writes: the in-memory store may hold a
# different document's history (e.g. loaded for named doc "A" while
# a save targets the default slot). Persisting it would overwrite
# that scope's history with unrelated snapshots.
target_scope = _slug_from_label(slug) if slug else None
if target_scope != _snapshot_store_scope:
_log_runtime_error(
f"Refusing to persist snapshot store loaded for scope "
f"'{_snapshot_store_scope}' into scope '{target_scope}'"
)
return False
root_comp = get_root_component()
if not root_comp:
return False
# Fusion attribute values have finite size limits — trim oldest
# snapshots until the serialized store fits rather than letting the
# whole write fail and lose the history.
trimmed = _snapshot_store.trim_to_json_size(_SNAPSHOT_STORE_MAX_BYTES)
if trimmed:
_log_runtime_error(
f"Snapshot store exceeded {_SNAPSHOT_STORE_MAX_BYTES} bytes; "
f"dropped {trimmed} oldest snapshot(s) to fit"
)
notify_warning(
f"Snapshot history was trimmed ({trimmed} oldest snapshot(s) "
"removed) to fit document storage limits"
)
payload = json.dumps(_snapshot_store.to_list())
if len(payload) > _SNAPSHOT_STORE_MAX_BYTES:
# Even a single snapshot exceeds the budget — refuse rather than
# attempt a write that Fusion may truncate or reject.
_log_runtime_error(
f"Refusing to persist snapshot store: a single snapshot exceeds "
f"{_SNAPSHOT_STORE_MAX_BYTES} bytes"
)
return False
attr_name = _snapshot_attr_name(slug)
attrs = root_comp.attributes
try:
for attr in attrs:
if attr.groupName == ATTR_GROUP and attr.name == attr_name:
attr.deleteMe()
break
# Persist snapshots alongside the document so version history survives
# add-in reloads and document switches.
attrs.add(ATTR_GROUP, attr_name, payload)
return True
except Exception as exc:
_log_runtime_error(
f"Failed to persist snapshot store for scope '{attr_name}'",
exc,
)
return False
def _iter_documents() -> list[Any]:
"""Enumerate open Fusion documents across API variants."""
documents = getattr(APP, "documents", None)
if not documents:
return []
try:
count = getattr(documents, "count", None)
if isinstance(count, int) and hasattr(documents, "item"):
return [documents.item(index) for index in range(count)]
except Exception:
pass
try:
return list(documents)
except Exception:
return []
def _resolve_design_for_doc(doc_id: str) -> adsk.fusion.Design | None:
"""Resolve a Fusion design by document ID, with active-product fallback."""
normalized_doc_id = str(doc_id or "").strip()
if normalized_doc_id:
for document in _iter_documents():
try:
data_file = getattr(document, "dataFile", None)
if not data_file or getattr(data_file, "id", "") != normalized_doc_id:
continue
products = getattr(document, "products", None)
if products and hasattr(products, "itemByProductType"):
product = products.itemByProductType("DesignProductType")
design = adsk.fusion.Design.cast(product)
if design:
return design
# Fallback: some API variants only expose the design of the
# active document. Temporarily activate the target document,
# grab its design, then restore the user's original document
# — resolving a link must never permanently switch their
# workspace.
original_document = getattr(APP, "activeDocument", None)
if original_document != document and hasattr(document, "activate"):
document.activate()
try:
adsk.doEvents()
except Exception:
pass
design = adsk.fusion.Design.cast(APP.activeProduct)
if (
original_document is not None
and original_document != document
and hasattr(original_document, "activate")
):
try:
original_document.activate()
adsk.doEvents()
except Exception:
_log_runtime_error(
"Failed to restore the previously active document "
"after design lookup"
)
if design:
return design
except Exception as exc:
_log_runtime_error(
f"Failed to inspect Fusion document '{normalized_doc_id}'",
exc,
)
_log_runtime_error(
f"Document '{normalized_doc_id}' not found; falling back to active design"
)
return adsk.fusion.Design.cast(APP.activeProduct)
class CommandScopeCleanupHandler(adsk.core.CommandEventHandler):
"""Release retained command handlers when the Fusion command is destroyed."""
def __init__(self, owner: Any):
super().__init__()
self._owner = owner
def notify(self, args):
_release_handlers(self._owner)
def send_palette_notification(message: str, level: str = "info") -> None:
"""Send a non-blocking notification to the HTML palette.
When the palette is unavailable, only warnings and errors fall back
to a blocking message box — info/success toasts are transient by
design and are just logged instead of interrupting the user.
Args:
message: The message to display.
level: The severity level ('info', 'success', 'warning', 'error').
"""
if _send_bridge_event(
BridgeEvent.NOTIFICATION,
{"message": message, "level": level},
):
return
if level in ("warning", "error"):
UI.messageBox(message)
elif LOGGING_AVAILABLE:
_logger.info("Palette unavailable; %s notification dropped: %s", level, message)
def notify_error(message: str) -> None:
send_palette_notification(message, level="error")
def notify_warning(message: str) -> None:
send_palette_notification(message, level="warning")
def notify_success(message: str) -> None:
send_palette_notification(message, level="success")
def notify_info(message: str) -> None:
send_palette_notification(message, level="info")
def _show_validation_errors_dialog(errors: list) -> None:
"""Display validation errors in a message box.
Shows a formatted list of validation errors from the core library
in a Fusion message box for user visibility.
Args:
errors: List of ValidationError instances from fsb_core.validation.
"""
if not errors:
return
# Format errors for display
lines = [f"Found {len(errors)} validation error(s):\n"]
for i, error in enumerate(errors[:10], 1): # Limit to first 10 errors
code = error.code.value if hasattr(error.code, "value") else str(error.code)
lines.append(f"{i}. [{code}] {error.message}")
if len(errors) > 10:
lines.append(f"\n... and {len(errors) - 10} more errors")
error_text = "\n".join(lines)
# Show in Fusion message box
try:
UI.messageBox(
error_text,
"Graph Validation Errors",
adsk.core.MessageBoxButtonTypes.OKButtonType,
adsk.core.MessageBoxIconTypes.WarningIconType,
)
except Exception:
# Fallback to simple notification
notify_error(error_text)
def get_root_component() -> adsk.fusion.Component | None:
"""Get the root component of the active design."""
try:
design = adsk.fusion.Design.cast(APP.activeProduct)
if design:
return design.rootComponent
except Exception:
pass
return None
def save_diagram_json(json_data: str | dict) -> bool:
"""Save diagram JSON to Fusion attributes.
Does NOT validate on save — validation is only triggered by the
explicit "Validate" / "Check Rules" button. This lets users persist
work-in-progress freely without being interrupted by warnings.
Args:
json_data: JSON string or already-parsed dict of the diagram.
Returns:
True if successful, False otherwise.
"""
try:
# Normalise: accept both dict and str so callers from the
# JS bridge (which may pass either type) never crash.
if isinstance(json_data, dict):
json_data = json.dumps(json_data)
else:
json.loads(json_data)
root_comp = get_root_component()
if not root_comp:
notify_error("No active design found")
return False
attrs = root_comp.attributes
# Remove existing attribute if it exists
for attr in attrs:
if attr.groupName == ATTR_GROUP and attr.name == "diagramJson":
attr.deleteMe()
break
# Add new attribute
attrs.add(ATTR_GROUP, "diagramJson", json_data)
return True
except Exception as e:
notify_error(f"Failed to save diagram: {str(e)}")
return False
def load_diagram_json():
"""Load diagram JSON from Fusion attributes."""
try:
root_comp = get_root_component()
if not root_comp:
return None
attrs = root_comp.attributes
for attr in attrs:
if attr.groupName == ATTR_GROUP and attr.name == "diagramJson":
return attr.value
return None
except Exception as e:
notify_error(f"Failed to load diagram: {str(e)}")
return None
def load_diagram_data():
"""Return the current diagram as a Python dictionary."""
diagram_json = load_diagram_json()
if not diagram_json:
return None
if isinstance(diagram_json, dict):
return diagram_json
try:
return json.loads(diagram_json)
except (json.JSONDecodeError, TypeError) as exc:
notify_error(f"Invalid diagram data: {exc}")
return None
# ── Named document helpers ──────────────────────────────────────────────
# Each named document is stored as an attribute:
# group = ATTR_GROUP, name = "doc_<slug>"
# A manifest attribute "docIndex" holds a JSON list of
# { "slug": "<slug>", "label": "<user name>", "modified": "<ISO>" }.
def _doc_attr_name(slug: str) -> str:
"""Return the Fusion attribute name for a named document."""
return f"doc_{slug}"
def _slug_from_label(label: str) -> str:
"""Derive a filesystem-safe slug from a user-visible label."""
import re
slug = re.sub(r"[^a-zA-Z0-9_-]", "_", label.strip())[:64]
return slug or "untitled"
def _resolve_unique_slug(label: str) -> str:
"""Resolve a slug for a Save As, avoiding cross-document collisions.
Slugging is lossy ("My Design!" and "My Design?" both become
"My_Design_"), so a new document could silently overwrite an
unrelated existing one. If the derived slug is taken by a document
with a *different* label, append a numeric suffix until free.
Saving with the same label as an existing document keeps its slug
(intentional overwrite of the same-named document).
"""
base = _slug_from_label(label)
taken = {entry.get("slug"): entry.get("label") for entry in list_named_diagrams()}
if base not in taken or taken[base] == label:
return base
suffix = 2
while True:
candidate = f"{base[:60]}_{suffix}"
if candidate not in taken or taken[candidate] == label:
return candidate
suffix += 1
def list_named_diagrams() -> list[dict[str, str]]:
"""Return the list of named documents stored on the root component.
Returns:
List of dicts with keys 'slug', 'label', 'modified'.
"""
try:
root_comp = get_root_component()
if not root_comp:
return []
for attr in root_comp.attributes:
if attr.groupName == ATTR_GROUP and attr.name == "docIndex":
return json.loads(attr.value)
except Exception:
pass
return []
def _save_doc_index(index: list[dict[str, str]]) -> None:
"""Persist the document manifest to a Fusion attribute."""
root_comp = get_root_component()
if not root_comp:
return
attrs = root_comp.attributes
for attr in attrs:
if attr.groupName == ATTR_GROUP and attr.name == "docIndex":
attr.deleteMe()
break
attrs.add(ATTR_GROUP, "docIndex", json.dumps(index))
def save_named_diagram(
label: str,
json_data: str | dict,
slug: str | None = None,
) -> bool:
"""Save a diagram under a user-chosen name.
Args:
label: User-visible name for the document.
json_data: JSON string or already-parsed dict of the diagram.
Returns:
True on success.
"""
# Normalise to string for attribute storage
if isinstance(json_data, dict):
json_data = json.dumps(json_data)
try:
resolved_slug = _slug_from_label(slug) if slug else _slug_from_label(label)
root_comp = get_root_component()
if not root_comp:
notify_error("No active design found")
return False
attr_name = _doc_attr_name(resolved_slug)
attrs = root_comp.attributes
# Remove existing attribute with same name
for attr in attrs:
if attr.groupName == ATTR_GROUP and attr.name == attr_name:
attr.deleteMe()
break
attrs.add(ATTR_GROUP, attr_name, json_data)
# Update manifest
index = list_named_diagrams()
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
entry = next((e for e in index if e["slug"] == resolved_slug), None)
if entry:
entry["modified"] = now
entry["label"] = label
else:
index.append(
{
"slug": resolved_slug,
"label": label,
"modified": now,
}
)
_save_doc_index(index)
return True
except Exception as e:
notify_error(f"Failed to save named diagram: {e}")
return False
def load_named_diagram(slug: str) -> str | None:
"""Load a named diagram's JSON by slug.
Args:
slug: The document slug.
Returns:
JSON string or None.
"""
try:
root_comp = get_root_component()
if not root_comp:
return None
attr_name = _doc_attr_name(slug)
for attr in root_comp.attributes:
if attr.groupName == ATTR_GROUP and attr.name == attr_name:
return attr.value
except Exception as e:
notify_error(f"Failed to load named diagram: {e}")
return None
def delete_named_diagram(slug: str) -> bool:
"""Delete a named diagram.
Args:
slug: The document slug to remove.
Returns:
True on success.
"""
try:
root_comp = get_root_component()
if not root_comp:
return False
attr_name = _doc_attr_name(slug)
for attr in root_comp.attributes:
if attr.groupName == ATTR_GROUP and attr.name == attr_name:
attr.deleteMe()
break
index = [e for e in list_named_diagrams() if e["slug"] != slug]
_save_doc_index(index)
return True
except Exception as e:
notify_error(f"Failed to delete named diagram: {e}")
return False
class DiagnosticsCommandHandler(adsk.core.CommandCreatedEventHandler):
"""Handler for the Run Diagnostics command.
When the command is executed, runs all diagnostic tests and
displays a summary in a message box.
"""
def __init__(self):
super().__init__()
def notify(self, args):
try:
if LOGGING_AVAILABLE:
_logger.debug("DiagnosticsCommandHandler.notify() called")
command = args.command
# Keep execute handlers attached to the command lifetime.
on_execute = DiagnosticsExecuteHandler()
command.execute.add(on_execute)
_retain_handler(command, on_execute)
cleanup_handler = CommandScopeCleanupHandler(command)
command.destroy.add(cleanup_handler)
_retain_handler(command, cleanup_handler)
except Exception as e:
if LOGGING_AVAILABLE:
_logger.exception(f"Error in DiagnosticsCommandHandler: {e}")
notify_error(f"Error in diagnostics command: {str(e)}")
class DiagnosticsExecuteHandler(adsk.core.CommandEventHandler):
"""Execute handler that runs the diagnostics suite."""
def __init__(self):
super().__init__()
def notify(self, args):
try:
if LOGGING_AVAILABLE:
_logger.info("Running diagnostics suite...")
if DIAGNOSTICS_AVAILABLE:
run_diagnostics_and_show_result()
else:
notify_warning(
"Diagnostics module not available. "
"Check that fusion_addin/diagnostics.py exists."
)
except Exception as e:
if LOGGING_AVAILABLE:
_logger.exception(f"Error running diagnostics: {e}")
notify_error(f"Diagnostics failed: {str(e)}")
class SystemBlocksPaletteShowCommandHandler(adsk.core.CommandCreatedEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
if LOGGING_AVAILABLE:
_logger.debug("SystemBlocksPaletteShowCommandHandler.notify() called")
# Get the command created event args
command = args.command
# Keep execute handlers attached to the command lifetime.
on_execute = CommandExecuteHandler()
command.execute.add(on_execute)
_retain_handler(command, on_execute)
cleanup_handler = CommandScopeCleanupHandler(command)
command.destroy.add(cleanup_handler)
_retain_handler(command, cleanup_handler)
if LOGGING_AVAILABLE:
_logger.debug("CommandExecuteHandler added successfully")
except Exception as e:
if LOGGING_AVAILABLE:
_logger.exception(
f"Error in SystemBlocksPaletteShowCommandHandler: {e}"
)
notify_error(f"Error in command created handler: {str(e)}")
class CommandExecuteHandler(adsk.core.CommandEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
# Get the palette
palette = UI.palettes.itemById("SystemBlocksPalette")
if not palette:
palette = _create_palette()
if palette:
palette.isVisible = True
except Exception as e:
notify_error(f"Error showing palette: {str(e)}")
class PaletteHTMLEventHandler(adsk.core.HTMLEventHandler):
def __init__(self):
super().__init__()
def notify(self, args):
try:
htmlArgs = adsk.core.HTMLEventArgs.cast(args)
data = json.loads(htmlArgs.data) if htmlArgs.data else {}
action = htmlArgs.action
if LOGGING_AVAILABLE:
_logger.debug(f"HTML event received: action='{action}'")
try:
action_enum = BridgeAction(action)
except ValueError:
if LOGGING_AVAILABLE:
_logger.warning(
f"Action '{action}' is not in BridgeAction enum — "
"update fsb_core/bridge_actions.py and src/types/bridge-actions.js"
)
htmlArgs.returnData = json.dumps(
{
"success": False,
"error": f"Unknown action: {action}",
}
)
return
handler_name = f"_handle_{action_enum.value}"
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
response = handler(data)
htmlArgs.returnData = json.dumps(response)
if LOGGING_AVAILABLE:
_logger.debug(
f"HTML event handled: action='{action}', "
f"success={response.get('success', 'N/A')}"
)
else:
if LOGGING_AVAILABLE:
_logger.warning(f"Unknown HTML action: '{action}'")
htmlArgs.returnData = json.dumps(
{"success": False, "error": f"Unknown action: {action}"}
)
except Exception as e:
if LOGGING_AVAILABLE:
_logger.exception(f"Error in PaletteHTMLEventHandler: {e}")
notify_error(f"Error in HTML event handler: {str(e)}")
if args:
args.returnData = json.dumps({"success": False, "error": str(e)})
def _handle_save_diagram(self, data: dict[str, Any]) -> dict[str, Any]:
json_data = data.get("diagram", "{}")
success = save_diagram_json(json_data)
if success:
# A plain save targets the default document scope. If the
# active store was loaded for a named document, reload the
# default-scope store first so its history is never
# overwritten with another document's snapshots.
if _snapshot_store_scope is not None:
_set_snapshot_store()
_persist_snapshot_store()
return {
"success": True,
"snapshots": _snapshot_store.list_snapshots(),
}
return {"success": False, "error": "Diagram validation or save failed"}
def _handle_load_diagram(self, data: dict[str, Any]) -> dict[str, Any]:
diagram_json = load_diagram_json()
if diagram_json:
try:
diagram_dict = (
diagram_json
if isinstance(diagram_json, dict)
else json.loads(diagram_json)
)
except json.JSONDecodeError as exc:
notify_error(f"Invalid diagram data: {str(exc)}")
diagram_dict = diagram_data.create_empty_diagram()
else:
diagram_dict = diagram_data.create_empty_diagram()
# Apply forward-only schema migrations so stored pre-versioning
# documents load correctly even if the JS-side migration is skipped.
diagram_dict = diagram_data.migrate_diagram(diagram_dict)
# Reload persisted history whenever the active diagram is opened.
_set_snapshot_store()
return {
"success": True,
"diagram": diagram_dict,
"snapshots": _snapshot_store.list_snapshots(),
}
def _validate_patch_ops(self, patch: list[Any]) -> str | None:
"""Validate patch operation structure and allowed target roots.
Returns an error string when invalid, otherwise ``None``.
"""
allowed_ops = {"add", "remove", "replace"}
allowed_roots = {
"blocks",
"connections",
"groups",
"namedStubs",
"metadata",
}
for idx, op in enumerate(patch):
if not isinstance(op, dict):
return f"Invalid patch op at index {idx}: expected object"
operation = op.get("op")
path = op.get("path")
if operation not in allowed_ops:
return f"Invalid patch op at index {idx}: unsupported op '{operation}'"
if not isinstance(path, str) or not path.startswith("/"):
return f"Invalid patch op at index {idx}: path must start with '/'"
parts = [part for part in path.split("/") if part]
if not parts:
return (
f"Invalid patch op at index {idx}: root-path operations "
"are not allowed"
)
if parts[0] not in allowed_roots:
return (
f"Invalid patch op at index {idx}: root '{parts[0]}' "
"is not patchable"
)
if operation in {"add", "replace"} and "value" not in op:
return (
f"Invalid patch op at index {idx}: '{operation}' requires 'value'"
)
return None
def _handle_apply_delta(self, data: dict[str, Any]) -> dict[str, Any]:
"""Apply a JSON-Patch delta to the persisted diagram.
Expects ``data`` to contain a ``patch`` list of RFC 6902
operations. The current diagram is loaded from Fusion
attributes, the patch is applied, and the result is saved back.
If the patch is trivial (empty), we skip I/O entirely and
return early.
"""
patch = data.get("patch", [])
if not isinstance(patch, list):
return {"success": False, "error": "Patch must be a list of operations"}
validation_error = self._validate_patch_ops(patch)
if validation_error:
return {"success": False, "error": validation_error}
if is_trivial_patch(patch):
return {"success": True, "patched": False}
diagram_json = load_diagram_json()
if not diagram_json:
return {"success": False, "error": "No diagram to patch"}
try:
current = (
diagram_json
if isinstance(diagram_json, dict)
else json.loads(diagram_json)
)
except json.JSONDecodeError as exc:
return {"success": False, "error": f"Invalid stored diagram: {exc}"}
try:
updated = apply_patch(current, patch)
except Exception as exc:
return {"success": False, "error": f"Patch failed: {exc}"}