TweetFollow Us on Twitter

XCMD Etiquette
Volume Number:9
Issue Number:1
Column Tag:Hypercard/Pascal

XCMD Etiquette

Standardizing the interaction of externals with HyperTalk in a user-oriented way

By Jeremy John Ahouse and Eric Carlson, Berkeley, California

Note: Source code files accompanying this article are located on MacTech CD-ROM or source code disks.

About the authors

Jeremy John Ahouse and Eric Carlson are biologists who have found themselves doing ever more computer work and lots of HyperCard scripting. Jeremy wrote a chapter in the new Howard Sams intermediate scripting book Tricks of the HyperTalk Masters and Eric is employed by Apple Computer Inc. as a multimedia software engineer.

This note suggests several approaches to standardizing the interaction of externals with HyperTalk in a user-oriented way.

We have noticed that as XFCN's and XCMD's are promulgated, many have become difficult to use, and are often difficult to interpret in the context of reading a script. There is no reason that externals should not retain the spirit of HyperTalk. We will make several recommendations to this end and then offer example code that illustrates our thoughts. (Note: We will refer to both XCMD's and XFCN's as XCMD's.)

HyperCard has given many people a chance to use their computers in ways that were until recently restricted to “programmers”. The distinction between users and programmers has been eroded by a new class of user/programmer called scripters. We'll give away the moral of this story now; when writing XCMDs you should treat scripters the way you would treat users if you were writing traditional Macintosh applications.

There are really two issues that we need to address. The first is making an external easy to use, the second is making scripts that use externals easy to read and understand. These two are not mutually exclusive.

We begin by listing four problems and then follow with discussions and possible solutions for them. We will end by illustrating our points with source for a StringLength XFCN.

The Problems

1) Many externals obscure the flow of HyperTalk scripts. This makes them harder to understand (and debug).

2) When an error occurs during the execution of an external, how should this be reported to the user/scripter?

3) A user forgets the parameters of your external and there isn't a standard way to find out what they are.

4) A user doesn't want to include a long list of parameters if only one feature of an external is used.

Solutions

Solution No. 1:

Making scripts read well requires XCMD's that are well named and parameters that are easy to understand. We illustrate this point with a counter example:

 put xseven(2, no, 4, h, 1) into msg

Try to use words for input parameters whenever you can. Obviously in some cases it will be much clearer to pass numbers. A rule of thumb is: use numbers only if you are actually working with a number in the external, like the number of items in a list, or lines in a container. Finally, numbers are appropriate if the parameters in the XCMD can get their values from HyperTalk functions (like max) or properties (like textHeight) that return numbers.

A way to avoid naming your XCMD obscurely is to not ask too much of it. Allow your external to do a reasonable number of things well. If you have lots of great ideas write more than one XCMD. Remember that XCMD's extend HyperTalk.

Another aspect of naming externals is to try to make them read well. This is particularly important for XFCNs, which may become part of HyperTalk statements. Try this test. How does your function sound/read in the following contexts:

get myFunction()
put myFunction() into msg
put item 4 of myFunction() into temp

Names that start with verbs don't work well. XCMDs, on the other hand, often read well if they start with verbs.

Solution No. 2:

Reporting errors is always a problem. There are many levels of users and while some will want to handle error codes themselves, others will benefit from a less subtle solution. Make the last (optional) parameter either "Dialog" or "noDialog" with the former as default. Here is an example:

functionThatDanLeftOut(param1, param2, "Dialog")

or, equivalently:

functionThatDanLeftOut(param1, param2)

In these cases the external will return error codes in a dialog and in the result, whereas

functionThatDanLeftOut(param1, param2, "noDialog")

will report return error conditions in the result only. This convention will allow users to suppress error messages that stop the flow of a script and to handle the error conditions on their own if they so choose.

It should also be apparent from the tone of this note that we don't encourage the idea of returning errors like this:

-202

rather do this:

"The Mac seems to have chewing gum in the speaker."

