TweetFollow Us on Twitter

MACINTOSH C CARBON

Demonstration Program Windows2

Goto Contents

// *******************************************************************************************
// Windows2.c                                                              CLASSIC EVENT MODEL
// *******************************************************************************************
// 
// This program demonstrates the following Window Manager features and functions introduced
// with Mac OS 8.5:
// 
// o  Creating floating windows and document windows using CreateNewWindow.
//
// o  Saving document windows and their associated data to a 'wind' resource.
//
// o  Creating document windows from 'wind' resources using CreateWindowFromResource.
//
// o  Managing windows in a floating windows environment.
//
// o  Setting and getting a window's property.
//
// o  Showing and hiding windows using TransitionWindow.
//
// o  Displaying window proxy icons.
//
// The program also demonstrates the creation of the system-managed Window menu introduced
// with Carbon and, on Mac OS X, a partial implementation of live window resizing.
//
// Those aspects of the newer Window Manager features not demonstrated in this program (full
// implementation of window proxy icons and window path pop-up menus) are demonstrated at the
// demonstration program Files (Chapter 18).
//
// The program utilises the following resources:
//
// o  A 'plst' resource.
//
// o  An 'MBAR' resource, and 'MENU' resources for Apple, File, Edit, Document Windows and
//    Floating Windows menus (preload, non-purgeable).
//
// o  'TEXT' resources for the document windows (non-purgeable).  
//
// o  'PICT' resources for the floating windows (non-purgeable).
//
// o  An 'ALRT' resource (purgeable), plus associated 'DITL', 'alrx', and 'dftb' resources
//    (all purgeable), for a movable modal alert invoked when the user chooses the About
//    Windows2... item from the  Apple/Application menu.
//
// o  A 'SIZE' resource with the acceptSuspendResumeEvents, canBackground, 
//    doesActivateOnFGSwitch, and isHighLevelEventAware flags set.
//
// In addition, the program itself creates a 'wind' resource, and saves it to the resource
// fork of the file titled "Document", when the user chooses CreateNewWindow from the 
// Document Windows menu.
//
// *******************************************************************************************

// .................................................................................. includes

#include <Carbon.h>

// ................................................................................... defines

#define rMenubar        128
#define mFile           129
#define  iQuit          12
#define rAboutAlert     128
#define rText           128
#define rColoursPicture 128
#define rToolsPicture   129
#define rWind           128
#define MIN(a,b)        ((a) < (b) ? (a) : (b))

// .................................................................................. typedefs

typedef struct
{
  TEHandle editStrucHdl;
} docStructure, **docStructureHandle;

// .......................................................................... global variables

Boolean   gRunningOnX = false;
SInt16    gDocResFileRefNum;
WindowRef gColoursFloatingWindowRef;
WindowRef gToolsFloatingWindowRef;
Boolean   gDone;

// ....................................................................... function prototypes

void    main                       (void);
void    doPreliminaries            (void);
OSErr   quitAppEventHandler        (AppleEvent *,AppleEvent *,SInt32);
void    doEvents                   (EventRecord *);
void    doMouseDown                (EventRecord *);
void    doUpdate                   (EventRecord *);
void    doUpdateDocumentWindow     (WindowRef);
void    doActivate                 (EventRecord *);
void    doActivateDocumentWindow   (WindowRef,Boolean);
void    doOSEvent                  (EventRecord *);
void    doAdjustMenus              (void);
void    doMenuChoice               (SInt32);
OSErr   doCreateNewWindow          (void);
OSErr   doSaveWindow               (WindowRef);
OSErr   doCreateWindowFromResource (void);
OSErr   doCreateFloatingWindows    (void);
void    doCloseWindow              (WindowRef);
void    doErrorAlert               (SInt16);
void    doConcatPStrings           (Str255,Str255);

// ************************************************************************************** main

void  main(void)
{
  MenuBarHandle      menubarHdl;
  SInt32             response;
  MenuRef            menuRef;
  OSErr              osError;
  SInt16             numberOfItems, a;
  MenuCommand        menuCommandID;
  FSSpec             fileSpecTemp;
  EventRecord        eventStructure;
  SInt32             sleepTime;
  WindowRef          windowRef;
  docStructureHandle docStrucHdl;
  UInt32             actualSize;

  // ........................................................................ do preliminaries

  doPreliminaries();

  // ..................... set up menu bar and menus, customise Window menu if running on OS X

  menubarHdl = GetNewMBar(rMenubar);
  if(menubarHdl == NULL)
    ExitToShell();
  SetMenuBar(menubarHdl);

  CreateStandardWindowMenu(0,&menuRef);
  InsertMenu(menuRef,0);

  DrawMenuBar();

  Gestalt(gestaltMenuMgrAttr,&response);
  if(response & gestaltMenuMgrAquaLayoutMask)
  {
    menuRef = GetMenuRef(mFile);
    if(menuRef != NULL)
    {
      DeleteMenuItem(menuRef,iQuit);
      DeleteMenuItem(menuRef,iQuit - 1);
      DisableMenuItem(menuRef,0);
    }

    gRunningOnX = true;
  }


  // .......... open resource fork of file "Windows2 Document" and store file reference number

  osError = FSMakeFSSpec(0,0,"\pWindows2 Document",&fileSpecTemp);
  if(osError == noErr)
    gDocResFileRefNum = FSpOpenResFile(&fileSpecTemp,fsWrPerm);
  else
    doErrorAlert(osError);

  // ................................................................. create floating windows

  if(osError = doCreateFloatingWindows())
    doErrorAlert(osError);

  // ......................................................................... enter eventLoop

  gDone = false;
  sleepTime = GetCaretTime();

  while(!gDone)
  {
    if(WaitNextEvent(everyEvent,&eventStructure,sleepTime,NULL))
      doEvents(&eventStructure);
    else
    {
      if(eventStructure.what == nullEvent)
      {
        if(windowRef = FrontNonFloatingWindow())
        {
          if(!(GetWindowProperty(windowRef,0,'docs',sizeof(docStrucHdl),&actualSize,
                                 &docStrucHdl)))
            TEIdle((*docStrucHdl)->editStrucHdl);
        }
      }
    }
  }
}

