TweetFollow Us on Twitter

File Package
Volume Number:1
Issue Number:7
Column Tag:MacPascal

Standard File Package, unpack & copy the bits

By Alan Wootton

Here is a program to view MacPaint documents from MacPascal (like “showpage”). I use the File Manager, the Standard File Package, the toolbox procedure UnPackBits, and QuickDraw’s CopyBits to display the image loaded in memory.

In MacTutor #5, Gary Palmer asked about loading MacPaint files in MacPascal. Well, I remembered once running across a description of MacPaint docs by Bill Atkinson. After some digging, I found the description in part of a mailing from tech support to developers dated Dec. 1983.

Atkinson explains that the resource fork is not used and that a 512 byte header precedes the packed bitmap data. The header is an array of patterns and some empty space. To simply view the picture we can ignore the header. The MacPaint ‘page’ is 720 lines of 72 bytes each. This is almost 51K and since we wish to load this into memory, a FatMac will probably be required. Atkinson gives a short routine to decode the data into a page. He uses UnpackBits, which is on page 7 of ToolBox Utilities.

Reading the data was a problem. I tried to use the file I/O routines provided with MacPascal. One must either read data byte-at-a-time, which takes forever, or, if you read large blocks, you can never get the last partially filled block. At this point I decided that Real Programmers use the low level File Manager routines. In other words PBOpen, PBRead, and then PBClose.

Another MacPascal shortcoming is the GetOldFile function. Once again, Real Programmers go straight past the limitations of the language and consult the bible (Inside Mac). We shall use the Standard File Package.

The Standard File Package

MacPascal’s function GetOldName will only select files of type TEXT. To select MacPaint docs it will be necessary to call the Standard File Package directly (OldPaintName in following program). On page 30 of Packages in “Inside Macintosh”, the procedure SFGetFile is described. To call it, use trap $A9EA, which is Pack3, and be sure to push a 2, the ‘selector’, on the stack last. You must type in the SFReply record on page 25. [For a complete description of SFReply, see the Assembly Column in this issue.] Since our type list will just be one type (PNTG) it will not be necessary to declare an array. Pass nil for filefilter and dlghook. There is an argument to pass a prompt string that Inside Mac says is historical only. I find that it works fine.

Low Level File Manager

The filecall interface in the following program simulates the PB calls of the File Manager. This is an example of the OS call I presented in MacTutor #6. [Please refer to issue #6 for details on calling OS routines from Pascal.] Before you can use the the PB routines, you must type the lengthy Parameter Block declarations. There are four variant parts to this record. I have only used the ioParam part here because that is all that was needed in this example. You should type the whole thing and save it somewhere for later use. Note that 8 bit types do not come out right, so one must take care that the declaration has the correct length. The routine descriptions (starting on page 31 of the File Manager) give a nice list of those parameters that must be set before calling (assembly programmers note: in some places ioRefNum is listed as 22, but the correct number is 24). You should carefully check that each parameter is set correctly before calling. The exception is ioCompletion, which can be ignored since we will be making synchronous calls. If ioNamePtr is not nil then the File Manager assumes that its value is the address of a string. This could badly mess up memory. In MacPascal, declared variables are cleared to 0’s so you can get away with this, but later, when you compile, nasty bugs pop up (this actually happened to me).

UnPackBits

UnPackBits is actually very simple. I have complicated things by not reading all the data into memory at once. The scheme used is to read 1024 bytes into memory (skipping the header) and when the first 512 bytes are used I slide the upper 512 bytes down and add 512 bytes onto the end. The program unpacks 72 bytes at a time for 720 lines. For faster operation you can unpack 4 lines at a time. Change 720 to 180 and 72 to 288.

After the page array is filled, it would be nice to take a look at it. Copybits is used to move the image onto the drawing window. The nice thing about copybits is that it will scale the image to fit. Simply setup a Quickdraw Bitmap record for page, set destrect to the desired size, and call copybits as shown. If you change 144 to 576 and 180 to 720 you can see the painting full size.

To write a MacPaint document (not done in this program) it is necessary to know the format of the header. The header is a 4 byte version number (default = 2) and then 38*8 = 304 bytes of patterns and then 204 unused bytes for a total of 512. However, Atkinson’s example writes 512 zeros for a header so I guess that would work. To pack the data you use the reverse of the unpack procedure. Things can be made simpler though because you can use one destination buffer and then write it out after every PackBits.

It is my contention that everything in Inside Mac can be demonstrated and used from MacPascal (except things like Vertical Retrace routines). If there is anything that you have trouble with and would like to see in MacTutor, write a letter to MacTutor and I will see if there isn’t a way to do it.


