DekGenius.com
[ Team LiB ] Previous Section Next Section

20.5 Standard Scripting Addition Commands

This section is a catalogue of the scripting addition commands present in a standard installation of Mac OS X.

For load script, store script, and run script, see Section 9.6. For the POSIX file class, see Section 13.7 and Section 14.5. For digital hub scripting, folder action, and CGI events, see Chapter 24. For the do shell script command, see Chapter 23.


20.5.1 Dialogs

These scripting addition commands put up dialogs. The dialog will appear in whatever application is being targeted at the moment, or in the host application if no application is being targeted.

display dialoggeneral informational, text entry, and button-choice dialog

Description

A remarkably flexible little command. You can put up an information dialog, with a choice of standard icons. You can put up a text entry dialog, where the user can type a short string. You can dictate the names of up to three buttons, and learn which one the user pressed. The dialog can be set to time out if the user does not respond, and you can learn that this is what happened. By default, the buttons are "Cancel" and "OK". Returns a dialog reply record containing only the relevant items. If the user presses a button entitled "Cancel", an error is thrown (-128: "User canceled.").

Examples

set r to display dialog "Quick! Pick a Pep Boy!" buttons {"Mannie", "Moe", "Jack"} ¬
        with icon caution giving up after 3
set favoritePepBoy to button returned of r
if favoritePepBoy is "" and gave up of r then set notFastEnough to true
set whoIsIt to text returned of (display dialog "What is your name?" ¬
        default answer "" buttons {"OK"} default button "OK")
choose from listlistbox selection dialog

Description

Puts up a scrolling list of strings for the user to choose from. Returns a list of chosen strings, or false if the user cancels.

Example

choose from list {"Mannie", "Moe", "Jack"} with prompt "Pick a Pep Boy:"
choose filefile selection dialog

Description

Puts up a standard Open File dialog, with title "Choose File" and default button "Choose". Returns an alias. If the user cancels, an error is thrown (-128: "User canceled.")

Example

set f to choose file with prompt "Pick a text file:" of type "TEXT"
choose folderfolder selection dialog

Description

Puts up a standard Choose Folder dialog, with title "Choose a Folder". The user can also create a new folder. Returns an alias. If the user cancels, an error is thrown (-128: "User canceled.")

Example

set f to choose folder with prompt "Pick a folder:"
choose file namefile save dialog

Description

Puts up a standard Save File dialog (default button "Save"), with title "Choose File Name" and default prompt "Specify new file name and location". The user can also create a new folder. If the user types the name of an existing file, goes through the usual "Replace?" rigmarole. Returns a file URL (which appears as a file specifier). If the user cancels, an error is thrown (-128: "User canceled.") Does not actually save anything.

Example

set f to choose file name with prompt "Where shall I save this stuff?"
choose applicationapplication selection dialog

Description

Puts up a standard Choose Application dialog. The user can choose from a list of all applications, or can switch to browsing in a standard Open File dialog. Returns an application specifier, or an alias if requested; or a list of either, if multiple selections are allowed. If the user cancels, an error is thrown (-128: "User canceled.")

Example

set theApp to choose application as alias
tell application "Finder"
        set isScriptable to has scripting terminology of theApp
end tell
if isScriptable then display dialog "It's scriptable!"
choose URLURL selection dialog

Description

Puts up a standard Choose URL dialog (with a Connect button); this is the same as the Finder's Connect to Server dialog, useful for specifying servers on the local network, with an option to let the user choose various categories of server. The user can also just type a URL unless you prevent it; this can be basically any string at all. Does not actually connect! Returns a string. If the user cancels, an error is thrown (-128: "User canceled.")

Example

choose URL showing Remote applications -- "eppc://169.254.199.218:3031/"
choose colorcolor selection dialog

Description

