File: macgworld.c

package info (click to toggle)
xconq 7.2.2-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 8,296 kB
  • ctags: 9,199
  • sloc: ansic: 107,849; sh: 2,108; perl: 2,057; makefile: 1,177; sed: 161; csh: 50; awk: 49; lisp: 39
file content (1012 lines) | stat: -rw-r--r-- 30,546 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
/* Offscreen graphics support for the Mac interface to Xconq.
   Copyright (C) 1997, 1998 Hans Ronne.

Xconq is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.  See the file COPYING.  */

#include "conq.h"
#include "kpublic.h"
#include "macconq.h"

/* Needed for changing screen depths and handling the control strip */

#include <Palettes.h>

#ifdef CONTROL_STRIP

// --- NEW STUFF MOVED HERE FROM APPLESTUFF.H ------------------

/*	Apple control strip routine descriptors follow below. */
/*	Must be included in PPC projects that use the control strip. *
/*	See http://devworld.apple.com/dev/qa/ops/ops15.html. */

#if GENERATINGCFM

/* If we're not generating CFM, then assume the
   68K inlines in the headers apply instead. */

#include <MixedMode.h>
#include <OSUtils.h>
pascal Boolean SBIsControlStripVisible ( void );
pascal void SBShowHideControlStrip(Boolean showIt);

/*  SBIsControlStripVisible is a Pascal routine, */
/*  dispatched from the selector in D0, returning */
/*  a Boolean result */
pascal Boolean SBIsControlStripVisible ( void )
{
    enum
        {
        uppSBIsControlStripVisibleInfo = kD0DispatchedPascalStackBased
            | RESULT_SIZE (SIZE_CODE (sizeof(Boolean)))
            | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE (kFourByteCode)
            };

            return CallUniversalProc (
            GetToolTrapAddress (_ControlStripDispatch),
            uppSBIsControlStripVisibleInfo, 0x00);
}

pascal void SBShowHideControlStrip(Boolean showIt)
{
    enum
        {
        uppSBShowHideControlStripInfo =
            kD0DispatchedPascalStackBased
            | DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE (kFourByteCode)
            | DISPATCHED_STACK_ROUTINE_PARAMETER
                (1, SIZE_CODE (sizeof (showIt)))
            };

            CallUniversalProc (
            GetToolTrapAddress (_ControlStripDispatch),
            uppSBShowHideControlStripInfo, 0x01, showIt);
}

#else   /*  not GENERATINGCFM */
#include <ControlStrip.h>
#endif /*  GENERATINGCFM */

// --- END NEW STUFF -------------------------------------------------------

#endif /* CONTROL_STRIP */

// --- USED TO DEBUG OFFSCREEN GRAPHICS ----------------------------------------

static Rect debugRect = {0};
static int scrolling = FALSE;

// --- FUNCTION PROTOTYPES  --------------------------------------------------

static void reduce_screen_depth(GDHandle gdev);
static void auto_scroll_left(Map *map);
static void auto_scroll_right(Map *map);
static void auto_scroll_up(Map *map);
static void auto_scroll_down(Map *map);
static void auto_scroll_down_left(Map *map);
static void auto_scroll_down_right(Map *map);
static void auto_scroll_up_left(Map *map);
static void auto_scroll_up_right(Map *map);

// --- NEW FUNCTION ------------------------------------------------------------

static void copy_clipped_to_map(Map *map, Rect sourcerect, Rect destrect);

// --- FUNCTIONS USED TO SET THE SCREEN DEPTH ----------------------------------------

/* Check if any device has more than 256 colors */

void
check_screen_depths(void)
{
	int 		depth;
	GDHandle 	gdev;
	Boolean	ControlStripShown;

	if (!hasColorQD)
	  return;

#ifdef CONTROL_STRIP
/*	
	Make sure all control strips or extensions strips are shown before proceeding since
	changing the screen depth while a strip is hidden will move it 20 pixels downwards.
	This is a pain if you like to keep your strips hidden.
*/
	/* First save the users control strip visibility setting */
	ControlStripShown = SBIsControlStripVisible();
	
	/* Unhide the strip */
	SBShowHideControlStrip(TRUE);
#endif

	/* Now check the Device List and change screen depths if necessary */
	gdev = GetDeviceList();
	depth = (*((*gdev)->gdPMap))->pixelSize;
	if (depth > 8 && HasDepth(gdev, 8, 0, 0)) {
		reduce_screen_depth(gdev);
	}
	while ((gdev = GetNextDevice(gdev)) != nil) {
		depth = (*((*gdev)->gdPMap))->pixelSize;
		if (depth > 8 && HasDepth(gdev, 8, 0, 0)) {
			reduce_screen_depth(gdev);
		}
	}

#ifdef CONTROL_STRIP
	/* Restore the users control strip visibility setting */
	SBShowHideControlStrip(ControlStripShown);
#endif
}