program Read_MacPaint_doc;{by Alan Wootton 4/85}
           { This program reads a MacPaint file and shows            
        the picture 1/4 size in Drawing }
 uses
  Quickdraw2;
 type
  ptr = ^integer;
  OStype = longint;

  SFReply = record { this is used by the standard file               
                           package, see Packages }
    good : integer;
    ftype : OSType;
    vrefNum : integer;
    version : integer;
    fname : string[63];
   end;

{ Parameter Block information contained in File Manager 
chapter of Inside Macintosh.  Note that MacPascal won’t do 8 bit fields 
right }

  ParamBlkPtr = ^ParamBlockRec;
  ParamBlockRec = record
{ data structure of File Manager }
    qLink : Ptr;
    qType : integer;
    ioTrap : integer;
    ioCmdAddr : ptr;
    ioCompletion : ptr;
    ioResult : integer;
    ioNamePtr : ^str255;
    ioVrefNum : integer;
{  case ParamBlkType of  ...  ioParam:  }
    ioRefNum : integer;
{       ioVersNum : byte;  }
    ioPermssn : integer;{ byte }
    ioMisc : ptr;
    ioBuffer : ptr;
    ioReqCount : longint;
    ioActCount : longint;
    ioPosMode : integer;
    ioPosOffset : longint;
   end;

  diskBlock = packed array[0..511] of char;

  paintPage = array[0..35, 0..719] of integer;
{  576*720 bitmap  = 72 bytes * 720 lines =  51,840           bytes }




 var
  reply : SFReply;{ used by OldPaintName, declared here              
                   to access vRefNum }
  filename : str255;
  fileblock : ParamBlockRec;
  buff : array[0..1] of diskblock;{ 1K }

  Page : paintPage;{ Huge variable, almost 52K  }

  srcPnt : ^diskBlock;
  destPnt : ^paintPage;

  lines, err : integer;

  curport : Grafptr;
  pageBits : bitmap;
  destRect : Rect;


{ common OS trap code, could be done with ‘Generic’ call}
{see MacTutor Vol. 1 No. 6 for assembly source code}
 function filecall (Pb : ParamBlkPtr;
         trap : integer) : integer;
  var
   access : array[0..12] of integer;
   d0, a0 : longint;
 begin
  stuffHex(@access, ‘2848548C41FA000C309F245F265F20522013FFFF224826804ED4’);
  a0 := ord(pb);
  inlineP($4E75, @d0, @a0, trap, @access);
  filecall := loword(d0);
 end;

{ The following File Manager calls work just like   }
{ those described in Inside Macintosh for the Lisa Pascal Workshop.  
}
{ Except that the async parameter is a dummy; all calls are sync }

 function PBOpen (Pb : ParamBlkPtr;
         async : boolean) : integer;
 begin
  PBOpen := filecall(pb, $A000);
 end;

 function PBClose (Pb : ParamBlkPtr;
         async : boolean) : integer;
 begin
  PBClose := filecall(pb, $A001);
 end;

 function PBRead (Pb : ParamBlkPtr;
         async : boolean) : integer;
 begin
  PBRead := filecall(pb, $A002);
 end;


{  same as OldFileName, only for MacPaint docs }
 function OldPaintName (prompt : str255) : str255;
  var
   where : point;
   typelist : longint;
 begin
  reply.good := 0;
  typelist := $504E5447;{ ‘PNTG’ }
  setPT(where, 100, 100);
  inlineP($A9EA, where, @prompt, nil, 1, @typelist, nil, @reply, 2);
{ $A9EA is pack3 ,  2 is SFGetFile, see Packages  }
  if reply.good <> 0 then
   OldPaintName := reply.Fname
  else
   OldPaintName := ‘’;
 end;


{  This procedure moves buff[1] down onto buff[0], adjusts srcPnt to 
point at it’s same data and tacks more data on end in buff[1].     }
 procedure Refill_Buffer;
 begin
  blockmove(@buff[1], @buff[0], 512);
  srcPnt := pointer(ord(srcPnt) - 512);
  fileBlock.ioBuffer := @buff[1];
  fileBlock.ioReqCount := 512;
  fileBlock.ioPosMode := 0;
  err := PBRead(@fileBlock, false);{ fill buff[1] }
 end;


begin { main }
 ShowDrawing;
 fileName := OldPaintName(‘ Select Painting to examine’);
 while filename <> ‘’ do
  begin
   fileBlock.ioVrefNum := reply.vrefnum;
   fileBlock.ioNamePtr := @fileName;
   fileBlock.ioPermssn := 1;{ read only, version number              
                                   is in upper byte and is 0 }
   fileBlock.ioMisc := nil;
   if PBOpen(@fileBlock, false) = 0 then
    begin
     refill_buffer;{  first block is skipped }
     refill_buffer;{   fill 1 }
     refill_buffer;{ 1 onto 0, refill 1 }

     srcPnt := @buff[0];{ <-- pointer to start of data }
     destPnt := @Page;{ <----  pointer to Page bitmap }

