-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui_tkinter.py
2120 lines (2118 loc) · 97.7 KB
/
ui_tkinter.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
#!/usr/bin/env python3
# coding=UTF-8
import sys
import platform
import logsetup
log=logsetup.getlog(__name__)
logsetup.setlevel('INFO',log) #for this file
# logsetup.setlevel('DEBUG',log) #for this file
log.info("Importing ui_tkinter.py")
import unicodedata
import tkinter #as gui
import tkinter.font
import tkinter.scrolledtext
import tkinter.ttk
import file #for image pathnames
from random import randint #for theme selection
import datetime
try: #translation
_
except:
def _(x):
return x
try: #PIL
import PIL.ImageFont
import PIL.ImageTk
import PIL.ImageDraw
import PIL.Image
pilisactive=True
log.info("PIL loaded OK")
except Exception as e:
log.error("Error loading PIL: {}".format(e))
pilisactive=False
# import tkintermod
# tkinter.CallWrapper = tkintermod.TkErrorCatcher
"""Variables for use without tkinter"""
END=tkinter.END
INSERT=tkinter.INSERT
N=tkinter.N
S=tkinter.S
E=tkinter.E
W=tkinter.W
RIGHT=tkinter.RIGHT
LEFT=tkinter.LEFT
"""These classes have no dependencies"""
class ObectwArgs(object):
"""ObectwArgs just allows us to throw away unused args and kwargs."""
def __init__(self, *args, **kwargs):
log.info("ObectwArgs args: {};{}".format(args,kwargs))
super(ObectwArgs, self).__init__()
class NoParent(object):
"""docstring for NoParent."""
def __init__(self, *args, **kwargs):
if args:
args=list(args)
args.remove(args[0])
super(NoParent, self).__init__(*args, **kwargs)
class Theme(object):
"""docstring for Theme."""
def startruntime(self):
self.start_time=datetime.datetime.utcnow()
log.info("starting at {}".format(self.start_time))
def nowruntime(self):
#this returns a delta!
return datetime.datetime.utcnow()-self.start_time
def logfinished(self,msg=None):
log.info("logging finish now")
run_time=self.nowruntime()
# if type(start) is datetime.datetime: #only work with deltas
# start-=self.start_time
if msg:
msg=str(msg)+' '
else:
msg=''
text=_("Finished {}at {} ({:1.0f}m, {:2.3f}s)"
"").format(msg,now(),*divmod((run_time).total_seconds(),60))
log.info(text)
return text
def setimages(self):
# Program icon(s) (First should be transparent!)
scale=self.program['scale'] #just reading this here
self.scalings=[]
self.photo={}
#do these once:
if scale-1: #x != y: #should be the same as scale != 1
log.info("Maybe scaling images; please wait...")
scaledalreadydir='images/scaled/'+str(scale)+'/'
file.makedir(file.fullpathname(scaledalreadydir)) #in case not there
def mkimg(name,filename):
relurl=file.getdiredurl('images/',filename)
# log.info("scale: {}".format(scale))
if scale-1: #x != y:
scaledalready=file.getdiredurl(scaledalreadydir,filename)
# log.info("Looking for {}".format(scaledalready))
if file.exists(file.fullpathname(scaledalready)):
# log.info("scaled image exists for {}".format(filename))
relurl=scaledalready
# log.info("Dirs: {}?={}".format(scaledalready,relurl))
if scaledalready != relurl: # should scale if off by >2% either way
# log.info("Scaling {}".format(relurl)) #Just do this once!
try:
assert self.fakeroot.winfo_exists()
except:
program=self.program.copy()
program['theme']=None
self.fakeroot=Root(program,
noimagescaling=True)
self.fakeroot.ww=Wait(parent=self.fakeroot,
msg="Scaling Images (Just this once)")
if not self.scalings:
maxscaled=100
else:
maxscaled=int(sum(self.scalings)/len(self.scalings)+10)
for y in range(maxscaled,10,-5):
# Higher number is better resolution (x*y/y), more time to process
#10>50 High OK, since we do this just once now
#lower option if higher fails due to memory limitations
# y=int(y)
x=int(scale*y)
# log.info("Scaling {} @{} resolution".format(relurl,y)) #Just do this once!
try:
img = Image(file.fullpathname(relurl))
# keep these at full size, for now
if 'openclipart.org' not in filename:
img.scale(scale,pixels=img.maxhw(),resolution=y)
self.photo[name]=img.scaled
else:
self.photo[name]=img
# log.info("scaledalready.parent: {}".format(scaledalready.parent))
# log.info("parent: {}".format(scaledalreadydir != scaledalready.parent))
if scaledalready.parent != scaledalreadydir:
file.makedir(scaledalready.parent,silent=True)
self.photo[name].write(
file.fullpathname(scaledalready)
)
self.scalings.append(y)
if file.exists(scaledalready):
log.info("Scaled {} {} @{} resolution: {}"
"".format(name,relurl,y,_("OK")))
# else:
# log.info("Problem Scaling {} {} @{} resolution"
# "".format(name,relurl,y,_("OK"))
return #stop when the first/best works
except tkinter.TclError as e:
# log.info(e)
if ('not enough free memory '
'for image buffer' in str(e)):
continue
# log.info("Using {}".format(relurl))
self.photo[name] = Image(file.fullpathname(relurl))
# log.info("Compiled {} {}".format(name,relurl))
imagelist=[ ('transparent','AZT stacks6.png'),
('tall','AZT clear stacks tall.png'),
('small','AZT stacks6_sm.png'),
('icon','AZT stacks6_icon.png'),
('icontall','AZT clear stacks tall_icon.png'),
('iconT','T alone clear6_icon.png'),
('iconC','Z alone clear6_icon.png'),
('iconV','A alone clear6_icon.png'),
('iconCV','ZA alone clear6_icon.png'),
('iconWord','ZAZA clear stacks6_icon.png'),
('iconWordRec','ZAZA Rclear stacks6_icon.png'),
('iconTRec','T Rclear stacks6_icon.png'),
('iconReport','Report_icon.png'),
('iconReportLogo','Generic AZT Reports_icon.png'),
('iconTRep','T Report_icon.png'),
('iconCVRep','ZA Report_icon.png'),
('iconTranscribe','Transcribe Tone_icon.png'),
('iconTranscribeC','Consonant Choice_icon.png'),
('iconTranscribeV','Vowel Choice_icon.png'),
('iconJoinUF','Join Tone_icon.png'),
('iconTRepcomp','T Report Comprehensive_icon.png'),
('iconVRepcomp','A Report Comprehensive_icon.png'),
('iconCRepcomp','Z Report Comprehensive_icon.png'),
('iconCVRepcomp','ZA Report Comprehensive_icon.png'),
('iconVCCVRepcomp','AZZA Report Comprehensive_icon.png'),
('USBdrive','USB drive.png'),
('T','T alone clear6.png'),
('C','Z alone clear6.png'),
('V','A alone clear6.png'),
('CV','ZA alone clear6.png'),
('Word','ZAZA clear stacks6.png'),
('WordRec','ZAZA Rclear stacks6.png'),
('TRec','T Rclear stacks6.png'),
('Report','Report.png'),
('ReportLogo','Generic AZT Reports.png'),
('TRep','T Report.png'),
('CVRep','ZA Report.png'),
('Transcribe','Transcribe Tone.png'),
('TranscribeC','Consonant Choice.png'),
('TranscribeV','Vowel Choice.png'),
('JoinUF','Join Tone.png'),
('TRepcomp','T Report Comprehensive.png'),
('VRepcomp','A Report Comprehensive.png'),
('CRepcomp','Z Report Comprehensive.png'),
('CVRepcomp','ZA Report Comprehensive.png'),
('VCCVRepcomp','AZZA Report Comprehensive.png'),
('backgrounded','AZT stacks6.png'),
#Set images for tasks
('verify','Verify List.png'),
('sort','Sort List.png'),
('join','Join List.png'),
('record','Microphone alone_sm.png'),
('change','Change Circle_sm.png'),
('checkedbox','checked.png'),
('uncheckedbox','unchecked.png'),
('NoImage','toselect/Image-Not-Found.png'),
('Order!','toselect/order!.png'),
]
ntodo=len(imagelist)
self.startruntime()
for n,(name,filename) in enumerate(imagelist):
try:
#Can't hyperthread here!
mkimg(name,filename)
except Exception as e:
log.info("Image {} ({}) not compiled ({})".format(
name,filename,e
))
try:
self.fakeroot.ww.progress(n*100/ntodo)
except:
pass
try:
self.logfinished("Image compilation")
self.fakeroot.ww.close()
self.fakeroot.destroy()
self.program['theme'].unbootstraptheme()
except Exception as e:
# log.info("Something happened: {}".format(e))
# raise
pass
def settheme(self):
if not self.name:
defaulttheme='greygreen'
multiplier=99 #The default theme will be this more frequent than others.
pot=list(self.themes.keys())+([defaulttheme]*
(multiplier*len(self.themes)-1))
self.name='Kent' #for the colorblind (to punish others...)
self.name='highcontrast' #for low light environments
self.name=pot[randint(0, len(pot))-1] #mostly defaulttheme
try:
if platform.uname().node == 'CS-477':
self.name='pink'
if (platform.uname().node == 'karlap' and
not self.program.get('production')):
self.name='Kim' #for my development
except Exception as e:
log.info("Assuming I'm not working from main ({}).".format(e))
elif self.name not in self.themes:
print("Sorry, that theme doesn't seem to be set up. Pick from "
"these options:",self.themes.keys())
exit()
for k in self.themes[self.name]:
setattr(self,k,self.themes[self.name][k])
self.themettk = tkinter.ttk.Style()
self.themettk.theme_use('clam')
self.themettk.configure("Progressbar",
troughcolor=self.activebackground,
background=self.background,
# bordercolor=self.background,
# darkcolor=self.background,
# lightcolor=self.background
)
def setthemes(self):
self.themes={'lightgreen':{
'background':'#c6ffb3',
'activebackground':'#c6ffb3',
'offwhite':None,
'highlight': 'red',
'menubackground': 'white',
'white': 'white'}, #lighter green
'green':{
'background':'#b3ff99',
'activebackground':'#c6ffb3',
'offwhite':None,
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'pink':{
'background':'#ff99cc',
'activebackground':'#ff66b3',
'offwhite':None,
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'lighterpink':{
'background':'#ffb3d9',
'activebackground':'#ff99cc',
'offwhite':None,
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'evenlighterpink':{
'background':'#ffcce6',
'activebackground':'#ffb3d9',
'offwhite':'#ffe6f3',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'purple':{
'background':'#ffb3ec',
'activebackground':'#ff99e6',
'offwhite':'#ffe6f9',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'Howard':{
'background':'green',
'activebackground':'red',
'offwhite':'grey',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'Kent':{
'background':'red',
'activebackground':'green',
'offwhite':'grey',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'Kim':{
'background':'#ffbb99',
'activebackground':'#ffaa80',
'offwhite':'#ffeee6',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'yellow':{
'background':'#ffff99',
'activebackground':'#ffff80',
'offwhite':'#ffffe6',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'greygreen1':{
'background':'#62d16f',
'activebackground':'#4dcb5c',
'offwhite':'#ebf9ed',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'lightgreygreen':{
'background':'#9fdfca',
'activebackground':'#8cd9bf',
'offwhite':'#ecf9f4',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'greygreen':{
'background':'#8cd9bf',
'activebackground':'#66ccaa', #10% darker than the above
'offwhite':'#ecf9f4',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'}, #default!
'highcontrast':{
'background':'white',
'activebackground':'#e6fff9', #10% darker than the above
'offwhite':'#ecf9f4',
'highlight': 'red',
'menubackground': 'white',
'white': 'white'},
'tkinterdefault':{
'background':None,
'activebackground':None,
'offwhite':None,
'highlight': 'red',
'menubackground': 'white',
'white': 'white'}
}
def setfonts(self,fonttheme='default'):
scale=self.program['scale'] #just reading this here
log.info("Setting fonts with {} theme".format(fonttheme))
if fonttheme == 'smaller':
default=int(12*scale)
else:
default=int(18*scale)
title=bigger=int(default*2)
big=int(default*5/3)
normal=int(default*4/3)
default=int(default)
small=int(default*2/3)
tiny=int(default*1/2)
log.info("Using default font size: {}".format(default))
andika="Andika"# not "Andika SIL"
charis="Charis SIL"
self.fonts={
'title':tkinter.font.Font(family=charis, size=title), #Charis
'instructions':tkinter.font.Font(family=charis,
size=normal), #Charis
'report':tkinter.font.Font(family=charis, size=small),
'reportheader':tkinter.font.Font(family=charis, size=small,
# underline = True,
slant = 'italic'
),
'read':tkinter.font.Font(family=charis, size=big),
'readbig':tkinter.font.Font(family=charis, size=bigger,
weight='bold'),
'small':tkinter.font.Font(family=charis, size=small),
'tiny':tkinter.font.Font(family=charis, size=tiny),
'default':tkinter.font.Font(family=charis, size=default),
'fixed':tkinter.font.Font(family='TkFixedFont', size=small)
}
"""additional keyword options (ignored if font is specified):
family - font family i.e. Courier, Times
size - font size (in points, |-x| in pixels)
weight - font emphasis (NORMAL, BOLD)
slant - ROMAN, ITALIC
underline - font underlining (0 - none, 1 - underline)
overstrike - font strikeout (0 - none, 1 - strikeout)
"""
def setscale(self):
program=self.program #reading and setting here
root=tkinter.Tk() #just to get these values
h = program['screenh'] = root.winfo_screenheight()
w = program['screenw'] = root.winfo_screenwidth()
wmm = root.winfo_screenmmwidth()
hmm = root.winfo_screenmmheight()
root.destroy()
#this computer as a ratio of mine, 1080 (286mm) x 1920 (508mm):
hx=h/1080
wx=w/1920
hmmx=hmm/286
wmmx=wmm/508
log.info("screen height: {} ({}mm, ratio: {}/{})".format(h,hmm,hx,hmmx))
log.info("screen width: {} ({}mm, ratio: {}/{})".format(w,wmm,wx,wmmx))
xmin=min(hx,wx,hmmx,wmmx)
xmax=max(hx,wx,hmmx,wmmx)
if xmax-1 > 1-xmin:
program['scale']=xmax
else:
program['scale']=xmin
if program['scale'] < 1.02 and program['scale'] > 0.98:
log.info("Probably shouldn't scale in this case (scale: {})".format(
program['scale']))
program['scale']=1
# program['scale']=0.75 #for testing
log.info("Largest variance from 1:1 ratio: {} (this will be used to scale "
"stuff.)".format(program['scale']))
def setpads(self,**kwargs):
for kwarg in ['ipady','ipadx','pady','padx']:
if kwarg in kwargs:
setattr(self,kwarg,kwargs[kwarg])
def unbootstraptheme(self):
"""This is for when you have bootstrapped your main theme, to show some
UI while your theme is being made. Once it is made, revert here.
"""
self.program['theme']=self.originaltheme
def __init__(self,program,**kwargs):
self.program=program
"""This can be accessed elsewhere in this module
through widget._root().theme.program"""
if kwargs.get('noimagescaling'):
self.originaltheme=self.program['theme']
self.name=None
else:
if 'theme' not in self.program:
self.name=None
elif isinstance(self.program['theme'],str):
self.name=self.program['theme']
elif isinstance(self.program['theme'],Theme):
log.error("Asked to make a theme attribute, with "
"program['theme']={} ({})".format(self.program['theme'],
type(self.program['theme'])))
log.error("Stopping theme creation here.")
return #only do the following only once per run
self.program['theme']=self #this theme needs to be in use, either way
# log.info("making theme with program {}".format(self.program))
# I should allow a default theme here, so I can display GUI without
# any of this already done
self.setpads(**kwargs)
self.setthemes()
if kwargs.get('noimagescaling'):
self.program['scale']=1
else:
self.setscale()
self.settheme()
log.info("Using {} theme ({})".format(self.name,self.program))
self.setimages()
self.setfonts()
super(Theme, self).__init__()
# log.info("self.photo keys: {}".format(list(self.photo)))
# log.info("Theme initialized: {}".format(self))
class ExitFlag(object):
def istrue(self):
# log.debug("Returning {} exitflag".format(self.value))
return self.value
value=get=istrue
def true(self):
self.value=True
def false(self):
self.value=False
def __init__(self):
self.false()
class Renderer(ObectwArgs):
def __init__(self,test=False,**kwargs):
global pilisactive
if pilisactive:
self.isactive=True
else:
log.info("Seems like PIL is not installed; inactivating Renderer.")
# self.img=None
self.isactive=False
self.renderings={}
self.imagefonts={}
def gettextsize(self, img, text, font, fspacing):
# w, h = draw.multiline_textsize(text, font=font, spacing=fspacing)
l, t, r, b = img.multiline_textbbox((0,0), text, font=font, spacing=fspacing)
# w,h = r-l,b-t
# log.info("width: {}, height: {}".format(w,h))
return r-l,b-t
def render(self,**kwargs):
if not self.isactive:
return
self.img=None #clear past work
fontkey=font=kwargs['font'].actual() #should always be there
xpad=ypad=fspacing=font['size']
fname=font['family']
fsize=int(font['size']*1.33)
fspacing=10
text=kwargs['text'] #should always be there
text=text.replace('\t',' ') #Not sure why, but tabs aren't working.
wraplength=kwargs['wraplength'] #should always be there
log.log(2,"Rendering ‘{}’ text with font: {}".format(text,font))
if (('justify' in kwargs and
kwargs['justify'] in [tkinter.LEFT,'left']) or
('anchor' in kwargs and
kwargs['anchor'] in [tkinter.E,"e"])):
align="left"
else:
align="center" #also supports "right"
if str(font) not in self.imagefonts:
log.info("Making image font: {}".format(str(fontkey)))
fonttype=''
if font['weight'] == 'bold':
fonttype+='B'
if font['slant'] == 'italic':
fonttype+='I'
if fonttype == '':
fonttype='R'
"""make room for GentiumPlus and GentiumBookPlus, with same
attributes:
'Gentium Plus' and 'Gentium Book Plus'
Bold
BoldItalic
Italic
Regular
"""
fonttypewords=fonttype.replace('B','Bold').replace('I','Italic'
).replace('R','Regular')
"""Each of these is in a list, in priority order (newer, then older,
hide staves, then don't), use the first found."""
if fname in ["Andika","Andika SIL"]:
files=['Andika-tstv-{}.ttf'.format(fonttypewords)]
files+=['Andika-{}.ttf'.format(fonttypewords)]
fonttype='R' #There's only this one for these
files+=['Andika-tstv-{}.ttf'.format(fonttype)]
files+=['Andika-{}.ttf'.format(fonttype)]
elif fname in ["Charis","Charis SIL"]:
files=['CharisSIL-tstv-{}.ttf'.format(fonttypewords)]
files+=['CharisSIL-tstv-{}.ttf'.format(fonttype)]
files+=['CharisSIL-{}.ttf'.format(fonttypewords)]
files+=['CharisSIL-{}.ttf'.format(fonttype)]
elif fname in ["Gentium","Gentium SIL","Gentium Plus"]:
files=['GentiumPlus-tstv-{}.ttf'.format(fonttypewords)]
files+=['GentiumPlus-{}.ttf'.format(fonttypewords)]
if fonttype == 'B':
fonttype='R'
if fonttype == 'BI':
fonttype='I'
files+=['Gentium-{}.ttf'.format(fonttype)]
files+=['Gentium-tstv-{}.ttf'.format(fonttype)]
elif fname in ["Gentium Book Basic","Gentium Book Basic SIL",
"Gentium Book Plus"]:
files=['GentiumBookPlus-tstv-{}.ttf'.format(fonttypewords)]
files+=['GentiumBookPlus-{}.ttf'.format(fonttypewords)]
files+=['GenBkBas{}.ttf'.format(fonttype)]
files+=['GenBkBas-tstv-{}.ttf'.format(fonttype)]
elif fname in ["DejaVu Sans"]:
fonttype=fonttype.replace('B','Bold').replace('I','Oblique'
).replace('R','')
if len(fonttype)>0:
fonttype='-'+fonttype
files=['DejaVuSans-tstv-{}.ttf'.format(fonttype)]
files+=['DejaVuSans{}.ttf'.format(fonttype)]
else:
log.error("Sorry, I have no info on font {}".format(fname))
return
for file in files:
try:
font = PIL.ImageFont.truetype(font=file, size=fsize)
self.imagefonts[str(fontkey)]=font
log.info("Using font file {}".format(file))
break
except OSError as e:
if e == 'cannot open resource':
log.debug("no file {}, checking next".format(file))
else: #i.e., if it was done before
# log.info("Using image font: {}".format(str(fontkey)))
font=self.imagefonts[str(fontkey)]
if str(fontkey) not in self.imagefonts: #i.e., neither before nor now
log.error("Cannot find font file for {}; giving up".format(fname))
self.img=None
return
img = PIL.Image.new("1", (10,10), 255)
draw = PIL.ImageDraw.Draw(img)
w, h = self.gettextsize(draw, text, font, fspacing)
textori=text
lines=textori.split('\n') #get everything between manual linebreaks
for line in lines:
li=lines.index(line)
words=line.split(' ') #split by words/spaces
nl=x=y=0
while y < len(words):
y+=1
l=' '.join(words[x+nl:y+nl])
w, h = self.gettextsize(draw, l, font, fspacing)
log.log(2,"Round {} Words {}-{}:{}, width: {}/{}".format(y,x+nl,
y+nl,l,w,wraplength))
if wraplength and w>wraplength:
words.insert(y+nl-1,'\n')
x=y-1
nl+=1
line=' '.join(words) #Join back words
lines[li]=line
text='\n'.join(lines) #join back sections between manual linebreaks
w, h = self.gettextsize(draw, text, font, fspacing)
log.log(2,"Final size w: {}, h: {}".format(w,h))
black = 'rgb(0, 0, 0)'
white = 'rgb(255, 255, 255)'
img = PIL.Image.new("RGBA", (w+xpad, h+ypad), (255, 255, 255,0 )) #alpha
draw = PIL.ImageDraw.Draw(img)
draw.multiline_text((0+xpad//2, 0+ypad//4), text,font=font,fill=black,
align=align)
self.img = PIL.ImageTk.PhotoImage(img)
class Exitable(object):
"""This class provides the method and init to make things exit normally.
Hence, it applies to roots and windows, but not frames, etc."""
def killall(self):
self.destroy()
sys.exit()
def cleanup(self):
pass
def exittoroot(self):
if hasattr(self,'parent') and not isinstance(self.parent,Root):
self.parent.exittoroot()
return
elif hasattr(self,'parent'):
self.parent.exitFlag.true()
def on_quit(self):
"""Do this when a window closes, so any window functions can know
to just stop, rather than trying to build graphic components and
throwing an error. This doesn't do anything but set the flag value
on exit, the logic to stop needs to be elsewhere, e.g.,
`if self.exitFlag.istrue(): return`"""
if hasattr(self,'exitFlag'): #only do this if there is an exitflag set
log.info("Setting window ({}) exit flag True!".format(self))
self.exitFlag.true()
if self.mainwindow: #exit afterwards if main window
self.exittoroot()
self.killall()
else:
if (hasattr(self,'parent') and
self.parent.winfo_exists() and
not isinstance(self.parent,Root)):
if not self.parent.iswaiting():
self.parent.deiconify()
# else:
# self.parent.waitunpause()
# self.ww.paused=True
# log.info("Going to deiconify {}".format(self.parent))
# log.info("Going to cleanup {}".format(self))
self.cleanup()
self.destroy() #do this for everything
def __init__(self):
self.protocol("WM_DELETE_WINDOW", self.on_quit)
class Gridded(ObectwArgs):
def dogrid(self):
if self._grid:
log.log(4,"Gridding at r{},c{},rsp{},csp{},st{},padx{},pady{},"
"ipadx{},ipady{}".format(self.row,
self.column,
self.rowspan,
self.columnspan,
self.sticky,
self.padx,
self.pady,
self.ipadx,
self.ipady,
))
self.grid(
row=self.row,
column=self.column,
sticky=self.sticky,
padx=self.padx,
pady=self.pady,
ipadx=self.ipadx,
ipady=self.ipady,
columnspan=self.columnspan,
rowspan=self.rowspan
)
def lessgridkwargs(self,**kwargs):
for opt in self.gridkwargs:
if opt in kwargs:
del kwargs[opt]
if 'b'+opt in kwargs:
del kwargs['b'+opt]
return kwargs
def gridbkwargs(self,**kwargs):
# preserve some of these for buttons
for opt in self.gridkwargs:
if 'b'+opt in kwargs:
kwargs[opt]=kwargs['b'+opt]
del kwargs['b'+opt]
return kwargs
def bindchildren(self,bind,command):
self.bind(bind,command)
for child in self.winfo_children():
try:
child.bindchildren(bind,command)
except Exception as e:
log.info("Exception in Gridded binding: {}".format(e))
pass
def __init__(self, *args, **kwargs): #because this is used everywhere.
"""this removes gridding kwargs from the widget calls"""
self.gridkwargs=['sticky',
'row','rowspan',
'column','columnspan',
'padx','pady','ipadx','ipady']
self._grid=False
if set(kwargs) & set(self.gridkwargs):
self._grid=True
self.sticky=kwargs.pop('sticky',"ew")
self.row=kwargs.pop('row',kwargs.pop('r',0))
self.column=kwargs.pop('column',kwargs.pop('col',kwargs.pop('c',0)))
self.columnspan=kwargs.pop('columnspan',1)
self.rowspan=kwargs.pop('rowspan',1)
self.padx=kwargs.pop('padx',0)
self.pady=kwargs.pop('pady',0)
self.ipadx=kwargs.pop('ipadx',0)
self.ipady=kwargs.pop('ipady',0)
else:
log.log(4,"Not Gridding! ({})".format(kwargs))
class Childof(object):
def inherit(self,parent=None,attr=None):
"""This function brings these attributes from the parent, to inherit
from the root window, through all windows, frames, and scrolling frames, etc
"""
# log.info("inheriting")
if not parent and hasattr(self,'parent') and self.parent:
parent=self.parent
elif parent:
self.parent=parent
if not attr:
attrs=['theme',
# 'fonts', #in theme
# 'debug',
'wraplength',
# 'photo', #in theme
'renderer',
# 'program',
'exitFlag']
else:
attrs=[attr]
for attr in attrs:
if hasattr(parent,attr):
setattr(self,attr,getattr(parent,attr))
# log.info("inheriting {} from parent {} (to {})"
# "".format(attr,type(parent),type(self)))
else:
log.debug("parent {} (of {}) doesn't have attr {}, skipping inheritance"
"".format(parent,type(self),attr))
def __init__(self, parent): #because this is used everywhere.
self.parent=parent
self.inherit()
class UI(ObectwArgs):
"""docstring for UI, after tkinter widgets are initted."""
def wait(self,msg=None,cancellable=False):
if self.iswaiting():
log.debug("There is already a wait window: {}".format(self.ww))
return
self.withdraw()
self.ww=Wait(self,msg,cancellable=cancellable)
def iswaiting(self):
return hasattr(self,'ww') and self.ww.winfo_exists()
def waitprogress(self,x):
self.ww.progress(x)
def waitpause(self):
self.ww.withdraw()
self.ww.paused=True
def waitunpause(self):
self.ww.deiconify()
self.ww.paused=False
def waitcancel(self):
self.waitcancelled=True
log.info("Wait cancel registered; waiting to cancel")
def waitdone(self):
try:
self.ww.close()
self.deiconify()
except tkinter.TclError:
pass
except AttributeError:
log.info("Seem to have tried stopping waiting, when I wasn't...")
def __init__(self): #because this is used everywhere.
# log.info("UI self._root(): {} ({})".format(self._root(),type(self._root())))
# log.info("UI self._root() dir: {}".format(dir(self._root())))
# log.info("self.parent: {} ({})".format(self.parent,type(self.parent)))
# log.info("self.parent._root(): {} ({})".format(self.parent._root(),type(self.parent._root())))
# self.theme=self._root().program['theme']
# log.info("UI {}.theme({}).photo keys: {}".format(self,self.theme,
# list(self.theme.photo)))
for a in ['background','bg','troughcolor']:
if a in self.keys():
self[a]=self.theme.background
for a in ['ipady','ipadx','pady','padx']:
if a in self.keys() and hasattr(self.theme,a):
self[a]=getattr(self.theme,a)
for a in ['activebackground','selectcolor']:
if a in self.keys():
self[a]=self.theme.activebackground
self.waitcancelled=False
# try:
# self['background']=self.theme.background
# self['bg']=self.theme.background
# # self['foreground']=self.theme.background
# self['troughcolor']=self.theme.background
# self['activebackground']=self.theme.activebackground
# except TypeError as e:
# log.info("TypeError {}".format(e))
# except tkinter.TclError as e:
# log.info("TclError {}".format(e))
# super(UI, self).__init__(*args, **kwargs)
class Image(tkinter.PhotoImage):
def biggerby(self,x):
#always do this one first, if doing both, to start from scratch
self.scaled=self.zoom(x,x)
def smallerby(self,x):
try:
self.scaled=self.scaled.subsample(x,x)
except AttributeError:
self.scaled=self.subsample(x,x)
def maxhw(self,scaled=False):
if scaled:
return max(self.scaled.width(),self.scaled.height())
else:
return max(self.width(),self.height())
def scale(self,scale,pixels=100,resolution=10):
# log.info("Scaling with these args: scale {},pixels {}, resolution {}"
# "".format(scale,pixels,resolution))
# 'x' and 'resolution' here express a float as two integers,
# so r = 0.7 = 7/10, because the zoom and subsample fns
# only work on integers
if pixels:
s=pixels*scale #the number of pixels, scaled
r=s/self.maxhw() #the ratio we need to reduce actual pixels by
# log.info("scaled pixels: {} (of {})".format(s,pixels))
else:
r=1 #don't scale for pixels=0
x=resolution*r
# log.info("ratio to scale image: {} (of {})".format(r,self.maxhw()))
# log.info("biggerby to do: {}".format(x))
self.biggerby(int(x))
# log.info("Image: {} ({})".format(self.scaled, self.maxhw(scaled=True)))
self.smallerby(int(resolution))
# self[pixels]=self.scaled
# log.info("Image: {} ({})".format(self.scaled, self.maxhw(scaled=True)))
def __init__(self,filename):
# self.name=filename
try:
super(Image, self).__init__(file=filename)#,*args, **kwargs)
except tkinter.TclError as e:
# log.info("Error: {} ({})".format(e.args,type(e)))
if "couldn't recognize data in image file" in e.args[0]:
raise #this is processed elsewhere
elif 'value for "-file" missing' in e.args[0]:
raise #this is processed elsewhere
else:
log.info("Image error: {}".format(e))
self.biggerby(1)
class IntVar(tkinter.IntVar):
def __init__(self, *args, **kwargs):
super(tkinter.IntVar, self).__init__(*args, **kwargs)
class StringVar(tkinter.StringVar):
def __init__(self, *args, **kwargs):
super(tkinter.StringVar, self).__init__(*args, **kwargs)
class BooleanVar(tkinter.BooleanVar):
def __init__(self, *args, **kwargs):
super(tkinter.BooleanVar, self).__init__(*args, **kwargs)
"""below here has UI"""
class Root(Exitable,tkinter.Tk):
"""this is the root of the tkinter GUI."""
def __init__(self, program={}, *args, **kwargs):
"""specify theme name in program['theme']"""
"""bring in program here, send it to theme, everyone accesses scale from there."""
""""Some roots aren't THE root, e.g., contextmenu. Furthermore, I'm
currently not showing the root, so the user will never exit it."""
# log.info("Root called with program dict {}".format(program))
self.program=program
if 'root' not in self.program:
self.program['root']=self
self.mainwindow=False
self.exitFlag = ExitFlag()
tkinter.Tk.__init__(self)
self.withdraw() #this is almost always correct
try:
assert not kwargs.get('noimagescaling') #otherwise, make copy theme
assert isinstance(self.program['theme'],Theme) #use what's there
self.theme=self.program['theme']
except (KeyError,AssertionError):
self.theme=Theme(self.program, **kwargs)
self.renderer=Renderer()
Exitable.__init__(self)
UI.__init__(self)
# log.info("self.theme.photo keys: {}".format(list(self.theme.photo)))
# log.info("self.theme({}).photo keys: {}".format(self.theme,list(self.theme.photo)))
log.info("Root initialized")
"""These have parent (Childof), but no grid"""
class Toplevel(Childof,Exitable,tkinter.Toplevel,UI): #NoParent
"""This and all Childof classes should have a parent, to inherit a common
theme. Otherwise, colors, fonts, and icons will be incongruous."""
def __init__(self, parent, *args, **kwargs):
self.mainwindow=False
Childof.__init__(self,parent)
tkinter.Toplevel.__init__(self)
# log.info("Toplevel._root(): {} ({})".format(self._root(),type(self._root())))
# log.info("Toplevel.parent._root(): {} ({})".format(self.parent._root(),type(self.parent._root())))
Exitable.__init__(self)
UI.__init__(self)
self.protocol("WM_DELETE_WINDOW", lambda s=self: Window.on_quit(s))
class Menu(Childof,tkinter.Menu): #not Text
def pad(self,label):
w=5 #Make menus at least w characters wide
if len(label) <w:
spaces=" "*(w-len(label))
label=spaces+label+spaces
return label
def add_command(self,label,command):
# log.info("Menu opts: {}".format((self,label,command)))
label=self.pad(label)
tkinter.Menu.add_command(self,label=label,command=command)
def add_cascade(self,label,menu):
# log.info("Cascade opts: {}".format((self,label,menu)))
label=self.pad(label)
tkinter.Menu.add_cascade(self,label=label,menu=menu)
def __init__(self,parent,**kwargs):
Childof.__init__(self,parent)
self.theme=parent.theme
tkinter.Menu.__init__(self,parent,
font=self.theme.fonts['default'],
**kwargs)
UI.__init__(self)
self['background']=self.theme.menubackground
class Progressbar(Gridded,Childof,tkinter.ttk.Progressbar):
def current(self,value):
if 0 <= value <= 100:
self['value']=value
self.update_idletasks() #updates just geometry
def __init__(self, parent, **kwargs):
# log.info("Initializing Progressbar object")
Gridded.__init__(self,**kwargs)
kwargs=self.lessgridkwargs(**kwargs)
Childof.__init__(self,parent)
if 'orient' not in kwargs:
kwargs['orient']='horizontal' #or 'vertical'
if 'mode' not in kwargs:
kwargs['mode']='determinate' #or 'indeterminate'
tkinter.ttk.Progressbar.__init__(self,parent,**kwargs)
UI.__init__(self)
self.dogrid()
class Text(Childof,ObectwArgs):
"""This converts kwargs 'text', 'image' and 'font' into attributes which are
default where not specified, and rendered where appropriate for the
characters in the text."""
def wrap(self):
availablexy(self)
if not hasattr(self,'wraplength'):
wraplength=self.maxwidth
else:
wraplength=min(self.wraplength,self.maxwidth)
self.config(wraplength=wraplength)
log.log(3,'self.maxwidth (Label class): {}'.format(self.maxwidth))
def render(self, **kwargs):
if not self.renderer.isactive:
return
style=(self.font['family'], # from kwargs['font'].actual()
self.font['size'],self.font['weight'],
self.font['slant'],self.font['underline'],
self.font['overstrike'])
if style not in self.renderer.renderings:
self.renderer.renderings[style]={}
if kwargs['wraplength'] not in self.renderer.renderings[style]:
self.renderer.renderings[style][kwargs['wraplength']]={}
thisrenderings=self.renderer.renderings[style][kwargs['wraplength']]
if (self.text in thisrenderings and
thisrenderings[self.text] is not None):
log.log(5,"text {} already rendered with {} wraplength, using."
"".format(self.text,kwargs['wraplength']))
self.image=thisrenderings[self.text]