What should be the applescript handler for messages. Scripting for Mac OS X: starting to program on AppleScript

15.05.2022

From this article you will learn what AppleScript is, why and who needs it, how you can automate other people's applications and add automation capabilities to yours.

Automate it

There are often problems for which it is irrational to create a separate project in a compiled language. For example, when you need to quickly put together a code on your knees that should simply do a specific job - without any GUI decorations, handling all kinds of exception situations, optimization, and so on. This is where scripting languages ​​come to the rescue - shell, Perl, PHP, and so on you know. All of them (or almost all) are available under Mac OS X. But in this operating system, in addition to the generally accepted scripting languages, there is also a special scripting language that is oriented specifically towards Mac OS X and is closely related to it. This is AppleScript.

AppleScript has been included with the system since System 7. Growing out of the HyperCard project (which contained scripting language HyperTalk, very similar to natural English), AppleScript was originally created to enable communication between tasks, as well as to manage work third party applications. AppleScript itself has fairly modest functionality: in this language, even scripts for performing relatively simple tasks often look like calls to other applications. However, after a significant system overhaul during the transition to the Mac OS X line, the AppleScript language became more flexible and powerful, and the new Cocoa framework allowed developers to build automation capabilities into their applications using AppleScript with minimal effort.

Simple script

To edit and execute scripts we will use the standard Script Editor. You can find it in the /Application/AppleScript folder. First, let's write a simple “HelloWorld” script.

display alert "Hello World!" # Show the dialogue
say "Hello World" # Output to columns

I think there is no need to explain anything here, but I would like to note the extremely easy access to the speech synthesizer from AppleScript using the say command. This is real communication with the user in Apple style :). Of course, this dialogue can be easily customized. For example, add the necessary buttons:

Panel with additional buttons

display alert "Hello World!" buttons("Hello", "Bye")
set answer to button returned of the result
if answer is "Hello" then
...
else
...
end if

Now let's write something more useful. For example, let's let the user select a file and read its contents:

# File selection panel
set theFile to (choose file with prompt "Select a file to read:" of type ("TEXT"))
open for access theFile

Reading the content

set fileContents to (read theFile)
close access theFile

These examples clearly show the main idea of ​​AppleScript - it is very close to the living English language. Therefore, reading scripts is easy even for a person far from coding. Each verb command can be supplemented with modifier nouns and parameters.

Interaction with applications

AppleScript uses a messaging mechanism to communicate with other applications:

tell application "Microsoft Word"
quit
end tell

Using the tell command, we select the application to which we will send the message. In this case, we ask MS Word to exit. Any number of commands can be sent in a “tell - end tell” block. The messages sent to the application can be more specific. It all depends on what commands its developers implemented. iTunes, for example, exports quite a few commands and properties to the AppleScript environment:

Launch the desired playlist in iTunes

tell application "iTunes"
play the playlist named "My Favorite"
end tell

You can find out the set of messages and data types that an application exports to the AppleScript environment by looking at its terminology (the AppName.scriptRerminology file in application resources). To do this, in the Script Editor, go to the “File - Open Dictionary - ...” menu and select the desired application.

To make it easier for you to work with the classes and commands that the application exports, they are organized into sections. All applications that support scripting have at least two sections: one standard and one more specific to this application sections. The standard section contains a set of standard commands that any Mac application supports: open, print, close and quit. The content of the remaining sections depends on the imagination of the developers.

Executing AppleScript from within your application

If you are writing an application in Objective-C/Cocoa, then it is possible that some things will be more convenient to do using AppleScript. To create and execute scripts in Cocoa applications, there is the NSAppleScript class. Here is a simple example of its use - the implementation of obtaining a user status line from the iChat application.

NSAppleScript *iChatGetStatusScript = nil;
iChatGetStatusScript = [ initWithSource: @"tell application "iChat" to get status message"];
NSString *statusString = [stringValue];

It's possible that the same thing could be done another way without using a runtime generated script, but it's unlikely that the alternative code would look simpler than this. If the scripts are large, you can store them in bundle resources and read them when necessary.

Automation in a Cocoa application

It is very useful to add scripting support to your Cocoa applications, because if your application has an interface to AppleScript, then the user, by writing a few lines in AppleScript, will be able to customize it for his needs and integrate it with other applications that he has installed, and then, for example, automate the solution of routine tasks. To export types and commands to the AppleScript environment, you need to describe them in special files. It is possible to do this in the .scriptSuite and .scriptTerminology files or in one file with the .sdef extension. In both cases the files are in XML format, but sdef is easier to work with.

The contents of the scriptTermonology file are displayed in the Script Editor when viewing the application dictionary. This file contains a description of the objects exported to AppleScript.

Opening the scriptSuite file in the Plist Editor, you can see that it contains the following main sections:

  • AppleEventCode - a four-letter code that identifies the application for the AppleScript environment (the code must be unique within the same system);
  • Name - the name of the section that contains the exported commands and classes.

Disassemble internal organization these files don't make much sense, since you'll most likely only have to deal with sdef files.

Example sdef file
















In sdef, scripting terminology is mixed with detailed description commands and types, which can be found in .scriptingSuit files. Let's put this into practice by creating a Cocoa application that supports AppleScripting. To do this, in the new Cocoa project, add the Scripting and OSAScriptingDefinition flags with the name of our sdef file to the Info.plist file:

...
NSApleScriptEnabled

OSAScriptingDefinition
Scrtipting.sdef

Let's add the following Scripting.sdef file to the project:












So, from AppleScript we have one property available - myprop. All that remains is to write ObjC code that will process reading this property from scripts. To do this, we need to create the NSApplication category, since this is the class we chose as the recipient of messages from scripts.

#import
@interface NSApplication (Scripting) - (NSString *) myprop;
@end
@implementation NSApplication (Scripting) - (NSString *) myprop
{
return @"This is my property";
}

