TweetFollow Us on Twitter

MACINTOSH C CARBON

Demonstration Program Miscellany

Goto Contents

// *******************************************************************************************
// Miscellany.h                                                             CARBON EVENT MODEL
// *******************************************************************************************
// 
// This program demonstrates:
//
// o  The use of the Notification Manager to allow an application running in the background to
//    to communicate with the foreground application.
//
// o  The use of the determinate progress bar control to show progress during a time-
//    consuming operation, together with scanning the event queue for Command-period key-down
//    events for the purpose of terminating the lengthy operation  before it concludes of its
//    own accord.
//
// o  The use of the Color Picker to solicit a choice of colour from the user.
//
// o  Image drawing optimisation in a multi-monitors environment. 
//
// o  Help tags for controls and windows with minimum and maximum content. 
//
// The program utilises the following resources:
//
// o  A 'plst' resource.
//
// o  An 'MBAR' resource, and 'MENU' resources for Apple, File, Edit and Demonstration menus
//    (preload, non-purgeable).
//
// o  A 'DLOG' resource (purgeable), and associated 'DITL', 'dlgx', and 'dftb' resources
//    (purgeable), for a dialog box in which the progress indicator is displayed.
//
// o  'CNTL' resources (purgeable) for the progress indicator dialog.
//
// o  'icn#', 'ics4', and 'ics8' resources (non-purgeable) which contain the application icon
//    shown in the Application menu during the Notification Manager demonstration.
//
// o  A 'snd ' resource (non-purgeable) used in the Notification Manager demonstration.
//
// o  A 'STR ' resource (non-purgeable) containing the text displayed in the alert box invoked
//    by the Notification Manager.
//
// o  'STR#' resources (purgeable) containing the label and narrative strings for the
//    notification-related alert displayed by Miscellany and the minimum and maximum Help tag
//    content.
//
// o  A 'SIZE' resource with the acceptSuspendResumeEvents, canBackground, 
//    doesActivateOnFGSwitch, and isHighLevelEventAware flags set.
//
// *******************************************************************************************

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

#include <Carbon.h>

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

#define rMenubar            128
#define mAppleApplication   128
#define  iAbout             1
#define mFile               129
#define  iQuit              12
#define mDemonstration      131
#define  iNotification      1
#define  iProgress          2
#define  iColourPicker      3
#define  iMultiMonitors     4
#define  iHelpTag           5
#define rWindow             128
#define rDialog             128
#define  iProgressIndicator 1
#define rIconFamily         128
#define rBarkSound          8192
#define rString             128
#define rAlertStrings       128
#define  indexLabel         1
#define  indexNarrative     2
#define rPicture            128
#define topLeft(r)          (((Point *) &(r))[0])
#define botRight(r)         (((Point *) &(r))[1])

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

void      main                           (void);
void      doPreliminaries                (void);
OSStatus  appEventHandler                (EventHandlerCallRef,EventRef,void *);
OSStatus  windowEventHandler             (EventHandlerCallRef,EventRef,void *);
void      doMenuChoice                   (MenuID,MenuItemIndex);

void      doSetUpNotification            (void);
void      doPrepareNotificationStructure (void);
void      doIdle                         (void);
void      doDisplayMessageToUser         (void);

void      doProgressBar                  (void);

void      deviceLoopDraw                 (SInt16,SInt16,GDHandle,SInt32);

void      doColourPicker                 (void);
void      doDrawColourPickerChoice       (void);
char      *doDecimalToHexadecimal        (UInt16 n);

void      doHelpTagControl               (void);
void      doHelpTagWindow                (void);

// *******************************************************************************************
// Miscellany.c
// *******************************************************************************************

#include "Miscellany.h"

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

DeviceLoopDrawingUPP gDeviceLoopDrawUPP;
WindowRef            gWindowRef;
ControlRef           gBevelButtonControlRef;
ProcessSerialNumber  gProcessSerNum;
Boolean              gMultiMonitorsDrawDemo = false;
Boolean              gColourPickerDemo  = false;
Boolean              gHelpTagsDemo = false;
RGBColor             gWhiteColour = { 0xFFFF, 0xFFFF, 0xFFFF };
RGBColor             gBlueColour  = { 0x6666, 0x6666, 0x9999 };

extern Boolean       gNotificationInQueue;

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

