TweetFollow Us on Twitter

Ett Listigt
Volume Number:7
Issue Number:8
Column Tag:Programmer's Forum

Ett Listigt Program

By Martin Minow, Arlington, MA

Introduction

Perhaps I must begin with an apology for the title. It’s Swedish, and translates to “a clever program.” which is a bit of an overstatement for a minor hack but I couldn’t resist the opportunity to make a bilingual pun.

The program, in fact, isn’t clever at all. It merely serves to demonstrate how you can take control of the way the List Manager draws your data.

The List Manager, described in Inside Mac, volume IV, is a very simple table construction and selection function that lets your program manage a small collection of data. I use it in a number of applications: for example, to store the phone numbers for an autodialer and the names of elite runners in a road race display program.

While the List Manager is simple to use, it has a few limitations. For example, it is pretty sloppy about how it handles fonts, so if you put a list in a dialog, you run the risk of displaying parts of the dialog in the list font, rather than the dialog font.

Fortunately, the good folk who designed the List Manager gave programmers a way to add our own control function. They assume we’ll write the function as a code resource that is stored in the application’s resource fork. While this works well for most applications, this article shows two tricks that should make the list definition function easier to write and debug (no separate code resource) and easier to integrate into an application. The debugging advantages are significant: it is impossible to use the Think C symbolic debugger in a separately-compiled code resource.

The List Handler

Ignoring for a moment how we actually get there, the LDEF resource performs four services for the List Manager:

1. Initialize any private information when the list is first created. The demo handler defines some information based on the current font.

2. Draw a list cell. If your application doesn’t specify a drawing routine, the demo handler draws the cell using the font (and size) that were specified when the list was created. The window’s original font and size are restored, so the list can be used in, e.g., a dialog without messing up the font/size for other dialog items.

3. Hilite a list cell. The demo handler uses the new method of color highlighting described in Inside Mac, vol 5, pp 61-62.

4. Close a list -- this call lets a LDEF procedure release any private information. The demo handler ignores this call since it doesn’t store any private information.

The bulk of the work is done by the draw routine: the pen is moved to the proper place within the cell, the list data storage handle is locked in memory, the display area is erased, the font and size are set, and the data drawn (either by the handler or by the application’s callback function). Finally, the list data handle lock state is restored. If the cell was selected, the normal highlight procedure is then executed.

With that as background, the only remaining problem is connecting the list handler to your application. The sample program demonstrates three possible methods: building a separate code resource, building a fake code resource, and directly installing the list handler in the ListRecord without a separate resource.

The Code Resource

The approved way to write a list handler is to build it as a separate code resource that is stored as a LDEF resource in the application’s resource fork. Then, you specify the number of the LDEF resource when you execute LNew. If you’ve never done this before, the process is strange, but it’s fairly simple if you take it step-by-step. Using Think C (version 4), do the following:

1. Create a new project, say LDEF.Π.

2. Add the LDEF Resource.c and MacHeaders files.

3. Set the project type to Code Resource, set the resource name to LDEF and the resource id to, say, 128.

4. Build the code resource, saving it as LDEF.rsrc

Now, build your application. Think C (unfortunately) only supports RMaker, so you have to add the following line to your RMaker source file:

 Include LDEF.rsrc

RMaker will merge the code resource into your application’s resource fork.

Fake LDEF

Instead of building a separate LDEF resource, you can also compile the entire LDEF into your program. However, in order to satisfy the Macintosh Toolbox standards, you still need a resource. You can create one on the fly by building a callback LDEF. You do this by creating a dummy LDEF in your resource file that is defined as follows:

/* 1 */

 Type LDEF = GNRL
 , 128
 .h
 4EF9 0000 0000

Then, when your program starts, it calls the SetupLDEF function that “plugs” the address of the actual function into the LDEF and marks the LDEF as non-purgeable. As with the “normal” procedure, LNew specifies the resource id (128 in the example), and the toolbox ListManager manages the resource normally. Hex 4EF9 is a jump instruction, so the ListManager jumps to the real function. Your application only calls SetupLDEF once, even if the list handler will be used for several lists.

No Resource Needed

You don’t even need the degenerate 3 word version above. Instead, you can stuff the function address into the ListRecord after creating the list. While this technique seems to work without problems, it isn’t blessed by the Mac folk, so don’t complain when it stops working in some future release. The add_LDEF() function creates the fake handle -- call it just after you create the list. Be sure to call remove_LDEF() before deleting the list: otherwise, your program will surely crash!

