TweetFollow Us on Twitter

Doodats
Volume Number:5
Issue Number:9
Column Tag:C Workshop

Three Doodats

By Lee A. Neuse, Manassas, VA

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

[Lee Neuse started in the days you built them before programmed them. He was lured away from IBM compatibles to the Mac in 1982 and been there ever since. Currently, he is working for Computer Science Corporation designing and implementing Mac software as part of CSC research. His Mousehole handle is "Noisy".]

Three Doodats

Doodat -- a trivial problem guaranteed to make a programmer’s life miserable; from the expression “How did he do dat?”.

It seems like every programmer, at one time or another, is faced with the same dilemma: wanting to use a feature in a program, but not wanting to spend the time to figure out the technique. For example, we all know that a Balanced B-Tree index is wonderfully efficient, but how many of us really want to sit down and write the code? One solution is to start reading back issues of MacTutor, hoping that some kind soul has already published useable source code. Another is to scour public domain software for an author willing to impart knowledge in exchange for a shareware donation. Either way, it’s usually faster (and easier) to find and adapt someone else’s code instead of doing it yourself.

The purpose of ‘Doodats’ is to provide generic solutions to the little problems, so the programmer can spend his or her time working on the big problems (like what the program does).

Doodat #1

Problem: how to determine if the user has tried to abort something by pressing the Cmd-’.’ keys. EventAvail() returns only the first keystroke event in the queue, and the user may have pressed some other keys since the last keystroke event was read by the application. Either GetNextEvent() or WaitNextEvent() return all keystroke events, forcing the application to store them or ignore them (a Bad Thing). Moreover, if MultiFinder is running, calling any of these event-related traps may cause the application to be switched out, which could cause problems.

Solution: Doodat #1 is a routine called check_abort(), which directly scans the ToolBox’s internal event queue for Cmd-’.’ abort events.

The routine starts by setting a pointer to head of the event queue (stored in the system global EventQueue), then examining the next event in the queue. If the event is a Cmd-’.’ event, it is removed by calling Dequeue(), and the ‘found’ flag set. If the pointer does not match the event queue tail, it is advanced to the next event, otherwise, the function returns. This technique solves all of the problems posed by normal event processing:

1. It doesn’t affect any other keystroke events in the queue.

2. If the user has generated multiple aborts (by holding the keys down), it removes all of them.

3. It does not call EventAvail() or WaitNextEvent(), so no chance of being switched in or out under MultiFinder.

To use check_abort(), call it from within any place where the user might want to abort. For example:

/* 1 */

for (page = 1; page < last_page; page++)
 {
 /* print a page */
 if (check_abort())
 break;
 }

/*************************************************
**
** check_abort() - Lightspeed C Version
**
** This routine returns scans the low-level
** event queue in search of a Cmd-’.’ key event
** Each one found is removed from the event
** queue.
**
** In:  N/A
**
** Out: TRUE if Cmd-’.’ found, FALSE otherwise.
**
*/

Boolean
check_abort()
{
EvQElPtreq_p;
Boolean f_found = false;

/* start at head of internal queue */
eq_p = (EvQElPtr)(EventQueue.qHead);

while (true)
 {
 if ((eq_p->evtQWhat == keyDown ||
 (eq_p->evtQWhat == autoKey) &&
 (eq_p->evtQModifiers & cmdKey) &&
 (eq_p->evtQMessage & charCodeMask) == ‘.’)
 {
/* remove the event from the queue */
 Dequeue((QElemPtr)eq_p, &EventQueue);
 f_found = true;
 }
/* test for end of queue */
 if (eq_p == (EvQElPtr)EventQueue.qTail)
 break;

/* continue with next queue entry */
 eq_p = (EvQEl *)(eq_p->qLink);
 }
return(f_found);
}/* end of check_abort() */

Doodat #2

Problem: Many windows contain items such as lines, icons, pictures, or text strings that are there for decoration; these items don’t change in appearance, and clicking on them has no effect. While the code to draw these items is relatively simple, it is also very boring to write, and frequently quite lengthy. In addition, trying to figure out exactly which horizontal and vertical co-ordinates to use can be time-consuming and frustrating.

Solution: Doodat #2 is an attempt to save time (and code!) by making ResEdit and the Resource Manager do most of the work. This involves a two-step approach:

Step 1 is to use ResEdit (or any other Resource tool) to create a ‘DITL’ resource (Dialog Item List) that contains all of the items desired. ResEdit is particularly handy, as the items can be arranged visually within the window. The DITL resource may be created and edited normally, with all items being set to disabled. No Control or EditText items should be included (they will be ignored if you do), and the items may be in any order. The finished DITL resource is then included in the application’s resources for later use.

UserItems in the item list are handled in one of two ways: either as a dividing line or as frame. If the horizontal or vertical co-ordinates are equal, i.e. the boundary rectangle is empty, it is drawn as a 50% gray line. If the rectangle is not empty, it is drawn as a black frame.

Text items are drawn (left-justified) in whatever font the window’s port is using when draw_ditl() is called. Different text characteristics could be supplied by reserving the first few characters of the text string but that’s for another time.

Step 2 is to use the routine below called draw_ditl() to actually read in and draw the items within the window. This routine accepts the ID number of a DITL resource, reads the resource into memory, then traverses the item list, drawing each item accordingly. For draw_ditl() to work properly, the DITL resource must be present in the application’s resource fork (or in an open resource file), and the port set to the desired window.

draw_ditl() uses the following definitions and structure:

/* 2 */

#define NIL 0L

/* Test a pointer for validity */
#define VALID_PTR(p) ((long)(p) &&
 ((long)(p) & 1L) == NIL)

