TweetFollow Us on Twitter

XCMD Libraries
Volume Number:5
Issue Number:6
Column Tag:HyperChat™

XCMD Corner: XCMD Libraries

By Donald Koscheka, Arthur Young & Co., MacTutor Contributing Editor

Modularity and Coupling

As you to explore XCMDs, you should continue to discover new and interesting properties of these routines. Two properties are particularly noteworthy because they lead to code that is usable outside of Hypercard. They are strong modularity and weak coupling.

You determine the modularity of a routine by counting the number of tasks it performs. Strongly modular routines handle one task. If you were writing a spreadsheet program, you would most likely separate the routine that calculates the value of a cell from the routine that displays that value. Combining these functions results in weak modularity. Weakly modular code is hard to debug because you can easily lose track of what the routine is doing at a given point.

Coupling describes how the program interacts with the outside world. Weakly coupled routines operate only on data passed as formal parameters. Weak coupling eliminates harmful side-effects caused by relying on global memory. Weakly coupled programs force you to think over how and when to pass data back and forth.

Well written XCMDs exhibit both strong modularity and weak coupling. Most XCMDs perform one task (strongly modular XCMDs), typically to add a missing feature to Hypertalk. XCMDs interface to Hypertalk using a very strict protocol, passing parameters via the command block record. This protocol coerces weakly coupling in your code.

Software Breadboard

Strong modularity and weak coupling suggest that you can create libraries of useful routines for use both in Hypercard and in programs of your own design. Think of Hypercard as a “Software Breadboard”, a test platform that you plug code into for checkout and debugging. Once working, the routine can be dropped into any application.

An example of a set of routines that play well in this scenario are the calls to the File Manager. Every (non-trivial) application needs to call on the file manager to open a file, access information in the file and then close it. I decided to build my case around accessing a file because Hypercard itself doesn’t handle files “according to Hoyle”. Hypercard violates two precepts of the user interface guidelines when opening a file: (1) The user is required to know the full pathname of a file if it is not in the current working directory and (2) the OpenFile command performs an unexpected action; if it cannot find the file, it creates it!

In order to properly open a file, you first present the user with a dialog that contains the list of files in the current working directory. This dialog allows the user to flip from drive to drive as well as change directories. The standard file package provides you with the “vanilla” get file dialog. When the user selects a file and clicks the “Open” button, your code queries the reply record to discover the file’s name, working directory id and file type.

The working directory id pinpoints which folder contains the document. If you made a killing on Macintosh software and have been away on some deserted island for the past several years, the working directory assumes the role traditionally held by the volume reference number.

Given the file name and working directory, you can reconstruct and return the full pathname to Hypercard so that it can be used by Hypercard’s “open” command (pathname reconstruction is the subject of a future article). However, it’s just as easy to open the file ourselves to ensure that it opens in whatever manner is expected on the Macintosh. The XCMD that opens the file is left as an exercise.

GetFileName XFCN

The XFCN, GetFileName (Listing 1), displays strong modularity - its sole task is to get the name of a file from the user. By relying only on data passed to it formally, it also demonstrates weak coupling. This XFCN provides a general purpose technique for getting the name of a file from the user. GetFileName calls on a routine Called GetFileNametoLoad in HyperUtils.c (listing 2). The prototypes for HyperUtils are found in HyperUtils.h (listing 3). HyperUtils contains a set of re-usable utilities that do not presume the existence of Hypertalk. These routines aren’t encumbered with the XCmdBlkPtr interface.

GetFileNameToLoad accepts as its inputs a list of file types (up to 4) to filter out in the open dialog. If you were writing a text import routine, you might want to present the user with only files of type ‘TEXT’. From Hypercard, you would then invoke GetFileName as:

--1

 Put GetFileName( “TEXT” ) into it;  IF it is not empty then -- User 
selected a file  put item 1 of it into FileName          put item 2 of 
it into FolderID end if 

With little effort, we’ve created a re-usable, general purpose XCMD. Pass the name and the FolderID to any File Manager call that requires the file’s name and volume reference number (aka working directory id). I will call upon this XCMD in future editions of this column so you’ll have ample opportunity to see it action.

