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.

Reporter.P

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.

Scoping

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.

Summary

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    *}
{* ------------------------ *}
{********************************}

(****************************
 BUILD SEQUENCE

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; 

{----INTERFACE----}

INTERFACE

USES
 MemTypes, QuickDraw, OSIntf,
 ToolIntf, PackIntf, HyperXCmd,
 PrintTraps;


PROCEDURE EntryPoint(pPtr:XCmdPtr);

{----IMPLEMENTATION----}

IMPLEMENTATION

{$R-}   
CONST
 CARD   = TRUE;
 BKGND  = FALSE;
 NILCHAR= $00;
 CR= $0D; 
 TAB    = $09;
 SPACE  = $20;
 FF= $0C; 
 LINEFEED = $0A; 
 QUOTE  = $22; 
 COMMA  = $2C; 
 PERIOD = $2E;
 PAREN  = $28;
 
TYPE
 Str31 = String[31]; 

PROCEDURE Reporter(pPtr:XCmdPtr);FORWARD;

{----EntryPoint----}

PROCEDURE EntryPoint(pPtr: XCmdPtr);
BEGIN
 Reporter(pPtr);
END;


{----Reporter----}

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
***********************)
VAR
 done : BOOLEAN;
 wLen : INTEGER;
BEGIN
 done := FALSE;
 wLen := 0;
 
WHILE NOT done DO
BEGIN CASE wPtr^ OF

CR,FF,LINEFEED,NILCHAR:
 done := TRUE;
TAB:
 BEGIN
 WLen:=wLen+CharWidth( chr(SPACE) );
 done := TRUE;
 END;
 
 SPACE, QUOTE, COMMA, PERIOD: 
 BEGIN
 wlen:=wLen+CharWidth( chr(wPtr^));
 done := TRUE;
 wPtr:=Pointer( ORD(wPtr) +1);
 END;
 
OTHERWISE
 BEGIN
 WLen:=wLen+CharWidth( chr(wPtr^));
 wPtr := Pointer( ORD(wPtr) + 1 );
 END;
END; {*** CASE wPtr^ OF ***}
END; {*** WHILE NOT done ***}
 
IF wPtr^ = 0 THEN wPtr := NIL;
 
 CalcNextWord := wLen;
END;


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.
*
**********************)
VAR 
 done   : BOOLEAN;
 lineHite,
 wordSize : INTEGER;
 pageHite, 
 pageWidth: INTEGER;
 num    : INTEGER;
 cPos   : Ptr; 
 wPos   : Ptr;
 tPos   : Ptr;
 lineRect : Rect;
 fontInfo : FontInfo;
 
PROCEDURE EjectPage;
(****************************
* Eject the current page and 
* adjust the rectangle 
* accordingly
*
****************************)
BEGIN
 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 +
 fontInfo.leading;

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


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

PROCEDURE DrawLine;
(******************************
* Draw the current line please
******************************)
BEGIN
 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;
END;

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

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

 Hlock( hand );
 cPos := hand^;
 wPos := cPos;
 num  := 0;
 done := false;
 
 REPEAT
 tPos := wPos;
 
 CASE tPos^ OF
 LINEFEED, CR:
 BEGIN
 DrawLine;
 NewLine;
 wpos := tpos;
 END;
 
 FF:
 BEGIN
 EjectPage;
 wpos := tpos;
 lineRect.right := lineRect.right + wordSize;
 END;
 
 NILCHAR:
 BEGIN
 DrawLine;
 done := TRUE;
 END;
 
 OTHERWISE
 BEGIN
 wordSize := CalcNextWord( tPos );
 IF( wordSize + lineRect.right ) < pageWidth THEN
 BEGIN
 num := num + INTEGER( ORD(tPos) - ORD(wPos) );
 wPos := tPos;
 END
 ELSE
 BEGIN
 DrawLine;
 NewLine;
 END;
 lineRect.right:=lineRect.right + wordSize;
 END;
 
 END {** CASE ***};
 UNTIL done;
 
 PRClosePage( printer );
 HUnlock( hand );
END;



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

BEGIN
WITH pPtr^ DO
IF (paramCount <> 0) AND
(params[1] <> NIL) THEN 
BEGIN
 
PROpen;
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) 
THEN
 PRPicFile( prRecHandle, NIL, NIL, NIL, myStRec );

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

END.

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

end HyperChat
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.