home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 1.toast / Sample Code / Human Interface Toolbox / WDEFColorSample / WDEFColorSample.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-28  |  26.7 KB  |  791 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        WDEFColorSample.c
  3.  
  4.     Contains:    WDEFSample shows in high level what the system 7 WDEF does as far as
  5.                 choosing colors is concerned.
  6.  
  7.     Written by:     
  8.  
  9.     Copyright:    Copyright © 1989-1999 by Apple Computer, Inc., All Rights Reserved.
  10.  
  11.                 You may incorporate this Apple sample source code into your program(s) without
  12.                 restriction. This Apple sample source code has been provided "AS IS" and the
  13.                 responsibility for its operation is yours. You are not permitted to redistribute
  14.                 this Apple sample source code as "Apple sample source code" after having made
  15.                 changes. If you're going to re-distribute the source, we require that you make
  16.                 it clear in the source that the code was descended from Apple sample source
  17.                 code, but that you've made changes.
  18.  
  19.     Change History (most recent first):
  20.                 8/11/1999    Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
  21.                 
  22.  
  23. */
  24. #include <Resources.h>
  25. #include <Fonts.h>
  26. #include <Dialogs.h>
  27. #include <Desk.h>
  28. #include <ToolUtils.h>
  29. #include <SegLoad.h>
  30. #include <DiskInit.h>
  31. #include <Traps.h>
  32.  
  33.  
  34. #include "WDEFColorSample.h"        /* bring in all the #defines for WDEFColorSample */
  35.  
  36.  
  37. /* The "g" prefix is used to emphasize that a variable is global. */
  38.  
  39. /* GMac is used to hold the result of a SysEnvirons call. This makes
  40.    it convenient for any routine to check the environment. */
  41. SysEnvRec    gMac;                /* set up by Initialize */
  42.  
  43. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  44.    trap is available. If it is false, we know that we must call GetNextEvent. */
  45. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  46.  
  47. /* GInBackground is maintained by our osEvent handling routines. Any part of
  48.    the program can check it to find out if it is currently in the background. */
  49. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  50.  
  51.  
  52. /* The following globals are the state of the window. If we supported more than
  53.    one window, they would be attatched to each document, rather than globals. */
  54.  
  55. /* GStopped tells whether the stop light is currently on stop or go. */
  56. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  57.  
  58. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  59. Rect        gStopRect;            /* set up by Initialize */
  60. Rect        gGoRect;            /* set up by Initialize */
  61.  
  62.  
  63. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  64.    actual prototypes for parameter type checking. */
  65. void EventLoop( void );
  66. void DoEvent( EventRecord *event );
  67. void AdjustCursor( Point mouse, RgnHandle region );
  68. void GetGlobalMouse( Point *mouse );
  69. void DoUpdate( WindowPtr window );
  70. void DoActivate( WindowPtr window, Boolean becomingActive );
  71. void DoContentClick( WindowPtr window );
  72. void DrawWindow( WindowPtr window );
  73. void AdjustMenus( void );
  74. void DoMenuCommand( long menuResult );
  75. void SetLight( WindowPtr window, Boolean newStopped );
  76. Boolean DoCloseWindow( WindowPtr window );
  77. void Terminate( void );
  78. void Initialize( void );
  79. Boolean GoGetRect( short rectID, Rect *theRect );
  80. void ForceEnvirons( void );
  81. Boolean IsAppWindow( WindowPtr window );
  82. Boolean IsDAWindow( WindowPtr window );
  83. Boolean TrapAvail( short tNumber, TrapType tType );
  84. void AlertUser( void );
  85.  
  86. extern void FakeWDEF(WindowPtr window, Boolean hilite);
  87.  
  88. /* Define HiWrd and LoWrd macros for efficiency. */
  89. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  90. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  91.  
  92. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  93.    dependency on the ordering of fields within a Rect */
  94. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  95. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  96.  
  97.  
  98. extern void _DataInit();
  99.  
  100. /* This routine is part of the MPW runtime library. This external
  101.    reference to it is done so that we can unload its segment, %A5Init. */
  102.  
  103.  
  104. #pragma segment Main
  105. void main()
  106. {
  107.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  108.     
  109.     /* 1.01 - call to ForceEnvirons removed */
  110.     
  111.     /*    If you have stack requirements that differ from the default,
  112.         then you could use SetApplLimit to increase StackSpace at 
  113.         this point, before calling MaxApplZone. */
  114.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  115.  
  116.     Initialize();                    /* initialize the program */
  117.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  118.  
  119.     EventLoop();                    /* call the main event loop */
  120. }
  121.  
  122.  
  123. /*    Get events forever, and handle them by calling DoEvent.
  124.     Get the events by calling WaitNextEvent, if it's available, otherwise
  125.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  126.  
  127. #pragma segment Main
  128. void EventLoop()
  129. {
  130.     RgnHandle    cursorRgn;
  131.     Boolean        gotEvent;
  132.     EventRecord    event;
  133.     Point        mouse;
  134.  
  135.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  136.     do {
  137.         /* use WNE if it is available */
  138.         if ( gHasWaitNextEvent ) {
  139.             GetGlobalMouse(&mouse);
  140.             AdjustCursor(mouse, cursorRgn);
  141.             gotEvent = WaitNextEvent(everyEvent, &event, 60, cursorRgn);
  142.         }
  143.         else {
  144.             SystemTask();
  145.             gotEvent = GetNextEvent(everyEvent, &event);
  146.         }
  147.         if ( gotEvent ) {
  148.             /* make sure we have the right cursor before handling the event */
  149.             AdjustCursor(event.where, cursorRgn);
  150.             DoEvent(&event);
  151.         }
  152.         /*    If you are using modeless dialogs that have editText items,
  153.             you will want to call IsDialogEvent to give the caret a chance
  154.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  155.             for a non-NIL value before calling IsDialogEvent. */
  156.     } while ( true );    /* loop forever; we quit via ExitToShell */
  157. } /*EventLoop*/
  158.  
  159.  
  160. /* Do the right thing for an event. Determine what kind of event it is, and call
  161.  the appropriate routines. */
  162.  
  163. #pragma segment Main
  164. void DoEvent(EventRecord    *event)
  165. {
  166.     short        part, err;
  167.     WindowPtr    window;
  168.     Boolean        hit;
  169.     char        key;
  170.     Point        aPoint;
  171.  
  172.     switch ( event->what ) {
  173.         case mouseDown:
  174.             part = FindWindow(event->where, &window);
  175.             switch ( part ) {
  176.                 case inMenuBar:                /* process a mouse menu command (if any) */
  177.                     AdjustMenus();
  178.                     DoMenuCommand(MenuSelect(event->where));
  179.                     break;
  180.                 case inSysWindow:            /* let the system handle the mouseDown */
  181.                     SystemClick(event, window);
  182.                     break;
  183.                 case inContent:
  184.                     if ( window != FrontWindow() ) {
  185.                         SelectWindow(window);
  186.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  187.                     } else
  188.                         DoContentClick(window);
  189.                     break;
  190.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  191.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  192.                     break;
  193.                 case inGrow:
  194.                     break;
  195.                 case inZoomIn:
  196.                 case inZoomOut:
  197.                     hit = TrackBox(window, event->where, part);
  198.                     if ( hit ) {
  199.                         SetPort(window);                /* the window must be the current port... */
  200.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  201.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  202.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  203.                     }
  204.                     break;
  205.             }
  206.             break;
  207.         case keyDown:
  208.         case autoKey:                        /* check for menukey equivalents */
  209.             key = event->message & charCodeMask;
  210.             if ( event->modifiers & cmdKey )            /* Command key down */
  211.                 if ( event->what == keyDown ) {
  212.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  213.                     DoMenuCommand(MenuKey(key));
  214.                 }
  215.             break;
  216.         case activateEvt:
  217.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  218.             break;
  219.         case updateEvt:
  220.             DoUpdate((WindowPtr) event->message);
  221.             break;
  222.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  223.             to a diskEvt, so that the user can format a floppy. */
  224.         case diskEvt:
  225.             if ( HiWord(event->message) != noErr ) {
  226.                 SetPt(&aPoint, kDILeft, kDITop);
  227.                 err = DIBadMount(aPoint, event->message);
  228.             }
  229.             break;
  230.         case kOSEvent:
  231.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  232.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  233.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  234.                     gInBackground = (event->message & kResumeMask) == 0;
  235.                     DoActivate(FrontWindow(), !gInBackground);
  236.                     break;
  237.             }
  238.             break;
  239.     }
  240. } /*DoEvent*/
  241.  
  242.  
  243. /*    Change the cursor's shape, depending on its position. This also calculates the region
  244.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  245.     that region, an event would be generated, causing this routine to be called,
  246.     allowing us to change the region to the region the mouse is currently in. If
  247.     there is more to the event than just “the mouse moved”, we get called before the
  248.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  249.     this is called again before we     fall back into WNE. */
  250.  
  251. #pragma segment Main
  252. void AdjustCursor(Point mouse,RgnHandle region)
  253. {
  254.     WindowPtr    window;
  255.     RgnHandle    arrowRgn;
  256.     RgnHandle    plusRgn;
  257.     Rect        globalPortRect;
  258.  
  259.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  260.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  261.         /* calculate regions for different cursor shapes */
  262.         arrowRgn = NewRgn();
  263.         plusRgn = NewRgn();
  264.  
  265.         /* start with a big, big rectangular region */
  266.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  267.  
  268.         /* calculate plusRgn */
  269.         if ( IsAppWindow(window) ) {
  270.             SetPort(window);    /* make a global version of the viewRect */
  271.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  272.             globalPortRect = window->portRect;
  273.             RectRgn(plusRgn, &globalPortRect);
  274.             SectRgn(plusRgn, window->visRgn, plusRgn);
  275.             SetOrigin(0, 0);
  276.         }
  277.  
  278.         /* subtract other regions from arrowRgn */
  279.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  280.  
  281.         /* change the cursor and the region parameter */
  282.         if ( PtInRgn(mouse, plusRgn) ) {
  283.             SetCursor(*GetCursor(plusCursor));
  284.             CopyRgn(plusRgn, region);
  285.         } else {
  286.             SetCursor(&qd.arrow);
  287.             CopyRgn(arrowRgn, region);
  288.         }
  289.  
  290.         /* get rid of our local regions */
  291.         DisposeRgn(arrowRgn);
  292.         DisposeRgn(plusRgn);
  293.     }
  294. } /*AdjustCursor*/
  295.  
  296.  
  297. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  298.     it will return either a pending event or a null event. In either case,
  299.     the where field of the event record will contain the current position
  300.     of the mouse in global coordinates and the modifiers field will reflect
  301.     the current state of the modifiers. Another way to get the global
  302.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  303.     being sure that thePort is set to a valid port. */
  304.  
  305. #pragma segment Main
  306. void GetGlobalMouse(Point    *mouse)
  307. {
  308.     EventRecord    event;
  309.     
  310.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  311.     *mouse = event.where;                /* just the mouse position */
  312. } /*GetGlobalMouse*/
  313.  
  314.  
  315.  
  316.  
  317.  
  318.  
  319.  
  320. /*    This is called when an update event is received for a window.
  321.     It calls DrawWindow to draw the contents of an application window.
  322.     As an effeciency measure that does not have to be followed, it
  323.     calls the drawing routine only if the visRgn is non-empty. This
  324.     will handle situations where calculations for drawing or drawing
  325.     itself is very time-consuming. */
  326.  
  327. #pragma segment Main
  328. Boolean gHilite;
  329.  
  330. void DoUpdate(WindowPtr window)
  331. {
  332.     if ( IsAppWindow(window) ) {
  333.         BeginUpdate(window);                /* this sets up the visRgn */
  334.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  335.             DrawWindow(window);
  336.         if (gHilite) gHilite = false; else gHilite = true;
  337.         EndUpdate(window);
  338.     }
  339. } /*DoUpdate*/
  340.  
  341.  
  342. /*    This is called when a window is activated or deactivated.
  343.     Since we want to show color changes when activating/deactivating
  344.     we want to have an update in order to display the window in the
  345.     right colors.
  346. */
  347.  
  348. #pragma segment Main
  349. void DoActivate(WindowPtr window,Boolean becomingActive)
  350. {
  351.     if ( IsAppWindow(window) ) {
  352.         if ( becomingActive )
  353.             /* do whatever you need to at activation */ 
  354.             InvalRect(&(window->portRect));
  355.         else
  356.             /* do whatever you need to at deactivation */  
  357.             InvalRect(&(window->portRect));
  358.     }
  359. } /*DoActivate*/
  360.  
  361.  
  362. /*    This is called when a mouse-down event occurs in the content of a window.
  363.     Other applications might want to call FindControl, TEClick, etc., to
  364.     further process the click. */
  365.  
  366. #pragma segment Main
  367. void DoContentClick(WindowPtr window)
  368. {
  369.     SetLight(window, ! gStopped);
  370. } /*DoContentClick*/
  371.  
  372.  
  373. /* The core shield of tWDEFSample. When an update occurs we draw another window
  374.    using the same technique used by the WDEF.
  375. */
  376.  
  377. #pragma segment Main
  378. void DrawWindow(WindowPtr window)
  379. {
  380.     SetPort(window);
  381.  
  382.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  383.     
  384.     FakeWDEF(window, gHilite);
  385.     
  386. } /*DrawWindow*/
  387.  
  388.  
  389.  
  390. #pragma segment Main
  391. void AdjustMenus()
  392. {
  393.     WindowPtr    window;
  394.     MenuHandle    menu;
  395.  
  396.     window = FrontWindow();
  397.  
  398.     menu = GetMenuHandle(mFile);
  399.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  400.         EnableItem(menu, iClose);
  401.     else
  402.         DisableItem(menu, iClose);    /* but not our traffic light window */
  403.  
  404.     menu = GetMenuHandle(mEdit);
  405.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  406.         EnableItem(menu, iUndo);
  407.         EnableItem(menu, iCut);
  408.         EnableItem(menu, iCopy);
  409.         EnableItem(menu, iClear);
  410.         EnableItem(menu, iPaste);
  411.     } else {                        /* …but we don’t use it */
  412.         DisableItem(menu, iUndo);
  413.         DisableItem(menu, iCut);
  414.         DisableItem(menu, iCopy);
  415.         DisableItem(menu, iClear);
  416.         DisableItem(menu, iPaste);
  417.     }
  418.  
  419.     menu = GetMenuHandle(mLight);
  420.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  421.         EnableItem(menu, iStop);
  422.         EnableItem(menu, iGo);
  423.     } else {
  424.         DisableItem(menu, iStop);
  425.         DisableItem(menu, iGo);
  426.     }
  427.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  428.     CheckItem(menu, iGo, ! gStopped);
  429. } /*AdjustMenus*/
  430.  
  431.  
  432. /*    This is called when an item is chosen from the menu bar (after calling
  433.     MenuSelect or MenuKey). It performs the right operation for each command.
  434.     It is good to have both the result of MenuSelect and MenuKey go to
  435.     one routine like this to keep everything organized. */
  436.  
  437. #pragma segment Main
  438. void DoMenuCommand(long menuResult)
  439. {
  440.     short        menuID;                /* the resource ID of the selected menu */
  441.     short        menuItem;            /* the item number of the selected menu */
  442.     short        itemHit;
  443.     Str255        daName;
  444.     short        daRefNum;
  445.     Boolean        handledByDA;
  446.  
  447.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  448.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  449.     switch ( menuID ) {
  450.         case mApple:
  451.             switch ( menuItem ) {
  452.                 case iAbout:        /* bring up alert for About */
  453.                     itemHit = Alert(rAboutAlert, nil);
  454.                     break;
  455.                 default:            /* all non-About items in this menu are DAs */
  456.                     /* type Str255 is an array in MPW 3 */
  457.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  458.                     daRefNum = OpenDeskAcc(daName);
  459.                     break;
  460.             }
  461.             break;
  462.         case mFile:
  463.             switch ( menuItem ) {
  464.                 case iClose:
  465.                     DoCloseWindow(FrontWindow());
  466.                     break;
  467.                 case iQuit:
  468.                     Terminate();
  469.                     break;
  470.             }
  471.             break;
  472.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  473.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  474.             break;
  475.         case mLight:
  476.             switch ( menuItem ) {
  477.                 case iStop:
  478.                     SetLight(FrontWindow(), true);
  479.                     break;
  480.                 case iGo:
  481.                     SetLight(FrontWindow(), false);
  482.                     break;
  483.             }
  484.             break;
  485.     }
  486.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  487. } /*DoMenuCommand*/
  488.  
  489.  
  490. /* Change the setting of the light. */
  491.  
  492. #pragma segment Main
  493. void SetLight(WindowPtr window,Boolean newStopped )
  494. {
  495.     if ( newStopped != gStopped ) {
  496.         gStopped = newStopped;
  497.         SetPort(window);
  498.         InvalRect(&window->portRect);
  499.     }
  500. } /*SetLight*/
  501.  
  502.  
  503. /* Close a window. This handles desk accessory and application windows. */
  504.  
  505. /*    1.01 - At this point, if there was a document associated with a
  506.     window, you could do any document saving processing if it is 'dirty'.
  507.     DoCloseWindow would return true if the window actually closed, i.e.,
  508.     the user didn’t cancel from a save dialog. This result is handy when
  509.     the user quits an application, but then cancels the save of a document
  510.     associated with a window. */
  511.  
  512. #pragma segment Main
  513. Boolean DoCloseWindow(WindowPtr window)
  514. {
  515.     if ( IsDAWindow(window) )
  516.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  517.     else if ( IsAppWindow(window) )
  518.         CloseWindow(window);
  519.     return true;
  520. } /*DoCloseWindow*/
  521.  
  522.  
  523. /**************************************************************************************
  524. *** 1.01 DoCloseBehind(window) was removed ***
  525.  
  526.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  527.     and not having to worry about updating the windows, but it suffered
  528.     from a fatal flaw. If a desk accessory owned two windows, it would
  529.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  530.     got around to calling DoCloseWindow for that other window that was already
  531.     closed, things would go very poorly. Another option would be to have a
  532.     procedure, GetRearWindow, that would go through the window list and return
  533.     the last window. Instead, we decided to present the standard approach
  534.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  535.     has a potential benefit in that the window whose document needs to be saved
  536.     may be visible since it is the front window, therefore decreasing the
  537.     chance of user confusion. For aesthetic reasons, the windows in the
  538.     application should be checked for updates periodically and have the
  539.     updates serviced.
  540. **************************************************************************************/
  541.  
  542.  
  543. /* Clean up the application and exit. We close all of the windows so that
  544.  they can update their documents, if any. */
  545.  
  546. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  547.     shell, but will return instead. */
  548.  
  549. #pragma segment Main
  550. void Terminate()
  551. {
  552.     WindowPtr    aWindow;
  553.     Boolean        closed;
  554.     
  555.     closed = true;
  556.     do {
  557.         aWindow = FrontWindow();                /* get the current front window */
  558.         if (aWindow != nil)
  559.             closed = DoCloseWindow(aWindow);    /* close this window */    
  560.     }
  561.     while (closed && (aWindow != nil));
  562.     if (closed)
  563.         ExitToShell();                            /* exit if no cancellation */
  564. } /*Terminate*/
  565.  
  566.  
  567. /*    Set up the whole world, including global variables, Toolbox managers,
  568.     and menus. We also create our one application window at this time.
  569.     Since window storage is non-relocateable, how and when to allocate space
  570.     for windows is very important so that heap fragmentation does not occur.
  571.     Because Sample has only one window and it is only disposed when the application
  572.     quits, we will allocate its space here, before anything that might be a locked
  573.     relocatable object gets into the heap. This way, we can force the storage to be
  574.     in the lowest memory available in the heap. Window storage can differ widely
  575.     amongst applications depending on how many windows are created and disposed. */
  576.  
  577. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  578.     this module. If an error is detected, instead of merely doing an ExitToShell,
  579.     which leaves the user without much to go on, we call AlertUser, which puts
  580.     up a simple alert that just says an error occurred and then calls ExitToShell.
  581.     Since there is no other cleanup needed at this point if an error is detected,
  582.     this form of error- handling is acceptable. If more sophisticated error recovery
  583.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  584.  
  585. #pragma segment Initialize
  586. void Initialize()
  587. {
  588.     Handle        menuBar;
  589.     WindowPtr    window;
  590.     long        total, contig;
  591.     EventRecord event;
  592.     short        count;
  593.  
  594.     gInBackground = false;
  595.  
  596.     InitGraf((Ptr) &qd.thePort);
  597.     InitFonts();
  598.     InitWindows();
  599.     InitMenus();
  600.     TEInit();
  601.     InitDialogs(nil);
  602.     InitCursor();
  603.     
  604.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  605.          if you are using it. */
  606.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  607.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  608.         of checking for port availability themselves. */
  609.     
  610.     /*    This next bit of code is necessary to allow the default button of our
  611.         alert be outlined.
  612.         1.02 - Changed to call EventAvail so that we don't lose some important
  613.         events. */
  614.      
  615.     for (count = 1; count <= 3; count++)
  616.         EventAvail(everyEvent, &event);
  617.     
  618.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  619.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  620.         call to SysEnvirons by calling it after initializing AppleTalk. */
  621.      
  622.     SysEnvirons(kSysEnvironsVersion, &gMac);
  623.     
  624.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  625.     
  626.     if (gMac.machineType < 0) AlertUser();
  627.     
  628.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  629.         in TrapAvailable if a tool trap value is out of range. */
  630.         
  631.     gHasWaitNextEvent = TrapAvail(_WaitNextEvent, ToolTrap);
  632.  
  633.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  634.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  635.         MultiFinder we needed. This did not work well because it assumed too much about
  636.         the relationship between what we asked MultiFinder for and what we would actually
  637.         get back, as well as how to measure it. Instead, we will use an alternate
  638.         method comprised of two steps. */
  639.      
  640.     /*    It is better to first check the size of the application heap against a value
  641.         that you have determined is the smallest heap the application can reasonably
  642.         work in. This number should be derived by examining the size of the heap that
  643.         is actually provided by MultiFinder when the minimum size requested is used.
  644.         The derivation of the minimum size requested from MultiFinder is described
  645.         in Sample.h. The check should be made because the preferred size can end up
  646.         being set smaller than the minimum size by the user. This extra check acts to
  647.         insure that your application is starting from a solid memory foundation. */
  648.      
  649.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  650.     
  651.     /*    Next, make sure that enough memory is free for your application to run. It
  652.         is possible for a situation to arise where the heap may have been of required
  653.         size, but a large scrap was loaded which left too little memory. To check for
  654.         this, call PurgeSpace and compare the result with a value that you have determined
  655.         is the minimum amount of free memory your application needs at initialization.
  656.         This number can be derived several different ways. One way that is fairly
  657.         straightforward is to run the application in the minimum size configuration
  658.         as described previously. Call PurgeSpace at initialization and examine the value
  659.         returned. However, you should make sure that this result is not being modified
  660.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  661.         PurgeSpace. Make sure to remove that call before shipping, though. */
  662.     
  663.     /* ZeroScrap(); */
  664.  
  665.     PurgeSpace(&total, &contig);
  666.     if (total < kMinSpace) AlertUser();
  667.  
  668.     /* if color quickdraw is available then we use a color window,
  669.        an old style window is aquired otherwise.
  670.     */
  671.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  672.     if ( window == nil ) AlertUser();
  673.     if (gMac.machineType < envMacII) 
  674.       window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  675.     else
  676.       window = GetNewCWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  677.  
  678.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  679.     if ( menuBar == nil ) AlertUser();
  680.     SetMenuBar(menuBar);                    /* install menus */
  681.     DisposeHandle(menuBar);
  682.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  683.     DrawMenuBar();
  684.     
  685.     gStopped = true;
  686.     if ( !GoGetRect(rStopRect, &gStopRect) )
  687.         AlertUser();                        /* the stop light rectangle */
  688.     if ( !GoGetRect(rGoRect, &gGoRect) )
  689.         AlertUser();                        /* the go light rectangle */
  690. } /*Initialize*/
  691.  
  692.  
  693. /*    This utility loads the global rectangles that are used by the window
  694.     drawing routines. It shows how the resource manager can be used to hold
  695.     values in a convenient manner. These values are then easily altered without
  696.     having to re-compile the source code. In this particular case, we know
  697.     that this routine is being called at initialization time. Therefore,
  698.     if a failure occurs here, we will assume that the application is in such
  699.     bad shape that we should just exit. Your error handling may differ, but
  700.     the check should still be made. */
  701.     
  702. #pragma segment Initialize
  703. Boolean GoGetRect(short rectID,Rect    *theRect)
  704. {
  705.     Handle        resource;
  706.     
  707.     resource = GetResource('RECT', rectID);
  708.     if ( resource != nil ) {
  709.         *theRect = **((Rect**) resource);
  710.         return true;
  711.     }
  712.     else
  713.         return false;
  714. } /* GoGetRect */
  715.  
  716.  
  717. /*    Check to see if a window belongs to the application. If the window pointer
  718.     passed was NIL, then it could not be an application window. WindowKinds
  719.     that are negative belong to the system and windowKinds less than userKind
  720.     are reserved by Apple except for windowKinds equal to dialogKind, which
  721.     mean it is a dialog.
  722.     1.02 - In order to reduce the chance of accidentally treating some window
  723.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  724.     is userKind. If you add different kinds of windows to Sample you'll need
  725.     to change how this all works. */
  726.  
  727. #pragma segment Main
  728. Boolean IsAppWindow(WindowPtr window)
  729. {
  730.     short        windowKind;
  731.  
  732.     if ( window == nil )
  733.         return false;
  734.     else {    /* application windows have windowKinds = userKind (8) */
  735.         windowKind = ((WindowPeek) window)->windowKind;
  736.         return (windowKind == userKind);
  737.     }
  738. } /*IsAppWindow*/
  739.  
  740.  
  741. /* Check to see if a window belongs to a desk accessory. */
  742.  
  743. #pragma segment Main
  744. Boolean IsDAWindow(WindowPtr window)
  745. {
  746.     if ( window == nil )
  747.         return false;
  748.     else    /* DA windows have negative windowKinds */
  749.         return ((WindowPeek) window)->windowKind < 0;
  750. } /*IsDAWindow*/
  751.  
  752.  
  753. /*    Check to see if a given trap is implemented. This is only used by the
  754.     Initialize routine in this program, so we put it in the Initialize segment.
  755.     The recommended approach to see if a trap is implemented is to see if
  756.     the address of the trap routine is the same as the address of the
  757.     Unimplemented trap. */
  758. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  759.     if a ToolTrap is out of range of a pre-MacII ROM. */
  760.  
  761. #pragma segment Initialize
  762. Boolean TrapAvail(short tNumber,TrapType tType)
  763. {
  764.     if ( ( tType == ToolTrap ) &&
  765.         ( gMac.machineType > envMachUnknown ) &&
  766.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  767.         tNumber = tNumber & 0x03FF;
  768.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  769.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  770.     }
  771.  
  772.     return NGetTrapAddress(tNumber, tType) != GetToolTrapAddress(_Unimplemented);
  773. } /*TrapAvail*/
  774.  
  775.  
  776. /*    Display an alert that tells the user an error occurred, then exit the program.
  777.     This routine is used as an ultimate bail-out for serious errors that prohibit
  778.     the continuation of the application. Errors that do not require the termination
  779.     of the application should be handled in a different manner. Error checking and
  780.     reporting has a place even in the simplest application. The error number is used
  781.     to index an 'STR#' resource so that a relevant message can be displayed. */
  782.  
  783. #pragma segment Main
  784. void AlertUser()
  785. {
  786.     short        itemHit;
  787.  
  788.     SetCursor(&qd.arrow);
  789.     itemHit = Alert(rUserAlert, nil);
  790.     ExitToShell();
  791. } /* AlertUser */