If we now turn to the properties of our application from AppleScript, we will see our property and its value among them:

tell application "Scripting"
properties
end tell

Conclusion

Of course, it is impossible to describe here all the capabilities of AppleScript and its interaction with Cocoa applications. Yes, this is not necessary - there are manuals for this. And we, for our part, will continue the series of articles about coding for Apple platforms and will tell you many more new and interesting things.

Not using AppleScript yet? Don't know what it is? Do you think this is of no use to you? Or, perhaps, the memory of school computer science lessons causes you to have an allergy attack at the mere mention of the word “program”? This means you did the right thing by opening this article.

I hope it will help you sort this out a lot. useful tool, and the time spent reading will pay off handsomely later.

Often, when working with a particular program, we have to perform the same actions many times: press the same keys, select the same command from the menu, enter the same values ​​in dialog boxes& This is where we come to the rescue AppleScript arrives. We describe the sequence of our operations in the form of a “script” program, launch it and calmly drink coffee, occasionally glancing to see if the processing of the last, three thousand seven hundred and eighty-ninth file has finished. Something similar exists in the form of DOS BAT files or UNIX shell scripts. But AppleScript has an important advantage: the language is “understood” by both the Finder and a large number of application programs, and the script can access them all one by one.

The language we will use (also called AppleScript) is very close to regular English. For example, the script might look like this:

tell application "Finder"
make
end tell

I think everyone understood what he would do. But to learn how to write your own scripts, you will have to understand some concepts.

Objects, properties, events...

AppleScript is an object-oriented language. That is, everything that “exists” in your computer, it considers objects(objects). An object can consist of other objects, be included in another object, or relate to another object. For example, Finder is an object. It has “subordinate” objects - folders, files, windows. The Tex-Edit editor has a text object, consisting of words, lines, paragraphs, etc. Knowing how objects are related (their hierarchy) is very important, since the command is transmitted “along the chain”. A sort of “vertical of power” operates: we give orders to Finder, it gives orders to the folder, it gives orders to the folder nested in it, and so on, until it reaches the desired file. And the “execution report” will again follow the same chain - in the opposite direction.

Objects of the same type (for example, all folders) form Class(class). Each object has a certain set properties(properties) that distinguishes it from another. For example, each file has a name, label, type, creation date, version, and more than a dozen characteristics. The script can change some of them, some can only be read.

One class (called "descendant") can inherit properties of another class ( "ancestor"). For example, both folders and files have a common ancestor - an element (item).

Now let's look at our example, expanding it a little:

- any text written after the “two minuses”,
— considered a comment;
- the computer doesn’t pay attention to it
tell application "Finder"
- begins with the word tell team group,
- related to one object
make new folder at desktop with properties (name:"Mine!", label index:2)
end tell - and this is how the group of commands ends
tell application "Finder" to tell item "Mine!"
open
set its name to"Only for me"
end tell

We first tell Finder to create a new folder object located on the Desk. Some properties are specified in the command (folder name and its color label), the rest will be assigned by the computer by default. Then we tell Finder to command his folder (this and only this way: “my vassal’s vassal is not my vassal”) to open and change the name.

But it’s time to move from theoretical reasoning to something more tangible. It's time to launch the Script Editor.

Script editor

Several programs have been created to work with AppleScript, including very advanced development tools. You'll probably end up owning one of these later. But for an initial acquaintance, the editor included with Mac OS will be enough for us.

The Script Editor window is divided into two parts: the comment is written in the upper part (it is displayed on the screen before the script is executed), and the program is in the lower part. Let's try to type our example (of course, you can do without my comments). Then click the “Check syntax” button. If you made any mistake, an explanatory window will appear. But, most likely, everything will be fine - and after a short pause the text will change its appearance somewhat. The font used to highlight different elements of the script can be configured using the “AppleScript Formatting” command in the “Edit” menu. Now you can click the “Run” button. It worked?

The written script can be saved in different ways: either original text(Text), or already compiled script(Compiled Script) - ready to be executed by a script editor or some other programs, finally - in the form of an independent one (footnote: of course, not quite - it won’t do anything without AppleScript installed) applet program(Application). You can make a script “execution only” (Run-only). Just remember in this case to save - for yourself - and original file. Otherwise, not only competitors eager to violate your copyrights, but also you yourself will not be able to get to its source text.

Dictionaries, dictionaries, dictionaries...

“Well, okay,” you are probably thinking, “using the editor is as easy as shelling pears, reading ready-made scripts is also not difficult. But how to write them? Where do we get all these classes, commands, properties?” The answer is simple: you need to look at dictionary. Each program that supports working with AppleScript, as well as ScriptingAddition (we’ll talk about “additions” later) contains short description all its objects and recognized commands. You can view this dictionary directly from the script editor - by selecting “Open Dictionary” from the “File” menu or by dragging the desired program to the editor's picture.

Macintosh programs can support AppleScript at three different levels.
Scriptable- the program can execute commands described in the form of a script.
Recordable- it is possible to record commands executed in the program. Let’s create a new script, start recording (using the “Record” button), and perform it, for example, in Finder manually necessary actions, stop recording (“Stop”). That's all. This makes it very convenient to create script templates.
Attachable- the script can be executed directly from the program, being “attached” to a menu or any object in the window. Examples of such programs: AppleWorks, Tex-Edit, FileMaker Pro.

Let's open, for example, the Finder dictionary.

On the left you see a list of all the “terms” defined in the program. Please note: some of them are in italics. These are objects. All others are teams. By clicking on the desired word, you can read a short summary.

