TweetFollow Us on Twitter

XCMD Printer
Volume Number:4
Issue Number:10
Column Tag:HyperChat®

XCMD Cookbook

By Donald Koscheka, Apple Computer

Print Manager Access

Printing may not come to mind as an area where writing an XCMD might be useful since HyperCard prints card reports. Perhaps you don’t like the reports that HyperCard prints out, or you want to set your own margins or draw borders around each field that’s printed out. XCMDs provide access to the ToolBox Print Manager, empowering you with the capability of performing custom printing in HyperCard. The Print Manager, then, becomes a good candidate for XCMD exploration.


This month’s XCMD, Reporter.P ( see Listing 1) is a simple text printer that you can adapt to your own needs or use as a template for further exploring Macintosh Printing. As always, we start with the XCMDBlockPtr as the interface to Hypercard. We pass a handle to the text in the first parameter. We could use the other parameters to pass formatting information. Parameter 2, for example, might be set to tell us to draw a border around the page. Parameter 3 might contain the margins in page coordinates.

The algorithm we use goes like this: Move to the top of the page and initialize a rectangle, lineRect, whose height is the height of the text to be printed and whose width is zero. Step through the text to be printed accumulating words (text separated by “white space” or punctuation). If the width of this word plus the width of linerect is less than the page width, add this line to the current line; otherwise, move down to the next line and add the current word to the start of the next line. If any part of the next line is below the bottom margin of the page, eject the page and reset lineRect’s top to the top of the page.


One of the nice features of writing XCMDs in Pascal is the scoping feature of procedures and functions. Pascal allows us to define procedures and functions within the main procedure, in this case, the procedure “Reporter”. This is useful because it allows the callbacks and the nested procedures to share reporter’s local variables. When we invoke a callback, we don’t need to pass the parameterBlocPointer. The callbacks can “see” this pointer as if it was a global data declaration. Another nice feature of writing XCMDs in Pascal is that we don’t have to be fussy about the entry point. The variable scoping simplifies the compiler’s job of resolving the entry point. In “C”, subroutines follow the main body of the XCMD so that the compiler can use the start of the main body as the entry point.

Step Through

Reporter first checks the parameter block pointer to determine whether enough parameters were passed. Params[1] should be a handle to some text to print. If the handle is NIL, we don’t have anything to print; otherwise, we open the printer driver, allocate a printer record handle (prRecHandle) and fill the record with the print defaults. If you wanted to allow the user to change the page style (e.g. page orientation), this is where you would invoke the printer’s style dialog. We’ll skip this step for now because we want the XCMD to print the document with a minimum amount of intervention from the user.

Next, we put up the job dialog which is the standard printing dialog that comes up when you select print from the menu. If PRJobDialog returns true, the user clicked the “OK” button and wants us to print the document.

PROpenDoc associates our printing with a grafport. This technique effectively hides the gritty details of printing from the application. As long as we draw to the grafPort returned by PROpenDoc, the underlying code will convert our QuickDraw commands to Postscript for the LaserWriter and to a ribbon-eating bitmap for the Imagewriter.

Once the grafport is opened, we open the first page of the document with the PROpenPage and call PrintHandle to print the text. PrintHandle manages the opening, closing and ejecting of successive pages so when it returns all we need to do is close down the printing port with the PrCloseDoc call. Understanding this routine will take you a long way to understanding the how this printing business works.

Once we’re done printing, we check to see if the document needs to be spooled out. Spooled files are saved to disk and printed by the call to PrPicFile. This statement insures compatibility with print spoolers that will be looking for picture files to print.

The actual printing is performed by the procedure PrintHandle. For the sake of argument, we set the font to nine point Geneva. A better approach would be to pass font information as a parameter to the XCMD. GetFontInfo tells us the height of the text since that will also be the height of a line on the page. We then calculate some rectangles and set the coordinates of our lineRect variable. Note that lineRect starts off at the top left of the page and has an initial width of 0. LineRect will expand to include the width of each word that we add to the line.

Locking down the text handle allows us to maintain pointers to the text. The first pointer, cpos, points to the current position in the text while wpos is used to point to the first character in the current word. A third pointer, tpos, is used as a “test pointer” and will remember the end of the current word.

The repeat loop in printhandle points tpos to the start of the next word (or the first character in the text if we’re just starting the loop). If tpos is currently pointing to a line termination character (e.g. carriage return), we print the current line, move to the next line and reset wpos to point to the next word. Form feeds are handled in a similar fashion except that we eject the current page before continuing.

If tpos points to the nilChar (the ASCII character whose value is 0), we’ve printed all of the text in the input stream so we print the line, eject the page and exit the loop.

The otherwise clause checks to see if the next word in the input will fit on the current line. If so, add the word to the line and update the pointers accordingly. Since tpos points to the end of the current word, setting wpos equal to tpos causes us to “leap” over that word.

