summaryrefslogtreecommitdiffstats
path: root/Mac/Lib/FrameWork.py
blob: 8663d1f699d522d3d4ce85186f24de3168d17c26 (plain)
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
"A sort of application framework for the Mac"

DEBUG=0

import MacOS
import traceback

from AE import *
from AppleEvents import *
from Ctl import *
from Controls import *
from Dlg import *
from Dialogs import *
from Evt import *
from Events import *
from Menu import *
from Menus import *
from Qd import *
from QuickDraw import *
#from Res import *
#from Resources import *
#from Snd import *
#from Sound import *
from Win import *
from Windows import *

import EasyDialogs

kHighLevelEvent = 23	# Don't know what header file this should come from
SCROLLBARWIDTH = 16		# Again, not a clue...


# Map event 'what' field to strings
eventname = {}
eventname[1] = 'mouseDown'
eventname[2] = 'mouseUp'
eventname[3] = 'keyDown'
eventname[4] = 'keyUp'
eventname[5] = 'autoKey'
eventname[6] = 'updateEvt'
eventname[7] = 'diskEvt'
eventname[8] = 'activateEvt'
eventname[15] = 'osEvt'
eventname[23] = 'kHighLevelEvent'

# Map part codes returned by WhichWindow() to strings
partname = {}
partname[0] = 'inDesk'
partname[1] = 'inMenuBar'
partname[2] = 'inSysWindow'
partname[3] = 'inContent'
partname[4] = 'inDrag'
partname[5] = 'inGrow'
partname[6] = 'inGoAway'
partname[7] = 'inZoomIn'
partname[8] = 'inZoomOut'

#
# The useable portion of the screen
#	## but what happens with multiple screens? jvr
screenbounds = qd.screenBits.bounds
screenbounds = screenbounds[0]+4, screenbounds[1]+4, \
	screenbounds[2]-4, screenbounds[3]-4
	
next_window_x = 16		# jvr
next_window_y = 44		# jvr

def windowbounds(width, height):
	"Return sensible window bounds"
	global next_window_x, next_window_y
	r, b = next_window_x+width, next_window_y+height
	if r > screenbounds[2]:
		next_window_x = 16
	if b > screenbounds[3]:
		next_window_y = 44
	l, t = next_window_x, next_window_y
	r, b = next_window_x+width, next_window_y+height
	next_window_x, next_window_y = next_window_x + 8, next_window_y + 20	# jvr
	return l, t, r, b