// *************************************************************************** doPreliminaries

void  doPreliminaries(void)
{
  OSErr osError;

  MoreMasterPointers(128);
  InitCursor();
  FlushEvents(everyEvent,0);

  osError = AEInstallEventHandler(kCoreEventClass,kAEQuitApplication,
                            NewAEEventHandlerUPP((AEEventHandlerProcPtr) quitAppEventHandler),
                            0L,false);
  if(osError != noErr)
    ExitToShell();
}

// **************************************************************************** doQuitAppEvent

OSErr  quitAppEventHandler(AppleEvent *appEvent,AppleEvent *reply,SInt32 handlerRefcon)
{
  OSErr    osError;
  DescType returnedType;
  Size     actualSize;

  osError = AEGetAttributePtr(appEvent,keyMissedKeywordAttr,typeWildCard,&returnedType,NULL,0,
                              &actualSize);

  if(osError == errAEDescNotFound)
  {
    gDone = true;
    osError = noErr;
  } 
  else if(osError == noErr)
    osError = errAEParamMissed;

  return osError;
}

// ********************************************************************************** doEvents

void  doEvents(EventRecord *eventStrucPtr)
{
  switch(eventStrucPtr->what)
  {
    case mouseDown:
      doMouseDown(eventStrucPtr);
      break;

    case keyDown:
      if((eventStrucPtr->modifiers & cmdKey) != 0)
      {
        doAdjustMenus();
        doMenuChoice(MenuEvent(eventStrucPtr));
      }
      break;

    case updateEvt:
      doUpdate(eventStrucPtr);
      break;

    case activateEvt:
      doActivate(eventStrucPtr);
      break;

    case osEvt:
      doOSEvent(eventStrucPtr);
      break;
  }
}

// ******************************************************************************* doMouseDown

void  doMouseDown(EventRecord *eventStrucPtr)
{
  WindowRef      windowRef;
  WindowPartCode partCode, zoomPart;
  SInt32         menuChoice;
  WindowClass    windowClass;
  BitMap         screenBits;
  Rect           portRect, mainScreenRect;
  Point          standardStateHeightAndWidth;

  partCode = FindWindow(eventStrucPtr->where,&windowRef);
  
  switch(partCode)
  {
    case kHighLevelEvent:
      AEProcessAppleEvent(eventStrucPtr);
      break;

    case inMenuBar:
      doAdjustMenus();
      doMenuChoice(MenuSelect(eventStrucPtr->where));
      break;

    case inContent:
      GetWindowClass(windowRef,&windowClass);
      if(windowClass == kFloatingWindowClass)
      {
        if(windowRef != FrontWindow())
          SelectWindow(windowRef);
        else
        {
          if(windowRef == gColoursFloatingWindowRef)
            ; // Appropriate action for Colours floating window here. 
          else if(windowRef == gToolsFloatingWindowRef)
            ; // Appropriate action for Tools floating window here.
        }
      }
      else
      {  
        if(windowRef != FrontNonFloatingWindow())
          SelectWindow(windowRef);
        else
          ; // Appropriate action for active document window here.
      }
      break;

    case inDrag:
      DragWindow(windowRef,eventStrucPtr->where,NULL);
      break;

    case inGoAway:
      GetWindowClass(windowRef,&windowClass);
      if(windowClass == kFloatingWindowClass)
      {
        if(TrackGoAway(windowRef,eventStrucPtr->where) == true)
          TransitionWindow(windowRef,kWindowZoomTransitionEffect,
                           kWindowHideTransitionAction,NULL);
      }
      else
        if(TrackGoAway(windowRef,eventStrucPtr->where) == true)
          doCloseWindow(windowRef);
      break;

    case inGrow:
      ResizeWindow(windowRef,eventStrucPtr->where,NULL,NULL);
      GetWindowPortBounds(windowRef,&portRect);
      InvalWindowRect(windowRef,&portRect);
      break;

    case inZoomIn:
    case inZoomOut:
      mainScreenRect = GetQDGlobalsScreenBits(&screenBits)->bounds;
      standardStateHeightAndWidth.v = mainScreenRect.bottom - 100;
      standardStateHeightAndWidth.h = 600;

      if(IsWindowInStandardState(windowRef,&standardStateHeightAndWidth,NULL))
        zoomPart = inZoomIn;
      else
        zoomPart = inZoomOut;

      if(TrackBox(windowRef,eventStrucPtr->where,partCode))
        ZoomWindowIdeal(windowRef,zoomPart,&standardStateHeightAndWidth);
      break;
  }
}

// ********************************************************************************** doUpdate

void  doUpdate(EventRecord *eventStrucPtr)
{
  GrafPtr   oldPort;
  WindowRef windowRef;

  GetPort(&oldPort);
  windowRef = (WindowRef) eventStrucPtr->message;

  BeginUpdate(windowRef);

  SetPortWindowPort(windowRef);
  doUpdateDocumentWindow(windowRef);

  EndUpdate(windowRef);

  SetPort(oldPort);
}

// ******************************************************************** doUpdateDocumentWindow

