home *** CD-ROM | disk | FTP | other *** search
/ Otherware / Otherware_1_SB_Development.iso / mac / developm / scnote / tesample.002 / TESample.p < prev    next >
Text File  |  1989-06-01  |  52KB  |  1,580 lines

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