void  main(void)
{
  MenuBarHandle menubarHdl;
  SInt32        response;
  MenuRef       menuRef;
  Rect          contentRect = { 100,100,402,545 };
  Rect          portRect;
  Rect          controlRect = { 65,10,155,100 };
  EventTypeSpec applicationEvents[] = { { kEventClassApplication, kEventAppActivated    },
                                        { kEventClassCommand,     kEventProcessCommand  } };
  EventTypeSpec windowEvents[]      = { { kEventClassWindow, kEventWindowDrawContent    },
                                        { kEventClassWindow, kEventWindowGetIdealSize   },
                                        { kEventClassWindow, kEventWindowGetMinimumSize },
                                        { kEventClassWindow, kEventWindowBoundsChanged  } };

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

  doPreliminaries();

  // ...................................................... create universal procedure pointer

  gDeviceLoopDrawUPP = NewDeviceLoopDrawingUPP((DeviceLoopDrawingProcPtr) deviceLoopDraw);

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

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

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

  // ............................................. install application event handler and timer

  InstallApplicationEventHandler(NewEventHandlerUPP((EventHandlerProcPtr) appEventHandler),
                                 GetEventTypeCount(applicationEvents),applicationEvents,
                                 0,NULL);

  InstallEventLoopTimer(GetCurrentEventLoop(),0,1,
                        NewEventLoopTimerUPP((EventLoopTimerProcPtr) doIdle),NULL,NULL);

  // ............................................................................. open window

  CreateNewWindow(kDocumentWindowClass,kWindowStandardHandlerAttribute |
                  kWindowStandardDocumentAttributes,&contentRect,&gWindowRef);

  ChangeWindowAttributes(gWindowRef,0,kWindowCloseBoxAttribute);
  SetWTitle(gWindowRef,"\pMiscellany");
  RepositionWindow(gWindowRef,NULL,kWindowAlertPositionOnMainScreen);

  SetPortWindowPort(gWindowRef);
  TextSize(10);

  ShowWindow(gWindowRef);
  GetWindowPortBounds(gWindowRef,&portRect);
  InvalWindowRect(gWindowRef,&portRect);

  // ............................................................ install window event handler

  InstallWindowEventHandler(gWindowRef,
                            NewEventHandlerUPP((EventHandlerProcPtr) windowEventHandler),
                            GetEventTypeCount(windowEvents),windowEvents,0,NULL);

  // ............................................................ create control and help tags

  CreateBevelButtonControl(gWindowRef,&controlRect,CFSTR("Control"),
                           kControlBevelButtonNormalBevel,kControlBehaviorPushbutton,
                           NULL,0,0,0,&gBevelButtonControlRef);
  doHelpTagControl();
  HideControl(gBevelButtonControlRef);
  doHelpTagWindow();
  HMSetHelpTagsDisplayed(false);

  // ............................................... get process serial number of this process

  GetCurrentProcess(&gProcessSerNum);  

  // .............................................................. run application event loop

  RunApplicationEventLoop();
}

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

void  doPreliminaries(void)
{
  MoreMasterPointers(640);
  InitCursor();
}

// *************************************************************************** appEventHandler

OSStatus  appEventHandler(EventHandlerCallRef eventHandlerCallRef,EventRef eventRef,
                          void * userData)
{
  OSStatus      result = eventNotHandledErr;
  UInt32        eventClass;
  UInt32        eventKind;
  HICommand     hiCommand;
  MenuID        menuID;
  MenuItemIndex menuItem;

  eventClass = GetEventClass(eventRef);
  eventKind  = GetEventKind(eventRef);

  switch(eventClass)
  {
    case kEventClassApplication:
      if(eventKind == kEventAppActivated)
      {
        if(gNotificationInQueue)
          doDisplayMessageToUser();
        result = noErr;
      }
      break;

    case kEventClassCommand:
      if(eventKind == kEventProcessCommand)
      {
        GetEventParameter(eventRef,kEventParamDirectObject,typeHICommand,NULL,
                          sizeof(HICommand),NULL,&hiCommand);
        menuID = GetMenuID(hiCommand.menu.menuRef);
        menuItem = hiCommand.menu.menuItemIndex;
        if((hiCommand.commandID != kHICommandQuit) && 
           (menuID >= mAppleApplication && menuID <= mDemonstration))
        {
          doMenuChoice(menuID,menuItem);
          result = noErr;
        }
      }
      break;
  }

  return result;
}

// ************************************************************************ windowEventHandler

