TweetFollow Us on Twitter

PICT to RMaker
Volume Number:3
Issue Number:5
Column Tag:Toolbox Techniques

PICT to RMaker Source in MacForth

ArticleSubhead

By Larry Tannenbaum, Long Beach, CA

This program illustrates calling traps, using dialog boxes, the desk scrap, and the memory manager from MacFORTH. It takes a picture from the clipboard and converts it to RMaker resource format. The converted picture is put back into the desk scrap, so you can paste it into your resource file, using MockWrite or other editor.

Dialog boxes make programs more Mac-like and more "attractive", but they can be a bit tricky in MacFORTH. The reason is that the MacFORTH window always executes an ABORT when it is activated, and it is always activated when the dialog box is erased, if it was active before the dialog was drawn (To see what else is done when the MacFORTH window is activated, try SYS.WINDOW +ON.ACTIVATE W@. Use the forth decompiler from MacTutor Vol 1,#2 to decompile this token). For example, you start your program that calls a modal dialog box by typing the highest-level word in the MacFORTH window. When the dialog box is drawn in front, the MacFORTH window is de-activated. When the dialog is disposed of, the MacFORTH window is automatically activated and your program is aborted. This program works because all processing is done, before the dialog box is disposed of.

A couple of words in the program are from Thinking Forth:

: \  >IN @ 3C0 AND C/L + >IN ! ;  IMMEDIATE  (skips rest of line)
: ASCII  BL WORD 1+ C@ COMPILING IF [COMPILE] LITERAL THEN ;

IMMEDIATE  (leaves ascii value of following character on stack, or compiles 
it as a literal if used within a definition)

I also used one naming convention from Thinking Forth. Word names starting with "/" imply "bytes per", so /Row means bytes per row. I also tried to use descriptive names and ample comments. Forth can be hard to decipher, but doesn't have to be.

MacFORTH provides several pre-defined words for defining your own trap-calling words. What they do is compile machine code into your definitions that formats the stack for you, such as converting items that are supposed to be integers from the 32 bits that MacFORTH uses for everything, to 16 bits, or taking all of the arguments off the stack, reserving space for a returned result, then putting the arguments back on the stack. They also compile the trap code into the word.

Fig. 1 Pict to RMaker source Dialog Box

These pre-defined words are listed in table 1 along with the argument patterns they work for. Since the "FUNC" words must reserve space on the stack for a returned value underneath the arguments, they are for very specific cases only; the "MT" words are more general. For example, W>MT may be used with a trap that needs one 16-bit item on top of any number of 32-bit items, but W>FUNC>L must be used with a trap that takes one 16-bit argument only. If the trap you want to use doesn't fit any of these patterns, you must format the stack yourself and use MT for your definition.

Blocks 1 to 4 contain examples of calling traps from MacFORTH. The word WAdj, in Block 1, converts 32-bit items to 16 bits; it adds 2 to the stack pointer, essentially chopping off the two most significant bytes of the top stack item. I couldn't get OPEN.RSRC, supplied by MacFORTH 1.2 K2.3, to work, so I defined my own word, OpenRFile, to do the job. The 2nd line of code in block 2 is executed while the file is loading. It takes the name of the loading file as the resource file name. This way, if you rename the file, the resource fork will be opened properly without changing the code.

How do you get resources into a block's file? First, compile the resources with RMaker. The type and creator of the output file should be BLKS M4TH. Go to MacFORTH and open the new resource file with OPEN" rfilename". You have just opened the empty data fork of the file. Append enough blocks to it to hold the program (APPEND.BLOCKS). Either type in the program, or use XFER.BLOCKS (block 12 of Forth Blocks) to transfer it from another block's file. It's easier to use separate resource and blocks files, when developing a program. Finally, change the name of your completed file, because RMaker will delete it, if you recompile the resources.

I decided to use the desk scrap for the input and output of this program so that I could paste the picture resource into the middle of an existing file. It's also easy to select a portion of a picture with Paint Grabber or similar desk accessory and retrieve it from the desk scrap using GET.SCRAP.

Table 1: MacForth trap calling defining words

GET.SCRAP copies the scrap data to a handle that you pass to it. The handle is automatically sized, so it can be any length, including zero. You must also specify the type of data you are looking for. The most common types are text and pictures. Use the constant "TEXT or "PICT to designate the type you want. If the data in the scrap is different from the type you asked for, error code -102 is returned. An error code of zero indicates no error.

PUT.SCRAP works similarly. Give it the address and length of the data, and the data type. It will copy your data to the end of the desk scrap and return a result code.

ZERO.SCRAP deletes all data in the desk scrap and sets the scrap length to zero. You must execute ZERO.SCRAP before the first time you execute PUT.SCRAP, and before putting data into the scrap of the same type that is already there. This last restriction is necessary because GET.SCRAP always returns the first block of data of the type requested. If more than one chunk of data of a particular type is in the scrap, only the first one that was written is accessible.

Two other words help conserve memory: LOAD.SCRAP and UNLOAD.SCRAP. UNLOAD.SCRAP writes the desk scrap to the clipboard file on disk, releasing the memory used by the scrap. LOAD.SCRAP "knows" whether the scrap data is on disk or not and reads it into memory, if necessary. GET.SCRAP apparently will not get the data from the disk, even though Inside Macintosh says it will, so call LOAD.SCRAP first, if there is the possibility of it being in the clipboard file.

SCRAP.HANDLE returns the address where the handle to the desk scrap is stored. SCRAP.COUNTER returns the number of times the scrap has been zeroed since system start-up. According to Inside Macintosh, you can check to see if this value has changed during the operation of a desk accessory. If so, the accessory has probably put some data into the scrap.

SCRAP.LEN returns the address containing the length of the scrap data. This length includes 8 bytes for the scrap header. Sometimes the scrap is 8 bytes longer than the picture length, and sometimes it is 9 bytes longer. I suspect this has to do with whether the picture size is odd or even. The program needs the length of the picture. The easiest way to get it is from the first two bytes of the picture itself, so I don't use SCRAP.LEN. Block 8 contains the definitions using the scrap interface words.

Block 5 holds the memory manager interface definitions. Many programs in MacTutor have dealt with getting, releasing, resizing, locking, and unlocking handles, so I won't go into detail. The MacFORTH words that do these things have explicit names, except maybe FROM.HEAP, which gets a handle, and TO.HEAP, which releases one.

The program uses only one handle. GET.SCRAP copies the picture into it, then the handle is resized to hold the ascii. To avoid overwriting the data, the program starts converting from the end of the picture.

Blocks 9 and 10 contain the code that actually does the conversion. The constant /Row, in block 9, determines how many bytes of the picture are represented on each row of text. It can be changed to any convenient value.

Using this program, you can personalize your dialog and alert boxes, and keep the pictures in your source, rather than having to paste them in after compilation with ResEdit. The output format could also be changed to MDS or MacASM.

( Block 0    ***********Instructions*********** )

To use this program:
    1.  Cut or copy picture to be used as resource so it will
        be in the ClipBoard.
    2.  Load this file.
    3.  Execute Pict>Rsrc. The PICT in the clipboard
        will be converted to type TEXT in RMaker hex format.
    4.  Using MockWrite or other editor, paste the data from
        the clipboard into the RMaker file.

( Block #1   ***********Toolbox interface***********)

HEX

Create WAdj -2 Allot 548F { ADDQ.L #2,SP} W, 4ED4 W,

A997 L>FUNC>W <OpenRFile>        A99A W>MT <CloseRFile>
A97C MT <GetNewDlog>             A983 MT <DisposDlog>
A98D MT <GetDItem>               A991 MT <ModalDlog>
A990 MT <GetIText>               A98F MT <SetIText>
A95F MT <SetCTitle>              A95D W>MT <HiliteControl>
A987 MT <NoteAlert>

DECIMAL
    2 11 Thru

( Block #2   ******ToolBox InterfaceVariables*********)

Create   RFileName    30 Allot \ same name as this file
Block-File @ @File.Name    Dup C@ 1+ RFileName Swap CMove
Variable RFileRefNum           \ returned by OpenRFile
Variable DlogPtr               \ returned by GetNewDlog
Create   ItemHit 2 Allot       \ returned by ModalDlog
Create   ItemType 2 Allot      \ returned by GetDItem
Variable ItemHandle            \ returned by GetDItem
Create   ItemRect 8 Allot      \ returned by GetDItem
Create   Item$ 30 Allot        \ for manipulating text items
Create   Ok$ ," Done"          \ new title for control
1 Constant ConvertButton       \ compared to ItemHit when
                               \ ModalDlog returns

( Block #3    ***********Resource File/Alert***********)

: OpenRFile    RFileName <OpenRFile> Dup 0>
    If   RFileRefNum !
    Else Abort" Couldn't open resource file!" Then ;
: CloseRFile   RFileRefNum @ <CloseRFile> ;
: NoPictAlert  128 WAdj ( id) 0 ( filter proc) <NoteAlert> ;

( Block #4    ***********Dialog Interface***********)

: GetDlog    0 ( reserve stack space for returned dptr)
    128 WAdj ( id) 0 ( on heap) -1 ( in front)
    <GetNewDlog>    DlogPtr ! ;
: DisposeDlog  DlogPtr @ <DisposDlog> ;
: ModalDlog    0 ( filter proc) ItemHit <ModalDlog> ;
: GetDItem    ( item#)    DlogPtr @ Swap WAdj
    ItemType  ItemHandle ItemRect <GetDItem> ;
: GetIHandle  ( item#--handle)    GetDItem ItemHandle @ ;
: GetIText    ( $\item#)    GetIHandle Swap <GetIText> ;
: SetIText    ( item#)    GetIHandle Item$ <SetIText> ;
: Ok>Done  1  ( item#) GetIHandle Ok$ <SetCTitle> ;
: Can'tCancel 2 ( item#) GetIHandle 255 <HiliteControl> ;

( Block #5    ***********Memory Manager***********)

Variable DataH    \ holds handle to data

: GetH ( size--handle)    From.Heap Dup DataH ! Dup 0=
    If DisposeDlog CloseRFile
        1 Abort" Handle Allocation Error!" Then ;
: DataPtr ( --ad of data)    DataH @@ Mask.Handle ;
: /Data ( --data size in bytes)    DataH @ Handle.Size ;
: ResizeH ( new size--)    DataH @ Dup Rot Resize.Handle
        0< If   DisposeDlog CloseRFile
            1 Abort" Handle Resize Error!"
        Else Lock.Handle Then ;
: ReleaseH
   /Data 0< Not If DataH @ Dup Unlock.Handle To.Heap Then ;

( Block #6    ***********PICT Resource Header***********)

13 Constant CRet    \ ascii for carriage return
: AddCR ( ad--)     Count 1- +    CRet Swap C! ;
\ Asterisk in string is place holder for carriage return
Create Type$ ," TYPE PICT = GNRL*"  Type$ AddCR
Create Hex$  ," .H*"                Hex$  AddCR
Create Name$ 25 Allot
Create ID#$  10 Allot
: /Header ( --n)    Type$ C@ Hex$ C@ Name$ C@ ID#$ C@ + + + ;
: (Header>Text) ( ptr\$--updated ptr)
    Count >R Over R@ CMove R> + ;
: !Header    DataPtr            Type$ (Header>Text)
             Name$ (Header>Text) Id#$  (Header>Text)
             Hex$  (Header>Text) Drop ;

( Block #7    ***********Get/Set Dialog Items***********)

: Num>Str ( n)       <# #S #> Item$ 2Dup C!    1+ Swap Cmove ;
: AddChar ( $\char)  Over Count + C!    Dup C@ 1+ Swap C! ;
: SetPictSize        DataPtr W@ Num>Str 9 SetIText ;
: SetPictWidth
    DataPtr Dup 8+ W@ Swap 4+ W@ - Num>Str 11 SetIText ;
: SetPictHeight
    DataPtr Dup 6+ W@ Swap 2+ W@ - Num>Str 13 SetIText ;
: GetPictName    Name$ Dup 5 GetIText Ascii , AddChar ;
: GetPictID#     ID#$ Dup 7 GetIText CRet AddChar ;
: GetHeader      GetPictName    GetPictID# ;
: SetUpDlog
    GetDlog SetPictSize SetPictWidth SetPictHeight ModalDlog ;
: DoneDlog       Ok>Done Can'tCancel ModalDlog ;

( Block #8    ***********Desk Scrap Interface***********)

: ScrapErr? ( result code--)
    0< IF ReleaseH DisposeDlog CloseRfile
          1 Abort" Scrap Error!" Then ;
: /Pict ( --bytes)
    Scrap.Handle @ Dup 0< If Drop 0 Else @ 4+ @ Then ;
: PictFromScrap ( --result code)   Load.Scrap ScrapErr?
    /Pict GetH    "PICT Get.Scrap ;
: Text>Scrap    Zero.Scrap ScrapErr?
    DataPtr /Data "TEXT Put.Scrap ScrapErr?
    ReleaseH    Unload.Scrap ScrapErr? ;

( Block #9    ***********Picture conversion***********)

16 Constant /Row   \ 1 row of text represents 16 bytes of pict
: #CR'S ( pict size--# of CR's in text )
    /Row W/Mod Swap If 1+ Then ;
: /Text ( --text size) /Pict Dup 2* Swap #CR'S + /Header + ;
: PictEnd ( --ad)    DataPtr /Pict + 1- ;
: TextEnd ( --ad)    DataPtr /Text + 1- ;
    Create Char$ ," 123456789ABCDEF"    Ascii 0 Char$ C!
:  >Ascii ( nybble--char)    Char$ + C@ ;
: !Byte  ( ad\byte--new ad)    Dup>R 15 And >Ascii Over C! 1-
                               R> 16/    >Ascii Over C! 1- ;
: !Cr    ( ad--new ad)    CRet Over C! 1- ;

( Block #10   ***********Picture conversion***********)

Variable PictAd

: RowLimits ( #bytes--limit\index)
    PictAd @ Dup Rot - Dup PictAd ! 1+ Swap ;
: !Row    ( dest ad\#bytes--new dest ad)
    RowLimits Do IC@ !Byte -1 +Loop ;
: !Pict    PictEnd PictAd !    TextEnd
    1 /Pict Do !Cr   I /Row Min !Row  /Row Negate +Loop Drop ;
: Pict>Text    Watch Set.Cursor  GetHeader
        /Text ResizeH    !Pict !Header   Init.Cursor ;

( Block #11    ***********User Interface***********)

: Convert?    ItemHit W@ ConvertButton = If
    Pict>Text Text>Scrap DoneDlog Then ;
: ConvertPict    SetUpDlog Convert? DisposeDlog ;
: Pict>Rsrc      OpenRFile PictFromScrap
    0< If   NoPictAlert
       Else ConvertPict
       Then CloseRFile ;
 

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

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
New promo at Visible: Buy a new iPhone, get $...
Switch to Visible, and buy a new iPhone, and Visible will take $10 off their monthly Visible+ service for 24 months. Visible+ is normally $45 per month. With this promotion, the cost of Visible+ is... Read more
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 $100 off Apple’s new MSRP, only $899. Free 1-2 day delivery is available to most US addresses. Their... Read more
Take advantage of Apple’s steep discounts on...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... 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.