{------> This is the part that actually decodes the packed MacPaint data 
<------}
{ $A8D0 is UnPackBits, see page 7 in Toolbox Utilities   }
{ srcPnt and destPnt are updated by UnPackBits so use @}
     for lines := 1 to 720 do{ 720 lines in paint doc }
      begin
       inlineP($A8D0, @srcPnt, @destPnt, 72);
                                     { UnPackBits for 72 bytes }
       if ord(srcpnt) >= ord(@buff[1]) then
        Refill_Buffer; { if src no longer in buff[0] }
      end;{ of 720 lines }

     if PBClose(@fileBlock, false) <> 0 then
      writeln(‘close error’);

{  now show drawing  in current port  (drawing window) }
     GetPort(curPort);

 
{  set up bitmap record }
    pagebits.baseaddr := pointer(ord(@page));
    pagebits.rowbytes := 72;
    setRect(pagebits.bounds, 0, 0, 576, 720);

     setRect(destRect, 0, 0, 144, 180);
{ 144,180 =1/4 normal, image will be squashed to fit }

     copyBits(pagebits, curport^.portbits, pagebits.bounds,          
           destRect, srcCopy, nil);
     moveto(4, 190);
     drawstring(‘Click to open another MacPainting’);
     repeat
     until button;

    end;{ if no Open error }
   fileName := OldPaintName(‘ Select another Painting ?’);
  end;{ if name<>’’ loop }
end.
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Capture One 15.3.1 - RAW workflow softwa...
Capture One is a professional RAW converter offering you ultimate image quality with accurate colors and incredible detail from more than 400 high-end cameras - straight out of the box. It offers... Read more
Connect Fonts 23.0.3 - Font management s...
Connect Fonts is the creative professional's font manager. Every professional font manager should deliver the basics: spectacular previews, powerful search tools, and efficient font organization. You... Read more
CleanMyMac X 4.11.0 - Delete files that...
CleanMyMac X makes space for the things you love. Sporting a range of ingenious new features, CleanMyMac lets you safely and intelligently scan and clean your entire system, delete large, unused... Read more
Firefox 102.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
Hopper Disassembler 5.6.1 - Binary disas...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more
Skim 1.6.11 - PDF reader and note-taker...
Skim is a PDF reader and note-taker for OS X. It is designed to help you read and annotate scientific papers in PDF, but is also great for viewing any PDF file. Skim includes many features and has a... Read more
Alfred 4.6.7 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Transmit 5.8.7 - Excellent FTP/SFTP clie...
Transmit is an excellent FTP (file transfer protocol), SFTP, S3 (Amazon.com file hosting) and iDisk/WebDAV client that allows you to upload, download, and delete files over the internet. With the... Read more
Adobe Lightroom Classic 11.4.1 - Import,...
You can download Lightroom for Mac as a part of Creative Cloud for only $9.99/month with Photoshop, included as part of the photography package. The latest version of Lightroom gives you all of the... Read more
MarsEdit 4.5.9 - Quick and convenient bl...
MarsEdit is a blog editor for OS X that makes editing your blog like writing email, with spell-checking, drafts, multiple windows, and even AppleScript support. It works with with most blog services... Read more

Latest Forum Discussions

See All

Apple Arcade Weekly Round-Up: Major Upda...
Apple recently revealed July’s upcoming Apple Arcade releases in a new App Store Story, and this week’s new release is My Bowling 3D+ featuring offline and online multiplayer support, and more. It arrives from the developers of Pro Darts 2022+ and... | Read more »
Downhill Mountain Biking Game ‘Descender...
Just over three years ago in May of 2019 developer RageSquid and publisher No More Robots released a quirky downhill mountain biking game called Descenders on PC and Xbox One. Bemoaning a lack of “extreme sports" titles in recent years led RageSquid... | Read more »
SwitchArcade Round-Up: ‘Monster Hunter R...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for June 30th, 2022. Thursday is once more upon us, and that means a bunch of new releases to look at. We start things off with DLC for some very big games, Monster Hunter Rise and... | Read more »
‘HOOK 2’ Review – A Sharp Left Hook From...
The original HOOK ($1.99) had a very simple idea behind it. You were presented with a tangled mess of hooks and loops, and you needed to remove each one without snagging any others. Extremely simple at first, but as the puzzles rolled along,... | Read more »
‘Dicey Dungeons’ Mobile Version Launchin...
After a very long wait, Terry Cavanagh’s dungeon crawling roguelite deckbuiler hybrid experience Dicey Dungeons is coming to mobile platforms next week alongside a huge free DLC pack on all platforms. This DLC will be included in the mobile... | Read more »
Distract Yourself With These Great Mobil...
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
‘Danganronpa S: Ultimate Summer Camp’ is...
If you’ve been following Danganronp over the last few years, Spike Chunsoft celebrated its anniversary by bringing the series to mobile in the form of anniversary editions. After the first two released, there was a long delay for V3, but it finally... | Read more »
Out Now: ‘HOOK 2’, ‘Incoherence’, ‘Juras...
Each and every day new mobile games are hitting the App Store, and so each week we put together a big old list of all the best new releases of the past seven days. Back in the day the App Store would showcase the same games for a week, and then... | Read more »
Upcoming Mobile MMO RPG Shooter ‘Avatar:...
This past January a contingent of developers made up of Archosaur Games, Tencent, Lightstorm Entertainment, and Disney announced a new mobile game set in James Cameron’s Avatar universe titled Avatar: Reckoning. | Read more »
Culinary Platformer ‘Chefy-Chef’ Coming...
If your name is Chefy, it’s pretty much a given that you should be a chef. Such is the case with Chefy-Chef, a game from Bug Studio about a chef named Chefy who must travel to all sorts of exotic locations using a magical refrigerator in an effort... | Read more »