OSStatus  windowEventHandler(EventHandlerCallRef eventHandlerCallRef,EventRef eventRef,
                             void* userData)
{
  OSStatus  result = eventNotHandledErr;
  UInt32    eventClass;
  UInt32    eventKind;
  WindowRef windowRef;
  SInt32    deviceLoopUserData;
  RgnHandle regionHdl;
  Rect      portRect, positioningBounds;
  Point     idealHeightAndWidth, minimumHeightAndWidth;

  eventClass = GetEventClass(eventRef);
  eventKind  = GetEventKind(eventRef);

  switch(eventClass)
  {
    case kEventClassWindow:
      GetEventParameter(eventRef,kEventParamDirectObject,typeWindowRef,NULL,sizeof(windowRef),
                        NULL,&windowRef);
      switch(eventKind)
      {
        case kEventWindowDrawContent:
          if(gMultiMonitorsDrawDemo)
          {
            RGBBackColor(&gWhiteColour);
            deviceLoopUserData = (SInt32) windowRef;
            regionHdl = NewRgn();
            if(regionHdl)
            {
              GetPortVisibleRegion(GetWindowPort(windowRef),regionHdl);
              DeviceLoop(regionHdl,gDeviceLoopDrawUPP,deviceLoopUserData,0);
              DisposeRgn(regionHdl);
            }
          }
          else if(gColourPickerDemo )
          {
            RGBBackColor(&gBlueColour);
            GetWindowPortBounds(windowRef,&portRect);
            EraseRect(&portRect);
            doDrawColourPickerChoice();
          }
          else
          {
            RGBBackColor(&gBlueColour);
            GetWindowPortBounds(windowRef,&portRect);
            EraseRect(&portRect);
            if(gHelpTagsDemo)
            {
              Draw1Control(gBevelButtonControlRef);
              RGBForeColor(&gWhiteColour);
              MoveTo(10,20);
              DrawString("\pHover the cursor in the window, and over the bevel button, ");
              DrawString("\puntil the Help tag appears.");
              MoveTo(10,35);
              DrawString("\pPress the Command key to invoke the maximum content.");
              MoveTo(10,50);
              DrawString("\pDrag the window to a new location.");
            }
          }
          result = noErr;
          break;

        case kEventWindowGetIdealSize:
          GetAvailableWindowPositioningBounds(GetMainDevice(),&positioningBounds);
          idealHeightAndWidth.v = positioningBounds.bottom;
          idealHeightAndWidth.h = positioningBounds.right;
          SetEventParameter(eventRef,kEventParamDimensions,typeQDPoint,
                            sizeof(idealHeightAndWidth),&idealHeightAndWidth);
           result = noErr;
          break;

        case kEventWindowGetMinimumSize:
          minimumHeightAndWidth.v = 302; 
          minimumHeightAndWidth.h = 445;
          SetEventParameter(eventRef,kEventParamDimensions,typeQDPoint,
                            sizeof(minimumHeightAndWidth),&minimumHeightAndWidth);
          result = noErr;
          break;

        case kEventWindowBoundsChanged:
          doHelpTagWindow();
          GetWindowPortBounds(windowRef,&portRect);
          InvalWindowRect(windowRef,&portRect);
          result = noErr;
          break;
      }
      break;
  }

  return result;
}

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

void  doMenuChoice(MenuID menuID,MenuItemIndex menuItem)
{
  Rect portRect;

  if(menuID == 0)
    return;

  switch(menuID)
  {
    case mAppleApplication:
      if(menuItem == iAbout)
        SysBeep(10);
      break;

    case mDemonstration:
      gMultiMonitorsDrawDemo = gColourPickerDemo = gHelpTagsDemo = false;
      if(HMAreHelpTagsDisplayed)
        HMSetHelpTagsDisplayed(false);
      HideControl(gBevelButtonControlRef);
      GetWindowPortBounds(gWindowRef,&portRect);

      switch(menuItem)
      {
        case iNotification:
          RGBBackColor(&gBlueColour);
          EraseRect(&portRect);
          doSetUpNotification();
          break;
          
        case iProgress:
          RGBBackColor(&gBlueColour);
          EraseRect(&portRect);
          doProgressBar();
          break;

        case iColourPicker:
          gColourPickerDemo = true;
          doColourPicker();
          break;
          
        case iMultiMonitors:
          gMultiMonitorsDrawDemo = true;
          InvalWindowRect(gWindowRef,&portRect);
          break;

        case iHelpTag:
          gHelpTagsDemo = true;
          InvalWindowRect(gWindowRef,&portRect);
          ShowControl(gBevelButtonControlRef);
          HMSetHelpTagsDisplayed(true);
          break;
      }

      break;
  }
}

// *******************************************************************************************
// Notification.c
// *******************************************************************************************

#include "Miscellany.h"

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

NMRec                      gNotificationStructure;
long                       gStartingTickCount;
Boolean                    gNotificationDemoInvoked;
Boolean                    gNotificationInQueue;
extern WindowRef           gWindowRef;
extern ProcessSerialNumber gProcessSerNum;
extern RGBColor            gWhiteColour;
extern RGBColor            gBlueColour;

// *********************************************************************** doSetUpNotification

void  doSetUpNotification(void)
{
  doPrepareNotificationStructure();
  gNotificationDemoInvoked = true;

  gStartingTickCount = TickCount();

  RGBForeColor(&gWhiteColour);
  MoveTo(10,279);
  DrawString("\pPlease click on the desktop now to make the Finder ");
  DrawString("\pthe frontmost application.");
  MoveTo(10,292);
  DrawString("\p(This application will post a notification 10 seconds from now.)");
}