An obvious addition to this list an xcmd that asks the user for the name of a file to save by calling SFPutFile. This is a simple modification to GetFileNameToLoad so I’ll leave it as yet another exercise.

After creating enough XCMDs, you’ll soon view them as general purpose routines with a specific interface (XCmdBlkPtr) to HyperTalk. With this in mind, you should have no trouble creating XCMD libraries that can be used in other applications. Get in the habit of separating the Hypertalk interface, including any callbacks, from the action code. The XCMD itself then becomes an interface between HyperTalk and your code.

Listing 1:  GetFileName.c
/********************************/
/* File: GetFileName.c    */
/* */
/* Using Standard File Package*/
/* query the user for the name*/
/* of a file to open, and return*/
/* the name along with the  */
/* working directory id of the*/
/* file.*/
/* Paramters:    */
/* paramCnt = number of types */
/* params[0..3] = the types to   */
/* filter for (see Inside Mac.*/
/* I-523 for details */ 
/* ----------------------------  */
/* To Build:*/
/* (1) Create a project using */
/* this file as well as the */
/* XCMD.Glue.c file. (Set */
/* project type to XCMD (or */
/* XFCN) from the Project menu.  */
/* */
/* (2) Bring the project up to*/
/* date.*/
/* (3) Build Code Resource. */
/* (4) Use ResEdit to copy the   */
/* resource to your stack.*/
/********************************/

#include<MacTypes.h>
#include<OSUtil.h>
#include<MemoryMgr.h>
#include<FileMgr.h>
#include<ResourceMgr.h>
#include<pascal.h>
#include<strings.h>
#include  “HyperXCmd.h”
#include“HyperUtils.h”

pascal void main( paramPtr )
 XCmdBlockPtr  paramPtr;
{
 short  FileWDID;
 short  numTypes;
 short  i;
 SFTypeList typs;
 char   FileName[256];
 char   WDIDString[32];
 char   comma[2];
 
 if( !paramPtr->paramCount )
 numTypes = -1;  /* select all since no type specified */
 else{
 numTypes = paramPtr->paramCount;
 for( i = 0; i < numTypes; i++ )
 BlockMove( *(paramPtr->params[i]), &typs[i], 4L );
 }
 
 *FileName = ‘\0’;
 
 if( GetFileNameToOpen( typs, numTypes, FileName, &FileWDID ) ){
 NumToStr( paramPtr, (long)FileWDID, &WDIDString );
 PtoCstr( WDIDString );
 
 comma[0] = ‘,’; /* for you MPW folk */
 comma[1] = ‘\0’;
 
 strcat( FileName, comma );
 strcat( FileName, WDIDString );
 CtoPstr( FileName );
 }
 paramPtr->returnValue = PasToZero( paramPtr, FileName );
}
Listing 2:  HyperUtils.c

/****************************/
/* HyperUtils.c  */
/* A collection of useful */
/* routines...   */
/****************************/
#include<MacTypes.h>
#include<OSUtil.h>
#include<MemoryMgr.h>
#include<FileMgr.h>
#include<ResourceMgr.h>
#include<StdFilePkg.h>
#include  “HyperXCmd.h”
#include  “HyperUtils.h”

void  CenterWindow( wptr )
 WindowPtrwptr;
/***************************
* Center a window in the current
* screen port.  Note: Does not
* attempt to work with multi-screen
* systems.
*
* This code is inspired by a
* similar routine written by Steve
* Maller in MPW Pascal.  Thanks Steve.
***************************/
{
 short  hWindSize = wptr->portRect.right - wptr->portRect.left;
 short  vWindSize = wptr->portRect.bottom - wptr->portRect.top;
 short  hSize = wptr->portBits.bounds.right - wptr->portBits.bounds.left;
 short  vSize = wptr->portBits.bounds.bottom - wptr->portBits.bounds.top;
 
 MoveWindow( wptr, 
 ( hSize - hWindSize ) / 2, 
 ( vSize - vWindSize + 20) / 2,
 false
 );
}

