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
$99.76
Apple Inc.
+2.09
MSFT
$44.08
Microsoft Corpora
+0.45
GOOG
$520.84
Google Inc.
+9.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

RestoreMeNot 2.0.3 - Disable window rest...
RestoreMeNot provides a simple way to disable the window restoration for individual applications so that you can fine-tune this behavior to suit your needs. Please note that RestoreMeNot is designed... Read more
Macgo Blu-ray Player 2.10.9.1750 - Blu-r...
Macgo Mac Blu-ray Player can bring you the most unforgettable Blu-ray experience on your Mac. Overview Macgo Mac Blu-ray Player can satisfy just about every need you could possibly have in a Blu-ray... Read more
Apple iOS 8.1 - The latest version of Ap...
The latest version of iOS can be downloaded through iTunes. Apple iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family.... Read more
TechTool Pro 7.0.5 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PDFKey Pro 4.0.2 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Yasu 2.9.1 - System maintenance app; per...
Yasu was originally created with System Administrators who service large groups of workstations in mind, Yasu (Yet Another System Utility) was made to do a specific group of maintenance tasks... Read more
Hazel 3.3 - Create rules for organizing...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a... Read more
Autopano Giga 3.7 - Stitch multiple imag...
Autopano Giga allows you to stitch 2, 20, or 2,000 images. Version 3.0 integrates impressive new features that will definitely make you adopt Autopano Pro or Autopano Giga: Choose between 9... Read more
MenuMeters 1.8 - CPU, memory, disk, and...
MenuMeters is a set of CPU, memory, disk, and network monitoring tools for Mac OS X. Although there are numerous other programs which do the same thing, none had quite the feature set I was looking... Read more
Coda 2.5 - One-window Web development su...
Coda is a powerful Web editor that puts everything in one place. An editor. Terminal. CSS. Files. With Coda 2, we went beyond expectations. With loads of new, much-requested features, a few... Read more

Latest Forum Discussions

See All

This Week at 148Apps: October 13-17, 201...
Expert App Reviewers   So little time and so very many apps. What’s a poor iPhone/iPad lover to do? Fortunately, 148Apps is here to give you the rundown on the latest and greatest releases. And we even have a tremendous back catalog of reviews; just... | Read more »
Angry Birds Transformers Review
Angry Birds Transformers Review By Jennifer Allen on October 20th, 2014 Our Rating: :: TRANSFORMED BIRDSUniversal App - Designed for iPhone and iPad Transformed in a way you wouldn’t expect, Angry Birds Transformers is a quite... | Read more »
GAMEVIL Announces the Upcoming Launch of...
GAMEVIL Announces the Upcoming Launch of Mark of the Dragon Posted by Jessica Fisher on October 20th, 2014 [ permalink ] Mark of the Dragon, by GAMEVIL, put | Read more »
Interview With the Angry Birds Transform...
Angry Birds Transformers recently transformed and rolled out worldwide. This run-and-gun title is a hit with young Transformers fans, but the ample references to classic Transformers fandom has also earned it a place in the hearts of long-time... | Read more »
Find Free Food on Campus with Ypay
Find Free Food on Campus with Ypay Posted by Jessica Fisher on October 20th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
Strung Along Review
Strung Along Review By Jordan Minor on October 20th, 2014 Our Rating: :: GOT NO STRINGSUniversal App - Designed for iPhone and iPad A cool gimmick and a great art style keep Strung Along from completely falling apart.   | Read more »
P2P file transferring app Send Anywhere...
File sharing services like Dropbox have security issues. Email attachments can be problematic when it comes to sharing large files. USB dongles don’t fit into your phone. Send Anywhere, a peer-to-peer file transferring application, solves all of... | Read more »
Zero Age Review
Zero Age Review By Jordan Minor on October 20th, 2014 Our Rating: :: MORE THAN ZEROiPad Only App - Designed for the iPad With its mind-bending puzzles and spellbinding visuals, Zero Age has it all.   | Read more »
Hay Ewe Review
Hay Ewe Review By Campbell Bird on October 20th, 2014 Our Rating: :: SAVE YOUR SHEEPLEUniversal App - Designed for iPhone and iPad Pave the way for your flock in this line drawing puzzle game from the creators of Worms.   | Read more »
My Very Hungry Caterpillar (Education)
My Very Hungry Caterpillar 1.0.0 Device: iOS Universal Category: Education Price: $3.99, Version: 1.0.0 (iTunes) Description: Care for your very own Very Hungry Caterpillar! My Very Hungry Caterpillar will captivate you as he crawls... | Read more »

Price Scanner via MacPrices.net

2013 15-inch 2.0GHz Retina MacBook Pro availa...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
Updated iPad Prices
We’ve updated our iPad Air Price Tracker and our iPad mini Price Tracker with the latest information on prices and availability from Apple and other resellers, including the new iPad Air 2 and the... Read more
Apple Pay Available to Millions of Visa Cardh...
Visa Inc. brings secure, convenient payments to iPad Air 2 and iPad mini 3as well as iPhone 6 and 6 Plus. Starting October 20th, eligible Visa cardholders in the U.S. will be able to use Apple Pay,... Read more
Textkraft Pocket – the missing TextEdit for i...
infovole GmbH has announced the release and immediate availability of Textkraft Pocket 1.0, a professional text editor and note taking app for Apple’s iPhone. In March 2014 rumors were all about... Read more
C Spire to offer iPad Air 2 and iPad mini 3,...
C Spire on Friday announced that it will offer iPad Air 2 and iPad mini 3, both with Wi-Fi + Cellular, on its 4G+ LTE network in the coming weeks. C Spire will offer the new iPads with a range of... Read more
Belkin Announces Full Line of Keyboards and C...
Belkin International has unveiled a new lineup of keyboard cases and accessories for Apple’s newest iPads, featuring three QODE keyboards and a collection of thin, lightweight folios for both the... Read more
Verizon offers new iPad Air 2 preorders for $...
Verizon Wireless is accepting preorders for the new iPad Air 2, cellular models, for $100 off MSRP with a 2-year service agreement: - 16GB iPad Air 2 WiFi + Cellular: $529.99 - 64GB iPad Air 2 WiFi... Read more
Price drops on refurbished Mac minis, now ava...
The Apple Store has dropped prices on Apple Certified Refurbished previous-generation Mac minis, with models now available starting at $419. Apple’s one-year warranty is included with each mini, and... Read more
Apple refurbished 2014 MacBook Airs available...
The Apple Store has Apple Certified Refurbished 2014 MacBook Airs available for up to $180 off the cost of new models. An Apple one-year warranty is included with each MacBook, and shipping is free.... Read more
Refurbished 2013 MacBook Pros available for u...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available starting at $929. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros (4GB RAM/... Read more

Jobs Board

Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.