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.
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.