If the word doesn’t fit on the line, we first print out the line and then move to the next line. After a word is “accumulated” into a line, we add the width of the word to the linerect.

The last routine of note, CalcNextWord, checks to see if the next character in the text is a word break character such as a space or punctuation. If so, we now have another word to add to the output line.


Reporter left justifies the text but you can easily add full justification. When you get to the end of the current line (i.e. wordsize + linerect > page width) calculate the number of pixels that would be needed to “fill” out the line. Subtract the current line’s width (right-left) from the page width. If the current line is 2000 pixels wide and the page rectangle is 2500 pixels, then the number of pixels needed to fill out the line is 500. Divide this number into the number of spaces on the line and call SpaceExtra to space out the text.

You’ll be surprised out how easy text formatting is with the Macintosh toolbox and I encourage you to use Reporter as a starting point for your explorations.

{* File: Reporter.p*}
{* *}
{* Prints the entire *}
{* contents of the container*}
{* *}
{* ------------------------ *}
{* In:  params[1] = handle  *}
{* to the text to be printed*}
{* *}
{* ------------------------ *}
{* © 1988, Donald Koscheka, *}
{* All Rights Reserved    *}
{* ------------------------ *}


pascal Reporter.p
link -m ENTRYPOINT -rt 
XCMD=6555 -sn Main=Reporter 
Reporter.p.o 
“{Libraries}”Interface.o 
“{PLibraries}”Paslib.o 
-o “{xcmds}”testxcmds


{$S Reporter }

UNIT Donald_Koscheka; 



 MemTypes, QuickDraw, OSIntf,
 ToolIntf, PackIntf, HyperXCmd,

PROCEDURE EntryPoint(pPtr:XCmdPtr);



 NILCHAR= $00;
 CR= $0D; 
 TAB    = $09;
 SPACE  = $20;
 FF= $0C; 
 QUOTE  = $22; 
 COMMA  = $2C; 
 PERIOD = $2E;
 PAREN  = $28;
 Str31 = String[31]; 



PROCEDURE EntryPoint(pPtr: XCmdPtr);


Function CalcNextWord(VAR wPtr:Ptr):INTEGER;
* Given a pointer to a 
* word, calculate the 
* length of the next word
* in the run.  The length
* is determined by adding
* the width  of each character
* together until a word
* break is hit.
* The difference between 
* tpos and wpos is always
* one word (including the 
* sticky characters)
* IN: Pointer to text 
*wPtr == pointer to NEXT word in
*run (or NIL if No next word)
* OUT:  Width of the next 
* word in the line
 done : BOOLEAN;
 wLen : INTEGER;
 done := FALSE;
 wLen := 0;

 done := TRUE;
 WLen:=wLen+CharWidth( chr(SPACE) );
 done := TRUE;
 wlen:=wLen+CharWidth( chr(wPtr^));
 done := TRUE;
 wPtr:=Pointer( ORD(wPtr) +1);
 WLen:=wLen+CharWidth( chr(wPtr^));
 wPtr := Pointer( ORD(wPtr) + 1 );
END; {*** CASE wPtr^ OF ***}
END; {*** WHILE NOT done ***}
IF wPtr^ = 0 THEN wPtr := NIL;
 CalcNextWord := wLen;

Procedure PrintHandle( hand : Handle; printer : TPPrPort; Prec : THPrint 
* Print the data passed 
* as a handle and 
* using the given printer
* port.
* Prints the data into 
* the current port and
* handles word wrap and
* page breaks.
 done   : BOOLEAN;
 wordSize : INTEGER;
 pageWidth: INTEGER;
 num    : INTEGER;
 cPos   : Ptr; 
 wPos   : Ptr;
 tPos   : Ptr;
 lineRect : Rect;
 fontInfo : FontInfo;
* Eject the current page and 
* adjust the rectangle 
* accordingly
 PrClosePage( printer );
 PrOpenPage( printer, NIL );
{*** Opening a new page yields***}
{*** a new grafport, reset it ***}
 TextFont( GENEVA );
 TextSize( 9 );
 GetFontInfo( FontInfo );
 lineHite := fontInfo.ascent +
 fontInfo.descent +

WITH Prec^^.prInfo.rpage DO
lineRect.Top   := top; +lineHite;
lineRect.Right := lineRect.left;
lineRect.bottom );
tpos := Pointer( ORD( tpos ) +  1 );

* Move to a new position on the
* page.
 WITH lineRect DO
 top  := top + lineHite;
 bottom := bottom + lineHite;
 MoveTo( left, bottom );
 IF bottom > pageHite THEN 
 Right := Prec^^.prInfo.rpage.left;

* Draw the current line please
 DrawText( cPos, 0, num );
 lineRect.Right := lineRect.left + wordSize;
 tpos := Pointer( ORD( tpos ) + 1 ); { debug }
 num := INTEGER( ORD(tPos) - ORD(wPos) );
 cPos := wPos;
 wPos := tPos;

