DA Philosophy
Volume Number: | | 2
|
Issue Number: | | 6
|
Column Tag: | | Programmer's Forum
|
Philosophy of c Programming
By David Dunham, Maitreya Design
We are grateful to have this article from David Dunham, best known for his desk accessory DiskInfo, now in version 1.41. In this article, he shares some of his experiences in writing a first class DA. -Ed.
Introduction
Desk accessories (DAs) are in many ways one of the best design features of the Macintosh. Not only did Apple provide a clean way to handle them (unlike theincompatibilities between DAs under MSDOS), theyre currently the only way the average user is going to multitask.
In my opinion, desk accessories are really no different from applications. Examples of desk accessories which do the job of applications are MockWrite, ClickOn Worksheet, and Acta. One developer wondered why everything on the Mac couldnt be a DA. Theres really no reason, except that the Mac architecture implements them as drivers, and the unit table is limited to 32 entries. So were stuck.
Although in one sense writing a desk accessory should be no different than writing an application (Acta started out life as an application, and was easy to convert), there are some differences, mainly because desk accessories are the guests of an application. Ill discuss implementing DAs at a fairly abstract level. Plenty of detailed articles on desk accessories have already been published. See the Oct 85, Nov 85, Jan 86, Feb 86, Mar 86, or Apr 86 issues of MacTutor or the Oct 85 issue of MacUser for complete listings. Ill talk about what Ive learned writing the DAs DiskInfo, FileInfo, and Acta.
Edit Menu
An accessory that manipulates data almost certainly needs to support the Edit menu. But if you use the Edit menu, youre confronted with the fact that many applications dont include the keyboard equivalents to the standard commands. In fact, ThinkTank doesnt even provide an Undo menu item at all! This means that youll have to handle the standard equivalents (e.g. Command-Z for Undo).
EventRecord *ep;
/* This code is necessary because */
/* MenuKey() won't check for Edit menu */
case keyDown:
case autoKey:
c = (word)(ep->message & 255); /* Mask for low byte */
if (ep->modifiers & cmdKey) { /* Pretzel key , menu item*/
switch (c) {
case 'Z':
case 'z':
/* You may want to check for option-equivalents, too */
undo_cmd();
break;
case 'X':
case 'x':
cut_cmd();
break;
Note that this causes a localizing problem, since non-English systems may use different keyboard equivalents (the leftmost four keys on the bottom row are still used).
If at all appropriate, include Undo! I dont consider anything a true Mac program without it. And it impresses people. When Guy Kawasaki of Apple first saw Acta, he exclaimed, You have Undo in a desk accessory?! Having Undo is impressive because desk accessories are often considered poor cousins of applications. But ClickOn Worksheet provides more features than Multiplan, and Actas application equivalent lacks Undo.
Goodbye Kisses
Any intelligent application asks the user to save his work before quitting. Since desk accessories dont have access to the File menu, it isnt quite as easy to implement this feature. Luckily, Apple provided the goodbye kiss, a special call to your accessory before the heap is reinitialized. This is your way of knowing that the user quit the application, and is the time to remind him about unsaved changes. Users tend to get unhappy if they lose data, even if its because they didnt quit in the proper way.
When I was trying to implement this feature, I couldnt find a single DA that had it! (Ive since learned that ClickOn Worksheet [which by now you can tell I admire greatly] does field goodbye kisses.) In fact, since I couldnt get it to work, and since I couldnt determine that it worked anywhere else, I was convinced that it didnt work at all. It does. You do need to return via JIODone, which may be difficult in a high-level language. Mike Schusters article in the April MacTutor had some clever glue to handle this. I did it with inline code:
/* Pbp is a global pointer to the parameter block */
/* restore() restores registers */
if (Pbp->u.cp.csCode < 0) { /* Goodbye kiss */
close_window(); /* Close it NOW */
restore(); /* Since above affects A0/A1 */
close(); /* Exactly same as close box */
#asm
move.l Dp_,A1 ; restore DCE pointer
move.w #0,D0 ; Return code
movem.l(SP)+,.registers ; normally done in a return
unlk A6
move.l JIODone,-(SP); Goto IODone
rts
#endasm
}
I found that I had to close the DA window first, presumably since I was putting up an SFPutFile() dialog and thus getting reentrant calls. However, at the time of a goodbye kiss, your window may be gone already; programs like MacWrite close all windows before quitting (but dont close the desk accessory associated with a window ). Heres a routine to close your window only if its still there; I found this attributed to Mike Schuster:
/*************************************************** */
/* */
/* CLOSE_WINDOW - Close our window, if it's there. */
/* Note: Dp is the global DCE pointer */
/* */
/*************************************************** */
close_window() {
WindowPeek w;
/* Make sure window's still there before getting rid of it. */
/* It may be gone, because applications like MacWrite */
/* close all open windows without regard to */
/* what they are. */
/* Start at beginning of window list */
w = FrontWindow();
/* Look for our window */
while (w && w != Dp->dCtlWindow)
w = w->nextWindow;
/* If we found it, get rid of it */
if (w)
CloseWindow(w);
Dp->dCtlWindow = 0;
}
Files
Your DA can create, delete, and rename files, even from the Finder. The newer Finders handle these changes properly. All you have to do is call FlushVol() after making any changes. This signals the Finder to update the desktop (and its something you should do anyway after altering a disk).
There are a few things that you shouldnt do from the Finder. These include changing the FinderInfo of a file, including its type and creator. Apparently the Finder keeps those in memory, and doesnt update its copy if a DA changes them. If it then writes desktop information before launching an application, it overwrites what the DA did with its original copy.
If your DA uses a resource file to store information (like the Scrapbook File), you should open it on bootDrive (the global at $210). Despite its name, this is the vRefNum or WDRefNum where the Finder is located. In other words, the System Folder (usually).
If you want your DAs files to have distinctive icons, youll have to figure out a way to get the bundle into the Desktop file. Its best to put the bundle in a support program, such as an installer or configurer. This should be less confusing than having the user copy a special file to a disk, then delete it.
Menus
If youre going to use more than one menu, they wont fit. Youll have to change the entire menu bar in order to guarantee enough space.
In fact, the easiest way for the menu bar to run out of room is to use DAs that consist of just a menu. Several of these can swamp an application with many menus. So be sure the world needs another menu-only DA before you write one.
The big problem with menus is that your DA may have enough functions to require more than one. At least the current System has scrolling menus but if there are more than 19 items, your user might not realize there are any down below (this is where Apple really screwed up there was another implementation of scrolling menus that, while buggy, gave a visual indication of extra items).
Because a few applications dont handle highlighting DA menus properly, you should call HiliteMenu(0) after handling an accMenu call.
Zooming
A nice feature to provide is the capability for the user to expand a window to its maximum size. The fairly common practice of double-clicking the title bar wont work with a DA, because the DA never sees title bar events (the Desk Manager handles things like TrackGoAway() and DragWindow()). With the new ROMs, Apple came up with a standard way of enlarging a window to its maximum size: the zoom box. Luckily, a mouseDown in the zoom box can be detected by a DA. Its not that simple though, because FindWindow(), which applications can use to determine the logical position of a click, always returns inSysWindow. However, the mouseDown will have a position outside the portRect of your window, so its easy to identify.
You could try to keep track of the zoom state yourself, but this wont work, because the window manager recognizes when the user drags and resizes a window into its zoomed size. The correct method is to call the WDEF and let it tell you where the hit is.
By the way, you dont need to worry about whether youre running on the new ROMs or not, because the WDEF wont even draw the zoom box under the 64K ROMs.
/*************************************************** */
/*
*/
/* This is a fragment from the event-handling code */
/* to illustrate the two ways of resizing a window. */
/* None of these shenanigans are necessary for */
/* applications, since they can use FindWindow(). */
/*
*/
/*************************************************** */
typedef int (*PROCPTR)();
EventRecord *ep;
register word c;
WindowPtr window;
Point pt;
Rect r;
long size;
window = Dp->dCtlWindow;
case mouseDown:/* FindWindow() returns inSysWindow */
pt = ep->where; /* Keep a copy in global coordinates */
GlobalToLocal(&ep->where);
if (ep->where.v < 0) {
/* In no-man's land, so must be in zoom box; */
/* call WDEF for details */
c = (**(PROCPTR *)
(((WindowPeek)window)->windowDefProc))(8,
window,wHit,pass(pt));
if (TrackBox(window,pass(pt),c)) {
ZoomWindow(window,c,FALSE);
resize_window(); /* Readjust data structures */
}
break;
}
/* See if it's inGrowIcon */
r = window->portRect;
r.top = r.bottom - 15;
r.left = r.right - 15;
if (PtInRect(pass(ep->where),&r)) {
SetRect(&r,160,164,32767,32767);
size = GrowWindow(window,pass(pt),&r);
SizeWindow(window,(word)size & 0xFFFF,
HiWord(size),FALSE);
resize_window();/* Readjust data structures */
break;
}
Multiple windows
I havent written any DAs that let the user work with multiple windows; if I use a second window, its always a modal dialog. Why? Well, theres no problem using multiple windows. You do have to set windowKind in all of them, so the system can identify them as belonging to your desk accessory. This means that if any of them have a close box, the DA gets the close message when the user clicks it! This is apparently why MacLightning has a nonstandard close icon. Of course, they could have done what ClickOn Worksheet does, and include a menu item to close the second window.
Professor Mac (Steve Brecher) reports that there is a global called CloseOrnHook at $A88. If it contains a non-zero value, _SystemClick will assume it is the address of a subroutine to be called whan a DAs close box is clicked. It calls the subroutine instead of closing the DA. On entry to the routine, A1 contains the DAs DCE address and A4 contains the window pointer. He suggests implementing multiple windows as follows: on an activate of one of your windows, save the contents of CloseOrnHook and put a pointer to your own routine there. On a deactivate, restore the previous value. Your routine would close the window or the driver as appropriate. The routine must be non-relocateable while its address is in CloseOrnHook.
CloseOrnHook is not in the Inside Macintosh index; if any reader knows where this is documented, please let us know. I received this information just before press time and havent had the chance to try it yet.
Segmentation
Its possible to segment a desk accessory, which allows you to get around the 8K limit Apple suggests. Unfortunately, you cant use the segment loader. This means you cant freely call routines without worrying about which segment theyre in. But as long as you group routines appropriately, this shouldnt present a problem (although you may have to duplicate some of the common routines in each segment). You can call a segment from another segment, if you need to.
The idea behind segmentation on the Macintosh is that code is just another resource. The segment loader assumes its in CODE resources. You can choose any name; I use PROC. As long as the entry point is at the beginning of the resource, its easy to call:
/*********************************************** */
/*
*/
/* This fragment illustrates calling an overlay */
/*
*/
/*********************************************** */
typedef int (*PROCPTR)();
h = GetResource('PROC',drvr_rsrc); /* handle to PROC */
if (h == 0L) { /* Something's wrong (can't load) */
SysBeep(32); /* Let somebody know */
return;/* Don't try to call it! */
}
HLock(h); /* Hold down the PROC */
(**(PROCPTR *)h)(dp,drvr_rsrc,title); /* initialize dp,...,title */
HUnlock(h); /* Let it float in the heap again */
Here are the commands in my makefile to compile this segment. Temporary files are written to a RAMdisk, and the PROC ends up copied into a file with other resources for the DA.
init: init.c write.h
cc -tabu init.c -o memory:init.asm
as memory:init.asm -o memory:init.o
ln -t memory:init.o -o memory:init -lc
rm memory:init.o
rgen init.r
cprsrc -f PROC -15392 init /resource_file
Heres the file init.r (used by RGen, Manxs improved version of RMaker):
* Resource file for Init code
init
PROC@drd
type PROC
,-15392 (32)
memory:init
Globals vs private store
Writing in C, it seems slightly more efficient to use globals than go through a handle at dCtlStorage to get to your variables. Youll probably need a global to get to the DCE stuff anyway, so you might as well go all the way. This does mean that your variables are in the same place as your code, and thus you need one big block of memory rather than two smaller ones.
Development environment
Despite I-444 of Inside Macintosh, desk accessories are usually not written in assembly language at least at Maitreya Design. I use C exclusively. And I dont have a Lisa.
Development environments are a matter of preference. The main consideration in developing DAs is that you dont want to have to install them into the System file. That would make the development cycle incredibly slow. I develop with the editor QUED on a RAMdisk, and simply install the DRVR into QUED (with cprsrc -f DRVR 31 acta memory:QUED). This is very handy, since I know Ill have to use the editor anyway after trying out some changes.
Its also possible to create a Font/DA Mover file and open it with DA Key (Lofty Beckers shareware FKEY, easily worth its $5 asking price), but this makes the DA modal, and harder to debug. If you prefer, you can use Beckers Other DA (which is the same thing, implemented as a DA), but I cant spare the DRVR space for that.
I used to use MDS Edit as my editor, and installed into it. This uncovered a bug in the way Edit handles the clipboard. If you write a private scrap type, as well as TEXT, Edit will delete your format from the clipboard, leaving the TEXT intact. If you write only your own type, Edit leaves it alone. Apparently it really likes TEXT scraps, and will do anything to keep them pure. I know of no workaround to this problem (short of using QUED).
To save time in development, a desk accessory that uses resources should have an OpenResFile() call at the beginning to open a separate resource file. This means you wont have to copy resources which are essentially static during the development process. When you finish the DA, its a simple matter to copy the DRVR into the resource file and change its type and creator to DFIL DMOV so it can be opened by the Font/DA Mover.
Debugging
ResEdit is a harsh environment to try your DA in because of the magic things it does with resource files and the order in which theyre searched. Ive also been told that MDS Edit is a harsh environment for DAs, but I havent seen why except for the clipboard bug. Many Microsoft programs manage memory poorly, and are an ideal place to make sure your DA can live with a small heap. Of course, you have to figure out which bugs you uncover are yours, and which are Microsofts (Word, for example, doesnt handle menus well).
All the usual debugging techniques apply, like using Discipline and Heap Scramble from TMON.
Installer
Its definitely not worth writing your own installer, in my opinion. Theres no need to reinvent the wheel. According to people whove written them, theyre a pain (this should be easy to verify by observing the many revisions to Apples Font/DA Mover). The only reason to write your own installer is if your desk accessory is something else masquerading behind a desk accessory interface (like Tempo) and has resources which cant be numbered as owned (such as INITs).
Copy protection
Yes, you can protect a DA. But dont.
Pitfalls
One of the most annoying things Apples done is to reduce the number of DRVR slots available to desk accessories. Font/DA Mover enforces the restriction of not installing more than 15 DAs (its possible to install up to 20 using ResEdit, but this option isnt available to the average user). This suggests one of two conclusions: make your DA either modal, or versatile. Modal, because if a user runs a DA via DA Key, she wont be able to get at the main application until she closes the DA. Versatile, because it doesnt make sense to have a DA that renames files, another one to delete files, and a third to set file attributes. DA slots are too scarce to squander that way, and if you write DAs like that, nobody will want to install them. Of course, you have to watch out for creeping featurism.
Remember that, if youre given a close call, you must close. The close may have been issued by the Finder, closing all open DAs before launching an application. Theres no way a DA can put up a Cancel button for that!
If you write in a high-level language, being called from the ROM may present a problem. This usually happens in cases like a TextEdit clikLoop or a Standard File filterProc. The problem is that register A4 wont point to your globals. This may not be a real problem in the DRVR, but a segment has no way of determining the correct value of the global base. The inline assembly feature of Aztec C saved me; I simply added instructions to save A4 before calling a ROM routine which called me back, and restore it before returning to the ROM. It would be possible to save your global base in memory youve allocated and have a handle to in dCtlStorage; you could get at your DCE from the Unit Table using the method in Apples Technical Note 71. This method requires knowing the name of the DRVR, however, and you cant be certain of your own name (I routinely change DA names in my system to shorten them or remove s).
I dont know if reentrancy is really a pitfall, but you have to remember that ModalDialog calls SystemTask, and youll get activate and update events.
JIODone and locking have been covered already (MacTutor, Apr 86). Ill just add that if you unlock yourself, be sure to keep any references to routines saved in data structures (such as a TextEdit clikLoop) current when youre again locked.
Renumbering really shouldnt be a pitfall either, but you do have to be sure your resource IDs arent hardcoded, because Font/DA Mover will renumber all your resources. This routine figures out what theyre renumbered to.
/**********************************************************/
/* */
/* GET_DRVR - Find resource number, based on the driver */
/* */
/*********************************************************/
get_drvr() {
return 0xC000 | (((-Dp->dCtlRefNum) - 1) << 5);
}
A lot of development systems dont support desk accessories too well. MacTutor has had numerous articles on the difficulties of using different compilers. Using Aztec C, Ive found bugs in the Memory Manager glue code, where the reference to the memerr global was A5 relative, and might mean that different segments had different globals. Rewriting the glue and including it in my own source code (instead of the library) solved this.
Friendly Applications
The other side of the DA story is that applications have to support them. You might as well, because someones going to use DA Key on you and use DAs anyway. So your clipboard and files could be changed out from under you, and all your resources purged.
And youre doing the user a disservice if you dont. For example, I find playing adventure games more enjoyable if I can open a DA to take notes or draw a map. And Apples MiniFinder is useless without desk accessories.
Treat DAs as coequal applications. The user will expect the same behaviour from any open window. Dont do anything a DA cant. I always thought Multiplan, with its multiplicity of cursors, was silly. For example, the cursor changed to a multi-directional arrow when in the draggable title bar of a window. Unless, of course, the window was for a desk accessory In this case, I think inconsistency was the hobgoblin of small minds.
Since so few DAs are written to handle goodBye kisses, its a good idea to close each open desk accessory before quitting.
Dont force the user to memorize keyboard commands. Even if your application doesnt handle the Edit menu, include one for the benefit of desk accessories. And dont forget Undo, even if you have to dim it when your windows active.
Try to use normal windows. Its always bothered me that I have to close desk accessories before resuming work in MacPaint.
Dont gobble up the DA menu with stuff that has nothing to do with DAs. Jazz is a big offender here. Thank goodness updated Systems have scrolling menus.
Let DAs have memory! Certain applications such as Microsoft Basic do their own memory management, and dont leave enough for DAs.