/* Ask for permission to change depth of gdev to 8 bits (256 colors) */

void
reduce_screen_depth(GDHandle gdev)
{
	DialogPtr	 win;
	short 	done = FALSE;
	short 	ditem;

	win = GetNewDialog(dScreenDepth, NULL, (DialogPtr) -1);
	ShowWindow(win);
	while (!done) {

		SetCursor(&QD(arrow));
		draw_default_button(win, diScreenDepthOK);
		ModalDialog(NULL, &ditem);
		switch (ditem) {

			case diScreenDepthOK:
				SetDepth(gdev, 8, 0, 0);
				done = TRUE;
				break;

			case diScreenDepthCancel:
				done = TRUE;
				break;

			default:
				break;
		}
	}
	DisposeDialog(win);
}

// ---FUNCTIONS USED DIRECTLY IN OFFSCREEN GRAPHICS ----------------------------------

/* Scrolls the map window dx, dy steps within its offscreen gworld. This function should always 
   be called whenever the viewport is moved. If necessary, get the new focus point, reset to the old
   focus, and then let scroll_map_window do the job. This ensures that the gworld always is used. */

void 
scroll_map_window(Map *map, int dx, int dy)
{
	int 		newsx, newsy, scaled_sx, scaled_sy, dummy, redraw = FALSE;
	Rect		destRect, tmprect, portrect = map->gworldPortPtr->portRect;
	GrafPtr	oldport;
	
	GetPort(&oldport);
	/* Set current port to the map window */
	SetPort((GrafPtr)map->windowPortPtr);

	if (DebugG) {
		/* Erase the old debugRect */
		ForeColor(redColor);
		PenMode(patXor);
		FrameRect(&debugRect);
		ForeColor(blackColor);
		PenMode(normal);
		scrolling = TRUE;	/* Turns off debugRect while scrolling */
	}

	/* Erase other-map boxes in other windows */
	draw_related_maps(map);

	/* Find the new position */
	newsx = map->vp->sx + dx;
	newsy = map->vp->sy + dy;
	
	/* Handle xwrapped world */
	if (area.xwrap) {	
		/* Scrolling past the eastern edge of the world */
		if (newsx > map->vp->sxmax) newsx -= map->vp->sxmax;
		/* Scrolling past the western edge of the world */
		else if (newsx < 0) newsx += map->vp->sxmax;
	/* Handle non-xwrapped world */
	} else {		
		/* Restrict newsx to stay between the map edges */
		newsx = limitn(map->vp->sxmin, newsx, map->vp->sxmax);
		/* Adjust dx to reflect this restriction */
		dx = newsx - map->vp->sx;
	}

	/* Scale the scrollbar to circumvent the 32K limit */
	/* (see set_map_scrollbars for details) */
	dummy = map->vp->sxmax;
	scaled_sx = newsx;
	while (dummy > 32000) {
		dummy /= 2;
		scaled_sx /= 2;
	}		
	/* Use the scaled value to set the new thumb position */
	SetCtlValue(map->hscrollbar, scaled_sx);

	/* Restrict newsy to stay between the map edges */
	newsy = limitn(map->vp->symin, newsy, map->vp->symax);
	/* Adjust dy to reflect this restriction */
	dy = newsy - map->vp->sy;

	/* Scale the scrollbar to circumvent the 32K limit */
	/* (see set_map_scrollbars for details) */
	dummy = map->vp->symax;
	scaled_sy = newsy;
	while (dummy > 32000) {
		dummy /= 2;
		scaled_sy /= 2;
	}		
	/* Use the scaled value to set the new thumb position */
	SetCtlValue(map->vscrollbar, scaled_sy);

	/* Move the viewport */
	map->vp->sx = newsx;
	map->vp->sy = newsy;
	set_content_rect(map);

	/* Handle dx for wrapped gworlds.  Never update. */
	if (area.xwrap && map->vp->sxmax <= portrect.right - portrect.left) {
		redraw = FALSE; 
	} else if ((dx > 0 && map->offsetx + dx > map->bufx)
			   || (dx < 0 && map->offsetx + dx < -map->bufx)) {
		/* Handles dx in other cases.  Update if stepping outside. */
		redraw = TRUE;
	}		
	/* Always update if dy take us outside the gworld */
	if ((dy > 0 && map->offsety + dy > map->bufy)
		|| (dy < 0 && map->offsety + dy < -map->bufy)) {
		redraw = TRUE;
	}		

	if (redraw) {
		/* Redraw gworld and copy contentrect to the window */
		update_gworld(map);
		/* Redraw other-map boxes and restore port before exit */
		draw_related_maps(map);
		SetPort(oldport);
		if (DebugG) {
			SetRect(&debugRect, 0, 0, 0, 0);		/* Prevents drawing of junk next time */
			scrolling = FALSE;				/* Turns on debugRect after scrolling */
		}
		return;
	}	   
	  
	/* Scroll the already drawn region */
	ScrollRect(&map->contentrect, -dx, -dy, NULL);
	/* Update offset trackers */
	map->offsetx += dx;
	map->offsety += dy;
	/* Wrap offsetx if necessary */
	map->offsetx %= map->vp->sxmax;

	/* Calculate update rects and update each one in turn from the gworld */

	if (dx > 0) {				/* Going Right */
		SetRect(&destRect, 
				map->conw + map->vp->pxw - dx, 
				map->toph, 
				map->conw + map->vp->pxw, 
				map->toph + map->vp->pxh);

		copy_from_gworld(map, destRect);
	
	} else if (dx < 0) {			/* Going Left */
		SetRect(&destRect, 
				map->conw, 
				map->toph, 
				map->conw - dx, 
				map->toph + map->vp->pxh);

		copy_from_gworld(map, destRect);
	}

	if (dy > 0) {				/* Going Down */
		SetRect(&destRect, 
			/* Skip area already updated by Going Right */
			max(map->conw,   map->conw - dx), 
		   	         map->toph + map->vp->pxh - dy, 
			/* Skip area already updated by Going Left */
			min(map->conw + map->vp->pxw, map->conw + map->vp->pxw - dx), 
				map->toph + map->vp->pxh);

		copy_from_gworld(map, destRect);

	} else if (dy < 0) {			/* Going Up */
		SetRect(&destRect, 
			/* Skip area already updated by Going Right */
			 max(map->conw,   map->conw - dx), 
		   	         map->toph, 
			/* Skip area already updated by Going Left */
			 min(map->conw + map->vp->pxw, map->conw + map->vp->pxw - dx), 
				map->toph - dy);

		copy_from_gworld(map, destRect);
	}
	
	/* Redraw other-map boxes and restore the old port */
	draw_related_maps(map);
	SetPort(oldport);

	if (DebugG) {
		SetRect(&debugRect, 0, 0, 0, 0);		/* Prevents drawing of junk next time */
		scrolling = FALSE;				/* Turns on debugRect after scrolling */
	}
}

