• MacTech Network:
  • Tech Support
  • |
  • MacForge.net
  • |
  • Apple News
  • |
  • Register Domains
  • |
  • SSL Certificates
  • |
  • iPod Deals
  • |
  • Mac Deals
  • |
  • Mac Book Shelf

MAC TECH

  • Home
  • Magazine
    • About MacTech in Print
    • Issue Table of Contents
    • Subscribe
    • Risk Free Sample
    • Back Issues
    • MacTech DVD
  • Archives
    • MacTech Print Archives
    • MacMod
    • MacTutor
    • FrameWorks
    • develop
  • Forums
  • News
    • MacTech News
    • MacTech Blog
    • MacTech Reviews and KoolTools
    • Whitepapers, Screencasts, Videos and Books
    • News Scanner
    • Rumors Scanner
    • Documentation Scanner
    • Submit News or PR
    • MacTech News List
  • Store
  • Apple Expo
    • by Category
    • by Company
    • by Product
  • Job Board
  • Editorial
    • Submit News or PR
    • Writer's Kit
    • Editorial Staff
    • Editorial Calendar
  • Advertising
    • Benefits of MacTech
    • Mechanicals and Submission
    • Dates and Deadlines
    • Submit Apple Expo Entry
  • User
    • Register for Ongoing Raffles
    • Register new user
    • Edit User Settings
    • Logout
  • Contact
    • Customer Service
    • Webmaster Feedback
    • Submit News or PR
    • Suggest an article
  • Connect Tools
    • MacTech Live Podcast
    • RSS Feeds
    • Twitter

Demonstration Program

Go to Contents
// 
// MoreResources.c
// 
// 
// This program uses custom resources to:
//
//   Store application preferences in the resource fork of a preferences file, and also
//    to assist in the initial creation of the preferences file.
//
//   Store,in the resource fork of a document file, the user state and current state of
//    the window associated with the document.
//
//   Store, in the resource fork of a document file, the width and height of the
//    printable area of the paper size chosen in the print Style dialog box. 
//
// The program utilises the following standard resources:
//
//   An 'MBAR' resource, and 'MENU' resources for Apple, File, Edit and Demonstration
//    menus (preload, non-purgeable).  
//
//   A 'WIND' resource (purgeable) (initially invisible).  
//
//   A 'DLOG' resource (purgeable) and associated 'dlgx', 'DITL' and 'CNTL' resources 
//    (purgeable) associated with the display of, and user modification of, current 
//    application preferences. 
//
//   A 'STR#' resource (purgeable) containing the required name of the preferences file
//    created by the program.
//
//   A 'STR ' resource (purgeable) containing the application-missing string, which is
//    copied to the resource fork of the preferences file.
//
//   A 'SIZE' resource with the acceptSuspendResumeEvents and is32BitCompatible flags
//    set.
//
// The program utilises the following custom resources:
//
//   A 'PrFn' (preferences) resource comprising three boolean values, which is located
//    in the program's resource file, which contains default preference values, and which
//    is copied to the resource fork of a preferences file created when the program is
//    run for the first time.  Thereafter, the 'PrFn' resource in the preferences file
//    is used for the storage and retrieval of application preferences set by the user.
//
//   A 'WiSt' (window state) resource, which is created in the resource fork of the
//    document file used by the program, and which is used to store the associated
//    window's user state rectangle (a Rect structure) and zoom state (a Boolean value).
//
//   A 'PrAr' (printable area) resource, which is created in the resource fork of the
//    document file used by the program, and which is used to store the printable width
//    and height of the paper size chosen in the print Style dialog box.    
//
// 

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

#include <Appearance.h>
#include <Devices.h>
#include <Folders.h>
#include <Navigation.h>
#include <Printing.h>
#include <Resources.h>
#include <Sound.h>
#include <ToolUtils.h>

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

#define mApple          128
#define mFile           129
#define  iOpen          2
#define  iClose         4
#define  iPageSetup     8
#define  iQuit          11
#define mDemonstration  131
#define  iPreferences   1
#define rNewWindow      128
#define rMenubar        128
#define rPrefsDialog    128
#define  iSoundOn       4  
#define  iFullScreenOn  5
#define  iAutoScrollOn  6
#define rStringList     128
#define  iPrefsFileName 1
#define rTypePrintRect  'PrAr'
#define  kPrintRectID   128
#define rTypeWinState   'WiSt'
#define  kWinStateID    128
#define rTypePrefs      'PrFn'
#define  kPrefsID       128
#define rTypeAppMiss    'STR '
#define  kAppMissID     -16397
#define MAXLONG         0x7FFFFFFF
#define topLeft(r)      (((Point *) &(r))[0])
#define botRight(r)     (((Point *) &(r))[1])

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

typedef struct
{
  FSSpec    fileFSSpec;
}  docStructure, *docStructurePointer, **docStructureHandle;

typedef struct
{
  Boolean    soundOn;
  Boolean    fullScreenOn;
  Boolean    autoScrollOn;
}  appPrefs, *appPrefsPointer, **appPrefsHandle;

typedef struct
{
  Rect      userStateRect;
  Boolean   zoomState;
} winState, *winStatePtr,**winStateHandle;

typedef RectPtr *rectHandle;

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

Boolean   gDone;
Boolean   gInBackground;
THPrint   gTPrintHdl;
WindowPtr gWindowPtr;
Boolean   gWindowOpen         = false;
Boolean   gPrintStyleChanged  = false;
Rect      gPrintRect;
Boolean   gSoundOn;
Boolean   gFullScreenOn;
Boolean   gAutoScrollOn;  
SInt16    gAppResFileRefNum;
SInt16    gPrefsFileRefNum    = 0;

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

