home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / X / mit / fonts / server / MacFS / MacFontUI.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-07-31  |  53.5 KB  |  1,802 lines

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