TweetFollow Us on Twitter

Icon Stuffing
Volume Number:7
Issue Number:7
Column Tag:HyperChat

Related Info: Quickdraw Resource Manager

Icon Stuffing XCMD

By Steven Fuchs, Stony Brook, NY

iConjured Up

Last year at a meeting of LIMUG, the Long Island Mac Users Group I was introduced to a very useful utility stack called iConjurer by Tom Wimbish, which as the name would suggest is a tool for creating icons. What iConjuror provides is an environment from which the powerful painting tools contained in HyperCard can be used to create icon sized pictures as well as a convenient method of storing them. iConjuror’s shortcoming was that it provided no direct way to convert the pictures HyperCard created into ICON resources. The workaround for this was to copy the image of the icon onto the clipboard and then launch ResEdit, open the requested stack and paste the picture into ResEdits ICON editor, which would convert the first 32 pixels in each of the first 32 rows into an icon. Although once committed to muscular memory this process could be accomplished quickly, it was decidedly un-Mac like, in other words there had to be a better way. I decided that what was needed was an XCMD which could take the image of an icon and create an ICON resource, either in the current stack or in any desired stack. Hence the impetus behind the creation of the IconStuffer XCMD.

Working Overview

When a picture doesn’t tell a story

The first order of business was to make the data of the selected picture available to the XCMD. While some sleuthing into HyperCards inner workings probably could produce a direct method of obtaining the contents of the selection rectangle this is undesirable for some very good reasons. In general it is by far the more difficult task, and in any programming, Mac programming especially and XCMD programing even more so you should always look to avoid trouble. Secondly a method of this sort would almost certainly not work with a different version of HyperCard and may not even work between different machines. Therefore I chose to take the easier path and obtain this information from the clipboard, after forcing the user to copy the image of the icon. However easier does not mean easy, and accessing the clipboard for the icons image is no exception. The clipboard stores its images in the form of a ‘PICT’ resource, Inside Macintosh tells us that the format for a ‘PICT’ resource consists of the QuickDraw calls necessary to recreate the image. The ‘ICON’ resource is simply a series of 1024 bits, the ones and zeros of which represent the black and white pixels of the icons 32x32 rectangle. While much time could have been spent decoding the ins and outs of ‘PICT’ resources and learning how to convert these to icons, a much easier mechanism exists. All that is involved is pulling a bit of a fast one on the operating system and QuickDraw.

Now You See It

All QuickDraw drawing takes place into a data structure known as a GrafPort. When you create a window unbeknownst to you, you are creating a GrafPort. While the Mac OS allows for the creation of GrafPorts on their own it is rarely used, and I will not do that. What I do need to recreate is an important record of the GrafPort called portBits. The portBits record is a bitmap which is the destination of all drawing by the GrafPort.

This bitmap contains the ones and zeros which make up the black and white pixels of the GrafPort in question. It is this data which can easily be converted into an ‘ICON’ resource. The important record in the bitmap is the BufferAddr record, which is a pointer to the location at which the bits that make up the image begin. The QuickDraw sleight of hand I used was to create my own bitmap and fool the GrafPort into drawing into it. The data is now in a form suitable to my purposes and is ready to be made into an icon.

Step by Step

Take a picture, please

Before proceeding some error checking must be done, I know, boring,boring, boring. What must be, must be however and the first form of this takes place in the function FillIconPointer. Using the toolbox function GetScrap we will determine whether or not there is a ‘PICT’ resource on the clipboard at all. This is done by passing a handle of arbitrary size, and telling it I would like the available ‘PICT’ resource only. The function returns the size of the resource as well as resizing the handle and copying the ‘PICT’ resource into it.

If there was a ‘PICT’ resource in the scrap I need to allocate the memory necessary for the icon. Since I know an ‘ICON’ measures 32x32 I am spared the step of figuring out the size of the necessary bitmap. The space of the bitmap is allocated using the NewPointer function. Since NewPointer accepts its size parameter in bytes and not bits, and there are 8 bits in a byte, the size of the pointer should be 32x32/8 or 128. I allocate this into the pointer BufferAddress and in a fit of safety consciousness, check to be sure the allocation succeeded. Assuming that it did, I then assign the remaining records of the structure OffMap. Record 1 of a bitmap, baseAddr is a pointer to the address at which the bitmap image starts. Record 2 of a bitmap is rowBytes, or the number of bytes wide the image is to be. Since an ICON is a fixed size I know that this value will always be 32/8 or 4. In some other circumstance I would compute rowBytes by dividing the width of the bit image by 8. Also an important note is that the Mac operating system requires that all addresses be even, so to avoid a deadly crash the value for rowBytes must always be even. Finally we set bounds, which is the rectangle which encloses our bitmap or 32 x 4.