Which should you use?

Each of the three methods has its own advantages and disadvantages:

• The fully-compiled method is perhaps only useful if you absolutely cannot have a visible LDEF resource: perhaps for security or anti-viral reasons. Before using it, you should remember that it isn’t “blessed” by the Macintosh interface people.

• The “fake-resource” callback method is probably the most useful for development: you can set breakpoints within the list handler. (By the way, the “fake-resource” technique is useful for other user-written handlers that the Toolbox assumes will be stored as resources.) It does require, however, that you make sure that the LDEF be kept memory-resident -- otherwise, you’ll have messy, hard to debug crashes.

• The “true-resource” method is best if you’re worried about memory space, since the Toolbox takes care of loading and unloading the resource. It has the significant disadvantage of being essentially impossible to debug without an assembly-language debugger.

If you’re not sure, I’d recommend using the “fake-resource” technique, making sure that the list handler is stored in a permanently-resident code segment.

The Sample Program

The sample program is not intended to show you how to write a Macintosh application. All it does is let you open a file and display any ICN# resources as a list. It has an interesting bug: to show that the list display function (in IconicLDEF.c) can access the application’s globals, the code references a flag that allows displaying the cell’s contents either as an icon or as the icon’s value. If you switch between the two modes with several partially-obscured windows on the screen, you’ll note that the Macintosh efficiently -- but incorrectly --calculates what needs to be redrawn, and some icons will be displayed partially in one form and partially in the other. This is an easy bug to fix, but I left it in to warn you about the problems of using application-wide globals where a document-specific (or window-specific) variable would be better.

When reading the source of the application and list handler, note that they are conditionally-compiled to operate in all three modes. The projects are, of course, different:

• CompiledDemo.Π

CompiledDemo.c

CompiledLDEF.c

IconicLDEF.c

MacTraps

no resource file.

• FakeResource.Π

FakeDemo.c

FakeLDEF.c

IconicLDEF.c

MacTraps

FakeDemo.rsrc built from FakeDemo.r

• RealResource.Π

RealDemo.c

Iconic LDEF.c

MacTraps

RealResource.rsrc, built from RealLDEF.Π

RealLDEF.Π

RealLDEF.c

MacTraps

If you just type in the listing, you’ll get the “fake-resource” variant.

Acknowledgements

The ListManager is described in Inside Macintosh, Volume IV. Thanks to Amanda Walker, InterCon Corp. for posting the technique of calling an application-specific drawing function from the list handler to Usenet.

Listing:  iconicLDEF.h

/* iconicLDEF.h  */
/*
 * Header file for the LDEF demo: the IconInfo structure
 * defines the contents of a list cell.  Also, define
 * the application global values.
 *
 * Copyright 1990 Martin Minow and MacTutor.
 */
#define NIL ((void *) 0)

typedef struct {
 Handle handle;
 unsigned short  number;
} IconInfo;

/*
 * This is just to demonstrate that we can access an
 * application global value from the LDEF handler.
 */
extern Boolean drawAsText;
!
codeexampleend!
codeexamplestart
Listing:  FakeDemo.c

/* ListDemo.c  */
/*
 *
 * Demo my homemade LDEF.  The program lets you open
 * a file and display all of the icons in it.  You
 * can’t do anything else, though it would be easy
 * to allow you to copy an icon to the clipboard.
 *
 * Copyright 1990 Martin Minow and MacTutor.
 */
#include “iconicLDEF.h”

#define FORMAT FAKE_RESOURCE/* Define  program */
/*
 * These values configure the demo program: that way
 * we only need to write one piece of code.
 */
#define COMPILED 0
#define FAKE_RESOURCE1
#define TRUE_RESOURCE2
#if FORMAT == FAKE_RESOURCE || FORMAT == TRUE_RESOURCE
#define LDEF_ID  128
#else
#define LDEF_ID  0 /* Start with Mac LDEF */
#endif
#define RESOURCE ‘ICN#’
#define iconSize 32/* Pixels per icon */
#define sBarWidth15/* For grow button */
#define iconCols  4
#define iconRows  4
#define hOffsetDelta 16   /* For multiple windows */
#define vOffsetDelta 0
#define hOffsetMax (hOffsetDelta * 10)
#define vOffsetMax (vOffsetDelta * 10)

/*
 * Menu organization
 */
enum Menus {
 MENU_Apple = 1,
 MENU_File= 256,
 MENU_Edit= 257
};