/* Test a handle for validity */
#define VALID_HNDL(h)(VALID_PTR(h) &&
 VALID_PTR((long)(*(h)) & 0x00FFFFFF))

typedef struct
 {
 Handle hndl;
 Rect   frame;
 unsigned char   type;
 unsigned char   length;
 short  data[];
 } ditl_list;

/*************************************************
**
** draw_ditl() - Lightspeed C Version
**
** This routine reads in and draws the items in a
** Dialog Item List (DITL) resource.
**
** In:  resource id of DITL
**
** Out: N/A
**
*/

void
draw_ditl(ditl_id)
short   ditl_id;
{
Handle  ditl_h;
ditl_list *ditl_p;
PenStatesave_pen;
short   d_type, offset, num_items;

ditl_h = GetResource(‘DITL’, ditl_id);
if (ResError() != noErr || !VALID_HNDL(ditl_h))
 return;

HLock(ditl_h);
/* don’t change pen behind the window’s back */
GetPenState(&save_pen);
PenNormal();
/* get the number of items in list */
num_items = *((short *)(*ditl_h)) + 1;
/* set pointer to first item in list */
ditl_p = (ditl_list *)((*ditl_h) + sizeof(short));
while  (num_items--)
 {
/* mask out the item disabled bit */
 switch (ditl_p->type & 0x7F)
 {
 case statText:
 TextBox((char *)ditl_p->data,
 ditl_p->length, &(ditl_p->frame),
 teJustLeft);
 break;
 
 case iconItem:
 ditl_p->hndl =
 GetIcon(ditl_p->data[0]);
 if (VALID_HNDL(ditl_p->hndl))
 {
 PlotIcon(&(ditl_p->frame),
 ditl_p->hndl);
 ReleaseResource(ditl_p->hndl);
 }
 break;
 
 case picItem:
 ditl_p->hndl = GetResource(‘PICT’,
 ditl_p->data[0]);
 if (VALID_HNDL(ditl_p->hndl))
 {
 DrawPicture((PicHandle)ditl_p->hndl,
 &(ditl_p->frame));
 ReleaseReource(ditl_p->hndl);
 }
 break;
 
 case userItem:
 if (EmptyRect(&(ditl_p->frame)))
 {
 PenPat(gray);
 MoveTo(ditl_p->frame.left,
 ditl_p->frame.top);
 LineTo(ditl_p->frame.right,
 ditl_p->frame.bottom);
 PenPat(black);
 }
 else
 FrameRect(&(ditl_p->frame));
 break;
 }
/* force offset to a word (even) boundary */
 if ((offset = ditl_p->length) & 1)
 offset++;
/* advance pointer to next item */
 ditl_p = (ditl_list *)((char *)ditl_p +
 sizeof(ditl_list) + offset);
 }

HUnlock(ditl_h);
ReleaseResource(ditl_h);
/* restore pen to original condition */
SetPenState(&save_pen);
}/* end of draw_ditl() */

Doodat #3

Problem: Sooner or later, an application is going to need to access a data file of some sort, with fixed-length or variable-length records, keys, and so forth. Using the Resource Manager as a Poor Man’s Database is a Bad Thing according to Apple, and not everyone can afford (or write) a full ISAM (Indexed Sequential Access Method) utility.

Solution: Doodat #3, which includes some primitive (but useful) indexing routines. If used properly, they can be used for indexing files, arrays, or be used for look-up tables, etc.