Now that we are fully prepared to fool QuickDraw only a few more precautions remain. First and foremost is to remember the bitmap currently stored in portBits so as to return things to their original state upon completion, very important for the XCMD programmer. I obtain the existing portBits by calling GetPort and storing the value of portBits into the variable OldMap. Then I use the toolbox call SetPortBits to reassign any subsequent drawing in that GrafPort to my bitmap. I then call ClipRect to insure that the entire image is drawn and EraseRect in order to clear any existing bits from the BitMap. Then a simple call to DrawPicture will allow QuickDraw to fill in the proper pixels of my bitmap for me. Finally a call to SetPortBits again will restore the GrafPorts portBits, dispose of the handle to the PICT resource, and return as the result of FillIconPointer the address at which the bitmap image of the icon begins.

How a bitmap becomes an ICON

The path to creating an ICON resource now becomes very simple since I now have the data in the form I want it. Most of this remaining work takes place in the function CreateNewIcon . First I create a handle of size 128, the fixed size of an icon. A handle is necessary since the toolbox call AddResource demands a handle aand must be used to attach a resorce to the resource file. I then invoke the toolbox call BlockMove to copy the data from the bitmaps pointer to the handle. With the handle now prepared call AddResource which attaches the handle to the resource fork and WriteResource which makes it final by saving the resource to disk. Finally release the memory used by the icon. Congratulations! You have just made an icon.

Selective Stuffing

IconStuffer can act in one of two modes, simple and difficult. Simple mode is activated when IconStuffer is called with no parameters. It simply jams its new ICON resource into the current resource file, which in my case is the iConjuror stack. This is the default response and requires no additional action to bring about. The complex mode is induced when IconStuffer receives a parameter from HyperCard. IconStuffer expects this parameter to be the full pathname of a file. If a parameter is passed then the function SetResFile is called which accepts a file name and attempts to open a resource file with that name. If there is no file with that name one is created. SetResFile returns the new resource manager reference number. Finally the function CreateNewIcon is called which actually creates the ICON resource and places it in that file, the file is then closed and control returns to HyperCard.

Figure 1: Project File

The Final Steps

Compiling a code resource

For those readers new to the process of compiling a code resource I will provide a short description of this process which is also adequately explained in pages 156-158 of the THINK Users guide. The only items to insure that you use the DRVR runtime lib instead of the default runtime lib, and that the files HyperXCMD and HyperXCMD interface files are included in the project, as shown in Figure 1. The select “Set Project Type” from the project menu, and choose the Code Resource icon. Name the resource IconStuffer, give it any arbitrary number (1120 is used in my example), and set the type to “XCMD”. Now select build Code Resource from the menu and step back. If all goes well you have just created your first, (or yet another) XCMD for HyperCard.

The MenuField concept

My method of calling IconStuffer is through a device known as a MenuField (not my name), the script of which is in Figure 2 . A MenuField is a locked field which responds to mouseups within it depending upon the line clicked in. The first responsibility of a MenuField is to utilize the newfield message. The newfield message is passed to a field upon its being pasted . By trapping this and inserting text into itself the IconStuffer field insures that it will always contain the correct menu choices. Figure 2 contains the script for IconStuffer Field, the newfield handler will add the text “This Stack” into line 1, “Any Stack•” into line 2, and “Choose Stack” into line 3.

The real work is done in the mouseup handler which upon receiving a click determines the line clicked in a takes the proper action. Clicking in line 1 calls the simple mode of IconStuffer, adding the icon to the current stack. Clicking in line 3 pulls a bit of a trick on HyperCard. Sending HyperCard the message go to “the target stack” will cause HyperCard prompt the user for a stack with the prompt “Help find the target stack”.

