home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 August: Tool Chest / Apple_Developer_CD_Series_August_1997_Tool_Chest.iso / Sample Code / Overview / Sample / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-18  |  21.4 KB  |  654 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.c    -    C Source (main segment)
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                06/92
  20. #
  21. #    Components:
  22. #                Sample.p            June 1, 1989
  23. #                Sample.c            June 1, 1989
  24. #                SampleInit.c        June 2, 1992
  25. #                Sample.a            June 1, 1989
  26. #                Sample.inc1.a        June 1, 1989
  27. #                SampleMisc.a        June 1, 1989
  28. #                Sample.r            June 1, 1989
  29. #                Sample.h            June 1, 1989
  30. #                PSample.make        June 1, 1989
  31. #                CSample.make        June 1, 1989
  32. #                ASample.make        June 1, 1989
  33. #                CSample.π            June 2, 1992
  34. #                CSample.π.rsrc        June 2, 1992
  35. #
  36. #    Sample is an example application that demonstrates how to
  37. #    initialize the commonly used toolbox managers, operate 
  38. #    successfully under MultiFinder, handle desk accessories, 
  39. #    and create, grow, and zoom windows.
  40. #
  41. #    It does not by any means demonstrate all the techniques 
  42. #    you need for a large application. In particular, Sample 
  43. #    does not cover exception handling, multiple windows/documents, 
  44. #    sophisticated memory management, printing, or undo. All of 
  45. #    these are vital parts of a normal full-sized application.
  46. #
  47. #    This application is an example of the form of a Macintosh 
  48. #    application; it is NOT a template. It is NOT intended to be 
  49. #    used as a foundation for the next world-class, best-selling, 
  50. #    600K application. A stick figure drawing of the human body may 
  51. #    be a good example of the form for a painting, but that does not 
  52. #    mean it should be used as the basis for the next Mona Lisa.
  53. #
  54. #    We recommend that you review this program or TESample before 
  55. #    beginning a new application.
  56. #
  57. ------------------------------------------------------------------------------*/
  58.  
  59.  
  60. /* Segmentation strategy:
  61.  
  62.    This program consists of three segments.
  63.    1. "Main" contains most of the code, including the MPW libraries, and the
  64.       main program.  This segment is in the file Sample.c
  65.    2. "Initialize" contains code that is only used once, during startup, and
  66.       can be unloaded after the program starts.  This segment is in the file
  67.       SampleInit.c.
  68.    3. "%A5Init" is automatically created by the Linker to initialize globals
  69.       for the MPW libraries and is unloaded right away. */
  70.  
  71.  
  72. /* SetPort strategy:
  73.  
  74.    Toolbox routines do not change the current port. In spite of this, in this
  75.    program we use a strategy of calling SetPort whenever we want to draw or
  76.    make calls which depend on the current port. This makes us less vulnerable
  77.    to bugs in other software which might alter the current port (such as the
  78.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  79.    Hopefully, this also makes the routines from this program more self-contained,
  80.    since they don't depend on the current port setting. */
  81.  
  82. #pragma segment Main
  83.  
  84. #include <Limits.h>
  85. #include <Types.h>
  86. #include <Resources.h>
  87. #include <QuickDraw.h>
  88. #include <Fonts.h>
  89. #include <Events.h>
  90. #include <Windows.h>
  91. #include <Menus.h>
  92. #include <TextEdit.h>
  93. #include <Dialogs.h>
  94. #include <Desk.h>
  95. #include <ToolUtils.h>
  96. #include <Memory.h>
  97. #include <SegLoad.h>
  98. #include <Files.h>
  99. #include <OSUtils.h>
  100. #include <DiskInit.h>
  101. #include <Packages.h>
  102. #include <Traps.h>
  103. #include "Sample.h"        /* bring in all the #defines for Sample */
  104.  
  105. /* The "g" prefix is used to emphasize that a variable is global. */
  106.  
  107. /* GMac is used to hold the result of a SysEnvirons call. This makes
  108.    it convenient for any routine to check the environment. */
  109. SysEnvRec    gMac;                /* set up by Initialize */
  110.  
  111. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  112.    trap is available. If it is false, we know that we must call GetNextEvent. */
  113. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  114.  
  115. /* GInBackground is maintained by our osEvent handling routines. Any part of
  116.    the program can check it to find out if it is currently in the background. */
  117. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  118.  
  119.  
  120. /* The following globals are the state of the window. If we supported more than
  121.    one window, they would be attatched to each document, rather than globals. */
  122.  
  123. /* GStopped tells whether the stop light is currently on stop or go. */
  124. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  125.  
  126. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  127. Rect        gStopRect;            /* set up by Initialize */
  128. Rect        gGoRect;            /* set up by Initialize */
  129.  
  130.  
  131. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  132.    dependency on the ordering of fields within a Rect */
  133. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  134. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  135.  
  136.  
  137. /* This routine is part of the MPW runtime library. This external
  138.    reference to it is done so that we can unload its segment, %A5Init. */
  139.    
  140. #ifndef THINK_C
  141.   extern void _DataInit();
  142. #endif
  143.  
  144.  
  145. main()
  146. {
  147. #ifndef THINK_C
  148.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  149. #endif
  150.  
  151.     /* 1.01 - call to ForceEnvirons removed */
  152.     
  153.     /*    If you have stack requirements that differ from the default,
  154.         then you could use SetApplLimit to increase StackSpace at 
  155.         this point, before calling MaxApplZone. */
  156.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  157.  
  158.     Initialize();                    /* initialize the program */
  159.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  160.  
  161.     EventLoop();                    /* call the main event loop */
  162. }
  163.  
  164.  
  165. /*    Get events forever, and handle them by calling DoEvent.
  166.     Get the events by calling WaitNextEvent, if it's available, otherwise
  167.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  168.  
  169. void EventLoop()
  170. {
  171.     RgnHandle    cursorRgn;
  172.     Boolean        gotEvent;
  173.     EventRecord    event;
  174.     Point        mouse;
  175.  
  176.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  177.     do {
  178.         /* use WNE if it is available */
  179.         if ( gHasWaitNextEvent ) {
  180.             GetGlobalMouse(&mouse);
  181.             AdjustCursor(mouse, cursorRgn);
  182.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  183.         }
  184.         else {
  185.             SystemTask();
  186.             gotEvent = GetNextEvent(everyEvent, &event);
  187.         }
  188.         if ( gotEvent ) {
  189.             /* make sure we have the right cursor before handling the event */
  190.             AdjustCursor(event.where, cursorRgn);
  191.             DoEvent(&event);
  192.         }
  193.         /*    If you are using modeless dialogs that have editText items,
  194.             you will want to call IsDialogEvent to give the caret a chance
  195.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  196.             for a non-NIL value before calling IsDialogEvent. */
  197.     } while ( true );    /* loop forever; we quit via ExitToShell */
  198. } /*EventLoop*/
  199.  
  200.  
  201. /* Do the right thing for an event. Determine what kind of event it is, and call
  202.  the appropriate routines. */
  203.  
  204. void DoEvent(EventRecord *event)
  205. {
  206.     short        part, err;
  207.     WindowPtr    window;
  208.     Boolean        hit;
  209.     char        key;
  210.     Point        aPoint;
  211.  
  212.     switch ( event->what ) {
  213.         case mouseDown:
  214.             part = FindWindow(event->where, &window);
  215.             switch ( part ) {
  216.                 case inMenuBar:                /* process a mouse menu command (if any) */
  217.                     AdjustMenus();
  218.                     DoMenuCommand(MenuSelect(event->where));
  219.                     break;
  220.                 case inSysWindow:            /* let the system handle the mouseDown */
  221.                     SystemClick(event, window);
  222.                     break;
  223.                 case inContent:
  224.                     if ( window != FrontWindow() ) {
  225.                         SelectWindow(window);
  226.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  227.                     } else
  228.                         DoContentClick(window);
  229.                     break;
  230.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  231.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  232.                     break;
  233.                 case inGrow:
  234.                     break;
  235.                 case inZoomIn:
  236.                 case inZoomOut:
  237.                     hit = TrackBox(window, event->where, part);
  238.                     if ( hit ) {
  239.                         SetPort(window);                /* the window must be the current port... */
  240.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  241.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  242.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  243.                     }
  244.                     break;
  245.             }
  246.             break;
  247.         case keyDown:
  248.         case autoKey:                        /* check for menukey equivalents */
  249.             key = event->message & charCodeMask;
  250.             if ( event->modifiers & cmdKey )            /* Command key down */
  251.                 if ( event->what == keyDown ) {
  252.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  253.                     DoMenuCommand(MenuKey(key));
  254.                 }
  255.             break;
  256.         case activateEvt:
  257.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  258.             break;
  259.         case updateEvt:
  260.             DoUpdate((WindowPtr) event->message);
  261.             break;
  262.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  263.             to a diskEvt, so that the user can format a floppy. */
  264.         case diskEvt:
  265.             if ( HiWord(event->message) != noErr ) {
  266.                 SetPt(&aPoint, kDILeft, kDITop);
  267.                 err = DIBadMount(aPoint, event->message);
  268.             }
  269.             break;
  270.         case kOSEvent:
  271.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  272.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  273.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  274.                     gInBackground = (event->message & kResumeMask) == 0;
  275.                     DoActivate(FrontWindow(), !gInBackground);
  276.                     break;
  277.             }
  278.             break;
  279.     }
  280. } /*DoEvent*/
  281.  
  282.  
  283. /*    Change the cursor's shape, depending on its position. This also calculates the region
  284.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  285.     that region, an event would be generated, causing this routine to be called,
  286.     allowing us to change the region to the region the mouse is currently in. If
  287.     there is more to the event than just “the mouse moved”, we get called before the
  288.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  289.     this is called again before we     fall back into WNE. */
  290.  
  291. void AdjustCursor(Point mouse, RgnHandle region)
  292. {
  293.     WindowPtr    window;
  294.     RgnHandle    arrowRgn;
  295.     RgnHandle    plusRgn;
  296.     Rect        globalPortRect;
  297.  
  298.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  299.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  300.         /* calculate regions for different cursor shapes */
  301.         arrowRgn = NewRgn();
  302.         plusRgn = NewRgn();
  303.  
  304.         /* start with a big, big rectangular region */
  305.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  306.  
  307.         /* calculate plusRgn */
  308.         if ( IsAppWindow(window) ) {
  309.             SetPort(window);    /* make a global version of the viewRect */
  310.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  311.             globalPortRect = window->portRect;
  312.             RectRgn(plusRgn, &globalPortRect);
  313.             SectRgn(plusRgn, window->visRgn, plusRgn);
  314.             SetOrigin(0, 0);
  315.         }
  316.  
  317.         /* subtract other regions from arrowRgn */
  318.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  319.  
  320.         /* change the cursor and the region parameter */
  321.         if ( PtInRgn(mouse, plusRgn) ) {
  322.             SetCursor(*GetCursor(plusCursor));
  323.             CopyRgn(plusRgn, region);
  324.         } else {
  325.             SetCursor(&qd.arrow);
  326.             CopyRgn(arrowRgn, region);
  327.         }
  328.  
  329.         /* get rid of our local regions */
  330.         DisposeRgn(arrowRgn);
  331.         DisposeRgn(plusRgn);
  332.     }
  333. } /*AdjustCursor*/
  334.  
  335.  
  336. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  337.     it will return either a pending event or a null event. In either case,
  338.     the where field of the event record will contain the current position
  339.     of the mouse in global coordinates and the modifiers field will reflect
  340.     the current state of the modifiers. Another way to get the global
  341.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  342.     being sure that thePort is set to a valid port. */
  343.  
  344. void GetGlobalMouse(Point *mouse)
  345. {
  346.     EventRecord    event;
  347.     
  348.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  349.     *mouse = event.where;                /* just the mouse position */
  350. } /*GetGlobalMouse*/
  351.  
  352.  
  353. /*    This is called when an update event is received for a window.
  354.     It calls DrawWindow to draw the contents of an application window.
  355.     As an effeciency measure that does not have to be followed, it
  356.     calls the drawing routine only if the visRgn is non-empty. This
  357.     will handle situations where calculations for drawing or drawing
  358.     itself is very time-consuming. */
  359.  
  360. void DoUpdate(WindowPtr window)
  361. {
  362.     if ( IsAppWindow(window) ) {
  363.         BeginUpdate(window);                /* this sets up the visRgn */
  364.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  365.             DrawWindow(window);
  366.         EndUpdate(window);
  367.     }
  368. } /*DoUpdate*/
  369.  
  370.  
  371. /*    This is called when a window is activated or deactivated.
  372.     In Sample, the Window Manager's handling of activate and
  373.     deactivate events is sufficient. Other applications may have
  374.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  375.  
  376. void DoActivate(WindowPtr window, Boolean becomingActive)
  377. {
  378.     if ( IsAppWindow(window) ) {
  379.         if ( becomingActive )
  380.             /* do whatever you need to at activation */ ;
  381.         else
  382.             /* do whatever you need to at deactivation */ ;
  383.     }
  384. } /*DoActivate*/
  385.  
  386.  
  387. /*    This is called when a mouse-down event occurs in the content of a window.
  388.     Other applications might want to call FindControl, TEClick, etc., to
  389.     further process the click. */
  390.  
  391. void DoContentClick(WindowPtr window)
  392. {
  393.     SetLight(window, ! gStopped);
  394. } /*DoContentClick*/
  395.  
  396.  
  397. /* Draw the contents of the application window. We do some drawing in color, using
  398.    Classic QuickDraw's color capabilities. This will be black and white on old
  399.    machines, but color on color machines. At this point, the window’s visRgn
  400.    is set to allow drawing only where it needs to be done. */
  401.  
  402. void DrawWindow(WindowPtr window)
  403. {
  404.     SetPort(window);
  405.  
  406.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  407.     if ( gStopped )                    /* draw a red (or white) stop light */
  408.         ForeColor(redColor);
  409.     else
  410.         ForeColor(whiteColor);
  411.     PaintOval(&gStopRect);
  412.     ForeColor(blackColor);
  413.     FrameOval(&gStopRect);
  414.     if ( ! gStopped )                /* draw a green (or white) go light */
  415.         ForeColor(greenColor);
  416.     else
  417.         ForeColor(whiteColor);
  418.     PaintOval(&gGoRect);
  419.     ForeColor(blackColor);
  420.     FrameOval(&gGoRect);
  421. } /*DrawWindow*/
  422.  
  423.  
  424. /*    Enable and disable menus based on the current state.
  425.     The user can only select enabled menu items. We set up all the menu items
  426.     before calling MenuSelect or MenuKey, since these are the only times that
  427.     a menu item can be selected. Note that MenuSelect is also the only time
  428.     the user will see menu items. This approach to deciding what enable/
  429.     disable state a menu item has the advantage of concentrating all
  430.     the decision-making in one routine, as opposed to being spread throughout
  431.     the application. Other application designs may take a different approach
  432.     that is just as valid. */
  433.  
  434. void AdjustMenus()
  435. {
  436.     WindowPtr    window;
  437.     MenuHandle    menu;
  438.  
  439.     window = FrontWindow();
  440.  
  441.     menu = GetMenuHandle(mFile);
  442.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  443.         EnableItem(menu, iClose);
  444.     else
  445.         DisableItem(menu, iClose);    /* but not our traffic light window */
  446.  
  447.     menu = GetMenuHandle(mEdit);
  448.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  449.         EnableItem(menu, iUndo);
  450.         EnableItem(menu, iCut);
  451.         EnableItem(menu, iCopy);
  452.         EnableItem(menu, iClear);
  453.         EnableItem(menu, iPaste);
  454.     } else {                        /* …but we don’t use it */
  455.         DisableItem(menu, iUndo);
  456.         DisableItem(menu, iCut);
  457.         DisableItem(menu, iCopy);
  458.         DisableItem(menu, iClear);
  459.         DisableItem(menu, iPaste);
  460.     }
  461.  
  462.     menu = GetMenuHandle(mLight);
  463.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  464.         EnableItem(menu, iStop);
  465.         EnableItem(menu, iGo);
  466.     } else {
  467.         DisableItem(menu, iStop);
  468.         DisableItem(menu, iGo);
  469.     }
  470.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  471.     CheckItem(menu, iGo, ! gStopped);
  472. } /*AdjustMenus*/
  473.  
  474.  
  475. /*    This is called when an item is chosen from the menu bar (after calling
  476.     MenuSelect or MenuKey). It performs the right operation for each command.
  477.     It is good to have both the result of MenuSelect and MenuKey go to
  478.     one routine like this to keep everything organized. */
  479.  
  480. void DoMenuCommand(long menuResult)
  481. {
  482.     short        menuID;                /* the resource ID of the selected menu */
  483.     short        menuItem;            /* the item number of the selected menu */
  484.     short        itemHit;
  485.     Str255        daName;
  486.     short        daRefNum;
  487.     Boolean        handledByDA;
  488.  
  489.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  490.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  491.     switch ( menuID ) {
  492.         case mApple:
  493.             switch ( menuItem ) {
  494.                 case iAbout:        /* bring up alert for About */
  495.                     itemHit = Alert(rAboutAlert, nil);
  496.                     break;
  497.                 default:            /* all non-About items in this menu are DAs */
  498.                     /* type Str255 is an array in MPW 3 */
  499.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  500.                     daRefNum = OpenDeskAcc(daName);
  501.                     break;
  502.             }
  503.             break;
  504.         case mFile:
  505.             switch ( menuItem ) {
  506.                 case iClose:
  507.                     DoCloseWindow(FrontWindow());
  508.                     break;
  509.                 case iQuit:
  510.                     Terminate();
  511.                     break;
  512.             }
  513.             break;
  514.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  515.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  516.             break;
  517.         case mLight:
  518.             switch ( menuItem ) {
  519.                 case iStop:
  520.                     SetLight(FrontWindow(), true);
  521.                     break;
  522.                 case iGo:
  523.                     SetLight(FrontWindow(), false);
  524.                     break;
  525.             }
  526.             break;
  527.     }
  528.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  529. } /*DoMenuCommand*/
  530.  
  531.  
  532. /* Change the setting of the light. */
  533.  
  534. void SetLight(WindowPtr window, Boolean newStopped)
  535. {
  536.     if ( newStopped != gStopped ) {
  537.         gStopped = newStopped;
  538.         SetPort(window);
  539.         InvalRect(&window->portRect);
  540.     }
  541. } /*SetLight*/
  542.  
  543.  
  544. /* Close a window. This handles desk accessory and application windows. */
  545.  
  546. /*    1.01 - At this point, if there was a document associated with a
  547.     window, you could do any document saving processing if it is 'dirty'.
  548.     DoCloseWindow would return true if the window actually closed, i.e.,
  549.     the user didn’t cancel from a save dialog. This result is handy when
  550.     the user quits an application, but then cancels the save of a document
  551.     associated with a window. */
  552.  
  553. Boolean DoCloseWindow(WindowPtr window)
  554. {
  555.     if ( IsDAWindow(window) )
  556.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  557.     else if ( IsAppWindow(window) )
  558.         CloseWindow(window);
  559.     return true;
  560. } /*DoCloseWindow*/
  561.  
  562.  
  563. /**************************************************************************************
  564. *** 1.01 DoCloseBehind(window) was removed ***
  565.  
  566.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  567.     and not having to worry about updating the windows, but it suffered
  568.     from a fatal flaw. If a desk accessory owned two windows, it would
  569.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  570.     got around to calling DoCloseWindow for that other window that was already
  571.     closed, things would go very poorly. Another option would be to have a
  572.     procedure, GetRearWindow, that would go through the window list and return
  573.     the last window. Instead, we decided to present the standard approach
  574.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  575.     has a potential benefit in that the window whose document needs to be saved
  576.     may be visible since it is the front window, therefore decreasing the
  577.     chance of user confusion. For aesthetic reasons, the windows in the
  578.     application should be checked for updates periodically and have the
  579.     updates serviced.
  580. **************************************************************************************/
  581.  
  582.  
  583. /* Clean up the application and exit. We close all of the windows so that
  584.  they can update their documents, if any. */
  585.  
  586. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  587.     shell, but will return instead. */
  588.  
  589. void Terminate()
  590. {
  591.     WindowPtr    aWindow;
  592.     Boolean        closed;
  593.     
  594.     closed = true;
  595.     do {
  596.         aWindow = FrontWindow();                /* get the current front window */
  597.         if (aWindow != nil)
  598.             closed = DoCloseWindow(aWindow);    /* close this window */    
  599.     }
  600.     while (closed && (aWindow != nil));
  601.     if (closed)
  602.         ExitToShell();                            /* exit if no cancellation */
  603. } /*Terminate*/
  604.  
  605. /*    Check to see if a window belongs to the application. If the window pointer
  606.     passed was NIL, then it could not be an application window. WindowKinds
  607.     that are negative belong to the system and windowKinds less than userKind
  608.     are reserved by Apple except for windowKinds equal to dialogKind, which
  609.     mean it is a dialog.
  610.     1.02 - In order to reduce the chance of accidentally treating some window
  611.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  612.     is userKind. If you add different kinds of windows to Sample you'll need
  613.     to change how this all works. */
  614.  
  615. Boolean IsAppWindow(WindowPtr window)
  616. {
  617.     short        windowKind;
  618.  
  619.     if ( window == nil )
  620.         return false;
  621.     else {    /* application windows have windowKinds = userKind (8) */
  622.         windowKind = ((WindowPeek) window)->windowKind;
  623.         return ( windowKind == userKind );
  624.     }
  625. } /*IsAppWindow*/
  626.  
  627.  
  628. /* Check to see if a window belongs to a desk accessory. */
  629.  
  630. Boolean IsDAWindow(WindowPtr window)
  631. {
  632.     if ( window == nil )
  633.         return false;
  634.     else    /* DA windows have negative windowKinds */
  635.         return ( ((WindowPeek) window)->windowKind < 0 );
  636. } /*IsDAWindow*/
  637.  
  638.  
  639. /*    Display an alert that tells the user an error occurred, then exit the program.
  640.     This routine is used as an ultimate bail-out for serious errors that prohibit
  641.     the continuation of the application. Errors that do not require the termination
  642.     of the application should be handled in a different manner. Error checking and
  643.     reporting has a place even in the simplest application. The error number is used
  644.     to index an 'STR#' resource so that a relevant message can be displayed. */
  645.  
  646. void AlertUser()
  647. {
  648.     short        itemHit;
  649.  
  650.     SetCursor(&qd.arrow);
  651.     itemHit = Alert(rUserAlert, nil);
  652.     ExitToShell();
  653. } /* AlertUser */
  654.