TweetFollow Us on Twitter

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), they’re 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 couldn’t be a DA. There’s really no reason, except that the Mac architecture implements them as drivers, and the unit table is limited to 32 entries. So we’re 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. I’ll 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. I’ll talk about what I’ve 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, you’re confronted with the fact that many applications don’t include the keyboard equivalents to the standard commands. In fact, ThinkTank doesn’t even provide an Undo menu item at all! This means that you’ll 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 don’t 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 Acta’s application equivalent lacks Undo.

Goodbye Kisses

Any intelligent application asks the user to save his work before quitting. Since desk accessories don’t have access to the File menu, it isn’t 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 it’s because they didn’t quit in the “proper” way.

When I was trying to implement this feature, I couldn’t find a single DA that had it! (I’ve since learned that ClickOn Worksheet [which by now you can tell I admire greatly] does field goodbye kisses.) In fact, since I couldn’t get it to work, and since I couldn’t determine that it worked anywhere else, I was convinced that it didn’t work at all. It does. You do need to return via JIODone, which may be difficult in a high-level language. Mike Schuster’s 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 don’t close the desk accessory associated with a window ). Here’s a routine to close your window only if it’s 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 it’s something you should do anyway after altering a disk).

There are a few things that you shouldn’t 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 doesn’t 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 DA’s files to have distinctive icons, you’ll have to figure out a way to get the bundle into the Desktop file. It’s 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 you’re going to use more than one menu, they won’t fit. You’ll 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 don’t 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 won’t 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. It’s 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 it’s easy to identify.

You could try to keep track of the zoom state yourself, but this won’t 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 don’t need to worry about whether you’re running on the new ROMs or not, because the WDEF won’t 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 haven’t written any DAs that let the user work with multiple windows; if I use a second window, it’s always a modal dialog. Why? Well, there’s 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 DA’s close box is clicked. It calls the subroutine instead of closing the DA. On entry to the routine, A1 contains the DA’s 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 haven’t had the chance to try it yet.

Segmentation

It’s possible to segment a desk accessory, which allows you to get around the 8K limit Apple suggests. Unfortunately, you can’t use the segment loader. This means you can’t freely call routines without worrying about which segment they’re in. But as long as you group routines appropriately, this shouldn’t 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 it’s in CODE resources. You can choose any name; I use PROC. As long as the entry point is at the beginning of the resource, it’s 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

Here’s the file init.r (used by RGen, Manx’s 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. You’ll 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 don’t have a Lisa.

Development environments are a matter of preference. The main consideration in developing DAs is that you don’t 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 I’ll have to use the editor anyway after trying out some changes.

It’s also possible to create a Font/DA Mover file and open it with DA Key (Lofty Becker’s shareware FKEY, easily worth its $5 asking price), but this makes the DA modal, and harder to debug. If you prefer, you can use Becker’s Other DA (which is the same thing, implemented as a DA), but I can’t 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 won’t have to copy resources which are essentially static during the development process. When you finish the DA, it’s 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 they’re searched. I’ve also been told that MDS Edit is a harsh environment for DAs, but I haven’t 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 Microsoft’s (Word, for example, doesn’t handle menus well).

All the usual debugging techniques apply, like using Discipline and Heap Scramble from TMON.

Installer

It’s definitely not worth writing your own installer, in my opinion. There’s no need to reinvent the wheel. According to people who’ve written them, they’re a pain (this should be easy to verify by observing the many revisions to Apple’s 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 can’t be numbered as owned (such as INITs).

Copy protection

Yes, you can protect a DA. But don’t.

Pitfalls

One of the most annoying things Apple’s 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 (it’s possible to install up to 20 using ResEdit, but this option isn’t 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 won’t be able to get at the main application until she closes the DA. Versatile, because it doesn’t 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 you’re given a close call, you must close. The close may have been issued by the Finder, closing all open DAs before launching an application. There’s 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 won’t 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 you’ve allocated and have a handle to in dCtlStorage; you could get at your DCE from the Unit Table using the method in Apple’s Technical Note 71. This method requires knowing the name of the DRVR, however, and you can’t be certain of your own name (I routinely change DA names in my system to shorten them or remove ™s).

I don’t know if reentrancy is really a pitfall, but you have to remember that ModalDialog calls SystemTask, and you’ll get activate and update events.

JIODone and locking have been covered already (MacTutor, Apr 86). I’ll 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 you’re again locked.

Renumbering really shouldn’t be a pitfall either, but you do have to be sure your resource IDs aren’t hardcoded, because Font/DA Mover will renumber all your resources. This routine figures out what they’re renumbered to.

/**********************************************************/
/*                                                       */
/* GET_DRVR - Find resource number, based on the driver */
/*                                                       */
/*********************************************************/
get_drvr() {
 return 0xC000 | (((-Dp->dCtlRefNum) - 1) << 5);
}

A lot of development systems don’t support desk accessories too well. MacTutor has had numerous articles on the difficulties of using different compilers. Using Aztec C, I’ve 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 someone’s 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 you’re doing the user a disservice if you don’t. For example, I find playing adventure games more enjoyable if I can open a DA to take notes or draw a map. And Apple’s MiniFinder is useless without desk accessories.

Treat DAs as coequal applications. The user will expect the same behaviour from any open window. Don’t do anything a DA can’t. 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, it’s a good idea to close each open desk accessory before quitting.

Don’t force the user to memorize keyboard commands. Even if your application doesn’t handle the Edit menu, include one for the benefit of desk accessories. And don’t forget Undo, even if you have to dim it when your window’s active.

Try to use normal windows. It’s always bothered me that I have to close desk accessories before resuming work in MacPaint.

Don’t 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 don’t leave enough for DAs.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.