[ Team LiB ] |
20.5 Standard Scripting Addition CommandsThis section is a catalogue of the scripting addition commands present in a standard installation of Mac OS X.
20.5.1 DialogsThese 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.
DescriptionA 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."). Examplesset 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")
DescriptionPuts up a scrolling list of strings for the user to choose from. Returns a list of chosen strings, or false if the user cancels. Examplechoose from list {"Mannie", "Moe", "Jack"} with prompt "Pick a Pep Boy:"
DescriptionPuts 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.") Exampleset f to choose file with prompt "Pick a text file:" of type "TEXT"
DescriptionPuts 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.") Exampleset f to choose folder with prompt "Pick a folder:"
DescriptionPuts 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. Exampleset f to choose file name with prompt "Where shall I save this stuff?"
DescriptionPuts 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.") Exampleset 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!"
DescriptionPuts 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.") Examplechoose URL showing Remote applications -- "eppc://169.254.199.218:3031/"
DescriptionPuts 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. Examplechoose color default color {9000, 10000, 50000} -- {50000, 9000, 10000}
20.5.2 NoisesThe following commands can be invoked to produce a sound alert.
DescriptionPlays the system beep sound. Examplebeep
DescriptionSets how loud the speakers are, on a scale of 0 to 7. Exampleset volume 7 beep
DescriptionPerforms 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. Exampletell 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 InformationThe following commands can be used to get information about a file or your system.
DescriptionReturns the value of gestalt selectors. Exampleset 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. Examplesystem attribute "SHELL" -- "/bin/tcsh"
For an example of the system attribute command used to fetch an environment variable, see Chapter 23.
DescriptionLocates various standard folders, such as the system folder. Returns an alias (or string, if desired). Examplepath 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. Examplepath to application "Finder" -- alias "xxx:System:Library:CoreServices:Finder.app:" path to me -- alias "xxx:Applications:AppleScript:Script Editor.app:"
DescriptionGets the names of all mounted volumes. Returns a list of strings (see Section 19.5.11). Examplelist disks -- {"xxx", "main", "second", "extra"}
DescriptionGets the names of all items within a folder. Includes invisible files and folders if you don't prevent it. Returns a list of strings. Examplelist folder (path to home folder)
-- {".CFUserTextEncoding", ".DS_Store", ".Trash", "Desktop", ...}
DescriptionGets information about an item on disk. Returns a file information record packed with useful stuff. Exampleset 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 DataThese are scripting addition commands that read and write file data.
DescriptionOpens 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.
DescriptionReads 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.
DescriptionWrites 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. Exampleopen 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.
DescriptionReturns 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. Examplewrite "Howdy" to f set ourEof to get eof of f write "Doody" to f starting at ourEof + 1
DescriptionSets a file's size, truncating its data or filling the new excess with zeros.
DescriptionCloses 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 ClipboardThe following commands can be used to obtain a string or collect something from the Clipboard.
DescriptionConverts an ASCII numeric value to a one-character string. ExampleASCII character 82 -- "R"
DescriptionConverts the first character of a string to an ASCII numeric value. ExampleASCII number "Ribbit" -- 82
DescriptionReports the position of a substring within a target string. Character positions are 1-based. Returns 0 if the substring isn't found. Exampleoffset 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.
DescriptionSummarizes the content of a string or textfile, using the same technology as the Summarize Service.
DescriptionSets the clipboard.
DescriptionDescribes the contents of the clipboard as a list of class-size pairs. Exampleclipboard info -- {{string, 54}, {«class FMcl», 20}, {«class FMSC», 10240}}
DescriptionGets 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 DatesThe following commands are used for working with numbers and dates.
DescriptionRounds a real to an integer, in various ways. Exampleround 1.3 -- 1
DescriptionGenerates 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. Examplerandom 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"}
DescriptionGenerates a date object corresponding to the current date and time. Exampletime string of (current date) -- "10:41:13 AM"
DescriptionReports 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 MiscellaneousThese are scripting addition commands I couldn't categorize.
DescriptionPauses a specified number of seconds. Starting with Panther, this number can be a real. Exampledelay 1 beep
DescriptionMounts 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). Examplesset 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.
DescriptionReturns a list of strings giving the names of the installed OSA scripting components. One of these will be "AppleScript".
DescriptionHands the System a string representing a URL; the URL is opened with the appropriate helper application. |
[ Team LiB ] |