It seems that this recommendation may be difficult for people who implement whole systems that reside outside of HyperCard and who use a set of externals to communicate with their extra-HC system. We are thinking here of search engines, databases, etc For those who feel strongly about the need to return error conditions numerically, we suggest offering your users a function which returns a description of an error condition when passed the error number:

put Error("-202") into msg box

would put

"The Mac seems to have chewing gum in the speaker."

into the msg box. The point here is to make interactions with externals as easy to use as possible.

Solution No. 3:

XCMDs are often documented only within the simple stacks written to distribute and demonstrate them. It is inconvenient for a scripter to have to find and open that stack if they forget the syntax for an external during stack development. Additionally, as newer (debugged!) versions of externals come out, it is often difficult to know which version of an XCMD is in a stack. Support the following forms for your external:

functionThatDanLeftOut("?")

should reports back the syntax for the external without performing its function, i.e.:

functionThatDanLeftOut("param1", "param2", "param3")

would be returned by the XFCN (or XCMD). If some of the parameters are optional surround them with the <> symbols. For example,

commandThatDanLeftOut("param1", <"param2">, <"param3">).

Version and copyright information can be made available to scripters in the same way:

functionThatDanLeftOut("??")

or

commandThatDanLeftOut "??"

should return the copyright information and the version for the external. As first written, this article recommended using the copyright symbol (“©”) for version and copyright information. Upon review, Fred Stauder noted that this symbol is not available on all international keyboards, and so recommended a change. Thanks Fred!

A pair of simple Pascal functions to check for and respond to these requests might look like this:

