MPW Tools in Pascal
Volume Number: | | 5
|
Issue Number: | | 5
|
Column Tag: | | Programmer's Workshop
|
MPW Tools with TML Pascal II
By Randy Leonard, Jacksonville, FL
Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.
[Randy Leonard is currently employed by TML Systems, Inc. while completing his Masters thesis in computer science at the University of Central Florida. His thesis involves improving the efficiency of several key algorithms in constructive solid geometry (CSG). The thesis is written entirely with TML Pascal II and he uses several of his own MPW Tools to aid in his development.]
The introduction of the Macintosh Programmers Workshop (MPW) v3.0 this January requires that we revisit this programming environment and study its new and exciting features as well as the significant features of previous versions of the product. This article discusses how the MPW environment can be enhanced with the addition of your own integrated programming tools. The type of commands introduced here are capable of executing in the background while running MPW v3.0. This capability enables you to continue your most important task in the foreground while such tasks as compiling and linking of programs occur in the background. Indeed, the tool introduced here may also run in the background.
Macintosh Programmers Workshop
The Macintosh Programmers Workshop is the official Macintosh development environment from Apple Computer, Inc. The MPW Shell is a complete development system for the Macintosh that includes, among other things, a multi-windowing text editor and a command processor. Also included with MPW is a linker, make facility, resource compiler, resource decompiler, source code management system, and more. There is also complete online help as well as an optional graphical interface for just about every command available in MPW.
MPW has often times been accused of having a steep learning curve. The author believes this false accusation can be based upon two pretexts. The first is due to unfamiliarity with the product. The second is due to the extraordinary power that MPW can provide its advanced users via the command line environment and MPWs advanced command processor. The truth of the matter is that MPW is as easy to learn and use as any other programming environment if you were to utilize only those features found in MPW that the other programming environments provide.
The true beauty of MPW is found in its open architecture. That is, anyone can expand the functionality of MPW to suit his own needs. There exist two methods of adding new commands to MPW: scripts and tools. This two part article will demonstrate how to create new programming tools and how to fully integrate these tools into the MPW environment. This months article will give the motivation for writing your own MPW tool and show how it is done. Part two, to appear next month, will demonstrate how to integrate the tool into the MPWs online help facility and how to develop a graphical interface for the new command.
MPW Tools
Tools provide a method of adding commands that are not inherent to the MPW command processor. For example, the TML Pascal II compiler is an extension to the MPW environment and is therefore implemented as a tool. Other examples of MPW Tools are the canonical speller Canon and TMLPasMat. TML Systems, in fact, used these two tools to put the finishing touches on both its Source Code Library II and example programs found on the TML Pascal II distribution disk. Canon adjusts all identifiers in source code files so they have the same same capitalization as found in Inside Macintosh. TMLPasMat will format all Pascal source code files to a consistent format that you define. These two tools were especially helpful since programming styles of the programmers at TML Systems vary.
However, we needed even more help in providing a consistent format for all source code files that left our office. As it turns out, some programmers at TML Systems prefer different fonts and different font sizes for their work. Some programmers would print their work on the laser writer reduced to 75% while others would print at 100%. Some prefer different tab settings and still others have large screens on which to edit their programs. This last problem could be especially annoying to our customers with small screens since only a small part of the window of a text file would appear on their screen when they opened the file. Each customer could easily resolve the problem by resizing the window for his screen, but what if the window appeared off-screen to begin with!
Another problem unrelated to each programmers taste was the problem of USYM resources. The TML Pascal II compiler writes symbol table information for separately compiled units to the resource fork of the main unit source code file as USYM resources. This is perhaps a more favorable solution than creating separate files to hold the information as other compilers do. Deleting a file that contains symbol table information is easy, but how do you easily erase resources from the resource fork of a source code file?
To solve the above problems, we developed a MPW tool that changed the font of MPW text files to any specified font and font size. Tab spacing is set to any defined value and the window is made to appear on any Macintosh screen with the top left corner slightly staggered from other windows and the bottom right corner extending to the bottom right of the screen. The page setup is reset to print at 100%. All USYM and other resources are optionally deleted as well. We call this tool ChangeTextRes. Below, we explain how to implement this tool, but first a little background.
What Every Tool has in Common
MPW Tools are usually invoked from the command line of the MPW Shell. The command line of an MPW command is simply the line on which the MPW command exists. Parameters are passed to the tool by placing them on the command line. A graphical interface for the tool, called the Commando, does exist, but is not typically used. The Commando interface for a tool is invoked by typing in the command name followed by the ellipses character ( ). This character is obtained by holding the option key and pressing the semicolon. The implementation of a custom Commando interface for ChangeTextRes is discussed in next months article.
Apple has defined several conventions for MPW Tools that allow them to work well together in an integrated fashion. First and most important is that a tool have some default behavior. Deviations from this default result only from options specified on the command line. A command line option is simply a parameter found on the command line starting with the character -. For example, the resource decompiler tool DeRez is invoked by typing:
DeRez filename
where filename specifies any resource file at all. If you wish only to decompile only dialog resources, you would type:
DeRez filename -only DLOG
Now, only resources of type DLOG will be decompiled. The behavior of the DeRez tool has been modified by the -only option. Many command line options may be specified, but the order in which they are given should never matter.
Another rule is that tools are to run silently, they should require no interaction with the user to carry out its task. The only visual feedback from the tool should be in the form of a spinning cursor. The reasoning for these rules have their roots in the advanced capabilities of the MPW command processor. Should the reader wish to become a more powerful user of MPW, he is referred to the chapter Using the Command Language of the Macintosh Programmers Workshop Reference.
The Command Processor
Each time a command is entered, the MPW command processor attempts to interpret it. If it is unsuccessful, the command processor assumes the command is either a tool, script, or an external application. Since we are writing a tool, we do not need to concern ourselves to much with the command processor, but there are a few features that need to be discussed.
Before invoking an MPW tool, the command processor first attempts to interpret parts of the command line. Certain characters have special meaning to the command processor. For example, the (Option-x) character is a wild card character. If .p is specified, the command processor will expand this to a sequence of filenames that end with .p. The MPW Tool never sees the .p parameter. Rather, it sees the sequence of filenames that match the .p pattern! This not only increases a users productivity, but also simplifies the writing of tools.
Also allowed are special characters for I/O redirection, piping, and substitution of MPW Shell variables. Knowledge of these features are not necessary for the average MPW user. See the Macintosh Programmers Workshop Reference for more details.
Three file variables are predefined for MPW Tools, input (standard input), output (standard output), and diagnostic. As expected, standard input is the Macintosh keyboard. Standard output is the current topmost window found in the MPW environment as is diagnostic.
How ChangeTextRes Works
The underlying theory of ChangeTextRes is quite simple. The tool receives from the command line the name of each file it is to work on as well as any command line options that may exist. The resource fork of each MPW text file specified on the command line is deleted if the command option -d is also present on the command line. If the -d option is not specified then no resources of any files are ever deleted. ChangeTextRes will then change the files font, font size, and tab setting.
If ChangeTextRes is instructed to delete the entire resource fork with the -d option, there will no longer be any resource specifying the page setup or window size and position. If a file has no resource for page setup or file window position, the MPW Shell will assume default values. The default value for window position is to stagger the windows top left corner and cover the rest of the screen. The -d option will delete all USYM resources created by the TML Pascal II compiler as well.
ChangeTextRes assumes default values of Monaco, 9 point, and 3 for the font, font size, and tab setting, respectively. The user may change these values with the command line options -f, -s, and -t. The -f option, followed by a font name instructs ChangeTextRes to use that font name. The -s option followed by an integer value instructs ChangeTextRes to use the specified font size. And the -t option followed by an integer value instructs ChangeTextRes to use the specified tab setting. An error message is generated if an invalid font, a font size less than 1 or greater than 127, or a tab setting less than 1 or greater than 24 is specified.
To use ChangeTextRes, type the command followed by all file names and options desired. Keep in mind the MPW Shells filename expansion capabilities discussed above. For example:
ChangeTextRes MyProject.proj .p
-f Courier -s 12 -t 4 -d
will delete all resources of all MPW text files ending with a .p as well as the file MyProject.proj. The font for each file is set to Courier 9 point and the tab setting is set to 4.
Accessing the Command Line
Accessing the command line parameters from within a tool is quite simple. The IntEnv unit defines two global variables used to access the command line parameters: argv and argc. The argv variable is a pointer to an array of pointers to strings. Argc tells how many parameters exist in the argv array. The argv array starts at element 0 and argc is always one greater than the actual number of parameters found on the command line. The expression argv^[argc] is always equal to nil. The first parameter of the argv array (argv^[0]^) is the name of the MPW tool itself and is useful for error message generation. All parameters to the tool are stored in argv^[1]^ to argv^[argc-1]^. It is up to the programmer to read in command line parameters and to distinguish between regular parameters and command line options. The ChangeTextRes tool contains the procedure ReadCommandLine to accomplish this task.
{1}
procedure ReadCommandLine;
var
argVIndex : integer;
arg : Str255;
begin
if argc = 1 then SyntaxError(9, );
argVIndex := 1;
while argVIndex < argc do begin
arg := argv^[argVIndex]^;
if length(arg) <> 0 then
if arg[1] = - then
if length(arg) > 1 then
HandleOption(arg, argVIndex)
else SyntaxError(8, );
argVIndex := argVIndex + 1;
end; { while }
end;
In this routine, argVIndex is used to traverse the command line parameters. Each time a command line option is found, the procedure HandleOption is called. HandleOption will read the option and set program global variables accordingly. Since options may require an additional parameter (e.g. the ChangeTextRes option -f, -s, and -t), HandleOption must have the ability to read the next parameter(s) on the command line and increment argVIndex accordingly. If an invalid command line option or invalid value corresponding to a valid option is found, HandleOption will generate an error and terminate the program.
Rewriting a Files Resource Fork
The sole purpose for ChangeTextRes is to rewrite part or all of a files resource fork. Since it is intended to work only on source code files, the segment of the program that effects a files resource fork must first check to see if the file is of type TEXT and has a creator of MPS (the MPW signature). If this is so, ChangeTextRes will proceed to change the files resource fork. Below is the segment of code that accomplishes this task.
{2}
if (fnderInfo.fdType = TEXT) and
(fnderInfo.fdCreator = MPS ) then begin
if gResDelete then begin
anOSError := OpenRF(filename, vRefNum, ResRefNum);
anOSError := SetEOF(ResRefNum, 0);
anOSError := FSClose(ResRefNum);
end;
result := IEFAccess(filename, F_STabInfo, gTabSize);
result := IEFAccess(filename, F_SFontInfo, arg);
end
The global variable gResDelete is affected by the -d option. If the -d option is present on the command line, gResDelete is set to true, otherwise it is set to false. Only when gResDelete is true will all the resources be deleted.
An MPW files font, font size and tab setting are modified with calls to the IEFAccess function. This function is defined in the IntEnv unit. There are three parameters to IEFAccess. The first is the filename on which the routine is to operate. The second parameter defines which operation to perform, and the third provides a means of passing data to and receiving results from the IEFAccess routine.
Our first call to IEFAccess sets the tab setting of a file. The predefined constant F_STabInfo informs IEFAccess to set the tab of the specified file and the third parameter specifies the desired tab setting. The second call to IEFAccess sets the font and font size. The second parameter of IEFAccess is set to the predefined constant F_SFontInfo. Apple has inadvertently documented that the third parameter, in this case, is a pointer to the new font and font size. This is not the case, rather, the upper word of this long integer is the font number and the lower word contains the font size. Both F_STabInfo and F_SFontInfo are defined in the IntEnv unit.
Spinning the Beach Ball Cursor
MPW Tools are, by convention, supposed to provide visual feedback to the user by displaying and spinning a cursor. By default, this cursor is the MPW beach ball cursor but may be any other cursor the programmer defines. Spinning cursors have a resource type of acur and may be created with MPWs resource editor and/or resource compiler. See the appendix Programming for the Shell Environment in the MPW Pascal Reference Manual or Appendix D of the TML Pascal II Language Reference for more details on creating and using such resources.
All the routines related to the operation of the cursor by an MPW Tool are contained in the CursorCtl unit. Only two routines in this file are required by most tools: InitCursorCtl and RotateCursor.
For a tool to rotate the cursor, it must first call InitCursorCtl. This routine has just one parameter which is a handle to an acur resource. If this parameter is nil, then the cursor defaults to MPWs spinning beach ball cursor. Call this routine very early in the program to prevent fragmentation of the heap.
Initializing the spinning cursor does not in itself cause the cursor to spin. The MPW Tool must manually spin the cursor itself. This may seem to be an inconvenience, but it is actually to your advantage. For example, a user can track progress of the MPW Linker by watching which way the beach ball rotates. The linker has three phases, each change in phase is accompanied by a change in direction of rotation of the cursor.
To rotate the cursor, call RotateCursor(value) where value is some integer or long integer. Each time this procedure is called, value is added to an internal counter. When this counter is an even increment of 32, the beach ball is rotated. If value is positive, the cursor is rotated in the clockwise direction. If value is negative, the cursor is rotated in the counter-clockwise direction. It is important to call RotateCursor on a frequent basis. It is usually best to place this procedure call in the main loop of the program.
Software Interrupts
MPW Tools should be capable of responding to software interrupts known as signals. Currently, only one type of signal exists and that is the command-period (.). Signals have the capability of preempting a tool or any other MPW command. Tools will automatically respond to a signal but it may be necessary at times to prevent a signal from preempting a tool. Several routines in the Signal unit allow a tool to control the effect a signal may have on it. ChangeTextRes does not in any way attempt to control a signals effect.
The default actions taken by a tool in response to a signal are to close all open files, execute any installed exit procedures, and terminate the program. See the appendix Programming for the Shell Environment in the MPW Pascal Reference Manual or Appendix D of the TML Pascal II Language Reference for more details on how to install exit procedures. Also refer to these manuals for information on how to prevent or delay the effects of signals on MPW Tools.
Returning Status Results
There are basically three different conditions that cause ChangeTextRes to terminate. The first is normal termination and arises when ChangeTextRes has successfully completed processing its data. There are two abnormal termination conditions. One is due to invalid syntax of command line parameters and the other to the inability for the tool to successfully complete its task. In any case, when a tool returns control to the MPW Shell, it must inform the Shell of its termination condition. This is done by returning a status code.
Defined in the IntEnv unit is the procedure IEExit. This procedure has one parameter of type LongInt. When a tool is to terminate, either normally or abnormally, it should call IEExit. Note that IEExit actually terminates the program. The value of its parameter is returned to the MPW Shell as a status code which by convention is zero to signify normal completion and non-zero to indicate abnormal termination. ChangeTextRes returns 1 to indicate a syntax error and 2 to indicate other errors.
Further Reading
This article has addressed many of the issues involved in writing MPW Tools, but there still remains a significant amount of potential yet to be realized. The chapter Writing an MPW Tool of the Macintosh Programmers Workshop Reference discusses all the issues of writing MPW Tools, and does so in much greater detail than presented here. The chapter Building an Application, a Desk Accessory, or an MPW Tool of the same reference describes the mechanics of building a tool, but this knowledge is not necessary if you are using the TML Project Manager.
Chapter 8 of the TML Pascal II Users Guide shows how to write MPW Tools as does Programming with Macintosh Programmers Workshop, by Joel West. This second book is highly recommended for any MPW user. Appendix D of the TML Pascal II Language Reference and appendix titled Programming for the Shell Environment of the MPW Pascal Reference Manual give complete descriptions of the interface files required to create MPW Tools.
Introduction To Cammando Interface
An MPW tool is typically invoked from the command line. This method of accessing a tool is sometimes cumbersome, especially if you forget the command line options available for the given tool. The Commando offers an optional graphical interface to an MPW tool from which any capability of the tool may be accessed. This graphical interface is implemented as a resource of type cmdo and any resource number. Each tool may have its own unique cmdo resource, but such a definition is not required. If more than one cmdo resource is specified in the resource fork of a tool, then the one with the lowest resource number is selected. The MPW tool ChangeTextRes discussed last month was defined without such an interface. In this half, the standard Commando interface and the various controls its dialogs support are described. The article closes with an example interface for the tool created last month.
Figure 1.
The Standard Commando Interface
Most Commando dialogs share the same basic structure similar to the dialog for the MPW Search command seen in Figure 1. This dialog is divided primarily into three boxes. The first is the Options box. In this region are the controls used to access the various options of the command. There are numerous types of controls available to the designer of a Commando dialog, all of which are discussed in a later section. It is intended that every aspect of a given tool may be accessed via the controls in this box. Other dialog boxes, called subviews, may be accessed from button controls in this region to allow for a more organized and readable Options box.
The middle of the dialog contains what is called the Command box. The Command box is updated to reflect the current list of command line options each time a control in the Options box is modified. This command line may be copied into the clipboard using Command-C or the Edit menu. Below the Command box is the Help box. Clicking and holding down the mouse button on any control causes help information related to that control to be written in this box.
Located in the bottom right corner of the dialog are two buttons. These two buttons are generically referred to as the Cancel and Do It buttons. Clicking Cancel or pressing Command-period causes the Commando to be aborted. Clicking the Do It button or pressing the Enter key causes the command to be passed back to the MPW Shell for execution. Special results may be obtained, however, by holding down various modifier keys while pressing Enter. Holding the Option key while pressing Enter causes the command to be executed as well as echoed to MPWs active window. Alternatively, holding the Command key while pressing Enter causes no command to be executed, it just causes control to be passed back to the Shell. Holding both the Option and Command keys and pressing Enter results in the command line being written to the active window without being executed.
Invoking the Commando
There are three ways to invoke the Commando dialog. Perhaps the easiest is to type the name of the command and pressing Option-Enter, but this method is only available to users of MPW v3.0. Pressing Enter on a line containing the command name followed by the ellipsis ( ) character will also activate the Commando. The ellipsis character is obtained by holding the Option key while pressing the semicolon (;) character. The third method is to type the word commando followed by the name of the tool to be invoked, and then pressing Enter.
The latter method deserves special attention. Commando is actually an MPW tool. Typing commando and pressing Enter will activate this tool, which will then read the cmdo resource of the tool specified on the command line and display its dialog interface. This method of invoking the Commando results in only the generated command to be written to the topmost window, the command is never executed.
Standard dialog box controls
The cmdo resource allows for various types of controls to be displayed in the Options box. Only controls supported by Commando may be displayed, but with the types of controls provided, any required functionality should be easily accomplished. The controls and other items that may appear in the Options box include, but are not limited to:
Check boxes
Radio buttons
Boxes, lines, and text titles
Pop-up menus
Lists
Three-state buttons
Icons and Pictures
Nested dialog boxes
Redirecting output
Multiple input files
Multiple directories
Single input or output file
Version number
The chapter Using MPW: The Basics in the MPW Reference Manual contains a section detailing all the different types of controls allowed within a Commando dialog. The chapter titled Creating Commando Interfaces for Tools of the same reference gives complete resource descriptions for each type of control. Only a few types of controls and other Commando items will actually be described here.
Radio Buttons
Options that are mutually exclusive of each other are often presented as a group of radio buttons. The tab settings for ChangeTextRes are implemented as a cluster of radio buttons in the Commando interface defined here. Radio button groups are usually surrounded by a labeled perimeter to emphasize the grouping of the controls. The tab option was specified as a group of radio buttons in the ChangeTextRes Commando for example only. Depending upon taste, better methods probably exist for presenting this option.
A cluster of radio buttons is considered a single item in the resource description. The Rez type definition for a radio button cluster is given as follows:
/* 3 */
case RadioButtons:
key byte = RadioButtonsID;
byte = $$CountOf(radioArray); /* # of buttons */
wide array radioArray {
rect; /* bounds */
cstring; /* title */
cstring; /* option returned */
byte NotSet, Set; /* whether button is set or not */
cstring; /* help text for button */
align word;
};
A general rule to follow when reading Rez type definitions such as this is that any field containing an equal sign can effectively be ignored by the programmer. Rez inserts values for such fields automatically at compile time. In this resource type definition, a cluster of radio buttons is defined to be an array of radio button elements, with each element consisting of an enclosing rectangle, title, corresponding command line option, default value, and a help field. A sample excerpt from the ChangeTextRes cmdo resource is as follows:
/* 4 */
NotDependent { }, RadioButtons {
{ /* array radioArray: 21 elements */
/* [1] */
{40, 30, 55, 60}, 1, -t 1,
notSet, Set tabs to one spaces,
/* [2] */
{60, 30, 75, 60}, 2, -t 2,
notSet, Set tabs to two spaces,
/* [3] */
{80, 30, 95, 60}, 3, -t 3,
Set, Set tabs to three spaces,
/* [4] */
{100, 30, 115, 60}, 4, -t 4,
notSet, Set tabs to four spaces,
/* [20] */
{140, 170, 155, 210}, 20, -t 20,
notSet, Set tabs to twenty spaces,
/* [21] */
{160, 170, 175, 210}, 21, -t 21,
notSet, Set tabs to twenty one
spaces,
}/* array radioArray */
}, /* RadioButtons cluster */
Only one radio button should be marked as Set in the cluster, where the set button is defined as the default button. If no buttons are defined as set, then the first button in the list is assumed to be the default. If a particular radio button is defined to be the default, then its option return value (e.g. -t 3) is not written to the command line when that option is selected.
Check Boxes
Options to MPW tools are often Boolean flags, that is, they are either off or on non-exclusively of other options. Such options are best represented in the Commando dialog with check boxes. A group of related check boxes may or may not be surrounded by a labeled perimeter. The Rez type definition for check boxes is as follows:
/* 5 */
case CheckOption:
key byte = CheckOptionID;
byte NotSet, Set; /* whether button is set
or not */
rect; /* bounds */
cstring; /* title */
cstring; /* option returned */
cstring; /* help text for button */
};
This type definition is similar to that of the radio buttons. There is one instance of a check box control in the ChangeTextRes Commando dialog. It is used to set the flag for deleting all resources for selected files.
/* 6 */
NotDependent { }, CheckOption {
NotSet,
{100, 250, 115, 425},
Delete resource fork,
-d,
Delete all resources for the selected
files
},
Pop-Up menus
There are two types of pop-up menu controls allowed in a Commando dialog: shadow and editable. A shadow pop-up menu is a field displayed as a shadowed box. Clicking inside this box will cause a pop-up menu to appear containing all valid choices for that particular field. The shadowed box is aligned around the current selection in the menu, and this selection is checked as well. This menu will behave just like the standard pull-down menu for the duration of the time the mouse button is held down. The menu will scroll vertically if required and the selected menu item is placed in the menu box when the mouse button is released. The font control of the ChangeTextRes Commando is a shadow pop-up menu. The Rez definition for this type of resource is:
/* 7 */
case PopUp:
key byte = PopUpID;
byte Window, Alias, Font, Set;
/* popup type */
rect; /* bounds of title */
rect; /* bounds of popup line */
cstring; /* title */
cstring; /* option returned */
cstring; /* help text for popup */
byte noDefault, hasDefault;
/* hasDefault if first item
is Default Value */
A shadow pop-up menu may contain one of four possible lists. The only one we are concerned with here is Font. If Font is selected as the pop-up type, then all available fonts are displayed in a scrollable pop-up menu. Also specified in this resource type definition are enclosing rectangles of the shadow box, the controls title, enclosing rectangle of the controls title, option returned, and help information. Also, if the last item in the resource definition is set to hasDefault, then the first item in the scrollable menu is Default Font.
The shadow pop-up menu is convenient, but not always sufficient. If the desired value is not available in the menu box, then some means should exist for it to be manually entered. The type of control that allows a pop-up menu and edit box combined in one is called an editable pop-up menu. The Font Size control in the ChangeTextRes Commando is such a control. The resource type definition for this control is as follows:
/* 8 */
case EditPopUp:
key byte = EditPopUpID;
byte MenuTitle, MenuItem,
FontSize, Alias, Set;
/* Type of editable pop-up */
rect; /* bounds of title */
rect; /* bounds of text edit area */
cstring; /* title */
cstring; /* option to return */
cstring; /* help text for textedit part */
cstring; /* help text for popup part */
This definition is almost identical to that for shadow pop-up menus. As with shadow pop-up menus, only font information is discussed. When FontSize is selected as the type of menu, only the available font sizes for a specified font are listed. If none of the font sizes in the menu are desirable, then the user may type in his own value.
Of special importance here is the association of this pop-up menu with some font. Editable pop-up menus are required to be made dependent on another shadow pop-up menu containing a list of fonts so that the control knows what font sizes to display. Dependent controls are not discussed in this article, but one such control is actually implemented. The excerpt from the ChangeTextRes cmdo resource implementing two pop-up menus with one dependent upon the other is given below.
/* 9 */
/* [3] */
NotDependent { }, PopUp {
Font,
{20, 250, 40, 320},
{20, 330, 40, 450},
Font,
-f,
Select font specified files are
to assume,
hasDefault
},
Or {{1}}, EditPopUp {
FontSize,
{50, 250, 70, 320},
{50, 330, 70, 400},
Font Size,
-s,
User definable font,
Select from available fonts
},
All that will be said for this instance of dependent controls is that the editable pop-up menu is made dependent on the shadow pop-up menu. If no font is selected in the shadow pop-up menu, then the pop-up menu part of the editable pop-up menu is disabled. The editable part of the control, however, is still active.
Multiple Input Files
When a tool allows more than one input file of a given type, then a single button control is displayed. An example of this would be the Files button in Figure 2. Clicking this button will cause a modified version of the standard SFGetFile dialog to appear. This is shown in Figure 3. This dialog allows multiple files from various directories to be selected. All selected files are listed in the lower scrollable list. Files may be selectively removed from this list. A file filter may be applied to all files displayed in the upper scrollable list.
Figure 2.
Modifying Existing Commandos
When creating any standard type of graphical resource, MPW users usually prefer ResEdit. But when it comes to fine tuning, the resource is decompiled to text format, modified by hand, and then compiled back to object code with the Rez compiler. ResEdit, though, does not have the capability to graphically create and edit Commando interfaces. Instead, the Commando tool for MPW v3.0 has a built in editor that allows the programmer to edit text labels and help messages. Controls and other items may be moved and resized with this editor as well. Unlike ResEdit, controls cannot be created, duplicated or deleted.
The process of creating Commando resources is to first create the resource text file. This may be done with little concern for where controls are actually placed in the dialog because resources may then be compiled to object code format with the MPW tool Rez. The dialog is then modified with the Commando editor. The modified interface may then be decompiled back to text for fine tuning using the DeRez tool. Figure 4 illustrates the interrelationships of the various tools that may be used in creating a Commando interface.
Commandos built in editor may be activated by holding down the Command key immediately after launching Commando until the Watch cursor appears. This editor may also be invoked from the command line by adding the -modify option in one of the following ways:
Commando ChangeTextRes -modify
or
ChangeTextRes -modify
Commando may be used in two different modes once it has been launched with the built-in editor enabled. The first is Normal mode in which the interface operates as usual. The second is the Edit mode in which controls may be moved and resized. To activate the Edit mode, hold the Option key down while selecting a control. Continue to hold the Option key down while the control is selected to drag and/or resize the control.
The Commando editor works in many ways like the ResEdit graphical editor. It also allows multiple controls to be simultaneously selected and moved. Text labels may be edited much in the same way the text for an icon is changed from the Finder. Help messages as well as the size of the Commando dialog box may be modified as well.
If the Commandos Edit mode was activated at any time, then selecting the Cancel or Do It button to exit the dialog causes a Save dialog to appear. This Save dialog offers three options: save the resource, do not save the resource, or cancel the save operation and return to the Commando dialog. Saving a Commando resource causes the original resource to be overwritten, so caution is advised.
Figure 3.
Figure 4.
The ChangeTextRes Commando
The resource file given at the end of this article defines the Commando interface illustrated in Figures 2 and 3. They were created using the techniques described in this paper. First, the resource text file was entered and compiled with Rez. Next, the Commando editor was invoked to align and resize all controls. The DeRez tool was then used to decompile the cmdo resource back to the text given here. Assuming the filename containing the resource text file is called ChangeTextRes.r, the Rez command used to compile this resource is:
Rez ChangeTextRes.r cmdo.r -append
-o ChangeTextRes
The file cmdo.r contains the resource type declaration for the resource type cmdo. This file comes with MPW and the Rez compiler knows where to find it. Cmdo.r may be omitted from this command if it is specified as in include file within the ChangeTextRes.r file. After the Commando editor has been used to move and resize fields, the following DeRez command may be used to obtain a text file containing the modified cmdo resource.
DeRez ChangeTextRes cmdo.r -only cmdo
Of course, instead of using the MPW command line, the Commando interface for the Rez and DeRez tools could have been used. Just think, using Commando to create new Commando interfaces!
Conclusion
Commando dialogs offer an optional graphical interface to MPW commands implemented as tools. They offer a means to graphically select any feature of the MPW command they represent and may result in that command being executed. Creating a Commando interface is as easy as creating a resource of type cmdo using Rez, DeRez, and Commando. ResEdit is not capable of editing cmdo resources, but since Commando has its own built in editor, it does not matter.
program ChangeTextRes;
{
ChangeTextRes.p
--------------
An MPW Tool to delete resource fork of MPW
text files and rewrite the resource fork
to specify a desired tab setting, font,
and font size.
(c) TML Systems, Inc., 1988
All rights reserved.
}
uses MemTypes, QuickDraw, OSIntf, ToolIntf,
PackIntf, PasLibIntf,
{ required for MPW Tools }
CursorCtl, IntEnv;
var
ResRefNum : integer;
{ reference number for resource fork of a given file }
filename : Str255;
aStringPtr : StringPtr;
{ reference number for default drive }
vRefNum : integer;
{ Finder information for a given file }
fnderInfo : FInfo;
{ result from Mac ROM file I/O calls }
anOSError : OSErr;
{ passed to IEFAccess specifies font and font size }
arg : LongInt; { result from IEFAccess calls }
result : LongInt;
i : integer;
{ Font number of specified font as returned by GetFNum }
gFont : integer;
gFontSize : LongInt;
gTabSize : LongInt; { tab setting }
{ delete all of files resources? }
gResDelete : boolean;
function UpperCase(str: Str255): Str255;
{
Convert an alpanumeric string to all
uppercase characters.
}
var
i: integer;
begin
for i := 1 to length(str) do
if (str[i] >= a) and
(str[i] <= z) then
str[i] := chr(ord(str[i]) - 32);
UpperCase := str;
end;
procedure SyntaxError(err: integer; msg: Str255);
{
Display the appropriate syntax error and
then exit from the program. Return a
status value of 1 indicating an early
termination of program.
}
begin
case err of
1: writeln(# , msg, is an invalid option);
2: writeln(# missing font);
3: writeln(# missing font size);
4: writeln(# missing tab setting);
5: writeln(# , msg, is an invalid font);
6: writeln(# , msg, is an invalid font size);
7: writeln(# , msg, is an invalid tab size);
8: writeln(# the - character must be
accompanied by an option);
9: begin
writeln(# Usage - ChangeTextRes [name ] );
writeln( -f fontname # set
font of files to fontname);
writeln( -s fontsize # set
font size of files to fontsize);
writeln( -t tabs # set
tab setting to tabs);
end;
otherwise
writeln(fatal error #, err);
end;
IEExit(1); { return error status of 1 }
end;
procedure HandleOption(opt: Str255;
var argIndex: integer);
{
Set the appropriate global flag for each
command line option encountered on the
command line. If an invalid
option is found, give an error message and
exit from the program. If the option
requires an additional command line
parameter (e.g. -f Monaco), then retrieve
the option(s) needed and increment the
argIndex counter appropriately.
}
var
NumString, str : Str255;
begin
str := UpperCase(opt);
Delete(str, 1, 1); {delete the - character}
if str = F then begin { set font }
argIndex := argIndex + 1;
if argIndex < argc then begin
GetFNum(argv^[argIndex]^, gFont);
if gFont < 0 then
SyntaxError(5, argv^[argIndex]^);
end
else SyntaxError(2, );
end
else if str = S then begin { set font size }
argIndex := argIndex + 1;
if argIndex < argc then begin
StringToNum(argv^[argIndex]^, gFontSize);
if (gFontSize <= 0) or
(gFontSize >= 128) then begin
NumToString(gFontSize, NumString);
SyntaxError(6, NumString);
end;
end
else SyntaxError(3, );
end
else if str = T then begin { set tab }
argIndex := argIndex + 1;
if argIndex < argc then begin
StringToNum(argv^[argIndex]^,gTabSize);
if (gTabSize <= 0) or
(gTabSize >= 25) then begin
NumToString(gFontSize, NumString);
SyntaxError(7, NumString);
end;
end
else SyntaxError(4, );
end
else if str = D then
gResDelete := true
else SyntaxError(1, str);
end;
procedure SkipOption(opt: Str255; var argIndex: integer);
{
This routine is called only after the
command line parameters have already been
scanned once using HandleOption. The
purpose of this routine is to properly
increment argIndex according to the
appropriate command line options.
}
var
str: Str255;
begin
str := UpperCase(opt);
Delete(str, 1, 1); {delete the - character}
if str = F then { set font }
argIndex := argIndex + 1
else if str = S then { set font size }
argIndex := argIndex + 1
else if str = T then { set tab size }
argIndex := argIndex + 1
else if str = D then { nothing }
end;
procedure ReadCommandLine;
var
argVIndex : integer;
arg : Str255;
begin
if argc = 1 then SyntaxError(9, );
argVIndex := 1;
while argVIndex < argc do begin
arg := argv^[argVIndex]^;
if length(arg) <> 0 then
if arg[1] = - then
if length(arg) > 1 then
HandleOption(arg, argVIndex)
else SyntaxError(8, );
argVIndex := argVIndex + 1;
end; { while }
end;
procedure ReportError(error: integer; filename: Str255);
{
Generate the appropriate error message
then exit from the program. Return a
status value indicating early termination
from the program.
}
begin
if error = 0 then
exit(ReportError);
write(diagnostic, ERROR! );
case error of
-35: writeln(diagnostic, filename, volume does not exist);
-36: writeln(diagnostic, filename, IO Error);
-37: writeln(diagnostic, filename,
is a bad filename or volume name);
-42: writeln(diagnostic,Too many files open);
-43: writeln(diagnostic, filename, not found);
-45: writeln(diagnostic, filename, is locked);
-46: writeln(diagnostic, filename,
is locked by a software flag);
-47: writeln(diagnostic, filename,
is busy; one or more files are open);
-53: writeln(diagnostic, filename, volume not on-line);
-54: writeln(diagnostic, filename,
cannot be opened for writing, file is locked);
-61: writeln(diagnostic, filename,
Read/write permission doesnt allow writing);
otherwise
writeln(diagnostic, OS error #,
error, has occurred.);
writeln(diagnostic, Reference Inside
Macintosh pp. III:205-209 for further details);
end;
IEExit(2);
end;
begin {main program}
{ make first stmt toavoid heap fragmentation }
InitCursorCtl(nil);
InitFonts; {so we can read in font names}
{ so we read in JUST the font names! }
SetResLoad(false);
{ Set default values }
gResDelete := false;
gFont := 4;
gFontSize := 9;
gTabSize := 3;
ReadCommandLine;
arg := gFont;
arg := BSL(arg, 16);
arg := arg + gFontSize;
anOSError := GetVol(aStringPtr, vRefNum);
if anOSError <> 0 then
ReportError(anOSError, aStringPtr^);
i := 1;
while i < argc do begin
{ Make cursor rotate each time through loop }
RotateCursor(32);
filename := argv^[i]^;
if length(filename) = 0 then begin
i := i + 1;
cycle;
end;
if filename[1] = - then
SkipOption(filename, i)
else begin { valid filename }
anOSError := GetFInfo(filename, vRefNum, fnderInfo);
if anOSError <> 0 then begin
ReportError(anOSError, filename);
cycle;
end
else begin { file exists }
if (fnderInfo.fdType = TEXT) and
(fnderInfo.fdCreator = MPS )
then begin
if gResDelete then begin
anOSError := OpenRF(filename, vRefNum, ResRefNum);
anOSError := SetEOF(ResRefNum,0);
anOSError := FSClose(ResRefNum);
end;
result := IEFAccess(filename, F_STabInfo, gTabSize);
result := IEFAccess(filename, F_SFontInfo, arg);
end
else
writeln(WARNING! , filename, is not an MPW text file, resources
not deleted);
end; { file exists }
end; { valid filename }
i := i + 1;
end; { while i < argc }
writeln;
SetResLoad(true);
IEExit(0); { Normal status return }
end. {main program}
/*
ChangeTextRes.r
This file contains only one resource which
defines the commando interface for the MPW
Tool ChangeTextRes
*/
#include cmdo.r
resource cmdo (128, ChangeTextRes) {
{ /* array dialogs: 2 elements */
300,
ChangeTextRes, an MPW Tool that deletes
MPW text file resources,
{ /* array itemArray: 3 items */
/* [1] */
NotDependent { }, RadioButtons {
{ /* array radioArray: 21 elements */
/* [1] */
{40, 30, 55, 60}, 1, -t 1,
notSet, Set tabs to one spaces,
/* [2] */
{60, 30, 75, 60}, 2, -t 2,
notSet, Set tabs to two spaces,
/* [3] */
{80, 30, 95, 60}, 3, -t 3,
Set, Set tabs to three spaces,
/* [4] */
{100, 30, 115, 60}, 4, -t 4,
notSet, Set tabs to four spaces,
/* [5] */
{120, 30, 135, 60}, 5, -t 5,
notSet, Set tabs to five spaces,
/* [6] */
{140, 30, 155, 60}, 6, -t 6,
notSet, Set tabs to six spaces,
/* [7] */
{160, 30, 175, 60}, 7, -t 7,
notSet, Set tabs to seven spaces,
/* [8] */
{40, 100, 55, 140}, 8, -t 8,
notSet, Set tabs to eight spaces,
/* [9] */
{60, 100, 75, 140}, 9, -t 9,
notSet, Set tabs to nine spaces,
/* [10] */
{80, 100, 95, 140}, 10, -t 10,
notSet, Set tabs to ten spaces,
/* [11] */
{100, 100, 115, 140}, 11, -t 11,
notSet, Set tabs to eleven spaces,
/* [12] */
{120, 100, 135, 140}, 12, -t 12,
notSet, Set tabs to twelve spaces,
/* [13] */
{140, 100, 155, 140}, 13, -t 13,
notSet, Set tabs to thirteen spaces,
/* [14] */
{160, 100, 175, 140}, 14, -t 14,
notSet, Set tabs to fourteen spaces,
/* [15] */
{40, 170, 55, 210}, 15, -t 15,
notSet, Set tabs to fifteen spaces,
/* [16] */
{60, 170, 75, 210}, 16, -t 16,
notSet, Set tabs to sixteen spaces,
/* [17] */
{80, 170, 95, 210}, 17, -t 17,
notSet, Set tabs to seventeen spaces,
/* [18] */
{100, 170, 115, 210}, 18, -t 18,
notSet, Set tabs to eighteen spaces,
/* [19] */
{120, 170, 135, 210}, 19, -t 19,
notSet, Set tabs to nineteen spaces,
/* [20] */
{140, 170, 155, 210}, 20, -t 20,
notSet, Set tabs to twenty spaces,
/* [21] */
{160, 170, 175, 210}, 21, -t 21,
notSet, Set tabs to twenty one spaces,
} /* array radioArray */
}, /* RadioButtons cluster */
NotDependent { }, TextBox {
gray,
{30, 20,185, 220 },
Tab Setting
},
/* [3] */
NotDependent { }, PopUp {
Font,
{20, 250, 40, 320},
{20, 330, 40, 450},
Font,
-f,
Select font specified files are to
assume,
hasDefault
},
Or {{1}}, EditPopUp {
FontSize,
{50, 250, 70, 320},
{50, 330, 70, 400},
Font Size,
-s,
User definable font,
Select from available fonts
},
NotDependent { }, MultiFiles {
Files ,
Select files whos resources are to
be deleted,
{155, 350, 175, 450},
,
,
MultiInputFiles {
{text},
,
,
}
},
NotDependent { }, CheckOption {
NotSet,
{100, 250, 115, 425},
Delete resource fork,
-d,
Delete all resources for the selected
files
}
} /* array itemArray */
}/* array dialogs */
};