{---- Reporter ----}
 TextFont( GENEVA );
 TextSize( 9 );
 GetFontInfo( FontInfo );
 lineHite := fontInfo.ascent + 
 fontInfo.descent + 

{*** get information about page ***}
 WITH Prec^^.prInfo.rpage DO
 pageHite := bottom - top;
 pageWidth  := right-left;  := top;
 lineRect.bottom:= top + lineHite;
 lineRect.left   := left;
 lineRect.right  := left;
 MoveTo( lineRect.left, lineRect.bottom );

 Hlock( hand );
 cPos := hand^;
 wPos := cPos;
 num  := 0;
 done := false;
 tPos := wPos;
 CASE tPos^ OF
 wpos := tpos;
 wpos := tpos;
 lineRect.right := lineRect.right + wordSize;
 done := TRUE;
 wordSize := CalcNextWord( tPos );
 IF( wordSize + lineRect.right ) < pageWidth THEN
 num := num + INTEGER( ORD(tPos) - ORD(wPos) );
 wPos := tPos;
 lineRect.right:=lineRect.right + wordSize;
 END {** CASE ***};
 UNTIL done;
 PRClosePage( printer );
 HUnlock( hand );

PROCEDURE Reporter(pPtr: XCmdPtr);
* Print the data that’s 
* passed in as a 
* parameter.
 fieldPtr : Ptr;
 fieldName: Str255;
 fieldType: BOOLEAN;
 fieldData: Handle;
 prRecHandle: THPrint;
 prPort : TPPrPort;
 myStRec: TPrStatus;
{$I }

IF (paramCount <> 0) AND
(params[1] <> NIL) THEN 
prRecHandle := THPrint(NewHandle( SIZEOF(TPRINT) ));
PrintDefault( prRecHandle );
IF PRJobDialog( prRecHandle ) THEN BEGIN
prPort := PROpenDoc( prRecHandle, NIL, NIL );
PrOpenPage( prPort, NIL );
PrintHandle( params[1], prPort, prRecHandle );
PrCloseDoc( prPort );
 IF(prRecHandle^^.prJob.bJDocLoop = bSpoolLoop) AND (PrError = noErr) 
 PRPicFile( prRecHandle, NIL, NIL, NIL, myStRec );

END; {*** IF PRJobDialog ***}
 DisposHandle(Handle(prRecHandle) );
END; {*** paramCount <> 0 ***}
pPtr^.returnValue := NIL;
END; {*** PROCEDURE Reporter ***}


Listing 1. Reporter.P - A text printing XCMD.

end HyperChat

Community Search:
MacTech Search:

Software Updates via MacUpdate

Google Drive 1.20 - File backup and shar...
Google Drive is a place where you can create, share, collaborate, and keep all of your stuff. Whether you're working with a friend on a joint research project, planning a wedding with your fiancé, or... Read more
Simon 4.0.3 - Monitor changes and crashe...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
Vitamin-R 2.23 - Personal productivity t...
Vitamin-R creates the optimal conditions for your brain to work at its best by structuring your work into short bursts of distraction-free, highly focused activity alternating with opportunities for... Read more
iDefrag 5.0.0 - Disk defragmentation and...
iDefrag helps defragment and optimize your disk for improved performance. Features include: Supports HFS and HFS+ (Mac OS Extended). Supports case sensitive and journaled filesystems. Supports... Read more
PCalc 4.2 - Full-featured scientific cal...
PCalc is a full-featured, scriptable scientific calculator with support for hexadecimal, octal, and binary calculations, as well as an RPN mode, programmable functions, and an extensive set of unit... Read more
FileZilla 3.10.2 - Fast and reliable FTP...
FileZilla (ported from Windows) is a fast and reliable FTP client and server with lots of useful features and an intuitive interface. Version 3.10.2: Note: Now requires a 64-bit Intel processor.... Read more
The Hit List 1.1.11 - Advanced reminder...
The Hit List manages the daily chaos of your modern life. It's easy to learn - it's as easy as making lists. And it's powerful enough to let you plan, then forget, then act when the time is right.... Read more
Bartender 1.2.32 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more
ClamXav 2.7.5 - Free virus checker, base...
ClamXav is a free virus checker for OS X. It uses the tried, tested, and very popular ClamAV open source antivirus engine as a back end. I hope you like and use ClamXav a lot and that it helps keep... Read more
xScope 4.1.2 - Onscreen graphic measurem...
xScope is powerful set of tools that are ideal for measuring, inspecting, and testing on-screen graphics and layouts. Its tools float above your desktop windows and can be accessed via a toolbar,... Read more