// ************************************************************ doPrepareNotificationStructure

void  doPrepareNotificationStructure(void)
{
  Handle       iconSuiteHdl;
  Handle       soundHdl;
  StringHandle stringHdl;

  GetIconSuite(&iconSuiteHdl,rIconFamily,kSelectorAllSmallData);
  soundHdl = GetResource('snd ',rBarkSound);
  stringHdl = GetString(rString);

  gNotificationStructure.qType    = nmType;
  gNotificationStructure.nmMark   = 1;
  gNotificationStructure.nmIcon   = iconSuiteHdl;
  gNotificationStructure.nmSound  = soundHdl;
  gNotificationStructure.nmStr    = *stringHdl;
  gNotificationStructure.nmResp   = NULL;
  gNotificationStructure.nmRefCon = 0;
}

// ************************************************************************************ doIdle

void  doIdle(void)
{
  ProcessSerialNumber frontProcessSerNum;
  Boolean             isSameProcess;
  Rect                portRect;

  if(gNotificationDemoInvoked)
  {
    if(TickCount() > gStartingTickCount + 600)
    {
      GetFrontProcess(&frontProcessSerNum);
      SameProcess(&frontProcessSerNum,&gProcessSerNum,&isSameProcess);
  
      if(!isSameProcess)
      {
        NMInstall(&gNotificationStructure);
        gNotificationDemoInvoked = false;
        gNotificationInQueue = true;
      }
      else
      {
        doDisplayMessageToUser();
        gNotificationDemoInvoked = false;
      }

      GetWindowPortBounds(gWindowRef,&portRect);
      EraseRect(&portRect);
    }
  }
}

// ******************************************************************** doDisplayMessageToUser

void  doDisplayMessageToUser(void)
{
  Rect                  portRect;
  AlertStdAlertParamRec paramRec;
  Str255                labelText;
  Str255                narrativeText;
  SInt16                itemHit;

  if(gNotificationInQueue)
  {
    NMRemove(&gNotificationStructure);
    gNotificationInQueue = false;
  }

  GetWindowPortBounds(gWindowRef,&portRect);
  EraseRect(&portRect);
  
  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;

  GetIndString(labelText,rAlertStrings,indexLabel);
  GetIndString(narrativeText,rAlertStrings,indexNarrative);

  StandardAlert(kAlertNoteAlert,labelText,narrativeText,¶mRec,&itemHit);

  DisposeIconSuite(gNotificationStructure.nmIcon,false);
  ReleaseResource(gNotificationStructure.nmSound);
  ReleaseResource((Handle) gNotificationStructure.nmStr);
}

// *******************************************************************************************
// ProgressIndicator.c
// *******************************************************************************************

#include "Miscellany.h"

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

extern WindowRef gWindowRef;
extern RGBColor  gWhiteColour;

// ***************************************************************************** doProgressBar

void  doProgressBar(void)
{
  DialogRef  dialogRef;
  RgnHandle  visRegionHdl = NewRgn();
  ControlRef progressBarRef;
  SInt16     statusMax, statusCurrent;
  SInt16     a, b, c;
  Handle     soundHdl;
  Rect       portRect, theRect;
  RGBColor   redColour = { 0xFFFF, 0x0000, 0x0000 };
  
  if(!(dialogRef = GetNewDialog(rDialog,NULL,(WindowRef) -1)))
    ExitToShell();

  SetPortDialogPort(dialogRef);
  GetPortVisibleRegion(GetWindowPort(GetDialogWindow(dialogRef)),visRegionHdl);
  UpdateControls(GetDialogWindow(dialogRef),visRegionHdl);
  QDFlushPortBuffer(GetDialogPort(dialogRef),NULL);

  SetPortWindowPort(gWindowRef);
  GetWindowPortBounds(gWindowRef,&portRect);

  GetDialogItemAsControl(dialogRef,iProgressIndicator,&progressBarRef);

  statusMax = 3456;
  statusCurrent = 0;
  SetControlMaximum(progressBarRef,statusMax);

  for(a=0;a<9;a++)
  {
    for(b=8;b<423;b+=18)
    {
      for(c=8;c<286;c+=18)
      {
        if(CheckEventQueueForUserCancel())
        {
          soundHdl = GetResource('snd ',rBarkSound);
          SndPlay(NULL,(SndListHandle) soundHdl,false);
          ReleaseResource(soundHdl);
          DisposeDialog(dialogRef);

          EraseRect(&portRect);
          MoveTo(10,292);
          RGBForeColor(&gWhiteColour);
          DrawString("\pOperation cancelled at user request");

          return;
        }
        
        SetRect(&theRect,b+a,c+a,b+17-a,c+17-a);
        if(a < 3)                 RGBForeColor(&gWhiteColour);
        else if(a > 2 && a < 6)  RGBForeColor(&redColour);
        else if(a > 5)           RGBForeColor(&gWhiteColour);
        FrameRect(&theRect);

        QDFlushPortBuffer(GetWindowPort(gWindowRef),NULL);
        QDFlushPortBuffer(GetDialogPort(dialogRef),NULL);

        SetControlValue(progressBarRef,statusCurrent++);
      }
    }
  }

  DisposeRgn(visRegionHdl);
  DisposeDialog(dialogRef);  
  EraseRect(&portRect);
  MoveTo(10,292);
  RGBForeColor(&gWhiteColour);
  DrawString("\pOperation completed");
}

