-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheditor.py
1382 lines (1265 loc) · 57.8 KB
/
editor.py
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
#this is where the graphical node editor happens
import tkinter as tk
import random
import math
import copy
from tkinter import ttk
from tkinter import filedialog
from src import decoder, encoder
from src.lib import fs, util, atoms
from src.lib.luts import nodes, typeLists, enums, names, fieldAtoms
from src.nitro import nitro
import os
DEBUG = False
MED_FONT = ("Verdana", 9)
BOL_FONT = ("Verdana bold", 9)
THK_FONT = ("Arial bold", 14)
CODEFONT = ("Consolas", 8)
DOT_SIZE = 5
PORT_OFF = 15
TOTAL_OFF = 25
LINE_WID = 3
LINE_COL = "#fd811a"
H_MULT = 3
V_MULT = 1
UI_H_MULT = 5
UI_V_MULT = UI_H_MULT
BORDER = 8
NODECOL = "#eee"
BASECOL = "#414141"
ACCCOL1 = "#535353"
ACCCOL2 = "#888"
ACCCOL3 = "#3dd9ff"
INSP_WIDTH = 50
#TODO add ui editor
#TODO add node name tooltip viewer
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
try:
tk.Tk.iconbitmap(self, default="bwEdit.ico")
except:
try:
tk.Tk.iconbitmap(self, default="@bwEdit.xbm")
except:
pass
tk.Tk.wm_title(self, "bwEdit")
top = self.winfo_toplevel() #menu bar
self.menuBar = tk.Menu(top)
top['menu'] = self.menuBar
self.subMenu = tk.Menu(self.menuBar, tearoff=0) #file
self.menuBar.add_cascade(label='File', menu=self.subMenu)
self.subMenu.add_command(label='Save As', command=self.savefile)
self.subMenu.add_command(label='Load', command=self.openfile)
self.subMenu.add_command(label='Export to JSON', command=self.exportfile)
self.subMenu.add_separator()
self.subMenu.add_command(label='Exit',)
self.subMenu = tk.Menu(self.menuBar, tearoff=0) #help
self.menuBar.add_cascade(label='Help', menu=self.subMenu)
self.subMenu.add_command(label='About',)
self.file = ''
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
container.grid_rowconfigure(0,weight = 1)
container.grid_columnconfigure(0,weight = 1)
self.frames = {}
for f in (MainPage,):
frame = f(container, self)
self.frames[f] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(MainPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def openfile(self):
filename = tk.filedialog.askopenfilename(filetypes = (("All Files", "*.*"),
("Bitwig Devices", "*.bwdevice"),
("Bitwig Modulators", "*.bwmodulator"),
("Bitwig Presets", "*.bwpreset"),
))
f = ''
print ('-'+filename)
tk.Tk.wm_title(self, filename)
with open(filename, 'rb') as readThis:
r = readThis.read()
#self.frames[MainPage].editor.header = r[:24]
f = decoder.bwDecode(r)
self.frames[MainPage].editor.load(f)
def savefile(self):
self.frames[MainPage].editor.treeifyData()
with tk.filedialog.asksaveasfile(mode='wb', defaultextension=".bw", filetypes = (("", ""), #TODO automatically find filetype
("Bitwig Devices", "*.bwdevice"),
("Bitwig Modulators", "*.bwmodulator"),
("Bitwig Presets", "*.bwpreset"),
)) as f:
if f is None: #in case of cancel
return
header = self.frames[MainPage].editor.header
header = header[:11] + '2' + header[12:]
output = header.encode('utf-8') + encoder.bwEncode(self.frames[MainPage].editor.data)
f.write(output)
def exportfile(self): #same as save except it serializes the json instead of encoding it
self.frames[MainPage].editor.treeifyData()
with tk.filedialog.asksaveasfile(mode='wb', defaultextension=".bw") as f:
if f is None: #in case of cancel
return
header = self.frames[MainPage].editor.header
output = ''
for item in self.frames[MainPage].editor.data:
output += util.json_encode(atoms.serialize(item))
output = header + decoder.reformat(output)
f.write(output.encode("utf-8"))
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.editor = NodeEditorCanvas(self)
self.editor.pack(fill="both", expand=True)
class NodeEditorCanvas(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.data=0
#self.data_info = {}
self.header = 'BtWg00010001008d000016a00000000000000000'
self.canvas = tk.Canvas(self, bg = "#2e2e2e")
self.canvas.config(width=1500, height=1000)
self.hbar=tk.Scrollbar(self,orient='horizontal')
self.hbar.pack(side='bottom',fill='x')
self.hbar.config(command=self.canvas.xview)
self.vbar=tk.Scrollbar(self,orient='vertical')
self.vbar.pack(side='right',fill='y')
self.vbar.config(command=self.canvas.yview)
self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)
self.pCanvas = tk.Canvas(self, bg = "#1e1e1e")
self.pCanvas.config(width=1500, height=59*UI_H_MULT)
self.pCanvas.pack(side = 'bottom',fill='x', expand=True)
self.canvas.pack(side = 'top', fill="both", expand=True)
self.update()
self.canvas.config(scrollregion=self.canvas.bbox("all"))
#self.canvas.create_oval(0,0,10,10, activeoutline = "black" , outline=NODECOL, fill=NODECOL ,tags=("poop"))
self._drag_data = {"relPos": {}, "item": None}
#self._new_conn_data = {"start": 0, "end": 0, "type0": '', "type1": '', "port0": '', "port1": ''}
self._new_conn_data = {}
self._currentlyConnecting = False
self._dragged = False
self._inspector_active = False
self._input_active = False
self._manager_active = False
self._browser_active = False
self._rclicked = None
self._selected = []
self._browser_clicked = None
self.size = 0
self.numLines = 0
objLocs = []
objSize = []
self.linePorts = {}
self._currentlyConnecting = False
self.buffers = []
self.inports = []
self.atomList = []
self.portList = []
self.RortList = []
self.paneList = [] #unused probably, since panels can just be stored as atoms
self.panelMap = [] #index is panel object list, stores references
#click and button bindings
self.canvas.tag_bind("case||name||deco", "<ButtonPress-1>", self._on_atom_press)
self.canvas.tag_bind("case||name||deco", "<ButtonRelease-1>", self._on_atom_release)
self.canvas.tag_bind("case||name||deco", "<B1-Motion>", self._on_atom_motion)
self.canvas.tag_bind("case||name||deco", "<ButtonPress-3>", self.on_atom_rc_press)
self.canvas.tag_bind("case||name||deco", "<ButtonRelease-3>", self.on_atom_rc_release)
self.canvas.tag_bind("delete", "<ButtonPress-1>", self._on_del_press)
self.canvas.tag_bind("delete", "<ButtonRelease-1>", self._on_del_release)
self.canvas.tag_bind("refresh", "<ButtonPress-1>", self._on_refresh_press)
self.canvas.tag_bind("refresh", "<ButtonRelease-1>", self._on_refresh_release)
self.canvas.tag_bind("exportnitro", "<ButtonPress-1>", self._on_export_nitro_press)
self.canvas.tag_bind("exportnitro", "<ButtonRelease-1>", self._on_export_nitro_release)
self.canvas.tag_bind("inspector", "<ButtonPress-1>", self.on_inspector_click)
self.canvas.tag_bind("port", "<ButtonPress-1>", self.on_port_press)
self.canvas.tag_bind("conn", "<ButtonPress-1>", self.on_conn_press)
self.canvas.bind("<Motion>", self.on_move)
self.canvas.bind("<ButtonPress-1>", self.on_click)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
self.canvas.bind_all("<Double-Button-1>", self._on_2c_press)
self.canvas.bind_all("<ButtonPress-2>", self._on_mc_press)
self.canvas.bind_all("<B2-Motion>", self._on_mc_motion)
self.canvas.bind_all("<Return>", self._on_enter)
def load(self, file):
self.data = file
self.canvas.delete("all")
self.pCanvas.delete("all")
self.size = 0
self.numLines = 0
objLocs = []
objSize = []
self.linePorts = {}
self._currentlyConnecting = False
self.buffers = []
self.inports = []
self.atomList = []
self.portList = []
self.RortList = []
self.paneList = [] #unused probably, since panels can just be stored as atoms
self.panelMap = [] #index is object, stores list of references
#flatten data
for eachField in ("child_components(173)","proxy_in_ports(177)","proxy_out_ports(178)"):
for item in range(len(self.data[1].fields[eachField])):
if isinstance(self.data[1].fields[eachField][item], atoms.Atom):
self.atomList.append(self.data[1].fields[eachField][item])
self.atomList = self.flattenData(self.atomList, True)
for item in range(len(self.data[1].fields["panels(6213)"])):
if isinstance(self.data[1].fields["panels(6213)"][item], atoms.Atom):
self.paneList.append(self.data[1].fields["panels(6213)"][item])
#self.paneList = self.flattenData(self.paneList, True)
#draw atoms and connections and panels
for item in self.atomList:
if item:
self.drawKids(item)
self.drawConnections()
self._draw_panel(self.paneList[0], xOff = 3*UI_V_MULT, yOff = 3*UI_H_MULT)
#update scroll region
self.update()
sr = self.canvas.bbox("all")
p = 600
sr = (sr[0]-p,sr[1]-p,sr[2]+p,sr[3]+p,)
self.canvas.config(scrollregion=sr)
#scroll and zoom
def _on_mousewheel(self, event):#TODO implement zoom instead of scroll
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def _on_mc_press(self, event):
self.canvas.scan_mark(event.x, event.y)
def _on_mc_motion(self, event):
self.canvas.scan_dragto(event.x, event.y, gain=1)
#clicking/dragging atoms and connections
def _on_atom_press(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
self._drag_data["item"] = self.canvas.gettags(self.canvas.find_withtag("current"))[1] #id is tags[1]
self._dragged = False
for item in self.canvas.find_withtag(self._drag_data["item"]):
c = self.canvas.coords(item)
output = []
xySelect = True
for i in c:
output.append(i-(x if xySelect else y))
xySelect = not xySelect
self._drag_data["relPos"][item] = output
def _on_atom_motion(self, event):
self._dragged = True
eX,eY = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
xOff, yOff = eX-event.x, eY-event.y
idNum = int(self._drag_data["item"][2:])
rPos = self._drag_data["relPos"][self.canvas.find_withtag(self._drag_data["item"]+"&&case")[0]]
w = rPos[2]-rPos[0]
h = rPos[3]-rPos[1]
x = min(max(0+xOff,eX+rPos[0]), self.canvas.winfo_width()-w+xOff)
y = min(max(0+yOff,eY+rPos[1]), self.canvas.winfo_height()-h+yOff)
if len(self.portList) > idNum:
for i in range(len(self.portList[idNum])): #redraw incoming connections
inport = self.portList[idNum][i]
if inport != None:
name = str(idNum) + ':' + str(i) + ',' + str(inport[0]) + ':' + str(inport[1])
#print("i", name)
current = self.canvas.coords(name)
dist = min(abs(current[0] - current[6])/4,75) #for curvature
newC = (x, y + PORT_OFF*(i)+TOTAL_OFF)
self.canvas.coords(name, current[0], current[1], current[0]+dist, current[1], newC[0]-dist, newC[1], newC[0], newC[1])
if len(self.RortList) > idNum:
for o in range(len(self.RortList[idNum])): #redraw outgoing connections
outportList = self.RortList[idNum][o]
if outportList:
for outport in outportList:
if outport != None:
name = str(outport[0]) + ':' + str(outport[1]) + ',' + str(idNum) + ':' + str(o)
#print("o", name)
current = self.canvas.coords(name)
dist = min(abs(current[0] - current[6])/4,75) #for curvature
newC = (x + w, y + PORT_OFF*(o)+TOTAL_OFF)
self.canvas.coords(name, newC[0], newC[1], newC[0]+dist, newC[1], current[6]-dist, current[7], current[6], current[7])
for item in self.canvas.find_withtag(self._drag_data["item"]): #redraw cell
tag = self.canvas.gettags(item)[2]
localr = self._drag_data["relPos"][item]
newC = []
xySelect = True
for i in localr:
newC.append((x-rPos[0] if xySelect else y-rPos[1])+i)
xySelect = not xySelect
self.canvas.coords(item, *newC)
def _on_atom_release(self, event):
if self._dragged:
#add layer correction (atoms with a smaller y position should be on a lower canvas layer)
rPos = self._drag_data["relPos"][self.canvas.find_withtag(self._drag_data["item"]+"&&case")[0]]
idNum = int(self._drag_data["item"][2:])
atomX, atomY = self.canvas.canvasx(event.x)+rPos[0], self.canvas.canvasy(event.y)+rPos[1]
self.atomList[self.atomList[self.atomList[idNum].fields["settings(6194)"].id].fields["desktop_settings(612)"].id].fields["y(18)"] = int(atomX/H_MULT)
self.atomList[self.atomList[self.atomList[idNum].fields["settings(6194)"].id].fields["desktop_settings(612)"].id].fields["x(17)"] = int(atomY/V_MULT)
else:
id = int(self._drag_data["item"][2:])
self._draw_inspector(self.atomList[id], event.x, event.y)
#print("clicked")
self._drag_data["item"] = None
self._drag_data["x"] = 0
self._drag_data["y"] = 0
def on_conn_press(self, event): #deletes the connection that is currently being clicked on
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
tags = self.canvas.gettags(self.canvas.find_withtag("current"))
if "conn" in tags:
#delete drawn connection
lineIndex = tags[1]
self.canvas.delete(tags[1])
#delete from port list
connData = [int(x) for x in lineIndex.replace(':',',').split(',')]
self.delConn(*connData)
self.atomList[self.atomList[self.atomList[connData[0]].fields["settings(6194)"].id].fields["inport_connections(614)"][connData[1]].id].fields["source_component(248)"] = None
self.atomList[self.atomList[self.atomList[connData[0]].fields["settings(6194)"].id].fields["inport_connections(614)"][connData[1]].id].fields["outport_index(249)"] = 0
def on_port_press(self, event): #begins or completes a connection TODO simplify this a little
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
if self._currentlyConnecting:
end = self.canvas.find_closest(x, y)
drainTags = self.canvas.gettags(*end)
if 'port' in drainTags:
#set variables
typeE = drainTags[4]
portE = drainTags[5]
#check to ensure ports go from in to out
if self._new_conn_data['typeS'] == typeE:
return
#set all my source and drain variables
sID, dID = int(self.canvas.gettags(*self._new_conn_data['start'])[1][2:]), int(drainTags[1][2:])
sPort, dPort = int(self._new_conn_data['portS']), int(portE)
sPos, dPos = self.canvas.coords(self._new_conn_data['start']), self.canvas.coords(end)
if self._new_conn_data['typeS'] == 'in':
sID, dID = dID, sID
sPort, dPort = dPort, sPort
sPos, dPos = dPos, sPos
if len(self.portList) > dID:
if len(self.portList[dID]) > dPort:
if self.portList[dID][dPort]: #check to make sure only one in connection per port
return
#draw new connection
self.canvas.delete("connecting")
sX, sY, dX, dY = (sPos[0] + sPos[2]) / 2, (sPos[1] + sPos[3]) / 2, (dPos[0] + dPos[2]) / 2, (dPos[1] + dPos[3]) / 2
dist = min(abs(sX - dX)/4,75) #for curvature
name = str(dID) + ':' + str(dPort) + ',' + str(sID) + ':' + str(sPort)
self.canvas.tag_lower(self.canvas.create_line(sX, sY, sX+dist, sY, dX-dist, dY, dX, dY,
activefill = "white", width = LINE_WID, fill = LINE_COL, smooth=True, tags=('grapheditor', name, "conn")))
self.addConn(dID,dPort,sID,sPort)
while len(self.atomList[self.atomList[dID].fields["settings(6194)"].id].fields["inport_connections(614)"]) < dPort+1: #add empty inport connections
self.atomList[self.atomList[dID].fields["settings(6194)"].id].fields["inport_connections(614)"].append(atoms.Reference(self.addAtom('float_core.inport_connection(105)')))
self.atomList[self.atomList[self.atomList[dID].fields["settings(6194)"].id].fields["inport_connections(614)"][dPort].id].fields["source_component(248)"] = atoms.Reference(sID)
self.atomList[self.atomList[self.atomList[dID].fields["settings(6194)"].id].fields["inport_connections(614)"][dPort].id].fields["outport_index(249)"] = sPort
self._currentlyConnecting = False
else:
self._new_conn_data['start'] = self.canvas.find_closest(x, y)
tags = self.canvas.gettags(*self._new_conn_data['start'])
if tags[3] == 'port':
#set variables
self._new_conn_data['typeS'] = tags[4]
self._new_conn_data['portS'] = tags[5]
#find coords
c = self.canvas.coords(self._new_conn_data['start'])
nX, nY = (c[0] + c[2]) / 2, (c[1] + c[3]) / 2
mX, mY = x, y
if self._new_conn_data['typeS'] == 'in':
nX, nY, mX, mY = mX, mY, nX, nY
#draw pending connection
dist = min(abs(nX - mX)/4,75) #for curvature
self.canvas.tag_lower(self.canvas.create_line(nX, nY, nX+dist, nY, mX-dist, mY, mX, mY,
width=LINE_WID, fill='white', smooth=True, tags=('grapheditor', 'connecting')))
self._currentlyConnecting = True
def on_move(self, event): #redraws pending connection
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
if (self._currentlyConnecting):
#find coords
c = self.canvas.coords(self._new_conn_data['start'])
nX, nY = (c[0] + c[2]) / 2, (c[1] + c[3]) / 2
mX, mY = x, y
#move pending connection
dist = min(abs(c[0] - mX)/4,75) #for curvature
if self._new_conn_data['typeS'] == 'in':
nX, nY, mX, mY = mX, mY, nX, nY
self.canvas.coords("connecting", nX, nY, nX+dist, nY, mX-dist, mY, mX, mY)
def on_click(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clickedOn = self.canvas.find_withtag("current")
if self._currentlyConnecting:
tags = self.canvas.gettags(*clickedOn)
if len(clickedOn) == 1 and "port" not in tags:
self.canvas.delete("connecting")
self._currentlyConnecting = False
if clickedOn:
return
if self._inspector_active:
self.canvas.delete("inspector")
self.canvas.delete("input")
self._inspector_active = False
if self._manager_active:
self.canvas.delete("manager")
self._manager_active = False
if self._browser_active:
self.canvas.delete("browser")
self._browser_active = False
#menus TODO limit menu positions to inside of the window
#inspector
def _draw_inspector(self, obj, eX,eY, overwrite = True):
clickedOn = self.canvas.find_withtag("current")
currentTags = self.canvas.gettags(clickedOn)
if overwrite:
self.canvas.delete("inspector")
self.listList = []
self.listNum = 0
self.canvas.delete("manager")
self._manager_active = False
self._inspector_active = True
x,y = self.canvas.canvasx(eX), self.canvas.canvasy(eY)
maxWidth = 5
if "n_list" in currentTags:
fieldOffset = 0
iterate = range(len(obj))
id = currentTags[4]
inspWind = self.canvas.create_rectangle(x, y, x+10, y+10, outline=LINE_COL, fill=BASECOL, tags=("grapheditor","id"+str(id), "4pt", "inspwind", "inspector"))
else:
fieldOffset = 1
name = obj.classname.split('.', maxsplit = 1)
name = name[-1] + " id: " + str(obj.id)
id = obj.id
inspWind = self.canvas.create_rectangle(x, y, x+10, y+10, outline=LINE_COL, fill=BASECOL, tags=("grapheditor","id"+str(id), "4pt", "inspwind", "inspector"))
canvasText = self.canvas.create_text(x+BORDER,y+BORDER+BOL_FONT[1],fill="white",font=BOL_FONT, text=name, anchor="w", tags=("grapheditor","id"+str(id), "2pt", "text", "inspector",))
textBounds = self.canvas.bbox(canvasText)
maxWidth = max(textBounds[2] - textBounds[0], maxWidth)
iterate = obj.fields
for fields in iterate: #TODO clean this up
tags = ("grapheditor","id"+str(id), "2pt", "text",)
if isinstance(obj, atoms.Atom):
item = obj.fields[fields]
else:
item = obj[fields]
if type(item) in (int, str, float, bool, None,):
if fields == "code(6264)":
text = "{" + str(fields) + "}"
elif fields in enums.usesEnums:
text = str(fields) + ": " + str(enums.usesEnums[fields][item])
else:
text = str(fields) + ": " + str(item)
tags += ("variable", fields)
elif type(item) in (atoms.Atom, atoms.Reference):
text = "<" + str(fields) + ">"
tags+=(item.id, "nestedInsp",)
elif type(item) in (list,):
text = "[" + str(fields) + "]"
self.listList.append(item)
tags+=(str(self.listNum), "nestedInsp", "n_list",)
self.listNum+=1
else:
text = fields + ": invalid"
tags+=("inspector",)
text = self.canvas.create_text(x+BORDER,y+BORDER+MED_FONT[1]*2*fieldOffset+MED_FONT[1],fill="white",font=MED_FONT, text=text, anchor="w", tags=tags)
textBounds = self.canvas.bbox(text)
maxWidth = max(textBounds[2] - textBounds[0], maxWidth)
fieldOffset += 1
c = self.canvas.coords(inspWind)
self.canvas.coords(inspWind, c[0], c[1], x+maxWidth+BORDER*2, y+fieldOffset*2*MED_FONT[1] + BORDER + MED_FONT[1])
def on_inspector_click(self, event):
clickedOn = self.canvas.find_withtag("current")
tags = self.canvas.gettags(clickedOn)
if "variable" in tags:
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
id = int(tags[1][2:])
field = tags[5]
self._draw_modifier(id, x, y, field)
self._input_active = True
elif "nestedInsp" in tags:
if "n_list" in tags:
self._draw_inspector(self.listList[int(tags[4])], event.x, event.y, False)
else:
self._draw_inspector(self.atomList[int(tags[4])], event.x, event.y, False)
def _draw_modifier(self, id, x, y, field,):
self.canvas.delete("input")
self._input = tk.Entry(self.canvas)
self.canvas.create_window(x, y, window = self._input, anchor = "nw", tags = ("grapheditor","id"+str(id), "2pt", "input",))
self._input_data = (id, field,)
def _on_enter(self, event):
print("enter")
if self._input_active:
#parse the input
fieldNum = int(''.join([s for s in self._input_data[1] if s.isdigit()]))
#print(fieldNum)
type = typeLists.fieldList[fieldNum]
if type == 1:
if self._input.get().isdigit():
self.atomList[self._input_data[0]].fields[self._input_data[1]] = int(self._input.get())
elif self._input_data[1] in enums.usesEnums:
if self._input.get() in enums.usesEnums[self._input_data[1]]:
self.atomList[self._input_data[0]].fields[self._input_data[1]] = enums.usesEnums[self._input_data[1]].index(self._input.get())
elif type == 5:
if self._input.get().lower() in ('0','f','false'):
self.atomList[self._input_data[0]].fields[self._input_data[1]] = False
elif self._input.get().lower() in ('1','t','true'):
self.atomList[self._input_data[0]].fields[self._input_data[1]] = True
elif type == 6 or type == 7:
self.atomList[self._input_data[0]].fields[self._input_data[1]] = float(self._input.get())
elif type == 8:
self.atomList[self._input_data[0]].fields[self._input_data[1]] = str(self._input.get())
else:
print("modification of this parameter is not yet permitted")
self.canvas.delete("input")
self._input_active = False
#TODO redraw inspector?
#rc menu
def on_atom_rc_press(self, event):
rclicked = self.canvas.find_withtag("current")
self._rclicked = rclicked
print(rclicked)
def on_atom_rc_release(self, event):
rclicked = self.canvas.find_withtag("current")
if rclicked == self._rclicked:
id = int(self.canvas.gettags(rclicked)[1][2:])
self._draw_manager(self.atomList[id], event.x, event.y)
self._rclicked = None
print(rclicked)
def _draw_manager(self, obj, eX,eY,):#probably unnecessary once hotkeys are in place
clickedOn = self.canvas.find_withtag("current")
currentTags = self.canvas.gettags(clickedOn)
id = int(currentTags[1][2:])
self.canvas.delete("manager")
self.canvas.delete("inspector")
self._manager_active = True
self._inspector_active = True
self._currently_managed = True
x,y = self.canvas.canvasx(eX), self.canvas.canvasy(eY)
manaWind = self.canvas.create_rectangle(x, y, x+10, y+10, outline=ACCCOL3, fill=BASECOL, tags=("grapheditor","id"+str(id), "4pt", "manawind", "manager")) #id might be problematic for lists
maxWidth = 5
fieldOffset = 0
'''#add name
name = obj.classname
i = 0
while i < len(name):
if name[i] == '.':
break
i+=1
else:
i = -1;
name = name[i+1:] + " id: " + str(obj.id)
canvasText = self.canvas.create_text(x+BORDER,y+BORDER+BOL_FONT[1],fill="white",font=BOL_FONT, text=name, anchor="w",
tags=("grapheditor","id"+str(id), "2pt", "text", "manager",))
textBounds = self.canvas.bbox(canvasText)
maxWidth = max(textBounds[2] - textBounds[0], maxWidth)'''
#add delete
if obj.classname != "float_core.proxy_in_port_component(154)":
text = self.canvas.create_text(x+BORDER,y+MED_FONT[1]*2*fieldOffset+BOL_FONT[1]+BORDER,fill="white",font=MED_FONT, text="DELETE ATOM", anchor="w",
tags=("grapheditor","id"+str(id), "2pt", "text", "delete", "manager",))
textBounds = self.canvas.bbox(text)
maxWidth = max(textBounds[2] - textBounds[0], maxWidth)
fieldOffset += 1
#add code export for nitro
if obj.classname == 'float_common_atoms.nitro_atom(1721)':
text = self.canvas.create_text(x+BORDER,y+MED_FONT[1]*2*fieldOffset+BOL_FONT[1]+BORDER,fill="white",font=MED_FONT, text="Export nitro code", anchor="w",
tags=("grapheditor","id"+str(id), "2pt", "text", "exportnitro", "manager",))
textBounds = self.canvas.bbox(text)
maxWidth = max(textBounds[2] - textBounds[0], maxWidth)
fieldOffset += 1
text = self.canvas.create_text(x+BORDER,y+MED_FONT[1]*2*fieldOffset+BOL_FONT[1]+BORDER,fill="white",font=MED_FONT, text="Refresh atom", anchor="w",
tags=("grapheditor","id"+str(id), "2pt", "text", "refresh", "manager",))
textBounds = self.canvas.bbox(text)
maxWidth = max(textBounds[2] - textBounds[0], maxWidth)
fieldOffset += 1
#resize manager window to text
c = self.canvas.coords(manaWind)
self.canvas.coords(manaWind, c[0], c[1], x+maxWidth+BORDER*2, y+fieldOffset*2*MED_FONT[1] + 2*BORDER + BOL_FONT[1])
#print(id)
#print(self.data_info[id])
def _on_del_press(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clicked = self.canvas.find_closest(x, y)
self._deleting = clicked
def _on_del_release(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clicked = self.canvas.find_closest(x, y)
if clicked == self._deleting:
id = int(self.canvas.gettags(clicked)[1][2:])
self.delAtom(id)
self._deleting = None
def _on_refresh_press(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clicked = self.canvas.find_closest(x, y)
self._refreshing = clicked
def _on_refresh_release(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clicked = self.canvas.find_closest(x, y)
if clicked == self._refreshing:
self.refresh(clicked)
self._refreshing = None
def refresh(self, clicked = 0):
id = int(self.canvas.gettags(clicked)[1][2:])
self.canvas.delete(self.canvas.gettags(clicked)[1])
self._draw_atom(self.atomList[id])
print(self.atomList[id].stringify())
print("refreshing")
def _on_export_nitro_press(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clicked = self.canvas.find_closest(x, y)
self._exporting_nitro = clicked
def _on_export_nitro_release(self, event):
x,y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
clicked = self.canvas.find_closest(x, y)
if clicked == self._exporting_nitro:
id = int(self.canvas.gettags(clicked)[1][2:])
output = self.atomList[id].fields["code(6264)"].replace('\\n','\n')
with tk.filedialog.asksaveasfile(mode='w', defaultextension=".nitro") as f:
if f is None: #in case of cancel
self._exporting_nitro = None
return
f.write(output)
self._exporting_nitro = None
#browser
def _on_2c_press(self, event):
if not self.canvas.find_withtag("current"):
self._draw_browser(event.x, event.y)
def _draw_browser(self, eX,eY,):
x,y = self.canvas.canvasx(eX), self.canvas.canvasy(eY)
self.canvas.delete("browser")
self._browser_active = True
self._browser = tk.Frame(self.canvas)
self._browser_canvas = tk.Canvas(self._browser, bg=BASECOL)
self._browser_canvas.config(height = 400, width = 200)
self.vbar=tk.Scrollbar(self._browser,orient='vertical')
self.vbar.pack(side='right',fill='y')
self.vbar.config(command=self._browser_canvas.yview)
self._browser_canvas.config(yscrollcommand=self.vbar.set)
self._browser_canvas.pack(side = 'left', fill="both", expand=True)
self._browser_position = (x,y,)
offset=0
for i in nodes.list:
self._browser_canvas.create_text(5+BORDER,5+BORDER+MED_FONT[1]*2*offset,fill="white",font=MED_FONT, text=nodes.list[i]['name'], anchor="w",
tags=("grapheditor", i, "text", "browser",))
offset +=1
self._browser.update()
self._browser_canvas.config(scrollregion=self._browser_canvas.bbox("all"))
self.canvas.create_window(x, y, window = self._browser, anchor = "nw", tags = ("grapheditor","id"+str(id), "2pt", "browser",))
self._browser_canvas.tag_bind("browser", "<ButtonPress-1>", self._on_browser_press)
self._browser_canvas.tag_bind("browser", "<ButtonRelease-1>", self._on_browser_release)
def _on_browser_press(self, event):
x,y = self._browser_canvas.canvasx(event.x), self._browser_canvas.canvasy(event.y)
self._browser_clicked = self._browser_canvas.find_closest(x, y)
#tags = self.canvas.gettags(clicked)
def _on_browser_release(self, event):
x,y = self._browser_canvas.canvasx(event.x), self._browser_canvas.canvasy(event.y)
clicked = self._browser_canvas.find_closest(x, y)
if clicked and self._browser_clicked == clicked:
tags = self._browser_canvas.gettags(clicked)
self.addAtom(tags[1])
self.canvas.delete("browser")
self._browser_active = False
pass
def drawKids(self, child,):
if isinstance(child, atoms.Atom):
if "settings(6194)" in child.fields:#if its a regular atom
self._draw_atom(child)
kid = self.atomList[child.fields["settings(6194)"].id].fields["inport_connections(614)"]
inportCount = 0
for i in kid:
inportConn = self.atomList[i.id]
if inportConn.fields["source_component(248)"]:
obj = self.atomList[inportConn.fields["source_component(248)"].id]
if isinstance(obj, atoms.Atom):
if "settings(6194)" in obj.fields:
self.addConn(child.id, inportCount, obj.id, inportConn.fields["outport_index(249)"])
inportCount += 1
def addConn(self, dID,dPort, sID,sPort,): #d is drain, s is source
listLengths = max(sID+1,dID+1)
while len(self.portList) < listLengths:
self.portList.append([])
while len(self.portList[dID]) < dPort+1:
self.portList[dID].append(None)
self.portList[dID][dPort] = (sID, sPort)
while len(self.RortList) < listLengths:
self.RortList.append([])
while len(self.RortList[sID]) < sPort+1:
self.RortList[sID].append([])
self.RortList[sID][sPort].append((dID, dPort))
def delConn(self, dID,dPort, sID,sPort,): #d is drain, s is source
#print('b: d -',self.portList[dID], 's -', self.RortList[sID])
if len(self.portList[dID]) >= dPort+1:
if self.portList[dID][dPort] == (sID,sPort):
self.portList[dID][dPort] = None
else:
print("jerror: source doesn't match drain. (401)")
else:
print("inport doesn't exist (400)")
for i in range(len(self.portList[dID]),0,-1):#get rid of trailing empty arrays
if self.portList[dID][i-1] == None:
del self.portList[dID][i-1]
else:
break
index = -1
try:
index = self.RortList[sID][sPort].index((dID,dPort))
except:
print("jerror: source doesn't match drain. (402)")
else:
del self.RortList[sID][sPort][index]
for i in range(len(self.RortList[sID]),0,-1):#get rid of trailing 'None's
#print('i:',self.RortList[sID][i-1])
if len(self.RortList[sID][i-1]) == 0:
del self.RortList[sID][i-1]
else:
break
self.canvas.delete(str(dID) +':'+ str(dPort) +','+ str(sID) +':'+ str(sPort))
#print('a: d -',self.portList[dID], 's -', self.RortList[sID])
def addAtom(self, name,):
#print(name,x,y,)
fields = {}
num = int(name.replace(')', ' ').replace('(', ' ').split()[-1])
currentIndex = len(self.atomList)
self.atomList.append(atoms.Atom(name))
#add fields
for i in typeLists.classList[num]: #i is a field id
val = 0
if i in names.params:
fieldName = names.params[i] + '(' + str(i) + ')'
else:
fieldName = names.params[i]
type = typeLists.fieldList[i]
if type == 0x01:
if i == 17:
val = int(self._browser_position[1]/V_MULT)
elif i == 18:
val = int(self._browser_position[0]/H_MULT)
else:
val = int(0)
elif type == 0x05:
val = bool(0)
elif type in (0x06, 0x07):
val = float(0)
elif type == 0x08:
val = 'placeholder'
elif type == 0x12:
val = []
print("objlist:", i)
#if i == 614:
# val = self.addAtom('float_core.inport_connection(105)')
elif type == 0x19:
val = ['placeholder0','placeholder1',]
elif type == 0x16:
print("val is a color")
val = atoms.Color(0.5,0.5,0.5,1.0)
elif type == 0x09:
if i == 702:
if name == 'float_core.decimal_value_atom(289)':
objNum = 123
elif name == 'float_core.boolean_value_atom(87)':
objNum = 198
elif name == 'float_core.indexed_value_atom(180)':
objNum = 155
elif name == 'float_core.integer_value_atom(394)':
objNum = 143
else:
print("add thisi:", name)
objNum = -1
elif i == 248:
fields[fieldName] = None
continue
elif i in fieldAtoms.fa:
objNum = fieldAtoms.fa[i]
else:
print("add this:", i)
objNum = -1
className = names.objs[objNum] + '(' + str(objNum) + ')'
atomId = self.addAtom(className)
val = atoms.Reference(atomId)
else:
print("modification of this parameter is not yet permitted", hex(type))
fields[fieldName] = val
self.atomList[currentIndex].set_fields(fields)
#draw atom
if 6194 in typeLists.classList[num]:
self._draw_atom(self.atomList[currentIndex])
print("drawn")
print(self.atomList[currentIndex].id)
return self.atomList[currentIndex].id
def delAtom(self, id,):
#delete the ports
#print(self.RortList)
if len(self.portList) > id+1:
for port in range(len(self.portList[id])):
if self.portList[id][port]:
#print(self.portList[id][port])
self.delConn(id, port, *self.portList[id][port])
if len(self.RortList) > id+1:
for port in range(len(self.RortList[id])):
if self.RortList[id][port]:
for conn in range(len(self.RortList[id][port])):
if self.RortList[id][port][conn]:
#print(self.RortList[id][port][conn])
rConn = self.atomList[self.atomList[self.RortList[id][port][conn][0]].fields["settings(6194)"].id].fields["inport_connections(614)"][self.RortList[id][port][conn][1]]
self.atomList[rConn.id].fields["source_component(248)"] = None
#print(self.RortList[id][port])
self.delConn(*self.RortList[id][port][conn], id, port,)
#delete and erase the atom
self.atomList[id] = None
self.canvas.delete("id"+str(id))
#delete panel mappings
if len(self.panelMap) > id:#fix this (not working for delay-2's vumeters)
for i in self.panelMap[id]:
self.atomList[i].fields["data_model(6220)"] = None
#delete inport source components ?what does this mean ? why did i write this?
#close manager
self.canvas.delete("manager")
#print("delete")
def addPanel(self, name,):
fields = {}
num = int(name.replace(')', ' ').replace('(', ' ').split()[-1])
currentIndex = len(self.atomList)
self.atomList.append(atoms.Atom(name))
if 6226 in typeLists.classList[num]:
self._draw_panel(self.atomList[currentIndex])
pass
def flattenData(self, data, isRoot = True,):
if isinstance(data, list):
if isRoot:
self.finalOut = []
output = []
for eachClass in range(len(data)):
#self.flattenData(data[eachClass], isRoot = False)
output.append(self.flattenData(data[eachClass], isRoot = False)) #automatically checks type in the function
if isRoot:
return self.finalOut
return output
elif isinstance(data, atoms.Atom):
for eachField in data.fields:
field = data.fields[eachField]
data.fields[eachField] = self.flattenData(field, isRoot = False)
while len(self.finalOut) < data.id+1:
self.finalOut.append(None)
self.finalOut[data.id] = data
data = atoms.Reference(data.id)
elif (isinstance(data, atoms.Reference)):
pass
return data
def _renumber(self, element): #renumbers an atom or list of atoms
if isinstance(element, list):
output = []
#mutate = element[:]
for item in element:
if not (isinstance(item, atoms.Atom) or isinstance(item, atoms.Reference)):
return element
output.append(self._renumber(item))
return output
elif isinstance(element, atoms.Atom):
#print(element.id, element)
self.refIDs[element.id] = len(self.refIDs)
element.setID(self.refIDs[element.id])
for eachField in element.fields:
field = element.fields[eachField]
self._renumber(field)
elif isinstance(element, atoms.Reference):
if not element.id in self.refIDs:
print("element not already here")
return None
element.setID(self.refIDs[element.id])
return element
def treeifyData(self): #makes 3 trees: child_components, panels, and outports. outports is a singleton tree, but is used to root the child_components tree.
self.tempAtomList = copy.deepcopy(self.atomList)
subClasses = {"child_components(173)":[],"panels(6213)":[],"proxy_in_ports(177)":[],"proxy_out_ports(178)":[],}
#find main roots
for i in range(len(self.tempAtomList)):
obj = self.tempAtomList[i]
if obj == None:
continue
if obj.classname == "float_core.proxy_out_port_component(50)":
subClasses["proxy_out_ports(178)"].append(obj)
if self.portList[i] and self.portList[i][0]:
connectee = self.portList[i][0][0]
if not self.tempAtomList[connectee].classname == "float_core.proxy_in_port_component(154)":
'''type = self.tempAtomList[self.tempAtomList[connectee].fields["port(301)"].id].classname
if type == "float_core.audio_port(242)":
subClasses["proxy_in_ports(177)"].insert(0, self.tempAtomList[connectee]) #get inport references
elif type == "float_core.note_port(61)":
subClasses["proxy_in_ports(177)"].append(self.tempAtomList[connectee])
else:
print("jerror: inport that isnt note or audio 1777")
self.tempAtomList[i] = None
else:'''
subClasses["child_components(173)"].append(atoms.Reference(connectee))
else:
print("nothing connected to the out port")
self.tempAtomList[i] = None
#elif obj.classname == "float_core.panel(1680)":
# subClasses["panels(6213)"].append(obj)
# self.tempAtomList[i] = None
subClasses["panels(6213)"] = self.paneList
#find other roots
for i in range(len(self.tempAtomList)):
if self.tempAtomList[i] and "settings(6194)" in self.tempAtomList[i].fields and len(self.RortList) > i: #for all atoms that exist
for j in range(len(self.RortList[i])): #look for an outport
if self.RortList[i][j]:
break
else: #if there are no outports
if self.tempAtomList[i].classname == "float_core.proxy_in_port_component(154)":
type = self.tempAtomList[self.tempAtomList[i].fields["port(301)"].id].classname
if type == "float_core.audio_port(242)":
subClasses["proxy_in_ports(177)"].insert(0, self.tempAtomList[i]) #get inport references
elif type == "float_core.note_port(61)":
subClasses["proxy_in_ports(177)"].append(self.tempAtomList[i])
else:
print("jerror: inport that isnt note or audio 1777")
self.tempAtomList[i] = None