void  main                      (void);
void  doInitManagers            (void);
void  doEvents                  (EventRecord *);
void  doUpdateWindow            (WindowPtr);
void  doAdjustMenus             (void);
void  doMenuChoice              (long);
void  doErrorAlert              (SInt16);
void  doOpenCommand             (void);
void  doCloseCommand            (void);
void  doPreferencesDialog       (void);
void  doPrintStyleDialog        (void);
void  doGetPreferences          (void);
OSErr doCopyResource            (ResType,SInt16,SInt16,SInt16);
void  doSavePreferences         (void);
void  doGetandSetWindowPosition (WindowPtr);
void  doSaveWindowPosition      (WindowPtr);
void  doSetWindowState          (WindowPtr,Rect,Rect);
void  doGetPrintableSize        (WindowPtr);
void  doSavePrintableSize       (WindowPtr);

//  main

void  main(void)
{
  Handle      menubarHdl;
  MenuHandle  menuHdl;
  EventRecord eventStructure;

  // ................................................................ initialise managers

  doInitManagers();

  // ............................. set current resource file to application resource fork

  gAppResFileRefNum = CurResFile();

  // .......................................................... set up menu bar and menus

  menubarHdl = GetNewMBar(rMenubar);
  if(menubarHdl == NULL)
    doErrorAlert(MemError());
  SetMenuBar(menubarHdl);
  DrawMenuBar();

  menuHdl = GetMenuHandle(mApple);
  if(menuHdl == NULL)
    doErrorAlert(MemError());
  else
    AppendResMenu(menuHdl,'DRVR');

  // .............................................. create and initialise a TPrint record

  PrOpen();
  gTPrintHdl = (THPrint) NewHandleClear(sizeof(TPrint));
  PrintDefault(gTPrintHdl);
  PrClose();

  // .................................................... read in application preferences

  doGetPreferences();

  // ................................................................... enter event loop

  gDone = false;
  
  while(!gDone)
  {
    if(WaitNextEvent(everyEvent,&eventStructure,MAXLONG,NULL))
      doEvents(&eventStructure);
  }
}

//  doInitManagers

void  doInitManagers(void)
{
  MaxApplZone();
  MoreMasters();

  InitGraf(&qd.thePort);
  InitFonts();
  InitWindows();
  InitMenus();
  TEInit();
  InitDialogs(NULL);

  InitCursor();
  FlushEvents(everyEvent,0);

  RegisterAppearanceClient();
}

//  doEvents

void  doEvents(EventRecord *eventStrucPtr)
{
  WindowPtr windowPtr;
  Rect      growRect;
  long      newSize;
  SInt8     charCode;
  SInt16    partCode;

  windowPtr = (WindowPtr) eventStrucPtr->message;    

  switch(eventStrucPtr->what)
  {
    case mouseDown:
      partCode = FindWindow(eventStrucPtr->where,&windowPtr);
  
      switch(partCode)
      {
        case inMenuBar:
          doAdjustMenus();
          doMenuChoice(MenuSelect(eventStrucPtr->where));
          break;

        case inContent:
          if(windowPtr != FrontWindow())
            SelectWindow(windowPtr);
          break;

        case inDrag:
          DragWindow(windowPtr,eventStrucPtr->where,&qd.screenBits.bounds);
          break;

        case inGoAway:
          if(TrackGoAway(windowPtr,eventStrucPtr->where) == true)
            doCloseCommand();
          break;

        case inGrow:
          growRect = qd.screenBits.bounds;
          growRect.top   = 145; 
          growRect.left = 345;
          newSize = GrowWindow(windowPtr,eventStrucPtr->where,&growRect);
          if(newSize != 0)
            SizeWindow(windowPtr,LoWord(newSize),HiWord(newSize),true);
          break;

        case inZoomIn:
        case inZoomOut:
          if(TrackBox(windowPtr,eventStrucPtr->where,partCode))
            ZoomWindow(windowPtr,partCode,false);
          break;
      }
      break;

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

    case updateEvt:
      BeginUpdate(windowPtr);
      doUpdateWindow(windowPtr);
      EndUpdate(windowPtr);
      break;

    case osEvt:
      switch((eventStrucPtr->message >> 24) & 0x000000FF)
      {
        case suspendResumeMessage:
          gInBackground = (eventStrucPtr->message & resumeFlag) == 0;
          break;
      }
      HiliteMenu(0);
      break;
  }
}

//  doUpdateWindow

void  doUpdateWindow(WindowPtr windowPtr)
{
  Str255    string;
  RGBColor  whiteColour  = { 0xFFFF, 0xFFFF, 0xFFFF };
  RGBColor  blueColour  = { 0x1818, 0x4B4B, 0x8181 };

  RGBForeColor(&whiteColour);
  RGBBackColor(&blueColour);
  EraseRect(&windowPtr->portRect);  

  SetPort(windowPtr);

  MoveTo(10,20);
  TextFace(bold);
  DrawString("\pCurrent Application Preferences:");
  TextFace(normal);
  MoveTo(10,35);
  DrawString("\pSound On:  ");
  if(gSoundOn)  DrawString("\pYES");
  else  DrawString("\pNO");
  MoveTo(10,50);
  DrawString("\pFull Screen On:  ");
  if(gFullScreenOn)  DrawString("\pYES");
  else  DrawString("\pNO");
  MoveTo(10,65);
  DrawString("\pAutoScroll On:  ");
  if(gAutoScrollOn)  DrawString("\pYES");
  else  DrawString("\pNO");

  if(gPrintRect.bottom != 0)
  {
    MoveTo(10,85);
    TextFace(bold);
    DrawString("\pInformation From Printable Area ('PrAr') Resource:"); 
    TextFace(normal);
    NumToString((long) gPrintRect.bottom,string);
    MoveTo(10,100);
    DrawString("\pPage print area height in screen pixels:  ");
    DrawString(string);
    NumToString((long) gPrintRect.right,string);
    MoveTo(10,115);
    DrawString("\pPage print area width in screen pixels:  ");
    DrawString(string);
  }
  else
  {
    MoveTo(10,85);
    DrawString("\pNo printable area ('PrAr') resource saved yet"); 
  }
}

//  doAdjustMenus