/* Copies destrect from its source in the offscreen gworld. 
     Special code for handling wrapped cylindrical gworlds. */

void 
copy_from_gworld(Map *map, Rect destrect)
{
	Rect 	portrect, sourcerect;
	
	if (DebugG &! scrolling) {
		/* Erase the old debugRect */
		ForeColor(redColor);
		PenMode(patXor);
		FrameRect(&debugRect);
		ForeColor(blackColor);
		PenMode(normal);
	}

	portrect = map->gworldPortPtr->portRect;
	sourcerect = destrect;
	
	/* Adjust source position for offset, scrolling buffers and decor */
	OffsetRect(&sourcerect, map->offsetx + map->bufx - map->conw, 
			   		   map->offsety + map->bufy - map->toph);

	/* Handle wrapped cylindrical gworlds (complicated) */
	if (area.xwrap && map->vp->sxmax <= portrect.right - portrect.left) {
		Rect westsource = sourcerect;
		Rect eastsource = sourcerect;
		Rect midsource = sourcerect;
		Rect westdest = destrect;
		Rect eastdest = destrect;
		Rect middest = destrect;
		int rest;
				
		/* Handle region inside gworld (unnecessary if scrolling)*/
		if (!scrolling) {
			SectRect(&sourcerect, &portrect, &midsource);
			middest.left += midsource.left - sourcerect.left;				
			middest.right += midsource.right - sourcerect.right;				
			/* Make several tandem copies if necessary */
			rest = map->vp->pxw - middest.left;
			while (rest > -map->vp->sxmax) {
				copy_clipped_to_map(map, midsource, middest);
				/* Move destination one full gworld width east */
				OffsetRect(&middest, map->vp->sxmax, 0);
				rest -= map->vp->sxmax;
			} 
		}
				
		/* Handle region beyond western edge of gworld */
		if (sourcerect.left < portrect.left) {
			westsource.right = portrect.left;
			westdest.right   += portrect.left - sourcerect.right;
			OffsetRect(&westsource, map->vp->sxmax, 0);
			/* Make several tandem copies if necessary */
			rest = map->vp->pxw - westdest.left;
			while (rest > -map->vp->sxmax) {
				/* Only make westmost copy if scrolling */
				if (!scrolling || rest == map->vp->pxw - westdest.left)
					copy_clipped_to_map(map, westsource, westdest);
				/* Move destination one full gworld width east */
				OffsetRect(&westdest, map->vp->sxmax, 0);
				rest -= map->vp->sxmax;
			}
		}

		/* Handle region beyond eastern edge of gworld */
		if (sourcerect.right > portrect.right) {
			/* Extend/truncate source to right end of gworld */
			eastsource.left = portrect.right;
			/* Extend/truncate dest by the same amount */
			eastdest.left += portrect.right - sourcerect.left;
			/* Repeat as long as source protrudes beyond gworld */
			while (eastsource.right > eastsource.left) {
				Rect tmpsource, tmpdest = eastdest;
				/* Shift source one full area width to the left */
				OffsetRect(&eastsource, -map->vp->sxmax, 0);
				/* Copy to screen only when we reach destrect */
				if (destrect.left - eastdest.left < map->vp->sxmax) {
					/* Copy one full gworld content each time */
					SectRect(&eastsource, &portrect, &tmpsource);
					tmpdest.right -= eastsource.right - tmpsource.right; 
					/* Make several tandem copies if necessary */
					rest = map->vp->pxw - tmpdest.left;
					while (rest > -map->vp->sxmax) {
						/* Only make eastmost copy if scrolling */
						if (!scrolling || rest < map->vp->sxmax)
							copy_clipped_to_map(map, tmpsource, tmpdest);
						/* Move destination one full gworld width east */
						OffsetRect(&tmpdest, map->vp->sxmax, 0);
						rest -= map->vp->sxmax;
					} 
				}
				/* Truncate both rects by one area width */
				eastsource.left 	+= map->vp->sxmax;
				eastdest.left	+= map->vp->sxmax;
			}
		}

	/* Handle all other cases (simple) */
	} else copy_clipped_to_map(map, sourcerect, destrect);
	
	if (DebugG &! scrolling) {
		/* Draw the new debugRect */
		debugRect = destrect;					
		ForeColor(redColor);
		PenMode(patXor);
		FrameRect(&debugRect);
		ForeColor(blackColor);
		PenMode(normal);
	}
}