// *******************************************************************************************
// ColourPicker.c
// *******************************************************************************************

#include "Miscellany.h"

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

RGBColor         gInColour = { 0xCCCC, 0x0000, 0x0000 };
RGBColor         gOutColour;
Boolean          gColorPickerButton;
extern WindowRef gWindowRef;
extern RGBColor  gWhiteColour;
extern RGBColor  gBlueColour;

// **************************************************************************** doColourPicker

void  doColourPicker(void)
{
  Rect   portRect, theRect;
  Point  where;
  Str255 prompt = "\pChoose a rectangle colour:";

  GetWindowPortBounds(gWindowRef,&portRect);
  theRect = portRect;

  RGBBackColor(&gBlueColour);
  EraseRect(&theRect);
  InsetRect(&theRect,55,55);
  RGBForeColor(&gInColour);
  PaintRect(&theRect);

  where.v = where.h = 0;

  gColorPickerButton = GetColor(where,prompt,&gInColour,&gOutColour);

  InvalWindowRect(gWindowRef,&portRect);
}

// ******************************************************************* doDrawColorPickerChoice

void  doDrawColourPickerChoice(void)
{
  Rect portRect;
  char *cString;  

  GetWindowPortBounds(gWindowRef,&portRect);
  InsetRect(&portRect,55,55);

  if(gColorPickerButton)
  {
    RGBForeColor(&gOutColour);
    PaintRect(&portRect);

    RGBForeColor(&gWhiteColour);

    MoveTo(55,22);
    DrawString("\pRequested Red Value: ");
    cString = doDecimalToHexadecimal(gOutColour.red);
    MoveTo(170,22);
    DrawText(cString,0,6);

    MoveTo(55,35);
    DrawString("\pRequested Green Value: ");
    cString = doDecimalToHexadecimal(gOutColour.green);
    MoveTo(170,35);
    DrawText(cString,0,6);

    MoveTo(55,48);
    DrawString("\pRequested Blue Value: ");
    cString = doDecimalToHexadecimal(gOutColour.blue);
    MoveTo(170,48);
    DrawText(cString,0,6);
  }
  else
  {
    RGBForeColor(&gInColour);
    PaintRect(&portRect);

    RGBForeColor(&gWhiteColour);
    MoveTo(55,48);
    DrawString("\pCancel button was clicked.");
  }
}

// ******************************************************************** doDecimalToHexadecimal

char  *doDecimalToHexadecimal(UInt16 decimalNumber)
{
  static char cString[] = "0xXXXX";
  char        *hexCharas = "0123456789ABCDEF";
  SInt16      a;

  for (a=0;a<4;decimalNumber >>= 4,++a)
    cString[5 - a] = hexCharas[decimalNumber & 0xF];

  return cString;
}

// *******************************************************************************************
// MultiMonitor.c
// *******************************************************************************************

#include "Miscellany.h"

// **************************************************************************** deviceLoopDraw

void  deviceLoopDraw(SInt16 depth,SInt16 deviceFlags,GDHandle targetDeviceHdl,SInt32 userData)
{
  RGBColor  oldForeColour;
  WindowRef windowRef;
  Rect      portRect;
  RGBColor  greenColour  = { 0x0000, 0xAAAA, 0x1111 };
  RGBColor  redColour    = { 0xAAAA, 0x4444, 0x3333 };
  RGBColor  blueColour   = { 0x5555, 0x4444, 0xFFFF };
  RGBColor  ltGrayColour = { 0xDDDD, 0xDDDD, 0xDDDD };
  RGBColor  grayColour   = { 0x9999, 0x9999, 0x9999 };
  RGBColor  dkGrayColour = { 0x4444, 0x4444, 0x4444 };
  
  GetForeColor(&oldForeColour);

  windowRef = (WindowRef) userData;
  GetWindowPortBounds(windowRef,&portRect);
  EraseRect(&portRect);

  if(((1 << gdDevType) & deviceFlags) != 0)
  {
    InsetRect(&portRect,50,50);
    RGBForeColor(&greenColour);
    PaintRect(&portRect);
    InsetRect(&portRect,40,40);
    RGBForeColor(&redColour);
    PaintRect(&portRect);
    InsetRect(&portRect,40,40);
    RGBForeColor(&blueColour);
    PaintRect(&portRect);
  }
  else
  {
    InsetRect(&portRect,50,50);
    RGBForeColor(<GrayColour);
    PaintRect(&portRect);
    InsetRect(&portRect,40,40);
    RGBForeColor(&grayColour);
    PaintRect(&portRect);
    InsetRect(&portRect,40,40);
    RGBForeColor(&dkGrayColour);
    PaintRect(&portRect);
  }

  RGBForeColor(&oldForeColour);
}

