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
$97.67
Apple Inc.
+0.64
MSFT
$44.50
Microsoft Corpora
+0.10
GOOG
$589.02
Google Inc.
-4.33

MacTech Search:
Community Search:

Software Updates via MacUpdate

Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more
TinkerTool 5.3 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Audio Hijack Pro 2.11.0 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Intermission 1.1.1 - Pause and rewind li...
Intermission allows you to pause and rewind live audio from any application on your Mac. Intermission will buffer up to 3 hours of audio, allowing users to skip through any assortment of audio... Read more
Autopano Giga 3.6 - 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
Airfoil 4.8.7 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
Microsoft Remote Desktop 8.0.8 - Connect...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more
xACT 2.30 - Audio compression toolkit. (...
xACT stands for X Aaudio Compression Toolkit, an application that encodes and decodes FLAC, SHN, Monkey’s Audio, TTA, Wavpack, and Apple Lossless files. It also can encode these formats to MP3, AAC... Read more

Latest Forum Discussions

See All

This Week at 148Apps: July 21-25, 2014
Another Week of Expert App Reviews   At 148Apps, we help you sort through the great ocean of apps to find the ones we think you’ll like and the ones you’ll need. Our top picks become Editor’s Choice, our stamp of approval for apps with that little... | Read more »
Reddme for iPhone - The Reddit Client (...
Reddme for iPhone - The Reddit Client 1.0 Device: iOS iPhone Category: News Price: $.99, Version: 1.0 (iTunes) Description: Reddme for iPhone is an iOS 7-optimized Reddit client that offers a refreshing new way to experience Reddit... | Read more »
Jacob Jones and the Bigfoot Mystery : Ep...
Jacob Jones and the Bigfoot Mystery : Episode 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Jacob Jones is back in Episode 2 of one of Apples 'Best of 2013' games and an App Store... | Read more »
New Trailer For Outcast Odyssey, A New K...
New Trailer For Outcast Odyssey, A New Kind of Card Battler Posted by Jennifer Allen on July 25th, 2014 [ permalink ] Out this Fall is a new kind of card battle game: Outcast Odyssey. | Read more »
Hay Day – Tip, Tricks, Strategies, and C...
Recently got into Supercell’s other huge hit, Hay Day and could do with some advice on what to do? We’ve got you covered with some helpful trips and tricks to bear in mind! Ticking Along One of the key things to keep in mind while building up that... | Read more »
Monster Head Review
Monster Head Review By Nadia Oxford on July 25th, 2014 Our Rating: :: FEEDING TIMEUniversal App - Designed for iPhone and iPad Racking up a high score with Monster Head is trickier than it first appears. The appeal wears out fairly... | Read more »
Garfield: Survival of the Fattest Coming...
Garfield: Survival of the Fattest Coming to iOS this Fall Posted by Jennifer Allen on July 25th, 2014 [ permalink ] Who loves lasagna? Me. Also everyone’s favorite grumpy fat cat, Garfield. | Read more »
Happy Flock Review
Happy Flock Review By Andrew Fisher on July 25th, 2014 Our Rating: :: HERD IT ALL BEFOREUniversal App - Designed for iPhone and iPad Underneath the gloss of Happy Flock’s visuals is a game of very little substance. It’s cute, but... | Read more »
Square Register Updates Adds Offline Pay...
Square Register Updates Adds Offline Payments Posted by Ellis Spice on July 25th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Looking For Group – Hearthstone’s Curse...
For the first time since its release (which has thankfully been a much shorter window for iPad players than their PC counterparts), Blizzard’s wildly successful Hearthstone: Heroes of Warcraft CCG is sporting some brand new content: the single... | Read more »

Price Scanner via MacPrices.net

Apple’s 2014 Back to School promotion: $100 g...
 Apple’s 2014 Back to School promotion includes a free $100 App Store Gift Card with the purchase of any new Mac (Mac mini excluded), or a $50 Gift Card with the purchase of an iPad or iPhone,... Read more
iMacs on sale for $150 off MSRP, $250 off for...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
Mac minis on sale for $100 off MSRP, starting...
Best Buy has Mac minis on sale for $100 off MSRP. Choose free shipping or free instant local store pickup. Prices are for online orders only, in-store prices may vary: 2.5GHz Mac mini: $499.99 2.3GHz... Read more
Global Tablet Market Grows 11% in Q2/14 Notwi...
Worldwide tablet sales grew 11.0 percent year over year in the second quarter of 2014, with shipments reaching 49.3 million units according to preliminary data from the International Data Corporation... Read more
New iPhone 6 Models to Have Staggered Release...
Digitimes’ Cage Chao and Steve Shen report that according to unnamed sources in Apple’s upstream iPhone supply chain, the new 5.5-inch iPhone will be released several months later than the new 4.7-... Read more
New iOS App Helps People Feel Good About thei...
Mobile shoppers looking for big savings at their favorite stores can turn to the Goodshop app, a new iOS app with the latest coupons and deals at more than 5,000 online stores. In addition to being a... Read more
Save on 5th generation refurbished iPod touch...
The Apple Store has Apple Certified Refurbished 5th generation iPod touches available starting at $149. Apple’s one-year warranty is included with each model, and shipping is free. Many, but not all... Read more
What Should Apple’s Next MacBook Priority Be;...
Stabley Times’ Phil Moore says that after expanding its iMac lineup with a new low end model, Apple’s next Mac hardware decision will be how it wants to approach expanding its MacBook lineup as well... Read more
ArtRage For iPhone Painting App Free During C...
ArtRage for iPhone is currently being offered for free (regularly $1.99) during Comic-Con San Diego #SDCC, July 24-27, in celebration of the upcoming ArtRage 4.5 and other 64-bit versions of the... Read more
With The Apple/IBM Alliance, Is The iPad Now...
Almost since the iPad was rolled out in 2010, and especially after Apple made a 128 GB storage configuration available in 2012, there’s been debate over whether the iPad is a serious tool for... 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
WW Sales Program Manager, *Apple* Online St...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Lead Software Engineer, *Apple* Online Stor...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Manager, *Apple* Fullfillment Operation (AF...
…cross-functional teams to drive the highest level of program management quality for Apple . You will help plan launch strategy and demand generation programs with Read more
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.