{1}
 procedure reportToUser (paramPtr: XCmdPtr;
     msgStr: str255);
{}
{ report something back to the user.  we always fill }
{ in the result field of the paramBlock, and optionally }
{ use HC's "answer" dialog unless requested not to }
{}
  var
   tempName: str255;

 begin
  paramPtr^.returnValue := PasToZero(paramPtr, msgStr);
{check the last param to see if the user requested that }
{ we suppress the error dialog }
  ZeroToPas(paramPtr, paramPtr^.params[paramPtr^.paramCount]^, tempName);
  UprString(tempName, true);
  if tempName <> 'NODIALOG' then
   SendCardMessage(paramPtr, 
 concat('answer "', msgStr, '"'));
 end; { procedure }

 function askedForHelp (paramPtr: XCmdPtr;
     syntaxMsg: Str255;
     copyRightMsg: Str255): boolean;
{}
{ check to see if the user sent a '?' or a '??' as }
{ the only parameter. if so we will respond with }
{ the calling syntax or the copyright/version info }
{ for this external }
{}
  var
   firstStr: str255;
 begin
  askedForHelp := false;
  if paramPtr^.paramCount = 1 then
   begin
    ZeroToPas(paramPtr, paramPtr^.params[1]^, firstStr);
 { what is the first param? }
    if firstStr = '?' then
     begin
       reportToUser(paramPtr, syntaxMsg);
       askedForHelp := true
     end{ asked for help }
    else if firstStr = '??' then
     begin
       reportToUser(paramPtr, copyRightMsg);
       askedForHelp := true
     end; { asked for copyright info }
   end; { one parameter passed }
 end; { function }

Many externals (wise externals?) check the parameter count and return some of this information if the number of passed parameters is wrong. Most of these will continue to function properly if a user presents the external with a "?" or a "??", but the point is to make this method standard so that users know to use it. Adopting this approach will give scripters a standard way to query XCMDS and will give us a way to internally document externals.

Solution No. 4:

Support default values for your externals. This means that a user is required to pass only those parameters that are necessary. In the StringWidth function that we discuss below, if only a string is passed, the function defaults to the HyperCard default text size, font, and style - 12 point, Geneva, plain. This approach seems to offer a good combination of flexibility and clean HyperTalk. If taken to the extreme, this approach can also make it very difficult to elucidate the purpose of an XCMD when reading through a script, so keep point 1 in mind as you decide on optional parameters and default values.

Problems?

Not all of these recommendations will be universally applicable. Doubtless someone has written an external which must be passed "?" or "??", but try to remember the spirit of these approaches. Make the external easy to use, flexible, easy to read (for debugging if not aesthetics), and finally treat external users like Macintosh users. HyperCard has made “programming” (whoops “scripting”) available to many people who never thought they would ever have so much control over their computer. It is vital that we do what we can to suppress the tendency for the techno-macho/techno-less macho dichotomy to take hold (or should we say widen).

An Example

What follows is the source for an XFCN written in Think Pascal which tries to follow some of our own advice. This XFCN returns the width in pixels of a string passed to it. It is similar in function to Fred Stauder's XCMD from the March, 1991 issue of MacTutor, but we have given it some additional functionality as well as writing it as an XFCN (it is a function after all). Fred's implementation contained no information about the font, style, and size of the text. This can be a fatal flaw in many cases. The function we present allows you to specify all of these attributes. It is called as follows:

stringWidth (container, font, size, style, <noDialog>)

Finally, here is a description of what our example code does: StringWidth first checks the parameter block pointer to see if any parameters were passed (although most of the parameters have default values, it is fairly difficult to guess what string the user wishes to use). Assuming the user is somewhat confused about the XFCN's use if no parameter are passed, we send back the calling syntax.

Next we check to see if they have explicitly asked for the calling syntax or for copyright/version information, and respond appropriately if so.

Once we have the string to measure, we need to determine what the font, size and style parameters are, as they can make a huge difference in the string's width. HyperCard's default font is geneva, so if the user doesn't pass any information about the font we use it as our default too. HyperCard displays a button or field in Geneva if the font which was originally assigned to it is not available, but the textFont property for that field or button returns the number of the original font. Thus we must check to see if a number is passed as the font parameter, and use Geneva when we find one. The final check on the font parameter is to make certain that the name passed is available. If the font name is misspelled or not available in an open resource file, the toolbox call GetFNum returns 0. Because this is also the correct font number for Chicago, we call GetFontName and compare the name returned with the name passed as a parameter to see if the requested font is available. In the event of an error, we fill the result, and if the user did not pass “noDialog” as the last parameter, we also report the error via HyperCard's answer dialog.

The third parameter is the font point size. If none is passed, we use HyperCard's default, 12 point.

The fourth parameter is the font style. We check this parameter by a simple, if somewhat tedious, series of tests for the presence of each of the possible style options.

Once we have finally determined all of the parameters, our task is quite simple: set the port to the specified font characteristics, call StringWidth to find the pixel width of the string parameter, and reset the port back to its original characteristics. This last step is a small one but it should not be overlooked.

And So

Scripters who have “cut their programming teeth” on HyperTalk are accustomed to (and perhaps rely upon) HyperTalk's conventions, including code which reads easily and clearly, understandable error messages, and so forth. Remembering that these people are potential users of our externals should help us to write externals in such a way that they extend HyperCard's functionality without departing from its spirit. The distinctions between different kinds of computer users are finally becoming more and more difficult to define, let’s do our part to continue the trend.

We hope that these recommendations prove useful.

Good Luck and Good Scripting.

Fig. 1. The project window for the example presented below. Note that because we compile to a code resource we must use DRVRRuntime.lib library rather than Runtime.lib (the later references its globals through register A5, a definite no-no for an XCMD).

{2}
Listing:  String Width.p
unit stringWidthUnit;
{}
{ LSP Project contains: }
{ XCMDIntf.p }
{ XCMDUtils.p }
{ Interface.lib }
{ DRVRRuntime.lib }
{ stringWidth.p (this file ) }
{}
{ syntax is:stringWidth(stringHolder, font, size,}
{ style,<noDialog>) }
{ the parameters should be specified as hypercard }
{ reports them, ie. }
{ stringWidth("this is a dummy string", "PALATINO",}
{ "14", "BOLD,ITALIC", "noDialog") }
{}
{ copyright (©)  Eric Carlson and Jeremy Ahouse }
{ April 29, 1989 }
{ Waves Cosulting and Development }
{ Berkeley, CA     94792 }
{ free for non-commercial use only }
{}
interface
 uses
  XCMDIntf, XCMDUtils;

 procedure main (paramPtr: XCmdPtr);
implementation

{------------------------------------------------}

 procedure reportToUser (paramPtr: XCmdPtr;
     msgStr: str255);
{}
{ report something back to the user.  we always fill }
{ in the result field of the paramBlock, and optionally }
{ use HC's "answer" dialog unless requested not to }
{}
  var
   tempName: str255;
 begin
  paramPtr^.returnValue := PasToZero(paramPtr, msgStr);
{check the last param to see if the user requested that }
{ we suppress the error dialog }
  ZeroToPas(paramPtr, paramPtr^.params[paramPtr^.paramCount]^, tempName);
  UprString(tempName, true);
  if tempName <> 'NODIALOG' then
   SendCardMessage(paramPtr, 
 concat('answer "', msgStr, '"'));
 end; { procedure }

 function askedForHelp (paramPtr: XCmdPtr;
     syntaxMsg: Str255;
     copyRightMsg: Str255): boolean;
{}
{ check to see if the user sent a '?' or a '??' as }
{ the only parameter. if so we will respond with }
{ the calling syntax or the copyright/version info }
{ for this external }
{}
  var
   firstStr: str255;
 begin
  askedForHelp := false;
  if paramPtr^.paramCount = 1 then
   begin
    ZeroToPas(paramPtr, paramPtr^.params[1]^, firstStr);
 { what is the first param? }
    if firstStr = '?' then
     begin
       reportToUser(paramPtr, syntaxMsg);
       askedForHelp := true
     end{ asked for help }
    else if firstStr = '??' then
     begin
       reportToUser(paramPtr, copyRightMsg);
       askedForHelp := true
     end; { asked for copyright info }
   end; { one parameter passed }
 end; { function }

 procedure widthOfString (paramPtr: XCmdPtr);
{}
{ set the specified pen characteristics and get the }
{ width of the string with the toolbox routine }
{ StringWidth }
{}
  label
   1;
  var
   passedString, errorStr, tempName: str255;
   copyRtStr, syntaxStr: str255;
   oldFont, oldSize, fNum, fSize, width: integer;
   fName, sizeString, theStyleStr: Str255;
   oldStyle, theStyle: Style;
   HCPort: GrafPtr;
 begin
  syntaxStr := 'stringWidth(stringHolder, font, size, style, <"noDialog">)';
  copyRtStr := 'v1.0, ©1989 Waves Consulting and Development, Berkeley 
CA.';
  if paramPtr^.paramCount = 0 then
   begin
  { no parameters passed, report our calling syntax }
    reportToUser(paramPtr, syntaxStr);
    goto 1;
   end;

  if not (askedForHelp(paramPtr, syntaxStr,
 copyRtStr)) then
   begin
    GetPort(HCPort); { grab the port }
    with HCPort^ do
     begin
     oldFont := txFont;   { save current typeface }
     oldSize := txSize;   { save current size }
     oldStyle := txFace;  { save current style }
     end;

    ZeroToPas(paramPtr, paramPtr^.params[1]^,
 passedString);{ get the string to trim }

 { do we have a font name parameter? }
    if paramPtr^.paramCount > 1 then
     ZeroToPas(paramPtr, paramPtr^.params[2]^,
 fName)
 { which font? }
    else
     fName := 'GENEVA';
 { no font passed, use HCs default }

    fNum := StrToNum(paramPtr, fName);
{ check to see if a number was passed as the font }
{'name' parameter. if so, we assume that the font }
{ which HC wants to use for the field/button is not }
{ available in the current system. in this case geneva }
{ is being used instead, so we should use it too! }
    if fNum <> 0 then
     fName := 'GENEVA';
    GetFNum(fName, fNum); { get the font number }
{ if we call for an unavailable font (not present in }
{ this system, name spelled incorrectly, etc, GetFNum }
{ returns 0, which also happens to be the correct }
{ number for CHICAGO.  thus we now check to see if }
{ the name for the font num is the same as the font }
{ name passed to us, or if our user is requesting the }
{ impossible }
    GetFontName(fNum, tempName);
    UprString(fName, true);
    UprString(tempName, true);
    if tempName <> fName then
     begin
      errorStr := concat('Sorry, the font ', chr(39),
 fName, chr(39),' is not avaliable.');
      reportToUser (paramPtr, errorStr);
      goto 1;
     end;

    if paramPtr^.paramCount > 2 then
  { do we have a size parameter? }
     ZeroToPas(paramPtr, paramPtr^.params[3]^,
 sizeString) { font size in string form }
    else
     sizeString := '12';
 { no size passed, use HCs default }
    fSize := StrToNum(paramPtr, sizeString);
 { actual size }

    theStyle := [];
   { is there a style parameter? }
    if paramPtr^.paramCount > 3 then
     begin
       ZeroToPas(paramPtr, paramPtr^.params[4]^,
 theStyleStr); { which style(s)? }
      UprString(theStyleStr, true);
      { convert to uppercase }

 if pos('BOLD', theStyleStr) > 0 then
        theStyle := theStyle + [bold];
 if pos('ITALIC', theStyleStr) > 0 then
        theStyle := theStyle + [italic];
 if pos('UNDERLINE', theStyleStr) > 0 then
        theStyle := theStyle + [underline];
 if pos('OUTLINE', theStyleStr) > 0 then
        theStyle := theStyle + [outline];
 if pos('SHADOW', theStyleStr) > 0 then
        theStyle := theStyle + [shadow];
 if pos('CONDENSE', theStyleStr) > 0 then
        theStyle := theStyle + [condense];
 if pos('EXTEND', theStyleStr) > 0 then
        theStyle := theStyle + [extend];
     end;

 { now setup the port with the specified font }
 { attributes }
    TextFont(fNum);{ set it to the current font, }
    TextSize(fSize); { and the size, }
    TextFace(theStyle); { and the style... }

    width := StringWidth(passedString);
 { how wide is that string? }

 { we mustn't forget to clean up after ourselves, }
 { reset HC's port to the entry conditions }
    TextFont(oldFont);  { reset the  font  }
    TextSize(oldSize);  { and the size  }
    TextFace(oldStyle);{ and the style }

 { send back the width }
    paramPtr^.returnValue := PasToZero(paramPtr,
 NumToStr(paramPtr, width));
   end;

1: {bail out point if we run into trouble }
 end;

 procedure main;
 begin
  widthOfString(paramPtr);
 end;
end.
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

How to win big in Slots Deluxe
Cheating while gambling is illegal and morally wrong, and in some parts of the world it leads to men with names like Vinnie "Six Knuckles" Manchenzo beating you to a pulp in a dark alley. [Read more] | Read more »
How to take over the world in Dictator 2
Running a country isn't easy - especially when you're a dictator who wants to take over the world and crush everyone in your path while you do it. [Read more] | Read more »
Tips and tricks to get a higher score in...
Tank.iois - you guessed it! - another multiplayer arena battler likeAgar.io and Slither.io. It does differentiate itself by putting you in a tiny tank though, so it's not exactly the same. To help you get that all-important high score, we've got a... | Read more »
How to unlock characters in One Tap Tenn...
As the title suggests, One Tap Tennis requires only a single tap to play its particular brand of tennis, and rewards you with a ton of unlockable characters if you perform well. Fortunately for you, we at 148Apps have got a few tips and tricks to... | Read more »
Grab it now: Game Craft’s Legend of War...
The real time strategy game is now available for you to sink your teeth into, through the App Store and Google Play. Combining elements of skill, strategy and empire building, Legend of War is a real gamers’ game. [Read more] | Read more »
Skateboard Party 3 ft. Greg Lutzka (Gam...
Skateboard Party 3 ft. Greg Lutzka 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Skateboard Party is back! This third edition of the popular sports franchise features professional skater... | Read more »
Cubious (Games)
Cubious 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Cubious – How smart are you? How high is your IQube? Solve the impossible puzzles to find out, and help a lost little cube find his... | Read more »
Goat Simulator Waste of Space (Games)
Goat Simulator Waste of Space 1.1 Device: iOS Universal Category: Games Price: $4.99, Version: 1.1 (iTunes) Description: ** IMPORTANT - SUPPORTED DEVICESiPhone 4S, iPad 2, iPod Touch 5 or better.** | Read more »
Wildfulness - Unwind in nature and calm...
Wildfulness - Unwind in nature and calm your mind with nature sounds and illustrations 1.0 Device: iOS Universal Category: Healthcare & Fitness Price: $1.99, Version: 1.0 (iTunes) Description: Spending time in nature helps you to... | Read more »
Dr. Panda Racers (Education)
Dr. Panda Racers 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: STEP ON THE GAS, RACE AND WIN!Fasten your seat belts and get ready to race! Speed your way to the finish line while doing... | Read more »

Price Scanner via MacPrices.net

Enterprise Workers Pick Technology Over Perks...
New Adobe study shows surprising attitudes about office jobs and where the future of work is heading. Adobe has released survey findings revealing that a surprising 70 percent of U.S. office workers... Read more
Goal Zero and OtterBox Partner to Expand iPh...
Goal Zero, specialists in portable power, have announced a partnership with OtterBox, brand smartphone case protection, to offer the Slide and Slide Plus Batteries as modules compatible with the new... Read more
15-inch Retina MacBook Pros on sale for up to...
B&H Photo has 15″ Retina MacBook Pros on sale for up to $210 off MSRP. Shipping is free, and B&H charges NY tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799 $200 off MSRP - 15″ 2.5GHz Retina... Read more
Clearance 2015 13-inch MacBook Airs available...
B&H Photo has clearance 2015 13″ MacBook Airs available for $250 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/4GB/128GB MacBook Air (MJVE2LL/A): $799... Read more
Apple refurbished Apple TVs available for up...
Apple has Certified Refurbished 32GB and 64GB Apple TVs available for up to $30 off the cost of new models. Apple’s standard one-year warranty is included with each model, and shipping is free: -... Read more
21-inch iMacs on sale for up to $120 off MSRP
B&H Photo has 21″ iMacs on sale for up to $120 off MSRP including free shipping plus NY sales tax only: - 21″ 3.1GHz iMac 4K: $1379.99 $120 off MSRP - 21″ 2.8GHz iMac: $1189 $110 off MSRP - 21″ 1... Read more
Kanex Introduces GoPower USB-C Rechargeable B...
Kanex has announced its GoPower USB-C portable battery for the USB-C MacBook, featuring the new industry standard connector and cable used for connectivity and power. Providing users with a new... Read more
Convertible and Detachable Devices Winning Ov...
According to the latest figures published by International Data Corporation (IDC), Western European shipments of ultraslim convertibles and detachables posted positive growth (44.7%) to account for... Read more
New MacBook Pros And Will MacBook Air Be Upgr...
With my mid-2013 13-inch MacBook Air closing on its third anniversary come November, I’m in system upgrade mode. Actually the Haswell CPU equipped Air is still doing a fine job, but my good wife is... Read more
Apple’s Education discount saves up to $300 o...
Purchase a new Mac or iPad using Apple’s Education Store and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free, and... Read more

Jobs Board

*Apple* Project Engineer - Smart Source Inc...
SmartSource is in need of an Apple Project Engineer for a 12 month contract opportunity in Pittsburg, PA. Role: Apple Project Engineer Location: Pittsburg, PA Read more
Automotive Sales Consultant - Apple Ford Linc...
…you. The best candidates are smart, technologically savvy and are customer focused. Apple Ford Lincoln Apple Valley is different, because: $30,000 annual salary Read more
Service Assistant - *Apple* Chevrolet *App...
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
Editor, *Apple* News - APPLE (United States...
Job Summary The Apple News team is looking for a passionate and knowledgeable editor with experience covering entertainment/pop culture and experience running social Read more
*Apple* Nissan Service Technicians - Apple A...
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 , Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.