void  doUpdateDocumentWindow(WindowRef windowRef)
{
  RgnHandle          visibleRegionHdl = NewRgn();
  Rect               contentRect;
  OSStatus           osError;
  UInt32             actualSize;
  docStructureHandle docStrucHdl;
  TEHandle           editStrucHdl;

   GetPortVisibleRegion(GetWindowPort(windowRef),visibleRegionHdl);
  EraseRgn(visibleRegionHdl);

  DrawGrowIcon(windowRef);

  if(!(osError = GetWindowProperty(windowRef,0,'docs',sizeof(docStrucHdl),&actualSize,
                                   &docStrucHdl)))
  {
    GetWindowPortBounds(windowRef,&contentRect);
    InsetRect(&contentRect,3,3);
    contentRect.right -= 15;
    contentRect.bottom -= 15;
    editStrucHdl = (*docStrucHdl)->editStrucHdl;
    (*editStrucHdl)->destRect = (*editStrucHdl)->viewRect = contentRect;
    TECalText(editStrucHdl);
    TEUpdate(&contentRect,(*docStrucHdl)->editStrucHdl);
  }
}

// ******************************************************************************** doActivate

void  doActivate(EventRecord *eventStrucPtr)
{
  WindowRef windowRef;
  Boolean   becomingActive;

  windowRef = (WindowRef) eventStrucPtr->message;
  becomingActive = ((eventStrucPtr->modifiers & activeFlag) == activeFlag);

  doActivateDocumentWindow(windowRef,becomingActive);
}

// ****************************************************************** doActivateDocumentWindow

void  doActivateDocumentWindow(WindowRef windowRef,Boolean becomingActive)
{
  docStructureHandle docStrucHdl;
  UInt32             actualSize;
  OSStatus           osError;

  if(!(osError = GetWindowProperty(windowRef,0,'docs',sizeof(docStrucHdl),&actualSize,
                                   &docStrucHdl)))
  {
    if(becomingActive)
      TEActivate((*docStrucHdl)->editStrucHdl);
    else
      TEDeactivate((*docStrucHdl)->editStrucHdl);
  }
}

// ********************************************************************************* doOSEvent

void  doOSEvent(EventRecord *eventStrucPtr)
{
  switch((eventStrucPtr->message >> 24) & 0x000000FF)
  {
    case suspendResumeMessage:
      if((eventStrucPtr->message & resumeFlag) == 1)
        SetThemeCursor(kThemeArrowCursor);
      break;
  }
}

// ***************************************************************************** doAdjustMenus

void  doAdjustMenus(void)
{
  MenuRef       floatMenuRef;
  Boolean       isVisible;
  MenuItemIndex menuItem;

  isVisible = IsWindowVisible(gColoursFloatingWindowRef);
  GetIndMenuItemWithCommandID(NULL,'fcol',1,&floatMenuRef,&menuItem);
  CheckMenuItem(floatMenuRef,menuItem,isVisible);

  isVisible = IsWindowVisible(gToolsFloatingWindowRef);
  GetIndMenuItemWithCommandID(NULL,'ftoo',1,&floatMenuRef,&menuItem);
  CheckMenuItem(floatMenuRef,menuItem,isVisible);

  DrawMenuBar();
}

// ****************************************************************************** doMenuChoice

void  doMenuChoice(SInt32 menuChoice)
{
  MenuID        menuID;
  MenuItemIndex menuItem;
  OSErr         osError;
  MenuCommand   commandID;

  menuID = HiWord(menuChoice);
  menuItem = LoWord(menuChoice);

  if(menuID == 0)
    return;

  osError = GetMenuItemCommandID(GetMenuRef(menuID),menuItem,&commandID);
  if(osError == noErr && commandID != 0)
  {
    switch(commandID)
    {
      case 'abou':
        Alert(rAboutAlert,NULL);
        break;

      case 'quit':
        gDone = true;
        break;

      case 'cwin':
        if(osError = doCreateNewWindow())
          doErrorAlert(osError);
        break;

      case 'cwir':
        if(osError = doCreateWindowFromResource())
          doErrorAlert(osError);
        break;

      case 'fcol':
        if(IsWindowVisible(gColoursFloatingWindowRef))
          TransitionWindow(gColoursFloatingWindowRef,kWindowZoomTransitionEffect,
                           kWindowHideTransitionAction,NULL);
        else
          TransitionWindow(gColoursFloatingWindowRef,kWindowZoomTransitionEffect,
                           kWindowShowTransitionAction,NULL);
        break;

      case 'ftoo':
        if(IsWindowVisible(gToolsFloatingWindowRef))
          TransitionWindow(gToolsFloatingWindowRef,kWindowZoomTransitionEffect,
                           kWindowHideTransitionAction,NULL);
        else
          TransitionWindow(gToolsFloatingWindowRef,kWindowZoomTransitionEffect,
                           kWindowShowTransitionAction,NULL);
        break;
    }
  }

  HiliteMenu(0);
}

// ******************************************************************* doCreateFloatingWindows

OSErr  doCreateFloatingWindows(void)
{
  Rect      contentRect;
  OSStatus  osError;
  PicHandle pictureHdl;

  SetRect(&contentRect,102,59,391,132);

  if(!(osError = CreateNewWindow(kFloatingWindowClass,
                                 kWindowStandardFloatingAttributes | 
                                 kWindowSideTitlebarAttribute,
                                 &contentRect,&gColoursFloatingWindowRef)))
  {
    if(pictureHdl = GetPicture(rColoursPicture))
      SetWindowPic(gColoursFloatingWindowRef,pictureHdl);

    osError = TransitionWindow(gColoursFloatingWindowRef,kWindowZoomTransitionEffect,
                               kWindowShowTransitionAction,NULL);
  }

  if(osError != noErr)
    return osError;

  SetRect(&contentRect,149,88,213,280);

  if(!(osError = CreateNewWindow(kFloatingWindowClass,
                                 kWindowStandardFloatingAttributes,
                                 &contentRect,&gToolsFloatingWindowRef)))
  {
    if(pictureHdl = GetPicture(rToolsPicture))
      SetWindowPic(gToolsFloatingWindowRef,pictureHdl);

    osError = TransitionWindow(gToolsFloatingWindowRef,kWindowZoomTransitionEffect,
                               kWindowShowTransitionAction,NULL);
  }

  return osError;        
}