What, for example, can you find out about “Container”? First, we see: “Class container: An item that contains other items.” That is, it is an element containing other elements. And if you look at the descriptions of the next few classes, it will become clear that “container” is a concept that includes disks, folders, Desktop, and Trash. It has the common properties of these largely similar objects. And in the “family tree” - the hierarchy of classes - he is their ancestor.

Read on. "Plural form: containers". Plural form? Are we studying English grammar? Yes and no. I already mentioned that AppleScript is as close to natural language as possible. And if we want to process all objects of a given class, then write it down, as it should be in English language, you can either “every container” or “containers”.

As you already know, an object can contain other objects. Which ones and how they differ from each other are described in the next section of the dictionary - “Elements”. A container, as you can see, can contain objects of one and a half dozen different classes, for example, other containers, folders, document and program files, etc. And you can indicate a specific element of a class either by name (by name) or by serial number (by numeric index).

And finally, the last section is “Properties”. Here we, firstly, see that the “Container” class is a descendant of the “Element” class ( item ), that is, it has all its properties. But this class also has several of its own. Please note: some of them are marked “” (read only), these properties cannot be changed using the AppleScript command.

Now let's see how the commands are described in the dictionary. For example, let’s take the “Make” script that is already familiar to you from examples of scripts. At the top of the page is the purpose of the command (create new element). Then - how it is written (syntax) and what parameters it has. Note that some parameters are enclosed in square brackets. This is what the dictionary means optional options. When composing a script, we can do without them, but if we use them, we don’t need to put any parentheses. Completes the help for a command by indicating it result(Result). In our example, it will be a “reference” to the created object.

Here you go. You can already try to write some simple script. So…

O creator!

I think you know that every file on a Macintosh has two characteristics - a type and a creator code, which allow the Finder to decide how to handle this file. It is also no secret that often - for example, after transmission over the Internet - these attributes are lost. Of course, there are many programs that can change them. But let's try to make our own utility, using only what is already included in Mac OS.

Let's start with the simplest option. Suppose we need to assign the file letter.txt, located on the Desk, the type “TEXT” and the creator code “ttxt” (SimpleText).

Select the file object in the Finder dictionary. We find the properties we need: file type and creator type. To change the value of a particular property, use the command “setraquo; (install). So the whole script should look something like this:

tell application "Finder" to tell file "letter.txt"
set its file type to"TEXT"
set its creator type to"ttxt"
end tell

Or like this:

tell application "Finder"
set file type of file "letter.txt" to"TEXT"
set creator type of file "letter.txt" to"ttxt"
end tell

Thus, as you can see, you can either tell the file to change its (its) properties (in in this example the word “its” can be omitted, since the purpose of the command is clearly defined without it), or the Finder program can change the properties of the subordinate object.

It was not for nothing that I set the condition that the file is on the desktop. Otherwise, we needed a longer “chain” of subordinate objects (something like “tell application “Finder” to tell disk “Macintosh HD” to tell folder “lesson” to tell file “letter.txt””). Or - for the second version of the script - an indication full path: “file “Macintosh HD:lesson:letter.txt”” (Remember: the path in Mac OS is written using colons).

Well, the script is written. He works. But frankly speaking, there is no benefit from it - after all, for each subsequent file you need to change the text of the script itself. Wow, made the job easier! We need to improve our program. Let's teach it to ask the user which file to process. Open the Finder dictionary, look& Here are the ones! Nothing suitable. Did Apple really make such a mistake? Not at all…

“Don’t you have the same one, but with mother-of-pearl buttons?”

Open Script Architecture (OSA) allows you to acquire almost any necessary element of the language. Of course, if someone bothered to write "addition"(Scripting Addition or OSAX) that describes such an object and the corresponding commands. These additions are located in the Scripting Additions folder, located in the System Folder (formerly in Extensions). Any script can use them, regardless of what program it is currently running.

Let's open the Standard Additions dictionary (to quickly get to the Scripting Additions folder, there is a special button in the Open Dictionary dialog). Here it is - the “choose file” command. The result of its work will be a link to the file selected by the person in the standard Open dialog. We will save this link in a variable, which we will call, for example, MyFile.

Our script will look like this:

tell application "Finder"
set MyFile to choose file
set file type of MyFile to"TEXT"
set creator type of MyFile to"ttxt"
end tell

Quite functional program. But is it possible to make it more convenient? Why run the script separately, then select the file name in the dialog - isn’t it better to use the Drag’n’Drop method? Everything is within our power!

Writing Droplet

So what do we want to get and how to achieve it.

  1. The program should work independently of the script editor. Everything is clear with this, we already know that for this it needs to be saved as an applet.
  2. The purpose of the script is to change the properties of a given file. We already have this part ready.
  3. The file that is “drawn” onto the script image should be processed. This is where the fun begins. Various things constantly happen to objects “living” in our computer. events. For example, the file may be moved, copied, or opened. The program will start, execute some commands or do nothing, and finally end. In order for an object to “know” how to react to a particular event, a special subroutine is needed - "handler"(handler). When files, folders, or drives are “thrown” onto the applet, Finder sends it an “Open” command message and a list of “thrown” objects. It is for this event that we will have to write a handler.

In the simplest case it will look like this:

on open FileList — the word “on” begins the event handler
— at first the script works on its own without affecting any programs
set MyFile to item 1 of FileList
tell application "Finder" - now we command Finder
set file type of MyFile to"TEXT"
set creator type of MyFile to"ttxt"
end tell
end open - don’t forget to indicate that the handler has ended

To temporarily store the list, we used the FileList variable. Variables can be named using any combination of Latin letters, but it is advisable to name them in such a way that you can understand from the name what this variable means.

As you can see, the first element from the list passed when the script was launched is processed. What about the rest? Our program simply does not pay attention to them. It's not hard to guess that the next step on the path to perfection will be processing a whole bunch of files at once.

Once, once, once again...