void  doAdjustMenus(void)
{
  MenuHandle  menuHdl;

  if(gWindowOpen)
  {
    menuHdl = GetMenuHandle(mFile);
    DisableItem(menuHdl,iOpen);
    EnableItem(menuHdl,iClose);
    EnableItem(menuHdl,iPageSetup);
  }
  else
  {
    menuHdl = GetMenuHandle(mFile);
    EnableItem(menuHdl,iOpen);
    DisableItem(menuHdl,iClose);
    DisableItem(menuHdl,iPageSetup);
  }

  DrawMenuBar();
}

//  doMenuChoice

void  doMenuChoice(long menuChoice)
{
  SInt16  menuID, menuItem;
  Str255  itemName;
  SInt16  daDriverRefNum;

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

  if(menuID == 0)
    return;

  switch(menuID)
  {
    case mApple:
      GetMenuItemText(GetMenuHandle(mApple),menuItem,itemName);
      daDriverRefNum = OpenDeskAcc(itemName);
      break;

    case mFile:
      switch(menuItem)
      {
        case iClose:
          doCloseCommand();
          break;

        case iOpen:
          doOpenCommand();
          break;

        case iPageSetup:
          doPrintStyleDialog();
          break;

        case iQuit:
          while(FrontWindow())
            doCloseCommand();
          gDone = true;
          break;
      }
      break;

    case mDemonstration:
      if(menuItem == iPreferences)
        doPreferencesDialog();
      break;
  }

  HiliteMenu(0);
}
  
//  doErrorAlert

void  doErrorAlert(SInt16 errorCode)
{
  AlertStdAlertParamRec paramRec;
  Str255                errorString;
  SInt16                itemHit;

  paramRec.movable        = true;
  paramRec.helpButton     = false;
  paramRec.filterProc     = NULL;
  paramRec.defaultText    = (StringPtr) kAlertDefaultOKText;
  paramRec.cancelText     = NULL;
  paramRec.otherText      = NULL;
  paramRec.defaultButton  = kAlertStdAlertOKButton;
  paramRec.cancelButton   = 0;
  paramRec.position       = kWindowDefaultPosition;

  NumToString((SInt32) errorCode,errorString);

  if(errorCode != memFullErr)
    StandardAlert(kAlertCautionAlert,errorString,NULL,¶mRec,&itemHit);
  else
  {
    StandardAlert(kAlertStopAlert,errorString,NULL,¶mRec,&itemHit);
    ExitToShell();
  }
}

//  doOpenCommand

void  doOpenCommand(void)
{
  SFTypeList          fileTypes;
  StandardFileReply   fileReply;
  docStructureHandle  docStrucHdl;
  OSErr               osError = 0;

  fileTypes[0] = 'TEXT';
  
  StandardGetFile(NULL,1,fileTypes,&fileReply);
  if(!(fileReply.sfGood))
    return;

  if(!(gWindowPtr = GetNewCWindow(rNewWindow,NULL,(WindowPtr)-1)))
    return;

  if(!(docStrucHdl = (docStructureHandle) NewHandle(sizeof(docStructure))))
  {
    DisposeWindow(gWindowPtr);
    return;
  }

  gWindowOpen = true; 
  SetPort(gWindowPtr);
  TextSize(10);

  SetWRefCon(gWindowPtr,(long) docStrucHdl);
  (*docStrucHdl)->fileFSSpec = fileReply.sfFile;
  SetWTitle(gWindowPtr,(*docStrucHdl)->fileFSSpec.name);  

  doGetandSetWindowPosition(gWindowPtr);
  doGetPrintableSize(gWindowPtr);

  ShowWindow(gWindowPtr);
}

//  doCloseCommand

void  doCloseCommand(void)
{
  WindowPtr           windowPtr;
  docStructureHandle  docStrucHdl;
  OSErr               osError = 0;

  windowPtr = FrontWindow();
  docStrucHdl = (docStructureHandle) GetWRefCon(windowPtr);

  doSaveWindowPosition(windowPtr);

  if(gPrintStyleChanged)
    doSavePrintableSize(gWindowPtr);

  DisposeHandle((Handle) docStrucHdl);
  DisposeWindow(windowPtr);
  gWindowOpen = false;
}

//  doPreferencesDialog

void  doPreferencesDialog(void)
{
  DialogPtr     modalDlgPtr;
  ControlHandle controlHdl;
  SInt16        itemHit;

  if(!(modalDlgPtr = GetNewDialog(rPrefsDialog,NULL,(WindowPtr) -1)))
    return;

  GetDialogItemAsControl(modalDlgPtr,iSoundOn,&controlHdl);
  SetControlValue(controlHdl,gSoundOn);
  GetDialogItemAsControl(modalDlgPtr,iFullScreenOn,&controlHdl);
  SetControlValue(controlHdl,gFullScreenOn);
  GetDialogItemAsControl(modalDlgPtr,iAutoScrollOn,&controlHdl);
  SetControlValue(controlHdl,gAutoScrollOn);

  ShowWindow(modalDlgPtr);
  
  do
  {
    ModalDialog(NULL,&itemHit);
    GetDialogItemAsControl(modalDlgPtr,itemHit,&controlHdl);
    SetControlValue(controlHdl,!GetControlValue((ControlHandle) controlHdl));
  }while((itemHit != kStdOkItemIndex) && (itemHit != kStdCancelItemIndex));
  
  if(itemHit == kStdOkItemIndex)
  {
    GetDialogItemAsControl(modalDlgPtr,iSoundOn,&controlHdl);
    gSoundOn = GetControlValue(controlHdl);
    GetDialogItemAsControl(modalDlgPtr,iFullScreenOn,&controlHdl);
    gFullScreenOn = GetControlValue(controlHdl);
    GetDialogItemAsControl(modalDlgPtr,iAutoScrollOn,&controlHdl);
    gAutoScrollOn = GetControlValue(controlHdl);        
  }

  DisposeDialog(modalDlgPtr);

  if(gWindowPtr)
    InvalRect(&gWindowPtr->portRect);

  doSavePreferences();
}

//  doPrintStyleDialog