Price Scanner via MacPrices.net

July 4th sale at Verizon: Apple AirPods Pro f...
Verizon has Apple AirPods Pro on sale for $179.99 on their online store as part of their Fourth of July sale. Their price is $70 (28%) off Apple’s MSRP, and it’s among the lowest prices currently... Read more
Apple is now selling Certified Refurbished Ma...
Apple has added a full line of standard-configuration Mac Studios available in their Certified Refurbished section starting at only $1799 and ranging up to $400 off MSRP. Each Mac Studio comes with... Read more
Open-box 14″ M1 Pro MacBook Pros in stock tod...
QuickShip Electronics has open-box return Space Gray 14″ M1 Pro MacBook Pros in stock and on sale for $300-$450 off MSRP on their eBay store today. According to QuickShip, “The item in this listing... Read more
Can Being An iPhone User Really Determine Whe...
FEATURE: – If you’re traveling on the road today for the July 4th holiday, you might want to keep your Apple smartphone locked up inside the car’s glove compartment for your (and, everyone else’s)... Read more
2nd generation 4K Apple TVs with Siri remote...
Apple has restocked a full line of Certified Refurbished 2nd generation 32GB and 64GB 4K Apple TVs with Siri remotes for $30 off the cost of new models. Apple’s standard one-year warranty is included... Read more
Back in stock: Apple Watch Series 7 models fo...
Apple has restocked Certified Refurbished Apple Watch Series 7 WiFi-only models in their online store for $60-$70 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a... Read more
July 4th Sale at Expercom: $200 off any 16″ M...
Apple reseller Expercom has 16″ M1 Pro and M1 Max MacBook Pros available for $200 off MSRP as part of their July 4th sale. In addition to their MacBook Pro sale prices, take $50 off AppleCare+ when... Read more
10.2″ Apple iPads (WiFi models) are on sale f...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for up to $20-$50 off MSRP for a limited time. Their prices are the lowest price currently available for one of these iPads. All models are... Read more
10-Core M1 Pro 14″ MacBook Pros on sale for $...
B&H Photo is offering $200 discounts on Apple’s new 14″ M1 Pro MacBook Pros with 10-Core CPUs (16GB RAM/1TB SSDs). Free 1-2 day shipping is available to most US addresses, and both models are in... Read more
B&H has 16-inch M1 Pro MacBook Pros in st...
New Space Gray 16″ MacBook Pros with Apple’s M1 Pro CPUs are in stock and on sale today at B&H Photo for $200 off Apple’s MSRP. Sale prices are for M1 Pro models with 512GB or 1TB of SSD storage... Read more

Jobs Board

VP, Software Engineering - *Apple* and Andr...
…Client Application Software Engineering team is seeking a VP, Software Engineering for Apple and Android. You will lead the client engineering team building Disney+, Read more
I/S Senior Engineer - *Apple* Systems Engin...
**19647BR** **Position Title:** I/S Senior Engineer - Apple Systems Engineering - Remote **Department:** Information Systems **Location:** Lakeland, FL between Read more
*Apple* IT Support Analyst - 2nd Shift - Zon...
Apple IT Support Analyst - 2nd Shift Professional Services Albany, New York Malta, New York Clifton Park, New York Menands, New York Syracuse, New York Watertown, Read more
Infotainment Certification Test Engineer (XC)...
…integration - CarPlay, android auto, MirrorLink, Baidu Carlife, MFi/iPod certification testing; Apple PPID preparation, Google HUCD and GTM preparation + 3 years of Read more
Workplace Services *Apple* Device Managemen...
…3350 Riverwood Parkway Suite 900, Atlanta, GA, 30339 USA **Workplace Services Apple Device Management** **Role Overview** Carrier is seeking an experienced and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.