This flawed logic however will break if the user has a stack named “the target stack”. By choosing a phrase the would not often be used for a stack name this HyperCard trick can be used with success. As a precaution before using this get the long name of the current stack, and afterwards check to be certain that they are not identical. If they are identical you should assume that the user clicked on the cancel button , not selecting a stack. In this case the Mac like thing to do is to abort the operation of the script in as graceful a method as possible.

If the stack names are different then return to the starting point bringing the long name of the target stack with you. This will be in the form of “stack “StartUp:HyperCard:Utilities:IconBox”” for a stack named IconBox. simply remove the word stack, and the opening and closing quotes, this information is ready for passing to IconStuffer. This is what occurs when a user clicks on line 3 of the MenuField or optionclicks on line 2. The different is that an optionclick in line 2 of the MenuField stores the long name of the target stack in line 10 of the field and the short name of the stack in line 2. Subsequent clicks in line 2 of the field will utilize line 10 to paste the icon into that specified file.

--1

on newfield
  Put "This Stack"&return&"Any Stack"&return&"Choose Stack" into me
end newfield

on mouseup
  Put trunc((item 2 of the clickloc-item 2 of the rect of me)¬
  /textheight of me)+1 into LineHit
  if LineHit is 1 then IconStuffer
  else if (the optionkey is down and LineHit is 2) or LineHit is 3 ¬
  or (line 10 of me is empty and LineHit is 2) then
    push card
    Lock Screen
    go to stack "the target stack"
    put the long name of this stack into LName
    delete word 1 of LName
    delete char 1 of LName
    delete last char of LName
    put the short name of this stack into SName
    pop card
    unlock screen
    IconStuffer(LName)
    if LineHit is 2 then
      Put SName into line 2 of me
      Put LName into line 10 of me
    end if
  else  IconStuffer(line 10 of me)
end mouseup

Figure 2: HyperTalk Script

In Closing

My sources close to the Heartbeat of Apple have informed me that HyperCard 2.0 would soon be out , and that it contains an icon editor that not only makes iConjuror obsolete, but makes the writing of IconStuffer a waste of time. As of the writing of this article HyperCard 2.0 had not come out and I have not seen its icon editor. Needless to say that if I had heeded the naysayers and not written IconStuffer I would not be using it today, and much the poorer for it. Let that be a lesson to you. Even with impending obsolescence from the belated HyperCard 2.0 (or 2.01, 2.02, 2.03 etc. ) IconStuffer remains a good guide for creating icons from common QuickDraw calls, and for creating offscreen bitmaps. Good Luck and use in Good Health. Hope you enjoy.

unit IconStufferUnit;
interface
 uses
  HyperXCmd;

 procedure MAIN (ParamPtr: XCmdPtr);
implementation

{FillIconPointer accepts no parameters and returns a }
{pointer to the icons bits. The operation is successful }
{if the clipboard contains a PICT resource and the }
{ memory necessary for the ICON can be obtained}
 function FillIconPointer: Ptr;
  var
   HldHandle: handle;
   IconRect: Rect;
   OldPort: GrafPtr;
   err, TheOffset: longint;
   OffMap, OldBits: BitMap;
   BufferAddress: ptr;
 begin
  BufferAddress := nil;
  HldHandle := NewHandle(2);
  err := GetScrap(HldHandle, 'PICT', TheOffset);
  if err > 0 then
   begin
{**The clipboard contained a PICT  **}
    SetRect(IconRect, 0, 0, 32, 32);
    OffsetRect(IconRect, 40, 40);
    BufferAddress := NewPtr(32 * 4);
    if BufferAddress <> nil then
 {**    Memory for the ICON present**}
     begin
 {**    Create offsreen bitmap**}
      OffMap.baseAddr := BufferAddress;
      OffMap.rowBytes := 4;
      OffMap.bounds := IconRect;
      GetPort(OldPort);
{**Store previous bitmap  **}
      OldBits := OldPort^.portbits;
{**Draw into our bitmap   **}
      SetPortBits(OffMap);
      ClipRect(IconRect);
      EraseRect(IconRect);
      DrawPicture(PicHandle(HldHandle), IconRect);
{**Restore previous bitmap**}
      SetPortBits(OldBits);
      ClipRect(OldPort^.portRect);
     end;
   end;
{**Dispose of our copy of the scrap**}
  DisposHandle(HldHandle);
{**Return data bits**}
  FillIconPointer := BufferAddress;
 end;