class Application:
	
	"Application framework -- your application should be a derived class"
	
	def __init__(self):
		self._windows = {}
		self.makemenubar()
	
	def makemenubar(self):
		self.menubar = MenuBar()
		AppleMenu(self.menubar, self.getabouttext(), self.do_about)
		self.makeusermenus()

	def makeusermenus(self):
		self.filemenu = m = Menu(self.menubar, "File")
		self._quititem = MenuItem(m, "Quit", "Q", self._quit)
	
	def _quit(self, *args):
		raise self
		
	def appendwindow(self, wid, window):
		self._windows[wid] = window
		
	def removewindow(self, wid):
		del self._windows[wid]
	
	def getabouttext(self):
		return "About %s..." % self.__class__.__name__
	
	def do_about(self, id, item, window, event):
		EasyDialogs.Message("Hello, world!" + "\015(%s)" % self.__class__.__name__)
	
	# The main event loop is broken up in several simple steps.
	# This is done so you can override each individual part,
	# if you have a need to do extra processing independent of the
	# event type.
	# Normally, however, you'd just define handlers for individual
	# events.
	# (XXX I'm not sure if using default parameter values is the right
	# way to define the mask and wait time passed to WaitNextEvent.)
	
	def mainloop(self, mask = everyEvent, wait = 0):
		saveyield = MacOS.EnableAppswitch(self.yield)
		try:
			while 1:
				try:
					self.do1event(mask, wait)
				except (Application, SystemExit):
					break
		finally:
			MacOS.EnableAppswitch(saveyield)
	
	yield = -1
	
	def do1event(self, mask = everyEvent, wait = 0):
		ok, event = self.getevent(mask, wait)
		if IsDialogEvent(event):
			if self.do_dialogevent(event):
				return
		if ok:
			self.dispatch(event)
		else:
			self.idle(event)
			
	def idle(self, event):
		pass
	
	def getevent(self, mask = everyEvent, wait = 0):
		ok, event = WaitNextEvent(mask, wait)
		return ok, event
			
	def dispatch(self, event):
		(what, message, when, where, modifiers) = event
		if eventname.has_key(what):
			name = "do_" + eventname[what]
		else:
			name = "do_%d" % what
		try:
			handler = getattr(self, name)
		except AttributeError:
			handler = self.do_unknownevent
		handler(event)
		
	def do_dialogevent(self, event):
		gotone, window, item = DialogSelect(event)
		if gotone:
			if self._windows.has_key(window):
				self._windows[window].do_itemhit(item, event)
			else:
				print 'Dialog event for unknown dialog'
			return 1
		return 0
	
	def do_mouseDown(self, event):
		(what, message, when, where, modifiers) = event
		partcode, wid = FindWindow(where)

		#
		# Find the correct name.
		#
		if partname.has_key(partcode):
			name = "do_" + partname[partcode]
		else:
			name = "do_%d" % partcode

		if wid == None:
			# No window, or a non-python window	
			try:
				handler = getattr(self, name)
			except AttributeError:
				# Not menubar or something, so assume someone
				# else's window
				MacOS.HandleEvent(event)
				return		
		elif self._windows.has_key(wid):
			# It is a window. Hand off to correct window.
			window = self._windows[wid]
			try:
				handler = getattr(window, name)
			except AttributeError:
				handler = self.do_unknownpartcode
		else:
			# It is a python-toolbox window, but not ours.
			handler = self.do_unknownwindow
		handler(partcode, wid, event)

	def do_inSysWindow(self, partcode, window, event):
		MacOS.HandleEvent(event)
	
	def do_inDesk(self, partcode, window, event):
		MacOS.HandleEvent(event)
	
	def do_inMenuBar(self, partcode, window, event):
		(what, message, when, where, modifiers) = event
		result = MenuSelect(where)
		id = (result>>16) & 0xffff	# Hi word
		item = result & 0xffff		# Lo word
		self.do_rawmenu(id, item, window, event)
	
	def do_rawmenu(self, id, item, window, event):
		try:
			self.do_menu(id, item, window, event)
		finally:
			HiliteMenu(0)
	
	def do_menu(self, id, item, window, event):
		self.menubar.dispatch(id, item, window, event)
	
	
	def do_unknownpartcode(self, partcode, window, event):
		(what, message, when, where, modifiers) = event
		if DEBUG: print "Mouse down at global:", where
		if DEBUG: print "\tUnknown part code:", partcode
		if DEBUG: print "\tEvent:", self.printevent(event)
		MacOS.HandleEvent(event)
		
	def do_unknownwindow(self, partcode, window, event):
		if DEBUG: print 'Unknown window:', window
		MacOS.HandleEvent(event)
	
	def do_keyDown(self, event):
		self.do_key(event)
	
	def do_autoKey(self, event):
		if not event[-1] & cmdKey:
			self.do_key(event)
	
	def do_key(self, event):
		(what, message, when, where, modifiers) = event
		c = chr(message & charCodeMask)
		if modifiers & cmdKey:
			if c == '.':
				raise self
			else:
				result = MenuKey(ord(c))
				id = (result>>16) & 0xffff	# Hi word
				item = result & 0xffff		# Lo word
				if id:
					self.do_rawmenu(id, item, None, event)