void  doPrintStyleDialog(void)
{
  Boolean  clickedOK;

  PrOpen();

  if(clickedOK = PrStlDialog(gTPrintHdl))
  {
    gPrintStyleChanged = true;
    gPrintRect = (*gTPrintHdl)->prInfo.rPage;
    InvalRect(&gWindowPtr->portRect);
  }

  PrClose();
}

//  doGetPreferences

void  doGetPreferences(void)
{
  Str255          prefsFileName;
  OSErr           osError;
  SInt16          volRefNum;
  long            directoryID;
  FSSpec          fileSSpec;
  SInt16          fileRefNum;
  appPrefsHandle  appPrefsHdl;

  GetIndString(prefsFileName,rStringList,iPrefsFileName);

  osError = FindFolder(kOnSystemDisk,kPreferencesFolderType,kDontCreateFolder,&volRefNum,
                       &directoryID);

  if(osError == noErr)
    osError = FSMakeFSSpec(volRefNum,directoryID,prefsFileName,&fileSSpec);
  if(osError == noErr || osError == fnfErr)
    fileRefNum = FSpOpenResFile(&fileSSpec,fsCurPerm);

  if(fileRefNum == -1)
  {
    FSpCreateResFile(&fileSSpec,'PpPp','pref',smSystemScript);
    osError = ResError();

    if(osError == noErr)
    {
      fileRefNum = FSpOpenResFile(&fileSSpec,fsCurPerm);
      if(fileRefNum != -1 )
      {
        UseResFile(gAppResFileRefNum);
          
        osError = doCopyResource(rTypePrefs,kPrefsID,gAppResFileRefNum,fileRefNum);
        if(osError == noErr)
          osError = doCopyResource(rTypeAppMiss,kAppMissID,gAppResFileRefNum,fileRefNum);
        if(osError != noErr)
        {
          CloseResFile(fileRefNum);
          osError = FSpDelete(&fileSSpec);
          fileRefNum = -1;
        }
      }
    }
  }

  if(fileRefNum != -1)
  {
    UseResFile(fileRefNum); 

    appPrefsHdl = (appPrefsHandle) Get1Resource(rTypePrefs,kPrefsID);
    if(appPrefsHdl == NULL)
      return;

    gSoundOn       = (*appPrefsHdl)->soundOn;
    gFullScreenOn  = (*appPrefsHdl)->fullScreenOn;
    gAutoScrollOn  = (*appPrefsHdl)->autoScrollOn;

    gPrefsFileRefNum = fileRefNum;

    UseResFile(gAppResFileRefNum);
  }
}

//  doCopyResource

OSErr  doCopyResource(ResType resType,SInt16 resID,SInt16 sourceFileRefNum,
                      SInt16 destFileRefNum)
{
  SInt16  oldResFileRefNum;
  Handle  sourceResourceHdl;
  ResType ignoredType;
  SInt16  ignoredID;
  Str255  resourceName;
  SInt16  resAttributes;
  OSErr   osError;

  oldResFileRefNum = CurResFile();
  UseResFile(sourceFileRefNum);

  sourceResourceHdl = Get1Resource(resType,resID);

  if(sourceResourceHdl != NULL)
  {
    GetResInfo(sourceResourceHdl,&ignoredID,&ignoredType,resourceName);
    resAttributes = GetResAttrs(sourceResourceHdl);
    DetachResource(sourceResourceHdl);
    UseResFile(destFileRefNum);
    if(ResError() == noErr)
      AddResource(sourceResourceHdl,resType,resID,resourceName);
    if(ResError() == noErr)
      SetResAttrs(sourceResourceHdl,resAttributes);
    if(ResError() == noErr)
      ChangedResource(sourceResourceHdl);
    if(ResError() == noErr)
      WriteResource(sourceResourceHdl);
  }

  osError = ResError();

  ReleaseResource(sourceResourceHdl);
  UseResFile(oldResFileRefNum);

  return(osError);
}

//  doSavePreferences

void  doSavePreferences(void)
{
  appPrefsHandle  appPrefsHdl;
  Handle          existingResHdl;
  Str255          resourceName = "\pPreferences";

  if(gPrefsFileRefNum == -1)
    return;

  appPrefsHdl = (appPrefsHandle) NewHandleClear(sizeof(appPrefs));

  HLock((Handle) appPrefsHdl);

  (*appPrefsHdl)->soundOn = gSoundOn;
  (*appPrefsHdl)->fullScreenOn = gFullScreenOn;
  (*appPrefsHdl)->autoScrollOn = gAutoScrollOn;

  UseResFile(gPrefsFileRefNum);

  existingResHdl = Get1Resource(rTypePrefs,kPrefsID);
  if(existingResHdl != NULL)
  {
    RemoveResource(existingResHdl);
    if(ResError() == noErr)
      AddResource((Handle) appPrefsHdl,rTypePrefs,kPrefsID,resourceName);
    if(ResError() == noErr)
      WriteResource((Handle) appPrefsHdl);
  }

  HUnlock((Handle) appPrefsHdl);

  ReleaseResource((Handle) appPrefsHdl);
  UseResFile(gAppResFileRefNum);
}

//  doGetandSetWindowPosition

