-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPmw.py
9252 lines (7604 loc) · 295 KB
/
Pmw.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
import PmwColor
Color = PmwColor
del PmwColor
import PmwBlt
Blt = PmwBlt
del PmwBlt
### Loader functions:
_VERSION = '1.3.3'
def setversion(version):
if version != _VERSION:
raise ValueError, 'Dynamic versioning not available'
def setalphaversions(*alpha_versions):
if alpha_versions != ():
raise ValueError, 'Dynamic versioning not available'
def version(alpha = 0):
if alpha:
return ()
else:
return _VERSION
def installedversions(alpha = 0):
if alpha:
return ()
else:
return (_VERSION,)
######################################################################
### File: PmwBase.py
# Pmw megawidget base classes.
# This module provides a foundation for building megawidgets. It
# contains the MegaArchetype class which manages component widgets and
# configuration options. Also provided are the MegaToplevel and
# MegaWidget classes, derived from the MegaArchetype class. The
# MegaToplevel class contains a Tkinter Toplevel widget to act as the
# container of the megawidget. This is used as the base class of all
# megawidgets that are contained in their own top level window, such
# as a Dialog window. The MegaWidget class contains a Tkinter Frame
# to act as the container of the megawidget. This is used as the base
# class of all other megawidgets, such as a ComboBox or ButtonBox.
#
# Megawidgets are built by creating a class that inherits from either
# the MegaToplevel or MegaWidget class.
import os
import string
import sys
import traceback
import types
import Tkinter
# Special values used in index() methods of several megawidgets.
END = ['end']
SELECT = ['select']
DEFAULT = ['default']
# Constant used to indicate that an option can only be set by a call
# to the constructor.
INITOPT = ['initopt']
_DEFAULT_OPTION_VALUE = ['default_option_value']
_useTkOptionDb = 0
# Symbolic constants for the indexes into an optionInfo list.
_OPT_DEFAULT = 0
_OPT_VALUE = 1
_OPT_FUNCTION = 2
# Stacks
_busyStack = []
# Stack which tracks nested calls to show/hidebusycursor (called
# either directly or from activate()/deactivate()). Each element
# is a dictionary containing:
# 'newBusyWindows' : List of windows which had busy_hold called
# on them during a call to showbusycursor().
# The corresponding call to hidebusycursor()
# will call busy_release on these windows.
# 'busyFocus' : The blt _Busy window which showbusycursor()
# set the focus to.
# 'previousFocus' : The focus as it was when showbusycursor()
# was called. The corresponding call to
# hidebusycursor() will restore this focus if
# the focus has not been changed from busyFocus.
_grabStack = []
# Stack of grabbed windows. It tracks calls to push/popgrab()
# (called either directly or from activate()/deactivate()). The
# window on the top of the stack is the window currently with the
# grab. Each element is a dictionary containing:
# 'grabWindow' : The window grabbed by pushgrab(). The
# corresponding call to popgrab() will release
# the grab on this window and restore the grab
# on the next window in the stack (if there is one).
# 'globalMode' : True if the grabWindow was grabbed with a
# global grab, false if the grab was local
# and 'nograb' if no grab was performed.
# 'previousFocus' : The focus as it was when pushgrab()
# was called. The corresponding call to
# popgrab() will restore this focus.
# 'deactivateFunction' :
# The function to call (usually grabWindow.deactivate) if
# popgrab() is called (usually from a deactivate() method)
# on a window which is not at the top of the stack (that is,
# does not have the grab or focus). For example, if a modal
# dialog is deleted by the window manager or deactivated by
# a timer. In this case, all dialogs above and including
# this one are deactivated, starting at the top of the
# stack.
# Note that when dealing with focus windows, the name of the Tk
# widget is used, since it may be the '_Busy' window, which has no
# python instance associated with it.
#=============================================================================
# Functions used to forward methods from a class to a component.
# Fill in a flattened method resolution dictionary for a class (attributes are
# filtered out). Flattening honours the MI method resolution rules
# (depth-first search of bases in order). The dictionary has method names
# for keys and functions for values.
def __methodDict(cls, dict):
# the strategy is to traverse the class in the _reverse_ of the normal
# order, and overwrite any duplicates.
baseList = list(cls.__bases__)
baseList.reverse()
# do bases in reverse order, so first base overrides last base
for super in baseList:
__methodDict(super, dict)
# do my methods last to override base classes
for key, value in cls.__dict__.items():
# ignore class attributes
if type(value) == types.FunctionType:
dict[key] = value
def __methods(cls):
# Return all method names for a class.
# Return all method names for a class (attributes are filtered
# out). Base classes are searched recursively.
dict = {}
__methodDict(cls, dict)
return dict.keys()
# Function body to resolve a forwarding given the target method name and the
# attribute name. The resulting lambda requires only self, but will forward
# any other parameters.
__stringBody = (
'def %(method)s(this, *args, **kw): return ' +
#'apply(this.%(attribute)s.%(method)s, args, kw)')
'this.%(attribute)s.%(method)s(*args, **kw)')
# Get a unique id
__counter = 0
def __unique():
global __counter
__counter = __counter + 1
return str(__counter)
# Function body to resolve a forwarding given the target method name and the
# index of the resolution function. The resulting lambda requires only self,
# but will forward any other parameters. The target instance is identified
# by invoking the resolution function.
__funcBody = (
'def %(method)s(this, *args, **kw): return ' +
#'apply(this.%(forwardFunc)s().%(method)s, args, kw)')
'this.%(forwardFunc)s().%(method)s(*args, **kw)');
def forwardmethods(fromClass, toClass, toPart, exclude = ()):
# Forward all methods from one class to another.
# Forwarders will be created in fromClass to forward method
# invocations to toClass. The methods to be forwarded are
# identified by flattening the interface of toClass, and excluding
# methods identified in the exclude list. Methods already defined
# in fromClass, or special methods with one or more leading or
# trailing underscores will not be forwarded.
# For a given object of class fromClass, the corresponding toClass
# object is identified using toPart. This can either be a String
# denoting an attribute of fromClass objects, or a function taking
# a fromClass object and returning a toClass object.
# Example:
# class MyClass:
# ...
# def __init__(self):
# ...
# self.__target = TargetClass()
# ...
# def findtarget(self):
# return self.__target
# forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2'])
# # ...or...
# forwardmethods(MyClass, TargetClass, MyClass.findtarget,
# ['dangerous1', 'dangerous2'])
# In both cases, all TargetClass methods will be forwarded from
# MyClass except for dangerous1, dangerous2, special methods like
# __str__, and pre-existing methods like findtarget.
# Allow an attribute name (String) or a function to determine the instance
if type(toPart) != types.StringType:
# check that it is something like a function
if callable(toPart):
# If a method is passed, use the function within it
if hasattr(toPart, 'im_func'):
toPart = toPart.im_func
# After this is set up, forwarders in this class will use
# the forwarding function. The forwarding function name is
# guaranteed to be unique, so that it can't be hidden by subclasses
forwardName = '__fwdfunc__' + __unique()
fromClass.__dict__[forwardName] = toPart
# It's not a valid type
else:
raise TypeError, 'toPart must be attribute name, function or method'
# get the full set of candidate methods
dict = {}
__methodDict(toClass, dict)
# discard special methods
for ex in dict.keys():
if ex[:1] == '_' or ex[-1:] == '_':
del dict[ex]
# discard dangerous methods supplied by the caller
for ex in exclude:
if dict.has_key(ex):
del dict[ex]
# discard methods already defined in fromClass
for ex in __methods(fromClass):
if dict.has_key(ex):
del dict[ex]
for method, func in dict.items():
d = {'method': method, 'func': func}
if type(toPart) == types.StringType:
execString = \
__stringBody % {'method' : method, 'attribute' : toPart}
else:
execString = \
__funcBody % {'forwardFunc' : forwardName, 'method' : method}
exec execString in d
# this creates a method
fromClass.__dict__[method] = d[method]
#=============================================================================
def setgeometryanddeiconify(window, geom):
# To avoid flashes on X and to position the window correctly on NT
# (caused by Tk bugs).
if os.name == 'nt' or \
(os.name == 'posix' and sys.platform[:6] == 'cygwin'):
# Require overrideredirect trick to stop window frame
# appearing momentarily.
redirect = window.overrideredirect()
if not redirect:
window.overrideredirect(1)
window.deiconify()
if geom is not None:
window.geometry(geom)
# Call update_idletasks to ensure NT moves the window to the
# correct position it is raised.
window.update_idletasks()
window.tkraise()
if not redirect:
window.overrideredirect(0)
else:
if geom is not None:
window.geometry(geom)
# Problem!? Which way around should the following two calls
# go? If deiconify() is called first then I get complaints
# from people using the enlightenment or sawfish window
# managers that when a dialog is activated it takes about 2
# seconds for the contents of the window to appear. But if
# tkraise() is called first then I get complaints from people
# using the twm window manager that when a dialog is activated
# it appears in the top right corner of the screen and also
# takes about 2 seconds to appear.
#window.tkraise()
# Call update_idletasks to ensure certain window managers (eg:
# enlightenment and sawfish) do not cause Tk to delay for
# about two seconds before displaying window.
#window.update_idletasks()
#window.deiconify()
window.deiconify()
if window.overrideredirect():
# The window is not under the control of the window manager
# and so we need to raise it ourselves.
window.tkraise()
#=============================================================================
class MegaArchetype:
# Megawidget abstract root class.
# This class provides methods which are inherited by classes
# implementing useful bases (this class doesn't provide a
# container widget inside which the megawidget can be built).
def __init__(self, parent = None, hullClass = None):
# Mapping from each megawidget option to a list of information
# about the option
# - default value
# - current value
# - function to call when the option is initialised in the
# call to initialiseoptions() in the constructor or
# modified via configure(). If this is INITOPT, the
# option is an initialisation option (an option that can
# be set by the call to the constructor but can not be
# used with configure).
# This mapping is not initialised here, but in the call to
# defineoptions() which precedes construction of this base class.
#
# self._optionInfo = {}
# Mapping from each component name to a tuple of information
# about the component.
# - component widget instance
# - configure function of widget instance
# - the class of the widget (Frame, EntryField, etc)
# - cget function of widget instance
# - the name of the component group of this component, if any
self.__componentInfo = {}
# Mapping from alias names to the names of components or
# sub-components.
self.__componentAliases = {}
# Contains information about the keywords provided to the
# constructor. It is a mapping from the keyword to a tuple
# containing:
# - value of keyword
# - a boolean indicating if the keyword has been used.
# A keyword is used if, during the construction of a megawidget,
# - it is defined in a call to defineoptions() or addoptions(), or
# - it references, by name, a component of the megawidget, or
# - it references, by group, at least one component
# At the end of megawidget construction, a call is made to
# initialiseoptions() which reports an error if there are
# unused options given to the constructor.
#
# After megawidget construction, the dictionary contains
# keywords which refer to a dynamic component group, so that
# these components can be created after megawidget
# construction and still use the group options given to the
# constructor.
#
# self._constructorKeywords = {}
# List of dynamic component groups. If a group is included in
# this list, then it not an error if a keyword argument for
# the group is given to the constructor or to configure(), but
# no components with this group have been created.
# self._dynamicGroups = ()
if hullClass is None:
self._hull = None
else:
if parent is None:
parent = Tkinter._default_root
# Create the hull.
self._hull = self.createcomponent('hull',
(), None,
hullClass, (parent,))
_hullToMegaWidget[self._hull] = self
if _useTkOptionDb:
# Now that a widget has been created, query the Tk
# option database to get the default values for the
# options which have not been set in the call to the
# constructor. This assumes that defineoptions() is
# called before the __init__().
option_get = self.option_get
_VALUE = _OPT_VALUE
_DEFAULT = _OPT_DEFAULT
for name, info in self._optionInfo.items():
value = info[_VALUE]
if value is _DEFAULT_OPTION_VALUE:
resourceClass = string.upper(name[0]) + name[1:]
value = option_get(name, resourceClass)
if value != '':
try:
# Convert the string to int/float/tuple, etc
value = eval(value, {'__builtins__': {}})
except:
pass
info[_VALUE] = value
else:
info[_VALUE] = info[_DEFAULT]
def destroy(self):
# Clean up optionInfo in case it contains circular references
# in the function field, such as self._settitle in class
# MegaToplevel.
self._optionInfo = {}
if self._hull is not None:
del _hullToMegaWidget[self._hull]
self._hull.destroy()
#======================================================================
# Methods used (mainly) during the construction of the megawidget.
def defineoptions(self, keywords, optionDefs, dynamicGroups = ()):
# Create options, providing the default value and the method
# to call when the value is changed. If any option created by
# base classes has the same name as one in <optionDefs>, the
# base class's value and function will be overriden.
# This should be called before the constructor of the base
# class, so that default values defined in the derived class
# override those in the base class.
if not hasattr(self, '_constructorKeywords'):
# First time defineoptions has been called.
tmp = {}
for option, value in keywords.items():
tmp[option] = [value, 0]
self._constructorKeywords = tmp
self._optionInfo = {}
self._initialiseoptions_counter = 0
self._initialiseoptions_counter = self._initialiseoptions_counter + 1
if not hasattr(self, '_dynamicGroups'):
self._dynamicGroups = ()
self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups)
self.addoptions(optionDefs)
def addoptions(self, optionDefs):
# Add additional options, providing the default value and the
# method to call when the value is changed. See
# "defineoptions" for more details
# optimisations:
optionInfo = self._optionInfo
optionInfo_has_key = optionInfo.has_key
keywords = self._constructorKeywords
keywords_has_key = keywords.has_key
FUNCTION = _OPT_FUNCTION
for name, default, function in optionDefs:
if '_' not in name:
# The option will already exist if it has been defined
# in a derived class. In this case, do not override the
# default value of the option or the callback function
# if it is not None.
if not optionInfo_has_key(name):
if keywords_has_key(name):
value = keywords[name][0]
optionInfo[name] = [default, value, function]
del keywords[name]
else:
if _useTkOptionDb:
optionInfo[name] = \
[default, _DEFAULT_OPTION_VALUE, function]
else:
optionInfo[name] = [default, default, function]
elif optionInfo[name][FUNCTION] is None:
optionInfo[name][FUNCTION] = function
else:
# This option is of the form "component_option". If this is
# not already defined in self._constructorKeywords add it.
# This allows a derived class to override the default value
# of an option of a component of a base class.
if not keywords_has_key(name):
keywords[name] = [default, 0]
def createcomponent(self, componentName, componentAliases,
componentGroup, widgetClass, *widgetArgs, **kw):
# Create a component (during construction or later).
if self.__componentInfo.has_key(componentName):
raise ValueError, 'Component "%s" already exists' % componentName
if '_' in componentName:
raise ValueError, \
'Component name "%s" must not contain "_"' % componentName
if hasattr(self, '_constructorKeywords'):
keywords = self._constructorKeywords
else:
keywords = {}
for alias, component in componentAliases:
# Create aliases to the component and its sub-components.
index = string.find(component, '_')
if index < 0:
self.__componentAliases[alias] = (component, None)
else:
mainComponent = component[:index]
subComponent = component[(index + 1):]
self.__componentAliases[alias] = (mainComponent, subComponent)
# Remove aliases from the constructor keyword arguments by
# replacing any keyword arguments that begin with *alias*
# with corresponding keys beginning with *component*.
alias = alias + '_'
aliasLen = len(alias)
for option in keywords.keys():
if len(option) > aliasLen and option[:aliasLen] == alias:
newkey = component + '_' + option[aliasLen:]
keywords[newkey] = keywords[option]
del keywords[option]
componentPrefix = componentName + '_'
nameLen = len(componentPrefix)
for option in keywords.keys():
if len(option) > nameLen and option[:nameLen] == componentPrefix:
# The keyword argument refers to this component, so add
# this to the options to use when constructing the widget.
kw[option[nameLen:]] = keywords[option][0]
del keywords[option]
else:
# Check if this keyword argument refers to the group
# of this component. If so, add this to the options
# to use when constructing the widget. Mark the
# keyword argument as being used, but do not remove it
# since it may be required when creating another
# component.
index = string.find(option, '_')
if index >= 0 and componentGroup == option[:index]:
rest = option[(index + 1):]
kw[rest] = keywords[option][0]
keywords[option][1] = 1
if kw.has_key('pyclass'):
widgetClass = kw['pyclass']
del kw['pyclass']
if widgetClass is None:
return None
if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType:
# Arguments to the constructor can be specified as either
# multiple trailing arguments to createcomponent() or as a
# single tuple argument.
widgetArgs = widgetArgs[0]
widget = apply(widgetClass, widgetArgs, kw)
componentClass = widget.__class__.__name__
self.__componentInfo[componentName] = (widget, widget.configure,
componentClass, widget.cget, componentGroup)
return widget
def destroycomponent(self, name):
# Remove a megawidget component.
# This command is for use by megawidget designers to destroy a
# megawidget component.
self.__componentInfo[name][0].destroy()
del self.__componentInfo[name]
def createlabel(self, parent, childCols = 1, childRows = 1):
labelpos = self['labelpos']
labelmargin = self['labelmargin']
if labelpos is None:
return
label = self.createcomponent('label',
(), None,
Tkinter.Label, (parent,))
if labelpos[0] in 'ns':
# vertical layout
if labelpos[0] == 'n':
row = 0
margin = 1
else:
row = childRows + 3
margin = row - 1
label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos)
parent.grid_rowconfigure(margin, minsize=labelmargin)
else:
# horizontal layout
if labelpos[0] == 'w':
col = 0
margin = 1
else:
col = childCols + 3
margin = col - 1
label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos)
parent.grid_columnconfigure(margin, minsize=labelmargin)
def initialiseoptions(self, dummy = None):
self._initialiseoptions_counter = self._initialiseoptions_counter - 1
if self._initialiseoptions_counter == 0:
unusedOptions = []
keywords = self._constructorKeywords
for name in keywords.keys():
used = keywords[name][1]
if not used:
# This keyword argument has not been used. If it
# does not refer to a dynamic group, mark it as
# unused.
index = string.find(name, '_')
if index < 0 or name[:index] not in self._dynamicGroups:
unusedOptions.append(name)
if len(unusedOptions) > 0:
if len(unusedOptions) == 1:
text = 'Unknown option "'
else:
text = 'Unknown options "'
raise KeyError, text + string.join(unusedOptions, ', ') + \
'" for ' + self.__class__.__name__
# Call the configuration callback function for every option.
FUNCTION = _OPT_FUNCTION
for info in self._optionInfo.values():
func = info[FUNCTION]
if func is not None and func is not INITOPT:
func()
#======================================================================
# Method used to configure the megawidget.
def configure(self, option=None, **kw):
# Query or configure the megawidget options.
#
# If not empty, *kw* is a dictionary giving new
# values for some of the options of this megawidget or its
# components. For options defined for this megawidget, set
# the value of the option to the new value and call the
# configuration callback function, if any. For options of the
# form <component>_<option>, where <component> is a component
# of this megawidget, call the configure method of the
# component giving it the new value of the option. The
# <component> part may be an alias or a component group name.
#
# If *option* is None, return all megawidget configuration
# options and settings. Options are returned as standard 5
# element tuples
#
# If *option* is a string, return the 5 element tuple for the
# given configuration option.
# First, deal with the option queries.
if len(kw) == 0:
# This configure call is querying the values of one or all options.
# Return 5-tuples:
# (optionName, resourceName, resourceClass, default, value)
if option is None:
rtn = {}
for option, config in self._optionInfo.items():
resourceClass = string.upper(option[0]) + option[1:]
rtn[option] = (option, option, resourceClass,
config[_OPT_DEFAULT], config[_OPT_VALUE])
return rtn
else:
config = self._optionInfo[option]
resourceClass = string.upper(option[0]) + option[1:]
return (option, option, resourceClass, config[_OPT_DEFAULT],
config[_OPT_VALUE])
# optimisations:
optionInfo = self._optionInfo
optionInfo_has_key = optionInfo.has_key
componentInfo = self.__componentInfo
componentInfo_has_key = componentInfo.has_key
componentAliases = self.__componentAliases
componentAliases_has_key = componentAliases.has_key
VALUE = _OPT_VALUE
FUNCTION = _OPT_FUNCTION
# This will contain a list of options in *kw* which
# are known to this megawidget.
directOptions = []
# This will contain information about the options in
# *kw* of the form <component>_<option>, where
# <component> is a component of this megawidget. It is a
# dictionary whose keys are the configure method of each
# component and whose values are a dictionary of options and
# values for the component.
indirectOptions = {}
indirectOptions_has_key = indirectOptions.has_key
for option, value in kw.items():
if optionInfo_has_key(option):
# This is one of the options of this megawidget.
# Make sure it is not an initialisation option.
if optionInfo[option][FUNCTION] is INITOPT:
raise KeyError, \
'Cannot configure initialisation option "' \
+ option + '" for ' + self.__class__.__name__
optionInfo[option][VALUE] = value
directOptions.append(option)
else:
index = string.find(option, '_')
if index >= 0:
# This option may be of the form <component>_<option>.
component = option[:index]
componentOption = option[(index + 1):]
# Expand component alias
if componentAliases_has_key(component):
component, subComponent = componentAliases[component]
if subComponent is not None:
componentOption = subComponent + '_' \
+ componentOption
# Expand option string to write on error
option = component + '_' + componentOption
if componentInfo_has_key(component):
# Configure the named component
componentConfigFuncs = [componentInfo[component][1]]
else:
# Check if this is a group name and configure all
# components in the group.
componentConfigFuncs = []
for info in componentInfo.values():
if info[4] == component:
componentConfigFuncs.append(info[1])
if len(componentConfigFuncs) == 0 and \
component not in self._dynamicGroups:
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
# Add the configure method(s) (may be more than
# one if this is configuring a component group)
# and option/value to dictionary.
for componentConfigFunc in componentConfigFuncs:
if not indirectOptions_has_key(componentConfigFunc):
indirectOptions[componentConfigFunc] = {}
indirectOptions[componentConfigFunc][componentOption] \
= value
else:
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
# Call the configure methods for any components.
#apply has been deprecated since python 2.3
#map(apply, indirectOptions.keys(),
# ((),) * len(indirectOptions), indirectOptions.values())
for func in indirectOptions.keys():
func( **indirectOptions[func])
# Call the configuration callback function for each option.
for option in directOptions:
info = optionInfo[option]
func = info[_OPT_FUNCTION]
if func is not None:
func()
def __setitem__(self, key, value):
#apply has been deprecated since Python 2.3
#apply(self.configure, (), {key: value})
self.configure(*(), **{key: value})
#======================================================================
# Methods used to query the megawidget.
def component(self, name):
# Return a component widget of the megawidget given the
# component's name
# This allows the user of a megawidget to access and configure
# widget components directly.
# Find the main component and any subcomponents
index = string.find(name, '_')
if index < 0:
component = name
remainingComponents = None
else:
component = name[:index]
remainingComponents = name[(index + 1):]
# Expand component alias
if self.__componentAliases.has_key(component):
component, subComponent = self.__componentAliases[component]
if subComponent is not None:
if remainingComponents is None:
remainingComponents = subComponent
else:
remainingComponents = subComponent + '_' \
+ remainingComponents
widget = self.__componentInfo[component][0]
if remainingComponents is None:
return widget
else:
return widget.component(remainingComponents)
def interior(self):
return self._hull
def hulldestroyed(self):
return not _hullToMegaWidget.has_key(self._hull)
def __str__(self):
return str(self._hull)
def cget(self, option):
# Get current configuration setting.
# Return the value of an option, for example myWidget['font'].
if self._optionInfo.has_key(option):
return self._optionInfo[option][_OPT_VALUE]
else:
index = string.find(option, '_')
if index >= 0:
component = option[:index]
componentOption = option[(index + 1):]
# Expand component alias
if self.__componentAliases.has_key(component):
component, subComponent = self.__componentAliases[component]
if subComponent is not None:
componentOption = subComponent + '_' + componentOption
# Expand option string to write on error
option = component + '_' + componentOption
if self.__componentInfo.has_key(component):
# Call cget on the component.
componentCget = self.__componentInfo[component][3]
return componentCget(componentOption)
else:
# If this is a group name, call cget for one of
# the components in the group.
for info in self.__componentInfo.values():
if info[4] == component:
componentCget = info[3]
return componentCget(componentOption)
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
__getitem__ = cget
def isinitoption(self, option):
return self._optionInfo[option][_OPT_FUNCTION] is INITOPT
def options(self):
options = []
if hasattr(self, '_optionInfo'):
for option, info in self._optionInfo.items():
isinit = info[_OPT_FUNCTION] is INITOPT
default = info[_OPT_DEFAULT]
options.append((option, default, isinit))
options.sort()
return options
def components(self):
# Return a list of all components.
# This list includes the 'hull' component and all widget subcomponents
names = self.__componentInfo.keys()
names.sort()
return names
def componentaliases(self):
# Return a list of all component aliases.
componentAliases = self.__componentAliases
names = componentAliases.keys()
names.sort()
rtn = []
for alias in names:
(mainComponent, subComponent) = componentAliases[alias]
if subComponent is None:
rtn.append((alias, mainComponent))
else:
rtn.append((alias, mainComponent + '_' + subComponent))
return rtn
def componentgroup(self, name):
return self.__componentInfo[name][4]
#=============================================================================
# The grab functions are mainly called by the activate() and
# deactivate() methods.
#
# Use pushgrab() to add a new window to the grab stack. This
# releases the grab by the window currently on top of the stack (if
# there is one) and gives the grab and focus to the new widget.
#
# To remove the grab from the window on top of the grab stack, call
# popgrab().
#
# Use releasegrabs() to release the grab and clear the grab stack.
def pushgrab(grabWindow, globalMode, deactivateFunction):
prevFocus = grabWindow.tk.call('focus')
grabInfo = {
'grabWindow' : grabWindow,
'globalMode' : globalMode,
'previousFocus' : prevFocus,
'deactivateFunction' : deactivateFunction,
}
_grabStack.append(grabInfo)
_grabtop()
grabWindow.focus_set()
def popgrab(window):
# Return the grab to the next window in the grab stack, if any.
# If this window is not at the top of the grab stack, then it has
# just been deleted by the window manager or deactivated by a
# timer. Call the deactivate method for the modal dialog above
# this one on the stack.
if _grabStack[-1]['grabWindow'] != window:
for index in range(len(_grabStack)):
if _grabStack[index]['grabWindow'] == window:
_grabStack[index + 1]['deactivateFunction']()
break
grabInfo = _grabStack[-1]
del _grabStack[-1]
topWidget = grabInfo['grabWindow']
prevFocus = grabInfo['previousFocus']
globalMode = grabInfo['globalMode']
if globalMode != 'nograb':
topWidget.grab_release()
if len(_grabStack) > 0:
_grabtop()
if prevFocus != '':
try:
topWidget.tk.call('focus', prevFocus)
except Tkinter.TclError:
# Previous focus widget has been deleted. Set focus
# to root window.
Tkinter._default_root.focus_set()
else:
# Make sure that focus does not remain on the released widget.
if len(_grabStack) > 0:
topWidget = _grabStack[-1]['grabWindow']
topWidget.focus_set()
else:
Tkinter._default_root.focus_set()
def grabstacktopwindow():
if len(_grabStack) == 0:
return None
else:
return _grabStack[-1]['grabWindow']
def releasegrabs():
# Release grab and clear the grab stack.
current = Tkinter._default_root.grab_current()
if current is not None:
current.grab_release()
_grabStack[:] = []
def _grabtop():
grabInfo = _grabStack[-1]
topWidget = grabInfo['grabWindow']
globalMode = grabInfo['globalMode']
if globalMode == 'nograb':
return
while 1:
try:
if globalMode:
topWidget.grab_set_global()
else:
topWidget.grab_set()
break
except Tkinter.TclError:
# Another application has grab. Keep trying until
# grab can succeed.
topWidget.after(100)