/* Core function in offscren graphics that does the actual copying to the screen. Both source */
/* and destination rects are first adjusted so that copying is clipped to the map contentrect. */ 

void
copy_clipped_to_map(Map *map, Rect sourcerect, Rect destrect)
{
	/* Clip left edge to contentrect */
	if (destrect.right > map->contentrect.right) {
		sourcerect.right -= destrect.right - map->contentrect.right;
		destrect.right = map->contentrect.right;
	}
	/* Clip right edge to contentrect */
	if (destrect.left < map->contentrect.left) {
		sourcerect.left += map->contentrect.left - destrect.left;
		destrect.left = map->contentrect.left;
	}
	/* Clip top edge to contentrect */
	if (destrect.top < map->contentrect.top) {
		sourcerect.top += map->contentrect.top - destrect.top;
		destrect.top = map->contentrect.top;
	}
	/* Clip bottom edge to contentrect */
	if (destrect.bottom > map->contentrect.bottom) {
		sourcerect.bottom -= destrect.bottom - map->contentrect.bottom;
		destrect.bottom = map->contentrect.bottom;
	}

	LockPixels(GetGWorldPixMap(map->gworldPortPtr));
	CopyBits(&((GrafPtr) map->gworldPortPtr)->portBits,
		       &((GrafPtr) map->windowPortPtr)->portBits,
		       &sourcerect, &destrect, srcCopy, NULL  );
	UnlockPixels(GetGWorldPixMap(map->gworldPortPtr));
}

