blob: be75d8a2f218d2632805f81dc04cd95f311f1b98 [file] [log] [blame]
Just van Rossum2e9e71f2001-11-02 19:09:34 +00001from Carbon import Evt, Qd, QuickDraw, Win
Just van Rossum40f9b7b1999-01-30 22:39:17 +00002import string
3from types import *
4import sys
5
Just van Rossum2e9e71f2001-11-02 19:09:34 +00006class WidgetsError(Exception): pass
Just van Rossum40f9b7b1999-01-30 22:39:17 +00007
8DEBUG = 0
9
Just van Rossum2e9e71f2001-11-02 19:09:34 +000010
Just van Rossum40f9b7b1999-01-30 22:39:17 +000011class Widget:
12
13 """Base class for all widgets."""
14
15 _selectable = 0
16
17 def __init__(self, possize):
18 self._widgets = []
19 self._widgetsdict = {}
20 self._possize = possize
21 self._bounds = None
22 self._visible = 1
23 self._enabled = 0
24 self._selected = 0
25 self._activated = 0
26 self._callback = None
27 self._parent = None
28 self._parentwindow = None
29 self._bindings = {}
30 self._backcolor = None
31
32 def show(self, onoff):
33 self._visible = onoff
34 for w in self._widgets:
35 w.show(onoff)
36 if self._parentwindow is not None and self._parentwindow.wid is not None:
37 self.SetPort()
38 if onoff:
39 self.draw()
40 else:
41 Qd.EraseRect(self._bounds)
42
43 def draw(self, visRgn = None):
44 if self._visible:
45 # draw your stuff here
46 pass
47
48 def getpossize(self):
49 return self._possize
50
51 def getbounds(self):
52 return self._bounds
53
54 def move(self, x, y = None):
55 """absolute move"""
56 if y == None:
57 x, y = x
58 if type(self._possize) <> TupleType:
59 raise WidgetsError, "can't move widget with bounds function"
60 l, t, r, b = self._possize
61 self.resize(x, y, r, b)
62
63 def rmove(self, x, y = None):
64 """relative move"""
65 if y == None:
66 x, y = x
67 if type(self._possize) <> TupleType:
68 raise WidgetsError, "can't move widget with bounds function"
69 l, t, r, b = self._possize
70 self.resize(l + x, t + y, r, b)
71
72 def resize(self, *args):
73 if len(args) == 1:
74 if type(args[0]) == FunctionType or type(args[0]) == MethodType:
75 self._possize = args[0]
76 else:
77 apply(self.resize, args[0])
78 elif len(args) == 2:
79 self._possize = (0, 0) + args
80 elif len(args) == 4:
81 self._possize = args
82 else:
83 raise TypeError, "wrong number of arguments"
84 self._calcbounds()
85
86 def open(self):
87 self._calcbounds()
88
89 def close(self):
90 del self._callback
91 del self._possize
92 del self._bindings
93 del self._parent
94 del self._parentwindow
95
96 def bind(self, key, callback):
97 """bind a key or an 'event' to a callback"""
98 if callback:
99 self._bindings[key] = callback
100 elif self._bindings.has_key(key):
101 del self._bindings[key]
102
103 def adjust(self, oldbounds):
104 self.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +0000105 self.GetWindow().InvalWindowRect(oldbounds)
106 self.GetWindow().InvalWindowRect(self._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000107
108 def _calcbounds(self):
109 # calculate absolute bounds relative to the window origin from our
110 # abstract _possize attribute, which is either a 4-tuple or a callable object
111 oldbounds = self._bounds
112 pl, pt, pr, pb = self._parent._bounds
113 if callable(self._possize):
114 # _possize is callable, let it figure it out by itself: it should return
115 # the bounds relative to our parent widget.
116 width = pr - pl
117 height = pb - pt
118 self._bounds = Qd.OffsetRect(self._possize(width, height), pl, pt)
119 else:
120 # _possize must be a 4-tuple. This is where the algorithm by Peter Kriens and
121 # Petr van Blokland kicks in. (*** Parts of this algorithm are applied for
122 # patents by Ericsson, Sweden ***)
123 l, t, r, b = self._possize
124 # depending on the values of l(eft), t(op), r(right) and b(ottom),
125 # they mean different things:
126 if l < -1:
127 # l is less than -1, this mean it measures from the *right* of it's parent
128 l = pr + l
129 else:
130 # l is -1 or greater, this mean it measures from the *left* of it's parent
131 l = pl + l
132 if t < -1:
133 # t is less than -1, this mean it measures from the *bottom* of it's parent
134 t = pb + t
135 else:
136 # t is -1 or greater, this mean it measures from the *top* of it's parent
137 t = pt + t
138 if r > 1:
139 # r is greater than 1, this means r is the *width* of the widget
140 r = l + r
141 else:
142 # r is less than 1, this means it measures from the *right* of it's parent
143 r = pr + r
144 if b > 1:
145 # b is greater than 1, this means b is the *height* of the widget
146 b = t + b
147 else:
148 # b is less than 1, this means it measures from the *bottom* of it's parent
149 b = pb + b
150 self._bounds = (l, t, r, b)
151 if oldbounds and oldbounds <> self._bounds:
152 self.adjust(oldbounds)
153 for w in self._widgets:
154 w._calcbounds()
155
156 def test(self, point):
157 if Qd.PtInRect(point, self._bounds):
158 return 1
159
160 def click(self, point, modifiers):
161 pass
162
163 def findwidget(self, point, onlyenabled = 1):
164 if self.test(point):
165 for w in self._widgets:
166 widget = w.findwidget(point)
167 if widget is not None:
168 return widget
169 if self._enabled or not onlyenabled:
170 return self
171
172 def forall(self, methodname, *args):
173 for w in self._widgets:
174 rv = apply(w.forall, (methodname,) + args)
175 if rv:
176 return rv
177 if self._bindings.has_key("<" + methodname + ">"):
178 callback = self._bindings["<" + methodname + ">"]
179 rv = apply(callback, args)
180 if rv:
181 return rv
182 if hasattr(self, methodname):
183 method = getattr(self, methodname)
184 return apply(method, args)
185
186 def forall_butself(self, methodname, *args):
187 for w in self._widgets:
188 rv = apply(w.forall, (methodname,) + args)
189 if rv:
190 return rv
191
192 def forall_frombottom(self, methodname, *args):
193 if self._bindings.has_key("<" + methodname + ">"):
194 callback = self._bindings["<" + methodname + ">"]
195 rv = apply(callback, args)
196 if rv:
197 return rv
198 if hasattr(self, methodname):
199 method = getattr(self, methodname)
200 rv = apply(method, args)
201 if rv:
202 return rv
203 for w in self._widgets:
204 rv = apply(w.forall_frombottom, (methodname,) + args)
205 if rv:
206 return rv
207
208 def _addwidget(self, key, widget):
209 if widget in self._widgets:
210 raise ValueError, "duplicate widget"
211 if self._widgetsdict.has_key(key):
212 self._removewidget(key)
213 self._widgets.append(widget)
214 self._widgetsdict[key] = widget
215 widget._parent = self
216 self._setparentwindow(widget)
217 if self._parentwindow and self._parentwindow.wid:
218 widget.forall_frombottom("open")
Jack Jansen73023402001-01-23 14:58:20 +0000219 self.GetWindow().InvalWindowRect(widget._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000220
221 def _setparentwindow(self, widget):
222 widget._parentwindow = self._parentwindow
223 for w in widget._widgets:
224 self._setparentwindow(w)
225
226 def _removewidget(self, key):
227 if not self._widgetsdict.has_key(key):
228 raise KeyError, "no widget with key " + `key`
229 widget = self._widgetsdict[key]
230 for k in widget._widgetsdict.keys():
231 widget._removewidget(k)
232 if self._parentwindow._currentwidget == widget:
233 widget.select(0)
234 self._parentwindow._currentwidget = None
235 self.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +0000236 self.GetWindow().InvalWindowRect(widget._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000237 widget.close()
238 del self._widgetsdict[key]
239 self._widgets.remove(widget)
240
241 def __setattr__(self, attr, value):
242 if type(value) == InstanceType and isinstance(value, Widget) and \
243 attr not in ("_currentwidget", "_lastrollover",
244 "_parent", "_parentwindow", "_defaultbutton"):
245 if hasattr(self, attr):
246 raise ValueError, "Can't replace existing attribute: " + attr
247 self._addwidget(attr, value)
248 self.__dict__[attr] = value
249
250 def __delattr__(self, attr):
251 if attr == "_widgetsdict":
252 raise AttributeError, "cannot delete attribute _widgetsdict"
253 if self._widgetsdict.has_key(attr):
254 self._removewidget(attr)
255 if self.__dict__.has_key(attr):
256 del self.__dict__[attr]
257 elif self.__dict__.has_key(attr):
258 del self.__dict__[attr]
259 else:
260 raise AttributeError, attr
261
262 def __setitem__(self, key, value):
263 self._addwidget(key, value)
264
265 def __getitem__(self, key):
266 if not self._widgetsdict.has_key(key):
267 raise KeyError, key
268 return self._widgetsdict[key]
269
270 def __delitem__(self, key):
271 self._removewidget(key)
272
273 def SetPort(self):
274 self._parentwindow.SetPort()
Jack Jansen73023402001-01-23 14:58:20 +0000275
276
277 def GetWindow(self):
278 return self._parentwindow.GetWindow()
279
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000280 def __del__(self):
281 if DEBUG:
282 print "%s instance deleted" % self.__class__.__name__
283
284 def _drawbounds(self):
285 Qd.FrameRect(self._bounds)
286
287
288class ClickableWidget(Widget):
289
290 """Base class for clickable widgets. (note: self._enabled must be true to receive click events.)"""
291
292 def click(self, point, modifiers):
293 pass
294
295 def enable(self, onoff):
296 self._enabled = onoff
297 self.SetPort()
298 self.draw()
299
300 def callback(self):
301 if self._callback:
302 return CallbackCall(self._callback, 1)
303
304
305class SelectableWidget(ClickableWidget):
306
307 """Base class for selectable widgets."""
308
309 _selectable = 1
310
311 def select(self, onoff, isclick = 0):
312 if onoff == self._selected:
313 return 1
314 if self._bindings.has_key("<select>"):
315 callback = self._bindings["<select>"]
316 if callback(onoff):
317 return 1
318 self._selected = onoff
319 if onoff:
320 if self._parentwindow._currentwidget is not None:
321 self._parentwindow._currentwidget.select(0)
322 self._parentwindow._currentwidget = self
323 else:
324 self._parentwindow._currentwidget = None
325
326 def key(self, char, event):
327 pass
328
329 def drawselframe(self, onoff):
330 if not self._parentwindow._hasselframes:
331 return
332 thickrect = Qd.InsetRect(self._bounds, -3, -3)
333 state = Qd.GetPenState()
334 Qd.PenSize(2, 2)
335 if onoff:
336 Qd.PenPat(Qd.qd.black)
337 else:
338 Qd.PenPat(Qd.qd.white)
339 Qd.FrameRect(thickrect)
340 Qd.SetPenState(state)
341
342 def adjust(self, oldbounds):
343 self.SetPort()
344 if self._selected:
Jack Jansen73023402001-01-23 14:58:20 +0000345 self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3))
346 self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000347 else:
Jack Jansen73023402001-01-23 14:58:20 +0000348 self.GetWindow().InvalWindowRect(oldbounds)
349 self.GetWindow().InvalWindowRect(self._bounds)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000350
351
352class _Line(Widget):
353
354 def __init__(self, possize, thickness = 1):
355 Widget.__init__(self, possize)
356 self._thickness = thickness
357
358 def open(self):
359 self._calcbounds()
360 self.SetPort()
361 self.draw()
362
363 def draw(self, visRgn = None):
364 if self._visible:
365 Qd.PaintRect(self._bounds)
366
367 def _drawbounds(self):
368 pass
369
370class HorizontalLine(_Line):
371
372 def _calcbounds(self):
373 Widget._calcbounds(self)
374 l, t, r, b = self._bounds
375 self._bounds = l, t, r, t + self._thickness
376
377class VerticalLine(_Line):
378
379 def _calcbounds(self):
380 Widget._calcbounds(self)
381 l, t, r, b = self._bounds
382 self._bounds = l, t, l + self._thickness, b
383
384
385class Frame(Widget):
386
387 def __init__(self, possize, pattern = Qd.qd.black, color = (0, 0, 0)):
388 Widget.__init__(self, possize)
389 self._framepattern = pattern
390 self._framecolor = color
391
392 def setcolor(self, color):
393 self._framecolor = color
394 self.SetPort()
395 self.draw()
396
397 def setpattern(self, pattern):
398 self._framepattern = pattern
399 self.SetPort()
400 self.draw()
401
402 def draw(self, visRgn = None):
403 if self._visible:
404 penstate = Qd.GetPenState()
405 Qd.PenPat(self._framepattern)
406 Qd.RGBForeColor(self._framecolor)
407 Qd.FrameRect(self._bounds)
408 Qd.RGBForeColor((0, 0, 0))
409 Qd.SetPenState(penstate)
410
411def _darkencolor((r, g, b)):
412 return 0.75 * r, 0.75 * g, 0.75 * b
413
414class BevelBox(Widget):
415
416 """'Platinum' beveled rectangle."""
417
418 def __init__(self, possize, color = (0xe000, 0xe000, 0xe000)):
419 Widget.__init__(self, possize)
420 self._color = color
421 self._darkercolor = _darkencolor(color)
422
423 def setcolor(self, color):
424 self._color = color
425 self.SetPort()
426 self.draw()
427
428 def draw(self, visRgn = None):
429 if self._visible:
430 l, t, r, b = Qd.InsetRect(self._bounds, 1, 1)
431 Qd.RGBForeColor(self._color)
432 Qd.PaintRect((l, t, r, b))
433 Qd.RGBForeColor(self._darkercolor)
434 Qd.MoveTo(l, b)
435 Qd.LineTo(r, b)
436 Qd.LineTo(r, t)
437 Qd.RGBForeColor((0, 0, 0))
438
439
440class Group(Widget):
441
442 """A container for subwidgets"""
443
444
445class HorizontalPanes(Widget):
446
447 """Panes, a.k.a. frames. Works a bit like a group. Devides the widget area into "panes",
448 which can be resized by the user by clicking and dragging between the subwidgets."""
449
450 _direction = 1
451
452 def __init__(self, possize, panesizes = None, gutter = 8):
453 """panesizes should be a tuple of numbers. The length of the tuple is the number of panes,
454 the items in the tuple are the relative sizes of these panes; these numbers should add up
455 to 1 (the total size of all panes)."""
Just van Rossum05a56b82001-10-31 12:55:07 +0000456 Widget.__init__(self, possize)
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000457 self._panesizes = panesizes
458 self._gutter = gutter
459 self._enabled = 1
460 self.setuppanes()
461
462 #def open(self):
463 # self.installbounds()
464 # ClickableWidget.open(self)
465
466 def _calcbounds(self):
467 # hmmm. It should not neccesary be override _calcbounds :-(
468 self.installbounds()
469 Widget._calcbounds(self)
470
471 def setuppanes(self):
472 panesizes = self._panesizes
473 total = 0
474 if panesizes is not None:
475 #if len(self._widgets) <> len(panesizes):
476 # raise TypeError, 'number of widgets does not match number of panes'
477 for panesize in panesizes:
478 if not 0 < panesize < 1:
479 raise TypeError, 'pane sizes must be between 0 and 1, not including.'
480 total = total + panesize
481 if round(total, 4) <> 1.0:
482 raise TypeError, 'pane sizes must add up to 1'
483 else:
484 # XXX does not work!
485 step = 1.0 / len(self._widgets)
486 panesizes = []
487 for i in range(len(self._widgets)):
488 panesizes.append(step)
489 current = 0
490 self._panesizes = []
491 self._gutters = []
492 for panesize in panesizes:
493 if current:
494 self._gutters.append(current)
Jack Jansen34d11f02000-03-07 23:40:13 +0000495 self._panesizes.append((current, current + panesize))
Just van Rossum40f9b7b1999-01-30 22:39:17 +0000496 current = current + panesize
497 self.makepanebounds()
498
499 def getpanesizes(self):
500 return map(lambda (fr, to): to-fr, self._panesizes)
501
502 boundstemplate = "lambda width, height: (0, height * %s + %d, width, height * %s + %d)"
503
504 def makepanebounds(self):
505 halfgutter = self._gutter / 2
506 self._panebounds = []
507 for i in range(len(self._panesizes)):
508 panestart, paneend = self._panesizes[i]
509 boundsstring = self.boundstemplate % (`panestart`, panestart and halfgutter,
510 `paneend`, (paneend <> 1.0) and -halfgutter)
511 self._panebounds.append(eval(boundsstring))
512
513 def installbounds(self):
514 #self.setuppanes()
515 for i in range(len(self._widgets)):
516 w = self._widgets[i]
517 w._possize = self._panebounds[i]
518 #if hasattr(w, "setuppanes"):
519 # w.setuppanes()
520 if hasattr(w, "installbounds"):
521 w.installbounds()
522
523 def rollover(self, point, onoff):
524 if onoff:
525 orgmouse = point[self._direction]
526 halfgutter = self._gutter / 2
527 l, t, r, b = self._bounds
528 if self._direction:
529 begin, end = t, b
530 else:
531 begin, end = l, r
532
533 i = self.findgutter(orgmouse, begin, end)
534 if i is None:
535 SetCursor("arrow")
536 else:
537 SetCursor(self._direction and 'vmover' or 'hmover')
538
539 def findgutter(self, orgmouse, begin, end):
540 tolerance = max(4, self._gutter) / 2
541 for i in range(len(self._gutters)):
542 pos = begin + (end - begin) * self._gutters[i]
543 if abs(orgmouse - pos) <= tolerance:
544 break
545 else:
546 return
547 return i
548
549 def click(self, point, modifiers):
550 # what a mess...
551 orgmouse = point[self._direction]
552 halfgutter = self._gutter / 2
553 l, t, r, b = self._bounds
554 if self._direction:
555 begin, end = t, b
556 else:
557 begin, end = l, r
558
559 i = self.findgutter(orgmouse, begin, end)
560 if i is None:
561 return
562
563 pos = orgpos = begin + (end - begin) * self._gutters[i] # init pos too, for fast click on border, bug done by Petr
564
565 minpos = self._panesizes[i][0]
566 maxpos = self._panesizes[i+1][1]
567 minpos = begin + (end - begin) * minpos + 64
568 maxpos = begin + (end - begin) * maxpos - 64
569 if minpos > orgpos and maxpos < orgpos:
570 return
571
572 #SetCursor("fist")
573 self.SetPort()
574 if self._direction:
575 rect = l, orgpos - 1, r, orgpos
576 else:
577 rect = orgpos - 1, t, orgpos, b
578
579 # track mouse --- XXX move to separate method?
580 Qd.PenMode(QuickDraw.srcXor)
581 Qd.PenPat(Qd.qd.gray)
582 Qd.PaintRect(rect)
583 lastpos = None
584 while Evt.Button():
585 pos = orgpos - orgmouse + Evt.GetMouse()[self._direction]
586 pos = max(pos, minpos)
587 pos = min(pos, maxpos)
588 if pos == lastpos:
589 continue
590 Qd.PenPat(Qd.qd.gray)
591 Qd.PaintRect(rect)
592 if self._direction:
593 rect = l, pos - 1, r, pos
594 else:
595 rect = pos - 1, t, pos, b
596 Qd.PenPat(Qd.qd.gray)
597 Qd.PaintRect(rect)
598 lastpos = pos
599 Qd.PaintRect(rect)
600 Qd.PenNormal()
601 SetCursor("watch")
602
603 newpos = (pos - begin) / float(end - begin)
604 self._gutters[i] = newpos
605 self._panesizes[i] = self._panesizes[i][0], newpos
606 self._panesizes[i+1] = newpos, self._panesizes[i+1][1]
607 self.makepanebounds()
608 self.installbounds()
609 self._calcbounds()
610
611
612class VerticalPanes(HorizontalPanes):
613 """see HorizontalPanes"""
614 _direction = 0
615 boundstemplate = "lambda width, height: (width * %s + %d, 0, width * %s + %d, height)"
616
617
618class ColorPicker(ClickableWidget):
619
620 """Color picker widget. Allows the user to choose a color."""
621
622 def __init__(self, possize, color = (0, 0, 0), callback = None):
623 ClickableWidget.__init__(self, possize)
624 self._color = color
625 self._callback = callback
626 self._enabled = 1
627
628 def click(self, point, modifiers):
629 if not self._enabled:
630 return
631 import ColorPicker
632 newcolor, ok = ColorPicker.GetColor("", self._color)
633 if ok:
634 self._color = newcolor
635 self.SetPort()
636 self.draw()
637 if self._callback:
638 return CallbackCall(self._callback, 0, self._color)
639
640 def set(self, color):
641 self._color = color
642 self.SetPort()
643 self.draw()
644
645 def get(self):
646 return self._color
647
648 def draw(self, visRgn=None):
649 if self._visible:
650 if not visRgn:
651 visRgn = self._parentwindow.wid.GetWindowPort().visRgn
652 Qd.PenPat(Qd.qd.gray)
653 rect = self._bounds
654 Qd.FrameRect(rect)
655 rect = Qd.InsetRect(rect, 3, 3)
656 Qd.PenNormal()
657 Qd.RGBForeColor(self._color)
658 Qd.PaintRect(rect)
659 Qd.RGBForeColor((0, 0, 0))
660
661
662# misc utils
663
664def CallbackCall(callback, mustfit, *args):
665 """internal helper routine for W"""
666 # XXX this function should die.
667 if type(callback) == FunctionType:
668 func = callback
669 maxargs = func.func_code.co_argcount
670 elif type(callback) == MethodType:
671 func = callback.im_func
672 maxargs = func.func_code.co_argcount - 1
673 else:
674 if callable(callback):
675 return apply(callback, args)
676 else:
677 raise TypeError, "uncallable callback object"
678
679 if func.func_defaults:
680 minargs = maxargs - len(func.func_defaults)
681 else:
682 minargs = maxargs
683 if minargs <= len(args) <= maxargs:
684 return apply(callback, args)
685 elif not mustfit and minargs == 0:
686 return callback()
687 else:
688 if mustfit:
689 raise TypeError, "callback accepts wrong number of arguments: " + `len(args)`
690 else:
691 raise TypeError, "callback accepts wrong number of arguments: 0 or " + `len(args)`
692
693
694def HasBaseClass(obj, class_):
695 try:
696 raise obj
697 except class_:
698 return 1
699 except:
700 pass
701 return 0
702
703
704_cursors = {
705 "watch" : Qd.GetCursor(QuickDraw.watchCursor).data,
706 "arrow" : Qd.qd.arrow,
707 "iBeam" : Qd.GetCursor(QuickDraw.iBeamCursor).data,
708 "cross" : Qd.GetCursor(QuickDraw.crossCursor).data,
709 "plus" : Qd.GetCursor(QuickDraw.plusCursor).data,
710 "hand" : Qd.GetCursor(468).data,
711 "fist" : Qd.GetCursor(469).data,
712 "hmover" : Qd.GetCursor(470).data,
713 "vmover" : Qd.GetCursor(471).data,
714 "zoomin" : Qd.GetCursor(472).data,
715 "zoomout" : Qd.GetCursor(473).data,
716 "zoom" : Qd.GetCursor(474).data,
717}
718
719def SetCursor(what):
720 """Set the cursorshape to any of these: 'arrow', 'cross', 'fist', 'hand', 'hmover', 'iBeam',
721 'plus', 'vmover', 'watch', 'zoom', 'zoomin', 'zoomout'."""
722 Qd.SetCursor(_cursors[what])