Puts up a standard Color Picker dialog, where the user may choose a color. Returns a color. A color is expressed as an rgb color, which is a list of three integers representing the red, green, and blue components. If the user cancels, an error is thrown (-128: "User canceled.") You can optionally specify a color that is selected initially when the Color Picker appears.

Example

choose color default color {9000, 10000, 50000} -- {50000, 9000, 10000}

20.5.2 Noises

The following commands can be invoked to produce a sound alert.

beepbeep

Description

Plays the system beep sound.

Example

beep
set volumespeaker volume

Description

Sets how loud the speakers are, on a scale of 0 to 7.

Example

set volume 7
beep
saytext-to-speech

Description

Performs text-to-speech, either speaking text or saving the synthesized speech as a sound file. Can also be used in conjunction with speech recognition to determine what text appears below the microphone window.

Example

tell application "SpeechRecognitionServer"
        set s to listen for {"yes", "no"} with prompt "Would you like me to beep?" ¬
                giving up after 10
end tell
if s is "yes" then
        say "Okay, I will beep now." displaying "Okay."
        beep
else
        say "Okay, then I won't." displaying "Okay."
end if

20.5.3 File and Machine Information

The following commands can be used to get information about a file or your system.

system attributegestalt and environment variables

Description

Returns the value of gestalt selectors.

Example

set n to system attribute "sysv"
set s to "print sprintf \"%lx\", " & n
set v to do shell script "perl -e " & quoted form of s
set L to characters of v
set v to "." & item -1 of L
set v to "." & item -2 of L & v
set v to ((items 1 thru -3 of L) as string) & v
display dialog "You are running system " & v & "!"

For a list of gestalt selectors, see http://developer.apple.com/techpubs/macosx/Carbon/oss/GestaltManager/Gestalt_Manager/gestalt_refchap/ConstantsIndex.html.

Also returns the value of user environment variables. To find out what they are, give the system attribute command with no parameters.

Example

system attribute "SHELL" -- "/bin/tcsh"

For an example of the system attribute command used to fetch an environment variable, see Chapter 23.

path tostandard folder location

Description

Locates various standard folders, such as the system folder. Returns an alias (or string, if desired).

Example

path to desktop -- alias "xxx:Users:mattneub:Desktop:"

If the designated folder is legal but doesn't exist, the path to command silently creates it unless you specify without folder creation, in which case an error is returned if the folder doesn't exist.

Because of a bug in the Script Editor's dictionary display, it can't display the complete list of standard folders available. So here it is:

application support
applications folder
desktop
desktop pictures folder
documents folder
favorites folder
Folder Action scripts
fonts
frontmost application
help
home folder
internet plugins
keychain folder
library folder
modem scripts
movies folder
music folder
pictures folder
preferences
printer descriptions
public folder
scripting additions
scripts folder
shared documents
shared libraries
sites folder
startup disk
startup items
system folder
system preferences
temporary items
trash
users folder
utilities folder
voices
apple menu
control panels
control strip modules
extensions
launcher items folder
printer drivers
printmonitor
shutdown folder
speakable items
stationery

Many standard folders aren't documented by the dictionary; these are accessed through four-letter codes as strings. For example, path to "cmnu" gives an alias to the Contextual Menu Items folder. For a list of these four-letter codes, see http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/folder_manager_ref/constant_6.html.

For another way to access many standard folders, see Section 21.2.3.

This command also locates applications. Important undocumented uses are path to me and path to current application, which locate the host application.

Example

path to application "Finder" -- alias "xxx:System:Library:CoreServices:Finder.app:"
path to me -- alias "xxx:Applications:AppleScript:Script Editor.app:"
list disksvolume names

Description

Gets the names of all mounted volumes. Returns a list of strings (see Section 19.5.11).

Example

list disks -- {"xxx", "main", "second", "extra"}
list folderfolder contents

Description

Gets the names of all items within a folder. Includes invisible files and folders if you don't prevent it. Returns a list of strings.

Example