#				elif c == 'w':
#					w = FrontWindow()
#					if w:
#						self.do_close(w)
#					else:
#						if DEBUG: print 'Command-W without front window'
				else:
					if DEBUG: print "Command-" +`c`
		else:
			# See whether the front window wants it
			w = FrontWindow()
			if w and self._windows.has_key(w):
				window = self._windows[w]
				try:
					do_char = window.do_char
				except AttributeError:
					do_char = self.do_char
				do_char(c, event)
			# else it wasn't for us, sigh...
	
	def do_char(self, c, event):
		if DEBUG: print "Character", `c`
	
	def do_updateEvt(self, event):
		(what, message, when, where, modifiers) = event
		wid = WhichWindow(message)
		if wid and self._windows.has_key(wid):
			window = self._windows[wid]
			window.do_rawupdate(wid, event)
		else:
			MacOS.HandleEvent(event)
	
	def do_activateEvt(self, event):
		(what, message, when, where, modifiers) = event
		# XXXX Incorrect, should be fixed in suspendresume
		if type(message) == type(1):
			wid = WhichWindow(message)
		else:
			wid = message
		if wid and self._windows.has_key(wid):
			window = self._windows[wid]
			window.do_activate(modifiers & 1, event)
		else:
			MacOS.HandleEvent(event)
			
	def do_osEvt(self, event):
		(what, message, when, where, modifiers) = event
		which = (message >> 24) & 0xff
		if which == 1:	# suspend/resume
			self.do_suspendresume(event)
		else:
			if DEBUG:
				print 'unknown osEvt:',
				self.printevent(event)
				
	def do_suspendresume(self, event):
		# Is this a good idea???
		(what, message, when, where, modifiers) = event
		w = FrontWindow()
		if w:
			# XXXX Incorrect, should stuff windowptr into message field
			nev = (activateEvt, w, when, where, message&1)
			self.do_activateEvt(nev)

	def do_kHighLevelEvent(self, event):
		(what, message, when, where, modifiers) = event
		if DEBUG: 
			print "High Level Event:",
			self.printevent(event)
		try:
			AEProcessAppleEvent(event)
		except:
			print "AEProcessAppleEvent error:"
			traceback.print_exc()
	
	def do_unknownevent(self, event):
		if DEBUG:
			print "Unhandled event:",
			self.printevent(event)
	
	def printevent(self, event):
		(what, message, when, where, modifiers) = event
		nicewhat = `what`
		if eventname.has_key(what):
			nicewhat = eventname[what]
		print nicewhat,
		if what == kHighLevelEvent:
			h, v = where
			print `ostypecode(message)`, hex(when), `ostypecode(h | (v<<16))`,
		else:
			print hex(message), hex(when), where,
		print hex(modifiers)


class MenuBar:
	"""Represent a set of menus in a menu bar.
	
	Interface:
	
	- (constructor)
	- (destructor)
	- addmenu
	- addpopup (normally used internally)
	- dispatch (called from Application)
	"""
	
	nextid = 1	# Necessarily a class variable
	
	def getnextid(self):
		id = self.nextid
		self.nextid = id+1
		return id
	
	def __init__(self):
		ClearMenuBar()
		self.bar = GetMenuBar()
		self.menus = {}
	
	def addmenu(self, title, after = 0):
		id = self.getnextid()
		if DEBUG: print 'Newmenu', title, id # XXXX
		m = NewMenu(id, title)
		m.InsertMenu(after)
		DrawMenuBar()	# XXX appears slow! better do this when we're done. jvr
		return id, m
		
	def delmenu(self, id):
		if DEBUG: print 'Delmenu', id # XXXX
		DeleteMenu(id)
	
	def addpopup(self, title = ''):
		return self.addmenu(title, -1)
	
	def install(self):
		self.bar.SetMenuBar()
		DrawMenuBar()
	
	def dispatch(self, id, item, window, event):
		if self.menus.has_key(id):
			self.menus[id].dispatch(id, item, window, event)
		else:
			if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \
				(id, item, window, event)
	

# XXX Need a way to get menus as resources and bind them to callbacks

class Menu:
	"One menu."
	
	def __init__(self, bar, title, after=0):
		self.bar = bar
		self.id, self.menu = self.bar.addmenu(title, after)
		bar.menus[self.id] = self
		self.items = []
		
	def delete(self):
		self.bar.delmenu(self.id)
		del self.bar.menus[self.id]
		del self.bar
		del self.items
		del self.menu
		del self.id
	
	def additem(self, label, shortcut=None, callback=None, kind=None):
		self.menu.AppendMenu('x')		# add a dummy string
		self.items.append(label, shortcut, callback, kind)
		item = len(self.items)
		self.menu.SetMenuItemText(item, label)		# set the actual text
		if shortcut:
			self.menu.SetItemCmd(item, ord(shortcut))
		return item
	
	def addcheck(self, label, shortcut=None, callback=None):
		return self.additem(label, shortcut, callback, 'check')
	
	def addradio(self, label, shortcut=None, callback=None):
		return self.additem(label, shortcut, callback, 'radio')
	
	def addseparator(self):
		self.menu.AppendMenu('(-')
		self.items.append('', None, None, 'separator')
	
	def addsubmenu(self, label, title=''):
		sub = Menu(self.bar, title, -1)
		item = self.additem(label, '\x1B', None, 'submenu')
		self.menu.SetItemMark(item, sub.id)
		return sub
	
	def dispatch(self, id, item, window, event):
		title, shortcut, callback, type = self.items[item-1]
		if callback:
			callback(id, item, window, event)

	def enable(self, onoff):
		if onoff:
			self.menu.EnableItem(0)
		else:
			self.menu.DisableItem(0)