// *******************************************************************************************
// HelpTag.c
// *******************************************************************************************

#include "Miscellany.h"
#include <string.h>

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

extern ControlRef gBevelButtonControlRef;
extern WindowRef  gWindowRef;

// .......................................................................... doHelpTagControl

void  doHelpTagControl(void)
{
  HMHelpContentRec helpContent;

  memset(&helpContent,0,sizeof(helpContent));
  HMSetTagDelay(50);

  helpContent.version = kMacHelpVersion;
  helpContent.tagSide = kHMOutsideBottomLeftAligned;

  helpContent.content[kHMMinimumContentIndex].contentType = kHMStringResContent;
  helpContent.content[kHMMinimumContentIndex].u.tagStringRes.hmmResID = 129;
  helpContent.content[kHMMinimumContentIndex].u.tagStringRes.hmmIndex = 1;
  helpContent.content[kHMMaximumContentIndex].contentType = kHMStringResContent;
  helpContent.content[kHMMaximumContentIndex].u.tagStringRes.hmmResID = 129;
  helpContent.content[kHMMaximumContentIndex].u.tagStringRes.hmmIndex = 2;

  HMSetControlHelpContent(gBevelButtonControlRef,&helpContent);
}

// ........................................................................... doHelpTagWindow

void  doHelpTagWindow(void)
{
  Rect              hotRect;
  HMHelpContentRec  helpContent;

  memset(&helpContent,0,sizeof(helpContent));
  HMSetTagDelay(500);

  helpContent.version = kMacHelpVersion;
  helpContent.tagSide = kHMOutsideRightCenterAligned;
  
  GetWindowPortBounds(gWindowRef,&hotRect);
  LocalToGlobal(&topLeft(hotRect));
  LocalToGlobal(&botRight(hotRect));  
  helpContent.absHotRect = hotRect;

  helpContent.content[kHMMinimumContentIndex].contentType = kHMStringResContent;
  helpContent.content[kHMMinimumContentIndex].u.tagStringRes.hmmResID = 129;
  helpContent.content[kHMMinimumContentIndex].u.tagStringRes.hmmIndex = 3;
  helpContent.content[kHMMaximumContentIndex].contentType = kHMStringResContent;
  helpContent.content[kHMMaximumContentIndex].u.tagStringRes.hmmResID = 129;
  helpContent.content[kHMMaximumContentIndex].u.tagStringRes.hmmIndex = 4;

  HMSetWindowHelpContent(gWindowRef,&helpContent);
}

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

Demonstration Program Miscellany Comments

When this program is run, the user should make choices from the Demonstration menu, taking the
following actions and making the following observations:

o Choose the Notification item and, observing the instructions in the window, click the desktop
  immediately to make the Finder the foreground application.  A notification will be posted by
  Miscellany about 10 seconds after the Notification item choice is made.  Note that, when
  about 10 seconds have elapsed, the Notification Manager invokes an alert (Mac OS 8.6), 
  floating window (Mac OS 9.x), or system movable modal alert (Mac OS X) and alternates the
  Finder and Miscellany icons in the OS 8/9 Application menu title.  Observing the instructions
  in the alert/floating window/system movable modal alert:

o Dismiss the alert (Mac OS 8.6 only).

o On Mac OS 8/9, then choose the Miscellany item in the OS 8/9 Application menu, noting the 
  diamond mark to the left of the item name.  When Miscellany comes to the foreground, note
  that the icon alternation concludes and that an alert (invoked by Miscellany) appears. 
  Dismiss this second alert.

o On Mac OS X, click on the application's icon in the Dock.

o Choose the Notification item again and, this time, leave Miscellany in the foreground.  
  Note that only the alert invoked by Miscellany appears on this occasion.

o Choose the Notification item again and, this time, click on the desktop and then in the 
  Miscellany window before 10 seconds elapse.  Note again that only the alert invoked by
  Miscellany appears.

o Choose the Determinate Progress Indicator item, noting that the progress indicator dialog is
  automatically disposed of when the (simulated) time-consuming task concludes.

