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

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.