AppleScript Scripting Additions Guide English Dialect
Apple Computer, Inc. © 1996 Apple Computer, Inc. All rights reserved. No part of this publication or the software described in it may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Computer, Inc. Printed in the United States of America. The Apple logo is a trademark of Apple Computer, Inc.
Contents Figures, Tables, and Listings Preface About This Guide vii ix Audience ix Organization of This Guide ix Sample Applications and Scripts x For More Information x Getting Started x AppleScript Language x Other AppleScript Dialects x Information for Programmers xi Conventions Used in This Guide xi Chapter 1 Introduction to Scripting Additions Installing Scripting Additions 1 Sending Scripting Addition Commands Chapter 2 Scripting Addition Commands 1 2 5 Scripting Addition Files 5 Command D
Display Dialog 22 Get EOF 27 Info For 28 List Disks 32 List Folder 33 Load Script 34 Log 36 New File 37 Offset 39 Open for Access 41 Path To 43 Random Number 46 Read 48 Round 54 Run Script 55 Scripting Components 57 Set EOF 58 Start Log 60 Stop Log 62 Store Script 63 Time to GMT 66 Write 68 Using Read/Write Commands Chapter 3 Writing Scripting Additions 70 85 Types of Scripting Additions 85 Apple Event Handler Scripting Addition 86 Apple Event Coercions Scripting Addition 87 The Scripting Addition Size
Appendix Scripting Additions at a Glance Scripting Addition Commands Placeholders 110 Index 105 105 113 v
Figures, Tables, and Listings Chapter 1 Introduction to Scripting Additions Figure 1-1 Chapter 2 Chapter 3 A scripting addition icon Scripting Addition Commands 1 5 Figure 2-1 Figure 2-2 Figure 2-3 Figure 2-4 Figure 2-5 Figure 2-6 Figure 2-7 A Choose Application dialog box 14 A Choose File dialog box 16 A Choose Folder dialog box 18 A Display Dialog dialog box 23 Alert icons 26 A New File dialog box 38 The Script Editor’s Event Log window Table 2-1 Scripting addition commands described in this gu
P R E F A C E About This Guide The AppleScript Scripting Additions Guide: English Dialect describes the scripting additions that accompany the AppleScript English dialect of the AppleScript language. Scripting additions are files that extend the capabilities of the AppleScript language by providing additional commands you can use in scripts. Audience 0 This guide is for anyone who wants to write new scripts or modify existing scripts.
P R E F A C E At the end of the guide are one appendix and an index. ■ The appendix, “Scripting Additions at a Glance,” summarizes the commands defined by the standard scripting additions. Sample Applications and Scripts 0 A sample application, the Scriptable Text Editor, is included with AppleScript. The Scriptable Text Editor is scriptable; that is, it understands scripts written in the AppleScript language.
P R E F A C E describes the terms defined by the standard scripting additions that come with the AppleScript English dialect. Scripting additions intended for use with other dialects work the same way but define terms and syntax appropriate for those dialects.
P R E F A C E xii (a group). . . Three ellipsis points (. . .) after a group defined by parentheses indicate that you can repeat the group of elements within parentheses one or more times. a|b|c Vertical bars separate elements in a group from which you must choose a single element. The elements are often grouped within parentheses or brackets.
C H A P T E R Figure 1-0 Listing 1-0 Table 1-0 1 Introduction to Scripting Additions 1 Scripting additions are files that extend the capabilities of the AppleScript language by providing additional commands or coercions you can use in scripts. They are similar to XCMDs and XFCNs in HyperTalk. This chapter describes how to install scripting additions and briefly describes how scripting addition commands work.
C H A P T E R 1 Introduction to Scripting Additions Each scripting addition file contains one or more command handlers. If a scripting addition file is located in the Scripting Additions folder (in the Extensions folder of the System Folder), the command handlers it provides are available for use by any script whose target is an application on that computer. Some scripting additions also define object classes for records returned by their commands.
C H A P T E R 1 Introduction to Scripting Additions Scriptable Text Editor becomes the frontmost application (that is, its menus become visible and its windows become the frontmost windows on the screen) and passes the command to the scripting addition’s handler for the Display Dialog command, which displays the dialog box.
C H A P T E R 1 Introduction to Scripting Additions For example, the Offset command provided by the String Commands scripting addition reports the offset, in characters, of a string within another string. Offset is also a property of several Scriptable Text Editor objects and is thus a word in the Scriptable Text Editor dictionary. Therefore, you cannot use Offset as a scripting addition command within Tell statements to the Scriptable Text Editor.
C H A P T E R Figure 2-0 Listing 2-0 Table 2-0 2 Scripting Addition Commands 2 This chapter describes what the standard AppleScript scripting addition commands do and how to use them in scripts. The first two sections summarize the standard scripting addition files and the commands they provide. The last section describes in more detail how to use the commands provided by the Read/Write scripting addition, whose commands are usually used together.
C H A P T E R 2 Scripting Addition Commands Table 2-1 Name of scripting addition file Scripting addition commands described in this guide Name of command Description of command Activate Activates an application. Log Places a string between comment characters in the Script Editor’s Event Log Window. Start Log Turns logging on in the Script Editor’s Event Log window. Stop Log Turns logging off in the Script Editor’s Event Log window. Beep Beep Plays the alert sound.
C H A P T E R 2 Scripting Addition Commands Table 2-1 Scripting addition commands described in this guide (continued) Name of scripting addition file Name of command Description of command Load Script Load Script Loads a compiled script into the current script as a script object. New File New File Allows a user to create a new file. Numerics Random Number Generates a random number. Round Rounds a number to the nearest integer. Close Access Closes a file opened with Open for Access.
C H A P T E R 2 Scripting Addition Commands Table 2-1 Scripting addition commands described in this guide (continued) Name of scripting addition file Name of command Description of command String Commands ASCII Character Converts a number to its ASCII equivalent. ASCII Number Returns the ASCII number of a character. Offset Determines the offset of a string within another string. Time to GMT Returns the difference, in seconds, between the current time and Greenwich mean time.
C H A P T E R 2 Scripting Addition Commands SYNTAX activate referenceToApplication PARAMETER referenceToApplication A reference of the form application nameString (see “Notes”).
C H A P T E R 2 Scripting Addition Commands To specify an application on a remote computer, you must use a string that consists of the name of the application as it would be listed in the Application menu ("ApplicationName"), and you must also specify the name of the computer and if necessary the zone in which the computer is located. The application must be running. The Activate command does not launch applications on remote machines.
C H A P T E R 2 Scripting Addition Commands EXAMPLES ASCII character 100 --result: "d" ASCII character 101 --result: "e" ERRORS Error number Error message –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid. –1705 Operation involving a list item failed. –1718 Reply has not yet arrived. –1720 Invalid range.
C H A P T E R 2 Scripting Addition Commands PARAMETER string An ASCII character. Class: String RESULT The ASCII number that corresponds to the specified character. EXAMPLES ASCII number "d" --result: 100 ASCII number "e" --result: 101 ERRORS 12 Error number Error message –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid. –1705 Operation involving a list item failed.
C H A P T E R 2 Scripting Addition Commands Beep 2 The Beep command plays the alert sound for the Macintosh. It is the only command provided by the Beep scripting addition. SYNTAX beep [ numberOfBeeps ] PARAMETER numberOfBeeps The number of times to play the alert sound. If you omit numberOfBeeps, the alert sound is played once.
C H A P T E R 2 Scripting Addition Commands Choose Application 2 The Choose Application command allows the user to choose a running application from a dialog box like the one shown in Figure 2-1. Figure 2-1 A Choose Application dialog box The dialog box displays applications on the current computer and on any computer connected to the same network. Choose Application is the only command provided by the Choose Application scripting addition.
C H A P T E R 2 Scripting Addition Commands PARAMETERS promptString The prompt to be displayed in the dialog box. The prompt can be up to 255 characters long, but the standard dialog box has room for only about 50 characters. If you omit the with prompt parameter, the string "Choose a program to link to:" is displayed. Class: String Default Value: "Choose a program to link to:" appListLabel The label above the list of applications displayed in the dialog box.
C H A P T E R 2 Scripting Addition Commands ERRORS Error number Error message –108 Out of memory. –128 User canceled. Choose File 2 The Choose File command displays a dialog box like the one in Figure 2-2 to allow the user to choose a file. Figure 2-2 A Choose File dialog box The Choose File command is one of two commands provided by the Choose File scripting addition.
C H A P T E R 2 Scripting Addition Commands PARAMETERS promptString The prompt to be displayed in the dialog box. The prompt can be up to 255 characters long, but the standard dialog box has room for only about 40 characters. If you omit the with prompt parameter, no prompt is displayed. Class: String Default Value: (no prompt) listOfTypes A list of the file types of the files to be displayed in the dialog box.
C H A P T E R 2 Scripting Addition Commands Choose Folder 2 The Choose Folder command displays a dialog box like the one in Figure 2-3 to allow the user to choose a directory (that is, a folder, a volume, or the desktop). Figure 2-3 A Choose Folder dialog box The Choose Folder command is one of two commands provided by the Choose File scripting addition. SYNTAX choose folder [ with prompt promptString ] PARAMETERS promptString 18 The prompt that appears in the dialog box.
C H A P T E R 2 Scripting Addition Commands RESULT A reference of the form file "Disk:Folder1:Folder2:...:Foldername" for the directory specified by the user, if any. EXAMPLE choose folder with prompt "Choose a folder or volume:" NOTES If the user clicks Cancel in the Choose Folder dialog box, AppleScript returns error number –128. If you want your script to continue after the user clicks Cancel, you must include an error handler.
C H A P T E R 2 Scripting Addition Commands PARAMETER referenceToFile A reference of the form file nameString or alias nameString, or a file reference number returned by a previous call to the Open for Access command (see “Notes”). Class: Reference or integer RESULT None EXAMPLES This example closes the file named To Donald in the specified location if it was previously opened with the Open for Access command.
C H A P T E R 2 Scripting Addition Commands If you specify a reference to a file or an alias, the Close Access command attempts to match the reference with a file previously opened with the Open for Access command. If a match is found, Close Access closes the file. If no match is found, Close Access returns error number –43. If you specify a file reference number previously obtained with the Open for Access command, Close Access closes the file immediately.
C H A P T E R 2 Scripting Addition Commands EXAMPLES set timeOfTransfer to current date get timeOfTransfer if (current date) = ¬ date "Saturday, January 23, 1993 12:00:00 AM" then print the front window else return "The date is not " & ¬ "Saturday, January 23, 1993 12:00:00 AM" end if ERRORS Error number Error message –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid.
C H A P T E R 2 Scripting Addition Commands Figure 2-4 A Display Dialog dialog box SYNTAX display dialog questionString [ default answer answerString ] [ buttons buttonList] [ default button buttonNumberOrName ] [ with icon iconNumberOrName ] ¬ ¬ ¬ ¬ PARAMETERS questionString The string displayed in the dialog box. The string can be up to 255 characters long. Class: String answerString The default string provided in a text field that the user can edit.
C H A P T E R 2 Scripting Addition Commands buttonNumberOrName The default button. You can specify the default button with a string (the string provided for the button in buttonList) or with an integer (which specifies the position of the button in the buttonList list; 1 specifies the first button from the left, 2 specifies the second button from the left, and so on). Class: String or integer iconNumberOrName The icon to be included in the dialog box.
C H A P T E R 2 Scripting Addition Commands set prompt to "Please enter password:" repeat with i from 1 to 4 set dialogResult to display dialog prompt ¬ buttons {"I give up", "OK"} default button 2 ¬ default answer "Joe User" with icon 1 if button returned of dialogResult = "I give up" then error number -128 --user canceled else if text returned of dialogResult = "magic" then exit else if i < 3 then set prompt to "Password was incorrect. Try " ¬ & i + 1 else set prompt to ¬ "Password was incorrect.
C H A P T E R 2 Scripting Addition Commands The System file provides three standard icons to warn the user about problems. These icons, illustrated in Figure 2-5, have the following meanings: ■ ■ ■ Stop (icon number 0). Use this icon to call attention to a serious problem that requires the user to choose from alternative courses of action. Note (icon number 1). Use this icon to provide information about a situation that has no drastic effects. The user usually responds by pressing the OK button.
C H A P T E R 2 Scripting Addition Commands Get EOF 2 The Get EOF command returns an integer that indicates the offset, in bytes, of the end of a specified file from the beginning of the file. It is one of several commands provided by the Read/Write Commands scripting addition. For more information about these commands, see “Using Read/Write Commands,” which begins on page 71.
C H A P T E R 2 Scripting Addition Commands If you specify a reference to a file or an alias, the Get EOF command attempts to match the reference with a file previously opened with the Open for Access command. (It doesn’t matter whether the file was opened with read-only permission or with write permission.) If a match is found, Get EOF returns an integer indicating the offset of the end of the file. If no match is found, Get EOF opens the file, gets the end of the file, then closes the file.
C H A P T E R 2 Scripting Addition Commands RESULT A record of object class File Info (defined by the File Commands scripting addition) that contains the following properties: Name of file or folder. Class: String creation date Date and time the file or folder was first created. Class: Date modification date Date and time the file or folder was last modified. Class: Date icon position Location of the upper-left corner of the file or folder’s icon.
C H A P T E R 2 Scripting Addition Commands Indicates whether the file or folder is locked (true) or unlocked (false). Class: Boolean Modifiable? No file creator Four-character creator code of the file. Returned for files only. Class: String Modifiable? No file type Four-character code for the file type of the file. Returned for files only. Class: String Modifiable? No short version The file’s short version, if any. Returned for files only.
C H A P T E R 2 Scripting Addition Commands This example returns just the file type for Scriptable Text Editor. set x to info for ¬ file "Turing’s World:Scriptable Text Editor" x's file type --result: "APPL" This example displays a dialog box if the Scriptable Text Editor isn’t locked. if locked of ¬ (info for file "Hard Disk:Scriptable Text Editor") ¬ is false then display dialog "Scriptable Text Editor is not locked.
C H A P T E R 2 Scripting Addition Commands List Disks 2 The List Disks command returns a list containing the names of every mounted volume, including CD-ROMs, floppy disks, AppleShare volumes, and so on. List Disks is one of several commands provided by the File Commands scripting addition. SYNTAX list disks RESULT The result is a list of strings. EXAMPLE list disks --result: {"My Disk", "Our Server", "Joe's Floppy"} ERROR 32 Error number Error message –35 Disk wasn't found.
C H A P T E R 2 Scripting Addition Commands List Folder 2 The List Folder command returns a list of every file and folder in a specified folder or volume. List Folder is one of several commands provided by the File Commands scripting addition. SYNTAX list folder referenceToFolder PARAMETER referenceToFolder A reference of the form file nameString, alias nameString, or folder nameString (see “Notes”). Class: Reference or string RESULT A list of strings.
C H A P T E R 2 Scripting Addition Commands ERRORS Error number Error message –35 Disk wasn't found. –37 Bad name for file. –43 File wasn't found. –50 Parameter error. –108 Out of memory. –120 Folder wasn't found. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1703 Some data was the wrong type. –1704 Some parameter was invalid. –1705 Operation involving a list item failed.
C H A P T E R 2 Scripting Addition Commands PARAMETER referenceToFile A reference of the form file nameString or alias nameString (see “Notes”). The file must be a compiled script file or a script application file. It cannot be a text file. Class: Reference RESULT A script object. EXAMPLES The following example loads a compiled script called Numeric Operations and stores the resulting script object in the variable NumericLib.
C H A P T E R 2 Scripting Addition Commands ERRORS Error number Error message –108 Out of memory. –192 Bad name for file. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1703 Some data was the wrong type. –1704 Some parameter was invalid. –1705 Operation involving a list item failed. –1718 Reply has not yet arrived.
C H A P T E R 2 Scripting Addition Commands RESULT None EXAMPLE log "This string appears in the Log Events window" After running the preceding script, this text appears in the Log Events window: (* This string appears in the Log Events window" *) NOTES The Log command works even if logging has not been turned on with the Start Log command or has been turned off with the Stop Log command.
C H A P T E R 2 Scripting Addition Commands Figure 2-6 A New File dialog box SYNTAX new file [ with prompt promptString ] [ default name defaultName ] PARAMETERS promptString The prompt that appears in the dialog box. The string you specify can be up to 255 characters long. If you omit the with prompt parameter, the prompt "New File Name" is displayed. Class: String Default Value: "New File Name" defaultName The default filename that appears in the dialog box.
C H A P T E R 2 Scripting Addition Commands EXAMPLES set x to new file open for access x NOTES If the user chooses the Cancel button, New File returns error –128. If you want your script to continue after the user clicks Cancel, you must include an error handler. For information about Tell statements and error handlers, see Chapter 8, “Handlers,” of the AppleScript Language Guide. ERRORS Error number Error message –108 Out of memory. –128 User canceled.
C H A P T E R 2 Scripting Addition Commands PARAMETERS stringToFind stringToSearch The string to find in stringToSearch. Class: String A string containing stringToFind. Class: String RESULT The result is an integer that indicates the offset, in number of characters, of the first character of stringToFind from the beginning of stringToSearch. If stringToFind is not contained within stringToSearch, AppleScript returns the value 0.
C H A P T E R 2 Scripting Addition Commands ERRORS Error number Error message –50 Parameter error. –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid. –1705 Operation involving a list item failed. –1708 doesn't understand the message. –1718 Reply has not yet arrived.
C H A P T E R 2 Scripting Addition Commands PARAMETERS referenceToFile Boolean A reference of the form file nameString or alias nameString. If you specify an alias, the file must already exist, because AppleScript must locate the file before running the script. If you specify a file that doesn’t exist using the form file nameString, Open for Access creates a TeachText document of that name at the specified location and opens it for access.
C H A P T E R 2 Scripting Addition Commands tell application "Scriptable Text Editor" open for access alias "Hard Disk:Aliases:To Donald" ¬ with write permission end tell NOTES To specify the name (nameString) of a file, use a string of the form "Disk:Folder1: Folder2:...:Filename" as described in Chapter 5, “Objects and References,” of the AppleScript Language Guide.
C H A P T E R 2 Scripting Addition Commands SYNTAX path to folderOrApplication [ as className ] PARAMETERS folderOrApplication One of these constants: apple menu apple menu items control panels desktop extensions preferences printmonitor printmonitor documents trash startup items system folder temporary items startup disk frontmost application className The class identifier string. If you omit this parameter, the pathname is returned as an alias.
C H A P T E R 2 Scripting Addition Commands tell application "Scriptable Text Editor" activate tell application "HyperCard" to activate set x to path to frontmost application end tell return x --result: alias "Hard Disk:Applications:HyperCard" NOTES The optional as parameter is useful if you send the Path To command to an application on a remote computer.
C H A P T E R 2 Scripting Addition Commands Random Number 2 The Random Number command generates a random number. It is one of two commands provided by the Numerics scripting addition. SYNTAX random number [ numberToRandomize ] [ from beginningNumber to endNumber ] [ with seed seedNumber ] ¬ ¬ ¬ PARAMETERS numberToRandomize A number that specifies the upper limit of the range within which you want to generate a random number.
C H A P T E R 2 Scripting Addition Commands RESULT A random number within the specified limits. If no parameters are included, Random Number returns a real value between 0.0 and 1.0. EXAMPLES display dialog "A random number between 0 and 1: " & ¬ (random number) display dialog ¬ "A random integer between 1 and 10: " & ¬ (random number from 1 to 10) display dialog ¬ "A random real value between 1 and 10.0 : " & ¬ (random number from 1 to 10.0) display dialog ¬ "A random real value between -10.
C H A P T E R 2 Scripting Addition Commands Reseeding with the value 0 causes the seed to be reset to a random value each time the command is called. display dialog ¬ "After reseeding with 0, a truly random number: " & ¬ (random number from 1 to 10 with seed 0) ERRORS Error number Error message –50 Parameter error. –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid.
C H A P T E R 2 Scripting Addition Commands SYNTAX read referenceToFile [ from startingByte ] [ for bytesToRead | to byteToReadTo | until delimiterIncluded | before delimiterExcluded ] [ as className [ using delimiter[s] delimiters ] ] ¬ ¬ ¬ PARAMETERS referenceToFile A reference of the form file nameString or alias nameString, or a file reference number previously obtained with the Open for Access command (see “Notes”).
C H A P T E R 2 Scripting Addition Commands from the specified starting point to the specified delimiter; otherwise, the Read command begins reading at the file mark. Class: String delimiterExcluded A delimiter (such as a tab or return character) to which to read. The specified delimiter is not included in the read.
C H A P T E R 2 Scripting Addition Commands The next example reads MyFile starting at the end of the file and reading backward until the third byte from the end. read file "Hard Disk:MyFile" from -1 to -3 If the last characters of file MyFile were "123456", the preceding example would return "654". NOTES The file mark is a marker used by the File Manager that indicates the byte at which the Read command expects to begin reading data. By default, the file mark is the first byte of the file.
C H A P T E R 2 Scripting Addition Commands You can use the as className parameter to specify how the Read command should interpret the data it reads. If data to be read is not a valid value for the specified value class, the Read command returns an error. The rest of this section describes some of the value classes you can specify and the nature of the data returned if the Read command reads the data successfully.
C H A P T E R 2 Scripting Addition Commands more than one short value, Read returns a list of shorts. If the data is text, you can specify the delimiters used in the data with the using delimiter parameter, and the Read command attempts to coerce each item between delimiters to a short. as boolean If the data consists of a 1-byte Boolean value, Read returns the Boolean value. If the data consists of more than one Boolean value, Read returns a list of Boolean values.
C H A P T E R 2 Scripting Addition Commands Round 2 The Round command rounds or truncates a number to an integer. It is one of two commands provided by the Numerics scripting addition. By default, Round rounds to the nearest number. You may also include an optional parameter to specify rounding up, down, toward zero, or to the nearest number. SYNTAX round number ¬ [ rounding ( up | down | toward zero | to nearest ) ] PARAMETER number The number to round.
C H A P T E R 2 Scripting Addition Commands display dialog "round -3.67 toward zero: " & ¬ (round -3.67 rounding toward zero) & return & ¬ "round 3.67 toward zero: " & ¬ (round 3.67 rounding toward zero) display dialog "round -3.67 to nearest: " & ¬ (round -3.67 rounding to nearest) & return & ¬ "round 3.67 to nearest: " & ¬ (round 3.67 rounding to nearest) ERRORS Error number Error message –50 Parameter error. –108 Out of memory. –1700 Can't make some data into the expected type.
C H A P T E R 2 Scripting Addition Commands PARAMETERS referenceOrString A reference of the form file nameString or alias nameString that specifies a script file, or a string that consists of a valid script. Class: Reference or string listOfParameters A list of parameters to be passed to the Run handler of the target. Class: List scriptingComponent The name of the scripting component to use when running the script. Class: String RESULT Value returned by script that is run.
C H A P T E R 2 Scripting Addition Commands NOTES To specify the name (nameString) of a script file, use a string of the form "Disk:Folder1:Folder2:...:Filename" as described in Chapter 5, “Objects and References,” of the AppleScript Language Guide. If you specify only the name of the file (Filename) instead of its entire pathname, AppleScript attempts to find the file in the current directory. ERRORS Error number Error message –50 Parameter error. –108 Out of memory. –192 Bad name for file.
C H A P T E R 2 Scripting Addition Commands RESULT A list of strings. EXAMPLES scripting components --result: {"AppleScript"} NOTES A scripting component is a software component, such as AppleScript, that supports the Open Scripting Architecture (OSA). The OSA provides a mechanism, based on Apple events, that allows users to control multiple applications by means of scripts written in a variety of scripting languages. Each scripting language corresponds to a single scripting component.
C H A P T E R 2 Scripting Addition Commands PARAMETERS referenceToFile integer A reference of the form file nameString or alias nameString, or a file reference number returned by a previous call to the Open for Access command. Class: Reference or integer The number of bytes to which to set the offset of the end of the file.
C H A P T E R 2 Scripting Addition Commands IMPORTANT If the file is longer than the end of file set by Set EOF, it is truncated to the specified size and any additional data is lost. If the file is shorter than the end of file set by Set EOF, it is extended to the new length, but the additional data in the new part of the file is meaningless. ▲ ERRORS Error number Error message –34 Disk is full. –38 File wasn't open. –44 Disk is write protected.
C H A P T E R 2 Scripting Addition Commands Figure 2-7 The Script Editor’s Event Log window SYNTAX start log RESULT None EXAMPLE The example that follows demonstrates how to start logging and demonstrates how logging works. To see descriptions in AppleScript of the logged events generated by this example, open the Event Log window in the Script Editor application by choosing Open Event Log from the Controls menu.
C H A P T E R 2 Scripting Addition Commands ERRORS Error number Error message –50 Parameter error. –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid. –1705 Operation involving a list item failed. –1708 doesn't understand the message. –1718 Reply has not yet arrived. Stop Log 2 The Stop Log command turns off logging in the Script Editor’s Event Log window.
C H A P T E R 2 Scripting Addition Commands NOTES The Log command works even if logging has been turned off with the Stop Log command. If the Stop Log command is sent before the Log command, logging will still be turned off after the Log command is sent. ERRORS Error number Error message –50 Parameter error. –108 Out of memory. –1700 Can't make some data into the expected type. –1701 Some parameter is missing for . –1704 Some parameter was invalid.
C H A P T E R 2 Scripting Addition Commands PARAMETERS scriptObjectVariable The name of a script object declared previously in the same script. Class: Script referenceToFile A reference of the form file nameString or alias nameString (see “Notes”). If this parameter is omitted, Store Script displays a directory dialog box and requests that the user choose a file in which to store the script. Class: Reference replacementOption One of the constants ask, yes, or no.
C H A P T E R 2 Scripting Addition Commands This example stores the script object DemoStore in a file called Store My RGB: store script DemoStore in file ¬ "My HD:Some Folder:Store My RGB" replacing yes The replacing yes parameter indicates that Store Script should overwrite the existing file.
C H A P T E R 2 Scripting Addition Commands Error number Error message –1704 Some parameter was invalid. –1705 Operation involving a list item failed. –1708 doesn't understand the message. –1718 Reply has not yet arrived. Time to GMT The Time to GMT command returns the difference, in seconds, between the current time and Greenwich mean time (GMT). It is the only command provided by the Time to GMT scripting addition. SYNTAX time to GMT PARAMETERS None.
C H A P T E R 2 Scripting Addition Commands time to GMT --result: -28800 You can then use this value to write a script that tells you the time difference between the time in any other time zone and the current time in Cupertino: property offsetFromCupertino : -28800 set x to ((time to GMT) ÷ 60) ÷ 60 set y to x - (((offsetFromCupertino) ÷ 60) ÷ 60) if y = 0 then display dialog ("Same time zone as Cupertino") as string else if y > 0 then display dialog (y & " Hours Ahead of Cupertino") as string else disp
C H A P T E R 2 Scripting Addition Commands Error number Error message –1705 Operation involving a list item failed. –1708 doesn't understand the message. –1718 Reply has not yet arrived. Write 2 The Write command writes data to a specified file, beginning at the file mark. It is one of several commands provided by the Read/Write Commands scripting addition. For more information about these commands, see “Using Read/Write Commands,” which begins on page 71.
C H A P T E R 2 Scripting Addition Commands startingByte Specifies the offset of the byte at which to begin writing. A positive integer indicates the offset from the beginning of the file, and a negative integer indicates the offset from the end of the file. Class: Integer RESULT None EXAMPLES This example writes “abcde” to the file MyFile.
C H A P T E R 2 Scripting Addition Commands To set the file mark without reading or writing data, write a string of zero length to the byte to which you want to set the mark. For example, this script sets the file mark for the file specified by fileRefNum to the fourth byte in the file: write "" to fileRefNum starting at 4 To specify the name (nameString) of a file, use a string of the form "Disk:Folder1: Folder2:...
C H A P T E R 2 Scripting Addition Commands ERRORS Error number Error message –34 –38 –44 –45 –49 –50 –51 –61 –108 Disk is full. File wasn't open. Disk is write protected. File is locked. File is already open. Parameter error. File reference number error. File not open with write permission. Out of memory.
C H A P T E R 2 Scripting Addition Commands You can use the Read/Write commands with either text-based data or binary data. Most databases can export data as text, with fields and records separated by delimiters, and some store their data as text files. The examples in this section demonstrate how to use the Read/Write commands with text-based data.
C H A P T E R 2 Scripting Addition Commands display dialog errString close access x end try on ReadRecord(numberOfFields, whichRecord, fieldDelimiter, ¬ recordDelimiter, fileRefNum) try (* if there’s a record delimiter, read all fields except for last using field delimiter, then read last field using record delimiter *) if recordDelimiter is "" then set readxTimes to numberOfFields else set readxTimes to numberOfFields - 1 end if repeat whichRecord times set recordData to {} repeat (readxTimes) times set
C H A P T E R 2 Scripting Addition Commands The ReadRecord handler shown in Listing 2-1 takes five parameters: numberOfFields The number of fields in the record. whichRecord An integer that identifies the position of the desired record. fieldDelimiter The delimiter used in the file to separate fields. recordDelimiter The delimiter (if any) used to separate records. If the file doesn’t use a different delimiter to separate records, this parameter must be set to "".
C H A P T E R 2 Scripting Addition Commands try set x to open for access pathToUse with write permission DeleteRecord(10, 1, tab, return, x) close access x on error errString number errNum display dialog errString close access x end try on DeleteRecord(numberOfFields, whichRecord, ¬ fieldDelimiter, recordDelimiter, fileRefNum) try --initialize variables set startSize to get eof fileRefNum --current size set idx to 1 --counter set preRecordSize to 1 --offset of record to delete set accumulatedSize to 0 --
C H A P T E R 2 Scripting Addition Commands (* if record to delete is the first record in file or the next record that will be read, set preRecordSize *) if whichRecord is 1 or idx is whichRecord - 1 then if whichRecord is 1 then set preRecordSize to 1 else set preRecordSize to accumulatedSize end if end if end repeat (* now that preRecordSize is determined, read the record to be deleted so file mark is set to beginning of next record *) set fileBuffer to read fileRefNum from accumulatedSize + 1 --next,
C H A P T E R 2 Scripting Addition Commands The DeleteRecord handler shown in Listing 2-2 takes five parameters: numberOfFields The number of fields in each record. whichRecord An integer that identifies the position of the record you want to delete. fieldDelimiter The delimiter used in the file to separate fields. recordDelimiter The delimiter (if any) used to separate records. If the file doesn’t use a different delimiter to separate records, this parameter must be set to "".
C H A P T E R 2 Scripting Addition Commands try (* first put the record to be added into a variable; in this case the record to be added is actually an AppleScript list because the file on disk doesn’t include label data *) set newRecord to ¬ {"Granny", "Smith", "123 Potato Chip Lane", ¬ "Palo Minnow", "CA", "98761", "Snackable Computer", ¬ "888-987-0987", "978 -234-5432", "123-985-1122"} set x to open for access pathToUse with write permission AddRecord(newRecord, 5, tab, return, x) close access x on er
C H A P T E R 2 Scripting Addition Commands set postBuffer to read fileRefNum from 1 (* before writing new record, file mark must be reset to beginning of file; to do this, write an empty string to the beginning of file *) write "" to fileRefNum starting at 0 WriteNewRecord(recordToAdd, fieldDelimiter, ¬ recordDelimiter, fileRefNum) --now add back the rest of the record write postBuffer to fileRefNum return end if (* if the record is to be added somewhere other than at the beginning of the file, the rest
C H A P T E R 2 Scripting Addition Commands --now add back the rest of the record write postBuffer to fileRefNum on error errString number errNum display dialog errString end try end AddRecord on WriteNewRecord(recordToAdd, fieldDelimiter, recordDelimiter,¬ fileRefNum) try set numberOfFields to count of recordToAdd if recordDelimiter is "" then set readxTimes to numberOfFields else set readxTimes to numberOfFields - 1 end if repeat with idx from 1 to numberOfFields if idx ≤ readxTimes then write item idx
C H A P T E R 2 Scripting Addition Commands display dialog errString end try end WriteNewRecord The AddRecord handler shown in Listing 2-3 takes five parameters: recordToAdd A list of the fields for the record to be added. whichRecord An integer that identifies the offset of the record you want to add. fieldDelimiter The delimiter used in the file to separate fields. recordDelimiter The delimiter (if any) used to separate records.
C H A P T E R 2 Scripting Addition Commands After it has stored, in the accumulatedSize variable, the total size of the records preceding the point at which the new record is to be added, AddRecord reads the remainder of the file and stores it in the postBuffer variable. It then resets the file mark to the byte at which the new record is to be added by writing an empty string to that location.
C H A P T E R 2 Scripting Addition Commands return (open for access file theFile) end if on error theErrMsg number errorNum try --if error is -43, the user can choose to create the file display dialog "The file: " & theFile & " does not exist" ¬ buttons {"Create It For Me", "Cancel", "Ok"} ¬ default button 2 if button returned of the result is "Ok" then return errorNum else --create the file if writePermission is true then return open for access file theFile ¬ with write permission else return open for a
--OpenFileIfItExists returned a file reference number --do your work with the open file here close access z end if The OpenFileIfItExists handler shown in Listing 2-4 takes two parameters: A string that consists of the full pathname for the file to open or create. writePermission A Boolean value that indicates whether to open the file with (true) or without (false) write permission. theFile To determine whether the file exists or not, OpenFileIfItExists uses the Info For command.
C H A P T E R Figure 3-0 Listing 3-0 Table 3-0 3 Writing Scripting Additions 3 This chapter is intended for experienced Macintosh programmers. Before reading this chapter, you should have a thorough understanding of the Apple Event Manager, Apple event terminology resources, and the C or Pascal programming language. For information about the Apple Event Manager and Apple event terminology resources, see Inside Macintosh: Interapplication Communication.
C H A P T E R 3 Writing Scripting Additions A scripting addition resource file may contain up to four kinds of resource: (1) a code resource of type 'osax' that contains the executable code for the scripting addition, (2) an 'aete' resource that describes the terminology provided by the scripting addition, (3) a resource of type 'osiz' that informs AppleScript whether the scripting addition has any owned resources and whether it responds to commands sent from other computers on a network, and (4) any own
C H A P T E R 3 Writing Scripting Additions In Pascal, FUNCTION MyAEHandlerFunction (theEvent, theReply: AppleEvent; theRefCon: Longint): OSErr; The scripting addition handler is an extension to the AppleScript language. It needs an 'aete' resource that describes the human-language terms defined by the scripting addition for use in scripts, such as the names of commands, objects, and properties.
C H A P T E R 3 Writing Scripting Additions In C, the “coerce from pointer” coercion form (CSPT) is pascal OSErr MyCoercePtr (DescType fromType, Ptr dataPtr, Size dataSize, DescType toType, long theRefCon, AEDesc *theResult); In Pascal, the “coerce from pointer” coercion form (CSPT) is FUNCTION MyCoercePtr (typeCode:DescType; dataPtr: Ptr; dataSize: Size; toType: DescType; refcon: LongInt; VAR addressDesc: AEDesc): OSErr; In C, the “coerce from descriptor” coercion form (CSDS) is pascal OSErr MyCoerceDes
C H A P T E R 3 Writing Scripting Additions The Scripting Addition Size Resource 3 If your scripting addition doesn’t include any owned resources, you can improve its performance by providing a scripting addition size resource. A scripting addition size resource is a resource of type 'osiz' that allows you to specify whether your scripting addition has any owned resources and whether to limit the events it can receive to events sent from the local computer. An 'osiz' resource must have resource ID 0.
C H A P T E R 3 Writing Scripting Additions boolean boolean boolean boolean boolean boolean boolean boolean boolean boolean boolean boolean boolean boolean boolean reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; reserved; }; The data for an 'osiz' resource consists of flags that specify Boolean values: ■ ■ ■ 90 The first flag specifies whether AppleScript should (openResourceFile) or should not (dontOpenReso
C H A P T E R 3 Writing Scripting Additions Using Other Resources With Scripting Additions 0 The scripting addition loading mechanism adds the invoked scripting addition’s resource file to the top of the target application’s resource chain. This guarantees that resources in the scripting addition’s resource file will be found before resources with the same name or ID in the application or system resource files.
C H A P T E R 3 Writing Scripting Additions Listing 3-2 { Classes array for a scripting addition that returns a record /* array Classes: 1 elements */ /* [1] */ "my record names", 'hack', "A demo class used for record labels", { /* array Properties: 2 elements */ /* [1] */ "button returned", 'rone', ' hack', "The button returned", reserved, singleItem, notEnumerated, readOnly, reserved, reserved, reserved, reserved, reserved, reserved, reserved, reserved, /* [2] */ "text returned", 'rtwo', 'hack', "Th
C H A P T E R 3 Writing Scripting Additions For an example of this technique in action, see the reply returned by the Display Dialog scripting addition. Scripting Addition Limitations 0 Scripting additions are stand-alone code resources. As such they cannot have global variables. Solutions are available to circumvent this limitation in code resources. Check your compiler documentation for these solutions or see the appropriate technical notes from Apple Computer.
C H A P T E R 3 Writing Scripting Additions Listing 3-3 Play Sound scripting addition //////////////////////////////////////////////////////////////////// // // PlaySnd.c // // The Play Sound Scripting Addition // Copyright ®1993 Apple Computer Inc. // All rights reserved. // // Written by: Donald Olson // // To build: // C -b "PlaySnd.c" -d SystemSevenOrLater // Rez -a -o "Play Sound" -t osax -c ascr 'PlaySnd.
C H A P T E R 3 Writing Scripting Additions //////////////////////////////////////////////////////////////////// // // PlaySndEntry () // // The direct parameter is either a name or an ID of the 'snd ' // resource to play.
C H A P T E R 3 Writing Scripting Additions way we can determine the type and move its data directly into a variable instead of an AEDesc. Now we don't have to worry about disposing of the AEDesc later. */ theErr = AESizeOfParam( theAEEvent, keyDirectObject, &typeCode, &sizeOfParam); if(theErr != noErr){ /* If we fail here, just return the error. We don't need to do any cleanup, because we've allocated nothing on the heap yet.
C H A P T E R 3 Writing Scripting Additions theErr = AEGetParamPtr(theAEEvent, keyDirectObject, typeChar, &typeCode, (Ptr)&ourRezName, sizeof(ourRezName), &actualSize); if(theErr == noErr) { /* 'C' string has a null as last char */ ourRezName[actualSize] = '\0'; /* convert to Pascal string */ c2pstr((char*) ourRezName); /* now grab the 'snd ' resource by name*/ theSndHandle = GetNamedResource(kSndType, (ConstStr255Param)ourRezName); /* check the error */ theErr = ResError(); if(theErr == noErr) theErr =
C H A P T E R 3 Writing Scripting Additions if(theErr == noErr) { /* now grab the 'snd ' resource by ID */ theSndHandle = GetResource (kSndType, ourRezID); /* check the error */ theErr = ResError(); if(theErr == noErr) theErr = PlaySound(theSndHandle); /*call our */ /* sound code*/ } } else { if(typeCode == typeAlias) { /* If we receive a typeAlias, the user is asking us to play a sound file.
C H A P T E R 3 Writing Scripting Additions /* check the error */ theErr = ResError(); if(theErr != noErr) return theErr; /* make our files resource fork top in the chain */ UseResFile(ourFileRef); /* Since we don't know for sure the resource id of the targeted files 'snd ' resource, let's just get the first (and supposedly only) one.
C H A P T E R 3 Writing Scripting Additions //////////////////////////////////////////////////////////////////// // // PlaySound(Handle theSoundHdl) // // This is the code to play a 'snd '.
C H A P T E R 3 Writing Scripting Additions /********************************************** Resource file for PlaySnd.c Copyright ®1993 Apple Computer Inc. All rights reserved. Written by Donald Olson ***********************************************/ #include "Types.r" #include "SysTypes.r" #include "AEUserTermTypes.r" /* our version 1 and 2 resources */ resource 'vers' (1) { 0x1, 0x0, final, 0x0, verUS, "1.0", "1.0, Copyright ® 1993 Apple Comput" "er, Inc. All rights reserved.
C H A P T E R 3 Writing Scripting Additions /* This string is used when the user double-clicks on a scripting addition file. Since it contains nothing that can be opened or printed, the user gets this in a dialog box (thanks to the system for making this happen). */ resource 'STR ' (-16397) { "This document can not be opened or printed." " It extends the functionality of AppleScript™ " "and should be placed in the Scripting Additions" "folder found in the Extensions folder of your" " System Folder.
C H A P T E R 3 Writing Scripting Additions 1, 1, { /* array Events: 1 elements */ /* [1] */ "play sound", " This is the syntax for invoking this scripting" " addition from AppleScript™.
C H A P T E R 3 Writing Scripting Additions reserved, reserved, reserved, reserved, reserved, reserved, reserved, reserved, reserved, reserved, reserved, { /* array OtherParams: 0 elements */ } }, { /* array Classes: 0 elements */ }, { /* array ComparisonOps: 0 elements */ }, { /* array Enumerations: 0 elements */ } } }; 104 Sample Scripting Addition
A P P E N D I X Figure A-0 Listing A-0 Table A-0 Scripting Additions at a Glance A This appendix summarizes the commands described in this guide and the placeholders used in syntax descriptions. For more detailed information about these commands, see Chapter 2, “Scripting Addition Commands.” Scripting Addition Commands A Table A-1 beginning on page 106 summarizes the scripting addition commands described in this guide and their syntax.
106 None String activate referenceToApplication ASCII character integer activate ASCII character Scripting Addition Commands ¬ ¬ choose application with prompt dialogString application label dialogString close access referenceToFile current date current date choose folder with prompt dialogString choose folder choose file with prompt dialogString ¬ of type listOfTypes choose file of type listOfTypes choose file with prompt dialogString choose file ¬ choose application application label dialo
Scripting Addition Commands List of strings List of strings Script object None list disks list folder referenceToFolder load script referenceToFile log string new file list disks list folder load script log new file path to path to folderOrApplication as className path to folderOrApplication ¬ ¬ Alias or string continued File reference number open for access referenceToFile open for access open for access referenceToFile write permission Boolean Integer offset of string in string offset
108 Scripting Addition Commands round number round start log stop log start log stop log None None None set eof referenceToFile to integer set eof ¬ ¬ run script referenceOrString with parameters listOfParameters in scriptingComponent List of strings ¬ run script referenceOrString in scriptingComponent continued Value returned by script that is run scripting components ¬ run script referenceOrString with parameters listOfParameters run script referenceOrString Integer Requested data
Scripting Addition Commands ¬ ¬ ¬ ¬ write dataToWrite to referenceToFile starting at integer write dataToWrite to referenceToFile for integer starting at integer None write dataToWrite to referenceToFile write write dataToWrite to referenceToFile for integer Integer time to GMT ¬ ¬ store script scriptObjectVariable in referenceToFile replacing ( ask | yes | no ) time to GMT ¬ store script scriptObjectVariable replacing ( ask | yes | no ) ¬ None store script scriptObjectVariable store script
A P P E N D I X Scripting Additions at a Glance Placeholders A Table A-2 explains the placeholders used in the syntax descriptions in this appendix. Table A-2 Placeholders used in syntax descriptions Placeholder Explanation Boolean An expression that evaluates to true or false. buttonList A list of strings, each of which represents a button in a dialog box. The maximum number of characters in each string is 255. You can specify up to three buttons.
A P P E N D I X Scripting Additions at a Glance Table A-2 Placeholders used in syntax descriptions (continued) Placeholder Explanation nameString A string of the form "Disk:Folder1:Folder2:...:Filename". number An expression that evaluates to an integer or real number. referenceOrString A reference of the form file nameString or alias nameString, or a string that consists of a valid script. referenceToApplication A reference of the form application "Disk:Folder1:Folder2:...:ApplicationName".
Index Symbols () in syntax descriptions xi [] in syntax descriptions xi | in syntax descriptions xii A Activate command 8–10 AddRecord handler 77–81 'aete' resource type 86–92, 102 alert icons, displayed by Display Dialog 26 alert sound 13 Apple event coercion scripting additions 87–88 Apple event handler scripting additions 86–87 ASCII Character command 10–11 ASCII Number command 11–12 'ascr' creator type 85 B Beep command 13 brackets, in syntax descriptions xi C Caution icon, displayed by Display Dialo
I N D E X CSDS coercion form 88 CSPT coercion form 88 Current Date command 21–22 D DeleteRecord handler 74–77 dialects xi dictionary, scripting addition 3 Display Dialog command 3, 22–26 G Get EOF command 27–28 Greenwich mean time 66 H handlers in scripting additions Apple event 86–87 coercion 87–88 E I, J, K Esc key to cancel a dialog box 25 to cancel Beep command 13 icons displayed by Display Dialog command 25 scripting addition 1 Info For command 28–31 installing scripting additions 1–2 F File C
I N D E X O object class definitions File Info, returned by Info For 29–31 Reply, returned by Display Dialog 24 Object Support Library 93 Offset command 39–41 and Scriptable Text Editor’s Offset property 4 OpenFileIfItExists handler 82–83 Open for Access command 41–43 'osax' resource type 85–104 'osiz' resource 89–90 owned resources, for scripting additions 89, 91 P, Q parentheses, in syntax descriptions xi Path To command 43–45 placeholders, in syntax descriptions xi, 110–111 Play Sound scripting additio
I N D E X T Tell statements 2–4 Time to GMT command 66–67 typographic conventions xi–xii U undefined commands 2 V vertical bars, in syntax descriptions xii W, X, Y, Z Write command 68–70 WriteNewRecord handler 79–81 116
T H E A P P L E P U B L I S H I N G This Apple manual was written, edited, and composed on a desktop publishing system using Apple Macintosh computers and FrameMaker software. Proof pages were created on an Apple LaserWriter IINTX printer. Final page negatives were output directly from the text and graphic files. Line art was created using Adobe™ Illustrator. PostScript™, the page-description language for the LaserWriter, was developed by Adobe Systems Incorporated.