AppleScript

From Free net encyclopedia

Image:AppleScript Editor.png AppleScript is a scripting language devised by Apple Computer, and built into Mac OS. More generally, AppleScript is the word used to designate the Mac OS scripting interface, which is meant to operate in parallel with the graphical user interface.

Contents

History

The AppleScript project was an outgrowth of the HyperCard project. HyperCard had an English language-based scripting language called HyperTalk which could be used for embedding logic and behavior into a HyperCard stack. Apple engineers recognized that a similar scripting language could be designed to be used with any application, and the AppleScript project was born. AppleScript required extensive upgrades to the Mac OS to work (see below for details). Much of the underlying technology changes were made part of the massive System 7 release, notably the key Apple events concept. As such, Apple events were vying for developer attention along with many other new technologies introduced at the same time (balloon help, publish and subscribe, etc.). Apple events were among the most difficult of the System 7 technologies to implement, requiring a re-write of major portions of the "low level" code in an application. Apple's own application framework, MacApp, did not directly support Apple events for some time.

AppleScript was released in October 1993 as part of System 7.1.1 (System 7 Pro, the first major upgrade to System 7). QuarkXPress (ver. 3.2) was one of the first major software applications that supported AppleScript, and as a result AppleScript was widely adopted within the publishing segment of the Apple market. It is arguable that the main reason that the Mac remained a powerhouse in the publishing market after Quark (and other applications) were ported to Microsoft Windows, was that Mac users could automate complex workflows.

The move to Mac OS X and its Cocoa frameworks has made AppleScript come into its own. Cocoa applications offer basic scriptability with no effort on the part of the developer, and are "well-scriptable" for the cost of writing a text file. AppleScript Studio, released with Mac OS X v10.2, allows users to build entire applications using AppleScript and Cocoa objects.

Basic concepts

AppleScript was designed to be used primarily as a scripting language, offering users an intelligent mechanism to control and exchange information with various applications.

Prior to System 7 the Mac OS application runtime had only a rudimentary event model that could specify a small and fixed number of low-level events like "key was pressed" or "mouse was clicked". Each application was responsible for decoding these low-level events into meaningful high-level user actions, like "select cut from the Edit menu". In many cases the code for reading the event and decoding it was mixed together; for instance the code handling a mouse click might decode it to selecting the Quit item from the File menu, and then quit the application immediately.

Adding AppleScript support required the author to fully separate this decoding from carrying out the command, a task Apple referred to as factoring (...the application). Application developers were encouraged to write two complete event handling "stacks", one for handling the low-level events (clicks, etc.), and another for high-level events (AppleEvents). The actual work code that handled these commands, once decoded, was to be completely separated and called identically from both stacks.

AppleScript in Mac OS X

In Mac OS X AppleScript is simpler for developers to implement, particularly for those applications being developed in Cocoa. Unlike the Mac OS where events are handled by the applications, under Cocoa, events are decoded into a "high level" command by the NSApplication object, and the messages dispatched directly to the correct object. That is, all Cocoa applications are "factored" by default, the developer doesn't write any of the event handling code (normally) and writes only the "work methods" that those events will call.

Another major advantage is that Cocoa objects are presented to the outside world (other applications and even machines) in a standardized format that anyone can examine directly. Under Cocoa AppleScript is much "thinner"; the script engine decodes the script, translates object names from human-readable to their internal format, and then calls those methods on the target application directly.

The natural language metaphor

Whereas Apple Events are a way to send messages into applications, AppleScript is a particular language designed to send Apple Events. In keeping with the Mac OS tradition of ease-of-use, the AppleScript language is designed on the natural language metaphor, just as the graphical user interface is designed on the desktop metaphor. AppleScript programs are generally readable by anyone, and editable by most. The language is based largely on HyperCard's HyperTalk language, extended to refer not only to the HyperCard world of cards and stacks, but theoretically to any document. To this end, the AppleScript team introduced the AppleEvent Object Model (AEOM), which specified the objects any particular application "knew".

