Font Tool
Volume Number: | | 5
|
Issue Number: | | 3
|
Column Tag: | | Pascal Procedures
|
Related Info: Font Manager
How To Write a Font Tool for MPW
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 [if you come from Big Blue or have been inVAXinated, it might be familiar, but still not easy-ed]. 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 an 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 should 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[very nice to have.-ed]. 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 input), and diagnostic. As expected, standard input is the Macintosh keyboard. Standard output and diagnostic output are both the current topmost window found in the MPW environment.
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 pre-empting 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 pre-empting 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.
Next Month
Next month, we will develop a graphical interface, called the Commando interface, for the ChangeTextRes tool. We will also show how to add or modify Commando interfaces to other existing MPW Tools.
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. Publication rights granted to
MacTutor.
}
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}