void  doGetandSetWindowPosition(WindowPtr windowPtr)
{
  Rect                userStateRect, stdStateRect, displayRect;
  docStructureHandle  docStrucHdl;
  SInt16              fileRefNum;
  winStateHandle      winStateHdl;
  Boolean             gotResource;
  OSErr               osError;

  userStateRect = qd.screenBits.bounds;  
  SetRect(&userStateRect,userStateRect.left + 3,userStateRect.top + 42,
          userStateRect.right - 40,userStateRect.bottom - 6);

  stdStateRect = qd.screenBits.bounds;  
  SetRect(&stdStateRect,stdStateRect.left + 3,stdStateRect.top + 42,
          stdStateRect.right - 3,stdStateRect.bottom - 6);

  docStrucHdl = (docStructureHandle) GetWRefCon(windowPtr);

  fileRefNum = FSpOpenResFile(&(*docStrucHdl)->fileFSSpec,fsRdWrPerm);
  if(fileRefNum < 0)
  {
    osError = ResError();
    doErrorAlert(osError);
    return;
  }

  winStateHdl = (winStateHandle) Get1Resource(rTypeWinState,kWinStateID);
  if(winStateHdl != NULL )
  {
    gotResource = true;
    userStateRect = (*winStateHdl)->userStateRect;
  }
  else
    gotResource = false;

  if(gotResource)
  {
    if((*winStateHdl)->zoomState) 
      displayRect = stdStateRect;
    else
      displayRect = userStateRect;
  }
  else
  {
    displayRect = userStateRect;
  }

  MoveWindow(windowPtr,displayRect.left,displayRect.top,false);

  GlobalToLocal(&topLeft(displayRect));
  GlobalToLocal(&botRight(displayRect));
  SizeWindow(windowPtr,displayRect.right,displayRect.bottom,true);

  doSetWindowState(windowPtr,userStateRect,stdStateRect);

  ReleaseResource((Handle) winStateHdl);
  CloseResFile(fileRefNum);
}

//  doSaveWindowPosition

void  doSaveWindowPosition(WindowPtr windowPtr)
{
  docStructureHandle  docStrucHdl;
  SInt16              fileRefNum;
  WindowPeek          windowRecPtr;
  WStateData          *winStateDataPtr;
  Rect                stdRect, userRect;
  RgnHandle           contentRgnHdl;
  winState            userRectAndZoomState;
  winStateHandle      winStateHdl;
  OSErr               osError;

  docStrucHdl = (docStructureHandle) GetWRefCon(windowPtr);

  fileRefNum = FSpOpenResFile(&(*docStrucHdl)->fileFSSpec,fsRdWrPerm);
  if(fileRefNum < 0)
  {
    osError = ResError();
    doErrorAlert(osError);
    return;
  }

  windowRecPtr = (WindowPeek) windowPtr;  
  winStateDataPtr = (WStateData *) *(windowRecPtr->dataHandle);    
  stdRect = winStateDataPtr->stdState;
  userRect = winStateDataPtr->userState;

  contentRgnHdl = windowRecPtr->contRgn;
  userRectAndZoomState.userStateRect = (*contentRgnHdl)->rgnBBox;
  userRectAndZoomState.zoomState = EqualRect(&userRectAndZoomState.userStateRect,&stdRect);
  if(userRectAndZoomState.zoomState)
    userRectAndZoomState.userStateRect = userRect;

  winStateHdl = (winStateHandle) Get1Resource(rTypeWinState,kWinStateID);
  if(winStateHdl != NULL)
  {  
    **winStateHdl = userRectAndZoomState;
    ChangedResource((Handle) winStateHdl);
    osError = ResError();
    if(osError != noErr)
      doErrorAlert(osError);
  }
  else
  {
    winStateHdl = (winStateHandle) NewHandle(sizeof(winState));
    if(winStateHdl != NULL)
    {
      **winStateHdl = userRectAndZoomState;
      AddResource((Handle) winStateHdl,rTypeWinState,kWinStateID,"\pLast window state");
    }
  }

  if(winStateHdl != NULL)
  {
    UpdateResFile(fileRefNum);
    osError = ResError();
    if(osError != noErr)
      doErrorAlert(osError);

    ReleaseResource((Handle) winStateHdl);
  }

  CloseResFile(fileRefNum);
}

//  doSetWindowState

void  doSetWindowState(WindowPtr windowPtr,Rect userStateRect,Rect stdStateRect)
{
  WindowPeek  windowRecPtr;
  WStateData  *winStateDataPtr;

  windowRecPtr = (WindowPeek) windowPtr;
  winStateDataPtr = (WStateData *) *(windowRecPtr->dataHandle);
  winStateDataPtr->userState = userStateRect;
  winStateDataPtr->stdState = stdStateRect;
}

//  doGetPrintableSize

void  doGetPrintableSize(WindowPtr windowPtr)
{
  docStructureHandle  docStrucHdl;
  SInt16              fileRefNum;
  OSErr               osError;
  rectHandle          printRectHdl;

  docStrucHdl = (docStructureHandle) GetWRefCon(windowPtr);

  fileRefNum = FSpOpenResFile(&(*docStrucHdl)->fileFSSpec,fsRdWrPerm);
  if(fileRefNum < 0)
  {
    osError = ResError();
    doErrorAlert(osError);
    return;
  }

  printRectHdl = (rectHandle) Get1Resource(rTypePrintRect,kPrintRectID);
  if(printRectHdl != NULL)
  {
    gPrintRect = **printRectHdl;
    ReleaseResource((Handle) printRectHdl);
  }

  CloseResFile(fileRefNum);
}

//  doSavePrintableSize

void  doSavePrintableSize(WindowPtr windowPtr)
{
  docStructureHandle  docStrucHdl;
  SInt16              fileRefNum;
  rectHandle          printRectHdl;
  OSErr               osError;

  docStrucHdl = (docStructureHandle) GetWRefCon(windowPtr);

  fileRefNum = FSpOpenResFile(&(*docStrucHdl)->fileFSSpec,fsRdWrPerm);
  if(fileRefNum < 0)
  {
    osError = ResError();
    doErrorAlert(osError);
    return;
  }

  printRectHdl = (rectHandle) Get1Resource(rTypePrintRect,kPrintRectID);
  if(printRectHdl != NULL)
  {  
    **printRectHdl = (*gTPrintHdl)->prInfo.rPage;
    ChangedResource((Handle) printRectHdl);
    osError = ResError();
    if(osError != noErr)
      doErrorAlert(osError);
  }
  else
  {
    printRectHdl = (rectHandle) NewHandle(sizeof(Rect));
    if(printRectHdl != NULL)
    {
      **printRectHdl = (*gTPrintHdl)->prInfo.rPage;
      AddResource((Handle) printRectHdl,rTypePrintRect,kPrintRectID,"\pPrint rectangle");
    }
  }

  if(printRectHdl != NULL)
  {
    UpdateResFile(fileRefNum);
    osError = ResError();
    if(osError != noErr)
      doErrorAlert(osError);

    ReleaseResource((Handle) printRectHdl);
  }
  
  gPrintStyleChanged = false;

  CloseResFile(fileRefNum);
}