void Concat( str1, str2 )
 char *str1;
 char *str2;
/*****************************
* Append string 2 to the end of
* string 1.  Both strings are 
* pascal-format strings.
*
* str1 must be large enough to hold
* the new string and is assumed to 
* be of Type Str255 (a pascal string)
*****************************/
{
 short len1 = *str1; /***number of chars in str 1***/
 short len2 = *str2++;/***number of chars in str 2***/
 char  *temp;  /*** string pointer ***/
 
 *str1 += len2 + 1;/*** add sizes to get new size***/

 temp = str1 + len1 + 1;/*** move to end of str 1***/
 while( len2 ){
 *temp++ = *str2++;/*** add char to temp & move***/
 --len2;/*** until all characters are added***/
 }

}

void  CopyPStr( pStr1, pStr2 )
 char *pStr1;
 char *pStr2;
/****************************
* Copy the contents of pstr1 into
* pstr2.  The strings are assumed 
* to be of type STR255 (length byte
* precedes data 
*
****************************/
{short  i;
 char *tstr;
 
 tstr = pStr2;
 
 for( i = 0; i <= *pStr1; i++ )
 *tstr++ = *pStr1++;
}

short GetFileNameToOpen( typs, typCnt,theName, theWDID )
 SFTypeList typs;
 short  typCnt;
 char   *theName;
 short  *theWDID;
/*****************************
* Invokes SFOpenFile to query the 
* user for the name of a file to 
* open. 
*
* In:   List of types of files to
*filter for (up to 4)
* Out:  fileName if picked in theName
*working directory in theWDID
*nil otherwise
*the file’s volum ref num.
* ( Note that the space for the 
* string must be allocated by the
* caller).
*****************************/
{
 Point  where;
 char   prompt[1];
 SFReplyreply;
 GrafPort *oldPort;
 WindowPtrdlogID;
 
 prompt[0]  = ‘\0’;
 
 /*** Get and put up the standard file ***/
 /*** dialog.  You will only see the file***/
 /*** types that you filtered for.  If ***/
 /*** you filtered for no files, then  ***/
 /*** all files will display***/
 
 GetPort( &oldPort );
 dlogID = GetNewDialog( (short)getDlgID, (Ptr)NIL, (Ptr)UPFRONT );
 
 SetPort( dlogID );
 CenterWindow( dlogID );
 where.h = dlogID->portRect.left;
 where.v = dlogID->portRect.top;
 LocalToGlobal( &where );
 
 SFGetFile( where, prompt, (Ptr)NIL, typCnt, typs, (Ptr)NIL, &reply );
 
 DisposDialog( dlogID );
 SetPort( oldPort );
 
 /*** If the user selected a file, let’s ***/
 /*** get the information about it ***/
 
 if (reply.good){
 *theWDID = reply.vRefNum;
 PtoCstr( (char *)&reply.fName );
 strcpy( theName, &reply.fName  );
 }
 return( reply.good );
}
Listing 3:  HyperUtils.H

/********************************/
/* HyperUtils.H  */
/* Header file for HyperUtils.c  */
/* routines...   */
/********************************/

#define NIL 0L
#define UPFRONT  -1L

void  CenterWindow( WindowPtr wptr );
void  Concat( char * str1, char * str2 );
void  CopyPStr( char * pStr1, char * pStr2 );
short GetFileNameToOpen(SFTypeList typs,short typcnt, char *theName, 
short *theWDID);

NOTE: From Jul 89 Jorg Column

Note on a bug in last month’s article:

Last month’s XFCN, GetFileName, incorrectly returns the working directory id of the file selected from SFGetFile. Change the call to GetFileNameToOpen to Read:

if( GetFileNameToOpen(typs,numTypes,FileName,&FileWDID ) ){
 temp = (long)FileWDID & 0xFFFF;
 NumToStr( paramPtr, temp, &WDIDString );
 PtoCstr( WDIDString );

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
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
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.