o Choose the Determinate Progress Indicator item again, and this time press the Command-period
  key combination before the (simulated) time-consuming task concludes.  Note that the progress
  indicator dialog is disposed of when the Command-period key combination is pressed.

o Choose the Colour Picker item and make colour choices using the various available modes. 
  Note that, when the Colour Picker is dismissed by clicking the OK button, the requested RGB
  colour values for the chosen colour are displayed in hexadecimal, together with a rectangle
  in that colour, in the Miscellany window.

o Choose the Multiple Monitors Draw item, noting that the drawing of the simple demonstration
  image is optimised as follows:

o On a monitor set to display 256 or more colours, the image is drawn in three distinct
  colours.  The luminance of the three colours is identical, meaning that, if these colours are
  drawn on a grayscale screen, they will all appear in the same shade of gray.

o On a monitor set to display 256 shades of gray, the image is drawn in three distinct shades
  of gray.

o Choose the Help Tags item, hover the cursor over the window and, when the Help tag appears,
  press the Command key to observe the maximum content version of the tag.  Repeat this while
  hovering the cursor over the bevel button control.

Miscellany.c

Global Variables

gDeviceLoopDrawUPP will be assigned a universal procedure pointer to the image-optimising
drawing function deviceLoopDraw called by DeviceLoop.  gProcessSerNum will be assigned the
process serial number of the Miscellany application.

main

The call to NewDeviceLoopDrawingProc creates a universal procedure pointer to the
image-optimising drawing function deviceLoopDraw.

A timer is installed and set to fire every one second.  When it fires, the function doIdle is
called.

A bevel button control is created, following which the calls to doHelpTagControl and
doHelpTagWindow create Help tags for the bevel button control and the window. 
HMSetHelpTagsDisplayed is called to disable the tags until the Help Tags item is chosen from
the Demonstration menu.

GetCurrentProcess gets the process serial number of this process.  The timer and the process
serial number are used in the notification demonstration.

appEventHandler

When the kEventAppActivated event type is received, if the global variable gNotificationInQueue
is set to true, doDisplayMessageToUser is called.  This is part of the notification
demonstration.

windowEventHandler

When the kEventWindowDrawContent event type is received, if the Multiple Monitors Draw item in
the Demonstration menu has been chosen (gMultiMonitorsDrawDemo is true), a call is made to
DeviceLoop and the universal procedure pointer to the application-defined (callback) drawing
function deviceLoopDraw is passed as the second parameter.

doMenuChoice

When the Multiple Monitors Draw item in the Demonstration menu is chosen, the window's port
rectangle is invalidated so as to force a kEventWindowDrawContent event and consequential call
to DeviceLoop.

Notification.c

doSetUpNotification

doSetUpNotification is called when the user chooses Notification from the Demonstration menu.

The first line calls doPrepareNotificationStructure, which fills in the relevant fields of a
notification structure.  The next line assigns true to a global variable which records that the
Notification item has been chosen by the user.

The next line saves the system tick count at the time that the user chose the Notification
item.  This value is used later to determine when 10 seconds have elapsed following the
execution of this line.

doPrepareNotificationStructure

doPrepareNotificationStructure fills in the relevant fields of the notification structure.

First, however, GetIconSuite creates an icon suite based on the specified resource ID and the
third parameter, which limits the suite to 'ics#', 'ics4' and 'ics8' icons.  The GetIconSuite
call returns the handle to the suite in its first parameter.  The call to GetResource loads the
specified 'snd ' resource.  GetString loads the specified 'STR ' resource.

The first line of the main block specifies the type of operating system queue.  The next line
specifies that the ¨ mark is to appear next to the application's name in the Mac OS 8/9
Application menu.  The next three lines assign the icon suite (for Mac OS 8/9), sound (for Mac
OS 8/9) and string handles previously obtained.  The next line specifies that no response
function is required to be executed when the notification is posted.

doIdle

doIdle is called when the installed timer fires.

If the user has not just chosen the Notification item in the Demonstration menu
(gNotificationDemoInvoked is false), doIdle simply returns immediately.

If, however, that item has just been chosen, and if 10 seconds (600 ticks) have elapsed since
that choice was made, the following occurs:

o The calls to GetFrontProcess and SameProcess determine whether the current foreground process
  is Miscellany.  If it is not, the notification request is installed in the notification queue
  by NMInstall and the global variable gNotificationInQueue is set to indicate that a request 
  has been placed in the queue by Miscellany.  (This latter causes doDisplayMessageToUser to be
  called when the kEventAppActivated event is received.  doDisplayMessageToUser removes the
  notification request from the queue and has Miscellany convey the required message to the
  user.)  Also, gNotificationDemoInvoked is set to false so as to ensure that the main if block
  only executes once after the Notification item is chosen.

