TweetFollow Us on Twitter

DAs in C
Volume Number:1
Issue Number:11
Column Tag:Programmer's Forum

Desk Accessories in C

By Wesley Swannack, Computer Engineer, Richland, WA.

Creating a tools and mini-applications

A feature of the Macintosh that sets it apart from other computers is it's ability to have Desk Accessories. Desk Accessories can be considered a 'mini-application' that can be executed while using a program such as MacDraw or writing a Macintosh application program. Desk accessories are small programs that help you achieve a main goal, and is a part of the Desktop Concept that Apple has envisioned. In short, while creating programs or documents there are tools that we use intermittently, such as the Scrapbook, or a Hex Calculator. This is analogous to activities before the advent of personnel computers, tools physically sat on the desk, now the tools are more powerful electronic versions.

Can useful Desk Accessories be Written?

Desk Accessories can be very powerful; enhancing the functionality of the Macintosh. My favorite example, is Click-On Worksheet from T/Maker Graphics. Click-On Worksheet is a very powerful spreadsheet and chart program, that allows the creation of a small spreadsheet or chart while using a word processing or database program. Another example is the dCad Calculator from Desktop, a scientific and programing calculator.

Some Background Information

When writing that first desk accessory, there are two very important chapters in Inside Macintosh, to familiarize yourself with. The Chapters are the Desk Manager and the Device Manager. Briefly, the sole purpose of the Desk Manager is to coordinate activities between the executing desk accessory and the application program. The Device Manager handles the I/O of information to and from the desk accessory.

When writing a desk accessory, the program content is considered a 'DRVR' (driver) resource type, from a Macintosh viewpoint. 'DRVR' resources are kept in the System file and are read into memory by the Device Manager as needed. At this time the resource ID's of the DRVR's can range from 0 to 31, however remember that the first 11 are reserved by Apple. These reserved ID's are for things like the Disk, Sound, AppleTalk, and Printer drivers.

Open, Close, Control, Prime, and Status

A 'DRVR' routine is made up of 5 routines that dictate actions. They are Open, Close, Control, Prime, and Status. The Open routine reads all the 'DRVR' code and resources into memory, creates data structures and variables when the desk accessory is executed for the first time. The Close routine deletes and removes from memory, structures and resources that the desk accessory used. The Control routine is the most important of all five routines. This routine is executed everytime the procedure SystemTask() is called within the event loop of the application program currently running. Think of the procedure as giving control of the Mac over to the desk accessory; then, when the desk accessory is closed, control is handed back to the main application program. The Prime and Status routines deal with the reading and writing of information to the 'DRVR' and at this time are not important to us. One neat feature of Desk Accessories is the ability to attach and use resources such as WIND's and MENU's.

Getting Started on the Desk Accessory

Ok, Let us get started on the Desk Accessory. This desk accessory has been written using 'C' as the language and most C compilers support the creating of desk accessories. Even if you don't program in C, most programs are easy to follow because of all the toolbox calls that programs use. The type of desk accessory that we will be writing is called a Shell. Shells allow a person to start from a point that works. Then in a modular fashion new routines and functions, can be added. This allows you to track down errors and debug the program much easier. So once you have finished with this shell program, you will have a base to work from as you try out your own desk accessories.

Looking at the beginning of the program listing, the necessary header files have been included, that represent predefined constants and variable structures. Next is a procedure called ACC(). This is a MegaMax dependent item since the Linker supports the creation of desk accessories. What is important is the arguments of the ACC procedure.

