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

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