// ************************************************************************* doCreateNewWindow

OSErr  doCreateNewWindow(void)
{
  Rect               contentRect;
  OSStatus           osError;
  WindowRef          windowRef;
  docStructureHandle docStrucHdl;
  Handle             textHdl;
  MenuRef            menuRef;

  SetRect(&contentRect,10,40,470,340);

  do
  {
    if(osError = CreateNewWindow(kDocumentWindowClass,kWindowStandardDocumentAttributes,
                                 &contentRect,&windowRef))
      break;

    if(gRunningOnX)
      ChangeWindowAttributes(windowRef,kWindowLiveResizeAttribute,0);

    if(!(docStrucHdl = (docStructureHandle) NewHandle(sizeof(docStructure))))
    {
      osError = MemError();
      break;
    }

    if(osError = SetWindowProperty(windowRef,0,'docs',sizeof(docStructure),
                                   &docStrucHdl))
      break;

    SetPortWindowPort(windowRef);
    UseThemeFont(kThemeSmallSystemFont,smSystemScript);

    textHdl = GetResource('TEXT',rText);
    osError = ResError();
    if(osError != noErr)
      break;

    OffsetRect(&contentRect,-contentRect.left,-contentRect.top);
    InsetRect(&contentRect,3,3);
    contentRect.right -= 15;
    contentRect.bottom -= 15;

    (*docStrucHdl)->editStrucHdl = TENew(&contentRect,&contentRect);
    TEInsert(*textHdl,GetHandleSize(textHdl),(*docStrucHdl)->editStrucHdl);

    SetWTitle(windowRef,"\pCreateNewWindow");
    
    if(osError = SetWindowProxyCreatorAndType(windowRef,0,'TEXT',kOnSystemDisk))
      break;
    if(osError = SetWindowModified(windowRef,false))
      break;
    if(osError = RepositionWindow(windowRef,NULL,kWindowCascadeOnMainScreen))
      break;
    if(osError = TransitionWindow(windowRef,kWindowZoomTransitionEffect,
                                  kWindowShowTransitionAction,NULL))
      break;

    if(osError = doSaveWindow(windowRef))
      break;

  } while(false);

  if(osError)
  {
    if(windowRef)
      DisposeWindow(windowRef);
      
    if(docStrucHdl)
      DisposeHandle((Handle) docStrucHdl);
  }

  return osError;
}

// ****************************************************************************** doSaveWindow

OSErr  doSaveWindow(WindowRef windowRef)
{
  SInt16             oldResFileRefNum;
  Collection         collection = NULL;
  OSStatus           osError;
  docStructureHandle docStrucHdl;
  UInt32             actualSize;
  Handle             flatCollectHdl, flatCollectResHdl, existingResHdl;

  oldResFileRefNum = CurResFile();
  UseResFile(gDocResFileRefNum);

  do
  {
    if(!(collection = NewCollection()))
    {
      osError = MemError();
      break;
    }
    
    if(osError = StoreWindowIntoCollection(windowRef,collection))
      break;
      
    if(osError = GetWindowProperty(windowRef,0,'docs',sizeof(docStrucHdl),&actualSize,
                                   &docStrucHdl))
      break;
      
    if(osError = AddCollectionItemHdl(collection,'TEXT',1,
                                      (*(*docStrucHdl)->editStrucHdl)->hText))
      break;

    if(!(flatCollectHdl = NewHandle(0)))
    {
      osError = MemError();
      break;
    }

    if(osError = FlattenCollectionToHdl(collection,flatCollectHdl))
      break;

    existingResHdl = Get1Resource('wind',rWind);
    osError = ResError();
    if(osError != noErr && osError != resNotFound)
      break;

    if(existingResHdl != NULL)
      RemoveResource(existingResHdl);
    osError = ResError();
    if(osError != noErr)
      break;

    AddResource(flatCollectHdl,'wind',rWind,"\p");
    osError = ResError();
    if(osError != noErr)
      break;

    flatCollectResHdl = flatCollectHdl;
    flatCollectHdl = NULL;

    WriteResource(flatCollectResHdl);
    osError = ResError();
    if(osError != noErr)
      break;

    UpdateResFile(gDocResFileRefNum);
    osError = ResError();
    if(osError != noErr)
      break;
  } while(false);

  if(collection)
    DisposeCollection(collection);
  if(flatCollectHdl)
    DisposeHandle(flatCollectHdl);
  if(flatCollectResHdl)
    ReleaseResource(flatCollectResHdl);

  UseResFile(oldResFileRefNum);

  return osError;
}

// **************************************************************** doCreateWindowFromResource

