-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyMapper.py
1682 lines (1328 loc) · 72.7 KB
/
KeyMapper.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
#######################################################################
## ##
## KeyMapper - a module for handling keys and key-bindings ##
## v1.0 ##
## ##
#######################################################################
## ##
## Original version (0.8) written by ##
## Ian Eborn (Thaumaturge) in 2014 ##
## Major updates (to v1.0) by Ian Eborn in 2019 ##
## ##
#######################################################################
## ##
## This code is licensed under the MIT license. See the ##
## license file (LICENSE.md) for details. ##
## Link, if available: ##
## https://github.com/ArsThaumaturgis/KeyMapper/blob/master/LICENSE ##
## ##
#######################################################################
from direct.gui.DirectGui import *
from panda3d.core import TextNode, PandaNode, ModifierButtons
from panda3d.core import Filename, VirtualFileSystem
from panda3d.core import InputDevice, ButtonThrower, InputDeviceNode
from panda3d.core import BitMask32
from direct.task import Task
"""The four types of key-binding curently supported. Respectively:
* Event-released----------------a callback is called on key-release
* Event-pressed-----------------a callback is called on key-press
* Event-pressed-and-released----callbacks are called for both key -press and -release
* Held--------------------------a variable is created to represent the key's state, with
a value of True indicating that it is held and False
indicating that it is not. The variable may then be polled at will"""
KEYMAP_EVENT_RELEASED = 0
KEYMAP_EVENT_PRESSED = 1
KEYMAP_EVENT_PRESSED_AND_RELEASED = 2
KEYMAP_HELD_KEY = 3
DEVICE_TYPE_TAG = "deviceTag"
class KeyBindingButtonWrapper():
"""The base class from which KeyMapper's button-wrappers
are intended to be derived.
KeyMapper stores all of the buttons in its binding list,
each intended to be in a wrapper such as this. When a
key-binding is changed, the wrapper's "setBindingText" method
is called, allowing the wrapper to update the button's
representation of that key-binding in whatever way makes sense
for the approach to the binding buttons that it is intended to
deal with.
All of the methods of this base class are stubs; it is
intended only as the template for more-complete wrappers."""
def __init__(self):
pass
def setBindingText(self, newText):
"""Update the button's representation of the currentBinding.
Params: newText -- The new representation of the binding"""
pass
def destroy(self):
pass
class BasicKeyBindingButtonWrapper(KeyBindingButtonWrapper):
"""A button-wrapper representing the default approach to
KeyMapper's list-buttons: a button with an attached label,
the latter of which displays the key to which the control
is bound."""
def __init__(self, btn, label):
KeyBindingButtonWrapper.__init__(self)
self.button = btn
self.label = label
def setZ(self, newZ):
"""Set the button's z-position.
Params: newZ -- The new z-position
A convenience method used by KeyMapper's default
implementation of the binding buttons."""
self.button.setZ(newZ)
def reparentTo(self, newParent):
"""Give the button a new parent.
Params: newParent -- The NodePath to become the parent of the button
A convenience method used by KeyMapper's default
implementation of the binding buttons."""
self.button.reparentTo(newParent)
def setBindingText(self, newText):
"""Update the button's representation of the currentBinding.
Params: newText -- The new representation of the binding"""
self.label["text"] = newText
self.label.setText()
self.label.resetFrameSize()
def destroy(self):
"""Clean up the button wrapper, as well as its button and label."""
KeyBindingButtonWrapper.destroy(self)
if self.button is not None:
if not self.button.isEmpty():
self.button["extraArgs"] = None
self.button.destroy()
self.button.removeNode()
self.button = None
if self.label is not None:
if not self.label.isEmpty():
self.label.destroy()
self.label.removeNode()
self.label = None
class KeyBinding():
def __init__(self):
self.keyDescription = None
self.binding = None
self.defaultBinding = None
self.type = None
self.callback = None
self.deviceType = None
self.defaultDeviceType = None
self.axisDirection = 0
self.groupID = BitMask32(1)
class AxisData():
def __init__(self):
self.axis = ""
self.keyDescriptionPositive = None
self.keyDescriptionNegative = None
self.deadZone = 0
self.deviceTypePositive = None
self.deviceTypeNegative = None
self.devicePositive = None
self.deviceNegative = None
class KeyMapper():
"""The main KeyMapper class"""
def __init__(self, bindingFile, defaultProfileDirectory, userProfileDirectory,
eventObject, saveCallback, loadCallback,
acceptKeyCombinations=False, useNegativeValuesForNegativeAxes = False,
keyStateCallback = None):
"""Initialise the KeyMapper.
Params: bindingFile -- The name of the file on disk in
which the key-bindings are to be saved
defaultProfileDirectory -- The directory in which the default key-binding
profiles are found
userProfileDirectory -- The directory into which the user's key-bindings
and additional profiles should be saved
eventObject -- An object that derives from DirectObject,
and which is expected to provide event-handling
saveCallback -- A method that will handle the file-writing of
key-binding data produced by KeyMapper
loadCallback -- A method that will handle the file-reading of
key-binding data to be used by KeyMapper
acceptKeyCombinations -- A boolean value indicating whether
modifier-based key-combinations are to
be accepted. Defaults to False.
useNegativeValuesForNegativeAxes -- Whether negative axial inputs should
produce negative key-values
keyStateCallback -- An optional method that can be called when a key
-press or -release alters a key-map value"""
""" Information on the save- and load- callbacks:
~SAVE-CALLBACK~
* The save-callback is expected to take three parameters:
keySaveData, axisSaveData, fileName
* keySaveData is the data produced for key-bindings
- Structure: list of lists of key-binding data.
The key-binding data-lists have the following structure:
[keyDescription, currentBinding, deviceType]
i.e.: [key-description/control-name, currently-bound button/axis, type of device associated with the binding]
* axisSaveData is the data produced for axes being used
- Structure: list of lists of axis-data
The axis data-lists have the following structure:
[axisName, deadZoneValue, deviceTypePositive, deviceTypeNegative,
keyDescriptionPositive, keyDescriptionNegative]
i.e.: [the axis in question, the dead-zone for this axis,
the type of device associated with positive axis-values,
the type of device associated with negative axis-values,
the key-description/control bound to positive axis-values,
the key-description/control bound to negative axis-values]
* fileName is the Panda Filename-object that indicates the file to be saved to.
~LOAD-CALLBACK~
The load-callback is expected to take three parameters:
fileName
* fileName is the Panda Filename-object that indicates the file to be loaded from.
As to return-value, this callback is expected to return key-mapping data
in the same format as the save-callback takes in.
That is, it's expected to return a list/tuple containing
two lists--the first being a list of key-binding data-lists,
and the second being a list of axis data-lists.
Something like this:
[
[
[key-binding data 1], [key-binding data 2], ...
],
[
[axis-data 1], [axis-data 2], ...
]
]
"""
# These first three variables are KeyMapper's representation of the relevant key-states
# The first of these, self.keys, is the dictionary that may
# be polled by applications enquiring after the states of keys
# that use the "key-held" binding type.
# This dictionary stores values between zero and one.
# If an application just wants to know whether a key has been pressed or not,
# this can be queried via the convenience function "keyIsHeld".
# The second, self.keyBindings, is intended for internal KeyMapper
# use: it stores the current binding, default binding, binding type and
# callback, if any, for a given key
# Finally, the last, self.keyOrder, simply specifies the order in which
# the keys are to be represented in the binding list; it is simply a list
# of the key-names, with placement in this list giving the placement in
# the GUI list.
self.keys = {} # Arranged like so: {key-name : state}
self.keyBindings = {} # Arranged like so: {key-name : key-binding object}
self.keyOrder = [] # Gives the order in which they keys should appear in the GUI list
self.keyMap = base.win.getKeyboardMap()
self.keyStateCallback = keyStateCallback
self.acceptKeyCombinations = acceptKeyCombinations
if not acceptKeyCombinations:
base.mouseWatcherNode.setModifierButtons(ModifierButtons())
base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())
self.negativeValuesForNegativeAxes = useNegativeValuesForNegativeAxes
self.bindingFile = Filename(bindingFile)
self.bindingFileCustom = self.bindingFile
self.eventObject = eventObject
self.defaultProfileDirectory = defaultProfileDirectory
self.userProfileDirectory = userProfileDirectory
self.profileDict = {}
vfs = VirtualFileSystem.getGlobalPtr()
if not vfs.exists(self.defaultProfileDirectory):
succeeded = vfs.makeDirectoryFull(self.defaultProfileDirectory)
if not succeeded:
taskMgr.doMethodLater(0, self.showErrorDialogue, "Warning! Failed to create default profile directory: " + self.defaultProfileDirectory)
if not vfs.exists(self.userProfileDirectory):
succeeded = vfs.makeDirectoryFull(self.userProfileDirectory)
if not succeeded:
taskMgr.doMethodLater(0, self.showErrorDialogue, "Warning! Failed to create user profile directory: " + self.userProfileDirectory)
self.getAvailableProfiles()
self.keyInterceptionEvents = [
"keyInterception",
"keyRelease",
"keyInterceptionMouse",
"keyReleaseMouse"
]
# Button thrower and the two events registered below allow us to catch
# arbitrary button events, via which we set new bindings
self.buttonThrower = base.buttonThrowers[0].node()
self.eventObject.accept("keyInterception", self.keyInterception, extraArgs = [None])
self.eventObject.accept("keyRelease", self.keyRelease)
self.eventObject.accept("keyInterceptionMouse", self.keyInterceptionMouse, extraArgs = [None])
self.eventObject.accept("keyReleaseMouse", self.keyReleaseMouse)
for deviceType in InputDevice.DeviceClass:
if deviceType is not InputDevice.DeviceClass.keyboard and \
deviceType is not InputDevice.DeviceClass.mouse:
deviceTypeString = self.getDeviceTypeString(deviceType)
eventString = "keyInterception_" + deviceTypeString
self.eventObject.accept(eventString,
self.keyInterception,
extraArgs = [deviceTypeString])
self.keyInterceptionEvents.append(eventString)
self.deviceButtonThrowers = {}
self.dataNPList = []
self.deviceAxisTestValues = {}
self.eventObject.accept("connect-device", self.connectController)
self.eventObject.accept("disconnect-device", self.disconnectController)
self.lastKeyInterception = ""
self.lastKeyInterceptionDeviceType = None
self.keyBeingBound = None
self.buttonList = []
self.list = None
self.guiRoot = aspect2d.attachNewNode(PandaNode("KeyMapper"))
self.currentConflict = None
# Some parameters used in creating the GUI; these may be altered
# as desired by the user before calling "setup" in order to
# adjust the appearance of the list.
self.buttonSize = 0.05
self.buttonSpacing = self.buttonSize + 0.05
self.firstButtonTopPadding = self.buttonSize*2.0
self.listLength = 10
self.devicesInUse = {}
self.deadZoneDefaultValue = 0.3
self.axesInUse = [] # ["AxisData" objects]
self.updateTask = None
self.loadMappingCallback = loadCallback
self.saveMappingCallback = saveCallback
self.controllerNotificationCallback = None
self.deviceTypesThatAreRaw = [
InputDevice.DeviceClass.keyboard
]
"""""
METHODS INTENDED FOR DEVELOPER-USE:
"""""
"""
Setting up KeyMapper:
"""
def addKey(self, description, defaultKey, defaultKeyDeviceType, keyType,
callback = None, axisDirection = 0, groupID = None):
"""Add a key to the list of controls managed by the KeyMapper.
Params: description -- The name of the key (such as 'move forward' or 'shoot');
this should uniquely identify the key, as it is used
to identify it within KeyMapper.
defaultKey -- The default mapping for this key.
keyType -- The type of binding to be used, selected from:
KEYMAP_EVENT_RELEASED, KEYMAP_EVENT_PRESSED,
KEYMAP_EVENT_PRESSED_AND_RELEASED and KEYMAP_HELD_KEY
callback -- The callback--if any--to be used for binding types other than
KEYMAP_HELD_KEY.
In the case of KEYMAP_EVENT_PRESSED_AND_RELEASED, this may be
either:
* A single callback (in which case the same callback is
used for both events, with an additional event-type parameter
being provided to it (which should have a value of either
KEYMAP_EVENT_PRESSED or KEYMAP_EVENT_RELEASED, as appropriate)),
or
* A list or tuple holding two callbacks, in which case the first
should be called on key-down and the second on key-up."""
self.keys[description] = 0
defaultKeyDeviceTypeStr = self.getDeviceTypeString(defaultKeyDeviceType)
newBinding = KeyBinding()
newBinding.keyDescription = description
newBinding.binding = defaultKey
newBinding.defaultBinding = defaultKey
newBinding.type = keyType
newBinding.callback = callback
newBinding.defaultDeviceType = defaultKeyDeviceTypeStr
newBinding.deviceType = defaultKeyDeviceTypeStr
newBinding.axisDirection = axisDirection
if groupID is not None:
if not isinstance(groupID, BitMask32):
groupID = BitMask32(groupID)
newBinding.groupID = groupID
self.keyBindings[description] = newBinding
self.bindKey(description, defaultKey, keyType, callback, defaultKeyDeviceTypeStr, axisDirection)
self.keyOrder.append(description)
def setup(self):
"""Set up the KeyMapper after adding the relevant keys,
initialising the key-maps and constructing the GUI"""
# Build the error dialogue first, in case
# something goes wrong...
self.buildErrorGUI()
self.errorDialogue.hide()
self.loadKeyMapping()
self.saveKeyMapping()
self.buildMainGUI()
self.buildBindingGUI()
self.buildConflictGUI()
self.buildProfileSaveGUI()
self.conflictDialogue.hide()
self.profileSaveDialogue.hide()
self.bindingDialogue.hide()
self.bindingDialogueVisible = False
self.lastKeyInterception = None
self.lastKeyInterceptionDeviceType = None
self.lastKeyInterceptionValue = 0
# This works around the potential issue of
# the dialogue's modal nature being overridden
# as a result of other GUI items being created after it.
if not self.errorDialogue.isHidden():
self.errorDialogue.show()
self.updateTask = taskMgr.add(self.update, "update keymapper")
"""
UI-related methods. Override as called for!
"""
def getBindingName(self, binding, direction):
"""Get the display-name for a given binding, or lack thereof."""
result = "<none set>"
if binding is not None:
result = self.keyMap.getMappedButtonLabel(binding)
if len(result) == 0:
result = binding
if direction == 1:
result += " +"
elif direction == -1:
result += " -"
return result
def getButtonName(self, keyDescription):
"""Get the display-name for a given control"""
return keyDescription
def buildErrorGUI(self):
"""Construct the UI that provides error feedback.
This may be overridden to change said UI."""
self.errorDialogue = DirectDialog(frameSize = (-0.8, 0.8, -0.4, 0.4),
frameColor = (0.2, 0.3, 0.7, 1),
fadeScreen = 0.4,
image = None,
geom = None,
relief = DGG.FLAT)
self.errorTitle = DirectLabel(text = "Error!",
scale = 0.09,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.errorDialogue,
pos = (0, 0, 0.3),
relief = None)
self.errorLabel = DirectLabel(text = "<Error text here>",
scale = 0.07,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.errorDialogue,
pos = (0, 0, 0.1),
relief = None)
self.errorDoneBtn = DirectButton(text = "Close", command = self.hideErrorDialogue,
scale = 0.05,
text_align = TextNode.ACenter,
pos = (0, 0, -0.35),
parent = self.errorDialogue,
text_bg = (0.1, 0.8, 0.2, 1))
def buildMainGUI(self):
"""Construct the GUI.
This may be overridden for large-scale
changes to the user-interface of a
KeyMapper subclass."""
self.buildListGUI()
self.buildProfileGUI()
def buildProfileGUI(self):
"""Construct the GUI used to select mapping profiles
This may be overridden to change how that is handled."""
frameBounds = self.list["frameSize"]
self.profileMenu = DirectOptionMenu(
parent = self.guiRoot,
scale = self.buttonSize,
pos = (0, 0, frameBounds[2] - self.buttonSize*2.0),
relief = DGG.RAISED,
frameSize = (-5, 5, -0.7, 1),
text_align = TextNode.ACenter,
command = self.loadProfile,
items = list(self.profileDict.keys()))
self.profileMenu["text"] = "Load profile..."
self.profileMenu["textMayChange"] = 0
self.profileAddBtn = DirectButton(text = "Add new",
command = self.addNewProfile,
scale = self.buttonSize,
text_align = TextNode.ACenter,
pos = (0.45, 0, frameBounds[2] - self.buttonSize*2.0),
frameSize = (-3, 3, -0.7, 1),
parent = self.guiRoot)
def fillProfileList(self):
"""
Set the contents of the profile-list, based on the profiles
previously detected.
If "buildProfileGUI" has been overridden, and no longer uses
a DirectOptionMenu (or sub-class thereof), overriding this
may be called for.
"""
self.profileMenu["items"] = list(self.profileDict.keys())
def buildProfileSaveGUI(self):
"""Construct the GUI used to enter a name for a new profile
This may be overridden to change how that is handled."""
self.profileSaveDialogue = DirectDialog(frameSize = (-0.7, 0.7, -0.2, 0.4),
frameColor = (0.2, 0.3, 0.7, 1),
fadeScreen = 0.4,
image = None,
geom = None,
relief = DGG.FLAT)
self.profileSaveDialogue["frameSize"] = (-0.8, 0.8, -0.1, 0.3)
self.profileSaveTitle = DirectLabel(text = "Enter a name for this profile:",
scale = 0.09,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.profileSaveDialogue,
pos = (0, 0, 0.175),
relief = None)
self.profileSaveEntry = DirectEntry(parent = self.profileSaveDialogue,
pos = (0, 0, 0),
text_align = TextNode.ACenter,
width = 20,
command = self.saveNewProfile,
scale = 0.07)
def buildBindingGUI(self):
"""Build the interface that asks for a new key-binding.
This may be overridden to change said interface.
NB! If you override this, check whether you want to override
the method 'setBindingDescription'!"""
self.bindingDialogue = DirectDialog(frameSize = (-0.7, 0.7, -0.2, 0.4),
frameColor = (0.2, 0.3, 0.7, 1),
fadeScreen = 0.4,
image = None,
geom = None,
relief = DGG.FLAT)
self.bindingDialogue["frameSize"] = (-0.7, 0.7, -0.2, 0.4)
self.bindingTitle = DirectLabel(text = "Press a key to bind to:",
scale = 0.09,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.bindingDialogue,
pos = (0, 0, 0.225),
relief = None)
self.bindingDescriptionKey = DirectLabel(text = "Unused",
scale = 0.07,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.bindingDialogue,
pos = (0, 0, 0.055),
relief = None)
self.bindingDescriptionCurrent = DirectLabel(text = "Unused",
scale = 0.05,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.bindingDialogue,
pos = (0, 0, -0.075),
relief = None)
def setBindingDescription(self, keyDescription, currentBinding, axisDirection):
"""Update the binding GUI to reflect the binding being handled.
Params: keyDescription -- The key being bound.
currentBiding -- The binding being used at the moment."""
self.bindingDescriptionKey["text"] = keyDescription
self.bindingDescriptionCurrent["text"] = "(Currently: " + self.getBindingName(currentBinding, axisDirection) + ")"
self.bindingDescriptionKey.setText()
self.bindingDescriptionKey.resetFrameSize()
self.bindingDescriptionCurrent.setText()
self.bindingDescriptionCurrent.resetFrameSize()
def buildConflictGUI(self):
"""Build the interface that informs the user of a binding conflict,
and which asks how to proceed.
This may be overridden to change said interface.
NB! If you override this, check whether you want to override
the method 'setConflictText'!"""
self.conflictDialogue = DirectDialog(frameSize = (-0.9, 0.9, -0.25, 0.45),
frameColor = (0.2, 0.4, 0.75, 1),
fadeScreen = 0.4,
image = None,
geom = None,
relief = DGG.FLAT)
self.conflictDialogue["frameSize"] = (-0.9, 0.9, -0.25, 0.45)
self.conflictTitle = DirectLabel(text = "Warning!",
scale = 0.1,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.conflictDialogue,
pos = (0, 0, 0.3),
relief = None)
self.conflictLabel = DirectLabel(text = "Unused",
scale = 0.05,
text_align = TextNode.ACenter,
text_fg = (1, 1, 1, 1),
parent = self.conflictDialogue,
pos = (0, 0, 0.15),
relief = None)
self.conflictContinueBtn = DirectButton(text = "Continue", command = self.conflictResolutionContinue,
scale = 0.05,
text_align = TextNode.ACenter,
pos = (0.25, 0, -0.2),
parent = self.conflictDialogue,
text_bg = (0.1, 0.8, 0.2, 1))
self.conflictCancelBtn = DirectButton(text = "Cancel", command = self.conflictResolutionCancel,
scale = 0.05,
text_align = TextNode.ACenter,
pos = (-0.25, 0, -0.2),
parent = self.conflictDialogue,
text_bg = (0.1, 0.8, 0.2, 1))
def setConflictText(self, lastKeyInterception, conflictingKey):
"""Update the conflict GUI to reflect the conflict being handled.
Params: lastKeyInterception -- The attempted binding that resulted in a conflict
conflictingKey -- The control to which that binding is already bound."""
self.conflictLabel["text"] = "The key \"" + lastKeyInterception + "\" is already bound to \"" + \
conflictingKey + "\"\n\n" + "Would you like to continue anyway\n(rendering \"" + \
conflictingKey + "\" unbound), or \ncancel and choose a new key?"
def buildListGUI(self):
"""Build the main representation of the current bindings.
This may be overridden to change how a subclass of KeyMapper
displays its key-bindings"""
self.buildList()
index = 0
for keyDescription in self.keyOrder:
bindingEntry = self.keyBindings[keyDescription]
direction = 0
if bindingEntry.binding is not None:
if bindingEntry.binding.lower().startswith("axis."):
for axisData in self.axesInUse:
if axisData.keyDescriptionPositive == keyDescription:
direction = 1
elif axisData.keyDescriptionNegative == keyDescription:
direction = -1
btnWrapper = self.buildButton(keyDescription, bindingEntry, direction, self.getNewBinding, [keyDescription])
z = -(index)*self.buttonSpacing - self.firstButtonTopPadding
btnWrapper.reparentTo(self.list.getCanvas())
btnWrapper.setZ(z)
self.buttonList.append([keyDescription, btnWrapper, z, self.getNewBinding])
index += 1
def buildButton(self, keyDescription, bindingEntry, axisDirection, btnCommand, btnExtraArgs = None):
"""Construct a button that displays a key-binding and
allows the user to change that binding.
Params: keyDescription -- The key to be bound
bindingEntry -- The key's entry in self.keyBindings
axisDirection -- If this is an axis, is it positive or negative?
A value of 0 indicates no direction, or a non-axis.
btnCommand -- The command executed when the button is pressed
btnExtraArgs -- Any additional arguments to be sent to the above command
This may be overridden to change how a KeyMapper subclass
presents these elements."""
btn = DirectButton(text = keyDescription, command = btnCommand,
scale = self.buttonSize,
frameSize = (0.5, 20, -0.7, 1),
text_align = TextNode.ALeft,
text_pos = (1, 0, 0),
extraArgs = btnExtraArgs)
label = DirectLabel(text = self.getBindingName(bindingEntry.binding, axisDirection), parent = btn,
scale = 1,
text_align = TextNode.ARight,
relief = None,
pos = (17, 0, 0))
btnWrapper = BasicKeyBindingButtonWrapper(btn, label)
return btnWrapper
def buildList(self):
"""Construct the list-box in which the binding buttons
are presented.
This may be overridden by a KeyMapper subclass
to change how this element is presented."""
height = self.buttonSpacing*(self.listLength) + self.firstButtonTopPadding*2.1
self.list = DirectScrolledFrame(pos = (0, 0, 0),
color = (0.2, 0.2, 0.2, 1),
text_bg = (1, 1, 1, 1),
relief = DGG.SUNKEN,
frameSize = (-0.7, 0.7, -height*0.5, height*0.5),
parent = self.guiRoot)
self.list["canvasSize"] = (0, 0.5, -(len(self.keyBindings)-1)*self.buttonSpacing - self.firstButtonTopPadding*2.1 + 0.02, 0)
def showErrorDialogue(self, e):
"""Show a dialogue for a given error
Params: e -- The error in question"""
self.errorDialogue.show()
self.errorLabel["text"] = str(e)
def showBindingDialogue(self, keyDescription):
"""Display the dialogue that prompts the user for a new
key-binding.
Params: keyDecription -- The key to be bound"""
self.lastKeyInterception = None
self.lastKeyInterceptionDeviceType = None
self.lastKeyInterceptionValue = 0
direction = self.getAxisDirectionForKey(keyDescription)
self.setBindingDescription(keyDescription, self.keyBindings[keyDescription].binding, direction)
self.bindingDialogue.show()
self.bindingDialogueVisible = True
self.deviceAxisTestValues = {}
self.setEvents()
def hideBindingDialogue(self):
"""Hide the binding dialogue."""
self.bindingDialogue.hide()
self.bindingDialogueVisible = False
self.lastKeyInterception = None
self.lastKeyInterceptionDeviceType = None
self.lastKeyInterceptionValue = 0
self.clearEvents()
def hideProfileSaveDialogue(self):
"""Hide the profile-save dialogue"""
self.profileSaveDialogue.hide()
def hideErrorDialogue(self):
"""Hide the error dialogue"""
self.errorDialogue.hide()
"""
Tweaks and convenience-functions:
"""
def setDeadZoneForAllAxes(self, deadZone):
"""Apply the same dead-zone value to all currently-used axes,
and set the default dead-zone value to this new value.
Params: deadZone -- The new value to apply"""
for axisData in self.axesInUse:
axisData.deadZone = deadZone
self.deadZoneDefaultValue = deadZone
def setDeadZoneForAxis(self, axisIndex, deadZone):
"""Apply a new dead-zone value to an axis
Params: axisIndex -- The index of the axis-entry in the "axesInUse" list
deadZone -- The new value to apply"""
self.axesInUse[axisIndex].deadZone = deadZone
def findAxisAndSetDeadZone(self, axisName, deviceType, deadZone):
"""Apply a new dead-zone value to an axis
Params: axisName -- The description of the axis in question, as
taken from Panda's "InputDevice.Axis" enum and converted to a string
deviceType -- The type of device expected to be associated with the axis in question
deadZone -- The new value to apply"""
for axisData in self.axesInUse:
if axisData.axis == axisName and \
(axisData.deviceTypeNegative == deviceType or axisData.deviceTypePositive == deviceType):
axisData.deadZone = deadZone
def keyIsHeld(self, keyID):
"""Convenience function. Determine whether a key is being held"""
return abs(self.keys[keyID]) > 0.5
"""""
INTERNAL METHODS:
"""""
def connectController(self, controller):
"""A callback method that is called when a controller is connected
Params: controller -- The device that was connected"""
deviceTypeToAdd = controller.device_class
deviceTypeToAddString = self.getDeviceTypeString(deviceTypeToAdd)
for keyBinding in self.keyBindings.values():
if keyBinding.deviceType == deviceTypeToAddString:
self.addUsedDevice(deviceTypeToAdd)
if self.bindingDialogueVisible:
self.setupEventsForDevice(controller)
else:
if self.controllerNotificationCallback is not None:
used = False
for keyBinding in self.keyBindings.values():
if keyBinding.deviceType == deviceTypeToAddString:
used = True
self.controllerNotificationCallback(controller, used)
def disconnectController(self, controller):
"""A callback method that is called when a controller is removed
Params: controller -- The device that was removed"""
if self.bindingDialogueVisible:
self.clearEventsForDevice(controller)
if controller in self.devicesInUse:
self.removeUsedDevice(controller.device_class)
def addUsedDevice(self, deviceTypeToAdd):
"""Called when a device is to be added to the list of devices in use
Params: deviceTypeToAdd -- The type device that was connected"""
if not isinstance(deviceTypeToAdd, InputDevice.DeviceClass):
deviceTypeToAdd = eval("InputDevice.DeviceClass." + deviceTypeToAdd)
devices = base.devices.getDevices(deviceTypeToAdd)
for device in self.devicesInUse.keys():
if device.device_class == deviceTypeToAdd:
return device
if len(devices) > 0:
device = devices[0]
thrower = ButtonThrower(device.name)
dataNP = None
for prospectiveDataNP, otherThrower in self.dataNPList:
if prospectiveDataNP.node().device == device:
dataNP = prospectiveDataNP
if dataNP is None:
dataNP = base.dataRoot.attachNewNode(InputDeviceNode(device, device.name))
dataNP.attachNewNode(thrower)
self.devicesInUse[device] = (dataNP, thrower)
deviceTypeString = self.getDeviceTypeString(deviceTypeToAdd)
for axisData in self.axesInUse:
if axisData.deviceTypePositive == deviceTypeString:
axisData.devicePositive = device
if axisData.deviceTypeNegative == deviceTypeString:
axisData.deviceNegative = device
return device
return None
def removeUsedDevice(self, deviceTypeToRemove):
"""Called when a device is to be removed from the list of devices in use
Params: deviceTypeToRemove -- The type device that was connected"""
if not isinstance(deviceTypeToRemove, InputDevice.DeviceClass):
deviceTypeToRemove = eval("InputDevice.DeviceClass." + deviceTypeToRemove)
if deviceTypeToRemove is InputDevice.DeviceClass.keyboard or \
deviceTypeToRemove is InputDevice.DeviceClass.mouse:
return
deviceRemovalList = [(device, dataNP, thrower) for device, (dataNP, thrower) in self.devicesInUse.items() if device.device_class == deviceTypeToRemove]
for device, dataNP, thrower in deviceRemovalList:
for axisData in self.axesInUse:
if axisData.devicePositive == device or axisData.devicePositive is device:
axisData.devicePositive = None
if axisData.deviceNegative == device or axisData.deviceNegative is device:
axisData.deviceNegative = None
del self.devicesInUse[device]
self.dataNPList = [(otherDataNP, otherThrower) for (otherDataNP, otherThrower) in self.dataNPList if otherDataNP is not dataNP and otherDataNP != dataNP]
dataNP.removeNode()
def getDeviceTypeString(self, deviceTypeInput):
"""Get a string representing a given class of device
Params: deviceTypeInput -- The device-type in question, either
an "InputDevice.DeviceClass" or a string. """
if isinstance(deviceTypeInput, InputDevice.DeviceClass):
deviceTypeInputString = str(deviceTypeInput)
else:
deviceTypeInputString = deviceTypeInput
parts = deviceTypeInputString.split(".")
numParts = len(parts)
if numParts == 0:
return deviceTypeInputString
elif numParts == 1:
return deviceTypeInputString
else:
return parts[-1]
def getAxisDirectionForKey(self, keyDescription):
"""Figure out which axis-direction, if any, is associated with
a given control
Params: keyDescription -- The control in question"""
direction = 0
if keyDescription is not None:
if keyDescription in self.keyBindings:
binding = self.keyBindings[keyDescription].binding
if binding is not None:
if binding.lower().startswith("axis."):
for axisData in self.axesInUse:
if axisData.keyDescriptionPositive == keyDescription:
direction = 1
elif axisData.keyDescriptionNegative == keyDescription:
direction = -1
return direction