class MenuItem:
	def __init__(self, menu, title, shortcut=None, callback=None, kind=None):
		self.item = menu.additem(title, shortcut, callback)
		self.menu = menu
		
	def check(self, onoff):
		self.menu.menu.CheckItem(self.item, onoff)

	def enable(self, onoff):
		if onoff:
			self.menu.menu.EnableItem(self.item)
		else:
			self.menu.menu.DisableItem(self.item)
			
	def settext(self, text):
		self.menu.menu.SetMenuItemText(self.item, text)
		
	def setstyle(self, style):
		self.menu.menu.SetItemStyle(self.item, style)
		
	def seticon(self, icon):
		self.menu.menu.SetItemIcon(self.item, icon)
		
	def setcmd(self, cmd):
		self.menu.menu.SetItemCmd(self.item, cmd)
		
	def setmark(self, cmd):
		self.menu.menu.SetItemMark(self.item, cmd)
		

class RadioItem(MenuItem):
	def __init__(self, menu, title, shortcut=None, callback=None):
		MenuItem.__init__(self, menu, title, shortcut, callback, 'radio')

class CheckItem(MenuItem):
	def __init__(self, menu, title, shortcut=None, callback=None):
		MenuItem.__init__(self, menu, title, shortcut, callback, 'check')

def Separator(menu):
	menu.addseparator()

def SubMenu(menu, label, title=''):
	return menu.addsubmenu(label, title)


class AppleMenu(Menu):
	
	def __init__(self, bar, abouttext="About me...", aboutcallback=None):
		Menu.__init__(self, bar, "\024")
		self.additem(abouttext, None, aboutcallback)
		self.addseparator()
		self.menu.AppendResMenu('DRVR')
	
	def dispatch(self, id, item, window, event):
		if item == 1:
			Menu.dispatch(self, id, item, window, event)
		else:
			name = self.menu.GetMenuItemText(item)
			OpenDeskAcc(name)

class Window:
	"""A single window belonging to an application"""
	
	def __init__(self, parent):
		self.wid = None
		self.parent = parent
		
	def open(self, bounds=(40, 40, 400, 400), resid=None):
		if resid <> None:
			self.wid = GetNewWindow(resid, -1)
		else:
			self.wid = NewWindow(bounds, self.__class__.__name__, 1,
				8, -1, 1, 0)	# changed to proc id 8 to include zoom box. jvr
		self.do_postopen()
		
	def do_postopen(self):
		"""Tell our parent we exist"""
		self.parent.appendwindow(self.wid, self)
		
	def close(self):
		self.do_postclose()
			
	def do_postclose(self):
		self.parent.removewindow(self.wid)
		self.parent = None
		self.wid = None
		
	def SetPort(self):
		# Convinience method
		SetPort(self.wid)
	
	def do_inDrag(self, partcode, window, event):
		where = event[3]
		window.DragWindow(where, self.draglimit)
	
	draglimit = screenbounds
	
	def do_inGoAway(self, partcode, window, event):
		where = event[3]
		if window.TrackGoAway(where):
			self.close()
	
	def do_inZoom(self, partcode, window, event):
		(what, message, when, where, modifiers) = event
		if window.TrackBox(where, partcode):
			window.ZoomWindow(partcode, 1)
			rect = window.GetWindowUserState()				# so that zoom really works... jvr
			self.do_postresize(rect[2] - rect[0], rect[3] - rect[1], window)	# jvr
	
	def do_inZoomIn(self, partcode, window, event):
		SetPort(window) # !!!
		self.do_inZoom(partcode, window, event)
	
	def do_inZoomOut(self, partcode, window, event):
		SetPort(window) # !!!
		self.do_inZoom(partcode, window, event)
	
	def do_inGrow(self, partcode, window, event):
		(what, message, when, where, modifiers) = event
		result = window.GrowWindow(where, self.growlimit)
		if result:
			height = (result>>16) & 0xffff	# Hi word
			width = result & 0xffff		# Lo word
			self.do_resize(width, height, window)
	
	growlimit = (50, 50, screenbounds[2] - screenbounds[0], screenbounds[3] - screenbounds[1])	# jvr
	
	def do_resize(self, width, height, window):
		l, t, r, b = self.wid.GetWindowPort().portRect			# jvr, forGrowIcon
		self.SetPort()							# jvr
		InvalRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b))	# jvr
		window.SizeWindow(width, height, 1)		# changed updateFlag to true jvr
		self.do_postresize(width, height, window)
	
	def do_postresize(self, width, height, window):
		SetPort(window)
		InvalRect(window.GetWindowPort().portRect)
	
	def do_inContent(self, partcode, window, event):
		#
		# If we're not frontmost, select ourselves and wait for
		# the activate event.
		#
		if FrontWindow() <> window:
			window.SelectWindow()
			return
		# We are. Handle the event.
		(what, message, when, where, modifiers) = event
		SetPort(window)
		local = GlobalToLocal(where)
		self.do_contentclick(local, modifiers, event)
		
	def do_contentclick(self, local, modifiers, event):
		if DEBUG:
			print 'Click in contents at %s, modifiers %s'%(local, modifiers)
	
	def do_rawupdate(self, window, event):
		if DEBUG: print "raw update for", window
		SetPort(window)
		window.BeginUpdate()
		self.do_update(window, event)
		window.EndUpdate()
	
	def do_update(self, window, event):
		if DEBUG:
			import time
			for i in range(8):
				time.sleep(0.1)
				InvertRgn(window.GetWindowPort().visRgn)
			FillRgn(window.GetWindowPort().visRgn, qd.gray)
		else:
			EraseRgn(window.GetWindowPort().visRgn)
		
	def do_activate(self, activate, event):
		if DEBUG: print 'Activate %d for %s'%(activate, self.wid)
		