Generally, AEOM defined a number of objects, like "document" or "paragraph", and the actions that could be done to them, like "cut" and "close". The system also defined ways to refer to properties of objects, so one could refer to the "third paragraph of the document 'Good Day'", or the "color of the last word of the front window". AEOM uses an application dictionary to associate the Apple Events with human-readable terms, allowing the translation back and forth between human-readable AppleScript and bytecode Apple Events. To discover what elements of a program are scriptable, dictionaries for supported applications may be viewed. (In the Xcode and Script Editor applications, this is under File → Open Dictionary.)

To designate which application is meant to be the target of such a message, AppleScript uses a "tell block" construct:

 tell application "Microsoft Word"
   quit
 end tell

Alternatively, the tell block may be expressed in one line by using an infinitive:

 tell application "Microsoft Word" to quit

Though for events in the "Core Suite" (activate, open, reopen, close, print, and quit), the application may be supplied as the direct object to transitive commands:

 quit application "Microsoft Word"

The concept of an object hierarchy can be expressed using nested blocks:

 tell application "QuarkXpress"
      tell document 1
         tell page 2
            tell text box 1
              set word 5 to "Apple"
             end tell
         end tell
      end tell
  end tell

The concept of an object hierarchy can also be expressed using nested prepositional phrases:

 pixel 7 of row 3 of TIFF image "my bitmap"

which in another programming language might be expressed as sequential function calls:

 getTIFF("my bitmap").getRow(3).getPixel(7);

Many applications do not store pointers directly into anything but the lowest level objects; for instance, a word processor almost certainly has an object that returns all of the characters in a document, but may not have objects representing pages, paragraphs or documents as a whole. Since the authors intended AppleScript to be added to existing applications without too much redesign, they also provided a second way to write accessors known as iterators. Using iterators requires the developer only to keep track of the current location of an object, and provide a method to find the "next one". For instance, paragraph objects could be supported with a single pointer to the current paragraph, and a method that finds the next one by looking for a return character.

Note the similarities between the AEOM model and the considerably more recent DOM system used in XML. Both decompose a document into a hierarchy of objects, and offer the programmer a standardized iterative method to access the contents. Differences between the systems lie primarily in the user-level syntax, with AppleScript introducing a number of different ways to refer to any particular object. For instance, AppleScript includes syntax for ordinal counting, "the first paragraph", as well as cardinal, "paragraph one". Likewise the numbers themselves can be referred to as text or numerically, "five", "fifth" and "5" are all supported.

AppleScript on its own

AppleScript need not depend on other applications. For very simple tasks, AppleScript can be used for self-contained applets. For instance, the code:

set pix to 72
set answer to text returned of (display dialog "Enter in the number of inches" default answer "1")
display dialog answer & "in = " & (answer * pix) & "px"

brings up a dialog box requesting a number of inches from the user. This number is then converted to pixels, assuming 72 pixels per inch. A second dialog box is then brought up displaying the result.


AppleScript Studio

With Mac OS X, AppleScript has grown well beyond its humble beginnings. AppleScript Studio is a development environment, which comes free with Mac OS X, which uses AppleScript as the primary programming language, in conjunction with the Cocoa framework used to construct graphical user interfaces.

With Mac OS X v10.3 ("Panther") AppleScript Studio and Project Builder have been rolled into the Xcode IDE. Interface Builder, another component of Xcode, lets you build a user interface in a drag-and-drop fashion (similar to Visual Basic) and then "run" the user interface to see what the forms and menus looks like.

Panther also comes with an enhanced version of Script Editor, the minimalist editor for compiling and running AppleScripts. One new feature of this editor is that if you right-click (or control-click) on the editing area, you get a pop-up menu with a large range of options for script fragments to paste into your code. This is an excellent feature for people learning to write AppleScript. From that menu, you can also open up the directory where these scripts are kept, and have a look at them. You can also add your own scripts (although you need to restart Script Editor for these changes to show up in the pop up menu).

