TweetFollow Us on Twitter

XCMD Corner
Volume Number:4
Issue Number:7
Column Tag:HyperChat®

XCMD Corner

By Donald Koscheka, Apple Computers, Inc.

--Don Koscheka’s XCMD Corner

Last month I introduced XCMD programming. I explained the parameter block and discussed the interface between HyperTalk and the code that you write in either Pascal, “C” or the language of your choice. If you’re an experienced Macintosh programmer, that’s enough information to get started. The designers of HyperCard didn’t stop with just defining the interface for you. They went beyond what might be reasonably expected and provided some HyperTalk programming capabilities to the XCMD programmer. The XCMD programmer gains access to these capabilities through callbacks. Callbacks are procedures and functions that you call from your XCMD. Callbacks literally jump into Hypercard to perform some function.

Once you get the hang of XCMD programming, you’ll come to rely on some of the callbacks quite frequently. For example, Pascal programmers are accustomed to strings that are preceded by a length byte and that have a maximum of 255 characters (the Str255 type in Pascal) while HyperCard uses strings that have no length byte and are terminated with zero ( referred to as Zero-strings, zero-terminated strings or “C” strings). HyperTalk provides callbacks to convert from zero-terminated strings to Pascal and back again. The XCMD programmer can also use callbacks to retrieve and set the contents of fields and global containers as well as to send messages back to Hypercard.

One of the reasons that this access to HyperCard containers is so important is that XCMDs do not have access to the application globals. When Hypercard starts up, it takes control of its application globals and heap just as any application would. With Hypercard in control of the heap, your XCMD becomes a “guest” of Hypercard. You don’t have access to the globals from your XCMD so you’ll need a safe place to store information that you want to keep around.

A good candidate is a global container. Although Hypercard itself prefers to see text strings in containers, it’s not particular about what you put into a container; you can use the SetGlobal callback to put data into a global container, and GetGlobal to retrieve that data. Make sure that you declare any global containers in Hypercard before accessing them in an XCMD. Your XCMD may need to be backward compatible earlier versions of Hypercard that bombed if you called SetGlobal with an undeclared container name.

An interesting example of the use of callbacks is to send a card message back to HyperCard from a callback. The XCMD in listing 1, “SendMeAMessage”, takes one parameter which is the message to send back to HyperCard. Since messages are sent back as Pascal-format strings, we must convert the input string into a pascal string and then call SendCardMessage to send the message. As a matter of form, we set the return value to NIL indicating that this XCMD doesn’t have a result code (Hypercard will interpret NIL as empty).

The first callback that SendMeAMessage invokes, ZeroToPas, converts input parameter 1 from a zero-terminated string to a pascal-string. Input parameters are passed as handles so the parameter needs to be dereferenced one-time to convert the value to a pointer. ZeroToPas also expects you to pass a reference to the pascal-string into which you’ll store the converted Pascal-string. The second callback, SendCardMessage, sends the message back to Hypercard. To invoke this XCMD from a script use the form:

 SendMeAMessage “go next card”

Because Hypercard already handles message passing, this XCMD may not seem terribly useful. Nonetheless, it is a good illustration of callbacks and the technique is useful if you need to alert the user that some asynchronous event has completed.

{1}
{******************************}
{* File: SendMeAMessage.p *}
{******************************}
(******************************
 BUILD SEQUENCE
      (IGNORE LINK WARNINGS)
pascal SendMeAMessage.p
link -m ENTRYPOINT -rt XCMD=65534 
 -sn Main=SendMeAMessage 
 SendMeAMessage.p.o 
 “{Libraries}”Interface.o 
 “{PLibraries}”Paslib.o 
 -o “{xcmds}”testxcmds
******************************)

{$S SendMeAMessage }

UNIT Donald_Koscheka; 

{--------------INTERFACE----------------}
INTERFACE

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

PROCEDURE EntryPoint( paramPtr: XCmdPtr);

{----------IMPLEMENTATION--------------}
IMPLEMENTATION
{$R-}
 
TYPE
 Str31  = String[31];
 
PROCEDURE SendMeAMessage(paramPtr:XCmdPtr);
 FORWARD;

