Pattern Scroller
Volume Number: | | 6
|
Issue Number: | | 12
|
Column Tag: | | Pascal Procedures
|
Pattern Scroller
By Shelly Mendlinger, Brooklyn, NY
Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.
These programs are written in Borlands Turbo Pascal. Dont worry! Borlands implementation is straightforward and virtually straight out of Inside Macintosh (IM), Vol . I, II and IV. Perhaps the compiler directives need explanation.
{1}
{$D+} Turn on Generate Debug Symbols. Puts procedure names in the object
code.
{$R ResFileName } Define Resource File.
{$U-} Turn off Use Standard Units. Units PasInOut and PasConsole not
automatically complied.
PatternsScroller
PatternsScroller(fig. 1) creates a scrollable pattern list showing eight patterns at a time. Click in a pattern to select it. The selection is echoed in the test rectangle to prove the data has been correctly retrieved. This program came about by playing-I mean experimenting-with the List Manager Package(IM vol. IV) to solve a problem: give access the 38 patterns in the Systems PAT# resource while taking minimal screen space. Obviously, the MacPaint style of 2 rows of 19 patterns across the screen would not do. The solution is scrollable patterns. Showing several small squares of patterns and a scroll bar requires little screen area.
The two dozen or so routines of the List Manager handle the tedious chores of list maintenance and appearance such as drawing, storing and retrieving data, selecting, hiliting, scrolling, resizing, updating, activating. Quite an impressive list! PatternScroller utilizes the List Manager to manipulate non-text data(8-byte QuickDraw patterns). Since the default routines draw list data as text and invert to hilite selections, a new LDEF(List DEFinition) resource customized for patterns needs to be created. The second program, Pas_to_ResCode.LDEF, does this and writes the code to the specified resource file.
The Terminology
First, we discuss List Manager terminology. A list is a set of elements containing data of variable sizes. A cell is a screen rectangle that displays an elements data; its basic unit of the list interface. Cell is also a data type (the equivalent of type point) that describes a (screen)cells two dimensional position in the list. The first cell is in column one, row one (the top most, left most position) and has coordinates (0,0), actually the position of its top-left corner in the lists cell grid. To avoid confusion, remember a cells coordinates are (column - 1, row - 1). Be aware that some List Manager variables are in terms of cells and some in terms pixels. Hopefully, these will be clarified as we go through the subroutines of PatternScroller (Listing 2) in the order they are called.
Initialize: Initializes the usual managers and sets up a window to show the list. The Dialog Manager is not initialized and does not seem to be needed by the List Manager.
SetUpList: Calling LNew initiates the List Manager by loading in into memory and creating a list record data structure that includes the values passed in its nine parameters:
rView: Type rect. In local coordinates, the box in which the list is to be drawn. Its size determines the number of cells visible.
dataBounds: Type rect. In terms of cells, the initial dimensions of the list array. The first values are 0,0, the next two are the number of columns and rows of cells making up the list. Here its 38 columns across, 1 row down.
cSize: Type point. Holds the width and height in pixels of the basic cell. All cells in a given list have identical dimensions, no matter what the length of the data held.
theProc: Type integer. The ID of the LDEF resource to be used; the default ID = 0. Here its assigned the value of LDefNum, declared as a constant for easy changing.
theWindow: Type windowPtr. The window in which the list is to be drawn.
drawIt: if true, turns on the drawing routines(more on this later). Best to pass false until the list is complete or list building may be slowed.
hasGrow: If true, scroll bars will leave room for a growBox icon.
scrollHoriz, scrollVert: Draws and enables scroll bars for a list. Yes, its that easy! No coding for inUpPage, inUpbutton, ThumbsUp, Thumbsdown, click _held_down; the List Manager handles it all.
LNew returns a listhandle that is passed in all subsequent list routines. This new list, however, is empty, awaiting calls to LSetCell to add elements of data. This is accomplished with a handy little For loop that sets cell coordinates, accesses an indexed pattern and loads each cell with eight bytes of data. By the way, the at operator,@, returns a pointer to its operand, which can be a variable or a subroutine. Now the drawing routines are turned on via LDoDraw and the list is actually drawn on screen with LUpDate. A pattern is selected to start things off and the list is complete. Note totRect encloses rView and the scroll bar rectangle. totRect is used in the HandleEvent subroutine.
DoTestRect: Shows the opening pattern via ShowPat.
ShowPat: Displays the current pattern by calling LGetSelect to find the currently selected cell, then gets the pattern data by calling LGetCell. Note theCell is initially set to the first cell, (0,0), because LGetSelect returns in it the coordinates of the selected cell that is equal to or greater than the cell passed. Passing (0,0) ensures no cell will be overlooked.
HandleEvent: Handles two events, keydown and mousedown. Mousedown has the good stuff in the inContent case of FindWindow. If the click is in totRect(list rect + scroll rect), the current pattern is deselected. This is a two-step process: 1) the currently selected cell is returned in aCell by LGetSelect (see ShowPat), 2) false is passed as the first parameter of LSetSelect to deselect that cell. It is important to deselect before calling LClick or very strange hilite/unhilite things happen. LClick tracks the click, much as TrackControl does for controls. Scroll bar hits, drags and autoscrolling are all handled. The boolean result is true if a double-click occurs, both clicks in the same cell. (A fun exercise is to have a pattern editor pop up upon a double-click, ala MacPaint). Furthermore, if mousedown is in rView, i.e. in a pattern, the cell clicked in is determined with a call to LLastClick(which in Turbo returns type longint not type cell as stated in IM). That cell is assigned to aCell(the longint is cast to type cell) and then made the current selection via LSetSelect(first parameter := true). If the click is not in rView, it must be in the scroll bar, so aCell retains the value of the current selection, which is reselected. Finally, ShowPat is called to display the new selection.
The Source Code
Thats basically PatternScroller. To run it, First be sure to run Pas_to_ResCode(see below) to have a custom LDEF to call. When that is handled, choose Run(compile to memory and execute) from the Compile Menu to test out PatternScroller. Choosing To Disk from the Compile Menu will create a free-standing application. There are advantages to this. ResEdit can be used to see the LDEF as machine code(fig.2). When the Pascal environment is gone, some memory problems disappear. Its easier to debug, too, especially with the help of the D+ compiler directive. There is one peculiarity(bug?) within the LClickLoop routine of LClick. Upon a mousedown event, this routine is called to handle scroll bar hits, hiliting/unhiliting and autoscrolling until a mouseup event. When a click is dragged through patterns, each cell the cursor passes through is hilited then unhilited in turn. Upon release of the button, both the mousedown cell and the mouseup cell are hilited, although the lower cell is always selected. A more accurate interface would not change the selection if mouseup and mousedown were not in the same cell, and would unhilite the mouseup cell. But well save a custom ClickLoop routine for another project.
The second program, Pas_to_ResCode.LDEF (listing 2), writes code resources(res type WDEF, MDEF, CDEF, CDEV, etc.) to the named resource file. It is how I decided to answer a subtle challenge in IM: a definition procedure is usually written in assembly language, but may be written in Pascal. Sure, it can be written in Pascal, but how do you turn the text into a code resource? The neat part of this program is that the compiler converts the Pascal to machine language, which is then added to the res file. The machine code generated(fig. 2) this way starts with 4E56-LINK A6(create a stack frame for local variables) and winds up with 4E5E-UNLINK A6(dispose of stack frame), and lastly, 4ED0-JMP (A0) (JuMP to the return address in register A0). All very nice and tidy, although one wonders why the registers are not saved after linking and then restored before unlinking, as the Turbo manual states is standard entry and exit code. This may be nit-picking; the code works!
There are two important points in this program that warrant a closer look. First, the empty procedure Marker must immediately follow the procedure TheCode, because its address(@Marker) marks the end of TheCode. Address arithmetic is used to calculate theCodes size, which as CodeSize is passed to PtrToHand. This brings us to the second point. AddResource, the routine that writes data to a res file, requires that this data be in a relocatable block(IM vol I, The Resource Manager). As things stand, TheCode is locked in the heap with the rest of the program. Unlocking TheCode is accomplished by calling PtrToHand, which makes a relocatable copy of the data pointed to (@theCode), and returns a handle to this block. The handle is just what AddResource is waiting for.
List Manager
Now for List Manager specific stuff. LDEF, the list definition procedure governs the initializing, drawing, hiliting/unhiliting and closing of a list.
According to IM, the List Manager communicates with the procedure via the LMessage parameter(type integer), sending one of four possible values:
{2}
LInitMsg = 0, initialize list.
LDrawMsg = 1, draw cell.
LHiliteMag= 2, hilite/unhilite cell.
LCloseMsg = 3, close list.
According to IM, a separate routine should handle each operation represented by LMessage. In Pascal, the best approach is a case statement with LMessage as selector. Before looking at each routine, here are the other parameters passed by the List Manager to the definition procedure:
isSelect: Type boolean. True if a cell is selected.
cRect: Type rect. The local coordinates of the selected/deselected cells rectangle.
theCell: Type cell. The coordinates(in row and column) of the cell in question.
LDataOffSet: Type integer. The number of bytes into the lists data block that marks the start of theCells data.
LDataLen: Type integer. The length in bytes of theCells data. Here its eight bytes.
LHandle: Type listHandle. A handle to the list record.
Now the operation routines as they respond to each message:
LInitMsg: LNew sends this message after setting all default values in the list record. This initialize routine is used to change record settings, allocate private storage, etc. Here the selFlags field is changed so only one cell at a time is selected. The default setting offers all the selection possibilities found in a Standard File dialog window(like Font/DA Mover), with shift key extensions, dragging, etc. This routine is also a good place to draw a frame about the list.
LDrawMsg: Sent whenever a cell needs to be drawn. This is one half of the mysterious draw routines that gets turned off and on in the SetUpList procedure of PatternScroller. The first order of business is to change the ports clip region to cRect, the cells screen rectangle, as IM directs. Next, the pattern is accessed and drawn. Surprisingly, a problem developed accessing the pattern. Upon running PatternScroller, the System bombed when this routine had calls to GetPattern, GetIndPattern, BlockMove, even HLock! An exhaustive study was not done nor was there deep pondering as to the nature of the problem. (If you have a hint, please inform me!) Mercifully, the realization eventually hit that a data offset and a handle to a list record are passed for a reason. The way to the pattern is via the address of the data in the data block stored by the list, calculated by adding LDataOffSet to the pointer gotten by dereferencing the cells field(type DataHandle) of the list record. Now the pattern can be drawn inset from the cell rect, leaving room for a hilite frame(see below). Lastly, the ports original clip region is restored. Every visible cell is drawn this way.
LHiliteMsg: The other half of the drawing routines, the hilite routine has the same parameters as the draw routine. The ports clip region is handled the same way for insurance purposes. IM does not mention it, but with the similarity to the draw routine better safe than sorry. A 4x4 pixel black frame about a cell seems a clear way to hilite a pattern selection. Using pen mode Xor allows the luxury of disregarding the isSelect parameter. If the cell is not selected there is a white frame about its pattern, as initially drawn. If it is selected, the Xored frame is black. If deselected, an Xored black frame turns white. Nifty. This routine opens creative possibilities to hiliting non-text data, pictures could change, icons could be inverted, etc.
LCloseMsg: This message is sent by LDispose. If any private storage was allocated in the initialize routine, now is the time to dispose of it. This LDEF does not need a close routine.
Four messages, four suborutines, thats it!
Notice the call to CreateResFile is optional. After the first time or if theres an existing res file, comment out({ }) the call, the code will be added to the named file. As a rule, always change the resID constant with each refinement of a definition procedure. The Twilight Zone can spring up in the calling program when more than one instances of a res type have the same ID number. For this reason, Do Not Compile Pas_to_ResCode To Disk. An application has its info hard-wired, thus each run will add the res code with the same ID. Also, remember to change the resource ID in the calling program; dont get stuck with the same old routine.
This is the same reason there is a minor Mac interface to the program. As a courtesy, information is displayed. As a necessity, before calling AddReaource, the event loop awaits a positive action: keydown to quit, mousedown to proceed. This can avert potential disasters.
The List manager is a very handy tool for storing, updating and displaying data. For further information, see back issues of MacTutor (of course!) List Manager Inspires Help Function Solution, Vol. 3, No. 4 for one. Also, The Complete book of Macintosh Assembly Language Programming, Vol. II by Dan Weston (1987 Scott, Foresman, and Company, Glenview, IL.) has a very good chapter on the List Manager. Dont shy away because of assembly language. The text is so full of clear, useful info that the programming examples are secondary. Anyhow, as Mac assembly language programmers love to do, all Pascal routines out of IM commented into the source code, so its in Pascal anyway!
Through the LDEF procedure, you have complete control over a lists appearance and behavior. Other definition procedures offer the same control over other aspects of the interface. This means the power to fine tune your programs interface. And thats the way to real Mac creativity! So open IM and create a custom CDEF or WDEF with Pas_to_ResCode. You can add your own dot extension. Just be sure to change the constant RType to the appropriate type.
{$D+} {generate debug symbols}
Program PatternScroller;
{**** written and © 1989
*** by Shelly Mendlinger
**** Brooklyn, New York ***}
{$R PatList.RSRC} {identify res file}
{$U-} {No defaults. Well roll our own}
uses
memtypes, quickdraw, osintf, toolintf, packintf;
const
LdefNum = 1000;
title = PatternScroller ©1989 by Shelly Mendlinger;
var
Rview,
dBounds,
Wrect,
totRect,
testRect : rect;
cSize : point;
theCell : cell;
wind : windowPtr;
theList : listHandle;
thePat : pattern;
index,
dLen,
theProc : integer;
str : str255;
event : eventRecord;
aHand : handle;
aCell : cell;
over,
bool,
drawIt,
hasGrow,
scrollHoriz,
scrollVert : boolean;
Procedure ShowPat;
begin
{-- set vars --}
dLen := 8;
setPt(theCell,0,0);
{-- get current selection --}
bool := LGetSelect(true,theCell, theList);
{-- get cell data --}
LGetCell(@thePat,dLen,theCell,theList);
{-- show pat --}
fillrect(testRect,thePat);
framerect(testrect);
end;{proc show pat}
Procedure Initialize;
begin
{-- Let the Games Begin --}
initGraf(@thePort);
initFonts;
initWindows;
initCursor;
{-- open a window --}
setrect(wRect,10,50,500,330);
wind := newWindow(nil,wRect,title,true,0,
pointer(-1),true,0);
setPort(wind);
flushEvents(everyevent,0);
end;{proc init}
Procedure SetUpList;
begin
{-- set parameters --}
setRect(Rview,100,20,340,50);{drawing
area, local coords}
setrect(dBounds,0,0,38,1);{38 long, 1 high}
setPt(cSize,30,30);{30 X 30 pixel cells}
theProc := LDefNUm;{LDEF ID}
drawIt := false; {turn off drawing}
hasgrow := false; {no grow box}
scrollHoriz := true;{yes horiz scroll bar}
scrollVert := false; {no vert scroll}
{-- start things going --}
theList := LNew(Rview,dbounds,cSize,theProc,wind,drawIt,
hasGrow,scrollHoriz,scrollVert);
{-- fill cells with pat data --}
for index := 1 to 38 do
begin
setPt(theCell,index-1,0);
getIndPattern(thePat,sysPatListID,index);
LSetCell(@thePat,sizeof(pattern),theCell,thelist);
end;{for index}
{-- draw the list --}
LDoDraw(true,theList);
LUpdate(wind^.visRgn,theList);
{-- select starting pat --}
setPt(theCell,3,0);
LsetSelect(true,theCell,theList);
totrect := Rview;
totRect.bottom := totRect.bottom + 15;
{include scroll rect}
end;{proc Set up list}
Procedure doTestRect;
begin
setRect(testrect,100,100,340,250);
str:= Test Rect;
{-- center string --}
with testRect do
moveto(left+(right-left-stringWidth(str))
div 2,96);
drawstring(str);
Showpat;
end;{proc do Test Rect}
Procedure HandleEvent(evt : EventRecord);
var
aPt,
pt2 : point;
aRect,
oldRect : rect;
long : longint;
begin
aPt := evt.where;
{-- whats happining? --}
case evt.what of
keydown: over := true;{any key quits}
mousedown:
case findWindow(aPt,wind) of
inGoAway: over := true;{say bye-bye}
inContent: begin
setRect(oldRect,0,0,0,0);
globalToLocal(aPt);
{-- is click in list? --}
if ptInRect(aPt,totRect) then
begin
{- get current selection -}
setPt(theCell,0,0);
bool := LGetSelect(true, aCell,theList);
{-- deselect old cell --}
LSetSelect(false,aCell,theList);
{-- trach click --}
bool := LClick(aPt,
evt.modifiers, theLIst);
{- is click in a pattern -}
if ptInRect(aPt,Rview) then
begin
{-- get new cell --}
long :=LLastclick(theList);
aCell := cell(long);
end;{in pat}
{-- select/reselect cell --}
LSetSelect(true,aCell,theList);
ShowPat;
end;{in totRect}
end;{inContent}
otherwise
end;{case findwindow}
otherwise
end;{case what}
end;{proc handle event}
BEGIN {main}
Initialize;
SetUpList;
DoTestRect;
{-- do event loop --}
over := false;
repeat
if getNextEvent(everyEvent,event) then handleEvent(event);
until over;
{-- clean up --}
Ldispose(theList);
end.{prog PatternScroller}
Program Pas_to_ResCode_LDEF;
{**** © 1989 by Shelly Mendlinger ****}
{**** Brooklyn, New York ****}
uses
memtypes, quickdraw, osintf, toolintf, packintf;
const
resFile = PatList.rsrc;
RType = LDEF;
resID = 1000;
resName = PatList Def;
var
CodePtr : procPtr;
CodeHand : handle;
CodeSize : size;
oldResNum,
newResNum,
err : integer;
str : str255;
goAhead : boolean;
{*** This Proc is turned into res code *}
Procedure theCode(Message : integer;
isSelect : boolean;
cRect : rect;
theCell : cell;
LDataOffSet,
LdataLen : integer;
aList : Listhandle);
type
patPtr = ^pattern;
var
aPat : patPtr;
oldClip : rgnHandle;
hand : handle;
aRect : rect;
begin
{-- whats the story --}
case Message of
LInitMsg: {initialize the list}
begin
{-- select one cell at a time --}
aList^^.selFlags := LOnlyOne;
{-- frame the list --}
Pennormal;
aRect := aList^^.rView;
inSetRect(aRect,-1,-1);
framerect(aRect);
end;{init}
LdrawMsg: {draw theCell}
begin
{-- save ports cliprgn --}
oldclip := aList^^.port^.cliprgn;
{-- change ports cliprgn,
IM says so --}
rectRgn(aList^^.port^.cliprgn,cRect);
{-- calc cells data address --}
Hand := handle(aList^^.cells);
{handle to data}
aPat := patPtr(pointer(ord(hand^) + LDataOffSet));
{ptr to pat}
{-- draw pat & cell frame --}
framerect(cRect);
aRect := cRect;
inSetRect(aRect,5,5);
FillRect(aRect,aPat^);
FrameRect(aRect);
{-- restore ports clip --}
aList^^.port^.cliprgn := oldClip;
end;{draw}
LHiliteMsg: {hilite theCell}
begin
{-- same clip stuff as above --}
oldclip := aList^^.port^.cliprgn;
rectRgn(aList^^.port^.cliprgn,cRect);
{-- Xor a frame --}
pennormal;
penMode(patXor);
penSize(4,4);
aRect:= cRect;
inSetRect(aRect,-5,-5);
frameRect(cRect);
pennormal;
{-- clip stuff --}
aList^^.port^.cliprgn := oldClip;
end;{hilite}
otherwise
end;{case message}
end;{proc theCode}
{-- mark the end of theCode --}
Procedure Marker;
begin
end;{proc mark}
Procedure EventLoop;
var
evt : eventRecord;
GetOut : boolean;
begin
GetOut := false;
repeat
if getNextEvent(everyevent,evt) then
case evt.what of
{-- any key to quit --}
keyDown : GetOut := true;
{-- click to proceed --}
mouseDown : GoAhead := true;
otherwise
end;{case what}
until GetOut or GoAhead;
end;{proc eventloop}
Begin {main}
{-- address of theCode --}
CodePtr := @theCode;
{-- pointer math --}
CodeSize := size(ord(@Marker) -
ord(codePtr));
{-- get handle for AddResource --}
Err := PtrToHand(CodePtr, CodeHand,
CodeSize);
{-- handle error --}
if err <> noErr then
begin
numtoString(err,str);
str := OS ERROR GETTING HANDLE. # + str;
moveto(100,100);
drawstring(str);
end { error}
else
begin
goAhead := false;
{-- save current res fie --}
oldResNum := curResfile;
{-- draw interface --}
textfont(0);
textsize(18);
moveto(20,25);
drawstring(ANY KEY TO QUIT);
moveto(20,55);
drawstring(CLICK TO ADD RESOURCE);
str := Res File: + ResFile;
moveto(100,75);
drawstring(str);
str := Res Type: + RType;
moveto(100,95);
drawstring(str);
numtostring(ResID,str);
str := Res Id: + str;
moveto(100,115);
drawstring(str);
str := Res Name: + ResName;
moveto(100,135);
drawstring(str);
numtostring(CodeSize,str);
str := Code size: + str + bytes;
moveto(100,155);
drawstring(str);
EventLoop;
if GoAhead then
begin
{*** OPTIONAL ***}
createResFile(resFile);
{-- open s res file --}
newResNum := openResFile(ResFile);
{-- write to res file --} addResource(CodeHand,RType,resID,ResName);
{-- close selected res file }
closeresFile(newResNum);
{-- restore orig. res file }
useResFile(oldResNum);
end;{do it}
end;{else no err}
end.{prog pas to res code}