-
Notifications
You must be signed in to change notification settings - Fork 67
/
appjar.py
executable file
·8772 lines (7505 loc) · 291 KB
/
appjar.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
# -*- coding: utf-8 -*-
"""appJar.py: Provides a GUI class, for making simple tkinter GUIs."""
# Nearly everything I learnt came from: http://effbot.org/tkinterbook/
# with help from: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html
# with snippets from stackexchange.com
# make print backwards compatible
from __future__ import print_function
try:
# for Python2
from Tkinter import *
import tkMessageBox as messagebox
from tkColorChooser import askcolor
import tkFileDialog as filedialog
import ScrolledText as scrolledtext
import tkFont as font
PYTHON2 = True
PY_NAME = "Python"
except ImportError:
# for Python3
from tkinter import *
from tkinter import messagebox
from tkinter.colorchooser import askcolor
from tkinter import filedialog
from tkinter import scrolledtext
from tkinter import font
PYTHON2 = False
PY_NAME = "python3"
import os
import sys
import re
import hashlib
import imghdr
import time
import __main__ as theMain
from platform import system as platform
# Links
import webbrowser
# ajTree
try:
from idlelib.TreeWidget import TreeItem, TreeNode, ZoomHeight
except:
try:
from idlelib.tree import TreeItem, TreeNode
from idlelib.zoomheight import ZoomHeight
except:
raise Exception("Unsupported python build, unable to access idlelib")
from xml.dom.minidom import parseString
# DatePicker
import calendar
import datetime
#######################
# import borrowed libraries - not compulsory
#######################
try:
from appJar.lib.tooltip import ToolTip
TOOLTIP_AVAILABLE = True
except:
TOOLTIP_AVAILABLE = False
try:
from appJar.lib.tkinter_png import *
TKINTERPNG_AVAILABLE = True
except:
TKINTERPNG_AVAILABLE = False
try:
from appJar.lib import nanojpeg
NANOJPEG_AVAILABLE = True
except:
NANOJPEG_AVAILABLE = False
# only try to import winsound if we're on windows
if platform() in ["win32", "Windows"]:
import winsound
# details
__author__ = "Richard Jarvis"
__copyright__ = "Copyright 2016, Richard Jarvis"
__credits__ = ["Graham Turner", "Sarah Murch"]
__license__ = "GPL"
__version__ = "0.1"
__maintainer__ = "Richard Jarvis"
__email__ = "info@appJar.info"
__status__ = "Development"
# class to allow simple creation of tkinter GUIs
class gui(object):
"""
Class to represent the GUI
- Create one of these
- add some widgets
- call the go() function
"""
@staticmethod
def CLEAN_CONFIG_DICTIONARY(**kw):
"""
Used by all Classes to tidy up dictionaries passed into config functions
Allows us to more quickly process the dictionaries when overriding config
"""
try:
kw['bg'] = kw.pop('background')
except:
pass
try:
kw['fg'] = kw.pop('foreground')
except:
pass
kw = dict((k.lower().strip(), v) for k, v in kw.items())
return kw
# globals for supported platforms
WINDOWS = 1
MAC = 2
LINUX = 3
@staticmethod
def GET_PLATFORM():
# get the platform
if platform() in ["win32", "Windows"]:
return gui.WINDOWS
elif platform() == "Darwin":
return gui.MAC
elif platform() == "Linux":
return gui.LINUX
else:
raise Exception("Unsupported platform: " + platform())
@staticmethod
def CENTER(win):
"""
centers a tkinter window
http://stackoverflow.com/questions/3352918/
:param win: the root or Toplevel window to center
"""
win.attributes('-alpha', 0.0) # hide the window
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
y = y - 150
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
win.attributes('-alpha', 1.0)
built = False
# used to identify widgets in component configurations
WINDOW = 0
LABEL = 1
ENTRY = 2
BUTTON = 3
CHECKBOX = 4
SCALE = 5
RADIOBUTTON = 6
LISTBOX = 7
MESSAGE = 8
SPIN = 9
OPTION = 10
TEXTAREA = 11
LINK = 12
METER = 13
IMAGE = 14
PIECHART = 15
PROPERTIES = 16
GRID = 17
PLOTS = 18
RB = 60
CB = 40
LB = 70
LABELFRAME = 30
FRAME = 36
TABBEDFRAME = 31
PANEDFRAME = 32
SCROLLPANE = 33
PAGEDWINDOW = 34
TOGGLEFRAME = 35
# positioning
N = N
NE = NE
E = E
SE = SE
S = S
SW = SW
W = W
NW = NW
CENTER = CENTER
LEFT = LEFT
RIGHT = RIGHT
# reliefs
SUNKEN = SUNKEN
RAISED = RAISED
GROOVE = GROOVE
RIDGE = RIDGE
FLAT = FLAT
# containers
C_ROOT = 'rootPage'
C_LABELFRAME = 'labelFrame'
C_FRAME = 'frame'
C_TOGGLEFRAME = 'toggleFrame'
# 2 containers for pagedWindow
C_PAGEDWINDOW = 'pagedWindow'
C_PAGE = 'page'
# 2 containers for tabbedFrame
C_TABBEDFRAME = 'tabbedFrame'
C_TAB = 'tab'
# 2 containers for panedFrame
C_PANEDFRAME = 'panedFrame'
C_PANE = 'pane'
C_SUBWINDOW = 'subWindow'
C_SCROLLPANE = 'scrollPane'
# names for each of the widgets defined above
# used for defining functions
WIDGETS = {
LABEL: "Label",
MESSAGE: "Message",
BUTTON: "Button",
ENTRY: "Entry",
CB: "Cb",
SCALE: "Scale",
RB: "Rb",
GRID: "Grid",
LB: "Lb",
SPIN: "SpinBox",
OPTION: "OptionBox",
TEXTAREA: "TextArea",
LINK: "Link",
METER: "Meter",
IMAGE: "Image",
RADIOBUTTON: "RadioButton",
CHECKBOX: "CheckBox",
LISTBOX: "ListBox",
PIECHART: "PieChart",
PROPERTIES: "Properties",
FRAME: "Frame",
LABELFRAME: "LabelFrame",
PANEDFRAME: "PanedFrame",
TOGGLEFRAME: "ToggleFrame",
TABBEDFRAME: "TabbedFrame"}
# music stuff
BASIC_NOTES = {
"A": 440,
"B": 493,
"C": 261,
"D": 293,
"E": 329,
"F": 349,
"G": 392}
NOTES = {
'f8': 5587,
'c#6': 1108,
'f4': 349,
'c7': 2093,
'd#2': 77,
'g8': 6271,
'd4': 293,
'd7': 2349,
'd#7': 2489,
'g#4': 415,
'e7': 2637,
'd9': 9397,
'b8': 7902,
'a#4': 466,
'b5': 987,
'b2': 123,
'g#9': 13289,
'g9': 12543,
'f#2': 92,
'c4': 261,
'e1': 41,
'e6': 1318,
'a#8': 7458,
'c5': 523,
'd6': 1174,
'd3': 146,
'g7': 3135,
'd2': 73,
'd#3': 155,
'g#6': 1661,
'd#4': 311,
'a3': 219,
'g2': 97,
'c#5': 554,
'd#9': 9956,
'a8': 7040,
'a#5': 932,
'd#5': 622,
'a1': 54,
'g#8': 6644,
'a2': 109,
'g#5': 830,
'f3': 174,
'a6': 1760,
'e8': 5274,
'c#9': 8869,
'f5': 698,
'b1': 61,
'c#4': 277,
'f#9': 11839,
'e5': 659,
'f9': 11175,
'f#5': 739,
'a#1': 58,
'f#8': 5919,
'b7': 3951,
'c#8': 4434,
'g1': 48,
'c#3': 138,
'f#7': 2959,
'c6': 1046,
'c#2': 69,
'c#7': 2217,
'c3': 130,
'e9': 10548,
'c9': 8372,
'a#6': 1864,
'a#7': 3729,
'g#2': 103,
'f6': 1396,
'b3': 246,
'g#3': 207,
'b4': 493,
'a7': 3520,
'd#6': 1244,
'd#8': 4978,
'f2': 87,
'd5': 587,
'f7': 2793,
'f#6': 1479,
'g6': 1567,
'e3': 164,
'f#3': 184,
'g#1': 51,
'd8': 4698,
'f#4': 369,
'f1': 43,
'c8': 4186,
'g4': 391,
'g3': 195,
'a4': 440,
'a#3': 233,
'd#1': 38,
'e2': 82,
'e4': 329,
'a5': 880,
'a#2': 116,
'g5': 783,
'g#7': 3322,
'b6': 1975,
'c2': 65,
'f#1': 46}
DURATIONS = {
"BREVE": 2000,
"SEMIBREVE": 1000,
"MINIM": 500,
"CROTCHET": 250,
"QUAVER": 125,
"SEMIQUAVER": 63,
"DEMISEMIQUAVER": 32,
"HEMIDEMISEMIQUAVER": 16}
#####################################
# CONSTRUCTOR - creates the GUI
#####################################
def __init__(self, title=None, geom=None, warn=True, debug=False):
# first out, verify the platform
self.platform = gui.GET_PLATFORM()
self.WARN = warn
self.DEBUG = debug
# a stack to hold containers as being built
# done here, as initArrays is called elsewhere - to reset the gubbins
self.containerStack = []
# first up, set up all the data stores
self.__initArrays()
# dynamically create lots of functions for configuring stuff
self.__buildConfigFuncs()
# language parser
self.config = None
# set up some default path locations
self.lib_file = os.path.abspath(__file__)
self.exe_file = os.path.basename(theMain.__file__)
self.exe_loc = os.path.dirname(theMain.__file__)
# location of appJar
self.lib_path = os.path.dirname(self.lib_file)
self.resource_path = os.path.join(self.lib_path, "resources")
self.icon_path = os.path.join(self.resource_path, "icons")
self.sound_path = os.path.join(self.resource_path, "sounds")
self.appJarIcon = os.path.join(self.icon_path, "favicon.ico")
# user configurable
self.userImages = self.exe_loc
self.userSounds = self.exe_loc
# create the main window - topLevel
self.topLevel = Tk()
self.topLevel.bind('<Configure>', self.__windowEvent)
# override close button
self.topLevel.protocol("WM_DELETE_WINDOW", self.stop)
# temporarily hide it
self.topLevel.withdraw()
self.locationSet = False
# create a frame to store all the widgets
self.appWindow = Frame(self.topLevel)
self.appWindow.pack(fill=BOTH, expand=True)
# set the windows title
if title is None:
title = self.exe_file
self.setTitle(title)
# configure the geometry of the window
self.topLevel.escapeBindId = None # used to exit fullscreen
self.topLevel.stopFunction = None # used to exit fullscreen
self.setGeom(geom)
# set the resize status - default to True
self.setResizable(True)
# set up fonts
self.buttonFont = font.Font(family="Helvetica", size=12,)
self.labelFont = font.Font(family="Helvetica", size=12)
self.entryFont = font.Font(family="Helvetica", size=12)
self.messageFont = font.Font(family="Helvetica", size=12)
self.rbFont = font.Font(family="Helvetica", size=12)
self.cbFont = font.Font(family="Helvetica", size=12)
self.tbFont = font.Font(family="Helvetica", size=12)
self.scaleFont = font.Font(family="Helvetica", size=12)
self.statusFont = font.Font(family="Helvetica", size=12)
self.spinFont = font.Font(family="Helvetica", size=12)
self.optionFont = font.Font(family="Helvetica", size=12)
self.lbFont = font.Font(family="Helvetica", size=12)
self.taFont = font.Font(family="Helvetica", size=12)
self.meterFont = font.Font(family="Helvetica", size=12, weight='bold')
self.linkFont = font.Font(
family="Helvetica",
size=12,
weight='bold',
underline=1)
self.labelFrameFont = font.Font(family="Helvetica", size=12)
self.frameFont = font.Font(family="Helvetica", size=12)
self.toggleFrameFont = font.Font(family="Helvetica", size=12)
self.tabbedFrameFont = font.Font(family="Helvetica", size=12)
self.panedFrameFont = font.Font(family="Helvetica", size=12)
self.scrollPaneFont = font.Font(family="Helvetica", size=12)
self.propertiesFont = font.Font(family="Helvetica", size=12)
self.gridFont = font.Font(family="Helvetica", size=12)
# self.fgColour = self.topLevel.cget("foreground")
# self.buttonFgColour = self.topLevel.cget("foreground")
# self.labelFgColour = self.topLevel.cget("foreground")
# create a menu bar - only shows if populated
# now created in menu functions, as it generated a blank line...
self.hasMenu = False
self.hasStatus = False
self.hasTb = False
self.copyAndPaste = CopyAndPaste(self.topLevel)
# won't pack, if don't pack it here
self.tb = Frame(self.appWindow, bd=1, relief=RAISED)
self.tb.pack(side=TOP, fill=X)
# create the main container for this GUI
container = Frame(self.appWindow)
# container = Label(self.appWindow) # made as a label, so we can set an
# image
container.config(padx=2, pady=2, background=self.topLevel.cget("bg"))
container.pack(fill=BOTH, expand=True)
self.__addContainer(self.C_ROOT, container, 0, 1)
# set up the main container to be able to host an image
self.__configBg(container)
# an array to hold any threaded events....
self.events = []
self.pollTime = 250
self.built = True
if self.platform == self.WINDOWS:
try:
self.topLevel.wm_iconbitmap(self.appJarIcon)
except: # file not found
self.debug("Error setting Windows default icon")
def __configBg(self, container):
# set up a background image holder
# alternative to label option above, as label doesn't update widgets
# properly
self.bgLabel = Label(container)
self.bgLabel.config(
anchor=CENTER,
font=self.labelFont,
background=self.__getContainerBg())
self.bgLabel.place(x=0, y=0, relwidth=1, relheight=1)
container.image = None
#####################################
# set the arrays we use to store everything
#####################################
def __initArrays(self):
# set up a row counter - used to auto add rows
# breaks once user sets own row
# set up a minimum label width for label combos
self.labWidth = 1
# validate function callbacks - used by numeric texts
# created first time a widget is used
self.validateNumeric = None
self.validateSpinBox = None
# set up flash variable
self.doFlash = False
# used to hide/show title bar
self.hasTitleBar = True
# records if we're in fullscreen - stops hideTitle from breaking
self.isFullscreen = False
# splash screen?
self.splashConfig = None
# collections of widgets, widget name is key
self.n_frames = [] # un-named, so no direct access
self.n_labels = {}
self.n_buttons = {}
self.n_entries = {}
self.n_messages = {}
self.n_scales = {}
self.n_cbs = {}
self.n_rbs = {}
self.n_lbs = {}
self.n_tbButts = {}
self.n_spins = {}
self.n_props = {}
self.n_plots = {}
self.n_options = {}
self.n_frameLabs = {}
self.n_textAreas = {}
self.n_links = {}
self.n_meters = {}
self.n_subWindows = {}
self.n_labelFrames = {}
self.n_ajFrame = {}
self.n_tabbedFrames = {}
self.n_panedFrames = {}
self.n_panes = {}
self.n_pagedWindows = {}
self.n_toggleFrames = {}
self.n_scrollPanes = {}
self.n_trees = {}
self.n_flashLabs = []
self.n_pieCharts = {}
self.n_separators = []
# variables associated with widgets
self.n_entryVars = {}
self.n_optionVars = {}
self.n_boxVars = {}
self.n_rbVars = {}
self.n_rbVals = {}
self.n_images = {} # image label widgets
self.n_imageCache = {} # image file objects
self.n_imageAnimationIds = {} # stores after ids
self.n_taHashes = {} # for monitoring textAreas
# for simple grids
self.n_grids = {}
# menu stuff
self.n_menus = {}
self.n_menuVars = {}
self.n_accelerators = []
def setLanguage(self, language):
try:
from configparser import ConfigParser
except:
self.warn("Internationalisation not supported")
self.config = None
return
self.config = ConfigParser()
self.changeLanguage(language)
# function to update languages
def changeLanguage(self, language):
if self.config is None:
self.warn("Internationalisation not supported")
return
language = language.upper()
import codecs
if not PYTHON2:
try:
with codecs.open(language + ".ini", "r", "utf8") as langFile:
self.config.read_file(langFile)
except FileNotFoundError:
self.warn("Invalid language: " + language)
return
else:
try:
with codecs.open(language + ".ini", "r", "utf8") as langFile:
self.config.read_file(langFile)
except IOError:
self.warn("Invalid language: " + language)
return
self.debug("Switching to: " + language)
# loop through each section, get the relative set of widgets
# change the text
for section in self.config.sections():
section = section.upper()
# skip the config section (for now)
if section == "CONFIG":
continue
self.debug("\t" + section)
# convert the section title to its code
try:
kind = vars(gui)[section]
texts = self.config[section]
except KeyError:
self.warn("Invalid config section: " + section)
continue
# use the code to get the widget list
widgets = self.__getItems(kind)
if kind in [self.SCALE]:
self.warn("No text is displayed in " + section + ". Maybe it has a Label?")
continue
elif kind in [self.TEXTAREA, self.METER]:
self.warn("No text is displayed in " + section)
continue
elif kind in [self.PROPERTIES]:
self.warn(section + " - list-style widgets are currently not supported")
elif kind in [self.LISTBOX]:
for k in widgets.keys():
lb = widgets[k]
# convert data to a list
data = texts.get(k, lb.DEFAULT_TEXT).strip().split("\n")
# tidy up the list
data = [item.strip() for item in data if len(item.strip()) > 0]
self.updateListItems(k, data)
elif kind in [self.SPIN]:
for k in widgets.keys():
sb = widgets[k]
# convert data to a list
data = texts.get(k, sb.DEFAULT_TEXT).strip().split("\n")
# tidy up the list
data = [item.strip() for item in data if len(item.strip()) > 0]
self.changeSpinBox(k, data)
elif kind in [self.OPTION]:
for k in widgets.keys():
ob = widgets[k]
# convert data to a list
data = texts.get(k, ob.DEFAULT_TEXT).strip().split("\n")
# tidy up the list
data = [item.strip() for item in data if len(item.strip()) > 0]
self.changeOptionBox(k, data)
elif kind in [self.RADIOBUTTON]:
for (key, val) in self.config.items(section):
keys = key.split("-")
try:
rbs = self.n_rbs[keys[0]]
except KeyError:
self.warn("Invalid RADIOBUTTON key: " + keys[0])
continue
for rb in rbs:
if rb.DEFAULT_TEXT == keys[1]:
rb["text"] = val
break
elif kind in [self.PIECHART, self.GRID]:
self.warn(section + " - widgets not yet implemented")
continue
elif kind == self.ENTRY:
for k in widgets.keys():
ent = widgets[k]
self.updateDefaultText(k, texts.get(k, ent.DEFAULT_TEXT))
self.debug("\t\t" + k + "=" + ent.default)
elif kind in [self.LABEL, self.BUTTON, self.CHECKBOX, self.MESSAGE, self.LINK]:
# relabel each widget
for k in widgets.keys():
widg = widgets[k]
self.debug("\t\t" + k + "---->" + texts.get(k, widg.DEFAULT_TEXT))
widg.config(text = texts.get(k, widg.DEFAULT_TEXT))
self.debug("\t\t" + k + "=" + widg.cget("text"))
else:
self.warn("Unsupported widget: " + section)
continue
# function to generate warning messages
def warn(self, message):
if self.WARN:
print("Warning -", message)
# function to turn off warning messages
def disableWarnings(self):
self.WARN = False
def enableWarnings(self):
self.WARN = True
# function to generate warning messages
def debug(self, message):
if self.DEBUG:
print("Debug -", message)
# function to turn on debug messages
def enableDebug(self):
self.DEBUG = True
def disableDebug(self):
self.DEBUG = False
# function to turn on the splash screen
def showSplash(self, text="appJar", fill="red", stripe="black", fg="white", font=44):
self.splashConfig= {'text':text, 'fill':fill, 'stripe':stripe, 'fg':fg, 'font':font}
#####################################
# Event Loop - must always be called at end
#####################################
def go(self, language=None):
""" Most important function! Start the GUI """
if self.splashConfig is not None:
splash = SplashScreen(
self.topLevel,
self.splashConfig['text'],
self.splashConfig['fill'],
self.splashConfig['stripe'],
self.splashConfig['fg'],
self.splashConfig['font']
)
self.topLevel.withdraw()
self.__bringToFront(splash)
# if language is populated, we are in internationalisation mode
# call the setLanguage function - to re-badge all the widgets
if language is not None:
self.setLanguage(language)
# check the containers have all been stopped
if len(self.containerStack) > 1:
self.warn("You didn't stop all containers")
for i in range(len(self.containerStack) - 1, 0, -1):
kind = self.containerStack[i]['type']
if kind not in [self.C_PANE]:
self.warn("STOP: " + kind)
if len(self.n_trees) > 0:
for k in self.n_trees:
self.n_trees[k].update()
self.n_trees[k].expand()
# create appJar menu, if no menuBar created
if not self.hasMenu:
self.addAppJarMenu()
if self.platform == self.WINDOWS:
self.menuBar.add_cascade(menu=self.n_menus["WIN_SYS"])
self.topLevel.config(menu=self.menuBar)
# pack it all in & make sure it's drawn
self.appWindow.pack(fill=BOTH)
self.topLevel.update_idletasks()
# check geom is set and set a minimum size, also positions the window
# if necessary
self.__dimensionWindow()
if self.splashConfig is not None:
time.sleep(3)
splash.destroy()
# bring to front
self.__bringToFront()
self.topLevel.deiconify()
# required to make the gui reopen after minimising
if self.GET_PLATFORM() == self.MAC:
self.topLevel.createcommand(
'tk::mac::ReopenApplication',
self.topLevel.deiconify)
# start the call back & flash loops
self.__poll()
self.__flash()
# start the main loop
try:
self.topLevel.mainloop()
except(KeyboardInterrupt, SystemExit):
self.stop()
def setStopFunction(self, function):
""" set a function to call when the GUI is quit. Must return True or False """
tl = self.__getTopLevel()
tl.stopFunction = function
# link to exit item in topMenu
# only if in root
if self.containerStack[-1]['type'] != self.C_SUBWINDOW:
tl.createcommand('exit', self.stop)
def stop(self, event=None):
""" Closes the GUI. If a stop function is set, will only close the GUI if True """
theFunc = self.__getTopLevel().stopFunction
if theFunc is None or theFunc():
# stop the after loops
self.topLevel.after_cancel(self.pollId)
self.topLevel.after_cancel(self.flashId)
self.topLevel.after_cancel(self.preloadAnimatedImageId)
# stop any animations
for key in self.n_imageAnimationIds:
self.topLevel.after_cancel(self.n_imageAnimationIds[key])
# stop any sounds, ignore error when not on Windows
try:
self.stopSound()
except:
pass
self.topLevel.quit()
self.topLevel.destroy()
#####################################
# Functions for configuring polling events
#####################################
# events will fire in order of being added, after sleeping for time
def setPollTime(self, time):
""" Set a frequency for executing queued functions """
self.pollTime = time
# register events to be called by the sleep timer
def registerEvent(self, func):
""" Queue a function, to be executed every poll time """
self.events.append(func)
# internal function, called by 'after' function, after sleeping
def __poll(self):
# run any registered actions
for e in self.events:
# execute the event
e()
self.pollId = self.topLevel.after(self.pollTime, self.__poll)
# not used now, but called every time window is resized
# may be used in the future...
def __windowEvent(self, event):
new_width = self.topLevel.winfo_width()
new_height = self.topLevel.winfo_height()
self.debug("Window resized: " + str(new_width) + "x" + str(new_height))
# will call the specified function when enter key is pressed
def enableEnter(self, func):
""" Binds <Return> to the specified function - all widgets """
self.bindKey("<Return>", func)
def disableEnter(self):
""" unbinds <enter> from all widgets """
self.unbindKey("<Return>")
def bindKey(self, key, func):
""" bind the specified key, to the specified function, for all widgets """
# for now discard the Event...
myF = self.MAKE_FUNC(func, key, True)
self.__getTopLevel().bind(key, myF)
def unbindKey(self, key):
""" unbinds the specified key from whatever functions it os bound to """
self.__getTopLevel().unbind(key)
# helper - will see if the mouse is in the specified widget
def __isMouseInWidget(self, w):
l_x = w.winfo_rootx()
l_y = w.winfo_rooty()
if l_x <= w.winfo_pointerx() <= l_x + \
w.winfo_width() and l_y <= w.winfo_pointery() <= l_y + w.winfo_height():
return True
else:
return False
# function to give a clicked widget the keyboard focus
def __grabFocus(self, e):
e.widget.focus_set()
#####################################
# FUNCTIONS for configuring GUI settings
#####################################
# set a minimum size
def __dimensionWindow(self):
self.topLevel.update_idletasks()
if self.__getTopLevel().geom != "fullscreen":
# ISSUES HERE:
# on MAC & LINUX, w_width/w_height always 1
# on WIN, w_height is bigger then r_height - leaving empty space
# get the apps requested width & height
r_width = self.__getTopLevel().winfo_reqwidth()
r_height = self.__getTopLevel().winfo_reqheight()
# get the current width & height
w_width = self.__getTopLevel().winfo_width()
w_height = self.__getTopLevel().winfo_height()
# get the window's width & height
m_width = self.topLevel.winfo_screenwidth()
m_height = self.topLevel.winfo_screenheight()
# determine best geom for OS
if self.platform in [self.MAC, self.LINUX]:
b_width = r_width
b_height = r_height
elif self.platform == self.WINDOWS:
b_height = min(r_height, w_height)
b_width = min(r_width, w_width)
h_height = max(r_height, w_height)
h_width = max(r_width, w_width)
# if a geom has not ben set
if self.__getTopLevel().geom is None:
width = b_width
height = b_height
# store it in the app's geom
self.__getTopLevel().geom = str(width) + "x" + str(height)
else:
# now split the app's geom
width = int(self.__getTopLevel().geom.lower().split("x")[0])
height = int(self.__getTopLevel().geom.lower().split("x")[1])
# warn the user that their geom is not big enough
if width < b_width or height < b_height:
self.warn(
"Specified dimensions (" +
self.__getTopLevel().geom +
"), less than requested dimensions (" +
str(b_width) +
"x" +
str(b_height) +
")")
# and set it as the minimum size
self.__getTopLevel().minsize(width, height)
# if the window hasn't been positioned by the user, put it in the
# middle
if not self.locationSet:
if self.platform == self.WINDOWS:
x = (m_width - h_width) / 2
y = (m_height - h_height) / 2
elif self.platform in [self.MAC, self.LINUX]:
x = (m_width - width) / 2
y = (m_height - height) / 2
self.setLocation(x, y)
# called to update screen geometry
def setGeometry(self, geom, height=None):
self.setGeom(geom, height)
def setGeom(self, geom, height=None):
if height is not None:
geom = str(geom) + "x" + str(height)
container = self.__getTopLevel()
container.geom = geom