{GetNextEmptyID does just that while insuring that the  }
{ID's under 128 which are reserved are not used!**}
 function GetNextEmptyID: integer;
  var
   Answer: integer;
 begin
  Answer := 0;
  repeat
   Answer := UniqueID('ICON');
  until Answer > 128;
  GetNextEmptyID := Answer;
 end;

{**SetResFile accepts a string as a parameter and  }
{returns the resource manager reference number **}
 function SetResFile (TheName: str255): integer;
  var
   TheAns: integer;
 begin
  TheAns := OpenResFile(TheName);
  if TheAns = -1 then
   begin
    CreateResFile(TheName);
    TheAns := OpenResFile(TheName);
   end;
  SetResFile := TheAns;
 end;

{**CreateNewIcon accepts the data and the ID to }
{ be used and creates the ICON resource.Returning true  }
{if the operation was a success**}
 function CreateNewIcon (TheImage: Ptr; TheID: integer): Boolean;
  var
   TheHandle: handle;
 begin
  CreateNewIcon := false;
{**Allocate space for the ICON**}
  TheHandle := NewHandle(128);
  if TheHandle <> nil then
   begin
    HLock(TheHandle);
{**Copy bits from the pointer to the handle  **}
    BlockMove(TheImage, TheHandle^, 128);
    HUnLock(TheHandle);
{**Convert handle to a resource    **}
    AddResource(TheHandle, 'ICON', TheID, '');
    if ResError = noErr then
     begin
{**Test for success! **}
      CreateNewIcon := true;
{**Force a disk update    **}
      WriteResource(TheHandle);
     end;
   end;
 end;

{**MAIN brings the routines together **}
 procedure MAIN (ParamPtr: XCmdPtr);
  var
   TheData: Ptr;
   TheHandle: handle;
   TheID, OldRes, NewRes: integer;
   TheItem: str255;
 begin
  TheData := FillIconPointer;
  if TheData <> nil then
{**Could data for ICON be obtained **}
   begin
    OldRes := CurResFile;
    NewRes := 0;
    if ParamPtr^.paramCount > 0 then
     begin
{**Should a different file be used **}
      ZeroToPas(ParamPtr, ParamPtr^.params[1]^, TheItem);
      NewRes := SetResFile(TheItem);
{**If so use it  **}
      UseResFile(NewRes);
     end;
    if NewRes <> -1 then
     begin
{**If there was no file error **}
      TheID := GetNextEmptyID;
{**Do the work!  **}
      if not CreateNewIcon(TheData, TheID) then
       SendHCMessage(ParamPtr, 'Answer "Icon could not be created"');
{**Restore resource chain **}
      UseResFile(OldRes);
      if NewRes > 0 then
{**If a file was opened then close it**}
       CloseResFile(NewRes);
      DisposPtr(TheData);
     end
    else
     SendHCMessage(ParamPtr, 'Answer "File was not found"');
   end
  else
   SendHCMessage(ParamPtr, 'Answer "PICT could not be obtained"');
 end;
end.

 
AAPL
$117.60
Apple Inc.
-1.03
MSFT
$47.47
Microsoft Corpora
-0.12
GOOG
$541.08
Google Inc.
+1.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

MacUpdate Desktop 6.0.3 - Discover and i...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
SteerMouse 4.2.2 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
iMazing 1.1 - Complete iOS device manage...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
PopChar X 7.0 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
Carbon Copy Cloner 4.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more
SyncTwoFolders 2.0.6 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
Duplicate Annihilator 5.1.1 - Find and d...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
HandBrake 0.10.0 - Versatile video encod...
HandBrake is a tool for converting video from nearly any format to a selection of modern, widely supported codecs. Supported Sources: VIDEO_TS folder, DVD image or real DVD (unencrypted -- CSS is... Read more

Latest Forum Discussions

See All

Tilt to Live Bundle Set to Arrive This T...
Tilt to Live Bundle Set to Arrive This Thanksgiving Posted by Ellis Spice on November 25th, 2014 [ permalink ] One Man Left has unveiled an upcoming Tilt to Live bundle, allowing players to get the series for a di | Read more »
BattleLore: Command (Entertainment)
BattleLore: Command 1.0 Device: iOS Universal Category: Entertainment Price: $9.99, Version: 1.0 (iTunes) Description: ***NOTE: Compatible with iPad 2/iPad mini, iPod touch 5 and up and iPhone 4S and up – WILL NOT RUN ON EARLIER... | Read more »
Weather Or Not Review
Weather Or Not Review By Jennifer Allen on November 25th, 2014 Our Rating: :: STYLISH WEATHER REPORTINGiPhone App - Designed for the iPhone, compatible with the iPad Check the weather quickly and conveniently with Weather or Not... | Read more »
The All-New Football Manager Handheld 20...
The All-New Football Manager Handheld 2015 is Available Now Posted by Jessica Fisher on November 25th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Six iOS Games to Get You Ready for Thank...
Image Source: Friends Wiki At this point in the month, you or at least a few people you know are probably getting ready to scramble around (or are already scrambling around) for Thanksgiving Dinner. It’s a hectic day of precise oven utilization, but... | Read more »
Call of Duty: Heroes: Tips, Tricks, and...
Hello Heroes: What’d we think of Call of Duty‘s take on Clash of Clans? Check out our Call of Duty: Heroes review to find out! Just downloaded Call of Duty: Heroes and need some handy tips and tricks on how to get ahead of the rest? As we often do,... | Read more »
Call of Duty: Heroes Review
Call of Duty: Heroes Review By Jennifer Allen on November 25th, 2014 Our Rating: :: CLASH OF FRANCHISESUniversal App - Designed for iPhone and iPad Mix Clash of Clans with Call of Duty, and this is what you get.   | Read more »
Slider Review
Slider Review By Jordan Minor on November 25th, 2014 Our Rating: :: SLIDE TO PLAYUniversal App - Designed for iPhone and iPad Slider has all the excitement of unlocking your phone screen.   | Read more »
oh my giraffe (Games)
oh my giraffe 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Eat fruits while being chased by lions. Cut the vines to send fruit plummeting onto the lions. Don't worry, your flexible... | Read more »
One of 2000’s Most Loves Adventure Games...
One of 2000’s Most Loves Adventure Games, The Longest Journey, has Come to iOS Posted by Jessica Fisher on November 25th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Early Black Friday MacBook Pro sale: 15-inch...
 Best Buy has posted early Black Friday prices on 15″ Retina MacBook Pros, with models on sale for $300 off MSRP on their online store for a limited time. Choose free local store pickup (if available... Read more
A9 Chips Already?
It’s barely more than a couple of months since Apple got the first A8 systems-on-chip into consumer hands, but rumor and news focus is already turning to the next-generation A9 SoC. Apple Daily... Read more
NewerTech Announces NuGuard KXs Impact X-Orbi...
NewerTech has announced updates to its family of Impact X-Orbing Screen Armor bringing military grade, triple layer protection to Apple’s new iPhone 6 and 6 Plus. Like all models in the NuGuard KXs... Read more
13-inch 1.4GHz MacBook Air on sale for $889,...
 B&H Photo has the 13″ 1.4GHz/128GB MacBook Air on sale for $889 including free shipping plus NY tax only. Their price is $110 off MSRP. B&H will also include free copies of Parallels Desktop... Read more
Save up to $300 on Macs and iPads with your A...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
Apple refurbished Mac Pros available for up t...
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
Jumptuit Launches One-Tap Windows 8.1 iTunes...
Jumptuit has launched Windows 8.1 support for One-Tap iTunes Sync. with which Windows 8.1 users can now easily sync their iTunes libraries with Microsoft OneDrive. Jumptuit provides easy access from... Read more
Apple restocks refurbished 13-inch 2014 Retin...
The Apple Store has restocked Apple Certified Refurbished 2014 13″ 2.6GHz Retina MacBook Pros for up to $230 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
CEA Study Finds More People Recycling Electro...
A new study by the Consumer Electronics Association (CEA) finds that electronics recycling receives the continued and growing support of consumers. According to the CEA,s Recycling and Reuse Study,... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1749. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of Parallels Desktop... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the 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* 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* Solutions Consultant (ASC)- Retail S...
**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
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.