-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTESample.c
executable file
·1547 lines (1284 loc) · 50.1 KB
/
TESample.c
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
#include <Types.h>
#include <limits.h>
#include <Quickdraw.h>
#include <Fonts.h>
#include <Events.h>
#include <Controls.h>
#include <Windows.h>
#include <ControlDefinitions.h>
#include <Menus.h>
#include <TextEdit.h>
#include <Dialogs.h>
#include <Devices.h>
#include <Scrap.h>
#include <Sound.h>
#include <ToolUtils.h>
#include <Memory.h>
#include <SegLoad.h>
#include <Files.h>
#include <OSUtils.h>
#include <DiskInit.h>
#include <Packages.h>
#include "TESample.h" /* bring in all the #defines for TESample */
#include <Traps.h>
#include <stdlib.h>
#include "output_js.h"
#include "SerialHelper.h"
#include "coprocessorjs.h"
#define MAX_RECEIVE_SIZE 32767
// #define DEBUGGING 1
void AlertUser( short error );
void ShowIPAddresses();
void EventLoop( void );
void DoEvent( EventRecord *event );
void AdjustCursor( Point mouse, RgnHandle region );
void GetGlobalMouse( Point *mouse );
void DoGrowWindow( WindowPtr window, EventRecord *event );
void DoZoomWindow( WindowPtr window, short part );
void _ResizeWindow( WindowPtr window );
void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
void DoUpdate( WindowPtr window );
void DoDeactivate( WindowPtr window );
void DoActivate( WindowPtr window, Boolean becomingActive );
void DoContentClick( WindowPtr window, EventRecord *event );
void DoKeyDown( EventRecord *event );
unsigned long GetSleep( void );
void CommonAction( ControlHandle control, short *amount );
pascal void VActionProc( ControlHandle control, short part );
pascal void HActionProc( ControlHandle control, short part );
void DoIdle( void );
void DrawWindow( WindowPtr window );
void AdjustMenus( void );
void DoMenuCommand( long menuResult );
void DoNew( void );
Boolean DoCloseWindow( WindowPtr window );
void Terminate( void );
void Initialize( void );
void BigBadError( short error );
void GetTERect( WindowPtr window, Rect *teRect );
void AdjustViewRect( TEHandle docTE );
void AdjustTE( WindowPtr window );
void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
Boolean canRedraw );
void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
void AdjustScrollSizes( WindowPtr window );
void AdjustScrollbars( WindowPtr window, Boolean needsResize );
pascal void PascalClickLoop();
pascal TEClickLoopUPP GetOldClickLoop();
Boolean IsAppWindow( WindowPtr window );
Boolean IsDAWindow( WindowPtr window );
Boolean TrapAvailable( short tNumber, TrapType tType );
long int callIndex = 0L;
int globalSelStart = 0;
int globalSelEnd = 0;
/* The "g" prefix is used to emphasize that a variable is global. */
/* GMac is used to hold the result of a SysEnvirons call. This makes
it convenient for any routine to check the environment. It is
global information, anyway. */
SysEnvRec gMac; /* set up by Initialize */
/* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
trap is available. If it is false, we know that we must call GetNextEvent. */
Boolean gHasWaitNextEvent; /* set up by Initialize */
/* GInBackground is maintained by our OSEvent handling routines. Any part of
the program can check it to find out if it is currently in the background. */
Boolean gInBackground; /* maintained by Initialize and DoEvent */
/* GNumDocuments is used to keep track of how many open documents there are
at any time. It is maintained by the routines that open and close documents. */
short gNumDocuments; /* maintained by Initialize, DoNew, and DoCloseWindow */
/* Define TopLeft and BotRight macros for convenience. Notice the implicit
dependency on the ordering of fields within a Rect */
#define TopLeft(aRect) (* (Point *) &(aRect).top)
#define BotRight(aRect) (* (Point *) &(aRect).bottom)
/* A DocumentRecord contains the WindowRecord for one of our document windows,
as well as the TEHandle for the text we are editing. Other document fields
can be added to this record as needed. For a similar example, see how the
Window Manager and Dialog Manager add fields after the GrafPort. */
typedef struct {
WindowRecord docWindow;
TEHandle docTE;
ControlHandle docVScroll;
ControlHandle docHScroll;
TEClickLoopUPP docClick;
} DocumentRecord, *DocumentPeek;
/* Set up the whole world, including global variables, Toolbox managers,
menus, and a single blank document. */
/* 1.01 - The code that used to be part of ForceEnvirons has been moved into
this module. If an error is detected, instead of merely doing an ExitToShell,
which leaves the user without much to go on, we call AlertUser, which puts
up a simple alert that just says an error occurred and then calls ExitToShell.
Since there is no other cleanup needed at this point if an error is detected,
this form of error- handling is acceptable. If more sophisticated error recovery
is needed, an exception mechanism, such as is provided by Signals, can be used. */
void Initialize()
{
Handle menuBar;
long total, contig;
EventRecord event;
short count;
gInBackground = false;
InitGraf((Ptr) &qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(nil);
InitCursor();
/* Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
if you are using it. */
/* NOTE -- It is no longer necessary, and actually unhealthy, to check
PortBUse and SPConfig before opening AppleTalk. The drivers are capable
of checking for port availability themselves. */
/* This next bit of code is necessary to allow the default button of our
alert be outlined.
1.02 - Changed to call EventAvail so that we don't lose some important
events. */
for (count = 1; count <= 3; count++) {
EventAvail(everyEvent, &event);
}
/* Ignore the error returned from SysEnvirons; even if an error occurred,
the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
call to SysEnvirons by calling it after initializing AppleTalk. */
SysEnvirons(kSysEnvironsVersion, &gMac);
/* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
if (gMac.machineType < 0) BigBadError(eWrongMachine);
/* 1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
in TrapAvailable if a tool trap value is out of range. */
gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
/* 1.01 - We used to make a check for memory at this point by examining ApplLimit,
ApplicationZone, and StackSpace and comparing that to the minimum size we told
MultiFinder we needed. This did not work well because it assumed too much about
the relationship between what we asked MultiFinder for and what we would actually
get back, as well as how to measure it. Instead, we will use an alternate
method comprised of two steps. */
/* It is better to first check the size of the application heap against a value
that you have determined is the smallest heap the application can reasonably
work in. This number should be derived by examining the size of the heap that
is actually provided by MultiFinder when the minimum size requested is used.
The derivation of the minimum size requested from MultiFinder is described
in Sample.h. The check should be made because the preferred size can end up
being set smaller than the minimum size by the user. This extra check acts to
insure that your application is starting from a solid memory foundation. */
if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) BigBadError(eSmallSize);
// /* Next, make sure that enough memory is free for your application to run. It
// is possible for a situation to arise where the heap may have been of required
// size, but a large scrap was loaded which left too little memory. To check for
// this, call PurgeSpace and compare the result with a value that you have determined
// is the minimum amount of free memory your application needs at initialization.
// This number can be derived several different ways. One way that is fairly
// straightforward is to run the application in the minimum size configuration
// as described previously. Call PurgeSpace at initialization and examine the value
// returned. However, you should make sure that this result is not being modified
// by the scrap's presence. You can do that by calling ZeroScrap before calling
// PurgeSpace. Make sure to remove that call before shipping, though. */
// /* ZeroScrap(); */
PurgeSpace(&total, &contig);
if (total < kMinSpace) {
if (UnloadScrap() != noErr)
BigBadError(eNoMemory);
else {
PurgeSpace(&total, &contig);
if (total < kMinSpace)
BigBadError(eNoMemory);
}
}
/* The extra benefit to waiting until after the Toolbox Managers have been initialized
to check memory is that we can now give the user an alert to tell him/her what
happened. Although it is possible that the memory situation could be worsened by
displaying an alert, MultiFinder would gracefully exit the application with
an informative alert if memory became critical. Here we are acting more
in a preventative manner to avoid future disaster from low-memory problems. */
menuBar = GetNewMBar(rMenuBar); /* read menus into menu bar */
if ( menuBar == nil )
BigBadError(eNoMemory);
SetMenuBar(menuBar); /* install menus */
DisposeHandle(menuBar);
AppendResMenu(GetMenuHandle(mApple), 'DRVR'); /* add DA names to Apple menu */
DrawMenuBar();
gNumDocuments = 0;
/* do other initialization here */
DoNew(); /* create a single empty document */
} /*Initialize*/
/* Used whenever a, like, fully fatal error happens */
void BigBadError(short error)
{
AlertUser(error);
ExitToShell();
}
/* Check to see if a given trap is implemented. This is only used by the
Initialize routine in this program, so we put it in the Initialize segment.
The recommended approach to see if a trap is implemented is to see if
the address of the trap routine is the same as the address of the
Unimplemented trap. */
/* 1.02 - Needs to be called after call to SysEnvirons so that it can check
if a ToolTrap is out of range of a pre-MacII ROM. */
Boolean TrapAvailable(short tNumber, TrapType tType)
{
if ( ( tType == (unsigned char) ToolTrap ) &&
( gMac.machineType > envMachUnknown ) &&
( gMac.machineType < envMacII ) ) { /* it's a 512KE, Plus, or SE */
tNumber = tNumber & 0x03FF;
if ( tNumber > 0x01FF ) /* which means the tool traps */
tNumber = _Unimplemented; /* only go to 0x01FF */
}
return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, ToolTrap);
} /*TrapAvailable*/
int main()
{
// MaxApplZone(); // this seems to entirely break the program within the coprocessor code
Initialize(); /* initialize the program */
UnloadSeg((Ptr) Initialize); /* note that Initialize must not be in Main! */
setupDebugSerialPort(boutRefNum);
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "initializing focusededit");
#endif
SysBeep(1);
AdjustScrollSizes(FrontWindow());
EventLoop(); /* call the main event loop */
}
char nextTextBuffer[MAX_RECEIVE_SIZE];
char lastTextBuffer[MAX_RECEIVE_SIZE];
void pullText() {
if (asyncCallActive) {
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "async call active, refusing to pull text");
#endif
return;
}
Rect teRect;
DocumentPeek doc;
WindowPtr window;
window = FrontWindow();
doc = (DocumentPeek) (window);
TEHandle te = (doc)->docTE;
GetTERect(window, &teRect);
callFunctionOnCoprocessor("getBuffer", "", nextTextBuffer);
if (strcmp(nextTextBuffer, lastTextBuffer) == 0) {
return;
}
EraseRect(&window->portRect);
TESetText(nextTextBuffer, strlen(nextTextBuffer), te);
TEUpdate(&teRect, te);
strcpy(lastTextBuffer, nextTextBuffer);
}
/* Get events forever, and handle them by calling DoEvent.
Also call AdjustCursor each time through the loop. */
void EventLoop()
{
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "DEBUG_FUNCTION_CALLS: EventLoop");
#endif
int lastPulledText = 0;
RgnHandle cursorRgn;
Boolean gotEvent;
EventRecord event;
Point mouse;
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "setting up coprocessor");
#endif
setupCoprocessor("focusededit", "modem"); // could also be "printer", modem is 0 in PCE settings - printer would be 1
char programResult[256];
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "sending to coprocessor");
#endif
sendProgramToCoprocessor((char *)OUTPUT_JS, programResult);
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "program sent to coprocessor!");
#endif
cursorRgn = NewRgn(); /* we�ll pass WNE an empty region the 1st time thru */
do {
if (TickCount() - lastPulledText > 500) {
pullText();
lastPulledText = TickCount();
}
/* use WNE if it is available */
if ( gHasWaitNextEvent ) {
GetGlobalMouse(&mouse);
AdjustCursor(mouse, cursorRgn);
gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
} else {
SystemTask();
gotEvent = GetNextEvent(everyEvent, &event);
}
if ( gotEvent ) {
/* make sure we have the right cursor before handling the event */
AdjustCursor(event.where, cursorRgn);
DoEvent(&event);
// make sure we don't try to pull text if the user is actively using the application
lastPulledText = TickCount();
} else {
DoIdle();
coprocessorEventLoopActions();
/* perform idle tasks when it�s not our event */
/* If you are using modeless dialogs that have editText items,
you will want to call IsDialogEvent to give the caret a chance
to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
for a non-NIL value before calling IsDialogEvent. */
}
} while ( true ); /* loop forever; we quit via ExitToShell */
} /*EventLoop*/
/* Do the right thing for an event. Determine what kind of event it is, and call
the appropriate routines. */
void DoEvent(EventRecord *event)
{
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "DEBUG_FUNCTION_CALLS: EventLoop");
#endif
short part;
// short err;
WindowPtr window;
char key;
Point aPoint;
switch ( event->what ) {
case nullEvent:
/* we idle for null/mouse moved events ands for events which aren�t
ours (see EventLoop) */
DoIdle();
break;
case mouseDown:
part = FindWindow(event->where, &window);
switch ( part ) {
case inMenuBar: /* process a mouse menu command (if any) */
AdjustMenus(); /* bring �em up-to-date */
DoMenuCommand(MenuSelect(event->where));
break;
case inSysWindow: /* let the system handle the mouseDown */
SystemClick(event, window);
break;
case inContent:
if ( window != FrontWindow() ) {
SelectWindow(window);
/*DoEvent(event);*/ /* use this line for "do first click" */
} else
DoContentClick(window, event);
break;
case inDrag: /* pass screenBits.bounds to get all gDevices */
DragWindow(window, event->where, &qd.screenBits.bounds);
break;
case inGoAway:
if ( TrackGoAway(window, event->where) )
DoCloseWindow(window); /* we don�t care if the user cancelled */
break;
case inGrow:
DoGrowWindow(window, event);
break;
case inZoomIn:
case inZoomOut:
if ( TrackBox(window, event->where, part) )
DoZoomWindow(window, part);
break;
}
break;
case keyDown:
case autoKey: /* check for menukey equivalents */
key = event->message & charCodeMask;
if ( event->modifiers & cmdKey ) { /* Command key down */
if ( event->what == keyDown ) {
AdjustMenus(); /* enable/disable/check menu items properly */
DoMenuCommand(MenuKey(key));
}
} else
DoKeyDown(event);
break;
case activateEvt:
DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
break;
case updateEvt:
DoUpdate((WindowPtr) event->message);
break;
/* 1.01 - It is not a bad idea to at least call DIBadMount in response
to a diskEvt, so that the user can format a floppy. */
case diskEvt:
if ( HiWord(event->message) != noErr ) {
SetPt(&aPoint, kDILeft, kDITop);
// err = DIBadMount(aPoint, event->message);
}
break;
case kOSEvent:
/* 1.02 - must BitAND with 0x0FF to get only low byte */
switch ((event->message >> 24) & 0x0FF) { /* high byte of message */
case kMouseMovedMessage:
DoIdle(); /* mouse-moved is also an idle event */
break;
case kSuspendResumeMessage: /* suspend/resume is also an activate/deactivate */
gInBackground = (event->message & kResumeMask) == 0;
DoActivate(FrontWindow(), !gInBackground);
break;
}
break;
}
} /*DoEvent*/
/* Change the cursor's shape, depending on its position. This also calculates the region
where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
this region, an event is generated. If there is more to the event than just
�the mouse moved�, we get called before the event is processed to make sure
the cursor is the right one. In any (ahem) event, this is called again before we
fall back into WNE. */
void AdjustCursor(Point mouse, RgnHandle region)
{
WindowPtr window;
RgnHandle arrowRgn;
RgnHandle iBeamRgn;
Rect iBeamRect;
window = FrontWindow(); /* we only adjust the cursor when we are in front */
if ( (! gInBackground) && (! IsDAWindow(window)) ) {
/* calculate regions for different cursor shapes */
arrowRgn = NewRgn();
iBeamRgn = NewRgn();
/* start arrowRgn wide open */
SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
/* calculate iBeamRgn */
if ( IsAppWindow(window) ) {
iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
SetPort(window); /* make a global version of the viewRect */
LocalToGlobal(&TopLeft(iBeamRect));
LocalToGlobal(&BotRight(iBeamRect));
RectRgn(iBeamRgn, &iBeamRect);
/* we temporarily change the port�s origin to �globalfy� the visRgn */
SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
SetOrigin(0, 0);
}
/* subtract other regions from arrowRgn */
DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
/* change the cursor and the region parameter */
if ( PtInRgn(mouse, iBeamRgn) ) {
SetCursor(*GetCursor(iBeamCursor));
CopyRgn(iBeamRgn, region);
} else {
SetCursor(&qd.arrow);
CopyRgn(arrowRgn, region);
}
DisposeRgn(arrowRgn);
DisposeRgn(iBeamRgn);
}
} /*AdjustCursor*/
/* Get the global coordinates of the mouse. When you call OSEventAvail
it will return either a pending event or a null event. In either case,
the where field of the event record will contain the current position
of the mouse in global coordinates and the modifiers field will reflect
the current state of the modifiers. Another way to get the global
coordinates is to call GetMouse and LocalToGlobal, but that requires
being sure that thePort is set to a valid port. */
void GetGlobalMouse(Point *mouse)
{
EventRecord event;
OSEventAvail(kNoEvents, &event); /* we aren't interested in any events */
*mouse = event.where; /* just the mouse position */
} /*GetGlobalMouse*/
/* Called when a mouseDown occurs in the grow box of an active window. In
order to eliminate any 'flicker', we want to invalidate only what is
necessary. Since _ResizeWindow invalidates the whole portRect, we save
the old TE viewRect, intersect it with the new TE viewRect, and
remove the result from the update region. However, we must make sure
that any old update region that might have been around gets put back. */
void DoGrowWindow(WindowPtr window, EventRecord *event)
{
long growResult;
Rect tempRect;
RgnHandle tempRgn;
DocumentPeek doc;
tempRect = qd.screenBits.bounds; /* set up limiting values */
tempRect.left = kMinDocDim;
tempRect.top = kMinDocDim;
growResult = GrowWindow(window, event->where, &tempRect);
/* see if it really changed size */
if ( growResult != 0 ) {
doc = (DocumentPeek) window;
tempRect = (*doc->docTE)->viewRect; /* save old text box */
tempRgn = NewRgn();
GetLocalUpdateRgn(window, tempRgn); /* get localized update region */
SizeWindow(window, LoWord(growResult), HiWord(growResult), true);
_ResizeWindow(window);
/* calculate & validate the region that hasn�t changed so it won�t get redrawn */
SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
ValidRect(&tempRect); /* take it out of update */
InvalRgn(tempRgn); /* put back any prior update */
DisposeRgn(tempRgn);
}
} /* DoGrowWindow */
/* Called when a mouseClick occurs in the zoom box of an active window.
Everything has to get re-drawn here, so we don't mind that
_ResizeWindow invalidates the whole portRect. */
void DoZoomWindow(WindowPtr window, short part)
{
EraseRect(&window->portRect);
ZoomWindow(window, part, window == FrontWindow());
_ResizeWindow(window);
} /* DoZoomWindow */
/* Called when the window has been resized to fix up the controls and content. */
void _ResizeWindow(WindowPtr window)
{
AdjustScrollbars(window, true);
AdjustTE(window);
InvalRect(&window->portRect);
} /* _ResizeWindow */
/* Returns the update region in local coordinates */
void GetLocalUpdateRgn(WindowPtr window, RgnHandle localRgn)
{
CopyRgn(((WindowPeek) window)->updateRgn, localRgn); /* save old update region */
OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
} /* GetLocalUpdateRgn */
/* This is called when an update event is received for a window.
It calls DrawWindow to draw the contents of an application window.
As an efficiency measure that does not have to be followed, it
calls the drawing routine only if the visRgn is non-empty. This
will handle situations where calculations for drawing or drawing
itself is very time-consuming. */
void DoUpdate(WindowPtr window)
{
if ( IsAppWindow(window) ) {
BeginUpdate(window); /* this sets up the visRgn */
if ( ! EmptyRgn(window->visRgn) ) /* draw if updating needs to be done */
DrawWindow(window);
EndUpdate(window);
}
} /*DoUpdate*/
/* This is called when a window is activated or deactivated.
It calls TextEdit to deal with the selection. */
void DoActivate(WindowPtr window, Boolean becomingActive)
{
RgnHandle tempRgn, clipRgn;
Rect growRect;
DocumentPeek doc;
if ( IsAppWindow(window) ) {
doc = (DocumentPeek) window;
if ( becomingActive ) {
/* since we don�t want TEActivate to draw a selection in an area where
we�re going to erase and redraw, we�ll clip out the update region
before calling it. */
tempRgn = NewRgn();
clipRgn = NewRgn();
GetLocalUpdateRgn(window, tempRgn); /* get localized update region */
GetClip(clipRgn);
DiffRgn(clipRgn, tempRgn, tempRgn); /* subtract updateRgn from clipRgn */
SetClip(tempRgn);
TEActivate(doc->docTE);
SetClip(clipRgn); /* restore the full-blown clipRgn */
DisposeRgn(tempRgn);
DisposeRgn(clipRgn);
/* the controls must be redrawn on activation: */
(*doc->docVScroll)->contrlVis = kControlVisible;
(*doc->docHScroll)->contrlVis = kControlVisible;
InvalRect(&(*doc->docVScroll)->contrlRect);
InvalRect(&(*doc->docHScroll)->contrlRect);
/* the growbox needs to be redrawn on activation: */
growRect = window->portRect;
/* adjust for the scrollbars */
growRect.top = growRect.bottom - kScrollbarAdjust;
growRect.left = growRect.right - kScrollbarAdjust;
InvalRect(&growRect);
}
else {
TEDeactivate(doc->docTE);
/* the controls must be hidden on deactivation: */
HideControl(doc->docVScroll);
HideControl(doc->docHScroll);
/* the growbox should be changed immediately on deactivation: */
DrawGrowIcon(window);
}
}
} /*DoActivate*/
/* This is called when a mouseDown occurs in the content of a window. */
void DoContentClick(WindowPtr window, EventRecord *event)
{
Point mouse;
ControlHandle control;
short part, value;
Boolean shiftDown;
DocumentPeek doc;
Rect teRect;
TEHandle te;
if ( IsAppWindow(window) ) {
SetPort(window);
mouse = event->where; /* get the click position */
GlobalToLocal(&mouse);
doc = (DocumentPeek) window;
/* see if we are in the viewRect. if so, we won�t check the controls */
GetTERect(window, &teRect);
if ( PtInRect(mouse, &teRect) ) {
/* see if we need to extend the selection */
shiftDown = (event->modifiers & shiftKey) != 0; /* extend if Shift is down */
TEClick(mouse, shiftDown, doc->docTE);
te = ((DocumentPeek) window)->docTE;
globalSelStart = (*te)->selStart;
globalSelEnd = (*te)->selEnd;
} else {
part = FindControl(mouse, window, &control);
switch ( part ) {
case 0: /* do nothing for viewRect case */
break;
case kControlIndicatorPart:
value = GetControlValue(control);
part = TrackControl(control, mouse, nil);
if ( part != 0 ) {
value -= GetControlValue(control);
/* value now has CHANGE in value; if value changed, scroll */
if ( value != 0 ) {
if ( control == doc->docVScroll )
TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
else
TEScroll(value, 0, doc->docTE);
}
}
break;
default: /* they clicked in an arrow, so track & scroll */
{
ControlActionUPP upp;
if ( control == doc->docVScroll )
upp = NewControlActionProc(VActionProc);
else
upp = NewControlActionProc(HActionProc);
value = TrackControl(control, mouse, upp);
DisposeRoutineDescriptor(upp);
}
break;
}
}
}
} /*DoContentClick*/
/* This is called for any keyDown or autoKey events, except when the
Command key is held down. It looks at the frontmost window to decide what
to do with the key typed. */
void emptyCallback(char *output) {
#ifdef DEBUGGING
writeSerialPortDebug(boutRefNum, "emptyCallback\n");
writeSerialPortDebug(boutRefNum, output);
#endif
SetCursor(*GetCursor(plusCursor));
}
void DoKeyDown(EventRecord *event)
{
WindowPtr window;
char key;
TEHandle te;
window = FrontWindow();
if (IsAppWindow(window)) {
te = ((DocumentPeek) window)->docTE;
key = event->message & charCodeMask;
/* we have a char. for our window; see if we are still below TextEdit�s
limit for the number of characters (but deletes are always rad) */
if (key != kDelChar && (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 > kMaxTELength) {
AlertUser(eExceedChar);
return;
}
if ((key < 28 || key > 127) && key != 8 && key != 13) {
return;
}
// this is the delete key, doesn't seem to be respected in the TEKey event properly
// instead our strategy is to convert to a backspace, then advance the cursor 1 character
// and then run the key through the rest of the function
if (key == 127) {
key = 8;
if ((*te)->selEnd == (*te)->selStart) {
(*te)->selStart++;
(*te)->selEnd++;
globalSelStart++;
globalSelEnd++;
}
}
TEKey(key, te);
AdjustScrollbars(window, false);
AdjustTE(window);
char output[32];
sprintf(output, "%d&&&%d&&&%d&&&%ld", key, globalSelStart, globalSelEnd, callIndex++);
// handle updating the global selection tracker to the selection AFTER the key is pressed
// otherwise our selStart/selEnd will always just be a single point
globalSelStart = (*te)->selStart;
globalSelEnd = (*te)->selEnd;
#ifdef DEBUGGING
char debugOutput[255];
sprintf(debugOutput, "output to serial port %s, char code for input was %d", output, key);
writeSerialPortDebug(boutRefNum, debugOutput);
#endif
callVoidFunctionOnCoprocessorAsync("insertStringToBuffer", output);
return;
}
} /*DoKeyDown*/
/* Calculate a sleep value for WaitNextEvent. This takes into account the things
that DoIdle does with idle time. */
unsigned long GetSleep()
{
long sleep;
WindowPtr window;
TEHandle te;
sleep = LONG_MAX; /* default value for sleep */
if ( !gInBackground ) {
window = FrontWindow(); /* and the front window is ours... */
if ( IsAppWindow(window) ) {
te = ((DocumentPeek) (window))->docTE; /* and the selection is an insertion point... */
if ( (*te)->selStart == (*te)->selEnd )
sleep = GetCaretTime(); /* blink time for the insertion point */
}
}
return sleep;
} /*GetSleep*/
/* Common algorithm for pinning the value of a control. It returns the actual amount
the value of the control changed. Note the pinning is done for the sake of returning
the amount the control value changed. */
void CommonAction(ControlHandle control, short *amount)
{
short value, max;
value = GetControlValue(control); /* get current value */
max = GetControlMaximum(control); /* and maximum value */
*amount = value - *amount;
if ( *amount < 0 )
*amount = 0;
else if ( *amount > max )
*amount = max;
SetControlValue(control, *amount);
*amount = value - *amount; /* calculate the real change */
} /* CommonAction */
/* Determines how much to change the value of the vertical scrollbar by and how
much to scroll the TE record. */
pascal void VActionProc(ControlHandle control, short part)
{
short amount = 0;
WindowPtr window;
TEPtr te;
if ( part != 0 ) { /* if it was actually in the control */
window = (*control)->contrlOwner;
te = *((DocumentPeek) window)->docTE;
switch ( part ) {
case kControlUpButtonPart:
case kControlDownButtonPart: /* one line */
amount = 1;
break;
case kControlPageUpPart: /* one page */
case kControlPageDownPart:
amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
break;
}
if ( (part == kControlDownButtonPart) || (part == kControlPageDownPart) )
amount = -amount; /* reverse direction for a downer */
CommonAction(control, &amount);
if ( amount != 0 )
TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
}
} /* VActionProc */
/* Determines how much to change the value of the horizontal scrollbar by and how
much to scroll the TE record. */
pascal void HActionProc(ControlHandle control, short part)
{
short amount = 0;
WindowPtr window;
TEPtr te;
if ( part != 0 ) {
window = (*control)->contrlOwner;
te = *((DocumentPeek) window)->docTE;
switch ( part ) {
case kControlUpButtonPart:
case kControlDownButtonPart: /* a few pixels */
amount = kButtonScroll;
break;
case kControlPageUpPart: /* a page */
case kControlPageDownPart:
amount = te->viewRect.right - te->viewRect.left;
break;
}
if ( (part == kControlDownButtonPart) || (part == kControlPageDownPart) )
amount = -amount; /* reverse direction */
CommonAction(control, &amount);
if ( amount != 0 )
TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
}
} /* VActionProc */
/* This is called whenever we get a null event et al.
It takes care of necessary periodic actions. For this program, it calls TEIdle. */
void DoIdle()
{
WindowPtr window;
window = FrontWindow();
if ( IsAppWindow(window) )
TEIdle(((DocumentPeek) window)->docTE);
} /*DoIdle*/
/* Draw the contents of an application window. */
void DrawWindow(WindowPtr window)
{
SetPort(window);
EraseRect(&window->portRect);
DrawControls(window);
DrawGrowIcon(window);
TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
} /*DrawWindow*/
/* Enable and disable menus based on the current state.
The user can only select enabled menu items. We set up all the menu items
before calling MenuSelect or MenuKey, since these are the only times that
a menu item can be selected. Note that MenuSelect is also the only time
the user will see menu items. This approach to deciding what enable/
disable state a menu item has the advantage of concentrating all
the decision-making in one routine, as opposed to being spread throughout
the application. Other application designs may take a different approach
that may or may not be as valid. */
void AdjustMenus()
{
WindowPtr window;
MenuHandle menu;
long offset;
Boolean undo;
Boolean cutCopyClear;
Boolean paste;
TEHandle te;
window = FrontWindow();
menu = GetMenuHandle(mFile);