enum Apple_Menu {
 Apple_About = 1
};

enum File_Menu {
 File_Open= 1,
 File_Close,
 File_DrawAsText,
 File_Debug,
 Unused,
  File_Quit
};

#define width(r) ((r).right - (r).left)
#define height(r)((r).bottom - (r).top)

/*
 * All the information about a document
 * is stored here.  Note that, when the
 * toolbox selects a window, we can
 * immediately recover the document.
 */
typedef struct {
 WindowRecord  window;
 ListHandle list;
} DocumentRecord, *DocumentPtr;
/*
 * The current window is always stored in a local
 * WindowPtr variable named “window.”  If it’s ours,
 * we can access the document by casting window to
 * DocumentPtr and de-referencing it.
 */
#define DOC (*((DocumentPtr) window))

/*
 * isOurWindow is TRUE if its argument is our document.
 */
#define isOurWindow(window) (  \
 (window) != NIL  \
 && ((WindowPeek) (window))->windowKind == userKind \
  )

MenuHandleapple_menu;
MenuHandlefile_menu;
Boolean drawAsText;/* For iconicLDEF()  */
inthOffset, vOffset;

void    main(void);
Boolean do_mouse(EventRecord);
Boolean handle_events(void);
void    do_command(long);
void    setup(void);
void    open_document(void);
void    close_document(WindowPtr);
Boolean new_document(void *, int);
Boolean initialize_list(WindowPtr);
void    read_icons(WindowPtr, int);

#if FORMAT == FAKE_RESOURCE
void    setup_LDEF(int);
#endif
#if FORMAT == COMPILED
void    add_LDEF(ListHandle);
void    remove_LDEF(ListHandle);
#endif
void    iconicLDEF();

/*
 * main()
 * Initialize the program and run the event loop.
 */
void
main()
{
 EventRecordevent;
 WindowPtrwindow;
 GrafPtrsave_port;
 Rect   box;

 setup();
 for (;;) {
 SystemTask();
 while (GetNextEvent(everyEvent, &event)
  && event.what != nullEvent) {
 if (event.what == activateEvt
  || event.what == updateEvt)
   window = (WindowPtr) event.message;
 else {
 window = FrontWindow();
 }
 switch (event.what) {
 case mouseDown:
 do_mouse(event);
 break;
 case activateEvt:
 if (isOurWindow(window)) {
 SetPort(window);/* Or InvalRect crashes! */
 LActivate(
   event.modifiers & activeFlag,
   DOC.list
 );
 /*
  * For some reason, LActivate doesn’t redraw
  * the scroll bars.  The correct solution
  * is left as a puzzle for the reader.
  */
 if (event.modifiers & activeFlag) {
 ControlHandle handle;
 Rect   box;
 
 handle = (**DOC.list).vScroll;
 if (handle != NIL) {
 box = (**handle).contrlRect;
 InvalRect(&box);
 }
 }
 
 } 
 break;
 case updateEvt:
 if (isOurWindow(window)) {
 GetPort(&save_port);
 SetPort(window);
 BeginUpdate(window);
 EraseRect(&window->portRect);
 box = (**DOC.list).rView;
 InsetRect(&box, -1, -1);
 FrameRect(&box);
 LDoDraw(TRUE, DOC.list);
 LUpdate(window->visRgn, DOC.list);
 EndUpdate(window);
 SetPort(save_port);
 }
 break;
 default:
 break;
 }
 }
 }
}

/*
 * do_mouse(event)
 * Process a mouse button press, calling handlers as
 * needed.
 */