All of the routines are based on the idea of a simple index, made up of 1-n index entries. Each index entry is a key value and it’s associated data value, and is defined in the index_entry structure below. The key and data values are always handled in pairs: for any given key, there is only one data value (provided it exists). Duplicate keys are not allowed, and both key and data values are limited to numeric values. What the key and data values actually represent depends on the application, an obvious example would be relating a part number to an offset into a file.

Several different indices can be manipulated using the same routines, it is the application’s responsibility to determine which index to use. If the indexes are small and/or few in number, they could be manually rebuilt each time the application is executed. Alternately, they could be saved between sessions, either as data files, or as resources: all that is needed the memory block referenced by the index handle (use GetHandleSize() to find it’s size). An elegant solution would be to save any or all data file indices as resources in the data file’s resource fork, but that would limit the index size to 32K.

Adding a new key to an index (or updating an existing key) is done by the db_insert_key() function: a pointer to the index handle, a key value, and the data value associated with the key are all passed as parameters. If the index handle is NIL, a new handle is allocated, otherwise, the index is expanded by one index entry, and the new key added to the index in ascending order. If the key value already exists in the index, the data value is updated with the new value.

Once an index has keys inserted into it, db_get_key() can be used to search the index for a given key value. The routine expects an index handle and a key value, then performs a binary search on the index. If the key value is found, the data value associated with the key is returned, otherwise -1 is returned to signal failure.

There may be times when it is necessary to find a key’s location in the index, thus db_get_seq_key() accepts an index handle and an entry number, then returns the key value found at that entry. Once again, -1 is returned to signal failure if the entry number is less than 1 or greater than the number of keys. This routine can be used to sequentially read through an index (in ascending order), using the following code:

/* 3 */

long  w_key, key_value;

w_key = 1L;
while (true)
 {
 key_value = db_get_seq_key(my_index, w_key++);
 if (key_value == -1L)
 break;

 my_data = db_get_key(my_index, key_value);
/*
** process my_data here
*/
 }

Some possible extensions to these routines include modifying them to store a character pointer as the key, providing non-numeric keys. For small indexes, the entire data record could be embedded as part of the index_entry structure, and a pointer to the structure returned by db_get_key().

The routines db_get_key(), db_get_seq_key(), and db_insert_key() all utilize the following definitions and structure:

/* 4 */

#define NIL 0L
/* Test a pointer for validity */
#define VALID_PTR(p) ((long)(p) &&
 ((long)(p) & 1L) == NIL)

/* Test a handle for validity */
#define VALID_HNDL(h)(VALID_PTR(h) &&
 VALID_PTR((long)(*(h)) & 0x00FFFFFF))

typedef struct
 {
 unsigned long   key;
 unsigned long   data;
 } index_entry;

/************************************************
**
** db_get_key()
**
** This routine performs a binary search on a
** list of index entries
**
** In:  index_hndl Handle to index
** target key value to find
**
** Out: -1 if NOT found, data value otherwise
**
*/

long
db_get_key(index_hndl, target)
Handle  index_hndl;
register long  target;
{
register index_entry *i_ptr;
register long    mid, low, high;

if (VALID_HNDL(index_hndl))
 {
 low = 1L;
 high = GetHandleSize(index_hndl) /
 sizeof(index_entry);

 while (low <= high)
 {
/* calculate the mid point of list */
 mid = ((low + high) >> 1) - 1;
 i_ptr = *index_hndl + (mid *
 sizeof(index_entry));

 if (i_ptr->key > target)
/* too big, so look in lower half  */
 high = mid;
 else if (i_ptr->key < target)
/* too small, so look in upper half */
 low = mid + 2;
 else
/* hmmm, guess we found it  */
 return(i_ptr->data);
 }
 }
return(-1L);
}/* end of db_get_key() */

/************************************************
**
** db_get_seq_key()
**
** This routine reads a list of index entries,
** returning a key based on a sequential number
**
** In:  index_hndl Handle to index
** key_numkey number to return
**
** Out: -1 if NOT found, key value otherwise
**
*/