Until now, all the commands of our scripts were executed one by one in the order they were written. Now we need to repeat the same actions several times in a row. We will have to organize a special structure - cycle. AppleScript has a variety of control commands for this. You can repeat actions in advance a specified number of times, or perform them while a certain condition is met. But almost any programming language has such loops. In our task, another option is ideal - “repeat for each element of the list.” With it, the script will look like this:

on open FileList
repeat with MyFile in FileList - this is how the beginning of a cycle is written
tell application "Finder"
set file type of MyFile to"TEXT"
set creator type of MyFile to"ttxt"
end tell
end repeat - end management structure be sure to celebrate
end open

What else does our program need to become completely professional? And she doesn't have enough "foolproof". After all, you can “throw” folders and shortcuts onto the script’s image, but it should only work with regular files.

Whoever you want, choose

Therefore, when going through the elements of the list, you need to determine what each of them is. Only if you come across a regular file, change its properties. Another control structure allows you to choose whether to do or not do any operations - conditional operator If. You can determine whether an object is a folder or a shortcut by obtaining information about it using the “info for” command from Standard Additions. The result will be an object of the “file information” class. These are its properties - “folder?” (folder) and “shortcut?” (alias) - we will check. Because we need the element not to be a folder AND was not a shortcut, we will connect two conditions logical operation“and” (when it is sufficient to fulfill any one of the conditions - OR first, OR the second - use the connective “or”). In general, as a result of our reasoning, the following script was obtained:

on open FileList
repeat with MyFile in FileList
set theInfo to info for MyFile
if(folder of theInfo is false) and ¬
(alias of theInfo is false) then
tell application "Finder"
set file type of MyFile to"TEXT"
set creator type of MyFile to"ttxt"
end tell
end if
end repeat
end open

Please note that all conditions in the If statement must be written in one line. To make the program text more readable, it can be useful to “fold” a long line, as done in this example. To do this, press the “Option-Return” key combination. The continuation symbol “¬” will appear in the text.

Of course, in this short lesson I was only able to introduce you a little to the simplest techniques for working with AppleScript. But I think you are convinced that there is nothing complicated about this. Try it! I hope to continue this topic in future articles.

AppleScript is a powerful programming language that dates back to Mac OS 7. However, despite its maturity, experienced Mac programmers often criticize AppleScript for being too simple, too easy to learn, and too similar to regular English.

Of course, you would want a computer language to have these very qualities—if, of course, you want a computer language at all. AppleScript is simplest language programming with which you can automate your Mac, even if you are a simple user and not a certified computer scientist.

AppleScript programs (called scripts, or scripts) can be considered software robots. A simple AppleScript can do some everyday tasks like creating backup copy Documents folders. A more complex script may span several pages. In professional publishing houses, where AppleScripts are most popular, the script can connect over the Internet to the photographer's hard drive, retrieve the photo from a specified folder, perform color correction in Photoshop, paste the result into a specified layout document, print a rough layout, send an email notification to the editor - and all this is done automatically.

Without even knowing it, the user is constantly using the underlying AppleScript technology. Numerous Mac components communicate behind the scenes using Apple Events, which are messages that pass instructions or data from program to program. If you use the Show Original command on an alias or the Get Info command on a file or folder, the Apple Event will tell Finder how to respond.

AppleScript is superior to Automator in a number of ways, not least of which is its power. And one more thing: AppleScript is such a deep topic that it should be dedicated to a separate book. This chapter is just a tasty appetizer: a book like AppleScript: The Essential Guide would be a seven-course meal.

Advice You can download an entire chapter on AppleScript—which appeared in a previous edition of this book—from the Missing CD page at www.missingmanuals.com.

You don't need to create AppleScript to enjoy the benefits of this technology. Mac OS X comes with dozens of ready-made scripts that are really useful, and to execute any of them, just select its name in the menu. This "reproduction" of an AppleScript requires as much technical skill as pressing a button in an elevator.

You can try out some of these cool starter scenarios by adding a scenario menu to the menu bar (Figure 7.16, right).

The scenario menu has 16 ready-made categories, combining about 100 scenarios; to run a script, simply select its name. Here is a list of the most useful and interesting scenarios.

Advice If you press the Shift key while selecting a script name from the menu, Mac OS X will take you directly to where that script is located in the Finder (for example, the Home>Library>Scripts folder). Moreover, if you press the Option key while selecting a name, the script will open in the Script Editor, where you can examine or edit it.

This submenu contains only the Import Addresses script, which is designed to copy names and addresses from Entourage, Outlook Express, Palm Desktop, Eudora, Claris Emailer, or Netscape into the Address Book program. If you have a lot of friends, use this script so you don't have to re-enter all their names, phone numbers, and postal addresses. (The accompanying Address Importers subfolder offers scripts for importing from three specific programs.)

The Basics submenu contains three handy little scripts related to AppleScript: AppleScript Help (opens the Help Viewer and searches for the word AppleScript); AppleScript Website (opens the AppleScript web page in your web browser); Open Script Editor (opens the Script Editor program, designed for reading and editing AppleScript scripts).

This folder contains a group of ColorSync droplet scripts (that run when you drag something onto its icon) that are of interest to artists, website designers, publishers, and the like.

In some cases, when you select a script from this menu, you will see a short Announcement and then the Open dialog box to select the graphic file to be processed.

Others act immediately; for example, the Mimic PC monitor script adjusts the screen colors to closely match the slightly different hues on a Windows computer monitor. This is very convenient if you are working on

EXPERIENCED USER COURSES
Secrets of the script menu
The script menu displays the contents of two different folders Scripts: One is Home>Library>Scripts and the other is in the main Library folder. Those scripts that are taken from your personal folder are separated by a dotted line in the script menu.

