-
Notifications
You must be signed in to change notification settings - Fork 2
/
PhotonFileEditor.py
1623 lines (1352 loc) · 54.9 KB
/
PhotonFileEditor.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
# Shall we call it
# Photonsters Explorer
# Photonsters Toolkit?
# some photon files have preview images with w=0 and thus gives error...
# make preview for branch
# TODO:
# Integrate OpenSlicer in PFE
# Import PhotonS files
# Erode on XY plane using contours or erode
#
# ROADMAP:
# Menu positions:
# After check by Photonsters we should fix (tool/menu)bar positions and remove excess bars
# Remove these items from prefs dialog
# Than we can make toolbar for tab0/Preview
# 3d footprint backdrop
# 3d perspective of model or can we implement browser and use Rob's engine?
# full screen mode for layers?
# moeten we paddings tussen Header/previews/layerdefs ook laten zien?>
# kunnen we cv2.contours gebruiken om stls hol te maken?
import os
import sys
import time
import configparser
import tkinter
import tkinter.ttk as ttk
from tkinter import font
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image, ImageTk
import cv2
import numpy
import PhotonFile
import ToolTips
import ProgressDialog
import PrefDialog
import ResinDialog
# version
version="1.9 beta"
# colors
colForm='gainsboro'
colButton='light grey'
colButtonActive='gray'
colTreeview="gray30"
layerForecolor=(167,34,252)
# settings
installpath=""
recents=[]
editorscript=['new file...','%1']
# widgets
props=[]
labels=[]
entries=[]
entries_general=[]
entries_previews=[]
entries_layerdefs=[]
lb_PreviewImg=None
lb_LayerImg=None
cbLayerMode=None
# layout of window
root=None
header1=None
header2=None
center=None
left1=None
left2=None
body=None
right1=None
right2=None
tab_parent=None
tab1=None
tab2=None
footer1=None
footer2=None
lbImg=None
slLayerNr1=None
slLayerNr2=None
rootMenu=None
editMenu=None
prevMenu=None
tbEdit=None
tbView=None
tbResin=None
tab1EditIcons=None
tab2EditIcons=None
tab1EditMenuItems=None
tab2EditMenuItems=None
typeMenu=None
modeMenu=None
# toolbars
LEFT='left'
RIGHT='right'
TOP='top'
BOTTOM='bottom'
toolbarConfig={
'iconbar1':('tab1',TOP),
'infobar':('tab1',BOTTOM),
'slider1':('tab1',LEFT),
'iconbar2':('tab2',TOP),
'slider2':('tab2',BOTTOM)
}
# navigation counters
prevNr=0
layerNr=0
#####################################################################
## EVENTS
#####################################################################
def keydown(key,mods):
K_ESC='\x1b'
if key==K_ESC: root.destroy()
#####################################################################
## MAIN
#####################################################################
def init():
global installpath
if getattr(sys, 'frozen', False):# frozen
installpath = os.path.dirname(sys.executable)
else: # unfrozen
installpath = os.path.dirname(os.path.realpath(__file__))
print ("Installed at: ",installpath)
def readSettings():
global recents,editorscript,toolbarConfig
settingsfilepath=os.path.join(installpath,"settings.ini")
if not os.path.isfile(settingsfilepath): return
config = configparser.ConfigParser()
config.read(settingsfilepath)
try:
recents=config['DEFAULT']['recents'].split(',')
editorscript=config['DEFAULT']['editorscript'].replace('#','%').split(',')
toolbarConfig=eval(config['DEFAULT']['toolbars'])
print ("toolbarConfig",str(toolbarConfig))
except Exception:
print (Exception)
def writeSettings():
global recents,editorscript,toolbarConfig
settingsfilepath=os.path.join(installpath,"settings.ini")
config = configparser.ConfigParser()
config['DEFAULT']['recents'] = ','.join(recents)
config['DEFAULT']['editorscript']=','.join(editorscript).replace('%','#')
config['DEFAULT']['toolbars']=str(toolbarConfig)
with open(settingsfilepath, 'w') as configfile: # save
config.write(configfile)
def updateRecents(filename=None):
global recents
try:
for _ in range(5):
recentMenu.delete(0)
except:
pass
if filename!=None:
if filename in recents:
recents.remove(filename)
recents.insert(0,filename)
if len(recents)>5: recents=recents[:5]
for recent in recents:
recentMenu.add_command(label=recent,command=lambda recent=recent: mnRecent(recent))
##################################################################
####
##################################################################
ind=[None,None]
def createLayerIndicators():
for tabActive in (0,1):
sliderName='slider'+str(tabActive+1)
tab = toolbarConfig[sliderName][0]
position = toolbarConfig[sliderName][1]
master = getMasterWidget4Bar(tab, position)
ind[tabActive]=tkinter.Label(master,text=str(layerNr),bg=master['bg'],width=4,
#ind[tabActive]=tkinter.Label(master,text=str(layerNr),bg='yellow',width=4,
font=('Helvetica', 8, 'normal'))
def setLayerInd():
global ind1,ind2,layerNr,slLayerNr1,slLayerNr2
tabActive = tab_parent.index(tab_parent.select())
sliderName='slider'+str(tabActive+1)
tab = toolbarConfig[sliderName][0]
position = toolbarConfig[sliderName][1]
master = getMasterWidget4Bar(tab, position)
#if tabActive==0:
slLayerNr=slLayerNr1 if tabActive==0 else slLayerNr2
x,y=slLayerNr.coords()
#print ("cursor x,y",x,y)
#print ("widget x y",slLayerNr.winfo_x(),slLayerNr.winfo_y())
x=x+slLayerNr.winfo_x()
y=y+slLayerNr.winfo_y()
if position==TOP : x,y = x-ind[tabActive].winfo_width()/2,borderSize-slLayerNr.winfo_height()-ind[tabActive].winfo_height()
if position==BOTTOM: x,y = x-ind[tabActive].winfo_width()/2,slLayerNr.winfo_height()
if position==LEFT : x,y = borderSize-slLayerNr.winfo_width()-ind[tabActive].winfo_width(),y-ind[tabActive].winfo_height()/2
if position==RIGHT : x,y = slLayerNr.winfo_width(),y-ind[tabActive].winfo_height()/2
#print ("label x,y",x,y)
#print (slLayerNr2.coords())
ind[tabActive].place(x=x,y=y)
ind[tabActive]["text"]=str(layerNr)
#ind[tabActive].update_idletasks()
internalSetLayer=False
def setLayer(lNr):
global layerNr,lbLayerNr,tab_parent,ind,header2,slLayerNr1,slLayerNr2,internalSetLayer
layerNr=int(lNr)
lbLayerNr['text'] = str(layerNr)+" / "+str(pf.layers.count())
# Update hidden slLayerNr for new layerNr
if not internalSetLayer: # prevent callback by slLayerNr widget to this function which is set as its command parameter
internalSetLayer=True
slLayerNr1.set(lNr)
slLayerNr2.set(lNr)
internalSetLayer=False
def updateForLayerChange():
tabActive = tab_parent.index(tab_parent.select())
if tabActive == 0:
fillProps('layerdefs')
if tabActive == 1:
fillImage()
setLayerInd()
# Only update if idle to prevent buildup of events to process
root.after_idle(updateForLayerChange)
def updateSlLayerNr():
global slLayerNr1,slLayerNr2,lbNrLayers1,lbNrLayers2,layerNr
tab1 = toolbarConfig['slider1'][0]
position1 = toolbarConfig['slider1'][1]
master1 = getMasterWidget4Bar(tab1, position1)
tab2 = toolbarConfig['slider2'][0]
position2 = toolbarConfig['slider2'][1]
master2 = getMasterWidget4Bar(tab2, position2)
def updateSlLayer(slLayerNr,tab,position):
master = getMasterWidget4Bar(tab, position)
orient='horizontal' if (position == TOP or position == BOTTOM) else 'vertical'
slLayerNr.grid_forget()
slLayerNr=tkinter.Scale(master,
from_= 0,to=pf.layers.last(),orient = orient,relief="flat",
command=setLayer,
showvalue=False)
if position==TOP:st="sew"
if position==BOTTOM: st="new"
if position==LEFT:st="ens"
if position==RIGHT: st="wns"
if position==TOP or position==BOTTOM:
slLayerNr.grid(column=1,row=0,sticky=st)
else:
slLayerNr.grid(column=0,row=1,sticky=st)
return slLayerNr
slLayerNr1=updateSlLayer(slLayerNr1,tab1,position1)
slLayerNr2=updateSlLayer(slLayerNr2,tab2,position2)
lbNrLayers1['text']=pf.layers.last()
lbNrLayers2['text']=pf.layers.last()
if layerNr>pf.layers.count(): layerNr=pf.layers.last()
def mnNew():
global root,pf,layerNr
global slLayerNr,header1,LayerModeBG
pf.new()
layerNr=0
setLayer(0)
LayerModeBG=None
updateSlLayerNr()
root.title("Photonsters File Editor - new file")
loadPrevImages()
fillProps()
fillFooterWidgets()
def mnLoad(filename=None):
print ("Load")
global root,pf,layerNr
global slLayerNr,header1,LayerModeBG
if filename==None:
filename = tkinter.filedialog.askopenfilename(initialdir = ".",title = "Select file",filetypes = (("photon files","*.photon"),("all files","*.*")))
if not filename: return
pf.load(filename)
layerNr=0
setLayer(0)
LayerModeBG=None
updateSlLayerNr()
updateRecents(filename)
root.title("Photonsters File Editor - "+os.path.basename(filename))
loadPrevImages()
fillProps()
setBG2Dirty()
fillImage()
fillFooterWidgets()
def mnRecent(recent):
mnLoad(recent)
def mnSave():
global pf
mnSaveas(pf.filename)
def mnSaveas(filename=None):
global oldProp
global root,pf
# Check if last entry was valid and if so store it in memory/pf
if not oldProp==None:
(old_widget,old_catstr,old_prop,old_action)=oldProp
ret=editPhotonFileProp(old_widget,old_catstr,old_prop,'enter')
if ret==False:
root.option_add('*Dialog.msg.font', 'Helvetica 10')
messagebox.showinfo("Not saved...","File was not saved!")
return
# Check if we got a filename
if filename==None:
filename = tkinter.filedialog.asksaveasfilename(initialdir = ".",title = "Select file",filetypes = (("photon files","*.photon"),("all files","*.*")))
if not filename: return
# Save file
pf.save(filename)
updateRecents(filename)
pf.filename=filename
# Set title
root.title("Photonsters File Editor - "+os.path.basename(pf.filename))
def mnPrefs():
global root,editorscript,toolbarConfig
toolbarprefs=[
toolbarConfig['iconbar1'][1],
toolbarConfig['slider1'][1],
toolbarConfig['infobar'][1],
toolbarConfig['iconbar2'][1],
toolbarConfig['slider2'][1]
]
sp=PrefDialog.ShowPreferences(root,"Preferences")
ret=sp.show(editorscript+toolbarprefs)
editorscript=ret[:2]
toolbarprefs=ret[2:]
toolbarConfig={
'iconbar1':('tab1',toolbarprefs[0]),
'slider1':('tab1',toolbarprefs[1]),
'infobar':('tab1',toolbarprefs[2]),
'iconbar2':('tab2',toolbarprefs[3]),
'slider2':('tab2',toolbarprefs[4])
}
def mnExit():
writeSettings()
root.destroy()
quit()
def mnUndo():
pf.layers.undo()
updateSlLayerNr()
fillProps()
setBG2Dirty()
fillImage()
def mnCut():
pf.layers.delete(layerNr=layerNr,saveToHistory=True)
updateSlLayerNr()
fillProps()
setBG2Dirty()
fillImage()
def mnCopy():
pf.layers.copy(layerNr=layerNr,saveToHistory=True)
def mnPaste():
pf.layers.insert(image='clipboard',layerNr=layerNr,saveToHistory=True)
updateSlLayerNr()
fillProps()
setBG2Dirty()
fillImage()
def mnExportImg():
global pf
dirname = tkinter.filedialog.askdirectory()
if not dirname: return
pf.layers.save(layerNr,dirname)
def mnExportPrev():
global pf
dirname = tkinter.filedialog.askdirectory()
if not dirname: return
global prevNr
filepath=os.path.join(dirname,"prev_"+str(prevNr)+".png")
pf.previews.save(filepath,prevNr)
def correctImageSize(imagefilename):
image = cv2.imread(imagefilename,cv2.IMREAD_UNCHANGED)
# if RGB retrieve Red channel
if image.ndim==3:
image=image[:,:,0]
# Check if correct size
if image.shape != (2560,1440) or image.dtype!=numpy.uint8: # Numpy Array dimensions are switched from PIL.Image dimensions
root.option_add('*Dialog.msg.font', 'Helvetica 10')
messagebox.showerror('Wrong Image Size',
f'We need an png image with dimensions of 1440x2560 and 8 bit.\n\n'+
f'Got {image.shape[0]}x{image.shape[1]}x{24 if image.ndim==3 else 8} ({image.dtype})')
return False
else:
return True
def mnReplaceImg():
global pf
filename = tkinter.filedialog.askopenfilename(
initialdir = ".",
title = "Select file",
filetypes = (("png files","*.png"),)
)
if not filename: return
if correctImageSize(filename):
pf.layers.load(filename,layerNr,operation='replace')
def mnReplacePrev():
global pf
filename = tkinter.filedialog.askopenfilename(
initialdir = ".",
title = "Select file",
filetypes = (("png files","*.png"),)
)
if not filename: return
global prevNr
pf.previews.replace(prevNr,filename)
fillProps()
loadPrevImages()
resized()
def mnEditImg():
import subprocess
global installpath
global pf
global layerNr
print ("Implement external editor")
# Export img to tmp
tmpfilepath = os.path.join(installpath,"tmp.png")
im=pf.layers.get(layerNr,retType="image-cv2")
cv2.imwrite(tmpfilepath,im)
# Run editor
global editorscript
script=' '.join(editorscript)
script=script.replace("%1",tmpfilepath)
print ("run:"+script+"<")
ret=subprocess.run(script,shell=True) # shell=True so cmd is not searched in current path
print ("Done")
# Import new image
if not os.path.isfile(tmpfilepath):
messagebox.showerror ("Image not found","Image cannot be found. Did you delete it or don't you have write permissions in install directory?")
return
if not correctImageSize(tmpfilepath):
messagebox.showerror ("Image invalid","Image dimensions and/or depth are not longer the same.")
return
pf.layers.load(tmpfilepath,layerNr,operation='replace')
setBG2Dirty()
fillImage()
def mnInsertImg():
filename = tkinter.filedialog.askopenfilename(
initialdir = ".",
title = "Select file",
filetypes = (("png files","*.png"),)
)
if not filename: return
if correctImageSize(filename):
pf.layers.insert(filename,layerNr,saveToHistory=True)
updateSlLayerNr()
fillProps()
setBG2Dirty()
fillImage()
def mnAppendImg():
filename = tkinter.filedialog.askopenfilename(
initialdir = ".",
title = "Select file",
filetypes = (("png files","*.png"),)
)
if not filename: return
if correctImageSize(filename):
pf.layers.append(filename,saveToHistory=True)
global layerNr
updateSlLayerNr()
layerNr=pf.layers.last()
fillProps()
setBG2Dirty()
fillImage()
def mnReplaceStack():
global layerNr,root
dirname = tkinter.filedialog.askdirectory()
if not dirname: return
nrFiles = len([f for f in os.listdir(dirname)
if f.endswith('.png') and os.path.isfile(os.path.join(dirname, f))])
progressDialog=ProgressDialog.showProgress(root,"Importing...",0,nrFiles,autoShow=True,autoHide=False,cancelButton=False)
pf.layers.replaceAll(dirname,progressDialog)
layerNr=0
updateSlLayerNr()
setBG2Dirty()
fillImage()
fillProps()
def mnExportStack():
dirname = tkinter.filedialog.askdirectory()
if not dirname: return
if pf.filename==None:
subdir="newfile"
else:
subdir = os.path.basename(pf.filename)
subdir = os.path.splitext(subdir)[0]
fulldirpath=os.path.join(dirname,subdir)
# If directory exists warn:
if os.path.isdir(fulldirpath):
root.option_add('*Dialog.msg.font', 'Helvetica 10')
retOK = tkinter.messagebox.askokcancel(f"Directory {fulldirpath} already exists.","Do you want to proceed and possibly overwrite existing files?")
if not retOK: return
progressDialog=ProgressDialog.showProgress(root,"Exporting...",0,pf.layers.count(),autoShow=True,autoHide=False,cancelButton=False)
pf.layers.saveAll(fulldirpath,"",progressDialog)
def mnResins():
rD=ResinDialog.ResinDialog(root)
resinVals=rD.show() # 0:Brand 1:Type 2:LayerHeight 3:NormalExposure
# 4:OffTime 5:BottomExposure 6:BottomLayers
# Replace , in float with . prior to type casting to float
for i in range(2,6):
if isinstance(resinVals[i],str):
resinVals[i]=resinVals[i].replace(",",".")
print (resinVals)
# Check if resin profile depends on different layer height
curLayerHeight=pf.getProperty("Layer height (mm)")
newLayerHeight=float(resinVals[2])
if curLayerHeight!=newLayerHeight:
root.option_add('*Dialog.msg.font', 'Helvetica 10')
retOK = tkinter.messagebox.askokcancel(f"Different Layer Height","This setting depends on a different Layer Height. Do you want to continue?")
if not retOK: return
# Make sure all vars have correct type
layerHeight=float(resinVals[2])
expTime=float(resinVals[3])
offTime=float(resinVals[4])
expBottom=float(resinVals[5])
bottomLayers=int(resinVals[6])
# Set header properties
pf.setProperty("Layer height (mm)",layerHeight)
pf.setProperty("Exp. time (s)",expTime)
pf.setProperty("Off time (s)",offTime)
pf.setProperty("Exp. bottom (s)",expBottom)
pf.setProperty("# Bottom Layers",bottomLayers)
# Set layer properties
for layerNr in range(pf.layers.count()):
if layerNr<bottomLayers:
pf.layers.setProperty(layerNr,"Exp. time (s)",expBottom)
else:
pf.layers.setProperty(layerNr,"Exp. time (s)",expTime)
pf.layers.setProperty(layerNr,"Off time (s)",offTime)
# Update property labels
fillProps()
def mnAbout():
global version
root.option_add('*Dialog.msg.font', 'Helvetica 10')
#https://pythonspot.com/tk-message-box/
messagebox.showinfo('About',
"Version: "+ version +"\n \n Github: PhotonFileUtils \n\n NardJ, X3msnake, Rob2048, \n Antharon, Reonarudo \n \n License: Free for non-commerical use.",
)
##################################################################
####
##################################################################
nrResizes=0
resizing=False
def rootButtonRelease():
global resizing
print ("rootButtonRelease")
if resizing:
print ("MouseUp")
resizing=False
#resized(None)
lastTimerId=-1
oldSize=(0,0)
def resize(arg):
global lastTimerId,root,oldSize
# Only resize if size changed
newSize=(arg.width,arg.height)
if oldSize==newSize: return
print (time.time(),"resize",oldSize,newSize,arg)
# Only resize if size changed > 8 pixels
if (abs(oldSize[0]-newSize[0])<8 and
abs(oldSize[1]-newSize[1])<8 ): return
if lastTimerId!=-1: root.after_cancel(lastTimerId)
lastTimerId=root.after(100,resized)
oldSize=newSize
pass
lb_PreviewImg = None
def resized():
global labels
global entries
global tab1
global body,footer1,root
global lb_PreviewImg
global lb_LayerImg
global showPreviewTab1
print (time.time(),"resized")
try:
# Check which tab is active and which widgets to resize/reposition
tabActive = tab_parent.index(tab_parent.select())
# If second tab
if tabActive == 1:
fillImage()
return
# If first tab
tabheight=tab1.winfo_height()
dy=props[1].winfo_rooty()-props[0].winfo_rooty()
if dy<0: return # User is minimizing window too much
nry=int(tabheight/dy)
row=0
col=1
for prop in props:
if prop.name=="Category Header":
if not (col==0 and row==0):
col=col+1
row=0
#row=nr % nry
#col=nr //nry
prop.grid(row=row, column=col)
prop.update()
if prop.cat=="Previews":
if type(prop.prop)==list:
(bTitle, bNr, bType, bEditable,bHint) = prop.prop
if bTitle=="padding tail":
if showPreviewTab1.get(): # only reposition if visible
xspace = (prop.winfo_width()+12)*2+56 #padx=12 for prop, 56 is fix for some extra margin in columns
resizePrevImageForX(xspace)
lb_PreviewImg.place(x=prop.winfo_rootx()-tab1.winfo_rootx(),
y=prop.winfo_rooty()-tab1.winfo_rooty()+dy)
row=row+1
if row>(nry-1):
row=0
col=col+1
rf=tab1.winfo_height()/2560
lb_LayerImg['width']=rf*1440
lb_LayerImg['height']=rf*2560
lb_LayerImg.update_idletasks()
setPropLayerImage()
except Exception as e:
print ("... ABORT:",e)
def createWindow():
global root
# setup window
root = tkinter.Tk()
root.geometry("%dx%d+0+0" % (640,480))
root.title("Photonsters File Editor")
root.name="root"
iconfilepath=os.path.join(installpath+"/PhotonEditor.png")
#print("icon",iconfilepath)
imgicon = tkinter.PhotoImage(file=iconfilepath)
root.tk.call('wm', 'iconphoto', root._w, imgicon)
return root
# setup menu
def createMenu():
global root,recentMenu,rootMenu,editMenu,viewMenu,typeMenu,modeMenu,prevMenu
global tab1EditMenuItems,tab2EditMenuItems
rootMenu=tkinter.Menu(root,relief='flat')
root.config(menu=rootMenu)
fileMenu=tkinter.Menu(rootMenu,tearoff=False,relief='flat')
rootMenu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="New",command=mnNew)
fileMenu.insert_separator(1)
fileMenu.add_command(label="Load",command=mnLoad)
recentMenu=tkinter.Menu(fileMenu,tearoff=False,relief='flat')
recentMenu.add_command(label="recent")
fileMenu.add_cascade(label="Open Recent", menu=recentMenu)
fileMenu.insert_separator(5)
fileMenu.add_command(label="Save",command=mnSave)
fileMenu.add_command(label="Save As",command=mnSaveas)
fileMenu.insert_separator(8)
fileMenu.add_command(label="Preferences",command=mnPrefs)
fileMenu.insert_separator(10)
fileMenu.add_command(label="Exit",command=mnExit)
editMenu=tkinter.Menu(rootMenu,tearoff=False,relief='flat')
rootMenu.add_cascade(label="Layers", menu=editMenu)
editMenu.add_command(label="Undo", command=mnUndo)
editMenu.insert_separator(1)
editMenu.add_command(label="Cut",command=mnCut)
editMenu.add_command(label="Copy",command=mnCopy)
editMenu.add_command(label="Paste",command=mnPaste)
editMenu.insert_separator(5)
editMenu.add_command(label="Edit Image",command=mnEditImg)
editMenu.add_command(label="Insert Image",command=mnInsertImg)
editMenu.add_command(label="Append Image",command=mnAppendImg)
editMenu.add_command(label="Replace Image",command=mnReplaceImg)
editMenu.add_command(label="Export Image",command=mnExportImg)
editMenu.insert_separator(10)
editMenu.add_command(label="Replace All",command=mnReplaceStack)
editMenu.add_command(label="Export All",command=mnExportStack)
prevMenu=tkinter.Menu(rootMenu,tearoff=False,relief='flat')
rootMenu.add_cascade(label="Previews", menu=prevMenu)
prevMenu.add_command(label="Replace Image",command=mnReplacePrev)
prevMenu.add_command(label="Export Image",command=mnExportPrev)
resinMenu=tkinter.Menu(rootMenu,tearoff=False,relief='flat')
rootMenu.add_cascade(label="Resins", menu=resinMenu)
resinMenu.add_command(label="Change Resin",command=mnResins)
tab1EditMenuItems=("Undo","Cut","Copy","Paste","Edit Image","Insert Image","Append Image","Replace All","Export All")
tab2EditMenuItems=("Replace Image","Export Image")
viewMenu=tkinter.Menu(rootMenu,tearoff=False,relief='flat')
typeMenu=tkinter.Menu(viewMenu,tearoff=False,relief='flat')
modeMenu=tkinter.Menu(viewMenu,tearoff=False,relief='flat')
rootMenu.add_cascade(label="View", menu=viewMenu)
viewMenu.add_cascade(label="Type", menu=typeMenu)
viewMenu.add_cascade(label="Mode", menu=modeMenu)
typeMenu.IV=tkinter.IntVar()
modeMenu.IV=tkinter.IntVar()
typeMenu.add_radiobutton(label="None", command=setViewMenu2Toolbar,variable=typeMenu.IV,value=0)
typeMenu.add_radiobutton(label="XRay", command=setViewMenu2Toolbar,variable=typeMenu.IV,value=1)
typeMenu.add_radiobutton(label="Shade", command=setViewMenu2Toolbar,variable=typeMenu.IV,value=2)
modeMenu.add_radiobutton(label="All", command=setViewMenu2Toolbar,variable=modeMenu.IV,value=0)
modeMenu.add_radiobutton(label="Grow", command=setViewMenu2Toolbar,variable=modeMenu.IV,value=1)
viewMenu.add_command(label="Refesh",command=lambda: setBG())
helpMenu=tkinter.Menu(rootMenu,tearoff=False,relief='flat')
rootMenu.add_cascade(label="Help", menu=helpMenu)
helpMenu.add_command(label="About",command=mnAbout)
def setTab2Visible(visible):
global editMenu,header1,header1,center,footer1,footer2,left1,left2,right1,right2
global tbEdit,tabs1EditIcons,tabs2EditIcons
global tab1EditMenuItems,tab2EditMenuItems
global tbView,viewMenu,tbResin
print (time.time(),"setTab2Visible")
if not visible: # TAB 1
rootMenu.entryconfig('View', state="disabled")
rootMenu.entryconfig('Previews', state="normal")
rootMenu.entryconfig('Resins', state="normal")
#for entry in tab1EditMenuItems:
# editMenu.entryconfig(entry.title(), state="disabled")
#for entry in tab1EditIcons:
# tbEdit.entryconfig(entry.lower(),state="disabled")
for entry in tbView.buttons:
entry.config(state="disabled")
for entry in tbResin.buttons:
entry.config(state="normal")
#always display header 2
header1.grid_forget()
header2.grid(row=0,column=0,sticky="nsew")
left1.grid(row=0,column=0,sticky="wnse")
left2.grid_forget()
right1.grid(row=0,column=2,sticky="ensw")
right2.grid_forget()
footer1.grid(row=2,column=0,sticky="snew")
footer2.grid_forget()
else: # TAB 2
rootMenu.entryconfig('View', state="normal")
rootMenu.entryconfig('Previews', state="disabled")
rootMenu.entryconfig('Resins', state="disabled")
#for entry in tab1EditMenuItems:
# editMenu.entryconfig(entry.title(), state="normal")
#for entry in tab1EditIcons:
# tbEdit.entryconfig(entry.lower(),state="normal")
for entry in tbView.buttons:
entry.config(state="normal")
for entry in tbResin.buttons:
entry.config(state="disabled")
#always display header 2
header1.grid_forget()
header2.grid(row=0,column=0,sticky="nsew")
left1.grid_forget()
left2.grid(row=0,column=0,sticky="wnse")
right1.grid_forget()
right2.grid(row=0,column=2,sticky="ensw")
footer1.grid_forget()
footer2.grid(row=2,column=0,sticky="snew")
fillImage()
borderSize=46
def createWindowLayout():
global root, center, body, left1,right1,header1,footer1
global left2,right2,header2,footer2,tab_parent,tab1,tab2,lbImg
global borderSize
root.grid_columnconfigure(0,weight=1)
root.grid_rowconfigure(0,weight=0)
root.grid_rowconfigure(1,weight=1)
root.grid_rowconfigure(2,weight=0)
debug=False
defaultbg = root.cget('bg')
header1 = tkinter.Frame(root,bg='orange red' if debug else defaultbg)#colForm
header1.name="header1"
header1.grid(column=0,row=0,sticky="new")
header2 = tkinter.Frame(root,bg='orange' if debug else defaultbg)#colForm
header2.name="header2"
header2.grid(column=1,row=0,sticky="new")
header2.grid_forget()
center= tkinter.Frame(root,bg="magenta2" if debug else defaultbg)
center.name="center"
center.grid(column=0,row=1,sticky="nesw")
footer1 = tkinter.Frame(root, bg='deep sky blue' if debug else defaultbg)#colForm
footer1.name="footer"
footer1.grid(column=0,row=2,sticky="nesw")
footer2 = tkinter.Frame(root, bg='sky blue' if debug else defaultbg)#colForm
footer2.name="footer"
footer2.grid(column=0,row=2,sticky="nesw")
footer2.grid_forget()
# Fix minimal row widths in body
headerf=tkinter.Frame(root,height=borderSize,width=4,bg="green" if debug else defaultbg)
headerf.grid(column=1,row=0,sticky="ne")
centerf=tkinter.Frame(root,width=4,bg="yellow" if debug else defaultbg)
centerf.grid(column=1,row=1,sticky="nse")
footerf=tkinter.Frame(root,height=borderSize,width=4,bg="green" if debug else defaultbg)
footerf.grid(column=1,row=2,sticky="se")
# Populate center with 3 columns for left,body,right
center.grid_columnconfigure(0,weight=0)
center.grid_columnconfigure(1,weight=1)
center.grid_columnconfigure(2,weight=0)
center.grid_rowconfigure(0,weight=1)
left1 = tkinter.Frame(center,bg='spring green' if debug else defaultbg)
left1.name='left1'
left2 = tkinter.Frame(center,bg='yellow green' if debug else defaultbg)
left2.name='left2'
left1.grid(column=0,row=0,sticky="nsw")
left2.grid(column=0,row=0,sticky="nsw")
left2.grid_forget()
body = tkinter.Frame(center,bg="yellow" if debug else defaultbg)
body.grid(column=1,row=0,sticky="nesw")
right1 = tkinter.Frame(center,bg='hot pink' if debug else defaultbg)
right1.name='right1'
right2 = tkinter.Frame(center,bg='deep pink' if debug else defaultbg)
right2.name='right2'
right1.grid(column=2,row=0,sticky="nes")
right2.grid(column=2,row=0,sticky="nes")
right2.grid_forget()
# Fix minimal column widths in body
leftf=tkinter.Frame(center,width=borderSize,height=4,bg="red" if debug else defaultbg)
leftf.grid(column=0,row=1,sticky="nw")
bodyf=tkinter.Frame(center,height=4,bg="yellow" if debug else defaultbg)
bodyf.grid(column=1,row=1,sticky="new")
rightf=tkinter.Frame(center,width=borderSize,height=4,bg="red" if debug else defaultbg)
rightf.grid(column=2,row=1,sticky="ne")
# If we resize body we need to re-align props
body.bind("<Configure>", resize)
body.update()
# layout of body
body.grid_columnconfigure(0,weight=1)
body.grid_rowconfigure(0,weight=1)
# https://www.homeandlearn.uk/python-database-form-tabs2.html
tab_parent = ttk.Notebook(body)
#tab_parent.bind("<<NotebookTabChanged>>",changeTab())
tab1 = tkinter.Frame(tab_parent)
tab2 = ttk.Frame(tab_parent)
tab_parent.add(tab1, text="Properties")
tab_parent.add(tab2, text="Images")
tab_parent.pack(expand=1, fill='both')
tab2.bind("<Visibility>", (lambda _ :setTab2Visible(True)) )
tab1.bind("<Visibility>", (lambda _ :setTab2Visible(False)) )
def createSliderWidgets():
print ("createSliderWidgets")
tab1=toolbarConfig['slider1'][0]
position1=toolbarConfig['slider1'][1]
master1=getMasterWidget4Bar(tab1,position1)
tab2=toolbarConfig['slider2'][0]
position2=toolbarConfig['slider2'][1]
master2=getMasterWidget4Bar(tab2,position2)
global slLayerNr1, lbNrLayers1
global slLayerNr2, lbNrLayers2
def createSliderWidget(master,position):
global borderSize
if position==TOP:st="sew"
if position==BOTTOM: st="new"
if position==LEFT:st="ens"
if position==RIGHT: st="wns"
if position==TOP or position==BOTTOM:
master.grid_rowconfigure(0,weight=1)
lb=tkinter.Label(master,text="0",
font=('Helvetica', 8, 'normal'),
anchor='e',width=4,padx=4)
lb.grid(column=0,row=0,sticky=st)
slLayerNr=tkinter.Scale(master,
from_=0,to=0,orient='horizontal',
relief="flat",
command=setLayer,
showvalue=True)
slLayerNr.grid(column=1,row=0,sticky=st)
lbNrLayers=tkinter.Label(master,text="000",