static Boolean
do_mouse(event)
EventRecord event;
{
 WindowPtrwindow;
 register int  which_part;
 Rect   box;
 int    item;
 Point  mouse;
 int    result;
 long   new, choice;
 Str255 name;
 GrafPtrsave_port;
 
 which_part = FindWindow(event.where, &window);
 switch (which_part) {
 case inDesk:
 SysBeep(2);
 break;
 case inMenuBar:
 choice = MenuSelect(event.where);
 item = LoWord(choice);
 switch (HiWord(choice)) {
 case MENU_Apple:
 GetItem(apple_menu, item, &name);
 if (item == Apple_About)
 SysBeep(10);  /* No List About */
 else {
 GetPort(&save_port);
 OpenDeskAcc(name);
 SetPort(save_port);
 }
 break;
 case MENU_File:
 window = FrontWindow();
 switch (item) {
 case File_Open:
 open_document();
 break;
 case File_Close:
 close_document(window);
 break;
 case File_Debug:
 Debugger();
 break;
 case File_DrawAsText:
 drawAsText = !drawAsText;
 CheckItem(file_menu, File_DrawAsText, drawAsText);
 if (isOurWindow(window))
 InvalRect(&(*window).portRect);
 break;
 case File_Quit:
 ExitToShell();
 }
 default:
 break;
 }
 HiliteMenu(0);
 break;
 case inDrag:
 box = screenBits.bounds;
 box.top += GetMBarHeight();
 InsetRect(&box, 4, 4);
 DragWindow(window, event.where, &box);
 break;
 case inContent:
 if (FrontWindow() != window)
 SelectWindow(window);
 else {
 SetPort(window);
 if (isOurWindow(window)) {
 mouse = event.where;
 GlobalToLocal(&mouse);
 result = LClick(mouse, event.modifiers, DOC.list);
 (void) LLastClick(DOC.list);
 }
 }
 break;
 case inGoAway:
 if (isOurWindow(window)
  && TrackGoAway(window, event.where))
 close_document(window);
 break;
 }
 return (FALSE);
}

/*
 * open_document()
 * Ask for a file (allow all files).  Open its resource
 * fork (if possible).  If we succeed, create a new
 * window and look for all ICN# resources.
 */ 
void
open_document()
{
 SFReplyreply;
 int    file;
 static Point    where = { 85, 85 };

 SFGetFile(
 where, /* Where on the screen*/
 NIL,   /* Unused*/
 NIL,   /* no file filter */
 -1,    /* Allow all file types    */
 NIL,   /*   thus no typeList */
 NIL,   /* no dialog hook */
 &reply /* reply goes here*/
 );
 if (reply.good) {
 SetVol(NIL, reply.vRefNum);
 SetCursor(*GetCursor(watchCursor));
 if ((file = OpenResFile(reply.fName)) == -1)
 SysBeep(10);  /* No resource fork  */
 else {
 if (new_document(reply.fName, file) == FALSE)
 SysBeep(10);  /* No memory  */
 CloseResFile(file);
 }
 SetCursor(&arrow);
 }
}

/*
 * close_document()
 * Close the document in the current (front) window.
 * Dump the handles that were stored in the list’s cells.
 */
void
close_document(window)
WindowPtr window;
{
 IconInfo iconInfo;
 short  size;
 Cell   cell;

 if (isOurWindow(window) == FALSE)
 Debugger();
 SetCursor(*GetCursor(watchCursor));
 /*
  * Iterate over all cells in the list.
  */
 cell.h = cell.v = 0;
 do {
 size = sizeof iconInfo;
 LGetCell(&iconInfo, &size, cell, DOC.list);
 if (size == sizeof iconInfo) /* Non-empty cell? */
 DisposHandle(iconInfo.handle);
 } while (LNextCell(TRUE, TRUE, &cell, DOC.list));
#if FORMAT == COMPILED
 remove_LDEF(DOC.list);
#endif
 LDispose(DOC.list);
 CloseWindow(window);
 DisposPtr(window);
 SetCursor(&arrow);
}

/*
 * setup()
 * One-time initialization.
 */