The Control routine can respond to certain device routines, which are determined by the argument drvrFlags. Explanation of the flags can be found on pages 19 and 20 of the Device Manager Guide. How one determines the drvrFlags is tersely explained in Inside Macintosh, so after much thinking the light came on!! At the top of page 20 is a set of predefined constants such as dNeedTime. Looking at the equates one sees that the constants range from 0 to 6. These numbers represent which bit in the high word byte of the drvrFlags to set to a one. So the program example $2400 in binary form represents a 00100100 00000000. This binary number, (using page 20 as a guide), shows that the driver can respond to control events and that the driver needs time to perform periodic action. [Hence bit settings in the drvrFlags argument determine characteristics of the driver. --Ed.] The next argument drvrDelay contains a tick count indicating how often the control routine should be called. A tick count of 0 means that the control routine will be called as often as possible. A 1 means that the action should be called every 60th of a second, 2 means every 30th of a second. Using a value of 60 in the program, our control routine will be called every full second. Remember whether this action occurs, is dependent on how long it takes the application program to call SystemTasks(). DrvrEvmask is a mask that filters what type of events the desk accessory will responded to; these are explained on page 16 of the Event Manager. Basically, just add up all the numbers that represent those events you want to respond to. The argument drvrMenu represents the resource ID number of a menu that your desk accessory uses. You have seen many desk accessories that have a menu appear on the menubar such as Extras. To attach resources such as menus and windows, a special formula is used in determining the resource ID number. This formula is discussed on page 10 of the Resource Manger. In our example program, a resource number of -15424 is used. Looking at the chart on page 10 we know that bits 15 and 14 are set to a 1. This means that all resources of desk accessories will be negative value, such as the above example. Next bits 13, 12, and 11 are set to 0. This specifies that a DRVR resource own's the attached resources. Bits 5 thru 10 contain the resource id number of the DRVR. As mention in the very beginning of the program listing, we are using a resource id = 30. Bits 4 thru 0 are variable and allow us to have several menus attached to the same desk accessory. So the value -15424 = 11000011 11000000 in binary form. We used a variable of 0 in this MENU resource however if you want to add another menu you can use a 1, then 2, and so on. Length and Window title are arguments that are used for the title of the window and the length of the window title.

Format of the Desk Accessory File

The internal format of the desk accessory file can be found on page 12 of the Desk Manager. This is the final form that all desk accessories look like when finally compiled into machine code. If you have a compiler that creates Desk Accessories then this information is just for interest only.

Opening the DRVR routine

When a desk accessory is used for the first time, information about the desk accessory is read into a structure in memory called a Device Control Entry block. An illustrated version of this can be found on page 21 of the Device Manager. Looking at it, we notice that it has information about the window, menu, number of ticks, etc. This is very important, for this is how data can be accessed from one routine to the other. The first thing that is declared is a *dctl and a *pb pointers after the accopen(dctl,pb) function. The pointers allows access to the Device Control Block, and since this is a RAM driver (i.e. loaded from disk into memory), a paramunion block must be used to gain access to events and other information. Next a menu structure and a window pointer is created since this desk accessory will have a window and a menu associated with it. Then we check to make sure that that this desk accessory has not been already executed by checking for the presence of the window. Once the IF statement is true, use the function getmenu to get the menu resource that is already in the system file. Since the device control entry block already contains the menu resource id, just pass the value to the function getmenu. Next create the window, set the port, and assign the text mode. Now we get the device reference number (dctlrefnum) and insert into the windowkind field of my window structure. This reference number is what the Device Manager uses internally, instead of using the name of the Desk Accessory. Now assign the dcltwindow field in the device entry block, a pointer that points to my window. At this point we have created all the menus and windows and the Open routine is finished.

Controlling the DRVR routine

The Control routine represents the heart of the desk accessory. This routine is executed everytime a SystemTask is called from the application program. This desk accessory creates a window, menu, and prints the time of day in the window.

Following the program, create *dctl and *pb pointers to the various information structures of the driver (i.e. desk accessory.) Then we create a new menu structure and window pointer. Using the dclt (device control block) we can extract the menuhandle and the pointer to my desk accessory's window, that are somewhere, floating out in memory. Next is the event structure that determines what the desk accessory will do every time the procedure SystemTask is called from the application program.

The action taken by the Control routine is determined by a message that is stored in .cscode field of the paramunion.cntrlparam structure. This field is accessed by the pb pointer that was created when the Control routine was just executing. The messages that we can expect to receive can be found on page 14 of the Desk Manager. These messages simply tell the Control routine what kind of action to take. In our example we used the accrun, accevent, and the accmenu messages. As outlined in the page 14, accrun handles periodic actions such as getting the time for a clock. Handling events such as keyboard and mouse events the accevent message is used. When using menus the Desk Manager uses the accmenu message.

Looking at the accrun portion of the switch statement, in the program listing, we can see that the time of day is inserted into the datetime variable, then printed onto the window that is associated with the desk accessory. This is done as long as the switch condition finds the accrun message in the .cscode field.

