summaryrefslogtreecommitdiffstats
path: root/apps/samples/vrml/vrml-server.caching.scxml
blob: 2d935cd327bf9f939d3ea9c80eb12082bf4d1049 (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
<scxml datamodel="ecmascript" name="vrml">
	<script src="http://uscxml.tk.informatik.tu-darmstadt.de/scripts/dump.js" />
	<script src="http://uscxml.tk.informatik.tu-darmstadt.de/scripts/string.  .js" />
	<script src="http://uscxml.tk.informatik.tu-darmstadt.de/scripts/array.last.js" />
	<script>
		var wrls = {};        // information of the wrl, vrml files
		var models = {};      // information of the osgb files
		var processed = {};   // information about processed files
		
		var pathDelim = ':';  // we need to flatten directories - this will seperate them in filenames
		
		/** 
		 * This pattern matches the query string we use as part of generated image filenames
		 */
		var numPattern = '(-?[0-9]+\.?[0-9]*)';
		var formatPattern = new RegExp(
			'-(' + numPattern +            // pitch
			'_' + numPattern +             // roll
			'_' + numPattern +             // yaw
			'_' + numPattern +             // zoom
			'_' + numPattern +             // x
			'_' + numPattern +             // y
			'_' + numPattern +             // z
			'_' + numPattern +             // width
			'_' + numPattern +             // height
			'_(off|on)' +                  // autorotate
			')\\.\\w+$');      // end
		
		/**
		 * Transform a file we found into a processed or model struct
		 */
		function fileToStruct(file) {
			var struct = {};
			var formatMatch = formatPattern.exec(file.name);
			// is this a processed file?
			if (formatMatch &amp;&amp; formatMatch.length == 12) {
				struct.key = file.relDir.replace(/\//g, pathDelim).substr(1) + file.name.substr(0, file.name.length - formatMatch[0].length);
				struct.format = formatMatch[1] + '.' + file.extension;
				struct.pitch = parseFloat(formatMatch[2]);
				struct.roll = parseFloat(formatMatch[3]);
				struct.yaw = parseFloat(formatMatch[4]);
				struct.zoom = parseFloat(formatMatch[5]);
				struct.x = parseFloat(formatMatch[6]);
				struct.y = parseFloat(formatMatch[7]);
				struct.z = parseFloat(formatMatch[8]);
				struct.width = parseFloat(formatMatch[9]);
				struct.height = parseFloat(formatMatch[10]);
				struct.autorotate = parseFloat(formatMatch[11]);
			} else {
				struct.key = file.relDir.replace(/\//g, pathDelim).substr(1) + file.strippedName;
			}
			return struct;
		}
		
		/**
		 * Transform a http request into something to look up in the processed structure
		 */
		function reqToStruct(req) {
			var struct = {};
			
			var query = (('query' in req) ? req.query : {});
			
			struct.pitch =    (('pitch'  in query &amp;&amp; isNumber(query.pitch))  ? query.pitch  : 0);
			struct.roll =     (('roll'   in query &amp;&amp; isNumber(query.roll))   ? query.roll   : 0);
			struct.yaw =      (('yaw'    in query &amp;&amp; isNumber(query.yaw))    ? query.yaw    : 0);
			struct.zoom =     (('zoom'   in query &amp;&amp; isNumber(query.zoom))   ? query.zoom   : 1);
			struct.x =        (('x'      in query &amp;&amp; isNumber(query.x))      ? query.x      : 0);
			struct.y =        (('y'      in query &amp;&amp; isNumber(query.y))      ? query.y      : 0);
			struct.z =        (('z'      in query &amp;&amp; isNumber(query.z))      ? query.z      : 0);
			struct.width =    (('width'  in query &amp;&amp; isNumber(query.width))  ? query.width  : 640);
			struct.height =   (('height' in query &amp;&amp; isNumber(query.height)) ? query.height : 480);
			struct.autorotate = (('autorotate' in query &amp;&amp; (query.autorotate === 'on' || query.autorotate === 'off')) ? query.autorotate : 'on');

			var fileComp = req.pathComponent[req.pathComponent.length - 1];
			struct.file = fileComp.substr(0, fileComp.indexOf('.'));
			struct.ext = fileComp.substr(fileComp.indexOf('.') + 1);

			struct.key = _event.data.pathComponent.slice(1, _event.data.pathComponent.length - 1).join(pathDelim);
			if (struct.key.length > 0)
				struct.key += pathDelim;
			struct.key += struct.file;
			
			struct.format = 
				struct.pitch + '_' + 
				struct.roll + '_' + 
				struct.yaw + '_' + 
				struct.zoom + '_' + 
				struct.x + '_' + 
				struct.y + '_' + 
				struct.z + '_' + 
				struct.width + '_' + 
				struct.height + '_' + 
				struct.autorotate + '.' + 
				struct.ext;
			return struct;
		}

		function isSupportedFormat(extension) {
			if (extension === "gif")
				return true;
			if (extension === "jpg")
				return true;
			if (extension === "jpeg")
				return true;
			if (extension === "png")
				return true;
			if (extension === "tif")
				return true;
			if (extension === "tiff")
				return true;
			if (extension === "bmp")
				return true;
			return false;
		}

		// list all available models in a summary format for the topmost request
		function overviewList() {
			var struct = {};
			struct.models = {};
			for (key in models) {
				var model = models[key];
				var group = models[key].group
				var name = model.strippedName.split(pathDelim).last();
				var entry = assign(struct, ['models'].concat(group.substr(1).split('/')).concat(name), {});
				entry.url = 
					_ioprocessors['http'].location + model.relDir + model.strippedName.split(pathDelim).join('/') + '.png';
				entry.path = model.relDir + model.strippedName.split(pathDelim).join('/') + '.png';
			}
			return struct;
		}

		// check whether a given string represents a number	
		function isNumber(n) {
		  return !isNaN(parseFloat(n)) &amp;&amp; isFinite(n);
		}
		
		// allow to set deep keys in an object
		function assign(obj, path, value) {
			if (typeof path === 'string')
				path = path.split('.');
			if (!(path instanceof Array))
				return undefined;
				
			lastKeyIndex = path.length-1;
			for (var i = 0; i &lt; lastKeyIndex; ++ i) {
				key = path[i];
				if (key.length == 0)
				  continue;
				if (!(key in obj))
					obj[key] = {}
				obj = obj[key];
			}
			obj[path[lastKeyIndex]] = value;
			return obj[path[lastKeyIndex]];
		}
	</script>
	<state id="main">
		<!-- Stop processing if no vrml-path was given on command line -->
		<transition target="final" cond="_x['args']['vrml-path'] == undefined || _x['args']['vrml-path'].length == 0">
			<log expr="'No --vrml-path given'" />
		</transition>

		<!-- Stop processing if no tmp-path was given on command line -->
		<transition target="final" cond="_x['args']['tmp-path'] == undefined || _x['args']['tmp-path'].length == 0">
			<log expr="'No --tmp-path given'" />
		</transition>
				
		<!-- Stop processing if any error occurs -->
		<transition target="final" event="error">
			<log expr="'An error occured:'" />
			<script>dump(_event);</script>
		</transition>
						
		<!-- Start the directory monitor for generated files -->
		<invoke type="dirmon" id="dirmon.processed">
			<param name="dir" expr="_x['args']['tmp-path']" />
			<param name="recurse" expr="false" />
			<param name="reportExisting" expr="true" />
			<!-- Called for every file we found -->
			<finalize>
				<script>
					_event.fileStruct = fileToStruct(_event.data.file);
					
					if (_event.data.file.extension === "osgb") {
						// this is a binary 3D file converted from the wrls
						
						if (_event.name === "file.deleted") {
							delete models[_event.fileStruct.key];
							print("Removed a vanished osgb file at " + _event.fileStruct.key + "\n");
						} else {
							models[_event.fileStruct.key] = _event.data.file;
							models[_event.fileStruct.key].group = '/' + _event.data.file.name.split(pathDelim).slice(0,-1).join('/');
							print("Inserted a new osgb file at " + _event.fileStruct.key + "\n");
						}

					} else if ('format' in _event.fileStruct) {
						// this is a processed file generated for some request
						
						if (_event.name === "file.deleted") {
							delete processed[_event.fileStruct.key][_event.fileStruct.format];
							print("Removed a vanished processed file at " + _event.fileStruct.key + "\n");
						} else {
							if (!(_event.fileStruct.key in processed)) {
								processed[_event.fileStruct.key] = {}
							}
							processed[_event.fileStruct.key][_event.fileStruct.format] = _event.data.file;
							print("Inserted a new processed file at " + _event.fileStruct.key + "\n");
						}
					} else {
						print("Ignoring " + _event.data.file.name + "\n");
					}
				</script>
			</finalize>
		</invoke>
		
		<!-- Start the directory monitor for wrl files -->
		<invoke type="dirmon" id="dirmon.vrml">
			<param name="dir" expr="_x['args']['vrml-path']" />
			<param name="recurse" expr="true" />
			<param name="suffix" expr="'vrml wrl'" />
			<finalize>
				<script>
					_event.fileStruct = fileToStruct(_event.data.file);
					if (_event.name === "file.existing" || _event.name === "file.added") {
						wrls[_event.fileStruct.key] = _event.data.file;
						print("Inserting wrl " + _event.data.file.path + " from " +_event.data.file.relDir + " at " + _event.fileStruct.key + "\n");
					}
					if (_event.name === "file.deleted") {
						delete wrls[_event.fileStruct.key];
						print("Deleting wrl " + _event.data.file.path + " from " +_event.data.file.relDir + " at " + _event.fileStruct.key + "\n");
					}
				</script>
				<if cond="models &amp;&amp;
						(!(_event.fileStruct.key in models) ||
						wrls[_event.fileStruct.key].mtime > models[_event.fileStruct.key].mtime)
					">
					<send target="#_osgvonvert.osgb">
						<param name="source" expr="_event.data.file.path" />
						<param name="dest" expr="_x['args']['tmp-path'] + '/' + _event.fileStruct.key + '.osgb'" />
					</send>
				</if>
			</finalize>
		</invoke>
		
		<!-- Start the osgconvert invoker to transform 3D files -->
		<invoke type="osgconvert" id="osgvonvert.osgb">
			<param name="threads" expr="4" />
			<finalize>
				<script>
					//dump(_event);
				</script>
				<!-- <file operation="write" contentexpr="_event.data.content" sandbox="off" urlexpr="_event.data.dest" /> -->
			</finalize>
			<!--finalize>
				<script>
					// we could put the file into the osgbs or processed here, but we rely on the directory monitors for now
					print("Received " + _event.name + " regarding " + _event.data.dest + "\n");
				</script>
			</finalize-->
		</invoke>
		
		<!-- Start a nested SCXML interpreter to create movies from the images -->
		<!-- <invoke type="scxml" id="scxml.ffmpeg" src="ffmpeg-server.scxml" autoforward="true">
			<param name="modelDir" expr="_x['args']['tmp-path']" />
		</invoke> -->

		<!-- Idle here -->
		<state id="idle">
			<!--onentry>
				<log expr="_event" />
			</onentry -->
			<transition event="http.get" target="idle" cond="
					_event.data.pathComponent.length >= 2 &amp;&amp;
					_event.data.pathComponent[_event.data.pathComponent.length - 1].indexOf('.') !== -1">
				<!-- request for a specific format 
					http://host/vrml/relative/path/format?query=string -->
				<script>
					_event.fileStruct = reqToStruct(_event.data);
					_event.dest = _x['args']['tmp-path'] + '/' + _event['fileStruct'].key + '-' + _event['fileStruct'].format;
					print("Got a request for [" + _event['fileStruct'].key + '-' + _event['fileStruct'].format + "]\n");
//					dump(_event);
				</script>
				<if cond="_event['fileStruct'].key in models &amp;&amp; isSupportedFormat(_event['fileStruct'].ext)">
					<!-- There is such a file available as osgb -->
					<if cond="
							_event['fileStruct'].key in processed &amp;&amp; 
							_event['fileStruct'].format in processed[_event['fileStruct'].key]">
						<script>
							//print("Sending " + processed[_event['fileStruct'].key][_event['fileStruct'].format].path + "\n");
						</script>
						<respond status="200" to="_event.origin">
							<header name="Connection" value="close" />
							<header name="Access-Control-Allow-Origin" value="*" />
							<content fileexpr="processed[_event['fileStruct'].key][_event['fileStruct'].format].path" />
						</respond>
					<else />
						<if cond="_event.name.  ('postponed')">
							<!--
								A postponed event we couldn't answer
							-->
							<respond status="404" to="_event.origin">
								<header name="Connection" value="close" />
							</respond>
						<else />
							<script>
								print("Processing outfile " + _event['dest'] + " from model " + _event['file'] + "\n");
							</script>
							<send target="#_osgvonvert.osgb">
								<param name="source" expr="models[_event['fileStruct'].key].path" />
								<param name="dest" expr="_event['dest']" />
								<param name="pitch" expr="_event.fileStruct.pitch" />
								<param name="roll" expr="_event.fileStruct.roll" />
								<param name="yaw" expr="_event.fileStruct.yaw" />
								<param name="zoom" expr="_event.fileStruct.zoom" />
								<param name="x" expr="_event.fileStruct.x" />
								<param name="y" expr="_event.fileStruct.y" />
								<param name="z" expr="_event.fileStruct.z" />
								<param name="width" expr="_event.fileStruct.width" />
								<param name="height" expr="_event.fileStruct.height" />
								<param name="autorotate" expr="_event.fileStruct.autorotate" />
							</send>
							<!-- 
								Redeliver the event once the untilexpr is true. The untilexpr has to evaluate 
								into another valid expression that we will check again on stable configurations.
							-->
							<postpone
								untilexpr="
									'\'' + _event['fileStruct'].key + '\' in processed &amp;&amp; 
									\'' + _event['fileStruct'].format + '\'' + ' in processed[\'' + _event['fileStruct'].key + '\'] ||
									_event.name === \'convert.failure\' &amp;&amp; _event.data.dest === \'' + _event['dest'] + '\''
								"/>
						</if>
					</if>
				<else />
					<!-- There is no such model -->
					<respond status="404" to="_event.origin">
						<header name="Connection" value="close" />
					</respond>
				</if>
			</transition>

			<!-- 
				process request for JSON datastructures 
			-->
			<transition event="http.get" target="idle" cond="
					_event.data.pathComponent.length == 2 &amp;&amp; 
					_event.data.pathComponent[1] === 'models'">
				<script>//dump(_event)</script>
				<respond status="200" to="_event.origin">
					<header name="Connection" value="close" />
					<header name="Content-Type" value="application/json" />
					<header name="Access-Control-Allow-Origin" value="*" />
					<content expr="models" />
				</respond>
			</transition>

			<transition event="http.get" target="idle" cond="
					_event.data.pathComponent.length == 2 &amp;&amp; 
					_event.data.pathComponent[1] === 'processed'">
				<script>//dump(_event)</script>
				<respond status="200" to="_event.origin">
					<header name="Connection" value="close" />
					<header name="Content-Type" value="application/json" />
					<header name="Access-Control-Allow-Origin" value="*" />
					<content expr="processed" />
				</respond>
			</transition>

			<transition event="http.get" target="idle" cond="
					_event.data.pathComponent.length == 2 &amp;&amp; 
					_event.data.pathComponent[1] === 'wrls'">
				<script>//dump(_event)</script>
				<respond status="200" to="_event.origin">
					<header name="Connection" value="close" />
					<header name="Content-Type" value="application/json" />
					<header name="Access-Control-Allow-Origin" value="*" />
					<content expr="wrls" />
				</respond>
			</transition>

			<!-- request for topmost list of all files -->
			<transition event="http.get" target="idle" cond="
				_event.data.pathComponent.length == 1">
				<script>//dump(_event);</script>
				<respond status="200" to="_event.origin">
					<header name="Connection" value="close" />
					<header name="Content-Type" value="application/json" />
					<header name="Access-Control-Allow-Origin" value="*" />
					<content expr="overviewList()" />
				</respond>
			</transition>

			<!-- XHR CORS preflight response -->
			<transition event="http.options" target="idle">
				<script>//dump(_event);</script>
				<respond status="200" to="_event.origin">
					<header name="Access-Control-Allow-Origin" value="*" />
					<header name="Access-Control-Allow-Methods" value="GET, OPTIONS" />
					<header name="Access-Control-Allow-Headers" value="X-Requested-With" />
				</respond>
			</transition>

			<transition event="render.done" target="idle">
				<script>dump(_event);</script>
				<respond status="200" to="_event.data.context">
					<header name="Connection" value="close" />
					<header name="Content-Type" valueexpr="_event.data.mimetype" />
					<header name="Content-Disposition" valueexpr="'attachment; filename=' + _event.data.filename" />
					<content expr="_event.data.movie" />
				</respond>
			</transition>

		</state>
	</state>
	<state id="final" final="true" />
</scxml>
'>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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
/* 
 * tkMacScrollbar.c --
 *
 *	This file implements the Macintosh specific portion of the scrollbar
 *	widget.  The Macintosh scrollbar may also draw a windows grow
 *	region under certain cases.
 *
 * Copyright (c) 1996 by Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tkMacScrlbr.c,v 1.2 1998/09/14 18:23:39 stanton Exp $
 */

#include "tkScrollbar.h"
#include "tkMacInt.h"
#include <Controls.h>

/*
 * The following definitions should really be in MacOS
 * header files.  They are included here as this is the only
 * file that needs the declarations.
 */
typedef	pascal void (*ThumbActionFunc)(void);

#if GENERATINGCFM
typedef UniversalProcPtr ThumbActionUPP;
#else
typedef ThumbActionFunc ThumbActionUPP;
#endif

enum {
	uppThumbActionProcInfo = kPascalStackBased
};

#if GENERATINGCFM
#define NewThumbActionProc(userRoutine)		\
		(ThumbActionUPP) NewRoutineDescriptor((ProcPtr)(userRoutine), uppThumbActionProcInfo, GetCurrentArchitecture())
#else
#define NewThumbActionProc(userRoutine)		\
		((ThumbActionUPP) (userRoutine))
#endif

/*
 * Minimum slider length, in pixels (designed to make sure that the slider
 * is always easy to grab with the mouse).
 */

#define MIN_SLIDER_LENGTH	5

/*
 * Declaration of Windows specific scrollbar structure.
 */

typedef struct MacScrollbar {
    TkScrollbar info;		/* Generic scrollbar info. */
    ControlRef sbHandle;	/* Handle to the Scrollbar control struct. */
    int macFlags;		/* Various flags; see below. */
} MacScrollbar;

/*
 * Flag bits for scrollbars on the Mac:
 * 
 * ALREADY_DEAD:		Non-zero means this scrollbar has been
 *				destroyed, but has not been cleaned up.
 * IN_MODAL_LOOP:		Non-zero means this scrollbar is in the middle
 *				of a modal loop.
 * ACTIVE:			Non-zero means this window is currently
 *				active (in the foreground).
 * FLUSH_TOP:			Flush with top of Mac window.
 * FLUSH_BOTTOM:		Flush with bottom of Mac window.
 * FLUSH_RIGHT:			Flush with right of Mac window.
 * FLUSH_LEFT:			Flush with left of Mac window.
 * SCROLLBAR_GROW:		Non-zero means this window draws the grow
 *				region for the toplevel window.
 * AUTO_ADJUST:			Non-zero means we automatically adjust
 *				the size of the widget to align correctly
 *				along a Mac window.
 * DRAW_GROW:			Non-zero means we draw the grow region.
 */

#define ALREADY_DEAD		1
#define IN_MODAL_LOOP		2
#define ACTIVE			4
#define FLUSH_TOP		8
#define FLUSH_BOTTOM		16
#define FLUSH_RIGHT		32
#define FLUSH_LEFT		64
#define SCROLLBAR_GROW		128
#define AUTO_ADJUST		256
#define DRAW_GROW		512

/*
 * Globals uses locally in this file.
 */
static ControlActionUPP scrollActionProc = NULL; /* Pointer to func. */
static ThumbActionUPP thumbActionProc = NULL;    /* Pointer to func. */
static TkScrollbar *activeScrollPtr = NULL;        /* Non-null when in thumb */
						 /* proc. */
/*
 * Forward declarations for procedures defined later in this file:
 */

static pascal void	ScrollbarActionProc _ANSI_ARGS_((ControlRef theControl,
			    ControlPartCode partCode));
static int		ScrollbarBindProc _ANSI_ARGS_((ClientData clientData,
			    Tcl_Interp *interp, XEvent *eventPtr,
			    Tk_Window tkwin, KeySym keySym));
static void		ScrollbarEventProc _ANSI_ARGS_((
			    ClientData clientData, XEvent *eventPtr));
static pascal void	ThumbActionProc _ANSI_ARGS_((void));
static void		UpdateControlValues _ANSI_ARGS_((MacScrollbar *macScrollPtr));
		    
/*
 * The class procedure table for the scrollbar widget.
 */

TkClassProcs tkpScrollbarProcs = { 
    NULL,			/* createProc. */
    NULL,			/* geometryProc. */
    NULL			/* modalProc */
};

/*
 *----------------------------------------------------------------------
 *
 * TkpCreateScrollbar --
 *
 *	Allocate a new TkScrollbar structure.
 *
 * Results:
 *	Returns a newly allocated TkScrollbar structure.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

TkScrollbar *
TkpCreateScrollbar(
    Tk_Window tkwin)	/* New Tk Window. */
{
    MacScrollbar * macScrollPtr;
    TkWindow *winPtr = (TkWindow *)tkwin;
    
    if (scrollActionProc == NULL) {
	scrollActionProc = NewControlActionProc(ScrollbarActionProc);
	thumbActionProc = NewThumbActionProc(ThumbActionProc);
    }

    macScrollPtr = (MacScrollbar *) ckalloc(sizeof(MacScrollbar));
    macScrollPtr->sbHandle = NULL;
    macScrollPtr->macFlags = 0;

    Tk_CreateEventHandler(tkwin, ActivateMask|ExposureMask|
	    StructureNotifyMask|FocusChangeMask,
	    ScrollbarEventProc, (ClientData) macScrollPtr);

    if (!Tcl_GetAssocData(winPtr->mainPtr->interp, "TkScrollbar", NULL)) {
	Tcl_SetAssocData(winPtr->mainPtr->interp, "TkScrollbar", NULL,
		(ClientData)1);
	TkCreateBindingProcedure(winPtr->mainPtr->interp,
		winPtr->mainPtr->bindingTable,
		(ClientData)Tk_GetUid("Scrollbar"), "<ButtonPress>",
		ScrollbarBindProc, NULL, NULL);
    }

    return (TkScrollbar *) macScrollPtr;
}

/*
 *--------------------------------------------------------------
 *
 * TkpDisplayScrollbar --
 *
 *	This procedure redraws the contents of a scrollbar window.
 *	It is invoked as a do-when-idle handler, so it only runs
 *	when there's nothing else for the application to do.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information appears on the screen.
 *
 *--------------------------------------------------------------
 */

void
TkpDisplayScrollbar(
    ClientData clientData)	/* Information about window. */
{
    register TkScrollbar *scrollPtr = (TkScrollbar *) clientData;
    register MacScrollbar *macScrollPtr = (MacScrollbar *) clientData;
    register Tk_Window tkwin = scrollPtr->tkwin;
    
    MacDrawable *macDraw;
    CGrafPtr saveWorld;
    GDHandle saveDevice;
    GWorldPtr destPort;
    WindowRef windowRef;
    
    if ((scrollPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
	goto done;
    }

    /*
     * Draw the focus or any 3D relief we may have.
     */
    if (scrollPtr->highlightWidth != 0) {
	GC gc;

	if (scrollPtr->flags & GOT_FOCUS) {
	    gc = Tk_GCForColor(scrollPtr->highlightColorPtr,
		    Tk_WindowId(tkwin));
	} else {
	    gc = Tk_GCForColor(scrollPtr->highlightBgColorPtr,
		    Tk_WindowId(tkwin));
	}
	Tk_DrawFocusHighlight(tkwin, gc, scrollPtr->highlightWidth,
		Tk_WindowId(tkwin));
    }
    Tk_Draw3DRectangle(tkwin, Tk_WindowId(tkwin), scrollPtr->bgBorder,
	    scrollPtr->highlightWidth, scrollPtr->highlightWidth,
	    Tk_Width(tkwin) - 2*scrollPtr->highlightWidth,
	    Tk_Height(tkwin) - 2*scrollPtr->highlightWidth,
	    scrollPtr->borderWidth, scrollPtr->relief);

    /*
     * Set up port for drawing Macintosh control.
     */
    macDraw = (MacDrawable *) Tk_WindowId(tkwin);
    destPort = TkMacGetDrawablePort(Tk_WindowId(tkwin));
    GetGWorld(&saveWorld, &saveDevice);
    SetGWorld(destPort, NULL);
    TkMacSetUpClippingRgn(Tk_WindowId(tkwin));

    if (macScrollPtr->sbHandle == NULL) {
        Rect r;
        
        r.left = r.top = 0;
        r.right = r.bottom = 1;
	macScrollPtr->sbHandle = NewControl((WindowRef) destPort, &r, "\p",
		false, (short) 500, 0, 1000,
		scrollBarProc, (SInt32) scrollPtr);

	/*
	 * If we are foremost than make us active.
	 */
	if ((WindowPtr) destPort == FrontWindow()) {
	    macScrollPtr->macFlags |= ACTIVE;
	}
    }

    /*
     * Update the control values before we draw.
     */
    windowRef  = (**macScrollPtr->sbHandle).contrlOwner;    
    UpdateControlValues(macScrollPtr);
    
    if (macScrollPtr->macFlags & ACTIVE) {
	Draw1Control(macScrollPtr->sbHandle);
	if (macScrollPtr->macFlags & DRAW_GROW) {
	    DrawGrowIcon(windowRef);
	}
    } else {
	(**macScrollPtr->sbHandle).contrlHilite = 255;
	Draw1Control(macScrollPtr->sbHandle);
	if (macScrollPtr->macFlags & DRAW_GROW) {
	    DrawGrowIcon(windowRef);
	    Tk_Fill3DRectangle(tkwin, Tk_WindowId(tkwin), scrollPtr->bgBorder,
		Tk_Width(tkwin) - 13, Tk_Height(tkwin) - 13,
		Tk_Width(tkwin), Tk_Height(tkwin),
		0, TK_RELIEF_FLAT);
	}
    }
    
    SetGWorld(saveWorld, saveDevice);
     
    done:
    scrollPtr->flags &= ~REDRAW_PENDING;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpConfigureScrollbar --
 *
 *	This procedure is called after the generic code has finished
 *	processing configuration options, in order to configure
 *	platform specific options.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkpConfigureScrollbar(scrollPtr)
    register TkScrollbar *scrollPtr;	/* Information about widget;  may or
					 * may not already have values for
					 * some fields. */
{
}

/*
 *----------------------------------------------------------------------
 *
 * TkpComputeScrollbarGeometry --
 *
 *	After changes in a scrollbar's size or configuration, this
 *	procedure recomputes various geometry information used in
 *	displaying the scrollbar.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The scrollbar will be displayed differently.
 *
 *----------------------------------------------------------------------
 */

void
TkpComputeScrollbarGeometry(
    register TkScrollbar *scrollPtr)	/* Scrollbar whose geometry may
					 * have changed. */
{
    MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr;
    int width, fieldLength, adjust = 0;

    if (scrollPtr->highlightWidth < 0) {
	scrollPtr->highlightWidth = 0;
    }
    scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth;
    width = (scrollPtr->vertical) ? Tk_Width(scrollPtr->tkwin)
	    : Tk_Height(scrollPtr->tkwin);
    scrollPtr->arrowLength = width - 2*scrollPtr->inset + 1;
    fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin)
	    : Tk_Width(scrollPtr->tkwin))
	    - 2*(scrollPtr->arrowLength + scrollPtr->inset);
    if (fieldLength < 0) {
	fieldLength = 0;
    }
    scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction;
    scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction;

    /*
     * Adjust the slider so that some piece of it is always
     * displayed in the scrollbar and so that it has at least
     * a minimal width (so it can be grabbed with the mouse).
     */

    if (scrollPtr->sliderFirst > (fieldLength - 2*scrollPtr->borderWidth)) {
	scrollPtr->sliderFirst = fieldLength - 2*scrollPtr->borderWidth;
    }
    if (scrollPtr->sliderFirst < 0) {
	scrollPtr->sliderFirst = 0;
    }
    if (scrollPtr->sliderLast < (scrollPtr->sliderFirst
	    + MIN_SLIDER_LENGTH)) {
	scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH;
    }
    if (scrollPtr->sliderLast > fieldLength) {
	scrollPtr->sliderLast = fieldLength;
    }
    scrollPtr->sliderFirst += scrollPtr->arrowLength + scrollPtr->inset;
    scrollPtr->sliderLast += scrollPtr->arrowLength + scrollPtr->inset;

    /*
     * Register the desired geometry for the window (leave enough space
     * for the two arrows plus a minimum-size slider, plus border around
     * the whole window, if any).  Then arrange for the window to be
     * redisplayed.
     */

    if (scrollPtr->vertical) {
	if ((macScrollPtr->macFlags & AUTO_ADJUST) &&
		(macScrollPtr->macFlags & (FLUSH_RIGHT|FLUSH_LEFT))) {
	    adjust--;
	}
	Tk_GeometryRequest(scrollPtr->tkwin,
		scrollPtr->width + 2*scrollPtr->inset + adjust,
		2*(scrollPtr->arrowLength + scrollPtr->borderWidth
		+ scrollPtr->inset));
    } else {
	if ((macScrollPtr->macFlags & AUTO_ADJUST) &&
		(macScrollPtr->macFlags & (FLUSH_TOP|FLUSH_BOTTOM))) {
	    adjust--;
	}
	Tk_GeometryRequest(scrollPtr->tkwin,
		2*(scrollPtr->arrowLength + scrollPtr->borderWidth
		+ scrollPtr->inset), scrollPtr->width + 2*scrollPtr->inset + adjust);
    }
    Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset);
}

/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyScrollbar --
 *
 *	Free data structures associated with the scrollbar control.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkpDestroyScrollbar(
    TkScrollbar *scrollPtr)	/* Scrollbar to destroy. */
{
    MacScrollbar *macScrollPtr = (MacScrollbar *)scrollPtr;

    if (macScrollPtr->sbHandle != NULL) {
	if (!(macScrollPtr->macFlags & IN_MODAL_LOOP)) {
	    DisposeControl(macScrollPtr->sbHandle);
	    macScrollPtr->sbHandle = NULL;
	}
    }
    macScrollPtr->macFlags |= ALREADY_DEAD;
}

/*
 *--------------------------------------------------------------
 *
 * TkpScrollbarPosition --
 *
 *	Determine the scrollbar element corresponding to a
 *	given position.
 *
 * Results:
 *	One of TOP_ARROW, TOP_GAP, etc., indicating which element
 *	of the scrollbar covers the position given by (x, y).  If
 *	(x,y) is outside the scrollbar entirely, then OUTSIDE is
 *	returned.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

int
TkpScrollbarPosition(
    TkScrollbar *scrollPtr,	/* Scrollbar widget record. */
    int x, int y)		/* Coordinates within scrollPtr's
				 * window. */
{
    MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr;
    GWorldPtr destPort;
    int length, width, tmp, inactive = false;
    ControlPartCode part;
    Point where;
    Rect bounds;

    if (scrollPtr->vertical) {
	length = Tk_Height(scrollPtr->tkwin);
	width = Tk_Width(scrollPtr->tkwin);
    } else {
	tmp = x;
	x = y;
	y = tmp;
	length = Tk_Width(scrollPtr->tkwin);
	width = Tk_Height(scrollPtr->tkwin);
    }

    if ((x < scrollPtr->inset) || (x >= (width - scrollPtr->inset))
	    || (y < scrollPtr->inset) || (y >= (length - scrollPtr->inset))) {
	return OUTSIDE;
    }

    /*
     * All of the calculations in this procedure mirror those in
     * DisplayScrollbar.  Be sure to keep the two consistent.  On the 
     * Macintosh we use the OS call TestControl to do this mapping.
     * For TestControl to work, the scrollbar must be active and must
     * be in the current port.
     */

    destPort = TkMacGetDrawablePort(Tk_WindowId(scrollPtr->tkwin));
    SetGWorld(destPort, NULL);
    UpdateControlValues(macScrollPtr);
    if ((**macScrollPtr->sbHandle).contrlHilite == 255) {
	inactive = true;
	(**macScrollPtr->sbHandle).contrlHilite = 0;
    }

    TkMacWinBounds((TkWindow *) scrollPtr->tkwin, &bounds);		
    where.h = x + bounds.left;
    where.v = y + bounds.top;
    part = TestControl(((MacScrollbar *) scrollPtr)->sbHandle, where);
    if (inactive) {
	(**macScrollPtr->sbHandle).contrlHilite = 255;
    }
    switch (part) {
    	case inUpButton:
	    return TOP_ARROW;
    	case inPageUp:
	    return TOP_GAP;
    	case inThumb:
	    return SLIDER;
    	case inPageDown:
	    return BOTTOM_GAP;
    	case inDownButton:
	    return BOTTOM_ARROW;
    	default:
	    return OUTSIDE;
    }
}

/*
 *--------------------------------------------------------------
 *
 * ThumbActionProc --
 *
 *	Callback procedure used by the Macintosh toolbox call
 *	TrackControl.  This call is used to track the thumb of
 *	the scrollbar.  Unlike the ScrollbarActionProc function
 *	this function is called once and basically takes over
 *	tracking the scrollbar from the control.  This is done
 *	to avoid conflicts with what the control plans to draw.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May change the display.
 *
 *--------------------------------------------------------------
 */

static pascal void
ThumbActionProc()
{
    register TkScrollbar *scrollPtr = activeScrollPtr;
    register MacScrollbar *macScrollPtr = (MacScrollbar *) activeScrollPtr;
    Tcl_DString cmdString;
    Rect nullRect = {0,0,0,0};
    int origValue, trackBarPin;
    double thumbWidth, newFirstFraction, trackBarSize;
    char vauleString[40];
    Point currentPoint = { 0, 0 };
    Point lastPoint = { 0, 0 };
    Rect trackRect;
    Tcl_Interp *interp;
    
    if (scrollPtr == NULL) {
	return;
    }

    Tcl_DStringInit(&cmdString);
    
    /*
     * First compute values that will remain constant during the tracking
     * of the thumb.  The variable trackBarSize is the length of the scrollbar
     * minus the 2 arrows and half the width of the thumb on both sides
     * (3 * arrowLength).  The variable trackBarPin is the lower starting point
     * of the drag region.
     *
     * Note: the arrowLength is equal to the thumb width of a Mac scrollbar.
     */
    origValue = GetControlValue(macScrollPtr->sbHandle);
    trackRect = (**macScrollPtr->sbHandle).contrlRect;
    if (scrollPtr->vertical == true) {
	trackBarSize = (double) (trackRect.bottom - trackRect.top
		- (scrollPtr->arrowLength * 3));
	trackBarPin = trackRect.top + scrollPtr->arrowLength
	    + (scrollPtr->arrowLength / 2);
	InsetRect(&trackRect, -25, -113);
	
    } else {
	trackBarSize = (double) (trackRect.right - trackRect.left
		- (scrollPtr->arrowLength * 3));
	trackBarPin = trackRect.left + scrollPtr->arrowLength
	    + (scrollPtr->arrowLength / 2);
	InsetRect(&trackRect, -113, -25);
    }

    /*
     * Track the mouse while the button is held down.  If the mouse is moved,
     * we calculate the value that should be passed to the "command" part of
     * the scrollbar.
     */
    while (StillDown()) {
	GetMouse(&currentPoint);
	if (EqualPt(currentPoint, lastPoint)) {
	    continue;
	}
	lastPoint = currentPoint;

	/*
	 * Calculating this value is a little tricky.  We need to calculate a
	 * value for where the thumb would be in a Motif widget (variable
	 * thumb).  This value is what the "command" expects and is what will
	 * be resent to the scrollbar to update its value.
	 */
	thumbWidth = scrollPtr->lastFraction - scrollPtr->firstFraction;
	if (PtInRect(currentPoint, &trackRect)) {
	    if (scrollPtr->vertical == true) {
		newFirstFraction =  (1.0 - thumbWidth) *
		    ((double) (currentPoint.v - trackBarPin) / trackBarSize);
	    } else {
		newFirstFraction =  (1.0 - thumbWidth) *
		    ((double) (currentPoint.h - trackBarPin) / trackBarSize);
	    }
	} else {
	    newFirstFraction = ((double) origValue / 1000.0)
		* (1.0 - thumbWidth);
	}
	
	sprintf(vauleString, "%g", newFirstFraction);

	Tcl_DStringSetLength(&cmdString, 0);
	Tcl_DStringAppend(&cmdString, scrollPtr->command,
		scrollPtr->commandSize);
	Tcl_DStringAppendElement(&cmdString, "moveto");
	Tcl_DStringAppendElement(&cmdString, vauleString);

        interp = scrollPtr->interp;
        Tcl_Preserve((ClientData) interp);
	Tcl_GlobalEval(interp, cmdString.string);
        Tcl_Release((ClientData) interp);
	
	Tcl_DStringSetLength(&cmdString, 0);
	Tcl_DStringAppend(&cmdString, "update idletasks",
		strlen("update idletasks"));
        Tcl_Preserve((ClientData) interp);
	Tcl_GlobalEval(interp, cmdString.string);
        Tcl_Release((ClientData) interp);
    }
    
    /*
     * This next bit of code is a bit of a hack - but needed.  The problem is
     * that the control wants to draw the drag outline if the control value
     * changes during the drag (which it does).  What we do here is change the
     * clip region to hide this drawing from the user.
     */
    ClipRect(&nullRect);
    
    Tcl_DStringFree(&cmdString);
    return;
}

/*
 *--------------------------------------------------------------
 *
 * ScrollbarActionProc --
 *
 *	Callback procedure used by the Macintosh toolbox call
 *	TrackControl.  This call will update the display while
 *	the scrollbar is being manipulated by the user.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May change the display.
 *
 *--------------------------------------------------------------
 */

static pascal void
ScrollbarActionProc(
    ControlRef theControl, 	/* Handle to scrollbat control */
    ControlPartCode partCode)	/* Part of scrollbar that was "hit" */
{
    register TkScrollbar *scrollPtr = (TkScrollbar *) GetCRefCon(theControl);
    Tcl_DString cmdString;
    
    Tcl_DStringInit(&cmdString);
    Tcl_DStringAppend(&cmdString, scrollPtr->command,
	    scrollPtr->commandSize);

    if (partCode == inUpButton || partCode == inDownButton) {
	Tcl_DStringAppendElement(&cmdString, "scroll");
	Tcl_DStringAppendElement(&cmdString,
		(partCode == inUpButton ) ? "-1" : "1");
	Tcl_DStringAppendElement(&cmdString, "unit");
    } else if (partCode == inPageUp || partCode == inPageDown) {
	Tcl_DStringAppendElement(&cmdString, "scroll");
	Tcl_DStringAppendElement(&cmdString,
		(partCode == inPageUp ) ? "-1" : "1");
	Tcl_DStringAppendElement(&cmdString, "page");
    }
    Tcl_Preserve((ClientData) scrollPtr->interp);
    Tcl_DStringAppend(&cmdString, "; update idletasks",
	strlen("; update idletasks"));
    Tcl_GlobalEval(scrollPtr->interp, cmdString.string);
    Tcl_Release((ClientData) scrollPtr->interp);

    Tcl_DStringFree(&cmdString);
}

/*
 *--------------------------------------------------------------
 *
 * ScrollbarBindProc --
 *
 *	This procedure is invoked when the default <ButtonPress>
 *	binding on the Scrollbar bind tag fires.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The event enters a modal loop.
 *
 *--------------------------------------------------------------
 */

static int
ScrollbarBindProc(
    ClientData clientData,	/* Not used. */
    Tcl_Interp *interp,		/* Interp with binding. */
    XEvent *eventPtr,		/* X event that triggered binding. */
    Tk_Window tkwin,		/* Target window for event. */
    KeySym keySym)		/* The KeySym if a key event. */
{
    TkWindow *winPtr = (TkWindow*)tkwin;
    TkScrollbar *scrollPtr = (TkScrollbar *) winPtr->instanceData;
    MacScrollbar *macScrollPtr = (MacScrollbar *) winPtr->instanceData;

    Tcl_Preserve((ClientData)scrollPtr);
    macScrollPtr->macFlags |= IN_MODAL_LOOP;
    
    if (eventPtr->type == ButtonPress) {
    	Point where;
    	Rect bounds;
    	int part, x, y, dummy;
    	unsigned int state;
	CGrafPtr saveWorld;
	GDHandle saveDevice;
	GWorldPtr destPort;
	Window window;

	/*
	 * To call Macintosh control routines we must have the port
	 * set to the window containing the control.  We will then test
	 * which part of the control was hit and act accordingly.
	 */
	destPort = TkMacGetDrawablePort(Tk_WindowId(scrollPtr->tkwin));
	GetGWorld(&saveWorld, &saveDevice);
	SetGWorld(destPort, NULL);
	TkMacSetUpClippingRgn(Tk_WindowId(scrollPtr->tkwin));

	TkMacWinBounds((TkWindow *) scrollPtr->tkwin, &bounds);		
    	where.h = eventPtr->xbutton.x + bounds.left;
    	where.v = eventPtr->xbutton.y + bounds.top;
	part = TestControl(macScrollPtr->sbHandle, where);
	if (part == inThumb && scrollPtr->jump == false) {
	    /*
	     * Case 1: In thumb, no jump scrolling.  Call track control
	     * with the thumb action proc which will do most of the work.
	     * Set the global activeScrollPtr to the current control
	     * so the callback may have access to it.
	     */
	    activeScrollPtr = scrollPtr;
	    part = TrackControl(macScrollPtr->sbHandle, where,
		    (ControlActionUPP) thumbActionProc);
	    activeScrollPtr = NULL;
	} else if (part == inThumb) {
	    /*
	     * Case 2: in thumb with jump scrolling.  Call TrackControl
	     * with a NULL action proc.  Use the new value of the control
	     * to set update the control.
	     */
	    part = TrackControl(macScrollPtr->sbHandle, where, NULL);
	    if (part == inThumb) {
	    	double newFirstFraction, thumbWidth;
		Tcl_DString cmdString;
		char vauleString[TCL_DOUBLE_SPACE];

		/*
		 * The following calculation takes the new control
		 * value and maps it to what Tk needs for its variable
		 * thumb size representation.
		 */
		thumbWidth = scrollPtr->lastFraction
		     - scrollPtr->firstFraction;
		newFirstFraction = (1.0 - thumbWidth) *
		    ((double) GetControlValue(macScrollPtr->sbHandle) / 1000.0);
		sprintf(vauleString, "%g", newFirstFraction);

		Tcl_DStringInit(&cmdString);
		Tcl_DStringAppend(&cmdString, scrollPtr->command,
			strlen(scrollPtr->command));
		Tcl_DStringAppendElement(&cmdString, "moveto");
		Tcl_DStringAppendElement(&cmdString, vauleString);
		Tcl_DStringAppend(&cmdString, "; update idletasks",
			strlen("; update idletasks"));
		
                interp = scrollPtr->interp;
                Tcl_Preserve((ClientData) interp);
		Tcl_GlobalEval(interp, cmdString.string);
                Tcl_Release((ClientData) interp);
		Tcl_DStringFree(&cmdString);		
	    }
	} else if (part != 0) {
	    /*
	     * Case 3: in any other part of the scrollbar.  We call
	     * TrackControl with the scrollActionProc which will do
	     * most all the work.
	     */
	    TrackControl(macScrollPtr->sbHandle, where, scrollActionProc);
	    HiliteControl(macScrollPtr->sbHandle, 0);
	}
	
	/*
	 * The TrackControl call will "eat" the ButtonUp event.  We now
	 * generate a ButtonUp event so Tk will unset implicit grabs etc.
	 */
	GetMouse(&where);
	XQueryPointer(NULL, None, &window, &window, &x,
	    &y, &dummy, &dummy, &state);
	window = Tk_WindowId(scrollPtr->tkwin);
	TkGenerateButtonEvent(x, y, window, state);

	SetGWorld(saveWorld, saveDevice);
    }

    if (macScrollPtr->sbHandle && (macScrollPtr->macFlags & ALREADY_DEAD)) {
	DisposeControl(macScrollPtr->sbHandle);
	macScrollPtr->sbHandle = NULL;
    }
    macScrollPtr->macFlags &= ~IN_MODAL_LOOP;
    Tcl_Release((ClientData)scrollPtr);
    
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ScrollbarEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various
 *	events on scrollbars.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get
 *	cleaned up.  When it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
ScrollbarEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkScrollbar *scrollPtr = (TkScrollbar *) clientData;
    MacScrollbar *macScrollPtr = (MacScrollbar *) clientData;

    if (eventPtr->type == UnmapNotify) {
	TkMacSetScrollbarGrow((TkWindow *) scrollPtr->tkwin, false);
    } else if (eventPtr->type == ActivateNotify) {
	macScrollPtr->macFlags |= ACTIVE;
	TkScrollbarEventuallyRedraw((ClientData) scrollPtr);
    } else if (eventPtr->type == DeactivateNotify) {
	macScrollPtr->macFlags &= ~ACTIVE;
	TkScrollbarEventuallyRedraw((ClientData) scrollPtr);
    } else {
	TkScrollbarEventProc(clientData, eventPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * UpdateControlValues --
 *
 *	This procedure updates the Macintosh scrollbar control
 *	to display the values defined by the Tk scrollbar.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The Macintosh control is updated.
 *
 *--------------------------------------------------------------
 */

static void
UpdateControlValues(
    MacScrollbar *macScrollPtr)		/* Scrollbar data struct. */
{
    TkScrollbar *scrollPtr = (TkScrollbar *) macScrollPtr;
    Tk_Window tkwin = scrollPtr->tkwin;
    MacDrawable * macDraw = (MacDrawable *) Tk_WindowId(scrollPtr->tkwin);
    WindowRef windowRef  = (**macScrollPtr->sbHandle).contrlOwner;    
    double middle;
    int drawGrowRgn = false;
    int flushRight = false;
    int flushBottom = false;

    /*
     * We can't use the Macintosh commands SizeControl and MoveControl as these
     * calls will also cause a redraw which in our case will also cause
     * flicker.  To avoid this we adjust the control record directly.  The
     * Draw1Control command appears to just draw where ever the control says to
     * draw so this seems right.
     *
     * NOTE: changing the control record directly may not work when
     * Apple releases the Copland version of the MacOS (or when hell is cold).
     */
     
    (**macScrollPtr->sbHandle).contrlRect.left = macDraw->xOff + scrollPtr->inset;
    (**macScrollPtr->sbHandle).contrlRect.top = macDraw->yOff + scrollPtr->inset;
    (**macScrollPtr->sbHandle).contrlRect.right = macDraw->xOff + Tk_Width(tkwin)
	- scrollPtr->inset;
    (**macScrollPtr->sbHandle).contrlRect.bottom = macDraw->yOff +
	Tk_Height(tkwin) - scrollPtr->inset;
    
    /*
     * To make Tk applications look more like Macintosh applications without 
     * requiring additional work by the Tk developer we do some cute tricks.
     * The first trick plays with the size of the widget to get it to overlap
     * with the side of the window by one pixel (we don't do this if the placer
     * is the geometry manager).  The second trick shrinks the scrollbar if it
     * it covers the area of the grow region ao the scrollbar can also draw
     * the grow region if need be.
     */
    if (!strcmp(macDraw->winPtr->geomMgrPtr->name, "place")) {
	macScrollPtr->macFlags &= AUTO_ADJUST;
    } else {
	macScrollPtr->macFlags |= AUTO_ADJUST;
    }
    /* TODO: use accessor function!!! */
    if (windowRef->portRect.left == (**macScrollPtr->sbHandle).contrlRect.left) {
	if (macScrollPtr->macFlags & AUTO_ADJUST) {
	    (**macScrollPtr->sbHandle).contrlRect.left--;
	}
	if (!(macScrollPtr->macFlags & FLUSH_LEFT)) {
	    macScrollPtr->macFlags |= FLUSH_LEFT;
	    if (scrollPtr->vertical) {
		TkpComputeScrollbarGeometry(scrollPtr);
	    }
	}
    } else if (macScrollPtr->macFlags & FLUSH_LEFT) {
	macScrollPtr->macFlags &= ~FLUSH_LEFT;
	if (scrollPtr->vertical) {
	    TkpComputeScrollbarGeometry(scrollPtr);
	}
    }
    
    if (windowRef->portRect.top == (**macScrollPtr->sbHandle).contrlRect.top) {
	if (macScrollPtr->macFlags & AUTO_ADJUST) {
	    (**macScrollPtr->sbHandle).contrlRect.top--;
	}
	if (!(macScrollPtr->macFlags & FLUSH_TOP)) {
	    macScrollPtr->macFlags |= FLUSH_TOP;
	    if (! scrollPtr->vertical) {
		TkpComputeScrollbarGeometry(scrollPtr);
	    }
	}
    } else if (macScrollPtr->macFlags & FLUSH_TOP) {
	macScrollPtr->macFlags &= ~FLUSH_TOP;
	if (! scrollPtr->vertical) {
	    TkpComputeScrollbarGeometry(scrollPtr);
	}
    }
	
    if (windowRef->portRect.right == (**macScrollPtr->sbHandle).contrlRect.right) {
	flushRight = true;
	if (macScrollPtr->macFlags & AUTO_ADJUST) {
	    (**macScrollPtr->sbHandle).contrlRect.right++;
	}
	if (!(macScrollPtr->macFlags & FLUSH_RIGHT)) {
	    macScrollPtr->macFlags |= FLUSH_RIGHT;
	    if (scrollPtr->vertical) {
		TkpComputeScrollbarGeometry(scrollPtr);
	    }
	}
    } else if (macScrollPtr->macFlags & FLUSH_RIGHT) {
	macScrollPtr->macFlags &= ~FLUSH_RIGHT;
	if (scrollPtr->vertical) {
	    TkpComputeScrollbarGeometry(scrollPtr);
	}
    }
	
    if (windowRef->portRect.bottom == (**macScrollPtr->sbHandle).contrlRect.bottom) {
	flushBottom = true;
	if (macScrollPtr->macFlags & AUTO_ADJUST) {
	    (**macScrollPtr->sbHandle).contrlRect.bottom++;
	}
	if (!(macScrollPtr->macFlags & FLUSH_BOTTOM)) {
	    macScrollPtr->macFlags |= FLUSH_BOTTOM;
	    if (! scrollPtr->vertical) {
		TkpComputeScrollbarGeometry(scrollPtr);
	    }
	}
    } else if (macScrollPtr->macFlags & FLUSH_BOTTOM) {
	macScrollPtr->macFlags &= ~FLUSH_BOTTOM;
	if (! scrollPtr->vertical) {
	    TkpComputeScrollbarGeometry(scrollPtr);
	}
    }

    /*
     * If the scrollbar is flush against the bottom right hand coner then
     * it may need to draw the grow region for the window so we let the
     * wm code know about this scrollbar.  We don't actually draw the grow
     * region, however, unless we are currently resizable.
     */
    macScrollPtr->macFlags &= ~DRAW_GROW;
    if (flushBottom && flushRight) {
	TkMacSetScrollbarGrow((TkWindow *) tkwin, true);
	if (TkMacResizable(macDraw->toplevel->winPtr)) {
	    if (scrollPtr->vertical) {
		(**macScrollPtr->sbHandle).contrlRect.bottom -= 14;
	    } else {
		(**macScrollPtr->sbHandle).contrlRect.right -= 14;
	    }
	    macScrollPtr->macFlags |= DRAW_GROW;
	}
    } else {
	TkMacSetScrollbarGrow((TkWindow *) tkwin, false);
    }
    
    /*
     * Given the Tk parameters for the fractions of the start and
     * end of the thumb, the following calculation determines the
     * location for the fixed sized Macintosh thumb.
     */
    middle = scrollPtr->firstFraction / (scrollPtr->firstFraction +
	    (1.0 - scrollPtr->lastFraction));

    (**macScrollPtr->sbHandle).contrlValue = (short) (middle * 1000);
    if ((**macScrollPtr->sbHandle).contrlHilite == 0 || 
		(**macScrollPtr->sbHandle).contrlHilite == 255) {
	if (scrollPtr->firstFraction == 0.0 &&
		scrollPtr->lastFraction == 1.0) {
	    (**macScrollPtr->sbHandle).contrlHilite = 255;
	} else {
	    (**macScrollPtr->sbHandle).contrlHilite = 0;
	}
    }
    if ((**macScrollPtr->sbHandle).contrlVis != 255) {
	(**macScrollPtr->sbHandle).contrlVis = 255;
    }
}