BUY THIS BOOK
Add to Cart

Print Book $34.99


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint this content?


AppleScript in a Nutshell
AppleScript in a Nutshell By Bruce W. Perry
June 2001
Pages: 526

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: AppleScript: An Introduction
AppleScript is a scripting tool that installs with the Mac OS, including the newest release, Mac OS X. Programmers and power users use AppleScript to create scripts and applets, which are small Mac programs that can both accomplish useful tasks on their own and greatly extend the capabilities of other software systems.
This chapter covers the following topics:
  • How AppleScript is used (for example, for software automation and the attaching of scripts within an application's menus).
  • An overview of Apple events, a messaging technology that AppleScript uses to control scriptable applications. This section briefly describes (1) how AppleScript code sends Apple events, as well as (2) Apple event classes and objects.
  • Two applications that you can use to access and run your scripts from the file system: Script Runner (for Mac OS X) and OSA Menu (Mac OS 9). Chapter 2, is completely devoted to Script Editor, which is the script development environment that installs with the Macintosh OS.
  • AppleScript's language elements, such as data types, variables, handlers (i.e., subroutines or functions), and flow-control statements. This is a "quick reference" for the readers who want to dispense with narrative and dive right into scripting. Part II then covers all of these elements in detail.
AppleScript can be used for both simple, self-contained solutions, such as a program whose sole purpose is to monitor how much space is left on a disk, and comprehensive systems that automate or control a suite of software programs. Let's begin with a simple script type, a standalone applet that is not attached to or designed to automate another software program.
You generally create an applet by typing AppleScript source code into an Apple Computer scripting program called Script Editor. You then compile the script (if it does not have any errors) into a small program called a compiled script or an applet that can be double-clicked on the desktop. An AppleScript applet is a self-contained program with its own desktop icon, while a compiled script requires a host program like Script Editor or Script Runner (see "Using Script Runner with OS X" later in this chapter) to run it. Figure 1-1 shows an applet icon. Chapter 2 also explains the various options for saving an AppleScript.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Is AppleScript Used?
AppleScript can be used for both simple, self-contained solutions, such as a program whose sole purpose is to monitor how much space is left on a disk, and comprehensive systems that automate or control a suite of software programs. Let's begin with a simple script type, a standalone applet that is not attached to or designed to automate another software program.
You generally create an applet by typing AppleScript source code into an Apple Computer scripting program called Script Editor. You then compile the script (if it does not have any errors) into a small program called a compiled script or an applet that can be double-clicked on the desktop. An AppleScript applet is a self-contained program with its own desktop icon, while a compiled script requires a host program like Script Editor or Script Runner (see "Using Script Runner with OS X" later in this chapter) to run it. Figure 1-1 shows an applet icon. Chapter 2 also explains the various options for saving an AppleScript.
Figure 1-1: An applet icon
AppleScript is a great tool for writing everyday utilities, such as managing files, folders, disks, and networking activities. The utility scripts provide all the functionality you need, without the necessity to automate another software program. These tasks, such as file backups or getting a browser to access certain web pages, would be time-consuming and tedious if they always had to be performed manually. Two examples of scripts that I run at least once every day are:
  • A script that displays a dialog listing the names of all of the running programs on the Mac, including invisible background processes. I can select one or more of these programs and click a button on the dialog window to close them.
  • An applet that calculates the remaining free space on all of the volumes that are mounted on the desktop, then displays the result for each volume and the total free storage space on all of the volumes put together.
A single hard disk can be divided into several volumes, which the Mac OS represents as disk icons on the user's desktop.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Apple Events
AppleScript and scriptable programs communicate with each other via Apple events or internal, invisible messages. This section provides an overview of how Apple events are implemented with AppleScript. As this information goes beyond basic script development, some readers may choose to jump ahead to the book's language-reference sections, do some scripting, and then revisit this section at another time.
The Open Scripting Architecture, which has been present on the Mac since the early 1990s, is Apple Computer's mechanism for making interapplication communication available to a spectrum of scripting languages. AppleScript is the OSA language that Apple provides, but there are other OSA-compliant languages, including UserLand Frontier and JavaScript.
OSA accomplishes this "the-more-the-merrier" approach to scripting systems by using Apple events as the unifying technology. The situation is similar to Open Database Connectivity (ODBC) on the Windows platform, where any client application can talk to different database management systems using ODBC as a common conduit (as long as ODBC driver software exists for that particular database). In terms of OSA, the conduit (on Mac OS 9) is a scripting component that can convert whatever scripting language is used (AppleScript or JavaScript) into one or more properly constructed Apple events. Figure 1-3 shows the same Apple event being sent to an application in two different scripting languages.
Figure 1-3: OSA scripting tools send Apple events
Before AppleScripts or other scripting languages can be compiled and run, their corresponding extension files have to be installed (the AppleScript extension is included in an OS 9 installation) and then loaded into the computer's memory. The AppleScript extension or component is depicted in Figure 1-3.
Along with scripting components, another important OSA element is the Apple Event Registry. The Registry is an Apple Computer-maintained database that maps all of the Apple events that the Mac OS standard software uses to a corresponding English-language command. This means that the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Script Runner with OS X
OS X has a little application called Script Runner that you can use to run your scripts. Figure 1-8 shows what the open Script Runner looks like on the OS X desktop. You can find Script Runner in the AppleScript folder inside the Applications folder. Open the program by double-clicking it. If you want to add your own scripts to the Script Runner menu, choose "Open Scripts Folder" from the Script Runner menu. This opens a Finder window on to the following directory: /Users/yourname/Library/Scripts/. Then drag any compiled scripts (they have to be saved as compiled scripts) into this window. You can of course add compiled scripts to this /Scripts folder by navigating to it yourself (i.e., not using the Script Runner "Open Scripts Folder" menu command). After you close and restart Script Runner, you can run these scripts by choosing them in the Script Runner menu. If you create folders in the /Scripts folder, then Script Runner will display these folders as sub-menus. This is a good way to categorize and present lots of different scripts in the Script Runner menu.
Figure 1-8: Script Runner on OS X
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using OSA Menu with OS 9
I mentioned previously that you can run AppleScripts from within Script Editor or save them as applets that can be double-clicked. In Mac OS 9, an application called OSA Menu gives you a third script running option. OSA Menu is a non-Apple system extension that you can install from the OS 9 installation CD-ROM (you can find it in the folder CD Extras:AppleScript Extras). OSA Menu adds its own menu to the upper-right corner of the OS 9 Finder or desktop. Figure 1-9 shows the OSA Menu after it has been activated.
Figure 1-9: Activating the OSA Menu
The OSA Menu shows a list of compiled scripts that can be run straight from the desktop by choosing their filenames from the menu. OSA Menu will show the scripts that are stored in the following folder in OS 9: startup disk:System Folder:Scripts:Universal Scripts. To run properly from this menu, however, the AppleScripts have to be saved in Script Editor as compiled scripts, not applets. Chapter 2 contains more information on these script-saving options.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Checking Your AppleScript Version
This introduction would not be complete without mentioning how important it is to check which version of AppleScript is running on the machine executing your scripts. This is particularly true if your script is used on computers that might not be running Mac OS 9 or later. New versions of AppleScript are generally released along with the latest generation of the operating system. Mac OS 9 contains AppleScript Version 1.4 (an updated version of AppleScript, Version 1.4.3, also runs on OS 9). In the Spring of 2001, Mac OS 9.1 and Mac OS X used AppleScript 1.6.
There is an extremely simple way to find out which version of AppleScript is installed on the machine where the script is running. Checking the value of the version property in Script Editor will return the version number, as in 1.4 in Mac OS 9 or 1.3.4 in Mac OS 8.5. If you do not understand certain aspects of this script, Part II of the book is a detailed AppleScript language reference.
Your script can check the version property with code such as that shown in Example 1-6.
Example 1-6. Checking the AppleScript Version Number
set ASversion to version as string -- initialize ASversion to a string
set ASversion to (characters 1 thru 3 of ASversion as string) as real 
(* coerce ASversion to a real number like 1.4 *)
if ASversion is greater than or equal to 1.4 then (* test whether the version 
value is ≥ 1.4 *)
   display dialog "Good, you're running at least AppleScript 1.4" (* give the 
user some feedback with a dialog box *)
else
   display dialog "You're running AppleScript " & ASversion
end if
Example 1-6 first gets the AppleScript version property as a string value (e.g., "1.4") and stores it in an ASversion variable. The first three characters of this variable (such as 1.3 if the version was 1.3.4) are then coerced to a real type, as in 1.3. We had to take just the first three characters of the string because a string with two decimal points in it, as in 1.3.7, cannot be coerced to a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Diving In
No doubt there are readers who are eager to dive into AppleScripting before they go on to this book's upcoming language reference. This section summarizes the important AppleScript language elements you need to know before you start coding:
  • Case sensitivity
  • Statement termination
  • Line continuation character
  • Naming identifiers or variables
  • Variable declaration
  • Comments
  • Data types
  • Operators and reference forms
  • Flow-control statements
  • Subroutines
  • Script objects and libraries
All of these language elements are described in more detail in Part II (except for case sensitivity and statement termination, which are taken care of adequately in the following sections).
Unlike other scripting languages such as JavaScript and Perl, AppleScript is not case-sensitive. In other words, MYVAR is the same as myvar, or myfunc is the same as MyFunc in terms of function definitions. Script Editor will not let you define two functions with the same name, even if their letters are different combinations of upper- and lowercase characters. The numerous AppleScript constants and reserved words (case, current application, and other constants are covered in Chapter 6) cannot be reused as your own variable or method names. A script can change the values of predefined variables such as pi or space; however, scripters are better off using these predefined variables for the variables' intended purpose and creating their own variable names. Script Editor sees "pi" and "PI" as the same thing ("PI" would be corrected to "pi" when you compile the script). Class and command names within applications, while mostly lowercase, are corrected when you compile the script to the spelling that is specified in the app's dictionary. (Chapter 2 explains an application's dictionary.) For instance, if you typed the class name tcpip v4 configuration into Script Editor, inside of a tell app "Network Setup Scripting" block, it would be corrected to "TCPIP v4 configuration" when the statement was compiled.
You don't have to terminate an AppleScript statement using any special characters, as you do with Perl (the semi-colon character).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Using Script Editor with OS 9 and OS X
Unless you decide to use a commercial development environment to create scripts, the free Script Editor will be your principal AppleScripting tool. This is fine; many AppleScript purists have clung to Script Editor and still find it easy to use, even though it hasn't changed that much in years. Besides, it's free with the Mac OS 9 and OS X installation. You can find Script Editor in the /Applications/AppleScript folder in Mac OS X; in OS 9, this application is located in startup disk:Apple Extras:AppleScript.
Script Editor is particularly useful for creating the first versions of scripts using the Finder in OS 9. You can record most tasks involving the Finder (such as an action involving a file, folder, or disk), and then make any manual changes later in Script Editor. Chapter 1 , describes the recording of scripts.
The rest of this chapter is devoted to explaining the principal commands and controls of this program. I will also describe some basic scripting mechanics such as file-saving options and describe how to view dictionaries. The chapter concludes with an example applet that turns around and controls its creator.
Figure 2-1 shows what the Script Editor and its Results window (which displays the return values for its executed code) look like on the OS X desktop. The Script Editor includes controls and menus to:
Figure 2-1: Script Editor on OS X
  • Compile, save, and run AppleScripts
  • Record Apple events from recordable applications
  • Debug scripts with the Event Log and Result window
  • View other application's dictionaries (see the section "Dictionaries")
The Script window, shown in Figure 2-2 (from the OS 9 desktop) is where you edit and compile code. The other windows that are displayed and used by this program are dictionary windows, Event Log, and Result window (all these are discussed later in this chapter). The title bar of the window contains the name of the script next to a script icon that indicates which file type you saved it as (e.g., compiled script, applet). In Mac OS 9.1 and Mac OS X (i.e., AppleScript 1.5 and later), if you drag that icon to a disk folder the script will be moved to that folder.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Script Editor Controls/Commands
The Script window, shown in Figure 2-2 (from the OS 9 desktop) is where you edit and compile code. The other windows that are displayed and used by this program are dictionary windows, Event Log, and Result window (all these are discussed later in this chapter). The title bar of the window contains the name of the script next to a script icon that indicates which file type you saved it as (e.g., compiled script, applet). In Mac OS 9.1 and Mac OS X (i.e., AppleScript 1.5 and later), if you drag that icon to a disk folder the script will be moved to that folder.
All menu commands and windows attributed to Script Editor for OS 9 are replicated without any changes in OS X, except for the fact that the OS X Script Editor has been redesigned for the Aqua interface.
Figure 2-2: Script Editor window in OS 9
The following list describes the parts of the Script window:
  1. Description field . The text area at the top of the script window is called the description field. This space assumes the role of a global comment area for the script. You can use this area to type in information about a script's purpose, its properties, its functions, the scripting additions it may use, and any other helpful reminders to yourself or other script users. In addition, when creating a script to use an Apple Data Detector (ADD), use the description field to contain the type of detector that will be referenced in the script and other values. ADD is an intriguing Apple technology that allows you to run scripts that respond to contextual menu selections. Chapter 20, is devoted to ADD.
  2. Record . Pressing this button or typing Command-D turns on Script Editor's Apple-event recording capability. A cassette-tape icon will begin blinking in the upper left part of the computer screen on OS 9. Script Editor will only record Apple event code that originates from recordable apps, such as the Finder.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scripting the Script Editor
You can also use Script Editor as the target application for the Apple events sent from your script. If you are like me, you might want to begin your script in a more robust programmer's editor, such as BBEdit. Once you are ready to test and compile the code, the following script in Example 2-4 copies the text from BBEdit, and then pastes it into a new Script Editor window. This applet is for demonstration purposes only and performs marginal error-trapping for the sake of brevity (it only checks to see if BBEdit has an open window). The applet has been developed under Mac OS 9 and uses the open for access, write, and close access scripting-additions commands from the Standard Additions. (Scripting additions are covered in Appendix A.) Presumably, a tweaked version of this script could run on OS X; however, BBEdit had not yet released an OS X version of its text editor at the time of this writing.
Example 2-4. An AppleScript That Moves Script Code into a Script Editor File
(* this variable will store the BBEdit text and is initialized to a string *)
set allCode to ""

(* this variable will store the path to the Desktop folder and is initialized 
to a string *)
set deskPath to ""
tell application "BBEdit 5.0"
   try
      activate
      set allCode to (window text of document 1)
   on error errMessage
      display dialog "Looks like BBEdit does not have any open windows" &¬
      return & return & "Error: " & errMessage & return & return &¬
      "Exiting applet"
      return -- this return statement exits the applet's run handler
   end try
end tell

(* ask the user for a new filename then create a Script Editor file on the 
desktop *)
tell application "Finder"
   set frontmost to true
   display dialog¬
   set newScript to (the text returned in the result) as string
   make file at desktop with properties¬
   {name:newScript, file type:"TEXT", creator  type:"ToyS"}
   set deskPath to (desktop as string)
end tell

(* Use the 'write' scripting addition to write the code to the Script Editor file *)
tell application "Script Editor"
   activate
   set script_file to (deskPath & newScript) as alias
   open for access script_file with write permission
   write allCode to script_file
   close access script_file
   open script_file
end tell
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Data Types
In Chapter 1, I touched on data types, but now I will delve deeper! A data type describes how a programming system stores data in memory, and it is similar to the types used by other languages such as Java or Visual Basic. AppleScript data types specify the type of value that a variable stores (e.g., date, integer, string, real) or that an AppleScript command or scripting addition returns (see Appendix A). The data type that a variable stores determines what the script can do with it afterward, such as perform a math operation on an integer type or find out the length property (the number of characters) of a string type.
This chapter only describes the built-in AppleScript data types; however, a variable could also store a reference to an object such as a file, a web URL, or a database record (see Chapter 1 and its discussion of Apple event objects). Table 3-1 lists the data types described in this chapter, which also includes the correct syntax to use when storing a certain data type in a variable and the other data types to which a variable can allowably be cast or coerced.
Table 3-1: AppleScript Data Types
alias
real
boolean
record
class
reference
constant
RGB color
data
string
date
styled Clipboard Text
file specification
styled Text
integer
text
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Operators
Operators are symbols that programmers use to perform operations in AppleScript code, such as in mathematical expressions or equality tests. Operators (e.g., =, +, -, *) are familiar to programmers in other languages (such as Java and Perl), as well as young math students. In the following AppleScript code fragment, the * and the = characters are the operators:
2 * 10 = 20
With the exception of parentheses, AppleScript's operators (listed in Table 4-1) are binary operators, meaning that each operator takes an operand, such as a number, variable, or expression, on either side of it. In the previous code fragment, the 2 is the left-hand operand and the 10 is the right-hand operand for the * operator. Operators can also be used to test two expressions for equality or to combine two strings into one string, as in these two code fragments:
Set eq to (56.5 >= 56) (* the eq variable is set to true; the >= 
("greater than or equal to") operator is used to test two values for 
equivalence *)
Set twostrings to ("two strings" & " are now one string.") (* using 
the & string-concatenation operator *)
Table 4-1: AppleScript Operators
&
As
(  )
Begins with
*
Contains
+
Does not contain
-
Does not equal
/ ÷ div
Ends with
<
Is contained by
<= ≤
Is not contained by
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Reference Forms
This chapter describes the AppleScript reference forms, or the ways that you can specify or refer to one or more objects in AppleScript code. First we will describe the ten different reference forms, then the rest of the chapter provides a reference to the actual AppleScript reserved words (e.g., every, thru, whose) that you can use to identify or refer to objects in your code.
Here are the ten different reference forms:
Arbitrary Element
Using the reserved word some, AppleScript code can grab a random object in a container. Here is an example:
tell application "Finder"
    (* get a random image file from a desktop folder *)
    set randomImage to some file of folder "jpegs"
end tell
See the section on some.
Every Element
This type of reference form specifies every object of a certain class type in a container, such as:
tell application "Finder"
    set allFiles to every file in folder "today" (*  returns a list
    of file objects *)
end tell
See the section on every.
Filter
The Filter reference form specifies objects based on certain attributes, such as all files whose name ends with .txt. The where and whose reserved words are used in Filter references. See the whose section.
ID
The ID reference form can be used to grab an object based on the value of its ID property (if it has an ID property, that is.) The ID reference form is expressed in code with the AppleScript id reserved word. See the id section.
Index
The popular Index reference form specifies an object based on its numbered or indexed position in a container. The following example shows two ways to get the first file on a disk:
telll application "Finder"
    get file 1 of disk "backup"
    get first file of disk "backup"
end tell
See the sections on first and last.
Middle Element
The Middle Element reference form is designed to get the middle object of a certain class type in a container or the middle item of a list. See the section on middle.
Name
The Name reference form identifies an object by its name, as in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Variables and Constants
This chapter describes the rules for AppleScript variables, including variable scope and the special variables that you can add to your script called properties. The second part of this chapter is devoted to AppleScript's predefined variables such as pi and current application (a constant). These AppleScript variables are called constants because their value is predefined, and you mostly cannot use the same words for your own script variables. You could name one of your own variables pi (a predefined variable) and get away with it, but this would only confuse the readers of your code.
Here are two ways that you can create your own variables in AppleScript:
set int to 20 -- one way to set a variable to an integer

copy 20 to int -- another way
A variable is a word or identifier that the scripter creates to store a script value. An example is the int variable in the statement set int to 20. Along with copy, the set reserved word is used to set a variable name to a value, in this case an integer. AppleScript variables can store any value, including booleans, lists, numbers, records, strings, and application-defined classes. AppleScript variables have to begin with a letter or underscore ( _ ) character, but subsequent characters can include numbers and underscores. You cannot include operators and other symbols that AppleScript reserves for different uses (such as *, &, ^, or +) or special characters (such as $, @, or #). An exception to this rule in AppleScript allows the creation of memorable variable names if you use vertical-bar characters (|) to begin and end the identifier:
set |2$var*&^%#| to 2
AppleScript is not a case-sensitive language, so the variables that include the same characters but in varying case are treated as the same identifier. In other words, myname, myName, and MYNAME are all considered the same variable. Variable names can be one to several characters long, depending on your stylistic preferences.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Here are two ways that you can create your own variables in AppleScript:
set int to 20 -- one way to set a variable to an integer

copy 20 to int -- another way
A variable is a word or identifier that the scripter creates to store a script value. An example is the int variable in the statement set int to 20. Along with copy, the set reserved word is used to set a variable name to a value, in this case an integer. AppleScript variables can store any value, including booleans, lists, numbers, records, strings, and application-defined classes. AppleScript variables have to begin with a letter or underscore ( _ ) character, but subsequent characters can include numbers and underscores. You cannot include operators and other symbols that AppleScript reserves for different uses (such as *, &, ^, or +) or special characters (such as $, @, or #). An exception to this rule in AppleScript allows the creation of memorable variable names if you use vertical-bar characters (|) to begin and end the identifier:
set |2$var*&^%#| to 2
AppleScript is not a case-sensitive language, so the variables that include the same characters but in varying case are treated as the same identifier. In other words, myname, myName, and MYNAME are all considered the same variable. Variable names can be one to several characters long, depending on your stylistic preferences.
This AppleScript gives several examples of valid and invalid variable names, as well as how to use the set and copy keywords to declare a variable and store a value in it:
set l to {"a", "legal", "var"} as list (* a variable name can be one letter *)

set a_veryLong_but_legal30_variable500_name to "Too long in my opinion"

copy 500 to int (* using the copy keyword instead of set has the same effect on
integers *)

copy "A string" to str -- creating a string variable with copy

set $perl_string to "Can't imitate perl without pipe characters" (* this will 
raise a compiler error *)

set |$perl_string| to "Recreate a perl scalar variable if you use pipe¬ 
characters"

set 2str#in/g to "You can't start a variable with a number or use¬
special  symbols in it" (* another error, unless you enclose the characters in 
pipe symbols *)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constants and Predefined Variables
Constants are reserved words that AppleScript has given a predefined value that you cannot change. There are boolean constants (true or false), date constants (e.g., April, May), and considering or ignoring constants (e.g., case, white space), among others. Predefined variables, on the other hand, have a changeable value. In other words, you can use code such as set pi to 5 and the pi predefined variable will no longer have the value of about 3.14159 in your script! You cannot change the value of the boolean constant false, however (set false to 3 will not compile). The constants are listed in Table 6-1, and the Predefined Variables are listed in Table 6-2. Certain date and time values (i.e., minutes, hours, days, weeks) are changeable in a script like predefined values; however, they are grouped with other date constants for convenience.
Table 6-1: AppleScript Constants
all caps
all lowercase
application responses
ask
bold
case
condensed
current application
date and time constants (e.g., January, February)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Flow-Control Statements
The flow-control statements in AppleScript orchestrate the "flow" or the order in which the code statements execute in your scripts. Programmers will be familiar with AppleScript's if conditional statements, which are very similar to the syntax of Visual Basic, Perl, and other languages. These statements execute code only if the tested conditions are true. AppleScript handles loops in script code with several variations of the repeat statement, similar to the "for," "foreach," or "for each" statements in other languages. The repeat flow-control construct repeats the execution of code a specified number of times or for each member of a container, such as a list type. Or, it repeats a code phrase a specified number of times:
repeat 100 times...end repeat
You will be pleased to know that AppleScript has more than adequate error-trapping capabilities. This is accomplished by enclosing the statements that may raise errors in a try...end try statement block. In addition, you have already seen dozens of examples of the tell..end tell statement in earlier chapters. These statements specify the objects, usually application objects, that receive the commands or Apple events that your script sends. You specify the targets of different script commands by using these tell statements.
You can nest flow-control statements within other flow-control statements. Most of these statements end, appropriately, with the reserved word end, optionally followed by the statement identifier, such as tell or repeat. An example is:
tell app "Photoshop 5.5"...end tell
The if and tell statements allow "simple" rather than "compound" usage, such as:
if (current date) > date "1/1/2001" then display dialog "Welcome to 2001"
These simple statements appear on one line, they do not contain other code statements, and they do not need to be completed with the end reserved word. This code shows some nested flow-control statements and simple statements:
tell application "Finder"
   set freeMemoryBlock to largest free block
   (* Here's a simple statement; no 'end' is necessary *)
   if freeMemoryBlock < 10000000 then display dialog¬
   "Memory is getting low" 
   set listOfProcesses to name of processes
   if "BBEdit 5.0" is not in listOfProcesses then (* compound 'if' 
statement *)
      tell application "BBEdit 5.0" to run -- simple 'tell' statement
   end if
end tell
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 8: Subroutines
A subroutine is a piece of code or sequence of statements that is defined in a program or script and can be used repeatedly throughout that script. AppleScripters traditionally refer to this programming construct as a "handler." When the script calls the subroutine, the flow of code execution branches to the statements in the subroutine. Those statements are executed and may or may not return a value to the segment of the script that called the subroutine. Then the script execution resumes at the statement following the subroutine call.
AppleScript subroutines are not that much different than they are in other programming languages. AppleScript supports the creation of subroutines with positional parameters. This means that the subroutine definition begins with the keywords on or to and a subroutine name that does not clash with any of AppleScript's other predefined names (such as anything or pi), and then a set of parentheses that optionally lists any parameters or values that should be passed to the subroutine. The subroutine in Example 8-1 is called myfunc.
Example 8-1. Simple Subroutine Definition
on myfunc(s1,s2)
return (s1 & s2)
end myfunc"
This example concatenates or combines two strings that are passed to the subroutine as parameters (for the sake of brevity I have left out the typical checks that you would include for whether the parameters are valid strings). When calling myfunc in code, the parameters have to be in the same order as they are in the subroutine definition:
myfunc("one string ", "connected to another")
AppleScript also supports an unwieldy (my humble opinion, of course) form of subroutine that includes labeled parameters (see Section 8.2). This chapter concludes with a discussion of the five special built-in Apple-event handler types listed in Table 8-1.
Table 8-1: Five Built-in AppleScript Handlers
idle handler
open handler
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Subroutines with Positional Parameters
The AppleScript subroutines with positional parameters are simple to design and use, as long as you meet certain guidelines. The keywords on or to are required in the subroutine definition, followed by the name of the subroutine, and any parameters separated by commas and contained in parentheses. You have to use empty parentheses following the subroutine name if the subroutine will not take any parameters. The subroutine's name must comply with AppleScript's rules for identifiers. In AppleScript, the names that you create for variables and subroutines have to begin with a letter or underscore ( _ ) character, but subsequent characters can include letters, numbers, and underscores. Unless you begin and end the subroutine name with a vertical bar (|), you cannot include AppleScript's reserved words and operators such as *, &, ^, or +, or special characters such as $, @, or #.
The end keyword is required to signal the end of the subroutine definition. You can follow end with the subroutine name for the sake of readability:
On Squared(n1)...end Squared
This is not required, however; the compiler, Script Editor, does it for you. You can declare and give values to variables in AppleScript subroutines, and use the various flow-control statements such as:
if...then...end if
and:
repeat...end repeat
However, you cannot define another subroutine inside of a subroutine definition.
To call a subroutine, use the subroutine name followed by its parameters inside of parentheses:
Squared(7)
With subroutines that take positional parameters, you have to code the arguments in the same order as they appear in the subroutine definition. You have to include all of the specified arguments—the arguments in AppleScript subroutines are not optional (nor can they be declared as optional). Use empty parentheses with subroutine calls if the routine does not take any arguments. You can also use expressions, other variables, and other subroutine calls to give the parameters values, as in:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Subroutines with Labeled Parameters
These subroutine types are a slightly different animal than the subroutines with positional parameters, but they have some of the same rules. The keywords on or to are required in the labeled-subroutine definition, followed by the name of the subroutine, and optionally a nonlabeled parameter called a direct parameter. If the subroutine has a direct parameter (it does not have to), then the subroutine name has to be followed by the keyword of or in:
On Square of intOne...
Subroutines with labeled parameters are unwieldy to design compared with subroutines with positional parameters, but they make more subroutine calls resembling human language possible. The two different types of AppleScript subroutine designs are also a matter of personal taste, I suppose. Example 8-5 shows a labeled subroutine definition.
Example 8-5. Labeled Subroutine Definition
on Square of intOne above intLimit given Intclass:theClass
   if (intOne > intLimit) and (theClass is integer) then
      return intOne ^ 2
   else
      return 0
   end if
end Square
Square of myint above 0 given Intclass:(class of myint)
Example 8-6 redesigns the preceding subroutine using positional parameters instead.
Example 8-6. A Redesigned Subroutine Using Positional Parameters
on Square(intOne,intLimit,theClass)
   if (intLimit > 0) and (theClass is integer) then
      return intOne ^ 2
   else
      return 0
   end if
end Square
The rules on naming the subroutine (using local and global variables) and ending the subroutine definition are the same as those that apply to naming subroutines with positional parameters (see the previous section). In the following example, the direct parameter is followed by the first labeled argument, above intLimit:
on Square of intOne above intLimit given Intclass:theClass
Along with above, you can use the following AppleScript reserved words: about, against, apart from, around, aside from, at, below, beneath, beside, between, by, for, from, instead of, into, on, onto
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 9: Script Objects and Libraries
A script object is a template or class from which you can create AppleScript objects. Objects are self-contained script code that can have their own properties, methods, and variables. See Chapter 1 , for details on using objects in AppleScript.
When a script object is created in memory, that object is considered an instance (in object-oriented parlance) or copy of the template on which the object was based. The script object can be a collection of properties, a group of methods defined together (as a library, which is discussed in the section "Libraries"), or a bunch of properties, methods, and statements that comprise a single object. Script objects can inherit the properties and methods of a parent object simply by defining a parent property at the top of the script:
prop parent : MyParent
MyParent in this case is a variable that refers to another script object.
In summary, script objects represent a limited form of object-oriented programming in AppleScript. Considering that you can define objects and libraries on one machine, and create new instances of those objects or call methods in the library on another machine that shares a TCP/IP network, what you can achieve with AppleScript objects is limited only by the breadth of your imagination. This exciting new form of distributed computing on the Mac is called "program linking via IP".
Script Objects
You define an AppleScript script object using the basic syntax that Example 9-1 illustrates.
Example 9-1. Syntax for Creating a Script Object
script MyScript
 (* define properties, methods, variables here *)
end script
Use the syntax script...end script to define a script object within another script. For example, a single script could involve its own properties, subroutines, run handler, and one or more script objects. Used in this manner, a script object can be like a "type" that you define. Example 9-2 defines a Collection type within another script. A Collection involves one to several property/value pairs and methods that can return Collection values as well as add a new property/value pair to the Collection. In this case, the Collection object or type is defined at the top of the script and then demonstrated beneath the script-object definition. The example Collection involves the names of some planets followed by their diameters in kilometers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 10: Apple Guide and Help Viewer
With Mac OS 8.5 and beyond, Macintosh users have two pieces of system software to rely on for getting help on the Mac OS and programs: the Apple Guide extension and the new browser-based Help Viewer. Apple Guide (see Figure 10-1) is the tool that can be launched from the Help menu command of several programs. It usually provides the most basic software help, allowing the user to search a small help database and spawning little animations that circle and choose menu items for you. Mainly in response to the Web, Apple's system has since moved to a browser-based help system with the Help Viewer system application. Compared with Apple Guide, Help Viewer more closely integrates the operating-system help documents with web protocols and Sherlock 2. (Sherlock 2 is covered in Chapter 17.) You can find the Help Viewer in the following directory if you're running Mac OS 8.5 or later: startup disk:System Folder:Help:Apple Help Viewer:Help Viewer. This chapter describes the Apple Guide's and Help Viewer's dictionaries and gives some examples of how to script your own help systems.
Figure 10-1: An Apple Guide window
The scriptable Apple Guide extension is located in startup disk:System Folder:Extensions. You normally cannot open an application's Apple Guide file from outside the app, unless you are using trusty AppleScript. Example 10-1 opens up the BBEdit Guide file, goes instantly to the Look For help panel, and places the search term "grep" in that panel's search edit field. An AppleScript can be used as a software-testing device for new Mac help systems that use Apple Guide.
Example 10-1. Opening the BBEdit Guide File
(* Apple Guide's 'open' command can take a file specification type for a 
parameter *)
set filespec to¬
   "macintosh hd:BBEdit 5.0:BBEdit 5.0:BBEdit Guide" as file specification
tell application "Apple Guide"
   (* Use the 'string' labeled parameter and the 'ViewNumber' parameter 
   that takes an integer type *)
   open database filespec string "grep" ViewNumber 4
end tell
Apple Guide
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 11: Apple System Profiler
Apple System Profiler is a system program that gathers and displays everything you ever wanted to know about your software, hardware, and networking features, including a few things you wish you didn't know, such as how many extension files reside on your machine. The ASP is located in startup disk:System Folder:Apple menu Items; it is accessible from the Apple menu. A system administrator who is responsible for a lot of Macs could use AppleScript and ASP to print out customized reports on all the machines they are responsible for. Figure 11-1 shows the System Profile tab of the Apple System Profiler. The following dictionary reference applies to ASP Version 2.4.4, which is installed with Mac OS 9.04.
Figure 11-1: Apple System Profiler
Apple System Profiler
Syntax
tell app "Apple System Profiler"
   (* get the machine's IP address *)
   get TCPIP address
end tell
Dictionary commands
open object or list of objects
This command opens an ASP report, as in the following example:
set rep to "macintosh hd:desktop folder:ASP report" as alias 
tell application "Apple System Profiler"
   activate bring ASP to the front
   open rep
end tell
print object or list of objects to print
This prints a report, as in print ASPreportFile displaying print dialog true as text.
displaying print dialog (boolean)
This is an optional true/false value. If it's true, it displays a dialog for setting printing preferences prior to printing the ASP report.
as (text/shown on screen)
This is an optional labeled parameter involving whether to print out the report as text or as it is laid out on screen in the ASP document.
quit
This command quits ASP.
run
This command sends a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 12: Keychain Scripting and Apple Verifier
Mac OS 9 ships with a number of applications and files that help users protect their files, folders, and passwords from intruders. Apple Computer groups these technologies under the Apple Data Security umbrella term. These software tools include:
  • The Apple Verifier program, which verifies files that have been digitally signed
  • Apple File Signer software for applying digital signatures to files (this is only available in the Security Software Developers Kit)
  • Apple File Security, which you can use to encrypt and decrypt files
  • The Keychain Access control panel and Keychain Scripting, which involve the storage of passwords in a secure repository or database called a keychain file
  • Several extension files in the startup disk:System Folder:Extensions folder, including Security Cert Module, Security Library, Security Manager, Security Policy Module, Security Storage Module
Look in the startup disk:Applications:Security folder and you will find the Apple File Security and Apple Verifier programs. Apple File Security allows you to encrypt and decrypt files using a passphrase of five or more characters that you create. You must remember this password unless you have used Keychain Access with the file encryption, which is explained later in this chapter. Encryption mathematically scrambles the file data into a hodge-podge of nonsensical ASCII characters that look like Example 12-1, which is part of this paragraph after it was encrypted. It is extremely difficult, if not impossible (if they do not have your passphrases), for unintended or malicious recipients to break the code and decipher encrypted files.
Example 12-1. A Sample Portion of an Encrypted File
_!Åm¿__-#8_ÁÎ>°CºE_$ëBj,/Z.·,©._fnB,"†VS'íu,>…£1Ë-_éΣI_{_ÇRôY] *oe}g_
Z2<Ú¯e)EifÍ3&bEa_Ü__E,â#@aÍ'ÌÌ·k_m].¿__'__AQHuè·Ë…e>>é¤>/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 13: Desktop Printer Manager
Desktop Printer Manager (DPM), shown in Figure 13-1, is an application that was introduced in Mac OS 8.5. Located in the startup disk:System Folder:Scripting Additions directory, it is controlled entirely by Apple events and scripts. It does not have a graphical user interface or an Application Switcher icon. As an AppleScripter you have the privilege to control these applications that others rarely know exist, as long as they are scriptable.
Figure 13-1: Desktop Printer Manager application in the Scripting Additions folder
As you have probably figured out by its name, DPM lets you write powerful scripts that create and set several properties of desktop printers. These are desktop icons (they can be located in folders other than the Desktop folder) that can be used for printing or otherwise processing documents and files. You just drag and drop the document on to the icon, as you would when manually placing a file in a folder. Desktop printers can be created for PostScript printers, not, alas, with the trusty Hewlett-Packard DeskJet that is connected to my Mac. PostScript is an Adobe Systems graphics programming language that has become an industry printing standard. For instance, if you have a LaserWriter, which uses the LaserWriter 8 driver, then you can control desktop printers with DPM. You can also create desktop printers with the Desktop Printer Utility in the startup disk:Apple Extras:Apple LaserWriter folder.
Desktop Print Manager
Syntax
tell app "Desktop Printer Manager"
   (* Find out which installed drivers can work with desktop printers; a 
   list of these drivers is stored in the drivers variable, if your 
   computer has any supported drivers *)
   set drivers to supported drivers
end tell
The following dictionary commands and classes are based on the Desktop Printer Manager Version 1.0. The DPM has been scriptable since Mac OS 8.5 (in fact, it was introduced with that OS version).
Dictionary commands
run
This command sends DPM a
Additional content appea