The accevent portion of the switch statement is a little more complicated since we must determine what type of event has occurred. Besides the accevent message, the control routine receives in the csparam field of the paramunion structure, a pointer to an event record. This event record is needed to tell us the what and where of the event. To get the what of the event record, we do a 'C' type cast of the pointer, casting the pointer as an event record. One note, that in the header file of the paramunion structure that we must use a long that is a field of the csparam structure. This will allow us to conveniently get the address when type casting the pointer. It may seem somewhat complicated but it works quite well. Back to the program. Now that we know what type of event occurred, we can find out where it occurred such as in a mousedown event. Using the same technique as above, we can pass to the findwindow routine where the mousedown event occurred.

Remember that all windows created by desk accessories are considered system windows, as talked about on page 4 of the Window Manager. The insyswindow constant is what findwindow will return, if the mousedown event occurred inside of our desk accessory window, so beware. If the person clicked inside of a application window, the desk manager will handle it and does not have to be addressed by the desk accessory. In our program when clicking inside of the system window the procedure closedeskacc is called. The only argument that is passed is the reference number of the desk accessory. This can be accessed thru dctlrefnum field of the device control block. The procedure closedeskacc terminates the Control routine of the desk accessory and starts the execution of the Close routine.

When selecting a desk accessory's menu the Desk manager generates an accmenu message. Once again we can extract the data using the csparam field. This allows us to get the item number of which item was choosen in the desk accessories menu. If we selected the first item we can hide or show the window on the desktop. Notice this also toggles the menu from show to hide and back again. If we select close then the closedeskacc procedure is called and the desk accessory is terminated.

Closing the DRVR routine

When the Closing the desk accessory the windows, menus and any other data structures must be disposed of. Then the dctlwindow pointer field of the device control block must have a nil inserted. Looking at our Close routine example we once again access the pb and dctl thru the use of pointers. This allows us to dispose of the window structures and menu resources. We redraw and update the menubar, then do a sysbeep just to let us know that the routine is complete and the desk accessory is no more.

Some Closing Comments

Once you have compiled the desk accessory and the resource file, using REdit is useful for cutting and pasting the DRVR and MENU into the System file. Remember that the ID's of the DRVR and MENU are equal to 30. If you wish to change the DRVR id number, then remember to change the resource id's of the attached resources.

After looking over the code for this desk accessory you may decide that this is a trivial program. The idea here is to create a shell version that is understandable and most importantly works. In later issues we can approach the cutting and pasting between applications and desk accessories, and how to create a calculator.

Remember that desk accessories can be as powerful as application programs. It is not unlikely that a terminal program or text editor couldn't be written as a desk accessory. I write desk accessories because they can give the Macintosh a state of 'pseudo-concurrency' and the Mac is an interesting machine to program.

!codeexamplestart*
*
* shell.r
* resource file
* resource id = 30
*
shell.rsrc

Type MENU
 ,-15424