Dungeon Hunter 5 Coming on March 12
Gameloft has excitedly announced that Dungeon Hunter 5 is on its way! Once again, you will adventure across the land of Valenthia exploring dungeons and fighting monsters. The game will have a new asynchronous multiplayer mode called Strongholds... | Read more »
It Came From Canada: Jurojin: Immortal N...
At this point it’s pretty safe to say that no MOBA is going to dethrone Dota 2 and League of Legends anytime soon. After all, if Batman can’t do it, nobody can. However, with a genre as popular and profitable as this one, there’s still room for... | Read more »
Tiny Farm – Animals, Tractors and Advent...
Tiny Farm – Animals, Tractors and Adventures! Review By Amy Solomon on March 3rd, 2015 Our Rating: :: LIVELY LANDSCAPESUniversal App - Designed for iPhone and iPad Tiny Farm – Animals, Tractors and Adventures! includes farm-related... | Read more »
This Week at 148Apps: February 23-27, 20...
Final February Fun at 148Apps   How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you’re looking for. The ones we love become Editor’s Choice, standing out... | Read more »
GDC 2015 – Does Not Commute is Definitel...
GDC 2015 – Does Not Commute is Definitely a Game You Should Keep an Eye on Posted by Rob Rich on March 2nd, 2015 [ permalink ] We were teased about Mediocre Games’ (Smash Hit, | Read more »
F84 Games & POW! Announce Stan Lee V...
F84 Games has announced that it is working with legendary comic creator Stan Lee and POW! Entertainment to produce Stan Lee’s Hero Command. The game will be a action adventure of heroic proportions. | Read more »
Setlyst Keeps Your Set Straight So You C...
Setlyst Keeps Your Set Straight So You Can Focus On Rocking Out. Posted by Jessica Fisher on March 2nd, 2015 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Space is Vast, So Space Agency Has a Vas...
Space is Vast, So Space Agency Has a Vast New Update! Posted by Jessica Fisher on March 2nd, 2015 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Size DOES Matter Review
Size DOES Matter Review By Campbell Bird on March 2nd, 2015 Our Rating: :: HARD TO BEATUniversal App - Designed for iPhone and iPad This rhythm game has a unique control scheme and performance system that make it feel like a true... | Read more »
The first ever action 3D card battler Al...
On the other hand, you probably haven’t played an action 3D card battler – until now. Step forward, All Star Legion. All Star Legion is a 3D QTE-based action RPG card battler, but fear not – the game itself isn’t as convoluted as its description.... | Read more »

Price Scanner via

Another Tranche Of IBM MobileFirst For iOS Ap...
IBM has announced the next expansion phase for  its IBM MobileFirst for iOS portfolio, with a troika of new apps to address key priorities for the Banking and Financial Services, Airline and Retail... Read more
Sale! 15-inch Retina MacBook Pros for up to $...
B&H Photo has the new 2014 15″ Retina MacBook Pros on sale for up to $250 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $... Read more
WaterField Designs Introduces the Minimalist...
With Apple Pay gaining popularity, Android Pay coming in May 2015, and loyalty cards and receipts that can be accessed from smartphones, San Francisco’s WaterField Designs observes that it may be... Read more
Sale! 15-inch 2.2GHz Retina MacBook Pro for $...
 Best Buy has the 15″ 2.2GHz Retina MacBook Pro on sale for $1774.99 $1799.99, or $225 off MSRP. Choose free home shipping or free local store pickup (if available). Price valid for online orders... Read more
13-inch 2.5GHz MacBook Pro (refurbished) avai...
The Apple Store has Apple Certified Refurbished 13″ 2.5GHz MacBook Pros available for $170 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz... Read more
13-inch 2.5GHz MacBook Pro on sale for $100 o...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
27-inch 3.5GHz 5K iMac in stock today and on...
 B&H Photo has the 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available for... Read more
Apple Launches Free Web-Based Pages and Other...
Apple’s new Web-only access to iWork productivity apps is a free level of iCloud service available to anyone, including people who don’t own or use Apple devices. The service includes access to Apple... Read more
Survey Reveals Solid State Disk (SSD) Technol...
In a recent SSD technology use survey, Kroll Ontrack, a firm specializing in data recovery, found that while nearly 90 percent of respondents leverage the performance and reliability benefits of SSD... Read more
Save up to $600 with Apple refurbished Mac Pr...
The Apple Store is offering Apple Certified Refurbished Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more

Jobs Board

*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Pay Automation Engineer - iOS System...
**Job Summary** At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring passion and dedication to your job Read more
Sr. Technical Services Consultant, *Apple*...
**Job Summary** Apple Professional Services (APS) has an opening for a senior technical position that contributes to Apple 's efforts for strategic and transactional Read more
Event Director, *Apple* Retail Marketing -...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global engagement strategy and team. Delivering an overarching brand Read more
*Apple* Pay - Site Reliability Engineer - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.