forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectScrolledList.py
More file actions
530 lines (472 loc) · 20.1 KB
/
DirectScrolledList.py
File metadata and controls
530 lines (472 loc) · 20.1 KB
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
"""Contains the DirectScrolledList class.
See the :ref:`directscrolledlist` page in the programming manual for a more
in-depth explanation and an example of how to use this class.
"""
__all__ = ['DirectScrolledListItem', 'DirectScrolledList']
from panda3d.core import *
from direct.showbase import ShowBaseGlobal
from . import DirectGuiGlobals as DGG
from direct.directnotify import DirectNotifyGlobal
from direct.task.Task import Task
from .DirectFrame import *
from .DirectButton import *
class DirectScrolledListItem(DirectButton):
"""
While you are not required to use a DirectScrolledListItem for a
DirectScrolledList, doing so takes care of the highlighting and
unhighlighting of the list items.
"""
notify = DirectNotifyGlobal.directNotify.newCategory("DirectScrolledListItem")
def __init__(self, parent=None, **kw):
assert self.notify.debugStateCall(self)
self._parent = parent
if "command" in kw:
self.nextCommand = kw.get("command")
del kw["command"]
if "extraArgs" in kw:
self.nextCommandExtraArgs = kw.get("extraArgs")
del kw["extraArgs"]
optiondefs = (
('parent', self._parent, None),
('command', self.select, None),
)
# Merge keyword options with default options
self.defineoptions(kw, optiondefs)
DirectButton.__init__(self)
self.initialiseoptions(DirectScrolledListItem)
def select(self):
assert self.notify.debugStateCall(self)
self.nextCommand(*self.nextCommandExtraArgs)
self._parent.selectListItem(self)
class DirectScrolledList(DirectFrame):
notify = DirectNotifyGlobal.directNotify.newCategory("DirectScrolledList")
def __init__(self, parent = None, **kw):
assert self.notify.debugStateCall(self)
self.index = 0
self.__forceHeight = None
""" If one were to want a scrolledList that makes and adds its items
as needed, simply pass in an items list of strings (type 'str')
and when that item is needed, itemMakeFunction will be called
with the text, the index, and itemMakeExtraArgs. If itemMakeFunction
is not specified, it will create a DirectFrame with the text."""
# if 'items' is a list of strings, make a copy for our use
# so we can modify it without mangling the user's list
if 'items' in kw:
for item in kw['items']:
if not isinstance(item, str):
break
else:
# we get here if every item in 'items' is a string
# make a copy
kw['items'] = kw['items'][:]
self.nextItemID = 10
# Inherits from DirectFrame
optiondefs = (
# Define type of DirectGuiWidget
('items', [], None),
('itemsAlign', TextNode.ACenter, DGG.INITOPT),
('itemsWordwrap', None, DGG.INITOPT),
('command', None, None),
('extraArgs', [], None),
('itemMakeFunction', None, None),
('itemMakeExtraArgs', [], None),
('numItemsVisible', 1, self.setNumItemsVisible),
('scrollSpeed', 8, self.setScrollSpeed),
('forceHeight', None, self.setForceHeight),
('incButtonCallback', None, self.setIncButtonCallback),
('decButtonCallback', None, self.setDecButtonCallback),
)
# Merge keyword options with default options
self.defineoptions(kw, optiondefs)
# Initialize superclasses
DirectFrame.__init__(self, parent)
self.incButton = self.createcomponent("incButton", (), None,
DirectButton, (self,),
)
self.incButton.bind(DGG.B1PRESS, self.__incButtonDown)
self.incButton.bind(DGG.B1RELEASE, self.__buttonUp)
self.decButton = self.createcomponent("decButton", (), None,
DirectButton, (self,),
)
self.decButton.bind(DGG.B1PRESS, self.__decButtonDown)
self.decButton.bind(DGG.B1RELEASE, self.__buttonUp)
self.itemFrame = self.createcomponent("itemFrame", (), None,
DirectFrame, (self,),
)
for item in self["items"]:
if not isinstance(item, str):
item.reparentTo(self.itemFrame)
self.initialiseoptions(DirectScrolledList)
self.recordMaxHeight()
self.scrollTo(0)
def setForceHeight(self):
assert self.notify.debugStateCall(self)
self.__forceHeight = self["forceHeight"]
def recordMaxHeight(self):
assert self.notify.debugStateCall(self)
if self.__forceHeight is not None:
self.maxHeight = self.__forceHeight
else:
self.maxHeight = 0.0
for item in self["items"]:
if not isinstance(item, str):
self.maxHeight = max(self.maxHeight, item.getHeight())
def setScrollSpeed(self):
assert self.notify.debugStateCall(self)
# Items per second to move
self.__scrollSpeed = self["scrollSpeed"]
if self.__scrollSpeed <= 0:
self.__scrollSpeed = 1
def setNumItemsVisible(self):
assert self.notify.debugStateCall(self)
# Items per second to move
self.__numItemsVisible = self["numItemsVisible"]
def destroy(self):
assert self.notify.debugStateCall(self)
taskMgr.remove(self.taskName("scroll"))
if hasattr(self, "currentSelected"):
del self.currentSelected
if self.__incButtonCallback:
self.__incButtonCallback = None
if self.__decButtonCallback:
self.__decButtonCallback = None
self.incButton.destroy()
self.decButton.destroy()
DirectFrame.destroy(self)
def selectListItem(self, item):
assert self.notify.debugStateCall(self)
if hasattr(self, "currentSelected"):
self.currentSelected['state']=DGG.NORMAL
item['state']=DGG.DISABLED
self.currentSelected=item
def scrollBy(self, delta):
assert self.notify.debugStateCall(self)
#print "scrollBy[", delta,"]"
return self.scrollTo(self.index + delta)
def getItemIndexForItemID(self, itemID):
assert self.notify.debugStateCall(self)
#for i in range(len(self["items"])):
# print "buttontext[", i,"]", self["items"][i]["text"]
if len(self["items"]) == 0:
return 0
if isinstance(self["items"][0], str):
self.notify.warning("getItemIndexForItemID: cant find itemID for non-class list items!")
return 0
for i in range(len(self["items"])):
if(self["items"][i].itemID == itemID):
return i
self.notify.warning("getItemIndexForItemID: item not found!")
return 0
def scrollToItemID(self, itemID, centered=0):
assert self.notify.debugStateCall(self)
self.scrollTo(self.getItemIndexForItemID(itemID), centered)
def scrollTo(self, index, centered=0):
""" scrolls list so selected index is at top, or centered in box"""
assert self.notify.debugStateCall(self)
#print "scrollTo[", index,"] called, len(self[items])=", len(self["items"])," self[numItemsVisible]=", self["numItemsVisible"]
try:
self["numItemsVisible"]
except:
# RAU hack to kill 27633
self.notify.info('crash 27633 fixed!')
return
numItemsVisible = self["numItemsVisible"]
numItemsTotal = len(self["items"])
if(centered):
self.index = index - (numItemsVisible // 2)
else:
self.index = index
# Not enough items to even worry about scrolling,
# just disable the buttons and do nothing
if (len(self["items"]) <= numItemsVisible):
self.incButton['state'] = DGG.DISABLED
self.decButton['state'] = DGG.DISABLED
# Hmm.. just reset self.index to 0 and bail out
self.index = 0
ret = 0
else:
if (self.index <= 0):
self.index = 0
#print "at list start, ", len(self["items"])," ", self["numItemsVisible"]
self.decButton['state'] = DGG.DISABLED
self.incButton['state'] = DGG.NORMAL
ret = 0
elif (self.index >= (numItemsTotal - numItemsVisible)):
self.index = numItemsTotal - numItemsVisible
#print "at list end, ", len(self["items"])," ", self["numItemsVisible"]
self.incButton['state'] = DGG.DISABLED
self.decButton['state'] = DGG.NORMAL
ret = 0
else:
# deal with an edge condition - make sure any tasks are removed from the disabled arrows.
if (self.incButton['state'] == DGG.DISABLED) or (self.decButton['state'] == DGG.DISABLED):
#print "leaving list start/end, ", len(self["items"])," ", self["numItemsVisible"]
self.__buttonUp(0)
self.incButton['state'] = DGG.NORMAL
self.decButton['state'] = DGG.NORMAL
ret = 1
#print "self.index set to ", self.index
# Hide them all
for item in self["items"]:
if not isinstance(item, str):
item.hide()
# Then show the ones in range, and stack their positions
upperRange = min(numItemsTotal, numItemsVisible)
for i in range(self.index, self.index + upperRange):
item = self["items"][i]
#print "stacking buttontext[", i,"]", self["items"][i]["text"]
# If the item is a 'str', then it has not been created (scrolled list is 'as needed')
# Therefore, use the the function given to make it or just make it a frame
if isinstance(item, str):
if self['itemMakeFunction']:
# If there is a function to create the item
item = self['itemMakeFunction'](item, i, self['itemMakeExtraArgs'])
else:
item = DirectFrame(text = item,
text_align = self['itemsAlign'],
text_wordwrap = self['itemsWordwrap'],
relief = None)
#print "str stacking buttontext[", i,"]", self["items"][i]["text"]
# Then add the newly formed item back into the normal item list
self["items"][i] = item
item.reparentTo(self.itemFrame)
self.recordMaxHeight()
item.show()
item.setPos(0, 0, -(i-self.index) * self.maxHeight)
#print 'height bug tracker: i-%s idx-%s h-%s' % (i, self.index, self.maxHeight)
if self['command']:
# Pass any extra args to command
self['command'](*self['extraArgs'])
return ret
def makeAllItems(self):
assert self.notify.debugStateCall(self)
for i in range(len(self['items'])):
item = self["items"][i]
# If the item is a 'str', then it has not been created
# Therefore, use the the function given to make it or
# just make it a frame
#print "Making " + str(item)
if isinstance(item, str):
if self['itemMakeFunction']:
# If there is a function to create the item
item = self['itemMakeFunction'](item, i, self['itemMakeExtraArgs'])
else:
item = DirectFrame(text = item,
text_align = self['itemsAlign'],
text_wordwrap = self['itemsWordwrap'],
relief = None)
# Then add the newly formed item back into the normal item list
self["items"][i] = item
item.reparentTo(self.itemFrame)
self.recordMaxHeight()
def __scrollByTask(self, task):
assert self.notify.debugStateCall(self)
if ((task.time - task.prevTime) < task.delayTime):
return Task.cont
else:
ret = self.scrollBy(task.delta)
task.prevTime = task.time
if ret:
return Task.cont
else:
return Task.done
def __incButtonDown(self, event):
assert self.notify.debugStateCall(self)
task = Task(self.__scrollByTask)
task.setDelay(1.0 / self.__scrollSpeed)
task.prevTime = 0.0
task.delta = 1
taskName = self.taskName("scroll")
#print "incButtonDown: adding ", taskName
taskMgr.add(task, taskName)
self.scrollBy(task.delta)
messenger.send('wakeup')
if self.__incButtonCallback:
self.__incButtonCallback()
def __decButtonDown(self, event):
assert self.notify.debugStateCall(self)
task = Task(self.__scrollByTask)
task.setDelay(1.0 / self.__scrollSpeed)
task.prevTime = 0.0
task.delta = -1
taskName = self.taskName("scroll")
#print "decButtonDown: adding ", taskName
taskMgr.add(task, taskName)
self.scrollBy(task.delta)
messenger.send('wakeup')
if self.__decButtonCallback:
self.__decButtonCallback()
def __buttonUp(self, event):
assert self.notify.debugStateCall(self)
taskName = self.taskName("scroll")
#print "buttonUp: removing ", taskName
taskMgr.remove(taskName)
def addItem(self, item, refresh=1):
"""
Add this string and extraArg to the list
"""
assert self.notify.debugStateCall(self)
if not isinstance(item, str):
# cant add attribs to non-classes (like strings & ints)
item.itemID = self.nextItemID
self.nextItemID += 1
self['items'].append(item)
if not isinstance(item, str):
item.reparentTo(self.itemFrame)
if refresh:
self.refresh()
if not isinstance(item, str):
return item.itemID # to pass to scrollToItemID
def removeItem(self, item, refresh=1):
"""
Remove this item from the panel
"""
assert self.notify.debugStateCall(self)
#print "remove item called", item
#print "items list", self['items']
if item in self["items"]:
#print "removing item", item
if hasattr(self, "currentSelected") and self.currentSelected is item:
del self.currentSelected
self["items"].remove(item)
if not isinstance(item, str):
item.reparentTo(ShowBaseGlobal.hidden)
self.refresh()
return 1
else:
return 0
def removeAndDestroyItem(self, item, refresh = 1):
"""
Remove and destroy this item from the panel.
"""
assert self.notify.debugStateCall(self)
if item in self["items"]:
if hasattr(self, "currentSelected") and self.currentSelected is item:
del self.currentSelected
if (hasattr(item, 'destroy') and hasattr(item.destroy, '__call__')):
item.destroy()
self["items"].remove(item)
if not isinstance(item, str):
item.reparentTo(ShowBaseGlobal.hidden)
self.refresh()
return 1
else:
return 0
def removeAllItems(self, refresh=1):
"""
Remove this item from the panel
Warning 2006_10_19 tested only in the trolley metagame
"""
assert self.notify.debugStateCall(self)
retval = 0
#print "remove item called", item
#print "items list", self['items']
while len (self["items"]):
item = self['items'][0]
#print "removing item", item
if hasattr(self, "currentSelected") and self.currentSelected is item:
del self.currentSelected
self["items"].remove(item)
if not isinstance(item, str):
#RAU possible leak here, let's try to do the right thing
#item.reparentTo(ShowBaseGlobal.hidden)
item.removeNode()
retval = 1
if (refresh):
self.refresh()
return retval
def removeAndDestroyAllItems(self, refresh = 1):
"""
Remove and destroy all items from the panel.
Warning 2006_10_19 tested only in the trolley metagame
"""
assert self.notify.debugStateCall(self)
retval = 0
while len (self["items"]):
item = self['items'][0]
if hasattr(self, "currentSelected") and self.currentSelected is item:
del self.currentSelected
if (hasattr(item, 'destroy') and hasattr(item.destroy, '__call__')):
item.destroy()
self["items"].remove(item)
if not isinstance(item, str):
#RAU possible leak here, let's try to do the right thing
#item.reparentTo(ShowBaseGlobal.hidden)
item.removeNode()
retval = 1
if (refresh):
self.refresh()
return retval
def refresh(self):
"""
Update the list - useful when adding or deleting items
or changing properties that would affect the scrolling
"""
assert self.notify.debugStateCall(self)
self.recordMaxHeight()
#print "refresh called"
self.scrollTo(self.index)
def getSelectedIndex(self):
assert self.notify.debugStateCall(self)
return self.index
def getSelectedText(self):
assert self.notify.debugStateCall(self)
if isinstance(self['items'][self.index], str):
return self['items'][self.index]
else:
return self['items'][self.index]['text']
def setIncButtonCallback(self):
assert self.notify.debugStateCall(self)
self.__incButtonCallback = self["incButtonCallback"]
def setDecButtonCallback(self):
assert self.notify.debugStateCall(self)
self.__decButtonCallback = self["decButtonCallback"]
"""
from DirectGui import *
def makeButton(itemName, itemNum, *extraArgs):
def buttonCommand():
print itemName, itemNum
return DirectButton(text = itemName,
relief = DGG.RAISED,
frameSize = (-3.5, 3.5, -0.2, 0.8),
scale = 0.85,
command = buttonCommand)
s = scrollList = DirectScrolledList(
parent = aspect2d,
relief = None,
# Use the default dialog box image as the background
image = DGG.getDefaultDialogGeom(),
# Scale it to fit around everyting
image_scale = (0.7, 1, .8),
# Give it a label
text = "Scrolled List Example",
text_scale = 0.06,
text_align = TextNode.ACenter,
text_pos = (0, 0.3),
text_fg = (0, 0, 0, 1),
# inc and dec are DirectButtons
# They can contain a combination of text, geometry and images
# Just a simple text one for now
incButton_text = 'Increment',
incButton_relief = DGG.RAISED,
incButton_pos = (0.0, 0.0, -0.36),
incButton_scale = 0.1,
# Same for the decrement button
decButton_text = 'Decrement',
decButton_relief = DGG.RAISED,
decButton_pos = (0.0, 0.0, 0.175),
decButton_scale = 0.1,
# each item is a button with text on it
numItemsVisible = 4,
itemMakeFunction = makeButton,
items = ['Able', 'Baker', 'Charlie', 'Delta', 'Echo', 'Foxtrot',
'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima'],
# itemFrame is a DirectFrame
# Use it to scale up or down the items and to place it relative
# to eveything else
itemFrame_pos = (0, 0, 0.06),
itemFrame_scale = 0.1,
itemFrame_frameSize = (-3.1, 3.1, -3.3, 0.8),
itemFrame_relief = DGG.GROOVE,
)
"""