class ControlsWindow(Window):

	def do_rawupdate(self, window, event):
		if DEBUG: print "raw update for", window
		SetPort(window)
		window.BeginUpdate()
		self.do_update(window, event)
		#DrawControls(window)					# jvr
		UpdateControls(window, window.GetWindowPort().visRgn)	# jvr
		window.DrawGrowIcon()
		window.EndUpdate()
	
	def do_controlhit(self, window, control, pcode, event):
		if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode

	def do_inContent(self, partcode, window, event):
		if FrontWindow() <> window:
			window.SelectWindow()
			return
		(what, message, when, where, modifiers) = event
		SetPort(window)  # XXXX Needed?
		local = GlobalToLocal(where)
		ctltype, control = FindControl(local, window)
		if ctltype and control:
			pcode = control.TrackControl(local)
			if pcode:
				self.do_controlhit(window, control, pcode, event)
		else:
			if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \
				(local, window, ctltype, control)
			self.do_contentclick(local, modifiers, event)
			
class ScrolledWindow(ControlsWindow):
	def __init__(self, parent):
		self.barx = self.bary = None
		self.barx_enabled = self.bary_enabled = 1
		self.activated = 1
		ControlsWindow.__init__(self, parent)

	def scrollbars(self, wantx=1, wanty=1):
		SetPort(self.wid)
		self.barx = self.bary = None
		self.barx_enabled = self.bary_enabled = 1
		x0, y0, x1, y1 = self.wid.GetWindowPort().portRect
		vx, vy = self.getscrollbarvalues()
		if vx == None: self.barx_enabled, vx = 0, 0
		if vy == None: self.bary_enabled, vy = 0, 0
		if wantx:
			rect = x0-1, y1-(SCROLLBARWIDTH-1), x1-(SCROLLBARWIDTH-2), y1+1
			self.barx = NewControl(self.wid, rect, "", 1, vx, 0, 32767, 16, 0)
			if not self.barx_enabled: self.barx.HiliteControl(255)
##			InvalRect(rect)
		if wanty:
			rect = x1-(SCROLLBARWIDTH-1), y0-1, x1+1, y1-(SCROLLBARWIDTH-2)
			self.bary = NewControl(self.wid, rect, "", 1, vy, 0, 32767, 16, 0)
			if not self.bary_enabled: self.bary.HiliteControl(255)