long db_get_seq_key(index_hndl, key_num)
Handle  index_hndl;
short   key_num;
{
index_entry *i_ptr;
long    result = -1L;
short   num_keys;

if (VALID_HNDL(index_hndl)
 {
/* count number of keys in index */
 num_keys = GetHandleSize(index_hndl) /
 sizeof(index_entry);
 if (--key_num < num_keys)
 {
/* calculate offset into the index */
 i_ptr = *index_hndl + (key_num *
 sizeof(index_entry));
 result = i_ptr->key;
 }
 }

return(result);
}/* end of db_get_seq_key() */

/************************************************
**
** db_insert_key()
**
** This routine inserts a key into an index.
**
** In:  index_hndl Handle to index
** target key value to insert
** data data value associated
** with the key
**
** Out: N/A
*/

void
db_insert_key(index_hndl, target, data)
Handle  *index_hndl;
long    target;
long    data;
{
register index_entry *i_ptr, *n_ptr;
register long    mid, low, high, i_size;

/* empty list is special case! */
if (!VALID_HNDL(*index_hndl))
 {
/* allocate new handle */
 *index_hndl = NewHandle(sizeof(index_entry));
 ((index_entry *)(**index_hndl))->key = target;
 ((index_entry *)(**index_hndl))->data = data;
 }
else
 {
 low = 1L;
 high = i_size = GetHandleSize(*index_hndl) /
 sizeof(index_entry);

 while (low <= high)
 {
/* calculate the mid point of list */
 mid = ((low + high) >> 1) - 1;
 i_ptr = *index_hndl + (mid *
 sizeof(index_entry));

 if (i_ptr->key > target)
/* too big, so look in lower half */
 high = mid;
 else if (i_ptr->key < target)
/* too small, so look in upper half */
 low = mid + 2;
 else
/* found it, so store new key value */
 i_ptr->data = data;
 }

/* extend handle by size of one entry*/
 SetHandleSize(*index_hndl, (i_size + 1) *
 sizeof(index_entry));
/* test for memory error here */
 n_ptr = i_ptr = **index_hndl + (mid * 
 sizeof(index_entry));
 memcpy(++n_ptr, i_ptr, (i_size - mid) *
 sizeof(index_entry));
/* do we insert as right or left? */
 if (i_ptr->key < target)
 i_ptr = n_ptr;
/* and move in the new key and data value */
 i_ptr->key = target;
 i_ptr->data = data;
 }
}/* end of db_insert_key() */

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more
Alfred 5.1.3 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Sketch 98.3 - Design app for UX/UI for i...
Sketch is an innovative and fresh look at vector drawing. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and... Read more

Latest Forum Discussions

See All

Listener Emails and the iPhone 15! – The...
In this week’s episode of The TouchArcade Show we finally get to a backlog of emails that have been hanging out in our inbox for, oh, about a month or so. We love getting emails as they always lead to interesting discussion about a variety of topics... | Read more »
TouchArcade Game of the Week: ‘Cypher 00...
This doesn’t happen too often, but occasionally there will be an Apple Arcade game that I adore so much I just have to pick it as the Game of the Week. Well, here we are, and Cypher 007 is one of those games. The big key point here is that Cypher... | Read more »
SwitchArcade Round-Up: ‘EA Sports FC 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2023. In today’s article, we’ve got a ton of news to go over. Just a lot going on today, I suppose. After that, there are quite a few new releases to look at... | Read more »
‘Storyteller’ Mobile Review – Perfect fo...
I first played Daniel Benmergui’s Storyteller (Free) through its Nintendo Switch and Steam releases. Read my original review of it here. Since then, a lot of friends who played the game enjoyed it, but thought it was overpriced given the short... | Read more »
An Interview with the Legendary Yu Suzuk...
One of the cool things about my job is that every once in a while, I get to talk to the people behind the games. It’s always a pleasure. Well, today we have a really special one for you, dear friends. Mr. Yu Suzuki of Ys Net, the force behind such... | Read more »
New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »
‘The Elder Scrolls: Castles’ Is Availabl...
Back when Fallout Shelter (Free) released on mobile, and eventually hit consoles and PC, I didn’t think it would lead to something similar for The Elder Scrolls, but here we are. The Elder Scrolls: Castles is a new simulation game from Bethesda... | Read more »

Price Scanner via MacPrices.net

Clearance M1 Max Mac Studio available today a...
Apple has clearance M1 Max Mac Studios available in their Certified Refurbished store for $270 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Apple continues to offer 24-inch iMacs for up...
Apple has a full range of 24-inch M1 iMacs available today in their Certified Refurbished store. Models are available starting at only $1099 and range up to $260 off original MSRP. Each iMac is in... Read more
Final weekend for Apple’s 2023 Back to School...
This is the final weekend for Apple’s Back to School Promotion 2023. It remains active until Monday, October 2nd. Education customers receive a free $150 Apple Gift Card with the purchase of a new... Read more
Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* River -...
Park Dental Apple River in Somerset, WI is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. COMPETITIVE PAY AND SIGN-ON Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Sep 30, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* / Mac Administrator - JAMF - Amentum...
Amentum is seeking an ** Apple / Mac Administrator - JAMF** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.