Retired Document
Important: This sample code may not represent best practices for current development. The project may use deprecated symbols and illustrate technologies and techniques that are no longer recommended.
Utilities.h
/* |
File: Utilities.h |
Contains: Collection of Utilities for DTS Sample code |
Written by: |
Copyright: Copyright © 1988-1999 by Apple Computer, Inc., All Rights Reserved. |
You may incorporate this Apple sample source code into your program(s) without |
restriction. This Apple sample source code has been provided "AS IS" and the |
responsibility for its operation is yours. You are not permitted to redistribute |
this Apple sample source code as "Apple sample source code" after having made |
changes. If you're going to re-distribute the source, we require that you make |
it clear in the source that the code was descended from Apple sample source |
code, but that you've made changes. |
Change History (most recent first): |
8/18/1999 Karl Groethe Updated for Metrowerks Codewarror Pro 2.1 |
*/ |
#ifndef __UTILITIES__ |
#define __UTILITIES__ |
#ifndef __TYPES__ |
#include <Types.h> |
#endif |
#ifndef __QUICKDRAW__ |
#include <QuickDraw.h> |
#endif |
#ifndef __DIALOGS__ |
#include <Dialogs.h> |
#endif |
#ifndef __FILES__ |
#include <Files.h> |
#endif |
#ifndef __MEMORY__ |
#include <Memory.h> |
#endif |
#ifndef __OSUTILS__ |
#include <OSUtils.h> |
#endif |
#ifndef __WINDOWS__ |
#include <Windows.h> |
#endif |
#ifndef __GESTALT__ |
#include "Gestalt.h" |
#endif |
#ifndef __FOLDERS__ |
#include <Folders.h> |
#endif |
#include "UtilitiesCommon.h" |
/*----------------------------------------------------------------------------------------- |
Global constants |
-----------------------------------------------------------------------------------------*/ |
#define kOSEvent app4Evt /* event used by MultiFinder */ |
#define kSuspendResumeMessage 1 /* high byte of suspend/resume event message */ |
#define kResumeMask 1 /* bit of message field for resume vs. suspend */ |
#define kMouseMovedMessage 0xFA /* high byte of mouse-moved event message */ |
#define kNoEvents 0 /* no events mask */ |
#define kDelayTime 8 /* For the delay time when flashing the |
menubar and highlighting a button. |
8/60ths of a second*/ |
#define kStartPtH 2 /* offset from the left of the screen */ |
#define kStartPtV 2 /* offset from the top of the screen */ |
#define kStaggerH 12 /* staggering amounts for new windows */ |
#define kStaggerV 16 |
#define chBackspace '\b' /* ASCII code for Backspace character */ |
#define chClear '\033' /* ASCII code for Clear key (aka ESC) */ |
#define chDown '\037' /* ASCII code for down arrow */ |
#define chEnd '\004' /* ASCII code for the End key */ |
#define chEnter '\003' /* ASCII code for Enter character */ |
#define chEscape '\033' /* ASCII code for Escape (aka Clear) key */ |
#define chFunction '\020' /* ASCII code for any function key */ |
#define chFwdDelete '\177' /* ASCII code for forward delete */ |
#define chHelp '\005' /* ASCII code for Help key */ |
#define chHome '\001' /* ASCII code for the Home key */ |
#define chLeft '\034' /* ASCII code for left arrow */ |
#define chPageDown '\f' /* ASCII code for Page Down key */ |
#define chPageUp '\013' /* ASCII code for Page Up key */ |
#define chReturn '\n' /* ASCII code for Return character */ |
#define chRight '\035' /* ASCII code for right arrow */ |
#define chSpace ' ' /* ASCII code for Space character */ |
#define chTab '\t' /* ASCII code for Tab character */ |
#define chUp '\036' /* ASCII code for up arrow */ |
enum { kQDOriginal = 0, kQD8Bit, kQD32Bit }; /* For use with gQDVersion */ |
/*----------------------------------------------------------------------------------------- |
Types |
-----------------------------------------------------------------------------------------*/ |
typedef short *IntegerPtr, **IntegerHandle; |
typedef long *LongintPtr, **LongintHandle; |
typedef Boolean *BooleanPtr, **BooleanHandle; |
typedef Rect **RectHandle; |
struct WindowTemplate { /*template to a WIND resource*/ |
Rect boundsRect; |
short procID; |
Boolean visible; |
Boolean filler1; |
Boolean goAwayFlag; |
Boolean filler2; |
long refCon; |
Str255 title; |
}; |
typedef struct WindowTemplate WindowTemplate; |
typedef WindowTemplate *WindowTPtr, **WindowTHndl; |
typedef Rect (*PositionWndProcPtr)(WindowPtr window, WindowPtr relatedWindow); |
/*----------------------------------------------------------------------------------------- |
Handy Macros/inlines |
-----------------------------------------------------------------------------------------*/ |
#ifdef false /* The c++ stuff is turned OFF!!! */ |
inline long abs(val) |
{ return ((val < 0) ? (-val) : (val)); } /* Absolute value */ |
inline void PStrCopy(dest, src) /* Pascal string copy */ |
{ BlockMove (src, dest, (*(char *)(src))+1); } |
inline Point* TopLeft(Rect& r) /* provide access to rect.topLeft */ |
{ return (Point*)(&r.top); } |
inline Point* BotRight(Rect& r) /* provide access to rect.botRight */ |
{ return (Point*)(&r.bottom); } |
inline void SETPT(Point *pt,short h,short v) |
{ (*pt).h = h; (*pt).v = v); } |
inline void SETRECT(Rect *r,short left,short top,short right,short bottom) |
{ SETPT(TopLeft(*r), left, top); SETPT(BotRight(*r), right, bottom); } |
/* |
* Useful functions for testing gestalt attribute responses |
* |
* BTstBool returns a true boolean value (0 or 1), but is slower than: |
* BTstQ which simply returns a non-zero value if the bit is set which |
* means the result could get lost if assigned to a short, for example. |
* |
* arg is any integer value, bitnbr is the number of the bit to be tested. |
* bitnbr = 0 is the least significant bit. |
*/ |
inline short BTstBool(arg, bitnbr) |
{ return ((arg >> bitnbr) & 1); } |
inline long BTstQ(arg, bitnbr) |
{ return (arg & (1 << bitnbr)); } |
#else |
#ifndef THINK_C |
#define QD(whatever) (qd.##whatever) |
#else |
#define QD(whatever) (whatever) |
#endif |
/* define our own abs() so we don't need StdLib */ |
#define abs(val) (((val) < 0) ? (-(val)) : (val)) |
/* Pascal string copy */ |
#define PStrCopy(dest, src) (BlockMove (src, dest, (*(char *)(src))+1)) |
#define TopLeft(r) (* (Point *) &(r).top) |
#define BotRight(r) (* (Point *) &(r).bottom) |
#define MIN(a, b) ((a) < (b) ? (a) : (b) ) |
#define MAX(a, b) ((a) > (b) ? (a) : (b) ) |
#define SETPT(pt, x, y) (*(pt)).h = (x); (*(pt)).v = (y) |
#define SETRECT(r, left, top, right, bottom) \ |
SETPT(&TopLeft(*(r)), (left), (top)); \ |
SETPT(&BotRight(*(r)), (right), (bottom)) |
/* |
* Useful macros for testing gestalt attribute responses |
* |
* BTstBool returns a true boolean value (0 or 1), but is slower than: |
* BTstQ which simply returns a non-zero value if the bit is set which |
* means the result could get lost if assigned to a short, for example. |
* |
* arg is any integer value, bitnbr is the number of the bit to be tested. |
* bitnbr = 0 is the least significant bit. |
*/ |
#define BTstBool(arg, bitnbr) ((arg >> bitnbr) & 1) |
#define BTstQ(arg, bitnbr) (arg & (1 << bitnbr)) |
#endif |
/*----------------------------------------------------------------------------------------- |
Global variables |
-----------------------------------------------------------------------------------------*/ |
/* The following global variables are initialized by StardardInitialization to |
* define the environnment. This used to be a single SysEnvRec, but now, |
* all those variables defined in a SysEnvRec can be returned by Gestalt |
* (except sysVRefNum; see FindSysFolder). Note that all the variables |
* below will be correctly initialized whether Gestalt is available or not; |
* the Gestalt glue handles this. |
*/ |
extern short gMachineType; /* which machine this is */ |
extern short gSystemVersion; /* System version number */ |
extern short gProcessorType; /* which CPU this is */ |
extern Boolean gHasFPU; /* true if machine has an FPU */ |
extern short gQDVersion; /* major QD version #; 0 for original, |
1 for color QD, 2 for 32-bit QD */ |
extern short gKeyboardType; /* which type of keyboard is present */ |
extern short gAppleTalkVersion; /* AppleTalk version number */ |
/* These are also handled by Gestalt. gHasPMMU has no corresponding SysEnvRec |
* field, but it is handled by the glue, so we include it here for completeness. |
* gAUXVersion will be initialized with Gestalt if present, but correctly |
* set even if Gestalt is not available |
*/ |
extern Boolean gHasPMMU; /* true if machine has a PMMU or equivalent */ |
extern short gAUXVersion; /* major A/UX version number (0 if not present) */ |
/* |
* gHasWaitNextEvent is set to TRUE if the Macintosh we are running on has |
* WaitNextEvent implemented. We can use this in our main event loop to |
* determine whether to call WaitNextEvent or GetNextEvent. |
*/ |
extern Boolean gHasWaitNextEvent; |
/* |
* gAppResRef is the applicationÕs resource file reference. I need to save |
* this since I can open other resource files. The current resource file is |
* always gAppResRef unless I momentarily set it to another file to read its |
* resources, and then immediately restore it back. |
*/ |
extern short gAppResRef; |
/* |
* gInBackground is maintained by our osEvent handling routines. Any part of |
* the program can check it to find out if it is currently in the background. |
*/ |
extern Boolean gInBackground; /* maintained by StandardInitialization |
and DoEvent */ |
/* |
* gAppName holds the name of the application that's running. You can use if |
* for any purpose you'd like. It is also used by StandardAbout if it can't |
* find a string to use for the application name in a resource, so make sure |
* you call InitForStandardAbout if you are going to call StandardAbout. If you |
* call StandardInitialization, this is done for you. |
*/ |
extern Str255 gAppName; |
/* |
* gSignature holds the creator signature for the running application. It follows the |
* same rules as those for gAppName. |
*/ |
extern OSType gSignature; |
/* |
* Initial values of these global variables are set to zero or FALSE by MPW's |
* runtime initialization routines. If the Utilities initialization routines |
* have been properly called, then gUtilitiesInited will be true. If it is |
* not true, then the values of the above global variables are invalid. |
*/ |
extern Boolean gUtilitiesInited; |
/*----------------------------------------------------------------------------------------- |
Interface to routines |
-----------------------------------------------------------------------------------------*/ |
#ifdef __cplusplus |
extern "C" { |
#endif |
short CenteredAlert(short alertID, WindowPtr relWindow); |
/* Given an Alert ID and a related window pointer, this routine will center |
the alert on the same device as the related window. If the related |
window pointer is NULL, then the alert will be centered on the device |
that the alert would normally be placed if Alert was called directly. */ |
void CenterRectInRect(Rect outerRect, Rect *innerRect); |
/* Given two rectangles, this routine centers the second one within the first. */ |
Rect CenterWindow(WindowPtr window, WindowPtr relatedWindow); |
/* Given a window pointer and a related window pointer, this routine will |
center the window on the same device as the related window. If the |
related window pointer is NULL, then the window will be centered on the |
device that the window already is. |
WARNING: This routine may move or purge memory. */ |
void CloseAnyWindow(WindowPtr window); |
/* Closes the indicated window. Does the right thing, taking into account |
that the window may belong to a DA. |
WARNING: An application window is closed via a CloseWindow call. Use |
this call when you want to keep the storage for the window |
record. (Compare against DisposeAnyWindow.) */ |
void DisposeAnyWindow(WindowPtr window); |
/* Disposes of the indicated window. Does the right thing, taking into account |
that the window may belong to a DA. |
WARNING: An application window is closed via a DisposeWindow call. Use |
this call when you want to free up the storage for the window |
record. (Compare against CloseAnyWindow.) */ |
void DeathAlert(short errResID, short errStringIndex); |
/* Display an alert that tells the user an error occurred, then exit the |
program. This routine is used as an ultimate bail-out for serious errors |
that prohibit the continuation of the application. */ |
void DeathAlertMessage(short errResID, short errStringIndex, short message); |
void ErrorAlert(short errResID, short errStringIndex); |
void ErrorAlertMessage(short errResID, short errStringIndex, short message); |
OSErr FindSysFolder(short *foundVRefNum, long *foundDirID); |
/* FindSysFolder returns the (real) vRefNum, and the DirID of the current |
system folder. It uses the Folder Manager if present, otherwise |
it falls back to SysEnvirons. It returns zero on success, otherwise |
a standard system error. */ |
Handle GetAppIndResource(ResType theType, short index, OSErr *err); |
/* GetAppIndResource gets a resource from the application's res file by index */ |
Handle GetAppNamedResource(ResType theType, Str255 name, OSErr *err); |
/* GetAppNamedResource gets a resource from the application's res file by name */ |
Handle GetAppResource(ResType theType, short theID, OSErr *err); |
/* GetAppResource gets a resource from the application's res file by resource ID */ |
short GetAUXVersion( void); |
/* getAUXVersion -- Checks for the presence of A/UX by whatever means is |
appropriate. Returns the major version number of A/UX (i.e. 0 if A/UX |
is not present, 1 for any 1.x.x version 2 for any 2.x version, etc. |
This code should work for all past, present and future A/UX systems. */ |
DialogPtr GetCenteredDialog(short id, DialogPtr storage, WindowPtr relatedWindow, WindowPtr behind); |
/* Given a dialog ID and a related window pointer, this routine will center |
the dialog on the same device as the related window. If the related |
window pointer is NULL, then the dialog will be centered on the device |
that the dialog would normally be placed if GetNewDialog was called. */ |
WindowPtr GetCenteredWindow(short id, Ptr storage, WindowPtr relWindow, WindowPtr behind, Boolean inColor); |
/* Given a window ID and a related window pointer, this routine will center |
the window on the same device as the related window. If the related |
window pointer is NULL, then the window will be centered on the device |
that the window would normally be placed if GetNewWindow was called. */ |
Boolean GetCheckOrRadio(DialogPtr dlgPtr, short itemNo); |
long GetGestaltResult(OSType gestaltSelector); |
/* GetGestaltResult returns the result value from Gestalt for the specified |
selector. If Gestalt returned an error GetGestaltResult returns zero. Use |
of this function is only cool if we don't care whether Gestalt returned an |
error. In many casesyou may need to know the exact Gestalt error code so |
then this routine would be inappropriate. */ |
Point GetGlobalMouse(void); |
/* Returns the location of the mouse in local coordinates. It does this by |
calling OSEventAvail(). */ |
Point GetGlobalTopLeft(WindowPtr window); |
/* Given a window, this will return the top left point of the windowÕs port in |
global coordinates. Something this doesnÕt include, is the windowÕs drag |
region (or title bar). This returns the top left point of the windowÕs |
content area only. */ |
long GetKFreeSpace(short vRefNum); |
Rect GetMainScreenRect(void); |
GDHandle GetRectDevice(Rect globalRect); |
/* Find the greatest overlap device for the given global rectangle. */ |
Rect GetRectDeviceRect(Rect globalRect); |
/* Find the rect of the greatest overlap device for the given global rect. */ |
WindowPtr GetSomeKindOfWindow(PositionWndProcPtr whatKind, short windID, Ptr storage, WindowPtr relWindow, WindowPtr behind, Boolean inColor); |
/* Given a window positioning procedure pointer, a window ID and a window |
pointer the window relates to, this function open a new window by either |
a NewCWindow or a NewWindow call, depending on the value of inColor. The |
window will be opened invisible, independent of what the resource says. |
Once the window is opened successfully, the positioning procedure is |
called. The positioning procedure is passed a pointer to the just-opened |
invisible window and a pointer to the related window. It is up to the |
positioning procedure to move the invisible window to the correct location |
on the correct device. Once the positioning procedure returns, the window |
will be made visible if so indicated by the resource. */ |
WindowPtr GetStaggeredWindow(short id, Ptr storage, WindowPtr relWindow, WindowPtr behind, Boolean inColor); |
/* Given a window ID and a window pointer the window relates to, this function |
will stagger the windowÕs rectangle before showing it on the proper screen. |
This follows the Apple Human Interface Guidelines for where to place a |
staggered window on the screen. If the window is not closely associated |
with another window, pass a NULL for the window pointer of the related |
window. If you pass a NULL, the window is simply displayed where the |
resource would indicate. */ |
TrapType GetTrapType(short theTrap); |
/* Returns the type (OSType or ToolType) of the trap. It does this by checking |
the bits of the trap word. */ |
Rect GetWindowContentRect(WindowPtr window); |
/* Given a window pointer, return the global rectangle that encloses the |
content area of the window. */ |
short GetWindowCount(Boolean includeDAs, Boolean includeInvisibles); |
/* This procedure counts the number of windows in the application plane. You have the |
choices of also including DAs and invisible windows in this count. */ |
GDHandle GetWindowDevice(WindowPtr window); |
/* Find the greatest overlap device for the given window. */ |
Rect GetWindowDeviceRect(WindowPtr window); |
/* Given a window pointer, find the device that contains most of the window |
and return the device's bounding rectangle. */ |
Rect GetWindowDeviceRectNMB(WindowPtr window); |
/* Given a window pointer, find the device that contains most of the window |
and return the device's bounding rectangle. If this device is the main |
device, then remove the menubar area from the rectangle. */ |
Rect GetWindowStructureRect(WindowPtr window); |
/* This procedure is used to get the rectangle that surrounds the entire |
structure of a window. This is true whether or not the window is visible. |
If the window is visible, then it is a simple matter of using the bounding |
rectangle of the structure region. If the window is invisible, then the |
strucRgn is not correct. To make it correct, then window has to be moved |
way off the screen and then made visible. This generates a valid strucRgn, |
although it is valid for the position that is way off the screen. It still |
needs to be offset back into the original position. Once the bounding |
rectangle for the strucRgn is obtained, the window can then be hidden again |
and moved back to its correct location. Note that ShowHide is used, |
instead of ShowWindow and HideWindow. HideWindow can change the plane of |
the window. Also, ShowHide does not affect the hiliting of windows. */ |
void GlobalToLocalRect(Rect *aRect); |
void InitToolBox(void); |
void InitUtilities(void); |
/* This sets up some global variables for use by the utilities package. If you call |
StandardInitialization, you don't need to call this, as it will do it for you. */ |
Boolean IsAppWindow(WindowPtr window); |
/* Returns TRUE if the windowKind of the window is greater than or equal to |
userKind. If it is less, or the window is NIL, then return FALSE. */ |
Boolean IsDAWindow(WindowPtr window); |
/* Returns TRUE if the windowKind of the window is less than zero. If not, or |
the window is NIL, then return FALSE. */ |
void LocalToGlobalRect(Rect *aRect); |
char LockHandleHigh(Handle theHandle); |
/* Does a MoveHHi on the handle and then locks it. Also, the original state |
of the handle is returned, so you can keep it and set the handle back to it's |
original state with a HSetState call. */ |
short NumToolboxTraps(void); |
/* Determines the size of the Tool trap table. It does this by sampling a |
couple of trap locations and seeing which, if any are Unimplemented. */ |
void OutlineControl(ControlHandle button); |
void OutlineDialogItem(DialogPtr dlgPtr, short item); |
void PositionRectInRect(Rect outerRect, Rect *innerRect, Fixed horzRatio, Fixed vertRatio); |
/* Given two rectangles, this routine positions the second within the first one |
so that the it maintains the spacing specified the the horzRatio and vertRatio |
parameters. In other words, to center an inner rectangle hoizontally, but |
have its center be 1/3 from the top of the outer rectangle, call this |
routine with horzRatio = FixRatio(1, 2), vertRatio = FixRatio(1, 3). */ |
void PullApplicationToFront(void); |
void PStrConcat(Str255 targetStr, Str255 appendStr); |
/* Concatenate a Pascal string onto another. */ |
void SelectButton(ControlHandle button); |
/* Given the button control handle, this will cause the button to look as if it |
has been clicked in. This is nice to do for the user if they type return or |
enter to select the default item. */ |
void SetCheckOrRadioButton(DialogPtr dlgPtr, short itemNo, short state); |
Rect StaggerWindow(WindowPtr window, WindowPtr relatedWindow); |
/* This algorithm for staggering windows does quite a good job. It also is |
quite gnarly. Here's the deal: |
There are pre-designated positions that we will try when positioning a |
window. These slots will be tried from the upper-left corner towards the |
lower-right corner. If there are other windows in that slot, then we will |
consider that slot taken, and proceed to the next slot. A slot is |
determined to be taken by checking a point with a slop area. This slop |
area is diamond-shaped, not simply rectangular. If there is no other |
visible window with an upper-left corner within the slopt diamond, then |
we are allowed to position our window there. |
The above rule holds true unless this forces the window to be partly |
off the screen. If the window ends up partly off the screen, then we give |
up and just put it in the first slot. */ |
void StandardAbout(short appNameStringID); |
/* Shows a standard about box with the name of the application, its version |
number, a copyright notice, and DTS credits. Most of this information is |
taking from a standard DITL and the applicationÕs 'vers' resource. The name |
of the application is taken either from the 'STR ' resource passed in to |
this routine, or from GetAppParms() if that resource doesnÕt exist, or you |
pass in -1. */ |
void StandardInitialization(short callsToMoreMasters); |
/* Initializes ÒgInBackGroundÓ to FALSE. Makes the following InitXXX calls: |
InitGraf(), InitFonts(), InitWindows(), InitMenus(), TEInit(), |
InitDialogs(), InitCursor(). Brings application to front with 3 EventAvail |
calls. Calls SysEnvirons to initialize ÒgMacÓ. Calls TrapExists() to |
initialize ÒgHasWaitNextEventÓ. */ |
void StandardMenuSetup(short MBARID, short AppleMenuID); |
/* Installs and draws the menus indicated by 'MBAR'(MBARID). Adds DAÕs to the |
menu indicated by AppleMenuID by calling AddResMenu. If the menuBar cannot |
be created, the alert specified by rDeathAlert is displayed. */ |
void ToggleCheck(DialogPtr dlgPtr, short cChkItem); |
Boolean TrapExists(short theTrap); |
/* Returns TRUE if the trap exists (i.e., itÕs callable without getting DS |
error 12) */ |
void ZoomToWindowDevice(WindowPtr window, short maxWidth, short maxHeight, |
short zoomDir, Boolean front); |
#ifdef __cplusplus |
} |
#endif |
#endif |
Copyright © 2003 Apple Computer, Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2003-03-17