Shell
 Hide Window
 (-
 Close




/*
shell.c
Wesley C. Swannack
shell for most desk accessories
written in Megamax C.
id number of the 'DRVR' = 30
*/
#include <global.h>
#include <acc.h>
#include <desk.h>
#include <qd.h>
#include <event.h>
#include <res.h>
#include <misc.h>
#include <mem.h>
#include <menu.h>
#include <te.h>
#include <font.h>
#include <file.h>
#include <win.h>
#include <control.h>
#include <device.h>

/* drvrFlags, drvrDelay,drvrEvmask, drvrMenu , Length and window title 
*/ 
ACC(0x2400,60, 0x014A,-15424,5, "Shell")
int menuflag = FALSE;

accopen(dctl, pb)
dctlentry *dctl; /* pointer to device control block */
paramblockrec *pb; /* handle to parameter block */
{
 menuhandle mymenu;  /* creating my menu structure */
 windowpeek mywindow;/* pointer to the window record */
 rect wr; /* starting size for the window */
 if (dctl->dctlwindow == NULL)/* No window  created*/
 { 
 mymenu = getmenu(dctl->dctlmenu);
 insertmenu(mymenu, 0); /* appending the menu to the menubar */
 drawmenubar();
 setrect(&wr, 100, 50, 400, 250);  
 /* creating the window */
 mywindow = newwindow(NULL, &wr, "Window", 0, rdocproc, -1L, -1, 0L);
 setport(mywindow);
 textmode(srccopy);
 
 mywindow->windowkind = dctl->dctlrefnum;    /* getting neg number for 
my sys window */ 
 dctl->dctlwindow = mywindow; /* device window now my window ptr */
 }
 return 0;
}

accclose(dctl, pb)
dctlentry *dctl;
paramblockrec *pb;
{
 menuhandle mymenu;  /* declaring menu */
 windowptr mywindow; /* declaring window */
 mymenu = getmhandle(dctl->dctlmenu);  /* getting handle to desk menu 
*/
 mywindow = dctl->dctlwindow;      /* getting desk window */
 dctl->dctlwindow = NULL;
 disposewindow(mywindow);
 deletemenu(dctl->dctlmenu);
 releaseresource(mymenu); /* disposing of the menu  rsrc*/
 drawmenubar();
 sysbeep(2);/* just to let me know when closed */
 return 0;
}


accctl(dctl, pb)
dctlentry *dctl;
paramblockrec *pb;
{
 long datetime;
 char timestr[100];

 menuhandle mymenu;  /* declaring menu */
 windowptr mywindow; /* declaring window */
 
 mywindow = dctl->dctlwindow; /* getting my window stuff */
 mymenu = getmhandle(dctl->dctlmenu);/* getting my menu stuff */

 switch (pb->paramunion.cntrlparam.cscode) 
 {
 case accrun:
 setport(dctl->dctlwindow);
 getdatetime(&datetime);  /* getting the time for this moment */
 iutimestring(datetime, -1, timestr);
 moveto((100-stringwidth(timestr))>>1,15);   /* moving the pen to draw 
with */
 drawstring(timestr);
 break;
 case accevent:
 /* getting the event */ 
 switch (((eventrecord *)pb->paramunion.cntrlparam.csparam.eventaddress)->what)
 {
 case mousedown:
 {
 int wherepressed;
 /* Only because it is a really long statement to print,notice that the 
next to lines are really one line */ wherepressed=findwindow(&(((eventrecord*)pb->paramunion.cntrlparam.csparam.eventaddress)-> 
where), &mywindow); 
 switch(wherepressed)
 case insyswindow: /* in my desk accessory window */
 closedeskacc(dctl->dctlrefnum);
 break;
 }
 case keydown:
 sysbeep(3);
 break;
 }
 case accmenu:
 switch (pb->paramunion.cntrlparam.csparam.menustatus.itemnumber) 
 {
 case 1:/* selected 'Hide' or 'Show' */
 if (menuflag)
 {
 selectwindow(mywindow);  /* window is now visible */
 showwindow(mywindow);
 setitem(mymenu,1,"Hide Window");  /* inserting new menu item */
 /* user will see the 'Hide' option in the menu */ 
 menuflag = FALSE;
 }
 else
 {
 hidewindow(mywindow);
 setitem(mymenu, 1, "Show Window");/* inserting new menu item */
 /* user will see the 'Display' option in the menu */ 
 menuflag = TRUE;
 }
 break;
 case 3:
 closedeskacc(dctl->dctlrefnum);
 break;
 }
 }
 return 0;
}

accprime()
{
}

accstatus()
{
}
/* I have included the appropriate data structures so that you can tell
 whether or not your files have the appropriate variables.
 The variables talked about are in boldface type

 This is for refernence only
*/

typedef union {    /* control information */
 int sndval;
 int asncconfig;
 struct { ....  } asyncinbuff;
 struct { ....  } asyncshk;
 struct { ....  } printer;
 struct { ....  } fontmgr;
 ptr diskbuff;
 long eventaddress;/* address for desk events */
 long asyncnbytes;
 struct { ....  } asyncstatus;
 struct { ....  } diskstat;
 struct { /* menu manager */
 int menuident;
 int itemnumber;
        } menustatus;
   } opparamtype;

typedef opparamtype *opparamptr;

typedef struct {
     ptr iolink;
     int iotype;
     int iotrap;
     ptr iocmdaddr;
     procptr iocompletion;
     int ioresult;
     char *ionameptr;
     int iovrefnum;
     union {
 struct { .... } ioparam;
 struct { .... } fileparam;
 struct { .... } volumeparam;
 struct {
        int filler3;
        int cscode;
        opparamtype csparam;
   } cntrlparam;
        } paramunion;
   } paramblockrec;

 

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.