/* Updates the resized map using as much as possible of its offscreen gworld. Then also updates the 
   latter and redraws the map in the background. This function is called by grow_map and zoom_map 
   after window resizing but before contentrect has been resized. */

void
update_resized_map(Map *map)
{
	short right, left, down, up;
	Rect old_contentrect;

	/* Save and then resize contentrect */
	old_contentrect = map->contentrect;
	set_content_rect(map);						

	/* Calculate diffs between old & resized contentrects */
	right = map->contentrect.right 	- old_contentrect.right;
	left  = map->contentrect.left 	- old_contentrect.left;
	down  = map->contentrect.bottom - old_contentrect.bottom;
	up    = map->contentrect.top 	- old_contentrect.top;

	/* Draw the map decor */
	set_map_scrollbars(map);						
	if (map->conw > 0)
	  draw_control_panel(map);
	if (map->toplineh > 0)
	  draw_top_line(map);
	if (map->topunith > 0)
	  draw_unit_info(map);
	
	/* Check if the new contentrect extends outside the old gworld */
	if (right - left > map->bufx - map->offsetx 
	    || down - up > map->bufy - map->offsety) {

		/* Add buffers and substract offsets to get the old gworld portrect */
		InsetRect(&old_contentrect, - map->bufx, - map->bufy);
		OffsetRect(&old_contentrect, - map->offsetx, - map->offsety);

		/* First use as much as possible of the old gworld */
		copy_from_gworld(map, old_contentrect);	   

		/* Then exclude this region from the update */ 
		InvalRect(&map->window->portRect);
		ValidRect(&old_contentrect);
		BeginUpdate(map->window);

		/* Paint the update region blue (looks nice) */
		BackPat(QDPat(black));
		if (hasColorQD) ForeColor(cyanColor);
		EraseRect(&map->contentrect);
		ForeColor(blackColor);
		EndUpdate(map->window);

		/* Redraw the gworld (and the map) */ 
		update_gworld(map);

	} else {
		/* If not, first copy map content from the old gworld */
		copy_from_gworld(map, map->contentrect);	   

		/* Then redraw the gworld */
		update_gworld(map);
	}
}

/* Update the offscreen gworld. This function should always be called when the window size, magnification 
   or view angle is changed. It redraws the whole map within the updated gworld. It also optimizes the size 
   and position of the gworld. If the whole map fits within the gworld for either the x or y coordinate, the 
   viewport is shifted to the middle of the map for that coordinate, the gworld is updated, and the viewport is 
   then returned to the old position. If the map is larger than the gworld, the position of the latter is always 
   adjusted so that it does not protrude beyond the map edges. The purpose of these adjustements is to ensure 
   that as much scrolling as possible can be done without updating the gworld and redrawing the map. */

/* Note: update_gworld should NOT be called from within a BeginUpdate segment. */