o If, however, the current foreground process is Miscellany, the function
  doDisplayMessageToUser is called to present the required message to the user in the normal
  way.  Once again gNotificationDemoInvoked is reset to false so as to ensure that the main if 
  block only executes once after the Notification item is chosen.

doDisplayMessageToUser

doDisplayMessageToUser is called by appEventHandler and doIdle in the circumstances previously
described.

If a Miscellany notification request is in the queue, NMRemove removes it from the queue and
gNotificationInQueue is set to false to reflect this condition.  (Recall that, if the nmResp
field of the notification structure is not assigned -1, the application itself must remove the
queue element from the queue.)

Regardless of whether there was a notification in the queue or not, Miscellany then presents
its alert.  When the alert is dismissed, the notification's icon suite, sound and string
resources are released/disposed of.

ProgressBar.c

doProgressBar

doProgressBar is called when the user chooses Determinate Progress Indicator from the
Demonstration menu.

GetNewDialog creates a modal dialog.  The call to GetDialogItemAsControl retrieves the dialog's
progress indicator control.  SetControlMaximum sets the control's maximum value to equate to
the number of steps in a simulated time-consuming task.

The main for loop performs the simulated time-consuming task, represented to the user by the
drawing of a large number of coloured rectangles in the window.  The task involves 3456 calls
to FrameRect.

Within the inner for loop, CheckEventQueueForCancel is called to check whether the user has
pressed the Command-period key.  If so, a 'snd ' resource is loaded, played, and released, the
dialog is disposed of, an advisory message in drawn in the window, and the function returns.

Each time round around the inner for loop, a progress indicator control's value is incremented.

When the outer for loop exits (that is, when the Command-period key combination is not pressed
before the simulated time-consuming task completes), the dialog is disposed of.

ColourPicker.c

doColourPicker

doColourPicker is called when the user chooses Colour Picker from the Demonstration menu.

The first block erases the window's content area and paints a rectangle in the colour that will
be passed in GetColor's inColor parameter. 

The next line assigns 0 to the fields of the Point variable to be passed in GetColor's where
parameter.  ((0,0) will cause the Colour Picker dialog to be centred on the main screen.)

The call to GetColor displays the Colour Picker's dialog.  GetColor retains control until the
user clicks either the OK button or the Cancel button, at which time the port rectangle is
invalidated, causing the function doDrawColourPickerChoice to be called.

doDrawColourPickerChoice

If the user clicked the OK button, a filled rectangle is painted in the window in the colour
returned in GetColor's outColor parameter, and the values representing the red, green, and blue
components of this colour are displayed at the top of the window in hexadecimal.  Note that the
function doDecimalToHexadecimal is called to convert the decimal (UInt32) values in the fields
of the RGBColor variable outColor to hexadecimal.

If the user clicks the Cancel button, a filled rectangle is painted in the window in the colour
passed in GetColor's inColor parameter.

doDecimalToHexadecimal

doDecimalToHexadecimal converts a UInt16 value to a hexadecimal string.

MultiMonitor.c

deviceLoopDraw

deviceLoopDraw is the image-optimising drawing function the universal procedure pointer to
which is passed in the second parameter in the DeviceLoop call.  (Recall that the DeviceLoop
call is made whenever the Multiple Monitors Draw item in the Demonstration menu has been
selected and an kEventDrawContent event type is received.)  DeviceLoop scans all active video
devices, calling deviceLoopDraw whenever it encounters a device which intersects the drawing
region, and passing certain information to deviceLoopDraw.

The second line casts the SInt32 value received in the userData parameter to a WindowRef.  The
window's content area is then erased.

If an examination of the device's attributes, as received in the deviceFlags formal parameter,
reveals that the device is a colour device, three rectangles are painted in the window in three
different colours.  (The luminance value of these colours is the same, meaning that the
rectangles would all be the same shade of gray if they were drawn on a monochrome (grayscale)
device.) 

If the examination of the device's attributes reveals that the device is a monochrome device,
the rectangles are painted in three distinct shades of gray.

HelpTag.c

doHelpTagControl and doHelpTagWindow

doHelpTagControl and doHelpTagWindow create Help tags for the bevel button control and the
window.

The call to memset clears the specified block of memory.  The call to HMSetTagDelay sets the
delay, in milliseconds, before the tag opens.

For the bevel button, the tagSide field of the HMHelpContentRec structure is assigned a value
which will cause the control's tag to be displayed below the control with its left side aligned
with the left side of the button.  For the window, the tagSide field is assigned a value which
will cause the control's tag to be displayed on the window's right, centered vertically.

The main block sets the content type and retrieves and assigns the minimum and maximum content
strings from a 'STR#' resource.  The calls to HMSetControlHelpContent and
HMSetWindowHelpContent install the Help tags on the control and window.
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.