These scripts can not only be run. They're also ideal for opening them in the Script Editor (just double-click) and analyzing line by line how they work. Once you understand the syntax, you can copy code fragments and, after changing them, use them in your scripts. (The Script Editor is a program found in the Applications > AppleScript folder that you can use to create your own scripts.)

A photograph or a web page and want to know how it will look to the unenlightened masses. (To restore the original colors, go to the Color tab of the Display remote in the System Preferences window.)

All of these scenarios relate to working in the Finder - say, manipulating files and windows. Here are the most useful ones:

Add to File Names, Add to Folder Names. These scripts attach a prefix or suffix to the name of each file or folder in the front (active) Finder window (or, if there are no windows open, on the desktop). Using these scripts, you can add the word "draft" or "final" or "old" to the names of all the files in a folder.

Replace Text in Item Names allows you to perform a replacement search in the names of files, folders, or both. If one publisher rejects your 45-chapter book proposal, you can use this script to rename all 45 chapters: let's say what was "A History of Mousepads - Proposal for Random House, Chapter 1" becomes "A History of Mousepads - Proposal for Simon" & Schuster, chapter 1."

Trim File Names, Trim Folder Names. If you made a mistake when you ran the Add to File Names script, you can always fix it using Trim File Names. This script removes file extensions, suffixes, or prefixes of the user's choice.

Let's say you've just created several new folders at once. Mac OS X names these folders "untitled folder", "untitled folder 2", etc. But what if you're more comfortable with the names "folder 1", "folder 2", etc.? Run the Trim Folder Names script; In the dialog box, type untitled and click OK.

It is unlikely that you will actively use Folder Actions scripts, since the exact same access to operations on folders is provided by Control-clicking on a folder (or inside its window)

These scripts demonstrate how you can automate some font-related tasks.

FontSync is Apple's noble attempt to resolve old problem desktop publishing. You've finished creating a beautiful newsletter and are taking it to your local print shop to have it printed on high-quality equipment, only to find that you have to throw away the prints and start over - only to find out that the fonts don't look the way you wanted. . The printing house did not have exactly the same fonts that you used to prepare the document. Or, even worse, the fonts had exactly the same names, but were created by a different company, and therefore differed slightly from yours in certain parameters.

The idea behind FontSync is to notify the user in advance of possible inconsistencies. The Create FontSync Profile script creates a FontSync profile file in a few minutes. This document contains a staggering amount of information about the design, flow, and flourishes of all the fonts installed on the system. In a printing house, such a document can be processed using the additional Match FontSync Profile script. It will meticulously identify the differences between the fonts on the user's Mac and the printing presses.

Of course, this technology implicitly assumes too much: that the printing house has Macintosh computers installed, that they can handle FontSync, and also that the user will not forget to first create and transfer a FontSync profile to the printing house.

IChat has undergone a significant overhaul in 10.5 - Apple has added a lot of interesting (though sometimes useless) features. It also became possible to run AppleScripts as signals when an event related to your contacts occurs. For example, you can automatically accept chat invitations from individual contacts or even respond to them with a pre-prepared greeting. You can even control music playback on one Mac by typing commands into the iChat window of another Mac in your home. Details in Chapter 21.

The benefit of these two scenarios is small. Current Date & Time displays the current date and time in a dialog box equipped with a Clipboard button for copying information, ready for pasting. Font Sampler displays a page listing the fonts (whose names are written in the script) that are installed with Mac OS X. (The script has become less useful since Font Book added similar built-in print commands.)

Two scenarios in this menu deserve special mention. Current Temperature by Zipcode shows what the temperature outside the window is in Fahrenheit and Celsius. This is another reason not to leave the house all day.

Stock Quote receives stock quotes for the selected company with a 20-minute delay. Not as great as getting real-time quotes, but it's free.

Most of the scripts in this submenu solve some specific problem such as counting letters in your emails. mailboxes or setting up a new one account. The funniest of all, of course, is the Crazy Message Text scenario (Fig. 7.17).

The scripts in this folder allow you to jump into special Finder folders—right from the menu, from any program. If the folder you want to open does not have its own script assigned, select it from the list in the Open Special Folder script.

Advice For those who don't mind having to edit this script using the Script Editor, you can modify it to allow you to select and open more than one folder at a time (via, say, -click). You just need to type the text multiple selections allowed true immediately after the words Choose folder to open: (at the end of the line, located approximately at the beginning of the second third of the script). Don't forget to save your changes.

These scripts are designed to demonstrate the power of AppleScript for printing and creating PostScript and PDF documents.

One of them, Print Window, fills a long-standing gap in Mac OS X. It should print a text list of the contents of any selected folder. (It's a little buggy, though.)

According to the About these scripts team, these 48 pre-built scripts help you write faster and more accurate scripts because the code snippets are typo-free and syntax errors. As you get better, you can add your own scripts here, with snippets of code tailored to the scripts you typically write to make your work even more efficient. (When you create a script in the Script Editor, you insert these code snippets into the text using a Control-click and menu selection quick access.)

For the most part, the scripts do their job quietly and unnoticed. But if you want to automate a program that doesn't understand normal AppleScript commands, scripts can "control" it manually by simulating menu selections, button presses, and so on.

Note This feature, called user-interface (UI) scripting, will only take effect after you open the Universal Access console in System Preferences and select the Enable access for assistive devices check box. auxiliary devices).

There is no point in running the scripts from the UI Element Scripts submenu as is: they are just samples to demonstrate the correct syntax.

This latest set of scripts provides quick access to some popular websites. An exception is the Download Weather Map script, which downloads the current weather map of the continental United States, saves it to the desktop as weathermap.jpg, and then opens it in Preview.

Advice You can add scripts, files, and even Internet addresses to the menu, and then easily launch them all from the menu bar. Anything you drag into the Library>Scripts folder will automatically appear in the scripts menu.