{-------------- EntryPoint --------------}
PROCEDURE EntryPoint(paramPtr: XCmdPtr);
 BEGIN
 SendMeAMessage(paramPtr);
 END;

{------------ SendMeAMessage ------------}
PROCEDURE SendMeAMessage(paramPtr: XCmdPtr);
VAR
 theMessage : Str255;
 
{$I XCmdGlue.inc }
 
BEGIN {*** Body of XCMD ***}
 ZeroToPas( paramPtr^.params[1]^, theMessage );
 SendCardMessage( theMessage );
 paramPtr^.returnValue := NIL;
END; {*** Body of XCMD ***}
END.

Listing 1. SendACardMessage

XCMDs can also use callbacks to get the contents of a field or a global container. Listing 2, GetHomeInfo, uses two new callbacks (1) GetFieldByNum, to get the contents of background field 1 on the home card and (2) SetGlobal to set the contents of some global container.

GetHomeInfo Takes one parameter, the name of the global container to set. First, convert the parameter to a pascal-string. Next, use a series of callbacks to push the current card and go to the home stack. Once we get to the home stack, we call GetFieldByNum to get field data. The first parameter that GetFieldByNum takes is set to TRUE if you want to retrieve the contents of a card field and set to FALSE to retrieve the contents of a background field. The second parameter is the number of the field to retrieve. Alternatively, you could use GetFieldByID if you knew the id of the field or GetFieldByName if you knew the name.

GetFieldByNum returns a handle to the zero-terminated data that was stored in background field 1 of the home card. We then invoke SetGlobal to set the contents of the global container to whatever is stored in fieldData. Finally, we pop the current card to get back to where we started. A typical invocation of this XCMD is:


{2}
 global myData
 GetHomeInfo “myData”



PROCEDURE GetHomeInfo(paramPtr: XCmdPtr);
VAR
 globalName : Str255;
 fieldData: Handle;
 
{$I XCmdGlue.inc }
 
BEGIN
 WITH paramPtr^ DO
 BEGIN
 ZeroToPas( params[1]^, globalName );
 SendCardMessage( ‘Push Card’ );
 SendCardMessage( ‘Go Home’);
 
 fieldData := GetFieldByNum( FALSE, 1 );
 SetGlobal( globalName, fieldData );
 
 SendCardMessage( ‘Pop Card’);
 returnValue := NIL;
 END;
END;

Listing 2. Get Home Info.

So far I’ve showed you XCMDs that don’t do anything that you can’t already do in HyperTalk. A key feature of XCMD programming is that you can write your own commands to augment or add capabilities to Hypercard. Listing 3, “FCreateXFCN”, lets you create a file of any type from HyperCard. This XFCN demonstrates how XCMDs provide greater access to the toolbox than is available to the HyperTalk script writer.

FCreateXFCN introduces two new callbacks. NumToStr returns a result code to the script. NumToStr converts a signed long integer to a pascal-format string. If you don’t want a signed entity, use LongToStr instead which will convert the long integer without regard to sign.

The second callback introduced in this XFCN is PasToZero which takes a pascal format string and returns handle to a zero-terminated string. PasToZero is a handy way of copying from a pascal-string back to a zero-terminated string to return text to Hypercard.

I wrote the XFCN in “C” to show the difference in formats between Pascal and “C” XCMDS and to provide a template for “C” programmers. An important difference is that the parameter list, params, starts at index 0 for “C” and index 1 for Pascal.

FCreateXFCN first converts parameter 1 (params[0]) into a pascal-string and then moves the first four bytes of parameters 2 and 3 into the variables creator and type respectively. These two variables are of type OSType which is a special Macintosh type containing four consecutive ASCII characters. All four characters in this type are significant.

The result code will be empty if no error occurred and the file was created properly, otherwise it will return the OSErr number that occurred. First, convert the result code back to a pascal-string and then call PasToZero to convert that string into a handle to a zero-terminated string.

The XFCN would be more useful if it returned a brief description of the error in English, but I think I’ll leave that as an exercise for the student. Call FCreateXFCN with the following script:

Put FCreateXFCN( “New File Name”, “WILD”,  “STAK” )