OSErr  doCreateWindowFromResource(void)
{
  SInt16             oldResFileRefNum;
  OSStatus           osError;
  WindowRef          windowRef;
  Collection         unflattenedCollection = NULL;
  Handle             windResHdl;
  docStructureHandle docStrucHdl;
  SInt32             dataSize = 0;
  Handle             textHdl;
  Rect               contentRect;

  oldResFileRefNum = CurResFile();
  UseResFile(gDocResFileRefNum);

  do
  {
    if(osError = CreateWindowFromResource(rWind,&windowRef))
      break;

    if(gRunningOnX)
      ChangeWindowAttributes(windowRef,kWindowLiveResizeAttribute,0);

    if(!(unflattenedCollection = NewCollection()))
    {
      osError = MemError();
      break;
    }

    windResHdl = GetResource('wind',rWind);
    osError = ResError();
    if(osError != noErr)
      break;

    if(osError = UnflattenCollectionFromHdl(unflattenedCollection,windResHdl))
      break;

    if(!(docStrucHdl = (docStructureHandle) NewHandle(sizeof(docStructure))))
    {
      osError = MemError();
      break;
    }

    if(osError = GetCollectionItem(unflattenedCollection,'TEXT',1,&dataSize,
                                   kCollectionDontWantData))
      break;

    if(!(textHdl = NewHandle(dataSize)))
    {
      osError = MemError();
      break;
    }

    if(osError = GetCollectionItem(unflattenedCollection,'TEXT',1,kCollectionDontWantSize,
                                   *textHdl))
      break;

    GetWindowPortBounds(windowRef,&contentRect);
    contentRect.right -= 15;
    contentRect.bottom -= 15;
    SetPortWindowPort(windowRef);
    UseThemeFont(kThemeSmallSystemFont,smSystemScript);
    (*docStrucHdl)->editStrucHdl = TENew(&contentRect,&contentRect);
    TEInsert(*textHdl,dataSize,(*docStrucHdl)->editStrucHdl);

    if(osError = SetWindowProperty(windowRef,0,'docs',sizeof(docStrucHdl),&docStrucHdl))
      break;

    SetWTitle(windowRef,"\pCreateWindowFromResource");

    if(osError = SetWindowProxyCreatorAndType(windowRef,0,'TEXT',kOnSystemDisk))
      break;
    if(osError = SetWindowModified(windowRef,false))
      break;
    if(osError = RepositionWindow(windowRef,NULL,kWindowCascadeOnMainScreen))
      break;
    if(osError = TransitionWindow(windowRef,kWindowZoomTransitionEffect,
                                  kWindowShowTransitionAction,NULL))
      break;
  } while(false);

  if(unflattenedCollection)
    DisposeCollection(unflattenedCollection);
  if(windResHdl)
    ReleaseResource(windResHdl);

  UseResFile(oldResFileRefNum);

  return osError;
}

// ***************************************************************************** doCloseWindow

void  doCloseWindow(WindowRef windowRef)
{
  OSStatus           osError;
  docStructureHandle docStrucHdl;
  UInt32             actualSize;

  do
  {
    if(osError = TransitionWindow(windowRef,kWindowZoomTransitionEffect,
                                  kWindowHideTransitionAction,NULL))
    break;

    if(osError = GetWindowProperty(windowRef,0,'docs',sizeof(docStrucHdl),&actualSize,
                                   &docStrucHdl))
    break;
  } while(false);

  if(osError)
    doErrorAlert(osError);

  if((*docStrucHdl)->editStrucHdl)
    TEDispose((*docStrucHdl)->editStrucHdl);

  if(docStrucHdl)
    DisposeHandle((Handle) docStrucHdl);

  DisposeWindow(windowRef);
}

// ****************************************************************************** doErrorAlert

void  doErrorAlert(SInt16 errorCode)
{
  Str255 errorCodeString;
  Str255 theString = "\pAn error occurred.  The error code is ";
  SInt16 itemHit;

  NumToString((SInt32) errorCode,errorCodeString);
  doConcatPStrings(theString,errorCodeString);

  StandardAlert(kAlertStopAlert,theString,NULL,NULL,&itemHit);
  ExitToShell();
}

// ************************************************************************** doConcatPStrings

void  doConcatPStrings(Str255 targetString,Str255 appendString)
{
  SInt16  appendLength;

  appendLength = MIN(appendString[0],255 - targetString[0]);

  if(appendLength > 0)
  {
    BlockMoveData(appendString+1,targetString+targetString[0]+1,(SInt32) appendLength);
    targetString[0] += appendLength;
  }
}

// *******************************************************************************************

Demonstration Program Windows2 Comments

Two Window Manager features introduced with Mac OS 8.5 (full window proxy icon implementation
and window path pop-up menus) are not demonstrated in this program.  However, they are
demonstrated at the demonstration program associated with Chapter 18.

When the program is run, the user should:

o Choose CreateNewWindow from the Document Windows menu, noting that, when the new window is
  displayed, the floating windows and the new (document) window are all active.

  (Note:  As well as creating the window, the program loads and displays a 'TEXT' resource
  (simulating a document associated with the window) and then saves the window and the text to
  a 'wind' resource.)

o Choose CreateWindowFromResource from the Document Windows menu, noting that the window is
  created from the 'wind' resource saved when CreateNewWindow was chosen.

o Choose About Windows2É from the Apple menu, noting that the floating windows appear in the
  deactivated state when the alert box opens.

o Hide the floating windows by clicking their close boxes, and toggle the floating windows
  between hidden and showing by choosing their items in the Floating Windows menu, noting the
  transitional animations.

o Click in the Finder to send the application to the background, noting that the floating
  windows are hidden by this action.  Then click in one of the application's windows, noting
  that the floating windows re-appear.

o Note the transitional animations when the document windows are opened and closed.

o Exercise the system-managed Window menu, noting the customisation of this menu when the
  program is run on Mac OS X.

defines

rWind represents the ID of the 'wind' resource created by the program.

typedefs

A document structure of type docStructure will be associated with each document window. The
single field in the document structure (editStrucHdl) will be assigned a handle to a TextEdit
edit structure, which will contain the text displayed in the window.

Global Variables

gDocResFileRefNum will be assigned the file reference number for the resource fork of the
document file "Windows2 Document" included in the demo program's folder. 
gColoursFloatingWindowRef and gToolsFloatingWindowRef will be assigned references to the window
objects for the floating windows.

