home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 November: Tool Chest / Dev.CD Nov 94.toast / Sample Code / Macintosh Sample Code / SC.002.TESample / TESample.p < prev    next >
Encoding:
Text File  |  1992-06-04  |  50.7 KB  |  1,582 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    TESample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                06/92
  20. #
  21. #    Components:
  22. #                TESample.p            June 1, 1989
  23. #                TESample.c            June 1, 1989
  24. #                TESampleInit.c        June 4, 1992
  25. #                TESampleGlue.a        June 1, 1989
  26. #                TESample.r            June 1, 1989
  27. #                TESample.h            June 1, 1989
  28. #                PTESample.make        June 1, 1989
  29. #                CTESample.make        June 1, 1989
  30. #                TCTESample.π        June 4, 1992
  31. #                TCTESample.π.rsrc    June 4, 1992
  32. #                TCTESampleGlue.c    June 4, 1992
  33. #
  34. #    TESample is an example application that demonstrates how 
  35. #    to initialize the commonly used toolbox managers, operate 
  36. #    successfully under MultiFinder, handle desk accessories and 
  37. #    create, grow, and zoom windows. The fundamental TextEdit 
  38. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  39. #    also shows how to create and maintain scrollbar controls.
  40. #
  41. #    It does not by any means demonstrate all the techniques you 
  42. #    need for a large application. In particular, Sample does not 
  43. #    cover exception handling, multiple windows/documents, 
  44. #    sophisticated memory management, printing, or undo. All of 
  45. #    these are vital parts of a normal full-sized application.
  46. #
  47. #    This application is an example of the form of a Macintosh 
  48. #    application; it is NOT a template. It is NOT intended to be 
  49. #    used as a foundation for the next world-class, best-selling, 
  50. #    600K application. A stick figure drawing of the human body may 
  51. #    be a good example of the form for a painting, but that does not 
  52. #    mean it should be used as the basis for the next Mona Lisa.
  53. #
  54. #    We recommend that you review this program or Sample before 
  55. #    beginning a new application. Sample is a simple app. which doesn’t 
  56. #    use TextEdit or the Control Manager.
  57. #
  58. ------------------------------------------------------------------------------}
  59.  
  60.  
  61. PROGRAM TESample;
  62.  
  63.  
  64. {Segmentation strategy:
  65.  
  66.  This program consists of three segments. Main contains most of the code,
  67.  including the MPW libraries, and the main program. Initialize contains
  68.  code that is only used once, during startup, and can be unloaded after the
  69.  program starts. %A5Init is automatically created by the Linker to initialize
  70.  globals for the MPW libraries and is unloaded right away.}
  71.  
  72.  
  73. {SetPort strategy:
  74.  
  75.  Toolbox routines do not change the current port. In spite of this, in this
  76.  program we use a strategy of calling SetPort whenever we want to draw or
  77.  make calls which depend on the current port. This makes us less vulnerable
  78.  to bugs in other software which might alter the current port (such as the
  79.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  80.  Hopefully, this also makes the routines from this program more self-contained,
  81.  since they don't depend on the current port setting.}
  82.  
  83.  
  84. {Clipboard strategy:
  85.  
  86.  This program does not maintain a private scrap. Whenever a cut, copy, or paste
  87.  occurs, we import/export from the public scrap to TextEdit's scrap right away,
  88.  using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  89.  the import/export would be in the activate/deactivate event and suspend/resume
  90.  event routines.}
  91.  
  92. {$D+}
  93.  
  94. USES
  95.     MemTypes, QuickDraw, OSIntf, ToolIntf, PackIntf, Traps;
  96.  
  97.  
  98. CONST
  99.     {MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  100.      These constants are from that file.}
  101.     {1.02 - Uses Traps.p to obtain trap numbers.}
  102.  
  103.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  104.     {kTextMargin is the number of pixels we leave blank at the edge of the window.}
  105.     kTextMargin                = 2;
  106.  
  107.     {kMaxOpenDocuments is used to determine whether a new document can be opened
  108.      or created. We keep track of the number of open documents, and disable the
  109.      menu items that create a new document when the maximum is reached. If the
  110.      number of documents falls below the maximum, the items are enabled again.}
  111.     kMaxOpenDocuments        = 1;
  112.     
  113.     {kMaxDocWidth is an arbitrary number used to specify the width of the TERec's
  114.     destination rectangle so that word wrap and horizontal scrolling can be
  115.     demonstrated.}
  116.     kMaxDocWidth            = 576;
  117.     
  118.     {kMinDocDim is used to limit the minimum dimension of a window when GrowWindow
  119.     is called.}
  120.     kMinDocDim                = 64;
  121.     
  122.     {kControlInvisible is used to 'turn off' controls (i.e., cause the control not
  123.     to be redrawn as a result of some Control Manager call such as SetCtlValue)
  124.     by being put into the contrlVis field of the record. kControlVisible is used
  125.     the same way to 'turn on' the control.}
  126.     kControlInvisible        = 0;
  127.     kControlVisible            = $FF;
  128.     
  129.     {kScrollBarAdjust and kScrollBarWidth are used in calculating
  130.     values for control positioning and sizing.}
  131.     kScrollbarWidth            = 16;
  132.     kScrollbarAdjust        = kScrollbarWidth - 1;
  133.     
  134.     {kScrollTweek compensates for off-by-one requirements of the scrollbars
  135.      to have borders coincide with the growbox.}
  136.     kScrollTweek            = 2;
  137.     
  138.     {kCrChar is used to match with a carriage return when calculating the
  139.     number of lines in the TextEdit record. kDelChar is used to check for
  140.     delete in keyDowns.}
  141.     kCRChar                    = 13;
  142.     kDelChar                = 8;
  143.     
  144.     {kButtonScroll is how many pixels to scroll horizontally when the button part
  145.     of the horizontal scrollbar is pressed.}
  146.     kButtonScroll            = 4;
  147.     
  148.     {kMaxTELength is an arbitrary number used to limit the length of text in the TERec
  149.     so that various errors won't occur from too many characters in the text.}
  150.     kMaxTELength            = 32000;
  151.  
  152.     {kSysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  153.      SysEnvRec we understand.}
  154.     kSysEnvironsVersion        = 1;
  155.  
  156.     {kOSEvent is the event number of the suspend/resume and mouse-moved events sent
  157.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  158.      high byte of the message sent to determine which kind it is. To differentiate
  159.      suspend and resume events we check the resumeMask bit.}
  160.     kOSEvent                = app4Evt;    {event used by MultiFinder}
  161.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  162.     kResumeMask                = 1;        {bit of message field for resume vs. suspend}
  163.     kMouseMovedMessage        = $FA;        {high byte of mouse-moved event message}
  164.     kNoEvents                = 0;        {no events mask}
  165.  
  166.     {1.01 - kMinHeap - This is the minimum result from the following
  167.      equation:
  168.             
  169.             ORD(GetApplLimit) - ORD(ApplicZone)
  170.             
  171.      for the application to run. It will insure that enough memory will
  172.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  173.      application, and still give the application some 'breathing room'.
  174.      To derive this number, we ran under a MultiFinder partition that was
  175.      our requested minimum size, as given in the 'SIZE' resource.}
  176.      
  177.     kMinHeap    = 29 * 1024;
  178.     
  179.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  180.      at initialization time, for the application to run. This number acts
  181.      as a double-check to insure that there really is enough memory for the
  182.      application to run, including what has been taken up already by
  183.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  184.      
  185.     kMinSpace    = 20 * 1024;
  186.     
  187.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  188.     kExtremeNeg        = -32768;
  189.     kExtremePos        = 32767 - 1;    {required for old region bug}
  190.     
  191.     {kTESlop provides some extra security when pre-flighting edit commands.}
  192.     kTESlop            = 1024;
  193.  
  194.     {kErrStrings is the resource ID for the error strings STR# resource.}
  195.     kErrStrings        = 128;
  196.  
  197.     {The following are indicies into STR# resources.}
  198.     eWrongMachine    = 1;
  199.     eSmallSize        = 2;
  200.     eNoMemory        = 3;
  201.     eNoSpaceCut        = 4;
  202.     eNoCut            = 5;
  203.     eNoCopy            = 6;
  204.     eExceedPaste    = 7;
  205.     eNoSpacePaste    = 8;
  206.     eNoWindow        = 9;
  207.     eExceedChar        = 10;
  208.     eNoPaste        = 11;
  209.     
  210.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  211.     rMenuBar    = 128;                    {application's menu bar}
  212.     rAboutAlert    = 128;                    {about alert}
  213.     rUserAlert    = 129;                    {user error alert}
  214.     rDocWindow    = 128;                    {application's window}
  215.     rVScroll    = 128;                    {vertical scrollbar control}
  216.     rHScroll    = 129;                    {horizontal scrollbar control}
  217.  
  218.     {The following constants are used to identify menus and their items. The menu IDs
  219.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  220.     mApple        = 128;                    {Apple menu}
  221.     iAbout        = 1;
  222.  
  223.     mFile        = 129;                    {File menu}
  224.     iNew        = 1;
  225.     iClose        = 4;
  226.     iQuit        = 12;
  227.  
  228.     mEdit        = 130;                    {Edit menu}
  229.     iUndo        = 1;
  230.     iCut        = 3;
  231.     iCopy        = 4;
  232.     iPaste        = 5;
  233.     iClear        = 6;
  234.  
  235.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  236.     kDITop        = $0050;
  237.     kDILeft        = $0070;
  238.  
  239.  
  240. TYPE
  241.     {A DocumentRecord contains the WindowRecord for one of our document windows,
  242.      as well as the TEHandle for the text we are editing. We have added fields to
  243.      hold the ControlHandles to the vertical and horizontal scrollbars and to hold
  244.      the address of the default clikLoop that gets attached to a TERec when you call
  245.      TEAutoView. Other document fields can be added to this record as needed. For
  246.      a similar example, see how the Window Manager and Dialog Manager add fields
  247.      after the GrafPort.}
  248.     DocumentRecord    = RECORD
  249.         docWindow    : WindowRecord;
  250.         docTE        : TEHandle;
  251.         docVScroll    : ControlHandle;
  252.         docHScroll    : ControlHandle;
  253.         docClik        : ProcPtr;
  254.     END;
  255.     DocumentPeek    = ^DocumentRecord;
  256.  
  257.  
  258. VAR
  259.     {The "g" prefix is used to emphasize that a variable is global.}
  260.  
  261.     {GMac is used to hold the result of a SysEnvirons call. This makes
  262.      it convenient for any routine to check the environment. It is
  263.      global information, anyway.}
  264.     gMac                : SysEnvRec;    {set up by Initialize}
  265.  
  266.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  267.      trap is available. If it is false, we know that we must call GetNextEvent.}
  268.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  269.  
  270.     {GInBackground is maintained by our OSEvent handling routines. Any part of
  271.      the program can check it to find out if it is currently in the background.}
  272.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  273.  
  274.     {GNumDocuments is used to keep track of how many open documents there are
  275.      at any time. It is maintained by the routines that open and close documents.}
  276.     gNumDocuments        : INTEGER;        {maintained by Initialize, DoNew, and DoCloseWindow}
  277.  
  278.     
  279. {$S Initialize}
  280. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  281.  
  282. {Check to see if a given trap is implemented. This is only used by the
  283.  Initialize routine in this program, so we put it in the Initialize segment.
  284.  The recommended approach to see if a trap is implemented is to see if
  285.  the address of the trap routine is the same as the address of the
  286.  Unimplemented trap.}
  287. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  288.  if a ToolTrap is out of range of a pre-MacII ROM.}
  289.  
  290. BEGIN
  291.     IF (tType = ToolTrap) &
  292.         (gMac.machineType > envMachUnknown) &
  293.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  294.         tNumber := BAND(tNumber, $03FF);
  295.         IF tNumber > $01FF THEN                            {which means the tool traps}
  296.             tNumber := _Unimplemented;                    {only go to $01FF}
  297.     END;
  298.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  299.                         GetTrapAddress(_Unimplemented);
  300. END; {TrapAvailable}
  301.  
  302.  
  303. {$S Main}
  304. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  305.  
  306. {Check if a window belongs to a desk accessory.}
  307.  
  308. BEGIN
  309.     IF window = NIL THEN
  310.         IsDAWindow := FALSE
  311.     ELSE    {DA windows have negative windowKinds}
  312.         IsDAWindow := WindowPeek(window)^.windowKind < 0;
  313. END; {IsDAWindow}
  314.  
  315.  
  316. {$S Main}
  317. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  318.  
  319. {Check to see if a window belongs to the application. If the window pointer
  320.  passed was NIL, then it could not be an application window. WindowKinds
  321.  that are negative belong to the system and windowKinds less than userKind
  322.  are reserved by Apple except for windowKinds equal to dialogKind, which
  323.  mean it is a dialog.
  324.  1.02 - In order to reduce the chance of accidentally treating some window
  325.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  326.  is userKind. If you add different kinds of windows to Sample you'll need
  327.  to change how this all works.}
  328.  
  329. BEGIN
  330.     IF window = NIL THEN
  331.         IsAppWindow := FALSE
  332.     ELSE    {application windows have windowKinds = userKind (8)}
  333.         WITH WindowPeek(window)^ DO
  334.             IsAppWindow := (windowKind = userKind);
  335. END; {IsAppWindow}
  336.  
  337.  
  338. {$S Main}
  339. PROCEDURE AlertUser(error: INTEGER);
  340.  
  341. {Display an alert that tells the user an error occurred, then exit the program.
  342.  This routine is used as an ultimate bail-out for serious errors that prohibit
  343.  the continuation of the application. Errors that do not require the termination
  344.  of the application should be handled in a different manner. Error checking and
  345.  reporting has a place even in the simplest application. The error number is used
  346.  to index an 'STR#' resource so that a relevant message can be displayed.}
  347.  
  348. VAR
  349.     itemHit    : INTEGER;
  350.     message    : Str255;
  351. BEGIN
  352.     SetCursor(arrow);
  353.     GetIndString(message, kErrStrings, error);
  354.     ParamText(message, '', '', '');
  355.     itemHit := Alert(rUserAlert, NIL);
  356. END; {AlertUser}
  357.  
  358.  
  359. {$S Main}
  360. PROCEDURE GetTERect(window: WindowPtr; VAR teRect: Rect);
  361.  
  362. {return a rectangle that is inset from the portRect by the size of
  363. the scrollbars and a little extra margin.}
  364.  
  365. BEGIN
  366.     teRect := window^.portRect;
  367.     InsetRect(teRect, kTextMargin, kTextMargin);            {adjust for margin}
  368.     teRect.bottom := teRect.bottom - kScrollbarAdjust;    {and for the scrollbars}
  369.     teRect.right := teRect.right - kScrollbarAdjust;
  370. END; {GetTERect}
  371.  
  372.  
  373. {$S Main}
  374. FUNCTION DoCloseWindow(window: WindowPtr) : BOOLEAN;
  375.  
  376. {Close a window. This handles desk accessory and application windows.}
  377.  
  378. {1.01 - At this point, if there was a document associated with a
  379.  window, you could do any document saving processing if it is 'dirty'.
  380.  DoCloseWindow would return TRUE if the window actually closed, i.e.,
  381.  the user didn’t cancel from a save dialog. This result is handy when
  382.  the user quits an application, but then cancels the save of a document
  383.  associated with a window.}
  384.  
  385. BEGIN
  386.     DoCloseWindow := TRUE;
  387.     IF IsDAWindow(window) THEN
  388.         CloseDeskAcc(WindowPeek(window)^.windowKind)
  389.     ELSE IF IsAppWindow(window) THEN BEGIN
  390.         WITH DocumentPeek(window)^ DO
  391.             IF docTE <> NIL THEN
  392.                 TEDispose(docTE);        {dispose the TEHandle}
  393.         {1.01 - We used to call DisposeWindow, but that was technically
  394.          incorrect, even though we allocated storage for the window on
  395.          the heap. We should instead call CloseWindow to have the structures
  396.          taken care of and then dispose of the storage ourselves.}
  397.         CloseWindow(window);
  398.         DisposPtr(Ptr(window));
  399.         gNumDocuments := gNumDocuments - 1;
  400.     END;
  401. END; {DoCloseWindow}
  402.  
  403.  
  404. {$S Main}
  405. PROCEDURE AdjustViewRect(docTE: TEHandle);
  406.  
  407. {Update the TERec's view rect so that it is the greatest multiple of
  408. the lineHeight and still fits in the old viewRect.}
  409.  
  410. BEGIN
  411.     WITH docTE^^ DO BEGIN
  412.         viewRect.bottom := (((viewRect.bottom - viewRect.top) DIV lineHeight) *
  413.                             lineHeight) + viewRect.top;
  414.     END;
  415. END; {AdjustViewRect}
  416.  
  417.  
  418. {$S Main}
  419. PROCEDURE AdjustTE(window: WindowPtr);
  420.  
  421. {Scroll the TERec around to match up to the potentially updated scrollbar
  422. values. This is really useful when the window resizes such that the
  423. scrollbars become inactive and the TERec had been previously scrolled.}
  424.  
  425. VAR
  426.     value    : INTEGER;
  427. BEGIN
  428.     WITH DocumentPeek(window)^ DO BEGIN
  429.         TEScroll((docTE^^.viewRect.left - docTE^^.destRect.left) - GetCtlValue(docHScroll),
  430.                 (docTE^^.viewRect.top - docTE^^.destRect.top) -
  431.                     (GetCtlValue(docVScroll) * docTE^^.lineHeight),
  432.                 docTE);
  433.     END;
  434. END; {AdjustTE}
  435.  
  436.  
  437. {$S Main}
  438. PROCEDURE AdjustHV(isVert: BOOLEAN; control: ControlHandle; docTE: TEHandle; canRedraw: BOOLEAN);
  439.  
  440. {Calculate the new control maximum value and current value, whether it is the horizontal or
  441. vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  442. vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  443. width to the width of the viewRect. The current values are set by comparing the offset between
  444. the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  445. calling ShowControl.}
  446.  
  447. VAR
  448.     value, lines, max    : INTEGER;
  449.     oldValue, oldMax    : INTEGER;
  450. BEGIN
  451.     oldValue := GetCtlValue(control);
  452.     oldMax := GetCtlMax(control);
  453.     IF isVert THEN BEGIN
  454.         lines := docTE^^.nLines;
  455.         {since nLines isn’t right if the last character is a return, check for that case}
  456.         IF Ptr(ORD(docTE^^.hText^) + docTE^^.teLength - 1)^ = kCRChar THEN
  457.             lines := lines + 1;
  458.         max := lines - ((docTE^^.viewRect.bottom - docTE^^.viewRect.top) DIV docTE^^.lineHeight);
  459.     END ELSE
  460.         max := kMaxDocWidth - (docTE^^.viewRect.right - docTE^^.viewRect.left);
  461.     IF max < 0 THEN max := 0;            {check for negative values}
  462.     SetCtlMax(control, max);
  463.     IF isVert THEN
  464.         value := (docTE^^.viewRect.top - docTE^^.destRect.top) DIV docTE^^.lineHeight
  465.     ELSE
  466.         value := docTE^^.viewRect.left - docTE^^.destRect.left;
  467.     IF value < 0 THEN
  468.         value := 0
  469.     ELSE IF value > max THEN
  470.         value := max;                    {pin the value to within range}
  471.     SetCtlValue(control, value);
  472.     IF canRedraw & ( (max <> oldMax) | (value <> oldValue) ) THEN
  473.         ShowControl(control);            {check to see if the control can be re-drawn}
  474. END; {AdjustHV}
  475.  
  476.  
  477. {$S Main}
  478. PROCEDURE AdjustScrollValues(window: WindowPtr; canRedraw: BOOLEAN);
  479.  
  480. {Simply call the common adjust routine for the vertical and horizontal scrollbars.}
  481.  
  482. BEGIN
  483.     WITH DocumentPeek(window)^ DO BEGIN
  484.         AdjustHV(TRUE, docVScroll, docTE, canRedraw);
  485.         AdjustHV(FALSE, docHScroll, docTE, canRedraw);
  486.     END;
  487. END; {AdjustScrollValues}
  488.  
  489.  
  490. {$S Main}
  491. PROCEDURE AdjustScrollSizes(window: WindowPtr);
  492.  
  493. {Re-calculate the position and size of the viewRect and the scrollbars.
  494.  kScrollTweek compensates for off-by-one requirements of the scrollbars
  495.  to have borders coincide with the growbox.}
  496.  
  497. VAR
  498.     teRect    : Rect;
  499. BEGIN
  500.     GetTERect(window, teRect);                                        {start with teRect}
  501.     WITH DocumentPeek(window)^, window^.portRect DO BEGIN
  502.         docTE^^.viewRect := teRect;
  503.         AdjustViewRect(docTE);                                        {snap to nearest line}
  504.         MoveControl(docVScroll, right - kScrollbarAdjust, -1);
  505.         SizeControl(docVScroll, kScrollbarWidth, (bottom - top) -
  506.                         (kScrollbarAdjust - kScrollTweek));
  507.         MoveControl(docHScroll, -1, bottom - kScrollbarAdjust);
  508.         SizeControl(docHScroll, (right - left) - (kScrollbarAdjust -
  509.                         kScrollTweek), kScrollbarWidth);
  510.     END;
  511. END; {AdjustScrollSizes}
  512.  
  513.  
  514. {$S Main}
  515. PROCEDURE AdjustScrollbars(window: WindowPtr; needsResize: BOOLEAN);
  516.  
  517. {Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  518. and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  519. then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  520. by jamming a $FF in their contrlVis fields.}
  521.  
  522. VAR
  523.     oldMax, oldVal    : INTEGER;
  524. BEGIN
  525.     WITH DocumentPeek(window)^ DO BEGIN
  526.         {First, turn visibility of scrollbars off so we won’t get unwanted redrawing}
  527.         docVScroll^^.contrlVis := kControlInvisible;    {turn them off}
  528.         docHScroll^^.contrlVis := kControlInvisible;
  529.         IF needsResize THEN                                {move and size if needed}
  530.             AdjustScrollSizes(window);
  531.         AdjustScrollValues(window, NOT needsResize);    {fool with max and current value}
  532.         {Now, restore visibility in case we never had to ShowControl during adjustment}
  533.         docVScroll^^.contrlVis := kControlVisible;        {turn them on}
  534.         docHScroll^^.contrlVis := kControlVisible;
  535.     END;
  536. END; {AdjustScrollbars}
  537.  
  538.  
  539. {$S Main}
  540. {$PUSH} {$Z+}
  541. PROCEDURE PascalClikLoop;
  542.  
  543. {Gets called from our assembly language routine, AsmClikLoop, which is in
  544.  turn called by the TEClick toolbox routine. Saves the windows clip region,
  545.  sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  546.  amount, then restores the clip region.}
  547.  
  548. VAR
  549.     window    : WindowPtr;
  550.     region    : RgnHandle;
  551. BEGIN
  552.     window := FrontWindow;
  553.     region := NewRgn;
  554.     GetClip(region);                    {save the old clip}
  555.     ClipRect(window^.portRect);            {set the new clip}
  556.     AdjustScrollValues(window, TRUE);    {pass TRUE for canRedraw}
  557.     SetClip(region);                    {restore the old clip}
  558.     DisposeRgn(region);
  559. END; {PascalClikLoop}
  560. {$POP}
  561.  
  562.  
  563. {$S Main}
  564. {$PUSH} {$Z+}
  565. FUNCTION GetOldClikLoop : ProcPtr;
  566.  
  567. {Gets called from our assembly language routine, AsmClikLoop, which is in
  568. turn called by the TEClick toolbox routine. It returns the address of the
  569. default clikLoop routine that was put into the TERec by TEAutoView to
  570. AsmClikLoop so that it can call it.}
  571.  
  572. BEGIN
  573.     GetOldClikLoop := DocumentPeek(FrontWindow)^.docClik;
  574. END; {GetOldClikLoop}
  575. {$POP}
  576.  
  577.  
  578. PROCEDURE AsmClikLoop; EXTERNAL;
  579.  
  580. {A reference to our assembly language routine that gets attached to the clikLoop
  581. field of our TE record.}
  582.  
  583.  
  584. {$S Main}
  585. PROCEDURE DoNew;
  586.  
  587. {Create a new document and window.}
  588.  
  589. VAR
  590.     good, ignore        : BOOLEAN;
  591.     storage                : Ptr;
  592.     window                : WindowPtr;
  593.     destRect, viewRect    : Rect;
  594.  
  595. BEGIN
  596.     storage := NewPtr(SIZEOF(DocumentRecord));
  597.     IF storage <> NIL THEN BEGIN
  598.         window := GetNewWindow(rDocWindow, storage, WindowPtr(-1));
  599.         IF window <> NIL THEN BEGIN
  600.             gNumDocuments := gNumDocuments + 1;    {this will be decremented when we call DoCloseWindow}
  601.             good := FALSE;
  602.             SetPort(window);
  603.             WITH window^, DocumentPeek(window)^ DO BEGIN
  604.                 GetTERect(window, viewRect);
  605.                 destRect := viewRect;
  606.                 destRect.right := destRect.left + kMaxDocWidth;
  607.                 docTE := TENew(destRect, viewRect);
  608.                 IF docTE <> NIL THEN BEGIN        {1.02 - moved}
  609.                     good := TRUE;                {if TENew succeeded, we have a good document}
  610.                     AdjustViewRect(docTE);
  611.                     TEAutoView(TRUE, docTE);
  612.                     docClik := docTE^^.clikLoop;
  613.                     docTE^^.clikLoop := @AsmClikLoop;
  614.                 END;
  615.                 IF good THEN BEGIN
  616.                     docVScroll := GetNewControl(rVScroll, window);
  617.                     good := (docVScroll <> NIL);
  618.                 END;
  619.                 IF good THEN BEGIN
  620.                     docHScroll := GetNewControl(rHScroll, window);
  621.                     good := (docHScroll <> NIL);
  622.                 END;
  623.                 IF good THEN BEGIN
  624.                     {FALSE to AdjustScrollValues means musn’t redraw; technically, of course,
  625.                     the window is hidden so it wouldn’t matter whether we called ShowControl or not.}
  626.                     AdjustScrollValues(window, FALSE);
  627.                     ShowWindow(window);            {if the document is good, make the window visible}
  628.                 END ELSE BEGIN
  629.                     ignore := DoCloseWindow(window);    {otherwise regret we ever created it...}
  630.                     AlertUser(eNoWindow);                {and tell user}
  631.                 END
  632.             END;
  633.         END ELSE
  634.             DisposPtr(storage);                    {get rid of the storage if it is never used}
  635.     END;
  636. END; {DoNew}
  637.  
  638.  
  639. {$S Main}
  640. PROCEDURE BigBadError(error: INTEGER);
  641. BEGIN
  642.     AlertUser(error);
  643.     ExitToShell;
  644. END;
  645.  
  646.  
  647. {$S Initialize}
  648. PROCEDURE Initialize;
  649.  
  650. {Set up the whole world, including global variables, Toolbox managers,
  651.  menus, and a single blank document.}
  652.  
  653. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  654.  this module. If an error is detected, instead of merely doing an ExitToShell,
  655.  which leaves the user without much to go on, we call AlertUser, which puts
  656.  up a simple alert that just says an error occurred and then calls ExitToShell.
  657.  Since there is no other cleanup needed at this point if an error is detected,
  658.  this form of error- handling is acceptable. If more sophisticated error recovery
  659.  is needed, an exception mechanism, such as is provided by Signals, can be used.}
  660.  
  661. VAR
  662.     menuBar                : Handle;
  663.     total, contig        : LongInt;
  664.     ignoreResult        : BOOLEAN;
  665.     event                : EventRecord;
  666.     count, ignoreError    : INTEGER;
  667.     
  668.     PROCEDURE BigBadError(error: INTEGER);
  669.     BEGIN
  670.         AlertUser(error);
  671.         ExitToShell;
  672.     END;
  673.  
  674. BEGIN
  675.     gInBackground := FALSE;
  676.  
  677.     InitGraf(@thePort);
  678.     InitFonts;
  679.     InitWindows;
  680.     InitMenus;
  681.     TEInit;
  682.     InitDialogs(NIL);
  683.     InitCursor;
  684.  
  685.     {Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  686.      if you are using it.}
  687.     {NOTE -- It is no longer necessary, and actually unhealthy, to check
  688.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  689.      of checking for port availability themselves.}
  690.     
  691.     {This next bit of code is necessary to allow the default button of our
  692.      alert be outlined.
  693.      1.02 - Changed to call EventAvail so that we don't lose some important
  694.      events.}
  695.      
  696.     FOR count := 1 TO 3 DO
  697.         ignoreResult := EventAvail(everyEvent, event);
  698.     
  699.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  700.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  701.      call to SysEnvirons by calling it after initializing AppleTalk.}
  702.      
  703.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  704.     
  705.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  706.     
  707.     IF gMac.machineType < 0 THEN BigBadError(eWrongMachine);
  708.     
  709.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  710.      in TrapAvailable if a tool trap value is out of range.}
  711.      
  712.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  713.  
  714.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  715.      ApplicZone, and StackSpace and comparing that to the minimum size we told
  716.      MultiFinder we needed. This did not work well because it assumed too much about
  717.      the relationship between what we asked MultiFinder for and what we would actually
  718.      get back, as well as how to measure it. Instead, we will use an alternate
  719.      method comprised of two steps.}
  720.      
  721.     {It is better to first check the size of the application heap against a value
  722.      that you have determined is the smallest heap the application can reasonably
  723.      work in. This number should be derived by examining the size of the heap that
  724.      is actually provided by MultiFinder when the minimum size requested is used.
  725.      The derivation of the minimum size requested from MultiFinder is described
  726.      in Sample.h. The check should be made because the preferred size can end up
  727.      being set smaller than the minimum size by the user. This extra check acts to
  728.      insure that your application is starting from a solid memory foundation.}
  729.      
  730.     IF ORD(GetApplLimit) - ORD(ApplicZone) < kMinHeap THEN BigBadError(eSmallSize);
  731.     
  732.     {Next, make sure that enough memory is free for your application to run. It
  733.      is possible for a situation to arise where the heap may have been of required
  734.      size, but a large scrap was loaded which left too little memory. To check for
  735.      this, call PurgeSpace and compare the result with a value that you have determined
  736.      is the minimum amount of free memory your application needs at initialization.
  737.      This number can be derived several different ways. One way that is fairly
  738.      straightforward is to run the application in the minimum size configuration
  739.      as described previously. Call PurgeSpace at initialization and examine the value
  740.      returned. However, you should make sure that this result is not being modified
  741.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  742.      PurgeSpace. Make sure to remove that call before shipping, though.}
  743.      
  744.     {* ZeroScrap; *}
  745.     PurgeSpace(total, contig);
  746.     IF total < kMinSpace THEN
  747.         IF UnloadScrap <> noErr THEN
  748.             BigBadError(eNoMemory)
  749.         ELSE BEGIN
  750.             PurgeSpace(total, contig);
  751.             IF total < kMinSpace THEN
  752.                 BigBadError(eNoMemory);
  753.         END;
  754.  
  755.     {The extra benefit to waiting until after the Toolbox Managers have been initialized
  756.      to check memory is that we can now give the user an alert to tell her/him what
  757.      happened. Although it is possible that the memory situation could be worsened by
  758.      displaying an alert, MultiFinder would gracefully exit the application with
  759.      an informative alert if memory became critical. Here we are acting more
  760.      in a preventative manner to avoid future disaster from low-memory problems.}
  761.  
  762.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  763.     IF menuBar = NIL THEN
  764.         BigBadError(eNoMemory);
  765.     SetMenuBar(menuBar);                    {install menus}
  766.     DisposHandle(menuBar);
  767.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  768.     DrawMenuBar;
  769.  
  770.     gNumDocuments := 0;
  771.  
  772.     {do other initialization here}
  773.  
  774.     DoNew;                                    {create a single empty document}
  775. END; {Initialize}
  776.  
  777.  
  778. (**************************************************************************************
  779. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  780.  
  781. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  782.  and not having to worry about updating the windows, but it suffered
  783.  from a fatal flaw. If a desk accessory owned two windows, it would
  784.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  785.  got around to calling DoCloseWindow for that other window that was already
  786.  closed, things would go very poorly. Another option would be to have a
  787.  procedure, GetRearWindow, that would go through the window list and return
  788.  the last window. Instead, we decided to present the standard approach
  789.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  790.  has a potential benefit in that the window whose document needs to be saved
  791.  may be visible since it is the front window, therefore decreasing the
  792.  chance of user confusion. For aesthetic reasons, the windows in the
  793.  application should be checked for updates periodically and have the
  794.  updates serviced.}
  795. **************************************************************************************)
  796.  
  797.  
  798. {$S Main}
  799. PROCEDURE Terminate;
  800.  
  801. {Clean up the application and exit. We close all of the windows so that
  802.  they can update their documents, if any.}
  803.  
  804. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  805.  shell, but will return instead.}
  806.  
  807. VAR
  808.     aWindow    : WindowPtr;
  809.     closed    : BOOLEAN;
  810.  
  811. BEGIN
  812.     closed := TRUE;
  813.     REPEAT
  814.         aWindow := FrontWindow;                    {get the current front window}
  815.         IF aWindow <> NIL THEN
  816.             closed := DoCloseWindow(aWindow);    {close this window}
  817.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  818.     IF closed THEN
  819.         ExitToShell;                            {exit if no cancellation}
  820. END; {Terminate}
  821.  
  822.  
  823. {$S Main}
  824. PROCEDURE AdjustMenus;
  825.  
  826. {Enable and disable menus based on the current state.
  827.  The user can only select enabled menu items. We set up all the menu items
  828.  before calling MenuSelect or MenuKey, since these are the only times that
  829.  a menu item can be selected. Note that MenuSelect is also the only time
  830.  the user will see menu items. This approach to deciding what enable/
  831.  disable state a menu item has the advantage of concentrating all the decision-
  832.  making in one routine, as opposed to being spread throughout the application.
  833.  Other application designs may take a different approach that may or may not be
  834.  as valid.}
  835.  
  836. VAR
  837.     window            : WindowPtr;
  838.     menu            : MenuHandle;
  839.     offset            : LONGINT;
  840.     undo            : BOOLEAN;
  841.     cutCopyClear    : BOOLEAN;
  842.     paste            : BOOLEAN;
  843.  
  844. BEGIN
  845.     window := FrontWindow;
  846.  
  847.     menu := GetMHandle(mFile);
  848.     IF gNumDocuments < kMaxOpenDocuments THEN
  849.         EnableItem(menu, iNew)        {New is enabled when we can open more documents}
  850.     ELSE
  851.         DisableItem(menu, iNew);
  852.     IF window <> NIL THEN            {Close is enabled when there is a window to close}
  853.         EnableItem(menu, iClose)
  854.     ELSE
  855.         DisableItem(menu, iClose);
  856.  
  857.     menu := GetMHandle(mEdit);
  858.     undo := FALSE;
  859.     cutCopyClear := FALSE;
  860.     paste := FALSE;
  861.     IF IsDAWindow(window) THEN BEGIN
  862.         undo := TRUE;                {all editing is enabled for DA windows}
  863.         cutCopyClear := TRUE;
  864.         paste := TRUE;
  865.     END ELSE IF IsAppWindow(window) THEN BEGIN
  866.         WITH DocumentPeek(window)^.docTE^^ DO
  867.             IF selStart < selEnd THEN
  868.                 cutCopyClear := TRUE;
  869.                 {Cut, Copy, and Clear is enabled for app. windows with selections}
  870.         IF GetScrap(NIL, 'TEXT', offset) > 0 THEN
  871.             paste := TRUE;            {Paste is enabled for app. windows}
  872.     END;
  873.     IF undo THEN
  874.         EnableItem(menu, iUndo)
  875.     ELSE
  876.         DisableItem(menu, iUndo);
  877.     IF cutCopyClear THEN BEGIN
  878.         EnableItem(menu, iCut);
  879.         EnableItem(menu, iCopy);
  880.         EnableItem(menu, iClear);
  881.     END ELSE BEGIN
  882.         DisableItem(menu, iCut);
  883.         DisableItem(menu, iCopy);
  884.         DisableItem(menu, iClear);
  885.     END;
  886.     IF paste THEN
  887.         EnableItem(menu, iPaste)
  888.     ELSE
  889.         DisableItem(menu, iPaste);
  890. END; {AdjustMenus}
  891.  
  892.  
  893. {$S Main}
  894. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  895.  
  896. {This is called when an item is chosen from the menu bar (after calling
  897.  MenuSelect or MenuKey). It does the right thing for each command.}
  898.  
  899. VAR
  900.     menuID, menuItem        : INTEGER;
  901.     itemHit, daRefNum        : INTEGER;
  902.     daName                    : Str255;
  903.     ignoreResult, saveErr    : OSErr;
  904.     handledByDA                : BOOLEAN;
  905.     te                        : TEHandle;
  906.     window                    : WindowPtr;
  907.     ignore                    : BOOLEAN;
  908.     aHandle                    : Handle;
  909.     oldSize, newSize        : LongInt;
  910.     total, contig            : LongInt;
  911.  
  912. BEGIN
  913.     window := FrontWindow;
  914.     menuID := HiWrd(menuResult);    {use built-ins (for efficiency)...}
  915.     menuItem := LoWrd(menuResult);    {to get menu item number and menu number}
  916.     CASE menuID OF
  917.     
  918.         mApple:
  919.             CASE menuItem OF
  920.                 iAbout:                {bring up alert for About}
  921.                     itemHit := Alert(rAboutAlert, NIL);
  922.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  923.                     GetItem(GetMHandle(mApple), menuItem, daName);
  924.                     daRefNum := OpenDeskAcc(daName);
  925.                 END;
  926.             END;
  927.             
  928.         mFile:
  929.             CASE menuItem OF
  930.                 iNew:
  931.                     DoNew;
  932.                 iClose:
  933.                     ignore := DoCloseWindow(window); {we don't care if cancelled}
  934.                 iQuit:
  935.                     Terminate;
  936.             END;
  937.             
  938.         mEdit: BEGIN                {call SystemEdit for DA editing & MultiFinder}
  939.             IF NOT SystemEdit(menuItem-1) THEN BEGIN
  940.                 te := DocumentPeek(window)^.docTE;
  941.                 CASE menuItem OF
  942.                 
  943.                     iCut: BEGIN        {after cutting, export the TE scrap}
  944.                         IF ZeroScrap = noErr THEN BEGIN
  945.                             PurgeSpace(total, contig);
  946.                             IF (te^^.selEnd - te^^.selStart) + kTESlop > contig THEN
  947.                                 AlertUser(eNoSpaceCut)
  948.                             ELSE BEGIN
  949.                                 TECut(te);
  950.                                 IF TEToScrap <> noErr THEN BEGIN
  951.                                     AlertUser(eNoCut);
  952.                                     ignoreResult := ZeroScrap;
  953.                                 END;
  954.                             END;
  955.                         END;
  956.                     END;
  957.                     
  958.                     iCopy: BEGIN    {after copying, export the TE scrap}
  959.                         IF ZeroScrap = noErr THEN BEGIN
  960.                             TECopy(te);
  961.                             IF TEToScrap <> noErr THEN BEGIN
  962.                                 AlertUser(eNoCopy);
  963.                                 ignoreResult := ZeroScrap;
  964.                             END;
  965.                         END;
  966.                     END;
  967.                     
  968.                     iPaste: BEGIN    {import the TE scrap before pasting}
  969.                         IF TEFromScrap = noErr THEN BEGIN
  970.                             IF TEGetScrapLen + (te^^.teLength -
  971.                                 (te^^.selEnd - te^^.selStart)) > kMaxTELength THEN
  972.                                 AlertUser(eExceedPaste)
  973.                             ELSE BEGIN
  974.                                     aHandle := Handle(TEGetText(te));
  975.                                     oldSize := GetHandleSize(aHandle);
  976.                                     newSize := oldSize + TEGetScrapLen + kTESlop;
  977.                                     SetHandleSize(aHandle, newSize);
  978.                                     saveErr := MemError;
  979.                                     SetHandleSize(aHandle, oldSize);
  980.                                     IF saveErr <> noErr THEN
  981.                                         AlertUser(eNoSpacePaste)
  982.                                     ELSE
  983.                                         TEPaste(te);
  984.                                 END;
  985.                         END ELSE
  986.                             AlertUser(eNoPaste);
  987.                     END;
  988.                     
  989.                     iClear:
  990.                         TEDelete(te);
  991.                         
  992.                 END;
  993.                 AdjustScrollbars(window, FALSE);
  994.                 AdjustTE(window);
  995.             END;
  996.         END;
  997.     END;
  998.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  999. END; {DoMenuCommand}
  1000.  
  1001.  
  1002. {$S Main}
  1003. PROCEDURE DrawWindow(window: WindowPtr);
  1004.  
  1005. {Draw the contents of an application window.}
  1006.  
  1007. BEGIN
  1008.     SetPort(window);
  1009.     WITH window^ DO BEGIN
  1010.         EraseRect(portRect);        {as per TextEdit chapter of Inside Macintosh}
  1011.         DrawControls(window);        {this ordering makes for a better appearance}
  1012.         DrawGrowIcon(window);
  1013.         TEUpdate(portRect, DocumentPeek(window)^.docTE);
  1014.     END;
  1015. END; {DrawWindow}
  1016.  
  1017.  
  1018. {$S Main}
  1019. FUNCTION GetSleep: LONGINT;
  1020.  
  1021. {Calculate a sleep value for WaitNextEvent. This takes into account the things
  1022.  that DoIdle does with idle time.}
  1023.  
  1024. VAR
  1025.     sleep    : LONGINT;
  1026.     window    : WindowPtr;
  1027.  
  1028. BEGIN
  1029.     sleep := MAXLONGINT;                    {default value for sleep}
  1030.     IF NOT gInBackground THEN BEGIN            {if we are in front...}
  1031.         window := FrontWindow;            {and the front window is ours...}
  1032.         IF IsAppWindow(window) THEN BEGIN
  1033.             WITH DocumentPeek(window)^.docTE^^ DO
  1034.                 IF selStart = selEnd THEN    {and the selection is an insertion point...}
  1035.                     sleep := GetCaretTime;    {we need to blink the insertion point}
  1036.         END;
  1037.     END;
  1038.     GetSleep := sleep;
  1039. END; {GetSleep}
  1040.  
  1041.  
  1042. {$S Main}
  1043. PROCEDURE CommonAction(control: ControlHandle; VAR amount: INTEGER);
  1044.  
  1045. {Common algorithm for setting the new value of a control. It returns the actual amount
  1046. the value of the control changed. Note the pinning is done for the sake of returning
  1047. the amount the control value changed.}
  1048.  
  1049. VAR
  1050.     value, max    : INTEGER;
  1051.     window        : WindowPtr;
  1052. BEGIN
  1053.     value := GetCtlValue(control);    {get current value}
  1054.     max := GetCtlMax(control);        {and max value}
  1055.     amount := value - amount;
  1056.     IF amount < 0 THEN
  1057.         amount := 0
  1058.     ELSE IF amount > max THEN
  1059.         amount := max;
  1060.     SetCtlValue(control, amount);
  1061.     amount := value - amount;        {calculate true change}
  1062. END; {CommonAction}
  1063.  
  1064.  
  1065. {$S Main}
  1066. PROCEDURE VActionProc(control: ControlHandle; part: INTEGER);
  1067.  
  1068. {Determines how much to change the value of the vertical scrollbar by and how
  1069. much to scroll the TE record.}
  1070.  
  1071. VAR
  1072.     amount    : INTEGER;
  1073.     window    : WindowPtr;
  1074. BEGIN
  1075.     IF part <> 0 THEN BEGIN
  1076.         window := control^^.contrlOwner;
  1077.         WITH DocumentPeek(window)^, DocumentPeek(window)^.docTE^^ DO BEGIN
  1078.             CASE part OF
  1079.                 inUpButton, inDownButton:
  1080.                     amount := 1;                                                {one line}
  1081.                 inPageUp, inPageDown:
  1082.                     amount := (viewRect.bottom - viewRect.top) DIV lineHeight;    {one page}
  1083.             END;
  1084.             IF (part = inDownButton) | (part = inPageDown) THEN
  1085.                 amount := -amount;                                                {reverse direction}
  1086.             CommonAction(control, amount);
  1087.             IF amount <> 0 THEN
  1088.                 TEScroll(0, amount * docTE^^.lineHeight, docTE);
  1089.         END;
  1090.     END;
  1091. END; {VActionProc}
  1092.  
  1093.  
  1094. {$S Main}
  1095. PROCEDURE HActionProc(control: ControlHandle; part: INTEGER);
  1096.  
  1097. {Determines how much to change the value of the horizontal scrollbar by and how
  1098. much to scroll the TE record.}
  1099.  
  1100. VAR
  1101.     amount    : INTEGER;
  1102.     window    : WindowPtr;
  1103. BEGIN
  1104.     IF part <> 0 THEN BEGIN
  1105.         window := control^^.contrlOwner;
  1106.         WITH DocumentPeek(window)^, DocumentPeek(window)^.docTE^^ DO BEGIN
  1107.             CASE part OF
  1108.                 inUpButton, inDownButton:                                        {a few pixels}
  1109.                     amount := kButtonScroll;
  1110.                 inPageUp, inPageDown:
  1111.                     amount := viewRect.right - viewRect.left;                    {a page}
  1112.             END;
  1113.             IF (part = inDownButton) | (part = inPageDown) THEN
  1114.                 amount := -amount;                                                {reverse direction}
  1115.             CommonAction(control, amount);
  1116.             IF amount <> 0 THEN
  1117.                 TEScroll(amount, 0, docTE);
  1118.         END;
  1119.     END;
  1120. END; {HActionProc}
  1121.  
  1122.  
  1123. {$S Main}
  1124. PROCEDURE DoIdle;
  1125.  
  1126. {This is called whenever we get an null event or a mouse-moved event.
  1127.  It takes care of necessary periodic actions. For this program, it calls TEIdle.}
  1128.  
  1129. VAR
  1130.     window    : WindowPtr;
  1131.  
  1132. BEGIN
  1133.     window := FrontWindow;
  1134.     IF IsAppWindow(window) THEN
  1135.         TEIdle(DocumentPeek(window)^.docTE);
  1136. END; {DoIdle}
  1137.  
  1138.  
  1139. {$S Main}
  1140. PROCEDURE DoKeyDown(event: EventRecord);
  1141.  
  1142. {This is called for any keyDown or autoKey events, except when the
  1143.  Command key is held down. It looks at the frontmost window to decide what
  1144.  to do with the key typed.}
  1145.  
  1146. VAR
  1147.     window    : WindowPtr;
  1148.     key        : CHAR;
  1149.     te        : TEHandle;
  1150.  
  1151. BEGIN
  1152.     window := FrontWindow;
  1153.     IF IsAppWindow(window) THEN BEGIN
  1154.         te := DocumentPeek(window)^.docTE;
  1155.         key := CHR(BAnd(event.message, charCodeMask));
  1156.         IF (key = CHR(kDelChar)) |                            {don't count deletes}
  1157.             (te^^.teLength - (te^^.selEnd - te^^.selStart)
  1158.                             + 1 < kMaxTELength) THEN BEGIN    {but check haven't gone past}
  1159.             TEKey(key, te);
  1160.             AdjustScrollbars(window, FALSE);
  1161.             AdjustTE(window);
  1162.         END ELSE
  1163.             AlertUser(eExceedChar);
  1164.     END;
  1165. END; {DoKeyDown}
  1166.  
  1167.  
  1168. {$S Main}
  1169. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  1170.  
  1171. {Called when a mouseDown occurs in the content of a window.}
  1172.  
  1173. VAR
  1174.     mouse        : Point;
  1175.     control        : ControlHandle;
  1176.     part, value    : INTEGER;
  1177.     shiftDown    : BOOLEAN;
  1178.     teRect        : Rect;
  1179.  
  1180. BEGIN
  1181.     IF IsAppWindow(window) THEN BEGIN
  1182.         SetPort(window);
  1183.         mouse := event.where;                                            {get the click position}
  1184.         GlobalToLocal(mouse);                                            {convert to local coordinates}
  1185.         {see if we are in the viewRect. if so, we won’t check the controls}
  1186.         GetTERect(window, teRect);
  1187.         IF PtInRect(mouse, teRect) THEN BEGIN
  1188.             shiftDown := BAnd(event.modifiers, shiftKey) <> 0;    {extend if Shift is down}
  1189.             TEClick(mouse, shiftDown, DocumentPeek(window)^.docTE);
  1190.         END ELSE BEGIN
  1191.             part := FindControl(mouse, window, control);
  1192.             WITH DocumentPeek(window)^ DO
  1193.                 CASE part OF
  1194.                     0:;                                            {do nothing for viewRect case}
  1195.                     inThumb: BEGIN
  1196.                         value := GetCtlValue(control);
  1197.                         part := TrackControl(control, mouse, NIL);
  1198.                         IF part <> 0 THEN BEGIN
  1199.                             value := value - GetCtlValue(control);
  1200.                             IF value <> 0 THEN
  1201.                                 IF control = docVScroll THEN
  1202.                                     TEScroll(0, value * docTE^^.lineHeight, docTE)
  1203.                                 ELSE
  1204.                                     TEScroll(value, 0, docTE);
  1205.                         END;
  1206.                     END;
  1207.                     OTHERWISE                                    {must be page or button}
  1208.                         IF control = docVScroll THEN
  1209.                             value := TrackControl(control, mouse, @VActionProc)
  1210.                         ELSE
  1211.                             value := TrackControl(control, mouse, @HActionProc);
  1212.                 END;
  1213.         END;
  1214.     END;
  1215. END; {DoContentClick}
  1216.  
  1217.  
  1218. {$S Main}
  1219. PROCEDURE ResizeWindow(window: WindowPtr);
  1220.  
  1221. {Called when the window has been resized to fix up the controls and content}
  1222.  
  1223. BEGIN
  1224.     WITH window^ DO BEGIN
  1225.         AdjustScrollbars(window, TRUE);
  1226.         AdjustTE(window);
  1227.         InvalRect(portRect);
  1228.     END;
  1229. END; {ResizeWindow}
  1230.  
  1231.  
  1232. {$S Main}
  1233. PROCEDURE GetLocalUpdateRgn(window: WindowPtr; localRgn: RgnHandle);
  1234.  
  1235. {Returns the update region in local coordinates}
  1236.  
  1237. BEGIN
  1238.     CopyRgn(WindowPeek(window)^.updateRgn, localRgn);                        {save old update region}
  1239.     WITH window^.portBits.bounds DO
  1240.         OffsetRgn(localRgn, left, top);                                        {convert to local coords}
  1241. END; {GetLocalUpdateRgn}
  1242.  
  1243.  
  1244. {$S Main}
  1245. PROCEDURE DoGrowWindow(window: WindowPtr; event: EventRecord);
  1246.  
  1247. {Called when a mouseDown occurs in the grow box of an active window. In
  1248.  order to eliminate any 'flicker', we want to invalidate only what is
  1249.  necessary. Since ResizeWindow invalidates the whole portRect, we save
  1250.  the old TE viewRect, intersect it with the new TE viewRect, and
  1251.  remove the result from the update region. However, we must make sure
  1252.  that any old update region that might have been around gets put back.}
  1253.  
  1254. VAR
  1255.     growResult        : LONGINT;
  1256.     tempRect        : Rect;
  1257.     tempRgn            : RgnHandle;
  1258.     ignoreResult    : BOOLEAN;
  1259.  
  1260. BEGIN
  1261.     WITH screenBits.bounds DO
  1262.         SetRect(tempRect, kMinDocDim, kMinDocDim, right, bottom);            {set up limiting values}
  1263.     growResult := GrowWindow(window, event.where, tempRect);
  1264.     IF growResult <> 0 THEN                                                 {see if changed size}
  1265.         WITH DocumentPeek(window)^, window^ DO BEGIN
  1266.             tempRect := docTE^^.viewRect;                                    {save old text box}
  1267.             tempRgn := NewRgn;
  1268.             GetLocalUpdateRgn(window, tempRgn);                                {get localized update region}
  1269.             SizeWindow(window, LoWrd(growResult), HiWrd(growResult), TRUE);
  1270.             ResizeWindow(window);
  1271.             ignoreResult := SectRect(tempRect, docTE^^.viewRect, tempRect);    {find what stayed same}
  1272.             ValidRect(tempRect);                                            {take it out of update}
  1273.             InvalRgn(tempRgn);                                                {put back any prior update}
  1274.             DisposeRgn(tempRgn);
  1275.         END;
  1276. END; {DoGrowWindow}
  1277.  
  1278.  
  1279. {$S Main}
  1280. PROCEDURE DoZoomWindow(window: WindowPtr; part: INTEGER);
  1281.  
  1282. {Called when a mouseClick occurs in the zoom box of an active window.
  1283.  Everything has to get re-drawn here, so we don't mind that
  1284.  ResizeWindow invalidates the whole portRect.}
  1285.  
  1286. BEGIN
  1287.     WITH window^ DO BEGIN
  1288.         EraseRect(portRect);
  1289.         ZoomWindow(window, part, (window = FrontWindow));
  1290.         ResizeWindow(window);
  1291.     END;
  1292. END; {DoZoomWindow}
  1293.  
  1294.  
  1295. {$S Main}
  1296. PROCEDURE DoUpdate(window: WindowPtr);
  1297.  
  1298. {This is called when an update event is received for a window.
  1299.  It calls DrawWindow to draw the contents of an application window,
  1300.  but only if the visRgn is non-empty; for efficiency reasons,
  1301.  not because it is required.}
  1302.  
  1303. BEGIN
  1304.     IF IsAppWindow(window) THEN BEGIN
  1305.         BeginUpdate(window);                    {this sets up the visRgn}
  1306.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  1307.             DrawWindow(window);
  1308.         EndUpdate(window);
  1309.     END;
  1310. END; {DoUpdate}
  1311.  
  1312.  
  1313. {$S Main}
  1314. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  1315.  
  1316. {This is called when a window is activated or deactivated.}
  1317.  
  1318. VAR
  1319.     tempRgn, clipRgn    : RgnHandle;
  1320.     growRect            : Rect;
  1321.  
  1322. BEGIN
  1323.     IF IsAppWindow(window) THEN
  1324.         WITH DocumentPeek(window)^ DO
  1325.             IF becomingActive THEN BEGIN
  1326.                 {since we don’t want TEActivate to draw a selection in an area where
  1327.                  we’re going to erase and redraw, we’ll clip out the update region
  1328.                  before calling it.}
  1329.                 tempRgn := NewRgn;
  1330.                 clipRgn := NewRgn;
  1331.                 GetLocalUpdateRgn(window, tempRgn);            {get localized update region}
  1332.                 GetClip(clipRgn);
  1333.                 DiffRgn(clipRgn, tempRgn, tempRgn);            {subtract updateRgn from clipRgn}
  1334.                 SetClip(tempRgn);
  1335.                 TEActivate(docTE);                            {let TE do its thing}
  1336.                 SetClip(clipRgn);                            {restore the full-blown clipRgn}
  1337.                 DisposeRgn(tempRgn);
  1338.                 DisposeRgn(clipRgn);
  1339.  
  1340.                 {the controls need to be redrawn on activation:}
  1341.                 docVScroll^^.contrlVis := kControlVisible;
  1342.                 docHScroll^^.contrlVis := kControlVisible;
  1343.                 InvalRect(docVScroll^^.contrlRect);
  1344.                 InvalRect(docHScroll^^.contrlRect);
  1345.                 {the growbox needs to be redrawn on activation:}
  1346.                 growRect := window^.portRect;
  1347.                 WITH growRect DO BEGIN
  1348.                     top := bottom - kScrollbarAdjust;        {adjust for the scrollbars}
  1349.                     left := right - kScrollbarAdjust;
  1350.                     END;
  1351.                 InvalRect(growRect);
  1352.             END ELSE BEGIN
  1353.                 TEDeactivate(docTE);
  1354.                 {the controls should be hidden immediately on deactivation:}
  1355.                 HideControl(docVScroll);
  1356.                 HideControl(docHScroll);
  1357.                 {the growbox should be changed immediately on deactivation:}
  1358.                 DrawGrowIcon(window);
  1359.             END;
  1360. END; {DoActivate}
  1361.  
  1362.  
  1363. {$S Main}
  1364. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  1365.  
  1366. {Get the global coordinates of the mouse. When you call OSEventAvail
  1367.  it will return either a pending event or a null event. In either case,
  1368.  the where field of the event record will contain the current position
  1369.  of the mouse in global coordinates and the modifiers field will reflect
  1370.  the current state of the modifiers. Another way to get the global
  1371.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  1372.  being sure that thePort is set to a valid port.}
  1373.  
  1374. VAR
  1375.     event    : EventRecord;
  1376.     
  1377. BEGIN
  1378.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  1379.     mouse := event.where;                    {just the mouse position}
  1380. END;
  1381.  
  1382.  
  1383. {$S Main}
  1384. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  1385.  
  1386. {Change the cursor's shape, depending on its position. This also calculates the region
  1387.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  1388.  that region, an event is generated, causing this routine to be called. This
  1389.  allows us to change the region to the region the mouse is currently in. If
  1390.  there is more to the event than just “the mouse moved”, we get called before the
  1391.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  1392.  this is called again before we fall back into WNE.}
  1393.  
  1394.  
  1395. VAR
  1396.     window        : WindowPtr;
  1397.     arrowRgn    : RgnHandle;
  1398.     iBeamRgn    : RgnHandle;
  1399.     iBeamRect    : Rect;
  1400.  
  1401. BEGIN
  1402.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  1403.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  1404.         {calculate regions for different cursor shapes}
  1405.         arrowRgn := NewRgn;
  1406.         iBeamRgn := NewRgn;
  1407.  
  1408.         {start with a big, big rectangular region}
  1409.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  1410.  
  1411.         {calculate iBeamRgn}
  1412.         IF IsAppWindow(window) THEN BEGIN
  1413.             iBeamRect := DocumentPeek(window)^.docTE^^.viewRect;
  1414.             SetPort(window);                    {make a global version of the viewRect}
  1415.             WITH iBeamRect DO BEGIN
  1416.                 LocalToGlobal(topLeft);
  1417.                 LocalToGlobal(botRight);
  1418.             END;
  1419.             RectRgn(iBeamRgn, iBeamRect);
  1420.             WITH window^.portBits.bounds DO
  1421.                 SetOrigin(-left, -top);
  1422.             SectRgn(iBeamRgn, window^.visRgn, iBeamRgn);
  1423.             SetOrigin(0, 0);
  1424.         END;
  1425.  
  1426.         {subtract other regions from arrowRgn}
  1427.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  1428.         
  1429.         {change the cursor and the region parameter}
  1430.         IF PtInRgn(mouse, iBeamRgn) THEN BEGIN
  1431.             SetCursor(GetCursor(iBeamCursor)^^);
  1432.             CopyRgn(iBeamRgn, region);
  1433.         END ELSE BEGIN
  1434.             SetCursor(arrow);
  1435.             CopyRgn(arrowRgn, region);
  1436.         END;
  1437.  
  1438.         {get rid of our local regions}
  1439.         DisposeRgn(arrowRgn);
  1440.         DisposeRgn(iBeamRgn);
  1441.     END;
  1442. END; {AdjustCursor}
  1443.  
  1444.  
  1445. {$S Main}
  1446. PROCEDURE DoEvent(event: EventRecord);
  1447.  
  1448. {Do the right thing for an event. Determine what kind of event it is, and call
  1449.  the appropriate routines.}
  1450.  
  1451. VAR
  1452.     part, err    : INTEGER;
  1453.     window        : WindowPtr;
  1454.     key            : CHAR;
  1455.     ignore        : BOOLEAN;
  1456.     aPoint        : Point;
  1457.  
  1458. BEGIN
  1459.     CASE event.what OF
  1460.         nullEvent:
  1461.             DoIdle;
  1462.         mouseDown: BEGIN
  1463.             part := FindWindow(event.where, window);
  1464.             CASE part OF
  1465.                 inMenuBar: BEGIN
  1466.                     AdjustMenus;
  1467.                     DoMenuCommand(MenuSelect(event.where));
  1468.                 END;
  1469.                 inSysWindow:
  1470.                     SystemClick(event, window);
  1471.                 inContent:
  1472.                     IF window <> FrontWindow THEN BEGIN
  1473.                         SelectWindow(window);
  1474.                         {DoEvent(event);}    {use this line for "do first click"}
  1475.                     END ELSE
  1476.                         DoContentClick(window, event);
  1477.                 inDrag:
  1478.                     DragWindow(window, event.where, screenBits.bounds);
  1479.                 inGrow:
  1480.                     DoGrowWindow(window, event);
  1481.                 inGoAway:
  1482.                     IF TrackGoAway(window, event.where) THEN
  1483.                         ignore := DoCloseWindow(window);        {we don't care if cancelled}
  1484.                 inZoomIn, inZoomOut:
  1485.                     IF TrackBox(window, event.where, part) THEN
  1486.                         DoZoomWindow(window, part);
  1487.             END;
  1488.         END;
  1489.         keyDown, autoKey: BEGIN
  1490.             key := CHR(BAnd(event.message, charCodeMask));
  1491.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN BEGIN    {Command key down}
  1492.                 IF event.what = keyDown THEN BEGIN
  1493.                     AdjustMenus;            {enable/disable/check menu items properly}
  1494.                     DoMenuCommand(MenuKey(key));
  1495.                 END;
  1496.             END ELSE
  1497.                 DoKeyDown(event);
  1498.         END;                                {call DoActivate with the window and...}
  1499.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  1500.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  1501.         updateEvt:                            {call DoUpdate with the window to update}
  1502.             DoUpdate(WindowPtr(event.message));
  1503.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  1504.          to a diskEvt, so that the user can format a floppy.}
  1505.         diskEvt:
  1506.             IF HiWrd(event.message) <> noErr THEN BEGIN
  1507.                 SetPt(aPoint, kDILeft, kDITop);
  1508.                 err := DIBadMount(aPoint, event.message);
  1509.             END;
  1510.         kOSEvent:
  1511.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  1512.                 kMouseMovedMessage:
  1513.                     DoIdle;                    {mouse moved is also an idle event}
  1514.                 kSuspendResumeMessage: BEGIN
  1515.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  1516.                     DoActivate(FrontWindow, NOT gInBackground);
  1517.                 END;
  1518.             END;
  1519.     END;
  1520. END; {DoEvent}
  1521.  
  1522.  
  1523. {$S Main}
  1524. PROCEDURE EventLoop;
  1525.  
  1526. {Get events forever, and handle them by calling DoEvent.
  1527.  Also call AdjustCursor each time through the loop.}
  1528.  
  1529. VAR
  1530.     cursorRgn    : RgnHandle;
  1531.     gotEvent    : BOOLEAN;
  1532.     event        : EventRecord;
  1533.     mouse        : Point;
  1534.  
  1535. BEGIN
  1536.     cursorRgn := NewRgn;        {we'll pass an empty region to WNE the first time thru}
  1537.     REPEAT
  1538.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  1539.             GetGlobalMouse(mouse);        {since we might go to sleep}
  1540.             AdjustCursor(mouse, cursorRgn);
  1541.             gotEvent := WaitNextEvent(everyEvent, event, GetSleep, cursorRgn);
  1542.         END ELSE BEGIN
  1543.             SystemTask;                    {must be called if using GetNextEvent}
  1544.             gotEvent := GetNextEvent(everyEvent, event);
  1545.         END;
  1546.         IF gotEvent THEN BEGIN
  1547.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  1548.             DoEvent(event);                {Handle the event only if for us.}
  1549.             END
  1550.         ELSE
  1551.             DoIdle;
  1552.         {If you are using modeless dialogs that have editText items,
  1553.          you will want to call IsDialogEvent to give the caret a chance
  1554.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  1555.          for a non-NIL value before calling IsDialogEvent.}
  1556.     UNTIL FALSE;    {loop forever}
  1557. END; {EventLoop}
  1558.  
  1559.  
  1560. PROCEDURE _DataInit; EXTERNAL;
  1561.  
  1562. {This routine is automatically linked in by the MPW Linker. This external
  1563.  reference to it is done so that we can unload its segment, %A5Init.}
  1564.  
  1565.  
  1566. {$S Main}
  1567. BEGIN
  1568.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  1569.     
  1570.     {1.01 - call to ForceEnvirons removed}
  1571.     {If you have stack requirements that differ from the default,
  1572.      then you could use SetApplLimit to increase StackSpace at 
  1573.      this point, before calling MaxApplZone.}
  1574.      
  1575.     MaxApplZone;            {expand the heap so code segments load at the top}
  1576.  
  1577.     Initialize;                {initialize the program}
  1578.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  1579.  
  1580.     EventLoop;                {call the main event loop}
  1581. END.
  1582.