AppleScript dialects

AppleScript initially supported the idea of multiple dialects: different syntactic representations of the same script. The standard dialect was English; French, and Japanese dialects were also produced. (A C dialect was publicly discussed, but never shipped.) A dialect could redefine the keywords and even the grammar of the language, so that, for instance, commands in the Japanese dialect had the verb at the end. Because AppleScript stores scripts in a compiled form, it could compile a script in one dialect and decompile it in another. While the project was a technical success, few application developers provided terminology in multiple languages, which meant that scripts were a confusing mix of languages in most cases. Support for multiple dialects was dropped by Apple in Mac OS 8.5.

AppleScript language essentials

  • basic data types are boolean, string, integer, real, list, record and object
    • different types can coexist in a list, including nested lists
    • records are lists of key-value pairs
  • standard control flow with if/else constructions and repeat (for, while, in) loops
  • variables are instantiated when used, and are not strictly typed
  • script objects can encapsulate methods and data
  • script objects can inherit behavior from a parent script
  • "tell" construct used to identify target of message
  • applications can define terminology at runtime
  • runtime compilation possible using "run script" construct
  • persistence and modularity possible using "store script" and "load script"

Applets and Droplets

It is possible to save an AppleScript script as an executable file or applet. If the script has a run handler:

to run
	(*...*)
end run

then this will be invoked when the user double-clicks the applet. (If there are no handlers in the script, the entire script is a run handler.)

If the script has an open handler:

to open(SomeItems)
	(*...*)
end open

then the applet becomes a droplet: if the user drags and drops filesystem items onto the script, it will be launched and the open handler will be invoked with a list of aliases to the dropped items.

(Note: "on" is a synonym for "to" when starting a handler; for example, "on run" instead of "to run".)

Open Scripting Architecture

An important aspect of the AppleScript implementation was the Open Scripting Architecture (OSA). Apple provided OSA for third-party scripting/automation products such as QuicKeys and UserLand Frontier, to function on an equal status with AppleScript. AppleScript was implemented as a scripting component, and the basic specs for interfacing such components to the OSA were public, allowing other developers to add their own scripting components to the system. Public client APIs for loading, saving and compiling scripts would work the same for all such components, which also meant that applets and droplets could hold scripts in any of those scripting languages.

Under Mac OS X, the JavaScript OSA component remains the only serious OSA language alternative to AppleScript, though the Macintosh versions of Perl, Python, Ruby, and Tcl all support native means of working with AppleEvents without being OSA components.

One of the most interesting features of the architecture, the ability to write language extensions (called a "scripting addition", or "osax" for "Open Scripting Architecture eXtension") , which were based on Hypercard's external commands. Because an extension adds terms to the language, it sometimes became problematic to predict how the AppleScript compiler would behave given a specific syntax depending upon which OSAX were installed at runtime. The coiners of the term osax, Jon Pugh and Donald Olson consider the proper spelling to use all lowercase letters, "osax" and "osaxen".

See also

  • Sal Soghoian — AppleScript product manager
  • Script Debugger, a third-party AppleScript and OSA language editor.
  • William Cook, Donn Denman, Warren Harris, Kurt Piersol, Jens Alfke — AppleScript designers
  • Automator — Apple Automator is a new technology for controlling applications that can be used with AppleScript, first implemented in Mac OS X v10.4 "Tiger", the version of Mac OS X released on April 29, 2005.
  • GUI Scripting Gives AppleScript scripts the ability to control otherwise non-scriptable applications. AppleScript scripts can select menu items, click buttons, enter text into text fields, and generally control the interfaces of most Mac OS X 10.x applications.

Books

External links

Template:Mac OS X Template:Mac OSde:AppleScript fr:AppleScript it:AppleScript nl:AppleScript ja:AppleScript