void
setup()
{
 InitGraf(&thePort);
 InitFonts();
 FlushEvents(everyEvent, 0);
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs(NIL);
 InitCursor();
 MaxApplZone();
 apple_menu = NewMenu(MENU_Apple, “\p\024”);
 file_menu = NewMenu(MENU_File, “\pFile”);
 AppendMenu(apple_menu, “\p(No List Demo About;(-”);
 AddResMenu(apple_menu, ‘DRVR’);
 AppendMenu(file_menu,
 “\pOpen\311/O;Close;Draw As Text;Debug/.;(-;Quit/Q”);
 InsertMenu(apple_menu, 0);
 InsertMenu(file_menu, 0);
 DrawMenuBar();
#if FORMAT == FAKE_RESOURCE
 setup_LDEF(LDEF_ID);
#endif
 if (new_document(“\pList Demo”, -1) == FALSE) {
 SysBeep(10);
 ExitToShell();
 }
}

/*
 * new_document()
 * Build a document: get memory for the WindowRecord and
 * our attached information.  Offset the window with
 * respect to other windows and make the window.  If
 * this succeeds, initialize the document’s list.  If
 * that succeeds, read the icons.
 */
Boolean
new_document(title, resFile)
void    *title;  /* Pascal string */
intresFile; /* Open resource file, if any */
{
 WindowPtrwindow;
 DocumentPtrdoc;
 Rect   box;
 static longsequence;/* Identify windows */
 
 doc = (DocumentPtr) NewPtr(sizeof (DocumentRecord));
 if (doc == NIL)
 return (FALSE);
 /*
  * Locate the window and get its shape.  This could
  * probably be done better.
  */
 box.left = 0;
 box.top = GetMBarHeight() * 2;
 box.right = box.left
 + (iconSize * iconCols)
 + sBarWidth
 + 2;
 box.bottom = box.top
 + (iconSize * iconRows)
 + 2;
 OffsetRect(&box, hOffset, vOffset); 
 if (box.bottom > screenBits.bounds.bottom
  || box.right > screenBits.bounds.right) {
   OffsetRect(&box, -hOffset, -vOffset);
   hOffset = 0;
   vOffset = 0;
 }
 hOffset += hOffsetDelta;
 if (hOffset >= hOffsetMax)
 hOffset = 0;
 vOffset += vOffsetDelta;
 if (vOffset >= vOffsetMax)
 vOffset = 0;
 window = NewWindow(
 doc,   /* Allocated storage */
 &box,  /* Display Rect    */
 title, /* Title  */
 TRUE,  /* Visible on creation */
 noGrowDocProc,  /* Window type     */
 -1L,   /* Show in front   */
 TRUE,  /* GoAway box */
 ++sequence /* RefCon(debug only) */
 );
 if (window == NIL) {
 DisposPtr(doc);
 return (FALSE);
 }
 if (initialize_list(window) == FALSE) {
 CloseWindow(window);
 DisposPtr(doc);
 return (FALSE);
 }
 SetPort(window);
 TextFont(applFont);
 TextSize(9);
 read_icons(window, resFile);
 return (TRUE);
}

/*
 * initialize_list()
 * Build a list whose cells will hold our icon records.
 * If our LDEF is completely compiled, call add_LDEF
 * after creation.
 */
Boolean
initialize_list(window)
WindowPtr window;
{
 int    type;
 Handle handle;
 int    *jump;
 Rect   box;
 Point  cell;
 Rect   dimension;
 
 box = (*window).portRect;
 InsetRect(&box, 1, 1);  /* Room for frame */
 box.right -= sBarWidth;
 SetPt(&cell, iconSize, iconSize);
 box.bottom =
 box.top + (height(box) / cell.v) * cell.v;
 box.right =
 box.left + (width(box) / cell.h) * cell.h;
 SetRect(&dimension, 0, 0, box.right / cell.h, 0);
 DOC.list = LNew(
 &box,  /* Display rectangle*/
 &dimension,/* Shape (rows, cols)  */
 cell,  /* Cell shape on screen  */
 LDEF_ID, /* List handler, if any  */
 window,/* The window*/
 TRUE,  /* Drawing’s ok   */
 FALSE, /* No grow box    */
 FALSE, /* No horizontal scroll  */
 TRUE   /* Vertical scroll*/
 );
 if (DOC.list == NIL)
 return (FALSE);
 (**DOC.list).selFlags = lOnlyOne;
#if FORMAT == COMPILED
 add_LDEF(DOC.list);
#endif
 (**DOC.list).refCon = (long) iconicLDEF;
 return (TRUE);
}

/*
 * read_icons()
 * Fill the list with the icon handles and resource ids.
 */
void
read_icons(window, resFile)
WindowPtr window;
intresFile;
{
 int    n_icons;
 int    i;
 int    n_rows, n_cols;
 Cell   cell;
 ResTypetype;
 IconInfo iconInfo;
 Str255 name;
 
 LDoDraw(FALSE, DOC.list);
 if (resFile != -1) {
 UseResFile(resFile);
 n_icons = Count1Resources(RESOURCE);
 }
 else {
 n_icons = CountResources(RESOURCE);
 }
 n_cols = (**DOC.list).dataBounds.right;
 n_rows = (n_icons + (n_cols - 1)) / n_cols;
 /*
  * Note that we can have empty cells in the last row.
  * The drawing routine must check for this case.
  */
 if (n_rows > 0)
 LAddRow(n_rows, 0, DOC.list);
 for (i = 0; i < n_icons; i++) {
 if (resFile != -1)
 iconInfo.handle = Get1IndResource(RESOURCE, i + 1);
 else {
 iconInfo.handle = GetIndResource(RESOURCE, i + 1);
 }
 if (iconInfo.handle == NIL)
 iconInfo.number = -1;
 else {
 GetResInfo(
 iconInfo.handle, &iconInfo.number, &type, name);        
 DetachResource(iconInfo.handle);
 }
 cell.v = i / n_cols;
 cell.h = i % n_cols;
 LSetCell(&iconInfo, sizeof iconInfo, cell, DOC.list);
#if 0   /* Debug: watch the icons as they’re read in           */
 {
 Rect   rect;
 SetRect(&rect, 1, 1, 33, 33);
 PlotIcon(&rect, iconInfo.handle);
 }
#endif
 }
 LDoDraw(TRUE, DOC.list);
 InvalRect(&(**DOC.list).rView);
}
Listing:  FakeLDEF.c

/* LDEF Resource.c */
/*
 * Copyright © 1989, 1990 Martin Minow and MacTutor.
 *
 * You may use this software in any application and
 * redistribute this source without restriction as long
 * as this copyright and permission notice remains intact
 * and the source is not redistributed for profit and you
 * assume all responsibility for the proper operation of
 * this software.
 *
 * Written in Think C.  Set Tabs every 2 characters.
 */
#define FORMAT FAKE_RESOURCE
#ifdef DOCUMENTATION

Usage

 void   /* COMPILED only  */
 add_LDEF(list)  /* ...   */
 ListHandle list;/* ...   */
 
 void   /* COMPILED only  */
 remove_LDEF(list) /* ... */
 ListHandle list;/* ...   */
 
 void   /* FAKE_RESOURCE only */
 setup_LDEF(id)  /* ...   */
 int    id; /* ... */
 
User-provided function:

 void
 my_draw_function(
 Rect *lRrect,   /* Drawing rectangle*/
 Cell  lCcell,   /* Cell to redraw */
 short lDataOffset, /* Offset to cell to redraw */
 short lDataLen,  /* Length of cell’s data */
 ListHandle lHandle/* The list handle */
 )

 Note: this is called using C calling conventions --
 mostly because I couldn’t convince Think C to compile
 it as a pascal function.
 
Description

 Initialize your list as follows:
 
 setup_LDEF(resource_id); /* FAKE_RESOURCE only */
 resource_id = 0;/* COMPILED only */
 resource_id = <id>; /* FAKE_ or TRUE_RESOURCE */
 TextFont( ... );/* Font of your choice */
 TextSize( ... );/* Whatever you choose */
 myList = LNew(
 &box,  /* Display dimensions */
 &dimension,/* Shape (rows, cols) */
 cell,  /* Cell shape on screen */
 resource_id,    /* List func, if any */
 dialog,/* The window */
 FALSE, /* Don’t draw yet  */
 FALSE, /* No grow box     */
 FALSE, /* no horizontal scroll */
 TRUE   /* Vertical scroll */
 );
 add_LDEF(myList); /* COMPILED only */
 (**myList).refCon = my_draw_function;

 Now, whenever the list manager needs to draw something,
 the LDEF handler function will be called.  If the list
 refCon is zero, the LDEF handler operates identically
 to the standard, except that it preserves font and font
 size information.  This is all you need if you wish to
 draw a text list in a dialog using other than the system
 font.
 
 If the refCon is set to a user function, the function
 will be called after the following initialization has
 been completed:
 
 • The pen is “normal” and positioned properly to draw
   the text.
 • The cell to be drawn is locked.
 • The drawing rectangle is erased.
 • The font and font size are set to values in the list’s
   port.
  
 The simplest user function need only draw the cell:
 
 DrawText(*((**lHandle).cells), lDataOffset, lDataLen);
 
 A more complicated user function may get the cell’s
 contents (using LGetCell) and perform some function
 based on that information.
 
 If you have compiled the LDEF function, be sure to call
 remove_LDEF() before exiting: otherwise, your program
 will crash:
 
 remove_LDEF(myList);/* COMPILED only */
 LDispose(myList);
 
Author

 Martin Minow
 
 Thanks to Amanda Walker, InterCon Corporation,
 for the call-back idea.

#endif

/*
 * These values configure the demo program: that way
 * we only need to write one piece of code.
 */
#define COMPILED 0
#define FAKE_RESOURCE1
#define TRUE_RESOURCE2
#include <Color.h>
#define NIL 0
typedef short  word;
/*
 * The current ListHandle is always in local variable list.
 */
#define LIST(**list)

/*
 * This structure defines the fake LDEF resource.
 */
typedef struct {
 word instruction;
 void (*function)();
} LDEF_record, *LDEF_pointer, **LDEF_handle;

/*
 * Externally visible functions.
 */
#if FORMAT == FAKE_RESOURCE
void    setup_LDEF(int);
#endif
#if FORMAT == COMPILED
void    add_LDEF(ListHandle);
void    remove_LDEF(ListHandle);
#endif
#if FORMAT == TRUE_RESOURCE
pascal void main(
 int, Boolean, Rect *, Cell, int, int, ListHandle);
#else
static pascal void myListDef(
 int, Boolean, Rect *, Cell, int, int, ListHandle);
#endif

/*
 * Define the type of the callback function. Amanda Walker
 * calls this “the cast from hell”, and with good reason.
 */
typedef void (* FUNC)(Rect *, Cell, word, word, ListHandle);

#if FORMAT == COMPILED
/*
 * Call this after calling LNew for any list that is to
 * use this list definition routine.  It creates a handle
 * and fills it with enough code to jump to myListDef.
 * Note that we do not use a LDEF resource.
 */
void
add_LDEF(list)
ListHandlelist;
{
 LDEF_handleldef;
 
 ldef = (LDEF_handle) NewHandle(sizeof (LDEF_record));
 if (ldef != NIL) {
 (**ldef).instruction = 0x4EF9;  /* JMP instruction */
 (**ldef).function = myListDef;
 LIST.listDefProc = (Handle) ldef;
 }
}

/*
 * Be sure to call this before deleting the list.
 * Otherwise, you’ll have random program crashes.
 */
void
remove_LDEF(list)
ListHandlelist;
{
 LIST.listDefProc = NIL;
}
#endif

#if FORMAT == FAKE_RESOURCE
/*
 * Call this once when your application starts if it uses
 * the list definition function.  You only need to call it
 * once, even if several lists use this function.
 */
void
setup_LDEF(id)
intid;
{
 LDEF_handleldef;
 
 ldef = (LDEF_handle) Get1Resource(‘LDEF’, id);
 if (ldef != NIL
  && GetHandleSize(ldef) == sizeof (LDEF_record)) {
 (**ldef).instruction = 0x4EF9;
 (**ldef).function = myListDef;
 HNoPurge(ldef);
 }
}
#endif

/*
 * myListDef() is called by the Macintosh list manager.  It
 * is identical to the standard function, except that it
 * preserves font and size and may call a user function
 * for strange data formatting.
 */
#if FORMAT == TRUE_RESOURCE
pascal void main
#else
static pascal void myListDef
#endif
 (message, select, rect, cell, offset, length, list)
intmessage; /* List manager action  */
Boolean select;  /* TRUE if cell is to be selected */
Rect    *rect;   /* Rectangle to draw cell in */
Cell    cell;    /* The selected cell */
intoffset;/* Start of data in the list */
intlength;/* Number of bytes to draw */
ListHandlelist;  /* The list itself.  */
{
 int    old_font;
 int    old_size;
 FontInfo info;
 Point  where;
 int    lock_state;
 long   saved_A5;
 GrafPtrold_port;
 
 /*
  * This is needed so the drawing code can find the
  * application globals.
  */
 saved_A5 = SetCurrentA5();
 /*
  * If we’re compiled, we don’t have valid QuickDraw
  * globals (such as thePort), so we use the current
  * port information from the ListRecord.
  */
 GetPort(&old_port);
 SetPort(LIST.port);
 old_font = LIST.port->txFont;/* Save the old */
 old_size = LIST.port->txSize;/* font and size */
 /*
  * Editorial note: ‘--’ is the C decrement operator,
  * not the typeographer’s “long dash”.
  */
 if (message-- == 0) {    /* lInitMsg */
 /*
  * Initialization: save indentation.  Note: do not
  * touch select, rect, cell, offset, or length.
  */
 GetFontInfo(&info);
   LIST.indent.v = info.ascent;
   LIST.indent.h = 4;/* Arbitrary */
 }
 else if (message-- == 0) { /* lDrawMsg */
 where = topLeft(*rect);
 AddPt(LIST.indent, &where);
 MoveTo(where.h, where.v);
 PenNormal();
 lock_state = HGetState(LIST.cells);
 HLock(LIST.cells);
 EraseRect(rect);
 TextFont((LIST.port)->txFont);
 TextSize((LIST.port)->txSize);
 /*
  * We’re ready to roll.  If there’s a user-provided
  * function, call it.  Otherwise, just draw text.
  */
 if (LIST.refCon == NIL)
 DrawText(*(LIST.cells), offset, length);
 else {
 (*(FUNC) (LIST.refCon))
 (rect, cell, offset, length, list);
 } 
 HSetState(LIST.cells, lock_state);
 if (select)/* If selected */
 goto hilite;    /* go hilite it    */
 }
 else if (message-- == 0) { /* lHiliteMsg */
hilite:
 HiliteMode &= ~(1 << hiliteBit);  /* IM V-62 */
   InvertRect(rect);
 }
 TextFont(old_font);
 TextSize(old_size);
 SetA5(saved_A5);
}
Listing:  iconicLDEF.c

/* Iconic LDEF.c */
/*
 * All of the list-drawing nitty-gritty is here.
 * Each list cell contains an icon and the icon id.
 * Either draw the icon in the cell rectangle or convert
 * the icon id to hex and draw that string.
 *
 * Copyright © 1989, 1990 Martin Minow and MacTutor.
 */
#include “IconicLDEF.h”

void iconicLDEF(Rect *, Cell, short, short, ListHandle);
static void DrawHex(unsigned short, short);

/*
 * iconicLDEF() is called by the LDEF handler to draw
 * an icon whose resource ID is stored in the cell.
 */ 
void
iconicLDEF(rect, cell, offset, length, list)
Rect    *rect;   /* Rectangle to draw cell in */
Cell    cell;    /* The selected cell */
short   offset;  /* Start of data in the list */
short   length;  /* Number of bytes to draw */
ListHandlelist;  /* The list itself.  */
{
 IconInfo iconInfo;

 /*
  * Note that we ignore zero-length (empty) cells.
  */
 if (length == sizeof iconInfo) {
 LGetCell(&iconInfo, &length, cell, list);
 /*
  * Show we can access the global parameter.  Of
  * course, a “real” application would use a
  * document-specific data structure, probably
  * accessed via the document structure or window
  * refCon.  Using this global is actually incorrect
  * as partial window updates will leave a list cell
  * half in one format and half in the other.
  */
 if (drawAsText)
 DrawHex(iconInfo.number, sizeof (short) * 2);
 else {
 if (iconInfo.handle != NIL) {
 PlotIcon(rect, iconInfo.handle);
 }
 }
 }
}

/*
 * Recursive routine to draw a value in hex.
 * Each call of DrawHex outputs one nibble.
 */
static void
DrawHex(hex, size)
unsigned short   hex;
short   size;
{
 if (--size > 0)
 DrawHex(hex >> 4, size);
 hex &= 0x0f;
 DrawChar((hex >= 10) ? hex - 10 + ‘a’ : hex + ‘0’);
}
Listing:  FakeDemo.r

FakeResourceDemo.Π.rsrc
APPL????;; APPL, followed by your “signature”
Type LDEF = GNRL
, 128   ;; LDEF_Resource
.h
4EF9 0000 0000

 
AAPL
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

VMware Fusion 6.0.3 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more

Latest Forum Discussions

See All

Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Almost All of Playdek’s Library is on Sa...
Almost All of Playdek’s Library is on Sale Right Now, and You Should Check it Out Posted by Rob Rich on April 18th, 2014 [ permalink ] Playdek has released quite a few great iOS ports of board and card games over the years, and now most of them... | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »
Evernote Business Notebook by Moleskin I...
Evernote Business Notebook by Moleskin Introduced – Support Available in Evernote for iOS Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Free HopTo 2.2 Helps Enhance Your Productivit...
The HopTo app helps you do more on your iPad by providing more and easier adaccess to files and documents. Version 2.2 adds Egnyte and HopTo’s Mac OSX File Connector. If you already have the hopTo... Read more
National Distracted Driving Awareness Month:...
As the country recognizes National Distracted Driving Awareness Month, Sprint is reminding wireless consumers to focus on driving while behind the wheel, to not text or email while driving, and to... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
Abt has the 13″ 2.4GHz 128GB Retina MacBook Pro available for $1229 including free shipping. Their price is $70 off MSRP. Read more
iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more
Save up to $270 with Apple refurbished 13-inc...
The Apple Store has Apple Certified Refurbished October 2013 13″ Retina MacBook Pros available starting at $1099, with models up to $270 off MSRP. Apple’s one-year warranty is standard, and shipping... Read more

Jobs Board

*Apple* Automotive Parts Department position...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive, we Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.