void
update_gworld(Map *map)
{
	short margx, margy, newsx, newsy, oldsx, oldsy;			
	Rect GWportRect;	
	
	/* Compute sizes of map margins outside the viewport */
	margx = (map->vp->sxmax - map->vp->sxmin) / 2;
	margy = (map->vp->symax - map->vp->symin) / 2;

	/* Save the current viewport position */
	newsx = oldsx = map->vp->sx;
	newsy = oldsy = map->vp->sy;
	
	/* Optimize x position and size of the gworld */
	if (margx <= 0)									/* The viewport is wider than the map */
	  map->bufx = 0;								/* Scrolling buffers are unnecessary */								

	else if (area.xwrap 								
		&& map->vp->sxmax <= map->vp->pxw)			/* Handle wrapped worlds where the */
	  	map->bufx = 0;								/* window is wider than the area */

	else if (area.xwrap) {								/* Handle other wrapped worlds */
		map->bufx = min(map->max_bufx,				/* Make gworld same size as the area if */ 
		(area.width * map->vp->hw - map->vp->pxw)/2);	/* max_bufx is big enough for wrapping */
												/* 1 pixel may be lost here (see below) */
			
	} else if (margx < map->max_bufx - map->vp->sxmin- 4) {	/* The map will fit within the gworld */
		map->bufx = map->vp->sxmin + margx + 4; 		/* Minimize offscreen x buffer */
		newsx = limitn(map->vp->sxmin, margx, 			/* Center gworld around center of map */
				        map->vp->sxmax);  
	} else {										/* The map is wider than the gworld */
		map->bufx = map->max_bufx;					/* Set x buffer to max allowed value */
		newsx = limitn(map->vp->sxmin + map->bufx, newsx,	/* Adjust the gworld so that its edges */
				        map->vp->sxmax - map->bufx);	 	/* do not extend outside the map edges */
	}

	/* Optimize y position and size of the gworld */
	if (margy <= 0)
	  map->bufy = 0;								/* The viewport is higher than the map */
	else if (margy < map->max_bufy - map->vp->symin- 4) {	/* The map will fit within the gworld */
		map->bufy = map->vp->symin + margy + 4; 		/* Minimize offscreen y buffer */					
		newsy = limitn(map->vp->symin, margy, 			/* Center gworld around center of map */
				        map->vp->symax); 
	} else {										/* The map is higher than the gworld */								
		map->bufy = map->max_bufy;					/* Set y buffer to max allowed value */		
		newsy = limitn(map->vp->symin + map->bufy, newsy,	/* Adjust the gworld so that its edges */ 
				        map->vp->symax - map->bufy);		/* do not extend outside the map edges */
	}
		
	/* Shift the viewport to optimized gworld position */
	map->vp->sx += newsx - oldsx;
	map->vp->sy += newsy - oldsy; 

	/* Set gworld port rect to temp contentrect */
	set_content_rect(map);
	GWportRect = map->contentrect;
	
	/* Add offscreen scrolling buffers on each side */
	InsetRect(&GWportRect, - map->bufx, - map->bufy);

	/* Add 1 pixel to get correct wrapped gworld width if necessary */
	if (area.xwrap && map->vp->sxmax - map->vp->pxw != 2 * map->bufx)
		GWportRect.right += 1;

	/* Set gworld to area width if window is wider than area */
	if (area.xwrap && map->vp->sxmax <= map->vp->pxw) {
		SetRect(&GWportRect, 0, 0, 
				map->vp->sxmax, 
				map->vp->pxh + 2 * map->bufy);
	}

	/* Update gworld centered around new optimized positon and check for errors */
	map->qdErr = UpdateGWorld(&map->gworldPortPtr, 0,  &GWportRect, 0, 0, 0);

	/* Alert and close the map window if we ran out of memory */
	if (map->gworldPortPtr == NULL || map->qdErr != noErr ) {
		close_window(map->window);
		StopAlert(aNoMem, NULL);
		return;
	}

	/* Set window displacement trackers to zero */
	map->offsetx = map->offsety = 0;

	/* Do all drawing in the background */
	ValidRect(&map->contentrect);
	BeginUpdate(map->window);

	/* Redraw the map (in new position) */
	draw_map(map);

	/* Return viewport to the old position */
	map->vp->sx -= newsx - oldsx;
	map->vp->sy -= newsy - oldsy; 

	/* Adjust window displacement trackers */
	map->offsetx -= newsx - oldsx;
	map->offsety -= newsy - oldsy; 

	/* Restore old contentrect and draw scrollbars */
	set_content_rect(map);
	set_map_scrollbars(map);

	/* Show the result */
	EndUpdate(map->window);

	/* Finally update the screen using the new gworld */
	copy_from_gworld(map, map->contentrect);
}

/* Check if cell (x, y) is within the offscreen gworld of the current map */

int
cell_is_in_gworld(Map *map, int x, int y)
{
	Rect 	portrect = map->gworldPortPtr->portRect;
	int 	sx, sy;

	if (!in_area(x, y)) 
		return FALSE;   
	xform(map, x, y, &sx, &sy);
	if (sy + map->vp->hh + map->bufy < 0) 
		return FALSE;
	if (sy >  map->vp->pxh + 2 * map->bufy) 
		return FALSE;
	if (area.xwrap && map->vp->sxmax <= portrect.right - portrect.left)
		return TRUE;
	else if (sx + map->vp->hw + map->bufx < 0) 
		return FALSE;
	else if (sx >  map->vp->pxw + 2 * map->bufx) 
		return FALSE;
	return TRUE;
}