// 

Demonstration Program Comments

When this program is run for the first time, a preferences file (titled "MoreResources
Preferences") is created in the Preferences folder in the System folder and two resources
are copied to the resource fork of that file from the program's resource file.  These two
resources are a custom preferences ('PrFn') resource and a "application missing" 'STR '
resource.  Thereafter, the preferences resource will be read in from the preferences file
every time the program is run and replaced whenever the user invokes the Preferences
dialog box to change the application preferences settings.  In addition, if the user
double clicks on the preferences file's icon, an alert box is invoked displaying the text
contained in the "application missing" 'STR ' resource.

After the program is launched, the user should choose Open from the File menu to open the
included demonstration document file titled "Document").  The resource fork of this file
contains two custom resources, namely, a 'WiSt' resource containing the last saved window
user state and zoom state, and a 'PrAr' resource containing the last saved printable area
rectangle of the currently chosen paper size.  These two resources are read in whenever
the document file is opened.  The 'WiSt' resource is written to whenever the file is
closed.  The 'PrAr' resource is written to when the file is closed only if the user
invoked the print Style dialog box while the document was open.

No data is read in from the document's data fork.  Instead, the window is used to display
the current preferences settings and the current printable area (that is, page rectangle)
values.

The user should choose different paper size, scaling and orientation settings in the
print style dialog box, re-size or zoom the window, close the file, re-open the file, and
note that, firstly, the saved printable area values are correctly retrieved and,
secondly, the window is re-opened in the size and zoom state in which is was closed.  The
user should also change the application preferences settings via the Preferences dialog
box (which is invoked when the single item in the Demonstration menu is chosen), quit the
program, re-launch the program, and note that the last saved preferences settings are
retrieved at program launch.

The user may also care to remove the 'WiSt' and 'PrAr' resources from the document file,
run the program, force a 'PrAr' resource to be created and written to by invoking the
print Style dialog box while the document file is open, quit the program, and re-run the
program, noting that 'WiSt' and 'PrAr' resources are created in the document file's
resource fork if they do not already exist.

When done, the user should remove the MoreResources preferences file from the Preferences
folder in the System folder.

#define

rPrefsDialog represents the 'DLOG' resource ID for the Preferences dialog box and the
following three constants represent the item numbers of the dialog's checkboxes. 
rStringList and iPrefsFileName represent the 'STR#' resource ID and index for the string
containing the name of the application's preferences file.  The next eight constants
represent resource types and IDs for the custom printable area resource, the custom
window state resource, the custom preferences resource, and the application missing
string resource.

#typedef

The docStructure data type is for the document structure.  In this demonstration, the
only field required is that for a file system specification.

The appPrefs data type is for the application preferences settings.  The three Boolean
values are set by checkboxes in the Preferences dialog box.

The winState data type is for the window user state (a rectangle) and zoom state (a
Boolean value indicating whether the window is in the standard (zoomed out) or user
(zoomed in) state).

The rectHandle data type will be used in the functions related to the getting and saving
of the printable area width and height.

Global Variables

gDone controls exit from the main event loop and thus program termination.  gInBackground
relates to foreground/background switching.  

gTPrintHdl will be assigned a handle to a TPrint structure, the latter being required
because of the use by the program of the print style dialog.  gWindowPtr will be assigned
the pointer to the window's graphics port.  gWindowOpen is used to control File menu item
enabling/disabling according to whether the window is open or closed.

gPrintStyleChanged is set to true when the print style dialog is invoked, and determines
whether a new printable area resource will be written to the document file when the file
is closed.  gPrintRect will be assigned the rectangle representing the printable area.

gSoundOn, gFullScreenOn, and gAutoScrollOn will hold the application preferences
settings.

gAppResFileRefNum will be assigned the file reference number for the application file's
resource fork.  gPrefsFileRefNum will be assigned the file reference number for the
preferences file's resource fork.

main

The call to CurResFile sets the application's resource fork as the current resource file. 
The block beginning with the call to PrOpen creates and initialises a TPrint structure. 
The call to doGetPreferences reads in the application preferences settings from the
preferences file.  (As will be seen, if the preferences file does not exist, a
preferences file will be created, default preferences settings will be copied to it from
the application file, and these default settings will then be read in from the
newly-created file.)

doUpdateWindow

doUpdateWindow simply prints the current preferences and printable area information in
the window for the information of the user.

doErrorAlert

doErrorAlert presents an alert box displaying the error code passed to it.  In the case
of a memFullErr code, a stop alert is presented and the program is terminated when the
user clicks the OK button.  In all other cases, a caution alert is presented and the
program continues when the user clicks the OK button.

doOpenCommand

doOpenCommand is a much simplified version of the actions normally taken when a user
chooses the Open command from a File menu.

StandardGetFile presents the standard Open dialog box.  If the user clicks the Cancel
button, the function simply returns.  If the user clicks the OK button, a new window is
created, a document structure is created, a flag is set to indicate that the window is
open, the window's graphics port is set as the current port for drawing, the text size is
set to 10pt, the document structure is connected to the window structure, the file system
specification for the chosen file is assigned to the document structure's file system
specification field, and the window's title is set.

At that point, the application-defined function which reads in the window state resource
from the document's resource fork, and positions and sizes the window accordingly, is
called.  In addition, the application-defined function which reads in the printable area
resource from the document's resource fork is called.