On the other hand, if you start adding a lot of your own items to the Script menu, it will be more convenient to remove the Apple samples from it. No problem. Open AppleScript Utility and uncheck Show Computer scripts.

Work with ready-made scripts AppleScript

As you work through the scripts menu, you'll soon realize that you have dozens of free built-in scripts on your Mac. The great thing is that you can figure out how they work and even change them as you gradually learn to write your own AppleScripts. You can even copy and use entire sections of Apple scripts in your own scripts.

First, of course, you need to open the script. The easiest way to do this is to open the script menu, select the desired category and Option-click on the name of the desired script.

You can start learning AppleScript by watching a simple script. For example, open the New Application Window script (In the Navigation Scripts category) by Option-clicking its name. As a result, Script Editor will open the file in a new window (Fig. 7.18).

Here's how this script works:

Tell application "Finder" tells Mac OS X which program should run the following commands.

Activate brings the Finder to the foreground—just as if you had clicked its icon in the Dock.

Open folder "Applications" of the startup disk tells Finder to open a new window displaying the Applications folder of the main hard drive.

End tell tells Finder to go about its business and ignore any further commands from your script.

To test the script, click the Run button or press -R.

Advice You can edit this script to better suit your needs. Try, for example, replacing "Applications" with "Users" so that the script opens the Users folder.

Creating Your Own AppleScripts

Mac OS X comes with dozens of programs - so many of them! Okay, there's something missing - a metronome, for example. How are you going to play the piano in a steady rhythm without hearing the rhythmic clicks your Mac makes? Of course, in a pinch, a GarageBand metronome will help, but this is shooting sparrows from a cannon.

You can use AppleScript instead. Open a new document in the Script Editor (File>New, or -N) and type the following:

display dialog "Welcome to the AppleScript Metronome"

set bpm to the text returned of (display dialog ¬

"How many beats per minute?" default answer 60)

set pauseBetweenBeeps to (60/bpm)

delay pauseBetweenBeeps

Note There is no need to print the ¬ symbol. So programmers say: “This should be on one line, but there is not enough page width.”

When you run this script, a dialog box appears asking you how many beats per minute you want the metronome to count. The number you enter (for example, 120) is stored in a temporary storage variable within the script called bpm.

The script then calculates the amount of pause between beeps and records that fraction of a second in the pauseBetweenBeeps variable. If you told the script to beep, say, 120 times per minute, then pauseBetweenBeeps would be written to 0.5 because there should be a half-second pause between beeps.

Finally, the script creates an infinite loop: signal, pause for a specified length, and then repeat.

Click the Run button to test your script, and when you've heard enough sounds, click the Stop button.

MY FAVORITE TECHNIQUES
One-click desktop attachments
Here's a little trick with Automator that can be a lifesaver for anyone who frequently needs to send documents by email. (It models the very convenient Send To command found in the shortcut menu of Windows machines.)

Create a process in Automator with just two steps: Get Selected Finder Items (in the Finder category) and New Mail Message (in the Mail category).

If you always send files to the same recipient—your boss, for example—you can even pre-set the address in Automator's process panel. If the subject and text of the message are repeated each time, you can also set them in advance.

Now select File>Save As Plug-in. Name the process Email This or whatever you want.

From now on, you can send a document from the Finder by Control-clicking on it and choosing Automator>Email This from the menu that appears.

Victory! Mac OS X launches Mail and creates an outgoing message with a file attached.

Free tip: if you insert another Create Archive action (from the Finder category) between these two actions, your menu command will also compress the file (or folder) into a .zip file before sending it by mail!

Advice It will be even cooler if you put it in system settings System Preferences>Universal Access>Hearing>Flash the screen when an alert sound occurs. Now, when your script runs, the screen will flash along with the sound. If you're recording music, mute your Mac: you'll have a visual metronome, but no audio signal.

Comparison of AppleScript and Automator

There are hundreds of uses for AppleScript - automating processes that are too complex for Automator, controlling programs that Automator can't see, and programming things like command looping that Automator can't do.

If you only look at AppleScript as a replacement for Automator, you're missing out on a lot of power. In truth, AppleScript provides capabilities that Automator probably won't have in 10 years: it's a much more advanced tool.

Automator is good for simple tasks. If you need AppleScript to automate your Mac, don't despair. You are taking on a truly powerful tool. (You can even combine them and embed AppleScripts into Automator processes using the Run AppleScript action.)

Good luck with automation!

Open, crop, convert to another color model, save. Open, crop, convert to another color model, save. Open Or else: Select, transfer to the buffer, switch to another application, copy from the buffer. Select, transfer to buffer, switch

Doesn't sound like a creative activity, does it? But almost everyone who deals with a computer has to perform dozens and hundreds of repetitive, essentially identical operations per day. And after working for three weeks as a kind of “intelligent converter”, it’s no longer like teaching new version“Photoshop” or master InDesign - you don’t even want to go close to the computer. In a word - you need an assistant. Which will take upon itself the execution of all (or at least most) boring and routine, but, of course, necessary repetitive actions.

AppleScript - what kind of beast is it?