/* This function is called from handle_events. It enables a special use of the numeric keypad keys for 
   scrolling the map within its offscreen gworld. Returns TRUE if a numeric keypad key really was hit.
   Note: since numeric + and * double as arrow keys on antique Macs, the latter cannot zoom in or set
   the angle using these shortcuts. All other keypad shortcuts work as expected also on antique Macs. */

int
handle_numeric_keypad(EventRecord *event)
{
	int	pxh, pxw;
	Map *map;
	char key;

	/* Get the front map */
	map = front_map();

	/* Check keys by keyCode instead of charCode to identify numeric keypad events */
	key = (event->message & keyCodeMask) >> 8;

	/* Return FALSE if this is not a numeric keypad key (or if it is an arrow key on an antique Mac) */
	if (key < 0x41 || key > 0x5C || key == 0x42 || key == 0x46 || key == 0x48 || key == 0x4D)
	  return FALSE;

	/* Return TRUE and BEEP if the front window is not a map window */
	if (!map || map->window != FrontWindow()) {
		beep(); 
		return TRUE;
	}

	/* Moved here to stop crashes. */
	pxh = map->vp->pxh;
	pxw = map->vp->pxw;
	
	/* Make jumps reasonable size for small maps. */
	pxw = min(pxw, (area.width * map->vp->hw)/10);

	/* Scroll one full window if command key also was down */
	if (event->modifiers & cmdKey) {
		if (key == 0x56) { scroll_map_window(map, -pxw, 0); return TRUE; }		/* Keypad 4 */
		if (key == 0x58) { scroll_map_window(map, pxw, 0); return TRUE; }		/* Keypad 6 */
		if (key == 0x5B) { scroll_map_window(map, 0, -pxh); return TRUE; }		/* Keypad 8 */
		if (key == 0x54) { scroll_map_window(map, 0, pxh); return TRUE; }		/* Keypad 2 */

		if (key == 0x59) { scroll_map_window(map, -pxw, -pxh); return TRUE; }	/* Keypad 7 */
		if (key == 0x5C) { scroll_map_window(map, pxw, -pxh); return TRUE; }	/* Keypad 9 */
		if (key == 0x53) { scroll_map_window(map, -pxw, pxh); return TRUE; }	/* Keypad 1 */
		if (key == 0x55) { scroll_map_window(map, pxw, pxh); return TRUE; }		/* Keypad 3 */					

	/* Else either auto-scroll as long as the key is down, or change the center, scale or view angle  */
	} else {
		if (key == 0x56) { auto_scroll_left(map); return TRUE; }		/* Keypad 4 */
		if (key == 0x58) { auto_scroll_right(map); return TRUE; }		/* Keypad 6 */
		if (key == 0x5B) { auto_scroll_up(map); return TRUE; }		/* Keypad 8 */
		if (key == 0x54) { auto_scroll_down(map); return TRUE; }		/* Keypad 2 */

		if (key == 0x59) { auto_scroll_up_left(map); return TRUE; }	/* Keypad 7 */
		if (key == 0x5C) { auto_scroll_up_right(map); return TRUE; }	/* Keypad 9 */
		if (key == 0x53) { auto_scroll_down_left(map); return TRUE; }	/* Keypad 1 */
		if (key == 0x55) { auto_scroll_down_right(map); return TRUE; }	/* Keypad 3 */
		if (key == 0x57) { do_recenter(); return TRUE; }				/* Keypad 5 */
		if (key == 0x45) { do_mac_zoom_in(); return TRUE; }			/* Keypad + */
		if (key == 0x4E) { do_mac_zoom_out(); return TRUE; }			/* Keypad - */
		if (key == 0x43) { do_mac_set_map_angle(); return TRUE; }		/* Keypad * */

		if (Debug || DebugG || DebugM) {
			/* Take a snapshot of the gworld */
			if (key == 0x47) {
				copy_from_gworld(map, map->contentrect); 		/* Keypad CLEAR */
				return TRUE;
			}
			/* Enter the debugger */
			if (key == 0x4C) {Debugger(); return TRUE; }			/* Keypad ENTER */
		}
	}
	return FALSE;	/* Default FALSE permits normal use of unassigned numeric keypad keys */
}


/* The following auto_scroll functions bypass the main event loop for increased scrolling speeed. */

/* Scroll left as long as key is pressed */

void
auto_scroll_left(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, -4, 0);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x56 >> 3] >> (0x56 & 7) & 1;	/* keypad 4 */
	}
}