list folder (path to home folder)
-- {".CFUserTextEncoding", ".DS_Store", ".Trash", "Desktop", ...}
info forfile/folder information

Description

Gets information about an item on disk. Returns a file information record packed with useful stuff.

Example

set uf to (path to home folder as string)
set L to list folder uf
set s to {}
repeat with f in L -- collect sizes of all items
        set end of s to size of (info for file (uf & f))
end repeat
set maxItem to 0
set maxVal to 0
repeat with i from 1 to (count s) -- find biggest size
        if item i of s > maxVal then
                set maxItem to i
                set maxVal to item i of s
        end if
end repeat
display dialog ¬
        "The biggest thing in your home folder is " ¬
        & item maxItem of L

If you ask for the info for a folder, the script may take some time to run, in order to sum the sizes of all the files within it.

20.5.4 File Data

These are scripting addition commands that read and write file data.

open for accessopen file

Description

Opens a file for read access—optionally, for write access—creating the file as a text file if it doesn't exist (it does this even if you're opening for read access only; I regard this as a bug). Returns a file reference number that can be used with the other commands.

readread data

Description

Reads data from a file, optionally coercing the data to a desired datatype. There are options for where to start (character positions are 1-based), how many characters to read, and what delimiter character to stop at.

The using delimiter parameter is poorly documented. This parameter is a list, as long as you like, of one-character strings. They are used to break the data into a single-level list of strings which will lack all the delimiter characters.

writewrite data

Description

Writes data to a file, optionally coercing the data to a desired datatype. There are options for where to start and how much data to write.

The data coercion options for reading and writing allow you to store any kind of data in a text file and retrieve it later. The data is encoded, but it will be decoded correctly if you specify the same class when writing and when reading.

Example

        open for access f with write permission
        write {"Mannie", "Moe", "Jack"} as list to f
        close access f
        open for access f
        set L to read f as list
        close access f
        L -- {"Mannie", "Moe", "Jack"}

On the whole, however, this approach is not very flexible; see Section 9.6.2.

get eofget file end position

Description

Returns the 1-based index of the last character of a file (which is also the size of the file).

Because character positions are 1-based, and because the eof is the position of the last character, if you want to append to a file you must start writing at a position one greater than the eof. That is the largest position at which you are permitted to start writing.

Example

write "Howdy" to f
set ourEof to get eof of f
write "Doody" to f starting at ourEof + 1
set eofset file end position

Description

Sets a file's size, truncating its data or filling the new excess with zeros.

close accessclose file

Description

Closes a file. Always close a file you have opened for access.

In general, the file data commands are smart about how they let you describe the file you want to operate on: they can take a file reference number returned by open for access, or a file specifier or alias.

When using the file data commands, you should ensure sufficient error handling so as not to leave a file open. If you do accidentally leave a file open, you might have to quit the current application (such as the Script Editor) in order to close it.

In this example, we use AppleScript to construct a miniature "database." We have some strings; taking advantage of the write command's starting at parameter, we write each string into a 32-character "field." The example perhaps overdoes the error handling, but it shows the general idea:

set pep to {"Mannie", "Moe", "Jack"}
set f to (path to current user folder as string) & "testFile"
try
        set fNum to open for access file f with write permission
on error
        close access file f
        return
end try
try
        set eof fNum to 0 -- erase if exists
        set eof fNum to (count pep) * 32
        repeat with i from 1 to (count pep)
                write item i of pep to fNum starting at (i - 1) * 32
        end repeat
        close access fNum
on error
        close access fNum
end try

Now we'll fetch the data from the "database." We take advantage of the fact that all data that isn't part of a string is null.

set f to choose file of type "TEXT"
try
        set fNum to open for access f
on error
        close access f
        return
end try
set L to {}
try
        set ct to (get eof fNum) / 32
        repeat with i from 1 to ct
                set end of L to read fNum from (i - 1) * 32 ¬
                        before ASCII character 0 -- read up to but not including null
        end repeat
        close access fNum