The first parameter is the name of the file you wish to create, the second parameter is the creator and the last parameter is the file type. The foregoing invocation will create an empty stack. What can you do with that?

{3}
/*****************************\
*file: FCreateXFCN.c *
\*****************************/

/*****************************
 BUILD SEQUENCE
 
C -q2 -g FCreateXFCN.c
link  -sn Main=FCreateXFCN 
 -sn STDIO=FCreateXFCN 
  -sn INTENV=FCreateXFCN 
  -rt XFCN=300 
  -m FCREATEXFCN 
  FCreateXFCN.c.o 
  “{CLibraries}”CInterface.o 
  -o testXCMDs
 
*****************************/
#include<Types.h>
#include<OSUtils.h>
#include<Memory.h>
#include<Files.h>
#include<Resources.h>
#include  “HyperXCmd.h”

pascal void FCreateXFCN( paramPtr )
 XCmdBlockPtr  paramPtr;
/****************************
* In:   Paramblock:
*param[0] == filename
*param[1] == TYPE
*param[2] == CREATOR
* Out:  result code in returnValue
****************************/
{
char    *fname;
OSType  type, creator;
Str31 str;
char    vName[33];
short   error, vRefnum;

/** coerce the volume reference  ***
***number from the system **/
GetVol( vName, &vRefnum );
 
/**extract the filename from  ***
***the parameter list     **/
fname   = *(paramPtr->params[0]);
BlockMove(*(paramPtr->params[1]),&creator,4 );
BlockMove(*(paramPtr->params[2]),&type,4 );
 
error = Create( fname, vRefnum, 
 creator, type );
 
FlushVol( 0L, vRefnum );
 
if( !error )
 paramPtr->returnValue = 0L;
else{
 NumToStr( paramPtr, (long)error, &str );
 paramPtr->returnValue = 
 PasToZero( paramPtr, &str );
 }
}

#include <XCmdGlue.inc.c>

Listing 3. FCreateXFCN

Although this article covered some of the more frequently used callbacks, my objective was to present you with the spirit of the callback mechanism. You should have no trouble using any of the callbacks that are currently defined in the HyperCard Developer’s ToolKit (available from APDA). The most important lesson here is that before you go off and write an XCMD, check the callback list to see how you might incorporate them into your XCMDs. Try to get the callbacks to do as much work as possible for you so that you can concentrate on the code that you are trying to write.

Next Month: SortList, an XCMD that sorts a field by line.

end HyperChat
 
AAPL
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

VMware Fusion 6.0.3 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more

Latest Forum Discussions

See All

Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Almost All of Playdek’s Library is on Sa...
Almost All of Playdek’s Library is on Sale Right Now, and You Should Check it Out Posted by Rob Rich on April 18th, 2014 [ permalink ] Playdek has released quite a few great iOS ports of board and card games over the years, and now most of them... | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »
Evernote Business Notebook by Moleskin I...
Evernote Business Notebook by Moleskin Introduced – Support Available in Evernote for iOS Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Free HopTo 2.2 Helps Enhance Your Productivit...
The HopTo app helps you do more on your iPad by providing more and easier adaccess to files and documents. Version 2.2 adds Egnyte and HopTo’s Mac OSX File Connector. If you already have the hopTo... Read more
National Distracted Driving Awareness Month:...
As the country recognizes National Distracted Driving Awareness Month, Sprint is reminding wireless consumers to focus on driving while behind the wheel, to not text or email while driving, and to... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
Abt has the 13″ 2.4GHz 128GB Retina MacBook Pro available for $1229 including free shipping. Their price is $70 off MSRP. Read more
iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more
Save up to $270 with Apple refurbished 13-inc...
The Apple Store has Apple Certified Refurbished October 2013 13″ Retina MacBook Pros available starting at $1099, with models up to $270 off MSRP. Apple’s one-year warranty is standard, and shipping... Read more

Jobs Board

*Apple* Inc. Research Data Specialist - Appl...
…of Worldwide Market Research & Intelligence. The team is responsible for conducting Apple branded consumer market research. It is also responsible for analyzing data Read more
*Apple* Automotive Parts Department position...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive, we 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* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.