-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathnode_editor_modern.py
More file actions
2237 lines (1872 loc) · 93.6 KB
/
Copy pathnode_editor_modern.py
File metadata and controls
2237 lines (1872 loc) · 93.6 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
# node_editor_modern.py - Modern Node Editor with improved visuals
import tkinter as tk
from tkinter import ttk, messagebox
import uuid
import math
import os
import importlib
import inspect
import json
from node_registry import NODE_REGISTRY
from nodes.missing_node import MissingNode
from nodes.base_node import BaseNode
class Theme:
"""Modern dark color scheme"""
CANVAS_BG = '#1e1e2e'
GRID_COLOR = '#2a2a3e'
GRID_MAJOR_COLOR = '#353550'
NODE_BG = '#2d2d44'
NODE_HEADER = '#3d3d5c'
NODE_BORDER = '#4a4a6a'
NODE_BORDER_SELECTED = '#7c7cff'
NODE_BORDER_HOVER = '#5a5a8a'
NODE_SHADOW = '#15151f'
NODE_TYPE_INPUT = '#2d5a2d'
NODE_TYPE_OUTPUT = '#5a2d2d'
NODE_TYPE_PROCESS = '#2d3d5a'
NODE_TYPE_LOGIC = '#5a4a2d'
NODE_TYPE_MISSING = '#8a2d2d'
TEXT_PRIMARY = '#e0e0e0'
TEXT_SECONDARY = '#a0a0a0'
TEXT_MUTED = '#707080'
CONNECTOR_INPUT = '#5599ff'
CONNECTOR_OUTPUT = '#55ff99'
CONNECTOR_HOVER = '#ffffff'
CONNECTION_DEFAULT = '#5580aa'
CONNECTION_ACTIVE = '#77aaff'
CONNECTION_PREVIEW = '#ffffff'
CONNECTION_FLOW = '#ffcc00' # Yellow/gold for active data flow
TOOLBAR_BG = '#252535'
BUTTON_BG = '#3d3d5c'
BUTTON_HOVER = '#4d4d6c'
def clamp(value, min_val, max_val):
return max(min_val, min(max_val, value))
class ModernNodeEditor:
def __init__(self, parent, config, api_interfaces, existing_graph=None, existing_name="", save_callback=None, close_callback=None):
self.parent = parent
self.config = config
self.api_interfaces = api_interfaces
self.nodes = {}
self.connections = []
self.selected_node = None
self.canvas = None
self.node_classes = self.load_node_classes()
self.node_counter = {cls.__name__: 0 for cls in self.node_classes}
self.node_counter['MissingNode'] = 0
self.node_drag_data = {'x': 0, 'y': 0}
self.connection_start = None
self.temp_line = None
self.connection_motion_bind = None
self.connection_release_bind = None
self.instruction_name = existing_name
self.save_callback = save_callback
self.close_callback = close_callback
self.resizing_node_id = None
self.resize_start_data = None
self.is_modified = False
self.moving_node_id = None
self.selected_nodes = set()
self.dragging_nodes = []
self.is_selecting = False
self.selection_start = None
self.selection_rect = None
# Zoom and pan - applied as world transform
self.zoom_level = 1.0
self.pan_offset_x = 0
self.pan_offset_y = 0
self.panning = False
self.pan_start = {'x': 0, 'y': 0}
self.grid_size = 25
self.snap_to_grid = True
self.show_grid = True
# Minimum node dimensions
self.min_node_width = 140
self.min_node_height = 80
self.create_editor_window()
if existing_graph:
self.load_graph(existing_graph)
self.redraw_canvas()
# ==================== COORDINATE TRANSFORMS ====================
def world_to_screen(self, wx, wy):
"""Convert world coordinates to screen coordinates."""
sx = wx * self.zoom_level + self.pan_offset_x
sy = wy * self.zoom_level + self.pan_offset_y
return sx, sy
def screen_to_world(self, sx, sy):
"""Convert screen coordinates to world coordinates."""
wx = (sx - self.pan_offset_x) / self.zoom_level
wy = (sy - self.pan_offset_y) / self.zoom_level
return wx, wy
def is_open(self):
return self.editor_window.winfo_exists()
def load_node_classes(self):
return list(NODE_REGISTRY.values())
def get_node_class_by_type(self, node_type):
try:
return NODE_REGISTRY.get(node_type, lambda: MissingNode(original_type=node_type))
except Exception as e:
print(f"Error getting node class for type {node_type}: {e}")
return lambda: MissingNode(original_type=node_type)
def create_editor_window(self):
self.editor_window = tk.Toplevel(self.parent)
self.editor_window.title("Node-Based Instruction Editor")
self.editor_window.geometry("1200x800")
self.editor_window.resizable(True, True)
self.editor_window.configure(bg=Theme.CANVAS_BG)
self.editor_window.protocol("WM_DELETE_WINDOW", self.on_close)
self.create_toolbar()
canvas_frame = tk.Frame(self.editor_window, bg=Theme.CANVAS_BG)
canvas_frame.pack(fill=tk.BOTH, expand=True, padx=2, pady=2)
self.canvas = tk.Canvas(canvas_frame, bg=Theme.CANVAS_BG, highlightthickness=0)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<Button-3>", self.on_canvas_right_click)
self.canvas.bind("<ButtonPress-1>", self.on_canvas_left_press)
self.canvas.bind("<B1-Motion>", self.on_canvas_left_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_canvas_left_release)
self.canvas.bind("<MouseWheel>", self.on_mouse_wheel)
self.canvas.bind("<Button-2>", self.on_pan_start)
self.canvas.bind("<B2-Motion>", self.on_pan_move)
self.canvas.bind("<ButtonRelease-2>", self.on_pan_end)
self.canvas.bind("<Configure>", self.on_canvas_configure)
self.create_bottom_panel()
self.editor_window.after(100, self.draw_grid)
def create_toolbar(self):
toolbar = tk.Frame(self.editor_window, bg=Theme.TOOLBAR_BG, height=45)
toolbar.pack(side=tk.TOP, fill=tk.X)
toolbar.pack_propagate(False)
tk.Label(toolbar, text="Add Node:", bg=Theme.TOOLBAR_BG, fg=Theme.TEXT_PRIMARY, font=('Segoe UI', 9)).pack(side=tk.LEFT, padx=(10, 5), pady=10)
self.node_var = tk.StringVar()
node_names = sorted([cls.__name__.replace('Node', '') for cls in self.node_classes])
self.node_dropdown = ttk.Combobox(toolbar, textvariable=self.node_var, values=node_names, state="readonly", width=20)
self.node_dropdown.pack(side=tk.LEFT, padx=5, pady=10)
self.create_button(toolbar, "Add", self.on_add_button).pack(side=tk.LEFT, padx=5, pady=10)
tk.Frame(toolbar, width=2, bg=Theme.GRID_MAJOR_COLOR).pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=8)
tk.Label(toolbar, text="Zoom:", bg=Theme.TOOLBAR_BG, fg=Theme.TEXT_PRIMARY, font=('Segoe UI', 9)).pack(side=tk.LEFT, padx=(10, 5), pady=10)
self.create_button(toolbar, "−", lambda: self.zoom(-0.1), width=3).pack(side=tk.LEFT, padx=2, pady=10)
self.zoom_label = tk.Label(toolbar, text="100%", bg=Theme.TOOLBAR_BG, fg=Theme.TEXT_PRIMARY, font=('Segoe UI', 9), width=5)
self.zoom_label.pack(side=tk.LEFT, padx=2, pady=10)
self.create_button(toolbar, "+", lambda: self.zoom(0.1), width=3).pack(side=tk.LEFT, padx=2, pady=10)
self.create_button(toolbar, "Reset View", self.reset_view).pack(side=tk.LEFT, padx=10, pady=10)
self.grid_var = tk.BooleanVar(value=True)
tk.Checkbutton(toolbar, text="Grid", variable=self.grid_var, bg=Theme.TOOLBAR_BG, fg=Theme.TEXT_PRIMARY,
selectcolor=Theme.NODE_BG, activebackground=Theme.TOOLBAR_BG, command=self.toggle_grid).pack(side=tk.LEFT, padx=10, pady=10)
self.snap_var = tk.BooleanVar(value=True)
tk.Checkbutton(toolbar, text="Snap", variable=self.snap_var, bg=Theme.TOOLBAR_BG, fg=Theme.TEXT_PRIMARY,
selectcolor=Theme.NODE_BG, activebackground=Theme.TOOLBAR_BG, command=self.toggle_snap).pack(side=tk.LEFT, padx=5, pady=10)
def create_button(self, parent, text, command, width=None):
btn = tk.Button(parent, text=text, bg=Theme.BUTTON_BG, fg=Theme.TEXT_PRIMARY,
activebackground=Theme.BUTTON_HOVER, activeforeground=Theme.TEXT_PRIMARY,
relief='flat', padx=10, pady=2, command=command)
if width:
btn.config(width=width)
return btn
def create_bottom_panel(self):
bottom = tk.Frame(self.editor_window, bg=Theme.TOOLBAR_BG, height=50)
bottom.pack(side=tk.BOTTOM, fill=tk.X)
bottom.pack_propagate(False)
tk.Label(bottom, text="Instruction Set Name:", bg=Theme.TOOLBAR_BG, fg=Theme.TEXT_PRIMARY, font=('Segoe UI', 9)).pack(side=tk.LEFT, padx=(10, 5), pady=12)
self.name_var = tk.StringVar(value=self.instruction_name)
self.name_var.trace_add('write', self.on_name_changed)
name_entry = tk.Entry(bottom, textvariable=self.name_var, bg=Theme.NODE_BG, fg=Theme.TEXT_PRIMARY,
insertbackground=Theme.TEXT_PRIMARY, relief='flat', font=('Segoe UI', 10))
name_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=12)
self.save_btn = self.create_button(bottom, "Save", self.save_node_graph)
self.save_btn.config(state='disabled')
self.save_btn.pack(side=tk.RIGHT, padx=5, pady=12)
# Track window resize to enable save button
self.initial_window_size = None
self.editor_window.bind('<Configure>', self.on_window_configure)
self.create_button(bottom, "Close", self.on_close).pack(side=tk.RIGHT, padx=5, pady=12)
def draw_grid(self):
self.canvas.delete('grid')
if not self.show_grid:
return
w = self.canvas.winfo_width()
h = self.canvas.winfo_height()
if w <= 1 or h <= 1:
return
grid_size = int(self.grid_size * self.zoom_level)
if grid_size < 5:
return # Grid too small to draw
# Calculate grid offset based on pan
offset_x = self.pan_offset_x % grid_size
offset_y = self.pan_offset_y % grid_size
# Draw minor grid
for x in range(int(offset_x), w + grid_size, grid_size):
self.canvas.create_line(x, 0, x, h, fill=Theme.GRID_COLOR, tags='grid')
for y in range(int(offset_y), h + grid_size, grid_size):
self.canvas.create_line(0, y, w, y, fill=Theme.GRID_COLOR, tags='grid')
# Draw major grid (every 4 cells)
major_grid = grid_size * 4
if major_grid >= 20:
major_offset_x = self.pan_offset_x % major_grid
major_offset_y = self.pan_offset_y % major_grid
for x in range(int(major_offset_x), w + major_grid, major_grid):
self.canvas.create_line(x, 0, x, h, fill=Theme.GRID_MAJOR_COLOR, tags='grid')
for y in range(int(major_offset_y), h + major_grid, major_grid):
self.canvas.create_line(0, y, w, y, fill=Theme.GRID_MAJOR_COLOR, tags='grid')
self.canvas.tag_lower('grid')
def zoom(self, delta, center_x=None, center_y=None):
old_zoom = self.zoom_level
new_zoom = max(0.25, min(2.0, self.zoom_level + delta))
if new_zoom == old_zoom:
return
# If center point provided, zoom towards that point
if center_x is not None and center_y is not None:
# Convert center to world coords at old zoom
world_x = (center_x - self.pan_offset_x) / old_zoom
world_y = (center_y - self.pan_offset_y) / old_zoom
# Update zoom
self.zoom_level = new_zoom
# Adjust pan so the world point stays at the same screen position
self.pan_offset_x = center_x - world_x * new_zoom
self.pan_offset_y = center_y - world_y * new_zoom
else:
self.zoom_level = new_zoom
self.zoom_label.config(text=f"{int(self.zoom_level * 100)}%")
self.redraw_canvas()
def reset_view(self):
self.zoom_level = 1.0
self.pan_offset_x = 0
self.pan_offset_y = 0
self.zoom_label.config(text="100%")
self.redraw_canvas()
def toggle_grid(self):
self.show_grid = self.grid_var.get()
self.draw_grid()
def toggle_snap(self):
self.snap_to_grid = self.snap_var.get()
def on_canvas_configure(self, event):
self.draw_grid()
def on_mouse_wheel(self, event):
delta = 0.1 if event.delta > 0 else -0.1
# Zoom centered on mouse position
self.zoom(delta, event.x, event.y)
def on_pan_start(self, event):
self.panning = True
self.pan_start = {'x': event.x, 'y': event.y}
def on_pan_move(self, event):
if self.panning:
dx = event.x - self.pan_start['x']
dy = event.y - self.pan_start['y']
self.pan_offset_x += dx
self.pan_offset_y += dy
self.pan_start = {'x': event.x, 'y': event.y}
self.redraw_canvas()
def on_pan_end(self, event):
self.panning = False
def snap_position(self, x, y):
if self.snap_to_grid:
grid = self.grid_size
x = round(x / grid) * grid
y = round(y / grid) * grid
return x, y
def update_save_button_state(self):
self.save_btn.config(state='normal' if self.is_modified else 'disabled')
def on_name_changed(self, *args):
"""Called when the instruction set name is changed."""
self.is_modified = True
self.update_save_button_state()
def on_window_configure(self, event):
"""Called when the window is resized or moved."""
# Only track resize events for the main editor window
if event.widget != self.editor_window:
return
current_size = (event.width, event.height)
# Store initial size on first configure event
if self.initial_window_size is None:
self.initial_window_size = current_size
return
# If size changed from initial, mark as modified
if current_size != self.initial_window_size:
if not self.is_modified:
self.is_modified = True
self.update_save_button_state()
def on_close(self):
if self.is_modified:
if not messagebox.askokcancel("Quit", "You have unsaved changes. Discard and exit?"):
return
if self.close_callback:
self.close_callback(self)
self.editor_window.destroy()
def load_graph(self, graph_data):
self.nodes = graph_data.get('nodes', {})
self.connections = graph_data.get('connections', [])
for conn in self.connections:
conn.setdefault('disabled', False)
self.node_counter = {cls.__name__: 0 for cls in self.node_classes}
self.node_counter['MissingNode'] = 0
for node in self.nodes.values():
node_type = node['type']
if node_type not in self.node_counter:
self.node_counter[node_type] = 0
self.node_counter[node_type] += 1
# Restore viewport state if available
viewport = graph_data.get('viewport', {})
if viewport:
# Restore window size
window_width = viewport.get('window_width', 1200)
window_height = viewport.get('window_height', 800)
self.editor_window.geometry(f"{window_width}x{window_height}")
# Restore zoom and pan
self.zoom_level = viewport.get('zoom_level', 1.0)
self.pan_offset_x = viewport.get('pan_offset_x', 0)
self.pan_offset_y = viewport.get('pan_offset_y', 0)
def on_add_button(self):
node_type = self.node_var.get()
if node_type:
self.add_node(node_type)
self.node_var.set('')
def add_node(self, node_type):
node_id = str(uuid.uuid4())
node_class = self.get_node_class_by_type(node_type + 'Node')
if not node_class:
return
node_instance = node_class(node_id, self.config)
properties = node_instance.define_properties()
x, y = self.snap_position(150, 150)
node = {
'id': node_id,
'type': node_type + 'Node',
'title': node_type,
'x': x,
'y': y,
'width': 180,
'height': 120,
'properties': properties,
'inputs': node_instance.define_inputs(),
'outputs': node_instance.define_outputs(),
'canvas_items': {},
'highlight_state': False,
'selection_state': False
}
self.nodes[node_id] = node
self.draw_node(node)
self.is_modified = True
self.update_save_button_state()
def get_node_header_color(self, node_type):
node_type_lower = node_type.lower()
if 'input' in node_type_lower or 'start' in node_type_lower or 'basic' in node_type_lower:
return Theme.NODE_TYPE_PROCESS
elif 'output' in node_type_lower or 'end' in node_type_lower:
return Theme.NODE_TYPE_OUTPUT
elif 'splitter' in node_type_lower or 'merger' in node_type_lower or 'conditional' in node_type_lower or 'router' in node_type_lower:
return Theme.NODE_TYPE_LOGIC
elif node_type not in NODE_REGISTRY:
return Theme.NODE_TYPE_MISSING
else:
return Theme.NODE_HEADER
def draw_node(self, node):
# Get world coordinates and transform to screen
wx, wy = node['x'], node['y']
ww, wh = node.get('width', 180), node.get('height', 120)
# Transform to screen coordinates
x, y = self.world_to_screen(wx, wy)
width = ww * self.zoom_level
height = wh * self.zoom_level
node_type = node.get('type', 'Unknown')
header_height = 28 * self.zoom_level
is_missing = node_type not in NODE_REGISTRY
node['canvas_items'] = {}
# Shadow
shadow_offset = 4 * self.zoom_level
shadow = self.canvas.create_rectangle(
x + shadow_offset, y + shadow_offset,
x + width + shadow_offset, y + height + shadow_offset,
fill=Theme.NODE_SHADOW, outline='', tags=('node', node['id'], 'shadow')
)
node['canvas_items']['shadow'] = shadow
# Body
body = self.canvas.create_rectangle(
x, y + header_height, x + width, y + height,
fill=Theme.NODE_BG, outline=Theme.NODE_BORDER, width=2,
tags=('node', node['id'], 'body')
)
node['canvas_items']['body'] = body
# Header
header_color = self.get_node_header_color(node_type)
header = self.canvas.create_rectangle(
x, y, x + width, y + header_height,
fill=header_color, outline=Theme.NODE_BORDER, width=2,
tags=('node', node['id'], 'header', 'draggable')
)
node['canvas_items']['header'] = header
self.canvas.tag_bind(header, "<ButtonPress-1>", self.on_node_press)
self.canvas.tag_bind(header, "<B1-Motion>", self.on_node_move)
self.canvas.tag_bind(header, "<ButtonRelease-1>", self.on_node_release)
self.canvas.tag_bind(body, "<Button-3>", self.on_right_click)
self.canvas.tag_bind(body, "<Enter>", lambda e, nid=node['id']: self.on_node_enter(nid))
self.canvas.tag_bind(body, "<Leave>", lambda e, nid=node['id']: self.on_node_leave(nid))
self.canvas.tag_bind(header, "<Button-3>", self.on_right_click)
# Title - scale font size with zoom
title = node.get('title', node_type.replace('Node', ''))
if is_missing:
title = f"Missing: {node_type}"
# Truncate title to fit width
font_size = max(7, int(9 * self.zoom_level))
max_title_chars = max(8, int(width / (font_size * 0.7)))
if len(title) > max_title_chars:
title = title[:max_title_chars-2] + "..."
title_item = self.canvas.create_text(
x + width/2, y + header_height/2,
text=title, fill=Theme.TEXT_PRIMARY,
font=('Segoe UI', font_size, 'bold'), anchor='center',
tags=('node', node['id'], 'title', 'draggable')
)
node['canvas_items']['title'] = title_item
is_start = node.get('properties', {}).get('is_start_node', {}).get('default', False)
is_end = node.get('properties', {}).get('is_end_node', {}).get('default', False)
if is_start or is_end:
badge_size = max(10, int(14 * self.zoom_level))
badge_padding = max(4, int(6 * self.zoom_level))
badge_x2 = x + width - badge_padding
badge_x1 = badge_x2 - badge_size
badge_y1 = y + (header_height - badge_size) / 2
badge_y2 = badge_y1 + badge_size
badge_color = '#2ecc71' if is_start else '#e74c3c'
badge_text = 'S' if is_start else 'E'
badge = self.canvas.create_rectangle(
badge_x1, badge_y1, badge_x2, badge_y2,
fill=badge_color, outline=Theme.NODE_BORDER, width=1,
tags=('node', node['id'], 'badge', 'draggable')
)
badge_label = self.canvas.create_text(
(badge_x1 + badge_x2) / 2, (badge_y1 + badge_y2) / 2,
text=badge_text, fill=Theme.TEXT_PRIMARY,
font=('Segoe UI', max(7, int(8 * self.zoom_level)), 'bold'),
tags=('node', node['id'], 'badge', 'draggable')
)
node['canvas_items']['badge'] = badge
node['canvas_items']['badge_label'] = badge_label
self.canvas.tag_bind(title_item, "<ButtonPress-1>", self.on_node_press)
self.canvas.tag_bind(title_item, "<B1-Motion>", self.on_node_move)
self.canvas.tag_bind(title_item, "<ButtonRelease-1>", self.on_node_release)
# Description - only show if there's enough space
content_height = height - header_height
if 'properties' in node and content_height > 40 * self.zoom_level:
description = node['properties'].get('description', {}).get('default', '')
if description:
desc_font_size = max(6, int(8 * self.zoom_level))
max_desc_chars = max(10, int((width - 20) / (desc_font_size * 0.6)))
if len(description) > max_desc_chars:
description = description[:max_desc_chars-3] + "..."
desc_item = self.canvas.create_text(
x + width/2, y + header_height + 15 * self.zoom_level,
text=description, fill=Theme.TEXT_SECONDARY,
font=('Segoe UI', desc_font_size), anchor='center',
width=width - 20 * self.zoom_level,
tags=('node', node['id'], 'description')
)
node['canvas_items']['description'] = desc_item
self.draw_connectors(node, x, y, width, height, header_height)
# Resize handle
handle_size = 10 * self.zoom_level
resize_handle = self.canvas.create_polygon(
x + width, y + height - handle_size,
x + width, y + height,
x + width - handle_size, y + height,
fill=Theme.NODE_BORDER, outline='',
tags=('node', node['id'], 'resize_handle')
)
node['canvas_items']['resize_handle'] = resize_handle
self.canvas.tag_bind(resize_handle, '<ButtonPress-1>', self.on_resize_start)
self.canvas.tag_bind(resize_handle, '<B1-Motion>', self.on_resize_move)
self.canvas.tag_bind(resize_handle, '<ButtonRelease-1>', self.on_resize_end)
def draw_connectors(self, node, x, y, width, height, header_height):
connector_radius = max(5, 7 * self.zoom_level)
content_height = height - header_height
label_font_size = max(6, int(8 * self.zoom_level))
if 'inputs' in node:
num_inputs = len(node['inputs'])
gap = content_height / (num_inputs + 1) if num_inputs > 0 else content_height / 2
for idx, input_name in enumerate(node['inputs']):
cy = y + header_height + (idx + 1) * gap
connector = self.canvas.create_oval(
x - connector_radius, cy - connector_radius,
x + connector_radius, cy + connector_radius,
fill=Theme.CONNECTOR_INPUT, outline=Theme.TEXT_PRIMARY, width=2,
tags=('node', node['id'], f'input_{input_name}', 'connector')
)
node['canvas_items'][f'input_{input_name}'] = connector
self.canvas.tag_bind(connector, '<Button-1>', self.on_connector_press)
self.canvas.tag_bind(connector, '<Enter>', lambda e, c=connector: self.on_connector_enter(c))
self.canvas.tag_bind(connector, '<Leave>', lambda e, c=connector: self.on_connector_leave(c))
# Only show labels if there's enough space
if width > 80 * self.zoom_level:
label = self.canvas.create_text(
x + connector_radius + 5 * self.zoom_level, cy,
text=input_name, fill=Theme.TEXT_MUTED,
font=('Segoe UI', label_font_size), anchor='w',
tags=('node', node['id'], f'input_label_{input_name}')
)
node['canvas_items'][f'input_label_{input_name}'] = label
if 'outputs' in node:
num_outputs = len(node['outputs'])
gap = content_height / (num_outputs + 1) if num_outputs > 0 else content_height / 2
for idx, output_name in enumerate(node['outputs']):
cy = y + header_height + (idx + 1) * gap
connector = self.canvas.create_oval(
x + width - connector_radius, cy - connector_radius,
x + width + connector_radius, cy + connector_radius,
fill=Theme.CONNECTOR_OUTPUT, outline=Theme.TEXT_PRIMARY, width=2,
tags=('node', node['id'], f'output_{output_name}', 'connector')
)
node['canvas_items'][f'output_{output_name}'] = connector
self.canvas.tag_bind(connector, '<Button-1>', self.start_connection)
self.canvas.tag_bind(connector, '<Enter>', lambda e, c=connector: self.on_connector_enter(c))
self.canvas.tag_bind(connector, '<Leave>', lambda e, c=connector: self.on_connector_leave(c))
# Only show labels if there's enough space
if width > 80 * self.zoom_level:
label = self.canvas.create_text(
x + width - connector_radius - 5 * self.zoom_level, cy,
text=output_name, fill=Theme.TEXT_MUTED,
font=('Segoe UI', label_font_size), anchor='e',
tags=('node', node['id'], f'output_label_{output_name}')
)
node['canvas_items'][f'output_label_{output_name}'] = label
def on_connector_enter(self, connector):
self.canvas.itemconfig(connector, outline=Theme.CONNECTOR_HOVER, width=3)
def on_connector_leave(self, connector):
self.canvas.itemconfig(connector, outline=Theme.TEXT_PRIMARY, width=2)
def on_node_press(self, event):
clicked_item = self.canvas.find_withtag('current')[0]
tags = self.canvas.gettags(clicked_item)
if 'draggable' not in tags:
return
try:
node_id = tags[tags.index('node') + 1]
if node_id not in self.selected_nodes:
self.clear_selection()
self.set_node_selected(node_id, True)
self.moving_node_id = node_id
self.dragging_nodes = list(self.selected_nodes) or [node_id]
self.node_drag_data['x'] = event.x
self.node_drag_data['y'] = event.y
except (ValueError, IndexError):
self.moving_node_id = None
self.dragging_nodes = []
def on_node_move(self, event):
if not self.moving_node_id:
return
try:
node_ids = self.dragging_nodes or [self.moving_node_id]
# Calculate screen delta
screen_dx = event.x - self.node_drag_data['x']
screen_dy = event.y - self.node_drag_data['y']
# Convert to world delta (account for zoom)
world_dx = screen_dx / self.zoom_level
world_dy = screen_dy / self.zoom_level
for node_id in node_ids:
node = self.nodes.get(node_id)
if not node:
continue
node['x'] += world_dx
node['y'] += world_dy
items = self.canvas.find_withtag(node_id)
for item in items:
self.canvas.move(item, screen_dx, screen_dy)
self.node_drag_data['x'] = event.x
self.node_drag_data['y'] = event.y
# Only redraw connections (they need recalculation)
self.redraw_connections()
self.is_modified = True
self.update_save_button_state()
except (ValueError, IndexError, KeyError):
pass
def on_node_release(self, event):
if self.moving_node_id and self.snap_to_grid:
needs_redraw = False
for node_id in self.dragging_nodes or [self.moving_node_id]:
node = self.nodes.get(node_id)
if not node:
continue
old_x, old_y = node['x'], node['y']
new_x, new_y = self.snap_position(old_x, old_y)
if new_x != old_x or new_y != old_y:
node['x'], node['y'] = new_x, new_y
for item_id in node['canvas_items'].values():
self.canvas.delete(item_id)
self.draw_node(node)
needs_redraw = True
if needs_redraw:
self.redraw_connections()
self.moving_node_id = None
self.dragging_nodes = []
def redraw_canvas(self):
self.canvas.delete("all")
self.draw_grid()
for node_id in self.nodes:
self.draw_node(self.nodes[node_id])
self.redraw_connections()
def redraw_connections(self):
for item in self.canvas.find_withtag('connection'):
self.canvas.delete(item)
# Clear existing line segments tracking
self.existing_line_segments = []
for conn in self.connections:
self.draw_connection(conn)
def draw_connection(self, conn):
from_x, from_y = self.get_connector_position(conn['from_node'], conn['from_output'], 'output')
to_x, to_y = self.get_connector_position(conn['to_node'], conn['to_input'], 'input')
if from_x == 0 and from_y == 0:
return
if to_x == 0 and to_y == 0:
return
# Get ALL node bounding boxes including source and target for proper routing
all_boxes = self.get_node_bounding_boxes(exclude_nodes=[])
# Get source and target node boxes separately for special handling
source_box = self.get_single_node_box(conn['from_node'])
target_box = self.get_single_node_box(conn['to_node'])
# Get existing line segments for separation
existing_segments = getattr(self, 'existing_line_segments', [])
# Use A* pathfinding through visibility graph
waypoints = self.astar_orthogonal_path(from_x, from_y, to_x, to_y, all_boxes, source_box, target_box, existing_segments)
# Apply line separation to avoid parallel lines being too close
waypoints = self.apply_line_separation(waypoints, existing_segments)
# Store this connection's segments for future connections
self.store_line_segments(waypoints)
line_width = max(2, int(3 * self.zoom_level))
if conn.get('disabled'):
self.draw_disabled_path(conn, waypoints, line_width)
else:
# Draw the connection as gradient-colored segments
self.draw_gradient_path(conn, waypoints, line_width)
def draw_disabled_path(self, conn, points, line_width):
if len(points) < 4:
return
canvas_items = []
for i in range(0, len(points) - 2, 2):
x1, y1 = points[i], points[i + 1]
x2, y2 = points[i + 2], points[i + 3]
outline = self.canvas.create_line(
x1, y1, x2, y2,
fill='#5a5a5a', width=max(3, int(4 * self.zoom_level)),
capstyle='round', joinstyle='round',
tags=('connection', f'conn_{id(conn)}')
)
line = self.canvas.create_line(
x1, y1, x2, y2,
fill='#d0d0d0', width=max(2, int(2 * self.zoom_level)),
dash=(4, 4), capstyle='round', joinstyle='round',
tags=('connection', f'conn_{id(conn)}')
)
canvas_items.extend([outline, line])
conn['canvas_items'] = canvas_items
conn['canvas_item'] = canvas_items[0] if canvas_items else None
for line in canvas_items:
self.canvas.tag_bind(line, "<Button-3>", lambda e, c=conn: self.on_connection_right_click(e, c))
self.canvas.tag_bind(line, "<Enter>", lambda e, items=canvas_items: self.highlight_connection(items, True))
self.canvas.tag_bind(line, "<Leave>", lambda e, items=canvas_items: self.highlight_connection(items, False))
self.canvas.tag_lower(line, 'node')
def store_line_segments(self, points):
"""Store line segments from a drawn connection for future separation calculations."""
if not hasattr(self, 'existing_line_segments'):
self.existing_line_segments = []
# Convert flat points list to segments
if len(points) < 4:
return
for i in range(0, len(points) - 2, 2):
x1, y1 = points[i], points[i + 1]
x2, y2 = points[i + 2], points[i + 3]
# Determine if horizontal or vertical
is_horizontal = abs(y1 - y2) < 5
is_vertical = abs(x1 - x2) < 5
if is_horizontal or is_vertical:
self.existing_line_segments.append({
'x1': min(x1, x2),
'y1': min(y1, y2),
'x2': max(x1, x2),
'y2': max(y1, y2),
'horizontal': is_horizontal
})
def apply_line_separation(self, points, existing_segments):
"""Nudge line segments that run parallel and too close to existing lines."""
if len(points) < 4 or not existing_segments:
return points
min_separation = 12 * self.zoom_level # Minimum distance between parallel lines
# Convert to list of (x, y) tuples for easier manipulation
waypoints = []
for i in range(0, len(points), 2):
waypoints.append([points[i], points[i + 1]])
# Check each segment of the new path
for i in range(len(waypoints) - 1):
p1 = waypoints[i]
p2 = waypoints[i + 1]
is_horizontal = abs(p1[1] - p2[1]) < 5
is_vertical = abs(p1[0] - p2[0]) < 5
if not (is_horizontal or is_vertical):
continue
# Check against existing segments
for seg in existing_segments:
# Only compare same orientation segments
if is_horizontal and seg['horizontal']:
# Both horizontal - check if they overlap in X and are too close in Y
seg_min_x, seg_max_x = seg['x1'], seg['x2']
new_min_x, new_max_x = min(p1[0], p2[0]), max(p1[0], p2[0])
# Check X overlap
if new_max_x > seg_min_x and new_min_x < seg_max_x:
# They overlap horizontally, check Y distance
y_dist = abs(p1[1] - seg['y1'])
if 0 < y_dist < min_separation:
# Too close - nudge this segment
nudge = min_separation - y_dist
if p1[1] > seg['y1']:
nudge = nudge # Move down
else:
nudge = -nudge # Move up
# Only nudge middle waypoints, not start/end
if i > 0:
waypoints[i][1] += nudge
if i + 1 < len(waypoints) - 1:
waypoints[i + 1][1] += nudge
elif is_vertical and not seg['horizontal']:
# Both vertical - check if they overlap in Y and are too close in X
seg_min_y, seg_max_y = seg['y1'], seg['y2']
new_min_y, new_max_y = min(p1[1], p2[1]), max(p1[1], p2[1])
# Check Y overlap
if new_max_y > seg_min_y and new_min_y < seg_max_y:
# They overlap vertically, check X distance
x_dist = abs(p1[0] - seg['x1'])
if 0 < x_dist < min_separation:
# Too close - nudge this segment
nudge = min_separation - x_dist
if p1[0] > seg['x1']:
nudge = nudge # Move right
else:
nudge = -nudge # Move left
# Only nudge middle waypoints, not start/end
if i > 0:
waypoints[i][0] += nudge
if i + 1 < len(waypoints) - 1:
waypoints[i + 1][0] += nudge
# Convert back to flat list
result = []
for wp in waypoints:
result.extend(wp)
return result
def get_single_node_box(self, node_id):
"""Get bounding box for a single node."""
node = self.nodes.get(node_id)
if not node:
return None
padding = 10 * self.zoom_level
sx, sy = self.world_to_screen(node['x'], node['y'])
sw = node.get('width', 180) * self.zoom_level
sh = node.get('height', 120) * self.zoom_level
return {
'id': node_id,
'x1': sx - padding,
'y1': sy - padding,
'x2': sx + sw + padding,
'y2': sy + sh + padding,
'cx': sx + sw / 2,
'cy': sy + sh / 2
}
def get_node_bounding_boxes(self, exclude_nodes=None):
"""Get bounding boxes for all nodes (in screen coordinates) for collision detection."""
exclude_nodes = exclude_nodes or []
boxes = []
padding = 15 * self.zoom_level # Padding around nodes
for node_id, node in self.nodes.items():
if node_id in exclude_nodes:
continue
# Convert world coords to screen coords
sx, sy = self.world_to_screen(node['x'], node['y'])
sw = node.get('width', 180) * self.zoom_level
sh = node.get('height', 120) * self.zoom_level
# Add padding
boxes.append({
'id': node_id,
'x1': sx - padding,
'y1': sy - padding,
'x2': sx + sw + padding,
'y2': sy + sh + padding,
'cx': sx + sw / 2, # Center X
'cy': sy + sh / 2 # Center Y
})
return boxes
def line_intersects_box(self, x1, y1, x2, y2, box):
"""Check if a line segment intersects a bounding box."""
# Check if line is completely outside box
if max(x1, x2) < box['x1'] or min(x1, x2) > box['x2']:
return False
if max(y1, y2) < box['y1'] or min(y1, y2) > box['y2']:
return False
# Check if either endpoint is inside the box
if box['x1'] <= x1 <= box['x2'] and box['y1'] <= y1 <= box['y2']:
return True
if box['x1'] <= x2 <= box['x2'] and box['y1'] <= y2 <= box['y2']:
return True
# Check line intersection with box edges
edges = [
(box['x1'], box['y1'], box['x2'], box['y1']), # Top
(box['x1'], box['y2'], box['x2'], box['y2']), # Bottom
(box['x1'], box['y1'], box['x1'], box['y2']), # Left
(box['x2'], box['y1'], box['x2'], box['y2']), # Right
]
for ex1, ey1, ex2, ey2 in edges:
if self.lines_intersect(x1, y1, x2, y2, ex1, ey1, ex2, ey2):
return True
return False
def lines_intersect(self, x1, y1, x2, y2, x3, y3, x4, y4):
"""Check if two line segments intersect."""
def ccw(ax, ay, bx, by, cx, cy):
return (cy - ay) * (bx - ax) > (by - ay) * (cx - ax)
return (ccw(x1, y1, x3, y3, x4, y4) != ccw(x2, y2, x3, y3, x4, y4) and
ccw(x1, y1, x2, y2, x3, y3) != ccw(x1, y1, x2, y2, x4, y4))
def astar_orthogonal_path(self, from_x, from_y, to_x, to_y, node_boxes, source_box=None, target_box=None, existing_segments=None):
"""Use A* pathfinding on an orthogonal visibility graph to find optimal path.
Key rules:
- Output connections MUST go RIGHT first (away from source node)
- Input connections MUST come from LEFT (into target node)
"""
import heapq
existing_segments = existing_segments or []
offset = 25 * self.zoom_level