on error
        close access fNum
end try
L -- {"Mannie", "Moe", "Jack"}

20.5.5 String and Clipboard

The following commands can be used to obtain a string or collect something from the Clipboard.

ASCII characternumber to character

Description

Converts an ASCII numeric value to a one-character string.

Example

ASCII character 82 -- "R"
ASCII numbercharacter to number

Description

Converts the first character of a string to an ASCII numeric value.

Example

ASCII number "Ribbit" -- 82
offsetsubstring position

Description

Reports the position of a substring within a target string. Character positions are 1-based. Returns 0 if the substring isn't found.

Example

offset of "bb" in "Ribbit" -- 3

The offset command's behavior used to be to consider case and ignore diacriticals, which is backwards from AppleScript's own defaults. In the current version, this is fixed, and string considerations are obeyed.

summarizesummary of content

Description

Summarizes the content of a string or textfile, using the same technology as the Summarize Service.

set the clipboard toset clipboard

Description

Sets the clipboard.

clipboard infodescribe clipboard

Description

Describes the contents of the clipboard as a list of class-size pairs.

Example

clipboard info -- {{string, 54}, {«class FMcl», 20}, {«class FMSC», 10240}}
the clipboardget clipboard

Description

Gets the clipboard text, or you can specify some other class (you'd use clipboard info to know what to specify).

20.5.6 Numbers and Dates

The following commands are used for working with numbers and dates.

roundround

Description

Rounds a real to an integer, in various ways.

Example

round 1.3 -- 1
random numbergenerate random number

Description

Generates a random number. This can be a real between 0 and 1, exclusive; or it can be an integer between two non-negative integers, inclusive. You can seed the generator to get it started; this is useful for generating a fixed pseudo-random sequence.

Example

random number
set L to {}
repeat 10 times
        if (random number 1) as boolean then
                set end of L to "heads"
        else
                set end of L to "tails"
        end if
end repeat
L -- {"heads", "tails", "heads", "heads", "heads",
         "tails", "heads", "heads", "heads", "heads"}
current datenow

Description

Generates a date object corresponding to the current date and time.

Example

time string of (current date) -- "10:41:13 AM"
time to GMTtime zone

Description

Reports the time zone that has been set via the Date & Time preference pane, as an offset from Greenwich time, in seconds.

Example

(time to GMT) / hours -- -7.0

20.5.7 Miscellaneous

These are scripting addition commands I couldn't categorize.

delaywait

Description

Pauses a specified number of seconds. Starting with Panther, this number can be a real.

Example

delay 1
beep
mount volumeAppleShare

Description

Mounts an AppleShare volume (i.e., a machine where Personal File Sharing is turned on). The machine is specified as an afp URL; to avoid the dialog for choosing a particular volume, add the volume name as a second path element. Parameters can be used to avoid the username-password dialog (or you can include the username and password as part of the URL).

Examples

set s to choose URL showing File servers
mount volume s as user name "mattneub" with password "teehee"
mount volume "afp://little-white-duck.local" -- avoids no dialogs
mount volume "afp://little-white-duck.local/OmniumGatherum" ¬
        as user name "matt neuburg" with password "teehee" -- avoids all dialogs

If the machine is serving via AppleTalk (rather than TCP/IP), and if you have AppleTalk turned on in Mac OS X, you can mount the machine via AppleTalk using an AppleTalk URL, which looks, for example, like this: mount volume "afp:/at/LittleWhiteDuck". Note that you must use a name; the IP number doesn't apply here. You can specify volume, username, and password just as for a TCP/IP afp URL. Windows servers can be mounted using an smb URL.

scripting componentslist OSA components

Description

Returns a list of strings giving the names of the installed OSA scripting components. One of these will be "AppleScript".

open locationopen a URL

Description

Hands the System a string representing a URL; the URL is opened with the appropriate helper application.

    [ Team LiB ] Previous Section Next Section