With the window positioned and sized, ShowWindow is called to make the window visible. 
(The window's 'WIND' resource specifies that the window is to be initially invisible.)

doCloseCommand

doCloseCommand is a much simplified version of the actions normally taken when a user
chooses the Close command from a File menu.

At the first two lines, a pointer to the front window, and a handle to the associated
document structure, are retrieved.

The call to doSaveWindowPosition saves the window's user state and zoom state to the
window state resource in the document's resource fork.  If the print Style dialog was
invoked while the window was open, and if the user dismissed the dialog by clicking the
OK button, a call is made to doSavePrintableSize to save the printable area rectangle to
the printable area resource in the document file's resource fork.

DisposeHandle disposes of the document structure, DisposeWindow disposes of the window
structure, and the last line sets the "window is open" flag to indicate that the window
is not open.

doPreferencesDialog

doPreferencesDialog is called when the user chooses the Preferences item in the
Demonstration menu.  The function presents the Preferences dialog box and sets the values
in the global variables which hold the current application preferences according to the
settings of the dialog's checkboxes.

Note that, at the last line, a call is made to the application-defined function which
saves the dialog box's preference settings to the resource fork of the preferences file.

doPrintStyleDialog

doPrintStyleDialog is called when the user chooses the Page Setup... item in the File
menu.  It presents the print style dialog box.

If the user dismisses the dialog with a click on the OK button, the flag which indicates
that a print style change has been made is set to true, and the global variable which
holds the printable rectangle is assigned the value in the rPage (printable page size)
field of the TPrInfo structure, a handle to which is at the prInfo field of the TPrint
structure.  In addition, the window's port rectangle is invalidated to force an update of
the window, thus ensuring that the new printable area values are displayed immediately.

doGetPreferences

doGetPreferences, which is called from the main function immediately after program
launch, is the first of those application-defined functions central to the demonstration
aspects of the program.  Its purpose is to create the preferences file if it does not
already exist, copying the default preferences resource and the missing application
resource to that file as part of the creation process, and to read in the preferences
resource from the previously existing or newly-created preferences file.

GetIndString retrieves from the application's resource file the resource containing the
required name of the preferences file ("MoreResources Preferences").

FindFolder finds the location of the Preferences folder, returning the volume reference
number and directory ID in the last two parameters.  FSMakeFSSSpec makes a file system
specification from the preferences file name, volume reference number and directory ID. 
This file system specification is used in the FSpOpenResFile call to open the resource
fork of the preferences file with exclusive read/write permission.

If the specified file does not exist, FSpOpenResFile returns -1.  In that event
FSpCreateResFile creates the preferences file.  The call to FSpCreateResFile creates the
file of the specified type on the specified volume in the specified directory and with
the specified name and creator.  (Note that the creator is set to an arbitrary signature
which no other application known to the Finder is likely to have.  This is so that a
double click on the preferences file icon will cause the Finder to immediately display
the missing application alert box.)  Note also that, if 'pref' is used as the
fileType parameter, the icon used for the file will be the system-supplied preferences
document icon, which looks like this:

(Preferences icon)

If the file is created successfully, the resource fork of the file is opened by
FSpOpenResFile and the master preferences ('PrFn') and application missing 'STR '
resources are copied to the resource fork from the application's resource file.  If the
resources are not successfully copied, CloseResFile closes the resource fork of the new
file, FspDelete deletes the file, and the fileRefNum variable is set to indicate that the
file does not exist.

If the preferences file exists (either previously or newly-created), UseResFile sets the
resource fork of that file as the current resource file, the preferences resource is read
in from the resource fork by Get1Resource and, if the read was successful, the three
Boolean values are assigned to the global variables which store those values.  (Note
that, in this program, the function Get1Resource is used to read in resources so as to
restrict the Resource Manager's search for the specified resource to the current resource
file.)

The penultimate line assigns the file reference number for the open preferences file
resource fork to a global variable (the fork is left open).  The last line resets the
application's resource fork as the current resource file.

doCopyResource

doCopyResource is called by doGetPreferences to copy the default preferences and
application missing string to the newly-created preferences file from the application
file.

The first two lines save the current resource file's file reference number and set the
application's resource fork as the current resource file.  This will be the "source"
file.

The Get1Resource call reads the specified resource into memory.  GetResInfo gets the
resource's name and GetResAttrs gets the resource's attributes.  DetachResource replaces
the resource's handle in the resource map with NULL without releasing the associated
memory.  The resource data is now simply arbitrary data in memory.

UseResFile sets the preferences file's resource fork as the current resource file. 
AddResource makes the arbitrary data in memory into a resource, assigning it the
specified type, ID and name.  SetResAttrs sets the resource attributes in the resource
map.  ChangedResource tags the resource for update and pre-allocates the required disk
space.  WriteResource then writes the resource to disk.

With the resource written to disk, ReleaseResource discards the resource in memory and
UseResFile resets the resource file saved at the first line as the current resource file.

doSavePreferences

doSavePreferences is called when the user dismisses the preferences dialog box to save
the new preference settings to the preferences file.  It assumes that the preferences
file is already open.

At the first two lines, if doGetPreferences was not successful in opening the preferences
file at program launch, the function simply returns.

The next five lines create a new preferences structure and assign to its fields the
values in the global variables which store the current preference settings.  UseResFile
makes the preferences file's resource fork the current resource file.  Get1Resource gets
a handle to the existing preferences resource.  Assuming the call is successful (that is,
the preferences resource exists), RemoveResource is called to remove the resource from
the resource map, AddResource is called to make the preferences structure in memory into
a resource, and WriteResource is called to write the resource to disk.

With the resource written to disk, ReleaseResource disposes of the preferences structure
in memory and UseResFile resets the application's resource fork as the current resource
file.

doGetandSetWindowPosition

doGetandSetWindowPosition gets the window state ('WiSt') resource from the resource fork
of the document file and moves and sizes the window according to retrieved user state and
zoom state data.

The first three lines establish a default user state rectangle to cater for the
possibility that the document file may not yet have a 'WiSt' resource in its resource
fork.  The next three lines establish the standard state rectangle as desired by the
application.

GetWRefCon gets a handle to the window's document structure so that the file system
specification can be retrieved and used in the FSpOpenResFile call to open the document
file's resource fork.

Get1Resource attempts to read in the 'WiSt' resource.  If the Get1Resource call is
successful, a "success" flag is set and the user state rectangle is set to that retrieved
from the resource.  If the call is not successful, the "success" flag is unset and the
user state rectangle remains as the default rectangle defined earlier.

If the Get1Resource call was successful, the zoom state is also retrieved from the
resource.  If the zoom state is "zoomed out" to the standard state, the rectangle to be
used to display the window is set to the standard state.  If the zoom state is "zoomed
in" to the user state, the rectangle to be used to display the window is set to the user
state.  If the Get1Resource call was not successful, the display rectangle is set to the
user state rectangle, which will be the default rectangle defined earlier.

MoveWindow moves the window to the specified coordinates, keeping it inactive.  The next
block re-sizes the window to the specified size, adding any area added to the content
region to the update region.

doSetWindowState assigns the specified rectangles to the userState and stdState fields of
the WStateData structure for the window.  With this action completed, ReleaseResource
discards the 'WiSt' resource in memory and CloseResFile closes the document file's
resource fork.

doSaveWindowPosition

doSaveWindowPosition saves the current user state rectangle and zoom state to the
document file's resource fork.  The function is called when the associated window is
closed by the user.

The first line gets a handle to the window's document structure so that the document
file's file system specification can be retrieved and used in the FSpOpenResFile call. 
If the resource fork cannot be opened, an error alert is presented and the function
simply returns.

At the next block, a pointer to the window structure is retrieved, allowing a pointer to
the WStateData structure to be retrieved.  The last two lines in this block retrieve the
current standard state and user state rectangles from the WStateData structure.

The next step is to determine whether the window is currently in the "zoomed out"
(standard) state or the "zoomed in" (user) state.  The first two lines of the next block
get a rectangle equal to the content region of the window and set up a forthcoming test
by assigning this rectangle to the userStateRect field of a window state structure.  The
test is at the next line: If the content region rectangle equals the current standard
state rectangle, the call to EqualRect will return true, in which case:

*   The zoomstate field of the window state structure is assigned a value indicating
    that the window is in the standard state.

*   The userStateRect field of the window state structure is assigned the current user
    state rectangle.

If, on the other hand, the content region rectangle does not equal the current standard
state rectangle, the call to EqualRect will return false, in which case:

*   The zoomstate field of the window state structure is assigned a value indicating that
    the window is in the user state.

*   The userStateRect field of the window state structure retains the rectangle it was
    earlier assigned which, not being equal to the standard state rectangle, must be
    equal to the current user state rectangle.

Get1Resource attempts to read the 'WiSt' resource from the document's resource fork into
memory.  If the Get1Resource call is successful, the resource in memory is made equal to
the previously "filled-in" window state structure and the resource is tagged as changed. 
If the Get1Resource call is not successful (that is, the document file's resource fork
does not yet contain a 'WiSt' resource), the else statement creates a new window state
structure, makes this structure equal to the previously "filled-in" window state
structure, and makes this data in memory into a 'WiSt' resource.

If an existing 'WiSt' resource was successfully read in, or if a new 'WiSt' resource was
successfully created in memory, UpdateResFile writes the resource map and data to disk,
and ReleaseResource discards the resource in memory.  The document file's resource fork
is then closed by CloseResFile.

doSetWindowState

doSetWindowState is called by doGetandSetWindowPosition to assign the user and standard
state rectangles defined by that function to the userState and stdState fields of the
window's WStateData structure.

doGetPrintableSize

doGetPrintableSize gets the rectangle representing the printable area of the chosen page
size from the 'PrAr' resource in the document file's resource fork.  The function is
called when the document is opened.

The first line gets a handle to the window's document structure so that the document
file's file system specification can be retrieved and used in the call to FSpOpenResFile. 
If the call is not successful, an error alert box is presented and the function simply
returns.

If the resource fork is successfully opened, the call to Get1Resource attempts to read in
the resource.  If the call is successful, the data in the resource in memory is assigned
to the global variable which stores the current printable area rectangle.  The resource
in memory is then discarded and the document file's resource fork is closed.

doSavePrintableSize

doSavePrintableSize saves the printable area rectangle for the currently chosen paper
size to a 'PrAr' resource in the document file's resource fork.  The function is called
when the file is closed if the user invoked the print Style dialog while the document was
open and dismissed the dialog by clicking the OK button.

The first line gets a handle to the window's document structure so that the document
file's file system specification can be retrieved and used in the call to FSpOpenResFile. 
If the call is not successful, an error alert box is presented and the function simply
returns.

Get1Resource attempts to read the 'PrAr' resource from the document's resource fork into
memory.  If the Get1Resource call is successful, the resource in memory is made equal to
the rectangle in the prPage field of the prInfo structure, which is itself part of the
TPrint structure, and the resource is tagged as changed.  If the Get1Resource call is not
successful (that is, the document file's resource fork does not yet contain a 'PrAr'
resource), a block of memory is allocated for a Rect, the rectangle in the prPage field
of the prInfo structure is copied to this block, and AddResource  makes this data in
memory into a 'PrAr' resource.

If an existing 'PrAr' resource was successfully read in, or if a new 'PrAr' resource was
successfully created in memory, UpdateResFile writes the resource map and data to disk. 
ReleaseResource then discards the resource in memory.  At the last line, the document
file's resource fork is then closed.
 
MacTech Only Search:
Community Search:

 
 
 

 
 
 
 
 
  • SPREAD THE WORD:
  • Slashdot
  • Digg
  • Del.icio.us
  • Reddit
  • Newsvine
  • Generate a short URL for this page:



MacTech Magazine. www.mactech.com
Toll Free 877-MACTECH, Outside US/Canada: 805-494-9797
MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders.
All contents are Copyright 1984-2010 by Xplain Corporation. All rights reserved. Theme designed by Icreon.
 
Nov. 20: Take Control of Syncing Data in Sow Leopard' released
Nov. 19: Cocktail 4.5 (Leopard Edition) released
Nov. 19: macProVideo offers new Cubase tutorials
Nov. 18: S Stardom anounces Safe Capsule, a companion piece for Apple's
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live