##			InvalRect(rect)
			
	def do_postclose(self):
		self.barx = self.bary = None
		ControlsWindow.do_postclose(self)
		
	def do_activate(self, onoff, event):
		self.activated = onoff
		if onoff:
			if self.barx and self.barx_enabled:
				self.barx.ShowControl()	# jvr
			if self.bary and self.bary_enabled:
				self.bary.ShowControl()	# jvr
		else:
			if self.barx:
				self.barx.HideControl()	# jvr; An inactive window should have *hidden*
							# scrollbars, not just dimmed (no matter what
							# BBEdit does... look at the Finder)
			if self.bary:
				self.bary.HideControl()	# jvr
		self.wid.DrawGrowIcon()			# jvr
			
	def do_postresize(self, width, height, window):
		l, t, r, b = self.wid.GetWindowPort().portRect
		self.SetPort()
		if self.barx:
			self.barx.HideControl()		# jvr
			self.barx.MoveControl(l-1, b-(SCROLLBARWIDTH-1))
			self.barx.SizeControl((r-l)-(SCROLLBARWIDTH-3), SCROLLBARWIDTH)	# jvr
		if self.bary:
			self.bary.HideControl()		# jvr
			self.bary.MoveControl(r-(SCROLLBARWIDTH-1), t-1)
			self.bary.SizeControl(SCROLLBARWIDTH, (b-t)-(SCROLLBARWIDTH-3))	# jvr
		if self.barx:
			self.barx.ShowControl()		# jvr
			ValidRect((l, b - SCROLLBARWIDTH + 1, r - SCROLLBARWIDTH + 2, b))	# jvr
		if self.bary:
			self.bary.ShowControl()		# jvr
			ValidRect((r - SCROLLBARWIDTH + 1, t, r, b - SCROLLBARWIDTH + 2))	# jvr
		InvalRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b))	# jvr, growicon

	def do_controlhit(self, window, control, pcode, event):
		if control == self.barx:
			bar = self.barx
			which = 'x'
		elif control == self.bary:
			bar = self.bary
			which = 'y'
		else:
			return 0
		value = None
		if pcode == inUpButton:
			what = '-'
		elif pcode == inDownButton:
			what = '+'
		elif pcode == inPageUp:
			what = '--'
		elif pcode == inPageDown:
			what = '++'
		else:
			what = 'set'
			value = bar.GetControlValue()
		self.scrollbar_callback(which, what, value)
		self.updatescrollbars()
		return 1
		
	def updatescrollbars(self):
		SetPort(self.wid)
		vx, vy = self.getscrollbarvalues()
		if self.barx:
			if vx == None:
				self.barx.HiliteControl(255)
				self.barx_enabled = 0
			else:
				if not self.barx_enabled:
					self.barx_enabled = 1
					if self.activated:
						self.barx.HiliteControl(0)
				self.barx.SetControlValue(vx)
		if self.bary:
			if vy == None:
				self.bary.HiliteControl(255)
				self.bary_enabled = 0
			else:
				if not self.bary_enabled:
					self.bary_enabled = 1
					if self.activated:
						self.bary.HiliteControl(0)
				self.bary.SetControlValue(vy)
			
	# Auxiliary function: convert standard text/image/etc coordinate
	# to something palatable as getscrollbarvalues() return
	def scalebarvalue(self, absmin, absmax, curmin, curmax):
		if curmin <= absmin and curmax >= absmax:
			return None
		if curmin <= absmin:
			return 0
		if curmax >= absmax:
			return 32767
		perc = float(curmin-absmin)/float(absmax-absmin)
		return int(perc*32767)
			
	# To be overridden:
	
	def getscrollbarvalues(self):
		return 0, 0
		
	def scrollbar_callback(self, which, what, value):
		print 'scroll', which, what, value
	
class DialogWindow(Window):
	"""A modeless dialog window"""
	
	def open(self, resid):
		self.wid = GetNewDialog(resid, -1)
		self.do_postopen()
		
	def close(self):
		self.do_postclose()
		
	def do_itemhit(self, item, event):
		print 'Dialog %s, item %d hit'%(self.wid, item)
		
	def do_rawupdate(self, window, event):
		pass

def ostypecode(x):
	"Convert a long int to the 4-character code it really is"
	s = ''
	for i in range(4):
		x, c = divmod(x, 256)
		s = chr(c) + s
	return s


class TestApp(Application):
	
	"This class is used by the test() function"
	
	def makeusermenus(self):
		self.filemenu = m = Menu(self.menubar, "File")
		self.saveitem = MenuItem(m, "Save", "S", self.save)
		Separator(m)
		self.optionsmenu = mm = SubMenu(m, "Options")
		self.opt1 = CheckItem(mm, "Arguments")
		self.opt2 = CheckItem(mm, "Being hit on the head lessons")
		self.opt3 = CheckItem(mm, "Complaints")
		Separator(m)
		self.quititem = MenuItem(m, "Quit", "Q", self.quit)
	
	def save(self, *args):
		print "Save"
	
	def quit(self, *args):
		raise self


def test():
	"Test program"
	app = TestApp()
	app.mainloop()


if __name__ == '__main__':
	test()