main

The call to CreateStandardWindowMenu creates the system-managed Window menu, which is added to
the menu list by the call to InsertMenu.  If the program is running on Mac OS X, the next block
customises the Window menu by searching for the item with the command ID 'wldv' (that is, the
divider between the commands and the individual window items), inserting a divider and two
custom items before that item, and assigning command IDs to those items.  (At the time of
writing, the divider did not have the 'wldv' command ID in CarbonLib.)

The resource fork of the file titled "Windows2 Document" is opened and the file reference
number is saved to a global variable.  The program will be saving a 'wind' resource to this
file's resource fork.

CurResFile is called to set the application's resource fork as the current resource file.

The function doCreateFloatingWindows is called to create and show the floating windows.

In the next block (the main event loop), WaitNextEvent's sleep parameter is assigned the value
returned by GetCaretTime.  (GetCaretTime returns the value stored in the low memory global
CaretTime, which determines the blinking rate for the insertion point caret as set by the user. 
This ensures that TEIdle, which causes the caret to blink, will be called at the correct
interval.

When WaitNextEvent returns 0 with a null event, FrontNonFloatingWindow is called to obtain a
reference to the front document window.  If such a window exists, GetWindowProperty is called
to retrieve a handle to the window's document structure.  The handle to the TextEdit edit
structure, which is stored in the window's document structure, is then passed in the call to
TEIdle, which causes the insertion point caret to blink.

doMouseDown

doMouseDown continues the processing of mouse-down events, switching according to the part
code.

The inContent case is handled differently depending on whether the event is in a floating
window or a document window.  GetWindowClass returns the window's class.  If the window is a
floating window, and if that window is not the front floating window, SelectWindow is called to
bring that floating window to the front.  If the window is the front floating window, the
identity of the window is determined and the appropriate further action is taken.  (In this
demonstration, no further action is taken.)

If the window is not a floating window, and if the window is not the front non-floating window,
SelectWindow is called to:

o	Unhighlight the currently active non-floating window, bring the specified window to the front
of the non-floating windows, and highlight it.

o Generate activate events for the two windows.

o Move the previously active non-floating window to a position immediately behind the specified
  window.

If the window is the front non-floating window, the appropriate further action is taken.  (In
this demonstration, no further action is taken.)

The inGoAway case is also handled differently depending on whether the event is in a floating
window or a document window.  TrackGoAway is called in both cases to track user action while
the mouse-button remains down.  If the pointer is still within the go away box when the
mouse-button is released, and if the window is a floating window, TransitionWindow is called to
hide the window.  If the window is a non-floating window, the function doCloseWindow is called
to close the window.

doUpdate

doUpdate further processes update events.  When an update event is received, doUpdate calls
doUpdateDocumentWindow.  (As will be seen, in this particular demonstration, the Window Manager
will not generate updates for the floating windows.)

doUpdateDocumentWindow

doUpdateDocumentWindow is concerned with the drawing of the content region of the non-floating
windows.

GetWindowProperty is then called to retrieve the handle to the window's document structure,
which, as previously stated, contains a handle to a TextEdit structure containing the text
displayed in the window.  If the call is successful, measures are taken to redraw the text in
the window, taking account of the current height and width of the content region less the area
that would ordinarily be occupied by scroll bars.  (The TextEdit calls in this section are
incidental to the demonstration.  TextEdit is addressed at Chapter 21.)

doActivateDocumentWindow

doActivateDocumentWindow performs, for the non-floating windows, those window activation
actions for which the application is responsible.  In this demonstration, that action is
limited to calling TEActivate or TEDeactivate to show or remove the insertion point caret.

GetWindowProperty is called to retrieve the handle to the window's document structure, which
contains a handle to the TextEdit structure containing the text displayed in the window.  If
this call is successful, and if the window is being activated, TEActivate is called to display
the insertion point caret.  If the window is being deactivated, TEDeactivate is called to
remove the insertion point caret.

doAdjustMenus

doAdjustMenus is called in the event of a mouse-down event in the menu bar when a key is
pressed together with the Command key.  The function checks or unchecks the items in the
Floating Windows menu depending on whether the associated floating window is currently showing
or hidden.

doMenuChoice

doMenuChoice switches according to the menu choices of the user.

If the user chooses the About Windows2É item from the Apple menu, Alert is called to display
the About Windows2É alert box.

If the user chose the first item in the Document Windows menu, the function doCreateNewWindow
is called.  If the user chose the second item, the function doCreateWindowFromResource is
called.  If either of these functions return an error, an error-handling function is called.

When an item in the Floating Windows menu is chosen, IsWindowVisible is called to determine the
visibility state of the relevant floating window.  TransitionWindow is then called, with the
appropriate constant passed in the action parameter, to hide or show the window depending on
the previously determined current visibility state.

doCreateFloatingWindows

doCreateFloatingWindows is called from main to create the floating windows.

The Colours floating window is created first.  SetRect is called to define a rectangle which
will be used to establish the size of the window and its opening location in global
coordinates.  CreateNewWindow is then called to create a floating window (first parameter) with
a close box, a collapse box, and a side title bar (second parameter), and with the previously
defined content region size and location (third parameter).

If this call is successful,  GetPicture is called to load the specified 'PICT' resource.  If
the resource is loaded successfully, SetWindowPic is called to store the handle to the picture
structure in the windowPic field of the window's colour window structure.  This latter means
that the Window Manager will draw the picture in the window instead of generating update events
for it.  Finally, TransitionWindow is called to make the window visible (with animation and
sound).

The same general procedure is then followed to create the Tools floating window.

doCreateNewWindow

doCreateNewWindow is called when the user chooses Create New Window from the Document Windows
menu.  In addition to creating a window, and for the purposes of this demonstration,
doCreateNewWindow also saves the window and its associated data (text) in a 'wind' resource.

Firstly, SetRect is called to define a rectangle that will be used to establish the size of the
window and its opening location in global coordinates.  The call to CreateNewWindow creates a
document window (first parameter) with a close box, a full zoom box, a collapse box, and a size
box (second parameter), and with the previously defined content region size and location (third
parameter).

if the program is running on Mac OS X, ChangeWindowAttributes is called to set the
kWindowLiveResizeAttribute.  This results in a partial implementation of live resizing.

NewHandle is then called to create a relocatable block for the document structure to be
associated with the window.  SetWindowProperty associates the document structure with the
window.  0 is passed in the propertyCreator parameter because this demonstration has no
application signature.  The value passed in the propertyTag parameter ('docs') is just a
convenient value with which to identify the data.

The call to SetPortWindowPort sets the window's graphics port as the current port and the call
to UseThemeFont sets the window's font to the small system font.

The next three blocks load a 'TEXT' resource, insert the text into a TextEdit structure, and
assign a handle to that structure to the editStrucHdl field of the window's document structure. 
This is all for the purpose of simulating some text that the user has typed into the window.

SetWTitle sets the window's title.

The window lacks an associated file, so SetWindowProxyCreatorAndType is called to cause a proxy
icon to be displayed in the window's drag bar.  0 passed in the fileCreator parameter and
'TEXT' passed in the fileType parameter cause the system's default icon for a document file to
be displayed.  SetWindowModified is then called with false passed in the modified parameter to
cause the proxy icon to appear in the enabled state (indicating no unsaved changes).

The call to RepositionWindow positions the window relative to other windows according to the
constant passed in the method parameter.

As the final step in creating the window, TransitionWindow is called to make the window visible
(with animation).

To facilitate the demonstration of creating a window from a 'wind' resource (see the function
doCreateWindowFromResource), a function is called to save the window and its data (the text) to
a 'wind' resource in the application's resource fork.

If an error occurred within the do/while loop, if a window was created, it is disposed of. 
Also, if a nonrelocatable block for the document structure was created, it is disposed of.

doSaveWindow

doSaveWindow is called by doCreateNewWindow to save the window and its data (the text) to a
'wind' resource.

Firstly, the current resource file's file reference number is saved and the resource fork of
the document titled "Windows2 Document" is made the current resource file.

The call to the Collection Manager function NewCollection allocates memory for as new
collection object and initialises it.  The call to StoreWindowIntoCollection stores data
describing the window into the collection.

GetWindowProperty retrieves the handle to the window's document structure.

The handle to the window's text is stored in the hText field of the TextEdit structure.  The
handle to the TextEdit structure is, in turn, stored in the window's document structure.  The
Collection Manager function AddCollectionItemHdl adds a new item to the collection,
specifically, a copy of the text.

The call to NewHandle allocates a zero-length handle which will be used to hold a flattened
collection.  The Collection Manager function FlattenCollectionToHdl flattens the collection
into a Memory Manager handle.

The next six blocks use Resource Manager functions to save the flattened collection as a 'wind'
resource in the resource fork of the application file.

Get1Resource attempts to load a 'wind' resource with ID 128.  If ResError reports an error, and
if the error is not the "resource not found" error, the whole save process is aborted. 
(Accepting the "resource not found" error as an acceptable error caters for the possibility
that this may be the first time the window and its data have been saved.)

If Get1Resource successfully loaded a 'wind' resource with ID 128, RemoveResource is called to
remove that resource from the resource map, AddResource is called to make the flattened
collection in memory into a 'wind' resource, assigning a resource type, ID and name to that
resource, and inserting an entry in the resource map for the current resource file. 
WriteResource is called to write the resource to the document file's resource fork.  Since the
resource map has been changed, UpdateResFile is called to update the resource map on disk.

Below the do/while loop, the collection and the flattened collection block are disposed of and
the resource in memory is released.

Finally, the saved resource file is made the current resource file.

doCreateWindowFromResource

doCreateWindowFromResource creates a window from the 'wind' resource created by doSaveWindow.

Firstly, the current resource file's file reference number is saved and the resource fork of
the document titled "Windows2 Document" is made the current resource file.

CreateWindowFromResource creates a window, invisibly, from the 'wind' resource with ID 128.

The call to the Collection Manager function NewCollection creates a new collection. 
GetResource loads the 'wind' resource with ID 128.  The Collection Manager function
UnflattenCollectionFromHdl unflattens the 'wind' resource and stores the unflattened collection
in the collection object unflattenedCollection.

NewHandle allocates a relocatable block the size of a window document structure.

The Collection Manager function GetCollectionItem is called twice, the first time to get the
size of the text data, not the data itself.  (The item in the collection is specified by the
second and third parameters (tag and ID)).  This allows the call to NewHandle to create a
relocatable block of the same size.  GetCollection is then called again, this time to obtain a
copy of the text itself.

The next block creates a new TextEdit structure (TENew), assigning its handle to the
editStrucHdl field of the document structure which will shortly be associated with the window. 
TEInsert inserts the copy of the text obtained by the second call to GetCollectionItem into the
TextEdit structure.

The call to SetWindowProperty associates the document structure with the window, thus
associating the TextEdit structure and its text with the window.

SetWTitle sets the window's title.

The window lacks an associated file, so the Mac OS 8.5 function SetWindowProxyCreatorAndType is
called to cause a proxy icon to be displayed in the window's drag bar.  0 passed in the
fileCreator parameter and 'TEXT' passed in the fileType parameter cause the system's default
icon for a document file to be displayed.  SetWindowModified is then called with false passed
in the modified parameter to cause the proxy icon to appear in the enabled state (indicating no
unsaved changes).

The call to RepositionWindow positions the window relative to other windows according to the
constant passed in the method parameter.

As the final step in creating the window, TransitionWindow is called to make the window visible
(with animation).

Below the do/while loop, the unflattened collection is disposed of and the 'wind' resource is
released.

Finally, the saved resource file is made the current resource file.

doCloseWindow

doCloseWindow is called when the user clicks the close box of a document window.

TransitionWindow is called to hide the window (with animation).  GetWindowProperty is then
called to retrieve a handle to the window's document structure, allowing the memory occupied by
the TextEdit structure and document structure associated with the window to be disposed of. 
DisposeWindow is then called to remove the window from the window list and discard all its data
storage.

doErrorAlert

doErrorAlert is called when errors are detected.  In this demonstration, the action taken is
somewhat rudimentary.  A stop alert box displaying the error number is invoked.  When the user
dismisses the alert box, the program terminates.  eventFilter supports doErrorAlert.
 
AAPL
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
MYStuff Pro 2.0.16 - Create inventories...
MYStuff Pro is the most flexible way to create detail-rich inventories for your home or small business. Add items to MYStuff by dragging and dropping existing information, uploading new images, or... Read more
TurboTax 2013.r17.002 - Manage your 2013...
TurboTax guides you through your tax return step by step, does all the calculations, and checks your return for errors and overlooked deductions. It lets you file your return electronically to get... Read more

Latest Forum Discussions

See All

Living Planet - Tiny Planet Videos and P...
Living Planet - Tiny Planet Videos and Photos 1.0 Device: iOS Universal Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: 50% OFF LAUNCH SPECIAL! BUY NOW BEFORE THE PRICE GOES UP... | Read more »
Livescribe 3 Smartpen Review
Made by: Livescribe Price: $149.99 for Livescribe 3 Hardware/iOS Integration Rating: 4.5 out of 5 stars Usability Rating: 4 out of 5 stars Reuse Value Rating: 4.75 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.44 out of... | Read more »
Unpossible Review
Unpossible Review By Carter Dotson on April 17th, 2014 Our Rating: :: RALPH WIGGUM APPROVESUniversal App - Designed for iPhone and iPad Unpossible is much better than its English!   | Read more »
Hitman GO Review
Hitman GO Review By Carter Dotson on April 17th, 2014 Our Rating: :: GO HITMAN, GO!Universal App - Designed for iPhone and iPad Hitman GO is not the obvious way to do a mobile version of the Hitman series, but it’s an incredibly... | Read more »
Monster High Ghouls and Jewels is a Frea...
Monster High Ghouls and Jewels is a Freaky Fashion-Forward Match-3 Puzzler Posted by Rob Rich on April 17th, 2014 [ permalink ] | Read more »
Dinosaur Train A to Z Review
Dinosaur Train A to Z Review By Amy Solomon on April 17th, 2014 Our Rating: :: DINO DETAILSUniversal App - Designed for iPhone and iPad Dinosaur Train A to Z is an educational app about dinosaurs that includes In-App Purchases... | Read more »
Easter Comes to Junk Jack X – Bringing N...
Easter Comes to Junk Jack X – Bringing New Crafts, Chemistry, and More Posted by Rob Rich on April 17th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Call of Cookie Review
Call of Cookie Review By Jordan Minor on April 17th, 2014 Our Rating: :: COOKIE CRUMBLESUniversal App - Designed for iPhone and iPad Call of Cookie proves that plants aren’t the only fighting foods out there.   | Read more »
Corel Launches Video Editing App Pinnacl...
Corel Launches Video Editing App Pinnacle Studio for iPhone, Updates iPad Version for iOS 7 Posted by Tre Lawrence on April 17th, 2014 [ | Read more »
Bad Vamp Review
Bad Vamp Review By Jennifer Allen on April 17th, 2014 Our Rating: :: BASIC VAMPIRIC ADVENTURESUniversal App - Designed for iPhone and iPad Run or destroy the vampires in this simple, single-screen game that lacks real bite.   | Read more »

Price Scanner via MacPrices.net

Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more
Save up to $270 with Apple refurbished 13-inc...
The Apple Store has Apple Certified Refurbished October 2013 13″ Retina MacBook Pros available starting at $1099, with models up to $270 off MSRP. Apple’s one-year warranty is standard, and shipping... Read more
Apple now offering refurbished iPad mini with...
The Apple Store has Certified Refurbished 2nd generation iPad minis with Retina Displays now available starting at $339. Apple’s one-year warranty is included with each model, and shipping is free.... Read more
Microsoft Blinks – Drops Microsoft Office 365...
Microsoft has dropped the annual subscription fee for Microsoft Office 365 Personal – which is needed in order to create and edit documents in Microsoft Office for iPad. However, Apple’s iOS and OS X... Read more
New AVG Vault Apps for iOS and Android Help K...
AVG Technologies N.V. an online security company for 177 million active users, has announced the launch of its latest mobile application, AVG Vault. The free app introduces an innovative user... Read more
Free Local Carrot iPhone App Helps Find Fresh...
I love fresh vegetables. I’m not a vegan, although I was for several years in the 1980s, but fresh vegetables and other whole foods are still my dietary mainstays as a matter of taste rather than... Read more
CarSO Pro – Car Service and Finance Manager/O...
Lviv, Ukraine-based BM-Studios’ CarSO Pro is a tool to manage operations concerning your car. Never forget to change the oil or prolong the insurance for your car. Remember when you’ve done the car... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Market Leader - Cincinnati...
…challenges of developing individuals, building teams, and affecting growth across Apple Stores. You demonstrate successful leadership ability - focusing on excellence Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.