And we have such an assistant. This is a special language for writing scripts (or, if you prefer, scripts) called AppleScript. This language first appeared in Mac OS 7.5 (then still the Macintosh System), and was so well implemented and also had such wide capabilities that by the release of the tenth version of the OS it only reached version 1.8. But, oddly enough, despite its enormous potential capabilities and its more than ten-year history of existence, AppleScript technology has not become widespread among Mac users. Whether this is due to myths about its complexity, the inertia of users who are accustomed exclusively to the “icon-mouse” control of their Macs, or something else, I cannot judge, but the fact is a fact: hundreds know about the existence of AppleScript, but only use it units. Therefore, in my opinion, it would not be superfluous to consider the basic principles of operation of this technology.
AppleScript is based on Macintosh Apple Events, a system event processing service that allows control commands, data, and requests to be exchanged between applications. operating system, network services and even different computers. The script engine (which is an ordinary Extension located in the System folder) converts script commands into a sequence of events, and passes them to the application specified in the script, and after processing them, accepts the result and forwards it to the script source.
Although AppleScript is a real programming language (it supports variables, loops, conditional statements, subroutines, allows complex calculations, and even has tools for building and processing dialog boxes), performing the main tasks still falls on the shoulders of external applications. And AppleScript acts as a kind of “glue” that transfers data between programs (“transfer a file from Illustrator to Photoshop”), evaluates the current state of the working environment individual programs, OS and network (“has the rasterization of the file been completed, or not yet?”), and allows you to take actions based on the results of previous operations (“if all files are rasterized, then send the materials to a special folder, and run the script responsible for assembling the newspaper stripes").
There are several levels of "scriptability" of applications. So, for example, those programs that are least adapted to automation understand only the basic, simplest commands: load an application, open a document, send to print and close the application (run, open, print and quit). More “accommodating” ones (such as Photoshop, Illustrator and FreeHand) have tools in their arsenal that are quite sufficient for writing programs batch processing files and performing certain sequences of actions (macro commands). Well, those that implement support for almost all the capabilities of AppleScript technology (and this includes QuarkXPress, Adobe InDesign and most programs Apple) make it possible to control your work at the most “deep” levels: set printing parameters, use the clipboard, check and change the values ​​of internal variables, etc.

Basics of Scriptology

To enter source text and execute scripts, you can use the Script Editor program - the main and only tool for creating scripts in the standard Mac OS package.
The script editor is located in the Apple Extras/AppleScript folder (for the localized version of Mac OS - Add-ons/AppleScript), and after launch it displays a window similar to the one shown in Fig. 1.


Rice. 1. Script Editor

The upper and lower input fields are intended to describe the script and its text, respectively, and are unlikely to need additional comments. The Record button allows you to record a macro command; to do this, after pressing the button, go to required applications, and perform a series of actions; after which the script text will appear in the lower input field (it should be noted that the ability to record macro commands is not supported by every program). The Check Syntax button checks whether there are any errors in the text of the script, and also brings it into a “marketable” form - it is highlighted in bold and indented. keywords and nested blocks.
Scenario one. To begin with, as expected, let’s write the simplest program, which performs several basic actions: closes all open windows, removes all removable disks from the media, organizes icons on the screen, cleans the recycle bin and turns off the computer. The text of such a program looks like this:

tell application "Finder"

Close every window
eject every disk
clean up desktop
empty trash
shut down

End tell

What does all of this mean? The Apple Events service (the "core" of AppleScript technology) transfers data, requests, and messages not just between programs, but between program elements called objects, which can have a nested structure called an object model. So, for example, for the Finder program, the object model (more precisely, just one of the branches of this model) can be represented in the following form: Finder - Desktop - Folder - File; For text editor this model will take the form Document - Page - Paragraph - Sentence; for a vector illustration it will look like Illustration - Basic Shape - Bezier Curve - Point (Fig. 2).


Rice. 2. Examples of object models

Each object typically has one or more properties (Figure 3) that can be set (“set the page height to 14 inches”), modified (“change the width from 8 to 8.5 inches”), and controlled (“what equals the right margin of the page?").


Rice. 3. Object properties

In order to control a particular object, it must be selected (indicated) on the object model. For this purpose the design is used tell end tell, and all commands that control the object are contained within this construct; if the object is located “in the depths” of one of the branches of the model, then several blocks nested within each other are used tell end tell. In the following example, the script incrementally accesses the desktop (one of the elements of the Finder object model) and then moves the "test" folder, which is on the desktop, to the Trash.

tell application "Finder"
tell desktop

Delete folder "test"

End tell
end tell

When writing a script that controls any program - it doesn’t matter whether it’s Finder, FileMaker, Adobe Acrobat or something else, you need to know what AppleScript language commands this program supports, what objects are included in its object model, as well as the names and purposes of all the properties of the available objects. All this information is stored directly in the executable file of a particular program, in the so-called application dictionary. To use this dictionary, in the Script Editor program you need to execute the command File / Open Dictionary (File / Open Dictionary), and in the window that appears, select executable file application of interest. As a result, a window similar to the one shown in Fig. will be displayed on the screen. 4 - on the right side there is a list of all commands and objects, on the left side there are their brief descriptions.


Rice. 4. Dictionary application

Second scenario. Let's move on to solving practical problems. Those involved in web design quite often have to check their pages for compatibility with older versions of browsers. To do this, you need to open windows with folders, look for executable files of viewer programs there, download them, and then also look for folders with web pages on the disks. In general, it’s not the most pleasant experience. Let's create a script that will simplify browsing pages: it will automatically load several different browsers, and in each one it will open the document we need.

tell application "Finder"

Select (specify) the required file
select file "index.html" of folder "Current web-site" of desktop
-- assign the myFile variable the path to the selected file
set myFile to the selection as string

Load Microsoft IE and open the selected page
tell application "Internet Explorer 3.01"
open(alias myFile)
end tell

We do the same operation with Netscape Navigator
tell application "Netscape Navigator 3.01"
open (alias myFile)
end tell

Several new designs have appeared in the above program. All lines that begin with symbols "--" are comments. In AppleScript, comments can be written either on a separate line or at the end of the line, immediately after the command. In any case, all characters following "--" and before the start new line are considered comments and are ignored when the script is executed.

The "select" command simulates the explicit selection of an element with the mouse cursor, and its action is somewhat reminiscent of the use of the construct tell end tell, but with the difference that when using the command select we can assign some properties of the selected object (for example, the path of a file or folder) to a variable.

Operator set serves to indicate the values ​​of variables that are created when they are first accessed. That is, there is no need to first describe the name and type of the variable: you wrote, for example, set myDate to the current date, and AppleScript created the variable, and selected the required size and type. But that's not all: using the operator set you can change all properties of objects. This is done as follows:

tell application "Finder"
tell desktop
tell file "Price list"

-- change the comment property of the "Price List" file
-- the file is on the desktop
set comment to "This price list is out of date!"

End tell
end tell
end tell

Or the same thing, only with the help select commands:

tell application "Finder"

Select file "Price list" of desktop
set comment of selection to "This price list is out of date!"

End tell

As you may have noticed, until now all work with scripts - typing source text and execution - was carried out exclusively with the help of a special editor. This method is good when you need to create a new script, or remake an old one. But for everyday use it is no good - while you open the Script Editor, while you find the required script on the disks, you involuntarily think - wouldn’t it be faster to do the same work manually, without any automation? The AppleScript developers took care of this - scripts can be stored not only as text files, but also in compiled form, completely suitable for offline execution. In order to convert the script into executable code, you need to run the Save As Run-Only command in the script editor. In the dialog box that appears (similar to what can be seen in Fig. 5), select Application from the drop-down list; reset the Stay Open checkbox (if you do not enable this option, then after execution the script will automatically complete its work, otherwise it will remain in the computer’s memory), and check the Newer Show Startup Screen checkbox. After you have completed all the described actions, launching the script will not cause you any difficulties: just hover your mouse cursor over it and double-click the button.


Rice. 5. Saving the script as an executable program

Scenario three and last. Surely about the benefits Reserve copy many have heard. And those who at least once in their life have lost the results of their monthly (at worst - at least a week) work certainly know that it is better to spend 15 minutes every day on archiving necessary files than then tearing out your hair and throwing ashes on your monitor. But, as a rule, even after loss important information people don’t change their habits: you might say to yourself, “That’s it, from today I’m making copies of all files!” And a week or two will pass - and the programs seem to be “not glitching”, and there is no free time - “And why do I need that backup! And this will do.” To make life a little easier for all those who want to see their files safe and sound, but don’t really like working with the StuffIt program, we’ll write a script that will archive all the necessary data every day and put it on a special disk. Here is the source text of such a program:

tell application "Finder"

Specify the drive and folder in which all files are stored
-- for archiving
set myArhiveFolder to the "Mac OS:Current work:"
-- specify the folder where the archives are stored
set myTargetFolder to the "For arhives:Publish Archive:"
-- assign the name of the future archive
-- (acts as a name The current date)
set myFile to the date string of the (current date) & ".sit"
-- create the full file name (path + name)
set myArhiveFile to the myTargetFolder & myFile

If a file with the same name already exists
-- (that is, the backup was carried out today)
-- then we just end the script
if not (exists (file myArhiveFile)) then

If a file with the given name does not already exist,
-- then download StaffIt Deluxe and perform archiving,
-- and immediately unload StuffIt from memory
tell application "StuffIt Deluxe"

Activate
make new archive with properties (pathname:myArhiveFile)
stuff (alias myArhiveFolder) into archive 1
close archive 1
quit

The above script simplifies the backup procedure, but not as much as we would like - to start archiving you will have to look for this script (on disks or on the desktop) and execute it. To fully automate the work, you need to compile the script and save it in the System/Shutdown Items folder. Now, every time you turn off the computer, the archiver will automatically load and save all important files to a special disk. It should be noted that archiving will be carried out only once a day, regardless of whether the computer worked for 20 hours in a row, or rebooted every half hour - using the condition operator if end if We are checking whether it is worth archiving, or whether it is better to wait. Until the next day.

So what is next?..

After reading about the capabilities of AppleScript and seeing how easy it is to create scripts, even for beginners, you may want to continue exploring this automation tool. And this is where the first disappointment awaits you. Unfortunately, there is practically no information on AppleScript in Russian: in order to count all the publications, the fingers of one hand are more than enough. Therefore, to learn a scripting language, you will also need good knowledge of the English language.

There are two main sources of information about AppleScript technology. The first is the official website of Apple Computer, or rather a section of the site dedicated to everything related to scripts: technical documentation, tutorials, examples, collections of links and much more. The address for this section is http://www.apple.com/applescript/. I strongly advise you to first download the AppleScript Language Guide - a well-illustrated textbook that includes many practical examples (the book is located at http://developer.apple.com/techpubs/macosx/Carbon/pdf/AppleScriptLanguageGuide.pdf, file size - 2 ,6 MB). The second source - the site http://www.scripter.com - contains a lot of materials both on AppleScript and on other alternative scripting languages ​​for the Macintosh platform.

In addition, if you decide to get serious about writing scripts, then you will need a good tool environment - the Script Editor, supplied with Mac OS, is only suitable for simple scripts of 20-30 lines of code. In this case, we can recommend Scripter 2.5 from Main Event Software - the editor has a debugging mode and a well-thought-out mechanism for displaying application dictionaries. And if you're going to create AppleScript programs that will have their own user interface, then it wouldn't hurt to also get FaceSpan 3.5 from Digital Technology - this application will reduce the time it takes to create on-screen menus and dialog boxes, and will allow you to avoid time-consuming and unpleasant fiddling around with sketches on millimeter paper. paper.

Instead of a conclusion

Writing scripts is interesting. Writing scripts is useful. Writing scripts is even nice. Although, of course, it is much more pleasant to indulge in the desired idleness, while the “freshly baked” script patiently works out the entire weekly routine.

Take the time, spend a few days learning the language, write a couple of scripts that simplify your work, and you yourself will understand that AppleScript is a very simple, very powerful, and very flexible tool. Although, should we have expected something different from Apple?..