/* Scroll right as long as key is pressed. */

void
auto_scroll_right(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, 4, 0);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x58 >> 3] >> (0x58 & 7) & 1;	/* keypad 6 */
	}
}

/* Scroll up as long as key is pressed. */

void
auto_scroll_up(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, 0, -4);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x5B >> 3] >> (0x5B & 7) & 1;	/* keypad 8 */
	}
}

/* Scroll down as long as key is pressed. */

void
auto_scroll_down(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, 0, 4);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x54 >> 3] >> (0x54 & 7) & 1;	/* keypad 2 */
	}
}

/* Scroll down and left as long as key is pressed. */

void
auto_scroll_down_left(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, -4, 4);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x53 >> 3] >> (0x53 & 7) & 1;	/* keypad 1 */
	}
}

/* Scroll down and right as long as key is pressed. */

void
auto_scroll_down_right(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, 4, 4);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x55 >> 3] >> (0x55 & 7) & 1;	/* keypad 3 */
	}
}

/* Scroll up and left as long as key is pressed. */

void
auto_scroll_up_left(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, -4, -4);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x59 >> 3] >> (0x59 & 7) & 1;	/* keypad 7 */
	}
}

/* Scroll up and right as long as key is pressed. */

void
auto_scroll_up_right(Map *map)
{
	unsigned char keyMap[16];
	short keyDown = TRUE;

	while (keyDown) {
		scroll_map_window(map, 4, -4);
		GetKeys((long *) keyMap);
		keyDown = keyMap[0x5C >> 3] >> (0x5C & 7) & 1;	/* keypad 9 */
	}
}

/* Dialog that sets the size of the offscreen scrolling buffers. */

void
set_offscreen_buffers(Map *map)
{
	short ditem, itemtype, done = FALSE;
	long *itemnum = 0;
	Handle itemhandle;  
	Rect itemrect;
	Str255 tmpstr;
	DialogPtr win;

	win = GetNewDialog(dOffscreen, NULL, (DialogPtr) -1);

	GetDItem(win, diOffscreenHorizBuff, &itemtype, &itemhandle, &itemrect);
	NumToString(map->max_bufx, tmpstr);
	SetIText(itemhandle, tmpstr);

	GetDItem(win, diOffscreenVertiBuff, &itemtype, &itemhandle, &itemrect);
	NumToString(map->max_bufy, tmpstr);
	SetIText(itemhandle, tmpstr);
		
	ShowWindow(win);
	while (!done) {

		SetCursor(&QD(arrow));
		draw_default_button(win, diOffscreenOK);
		ModalDialog(NULL, &ditem);
		switch (ditem) {

			case diOffscreenOK:

				GetDItem(win, diOffscreenHorizBuff, &itemtype, &itemhandle, &itemrect);
	        			GetIText(itemhandle,tmpstr);
				StringToNum(tmpstr, itemnum);
				/* Dont allow negative values */
				map->max_bufx = max(*itemnum, 0);

				GetDItem(win, diOffscreenVertiBuff, &itemtype, &itemhandle, &itemrect);
	         			GetIText(itemhandle,tmpstr);
				StringToNum(tmpstr, itemnum);
				/* Dont allow negative values */
				map->max_bufy = max(*itemnum, 0);
				
				/* Redraw the gworld (and the map) */
				update_gworld(map);
				done = TRUE;
				break;

			case diOffscreenCancel:

				done = TRUE;
				break;

			default:
				break;
		}
	}
	DisposeDialog(win);

// --- FASTER UPDATES ---------------------------------------

	update_all_map_windows();
	
// -------------------------------------------------------

}

// --- NEW FUNCTIONS FOR FASTER UPDATE SUPPORT ---------------------------------

void
update_all_windows(void)
{
	WindowPtr win;
	
	for_all_windows(win) { 
		update_window(win);
	}
}

void
update_all_map_windows(void)
{
	Map *map;
	
	for_all_maps(map) {
		update_window(map->window);
	}
}

void
update_all_visible_windows(void)
{
	WindowPtr win;
	
	for_all_windows(win) {
		if (((WindowPeek) win)->visible)
			update_window(win);
	}
}

void
update_all_visible_map_windows(void)
{
	Map *map;
	
	for_all_maps(map) {
		if (((WindowPeek)map->window)->visible)
			update_window(map->window);
	}
}