Deeper Dialog 2
Volume Number: | | 9
|
Issue Number: | | 6
|
Column Tag: | | Getting started
|
Related Info: Dialog Manager
Looking Deeper into the Dialog Manager
Part II
Digging into the Modeless Code
By Dave Mark, MacTech Magazine Regular Contributing Author
Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.
Last month, we entered the source code and created the resources for a program called Modeless. Modeless implemented a modeless version of the dialog box used by the Dialogger program of a few months back. As a reminder, heres another look at Modeless in action.
Running Modeless
Dig into your Development folder and open the folder named Modeless . Double-click on the file named Modeless.Π. Once THINK C starts up, select Run from the Project menu to compile and run Modeless.
When Modeless runs, the My Pet Fred window will appear, showing the picture we saved as PICT 128. Pull down the menu and verify that the first item reads About Modeless.... Select About Modeless... from the menu and check out the About alert. Click the OK button to dismiss the About alert.
Hold down the mouse in the File menu and verify that the S command-key equivalent appears next to the Settings... item. Select Settings.... The Settings... modal dialog box should appear (Figure 1).
Figure 1. The Settings... modeless dialog box.
Click on the My Pet Fred window, bringing it to the front and sending the modeless dialog to the back. Notice that the radio buttons are dimmed when the dialog is no longer the front-most window (Figure 2).
Figure 2. The radio buttons are dimmed when the dialog box is not in front.
Now type the command-key equivalent S to bring the Settings... dialog to the front again. Once again, the radio buttons should be enabled. Click on the Elephant radio button. Notice that the My Pet Fred window changes appropriately, leaving the Settings... dialog in front. Click on a few more radio buttons. While you are at it, Click on the File menu. Notice that the Settings... item has been dimmed. Though this doesnt help us much in this program, its important to be able to disable and enable certain menu items when a modeless dialog is in front.
When you are satisfied with your pet selection, drag the Settings... window to another part of your screen. Now click the close box. The Settings... window disappears. Select Settings... from the File menu. The Settings... window reappears at the position it was in when it disappeared and with the same radio button settings.
Finally, type the command-key equivalent Q to exit the program.
The Modeless Source Code
As usual, Modeless starts off with a series of #defines. The first three define the base resource ID, and the resource IDs for the ALRT and DLOG resources.
/* 1 */
#define kBaseResID 128
#define kAboutALRTid 129
#define kDialogResID 128
kVisible, kMoveToBack, kMoveToFront, and kNoGoAway are used in the calls to NewWindow() and GetNewDialog(). kSleep, as usual, is passed to WaitNextEvent().
/* 2 */
#define kVisible true
#define kMoveToBackNULL
#define kMoveToFront (WindowPtr)-1L
#define kNoGoAwayfalse
#define kSleep 60L
kOn and kOff are passed to SetCtlValue() to turn a radio button on and off.
/* 3 */
#define kOn 1
#define kOff0
These three #defines define the item IDs for the three radio buttons that appear in the modeless dialog.
/* 4 */
#define iAfghan 1
#define iElephant2
#define iSquirrel3
kLeftMargin and kTopMargin determine the position of the My Pet Fred window on the screen.
/* 5 */
#define kLeftMargin5
#define kTopMargin 40
kFirstRadio defines the ID of the first radio button in the modeless dialog. kLastRadio defines the ID of the last radio button in the set.
/* 6 */
#define kFirstRadio1
#define kLastRadio 3
The remainder of the #defines represent the Modeless menus and menu items.
/* 7 */
#define mApple kBaseResID
#define iAbout 1
#define mFile kBaseResID+1
#define iSettings1
#define iQuit 3
Modeless makes use of four global variables. gDone is set to true until the program is ready to exit. gCurrentPICT contains the ID of the current My Pet Fred PICT. gSettingsDLOG is a pointer to the modeless dialog. We made this a global so we could keep the modeless dialog settings around, even if we close the dialog. gFredWindow points to the My Pet Fred window. Well take advantage of this pointer when we delete the My Pet Fred window and create a new one.
/* 8 */
Boolean gDone;
short gCurrentPICT = kBaseResID;
DialogPtr gSettingsDLOG = NULL;
WindowPtr gFredWindow = NULL;
As always, we created a function prototype for each of the Modeless functions.
/* 9 */
void ToolBoxInit( void );
PicHandle LoadPICT( short picID );
void CreateWindow( void );
void MenuBarInit( void );
void EventLoop( void );
void DoEvent( EventRecord *eventPtr );
void DoDialogEvent( EventRecord *eventPtr );
void HandleMouseDown( EventRecord *eventPtr );
void HandleMenuChoice( long menuChoice );
void HandleAppleChoice( short item );
void HandleFileChoice( short item );
void DoUpdate( EventRecord *eventPtr );
void CreateDialog( void );
void FlipControl( ControlHandle control );
void SwitchPICT( void );
main() starts off by initializing the Toolbox. Next, the menu bar is set up and the My Pet Fred window is created. Finally, the main event loop is entered.
/* 10 */
/********** main **********/
void main( void )
{
ToolBoxInit();
MenuBarInit();
CreateWindow();
EventLoop();
}
Nothing new about ToolBoxInit().
/* 11 */
/********** ToolBoxInit **********/
void ToolBoxInit( void )
{
InitGraf( &thePort );
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs( NULL );
InitCursor();
}
Just like its Dialogger counterpart, LoadPICT() takes a resource ID as an input parameter, loads the specified PICT resource, then returns a handle to the PICT.
/* 12 */
/********** LoadPICT **********/
PicHandle LoadPICT( short picID )
{
PicHandlepic;
pic = GetPicture( picID );
If the PICT could not be loaded for some reason, the program beeps once, then exits.
/* 13 */
if ( pic == NULL )
{
SysBeep( 10 ); /* Couldnt load the PICT resource!!! */
ExitToShell();
}
return( pic );
}
CreateWindow() creates a new My Pet Fred window.
/* 14 */
/********** CreateWindow **********/
void CreateWindow( void )
{
PicHandlepic;
Rect r;
First, LoadPICT() is called to load the PICT specified by gCurrentPICT.
/* 15 */
pic = LoadPICT( gCurrentPICT );
Next, the PICTs bounding rectangle is stored in the local variable r.
/* 16 */
r = (**pic).picFrame;
OffsetRect() is called to normalize the Rect, keeping it the same size as the PICT, but moving its upper left corner to the position specified by kLeftMargin and kTopMargin. Basically, were setting up the bounding rectangle for the new My Pet Fred window.
/* 17 */
OffsetRect( &r, kLeftMargin - r.left,
kTopMargin - r.top );
This rectangle is passed to NewWindow(). The new window is made visible. Notice that kMoveToBack is passed instead of our normal kMoveToFront. Why? We want the window to appear behind the modeless dialog window, if the dialog is currently visible.
/* 18 */
gFredWindow = NewWindow( NULL, &r, \pMy Pet Fred,
kVisible, noGrowDocProc, kMoveToBack, kNoGoAway, 0L );
If the window couldnt be created for some reason, beep once, then exit.
/* 19 */
if ( gFredWindow == NULL )
{
SysBeep( 10 ); /* Couldnt load the WIND resource!!! */
ExitToShell();
}
Finally, make the window visible (this line is unnecessary since we created the window with kVisible, but its a good habit to get into) and make it the current port. Well draw the current Fred by responding to an update event.
/* 20 */
ShowWindow( gFredWindow );
SetPort( gFredWindow );
}
MenuBarInit() loads the MBAR resource, and makes it the current menu bar.
/* 21 */
/********** MenuBarInit **********/
void MenuBarInit( void )
{
Handle menuBar;
MenuHandle menu;
menuBar = GetNewMBar( kBaseResID );
SetMenuBar( menuBar );
Next, a handle to the menu is retrieved and the desk accessories added to the menu.
/* 22 */
menu = GetMHandle( mApple );
AddResMenu( menu, DRVR );
Finally, the menu bar is redrawn.
/* 23 */
DrawMenuBar();
}
EventLoop() looks much the same. As youd expect, the program exits when gDone is set to true.
/* 24 */
/********** EventLoop **********/
void EventLoop( void )
{
EventRecordevent;
gDone = false;
while ( gDone == false )
{
if ( WaitNextEvent( everyEvent, &event, kSleep, NULL ) )
DoEvent( &event );
}
}
DoEvent() is slightly different than previous incarnations.
/* 25 */
/********** DoEvent **********/
void DoEvent( EventRecord *eventPtr )
{
char theChar;
The first difference lies in our call of IsDialogEvent(). IsDialogEvent() takes a pointer to an EventRecord as a parameter and returns true if the event is associated with a modeless dialog. Note that our code calls IsDialogEvent() whether or not a modeless dialog is currently open. Since we arent that concerned with efficiency here, this is just fine. In a more complex program, you might want to check to see if any of your modeless dialogs are open before you call IsDialogEvent(). Obviously, if your program contains no modeless dialogs, you shouldnt call IsDialogEvent().
/* 26 */
if ( IsDialogEvent( eventPtr ) )
{
If IsDialogEvent() returns true, the event is associated with our modeless dialog box and well pass it along to DoDialogEvent() for processing.
/* 27 */
DoDialogEvent( eventPtr );
}
If the event is not associated with a modeless dialog, well process the event as we always did, via a switch statement.
/* 28 */
else
{
switch ( eventPtr->what )
{
A mouseDown is handled by HandleMouseDown().
/* 29 */
case mouseDown:
HandleMouseDown( eventPtr );
break;
keyDown and autoKey events are turned into characters and turned from command-key equivalences (if appropriate) into menu selections by MenuKey(). The menu selections are handled by HandleMenuChoice().
/* 30 */
case keyDown:
case autoKey:
theChar = eventPtr->message & charCodeMask;
if ( (eventPtr->modifiers & cmdKey) != 0 )
HandleMenuChoice( MenuKey( theChar ) );
break;
updateEvts are handled by DoUpdate(). Since the update events for our modeless dialog will have been diverted to DoDialogEvent(), any updateEvts passed to DoUpdate() will be for the My Pet Fred window.
/* 31 */
case updateEvt:
DoUpdate( eventPtr );
break;
}
}
}
All events for the modeless dialog are passed to DoDialogEvent().
/* 32 */
/********** DoDialogEvent **********/
void DoDialogEvent( EventRecord *eventPtr )
{
short itemHit;
short itemType;
Handle itemHandle;
Rect itemRect;
short curRadioButton, i;
char theChar;
BooleanbecomingActive;
MenuHandle menu;
DialogPtrdialog;
Well start off by fetching a handle to the File menu. Why? Were going to dim the Settings... item if the modeless dialog is up front. Remember, were doing this just to demonstrate how its done, not because its needed.
/* 33 */
menu = GetMHandle( mFile );
Notice that we process keyDown and autoKey events in two different places. If the modeless dialog is up front, DoDialogEvent() will get all keyDowns and autoKeys. If the modeless dialog is not up front, or is not open, the normal event handling mechanism will get the keyDowns and autoKeys.
/* 34 */
switch ( eventPtr->what )
{
case keyDown:
case autoKey:
theChar = eventPtr->message & charCodeMask;
if ( (eventPtr->modifiers & cmdKey) != 0 )
HandleMenuChoice( MenuKey( theChar ) );
break;
If the modeless dialog window is either being activated or deactivated, DoDialogEvent() will get an activateEvt. In that case, well use the activeFlag to determine whether becomingActive should be set to true or false.
/* 35 */
case activateEvt:
becomingActive = ( (eventPtr->modifiers & activeFlag)
== activeFlag );
If the modeless dialog window is becoming active, well use HiliteControl() to enable all the radio buttons, from kFirstRadio to kLastRadio, then well disable the File menus Settings... item.
/* 36 */
if ( becomingActive )
{
for ( i=kFirstRadio; i<=kLastRadio; i++ )
{
GetDItem( gSettingsDLOG, i, &itemType,
&itemHandle, &itemRect );
HiliteControl( (ControlHandle)itemHandle, 0 );
}
DisableItem( menu, iSettings );
}
If the modeless dialog window is being deactivated, well dim all the radio buttons and enable the Settings... item. When the user goes to the File menu and sees that Settings... is dimmed, theyll have a clue that the modeless dialog is already up front and ready to use.
/* 37 */
else
{
for ( i=kFirstRadio; i<=kLastRadio; i++ )
{
GetDItem( gSettingsDLOG, i, &itemType,
&itemHandle, &itemRect );
HiliteControl( (ControlHandle)itemHandle, 255 );
}
EnableItem( menu, iSettings );
}
break;
}
The previous chunk of code accomplished two things. First, it made sure that command-key equivalents were supported. Second, it made any user interface adjustments that were not normally handled by the Dialog Manager. We decided to dim the radio buttons when the modeless window is deactivated and dim the Settings... item when the modeless window is activated. These user interface adjustments are window trimmings that we decided to add. The program would still work without them.
Next, were going to the things that absolutely must be done. DialogSelect() is the modeless version of ModalDialog(). DialogSelect() takes the event pointer and maps it to a specific dialog and a specific item in the dialog. DialogSelect() returns true if we need to do some processing (if an item was actually hit).
/* 38 */
if ( DialogSelect( eventPtr, &dialog, &itemHit ) )
{
Since our dialog was relatively simple, we know that itemHit is going to be one of iAfghan, iElephant, or iSquirrel.
/* 39 */
switch ( itemHit )
{
case iAfghan:
case iElephant:
case iSquirrel:
Before we process the radio button click, well first calculate which radio button should be currently lit.
/* 40 */
curRadioButton = gCurrentPICT -
kBaseResID + kFirstRadio;
If the button that was clicked in is not the current radio button, weve got some work to do.
/* 41 */
if ( curRadioButton != itemHit )
{
First, well turn off the current radio button.
/* 42 */
GetDItem( dialog, curRadioButton, &itemType,
&itemHandle, &itemRect );
FlipControl( (ControlHandle)itemHandle );
Next, well turn on the radio button that was just clicked. Remember, always turn off a radio button before you turn on a new one.
/* 43 */
GetDItem( dialog, itemHit, &itemType,
&itemHandle, &itemRect );
FlipControl( (ControlHandle)itemHandle );
Next, update curRadioButton to reflect the newly clicked radio button.
/* 44 */
curRadioButton = itemHit;
Next we check to see if the current PICT is still up to date.
/* 45 */
if ( gCurrentPICT != curRadioButton +
kBaseResID - kFirstRadio )
{
If not, well set it to its new value, then call SwitchPICT() to update the My Pet Fred window.
/* 46 */
gCurrentPICT = curRadioButton +
kBaseResID - kFirstRadio;
SwitchPICT();
}
}
break;
}
}
}
HandleMouseDown() works much the same as always.
/* 47 */
/********** HandleMouseDown **********/
void HandleMouseDown( EventRecord *eventPtr )
{
WindowPtrwindow;
short thePart;
long menuChoice;
GrafPtroldPort;
long windSize;
Rect growRect;
MenuHandle menu;
First, we call FindWindow() to find out what window the mouseDown was in and where in the window the mouseDown occurred.
/* 48 */
thePart = FindWindow( eventPtr->where, &window );
If the mouseDown was in the menu bar, pass the menu selection on to HandleMenuChoice(). A mouseDown in inSysWindow gets passed on to SystemClick().
/* 49 */
switch ( thePart )
{
case inMenuBar:
menuChoice = MenuSelect( eventPtr->where );
HandleMenuChoice( menuChoice );
break;
case inSysWindow :
SystemClick( eventPtr, window );
break;
A mouseDown inContent causes a call to SelectWindow() to bring the clicked-in window to the front.
/* 50 */
case inContent:
SelectWindow( window );
break;
Note that this line will get executed even if the mouse click was in the modeless dialog, but only if the modeless dialog was in the back when it was clicked in. Want to prove this? Try adding this line after the call of SelectWindow() but before the break:
/* 51 */
if ( window == gSettingsDLOG ) SysBeep( 20 );
If the mouseDown was inDrag, call DragWindow() to drag the window around on the screen.
/* 52 */
case inDrag :
DragWindow( window, eventPtr->where,
&screenBits.bounds );
break;
This next case is interesting. If the mouseDown was inGoAway, call TrackGoAway() to ensure that the mouse button was released inside the close box.
/* 53 */
case inGoAway:
if ( TrackGoAway( window, eventPtr->where ) )
If so, verify that the click was in the modeless dialogs close box (the only window with a close box, by the way).
/* 54 */
if ( window == gSettingsDLOG )
{
If so, make the modeless dialog window invisible. Why not close the window? We want to keep the dialog around so if the user brings it back up, it will have the same settings and will be in the same position, without us having to keep track of all the stuff.
/* 55 */
HideWindow( window );
Once the window is hidden, well enable the File menus Settings... item.
/* 56 */
menu = GetMHandle( mFile );
EnableItem( menu, iSettings );
}
break;
}
}
HandleMenuChoice() does what it always has, dispatching menu selections to the and File menus.
/* 57 */
/********** HandleMenuChoice **********/
void HandleMenuChoice( long menuChoice )
{
short menu;
short item;
if ( menuChoice != 0 )
{
menu = HiWord( menuChoice );
item = LoWord( menuChoice );
switch ( menu )
{
case mApple:
HandleAppleChoice( item );
break;
case mFile:
HandleFileChoice( item );
break;
}
HiliteMenu( 0 );
}
}
HandleAppleChoice() puts up an alert if the first item on the menu was selected. An alert is like a dialog, but is not interactive (other than dismissing it). The alert comes up and is then dismissed, usually by a button click. Read the section on alerts in Inside Macintosh. Alerts are not complicated.
/* 58 */
/********** HandleAppleChoice **********/
void HandleAppleChoice( short item )
{
MenuHandle appleMenu;
Str255 accName;
short accNumber;
switch ( item )
{
case iAbout:
NoteAlert( kAboutALRTid, NULL );
break;
default:
appleMenu = GetMHandle( mApple );
GetItem( appleMenu, item, accName );
accNumber = OpenDeskAcc( accName );
break;
}
}
HandleFileChoice() handles the two items in the File menu.
/* 59 */
/********** HandleFileChoice **********/
void HandleFileChoice( short item )
{
Ooops! The variable newPICTid was declared and never used. Sorry about that...
/* 60 */
short newPICTid;
If Settings... was selected, we first check to see if the modeless dialog was created yet. If not, we create it by calling CreateDialog().
/* 61 */
switch ( item )
{
case iSettings:
if ( gSettingsDLOG == NULL )
CreateDialog();
If the dialog does exist, we make it visible and bring it to the front. How does the Settings... item get dimmed, you might ask. When the dialog is brought to the front, an activateEvt gets posted. The activateEvt handling code takes care of that.
/* 62 */
else
{
ShowWindow( gSettingsDLOG );
SelectWindow( gSettingsDLOG );
}
break;
As always, when Quit is selected, we set gDone to true and drop out of the program.
/* 63 */
case iQuit:
gDone = true;
break;
}
}
Since events for the modeless dialog are handled elsewhere, the only update event this code will see is for the My Pet Fred window.
/* 64 */
/********** DoUpdate **********/
void DoUpdate( EventRecord *eventPtr )
{
PicHandlepic;
WindowPtrwindow;
Rect r;
Well retrieve the WindowPtr from eventPtr->message and load the current Fred PICT using LoadPICT.
/* 65 */
window = (WindowPtr)eventPtr->message;
pic = LoadPICT( gCurrentPICT );
Next, we make the window the current port, call BeginUpdate(), then draw the newest version of Fred and call EndUpdate().
/* 66 */
SetPort( window );
BeginUpdate( window );
r = window->portRect;
DrawPicture( pic, &r );
EndUpdate( window );
}
Just as wed do with a modal dialog, we load the modeless DLOG resource by calling GetNewDialog().
/* 67 */
/********** CreateDialog **********/
void CreateDialog( void )
{
short itemType;
Handle itemHandle;
Rect itemRect;
short curRadioButton;
gSettingsDLOG = GetNewDialog( kDialogResID,
NULL, kMoveToFront );
If the DLOG couldnt be loaded, beep once then exit.
/* 68 */
if ( gSettingsDLOG == NULL )
{
SysBeep( 10 ); /* Couldnt load the DLOG resource!!! */
ExitToShell();
}
Once the DLOG is loaded, make the dialog window visible and the current port.
/* 69 */
ShowWindow( gSettingsDLOG );
SetPort( gSettingsDLOG );
Next, turn the current radio button on.
/* 70 */
curRadioButton = gCurrentPICT - kBaseResID + kFirstRadio;
GetDItem( gSettingsDLOG, curRadioButton, &itemType,
&itemHandle, &itemRect );
SetCtlValue( (ControlHandle)itemHandle, kOn );
}
FlipControl() turns a radio button or check box thats on, off and one thats off, on.
/* 71 */
/********** FlipControl **********/
void FlipControl( ControlHandle control )
{
SetCtlValue( control, ! GetCtlValue( control ) );
}
SwitchPICT() calls DisposeWindow() to free up the memory used by the specified window (this closes the window as well) and then calls CreateWindow() to create a My Pet Fred window that reflects or most current choice of pet.
/* 72 */
/********** SwitchPICT **********/
void SwitchPICT( void )
{
DisposeWindow( gFredWindow );
CreateWindow();
}
Till Next Time...
Well, thats about it for modeless dialogs. Be sure to read the Inside Macintosh chapters that pertain to dialogs and alerts. Next month, well spend some time with a filterProc, a procedure that you provide to the Toolbox, that the Toolbox calls for you. You can read about filterProcs in Inside Macintosh, in the description of the Dialog Manager routine ModalDialog().
By the way, have you gotten a copy of THINK Reference 2.0 yet? If you dont want to spend the money on the first six volumes of Inside Macintosh, the new THINK Reference fills the bill pretty nicely. THINK Reference 2.0 is definitely my Product of the Month...
[For those of you who dont know, THINK Reference 2.0 is included FREE on the All of MacTech Magazine CD-ROM, Volumes I-VIII. With this CD, you can have all of Inside Macintosh and every issue of MacTech Magazine and MacTutor online and searchable.
- Ed.]