Contact

If you like a new Web or Desktop
application, update a existing one
or add new modifications. Your at
the right place and hit the
hire me button

Follow

If your intersted you can follow
me on Twitter by clicking here

Web and Apps Building Refernce World Wild Web UNIX Apps AND Tips Programming languages

AppleScript

The First Step

Consider this chapter a “book within a book.” If you don't read any other chapter, read this one. It has been designed to give you a quick but thorough introduction to AppleScript through a short, fun, hands-on tutorial. In 25 minutes you’ll learn what AppleScript is, how it works, and how to write basic, functional AppleScript scripts with confidence.

To accomplish this goal, you’ll learn the fundamentals of AppleScript, and then put them to use as we step through the creation of a Finder Toolbar script, that you can use to instantly reset a cluttered desktop window display to a predefined window set.

What is AppleScript?

AppleScript is a language used to automate the actions of the Macintosh Operating System and many of its applications.

Whether a task is as simple as copying a file or as complex as building a real estate catalog, AppleScript can perform the requisite actions for you with “intelligence,” controlling applications and making decisions based on its observations or from information provided by its interaction with the person running the script.

Every day, businesses and individuals alike use AppleScript to create newspapers and books, manage networks, build DVDs, process images, generate web pages, backup files and folders, make videos, and much more. AppleScript is the most powerful, easy-to-use, automation tool available on any platform. And best of all, this technology is free and is built into every copy of the Mac OS!

HOW IT WORKS...

To automate the actions of applications, the computer reads the sequential instructions contained in AppleScript “scripts,” and then communicates those instructions to targeted applications. The targeted applications interpret the communicated instructions, and then perform the actions listed in the scripts.

AppleScript scripts are composed, by motivated users like yourself, in AppleScript, an English-like language containing many of the verbs, nouns, adjectives, articles and other English language elements we use every day. The AppleScript language is designed to be easily understandable, and has a syntax or grammatical structure similar to the one we use to create normal sentences.

Scripts are written in the Script Editor application, a free utility included with every copy of the Mac OS. Scripts can be “run” from within the Script Editor application or saved as either script files or script applications, available for use at any time, and from within any application.

Script files are launched from an application’s script menu or from the Mac OS system-wide Script Menu utility. Script applications, or “applets,” are launched like other applications by double-clicking their icons in the Finder or by clicking their Dock or Finder Toolbar and Sidebar icons.

THE BIG PICTURE

AppleScript is based on the concept of scriptable objects belonging to or being contained in other scriptable objects, such as a file being in a folder that belongs to the hard disk, or a word being part of a paragraph belonging to a story. Understanding the relationship between scriptable objects is essential to learning how to write scripts, and can be summarized in the following statements:

On the Macintosh computer everything is an object.

The computer, the desktop, the disks it displays, the folders on the disks and the files in those folders — all of these items are objects. So are applications, their documents, and the data in those documents.

Everything belongs to, is related to, is contained in, or is part of something else.

The file is in the folder that is in the disk that is on the desktop that is on the computer. This same relationship can apply to text as well. The character is in the word that is in the line that is part of the paragraph that is contained in the story.

This relationship between objects is referred to as being hierarchical or, in military terms, follows a “Chain of Command.” AppleScript uses this hierarchical containment structure to identify specific scriptable objects. All the scripts you write will contain hierarchical references.

Just remember this:

In scripts, objects are described in terms of their position in their hierarchical structure, or where they are in their “Chain of Command.”

NOTE: Don’t be put off by the term hierarchical. We often use hierarchical references to identify objects in our lives. For example, you refer to your home as being on a specific street, in a specific city, in a specific county, in a specific state, in a specific country. Or your advanced pottery class as being in room 128, on the third floor, of the west wing, of the Creative Arts building. Object references in AppleScript work the same way.

Properties and Values

Disks, files, folders, alias files, document files, application files, clippings, font suitcases, packages, internet location files, application files, windows and Finder windows are all objects or “elements” belonging to the Finder application. They are the items the Finder application uses in its organization and display of information. Each of these items has properties that define or describe the particular item. Some of these properties are unique to each item, some of these properties are shared by all Finder items.

For example, while an Internet location file or “link,” is the only Finder element that has a property describing a location on the Internet, it still shares some properties common to all Finder elements such as its icon size or its position in a folder window or on the desktop. And like other Finder elements, such as a folder or document file, a link file has a name property whose value is text displayed with its icon and can be edited by the user of the computer.

An Internet Location file is a file that, when opened, displays its target URL in the default browser window.

An important rule to remember about scriptable objects is this:

Every scriptable application contains elements or objects that have properties. These properties have values that can be read or manipulated.

This rule applies to the Finder application and to all scriptable applications as well. All elements of the Finder application have properties, such as their name, size, and location. All of these properties have values, some of which can be edited, some which can only be read.

THINK BIG… START SMALL

Your exploration of AppleScript is about learning the fundamental principles of the AppleScript language and how to apply them in writing scripts. No matter how complex a script is, the fundamental principles applied within the script remain the same. The lessons learned in scripting a common object such as a Finder window, pertain to all scriptable objects and applications, and can be used to create more complex and powerful automation tools later.

You’ll begin the process of becoming a Scripter by examining the properties of a Finder window and learn how to manipulate them with scripts.

The Script Editor

Since this tutorial is very “hands-on,” we’ll be writing scripts right away. To write a script, you’ll use the Script Editor application installed in your system. You can find this application in the AppleScript folder located in the Applications folder on your computer’s main hard drive. Navigate to this folder now and double-click the Script Editor icon to launch the application.

NOTE: The following description and illustrations are for the Script Editor application included in Mac OSX 10.5. Earlier versions will have a different design.

The Script Editor application icon.

After starting up, the Script Editor application displays a multi-paned window known as a script window. This script window comprises two panes, the top pane containing the script text, and the bottom pane containing either the script description, the script result, or the script log, depending on which tab below the pane has been selected.

A script window in the Script Editor application.

By default, the script window is rather small, so you may wish expand its size before proceeding with this tutorial. Please note that the Script Editor and other AppleScript tools are covered in detail elsewhere in this book.

Our First Script

You’ll begin the process of learning AppleScript by writing a series a simple script commands in the form of a “tell statements.” A tell statement is a single line script beginning with the verb: tell. This verb is used to direct script actions at a specific application or scriptable object. A tell statement is composed of two parts:

  1. A reference to the object to be scripted, and
  2. The action to be performed.

Using this grammatical format or syntax, we can write scripts instructing the Finder to perform whatever actions we desire. Here's our first script:

A simple script statement to close all open Finder windows.A simple script statement to close all open Finder windows.
 

tell application "Finder" to close every window

Enter this script in the top pane of the Script Editor script window exactly as show (be sure to encase the word “Finder” in straight quotes). Click the Compile button on the script window to confirm that it has been written correctly and to prepare the script for use.

Next, click the Run button to play your script. The operating system will read the script and send the appropriate commands to the Finder application, which will then follow the instruction to close any open windows.

Congratulations, you’ve written and run your first AppleScript script!

Note that the word “Finder” is enclosed in quotation marks in the script. Names and textual data are always quoted in scripts. This is done to indicate to the Script Editor that the quoted material is textual data and not to be considered as commands or instructions when the script is compiled in preparation for execution.

Delete the previous script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script to open the hard drive that contains the currently running System folder.
 

tell application "Finder" to open the startup disk

A new Finder window will now appear on the desktop displaying the contents of the startup disk. We’ll use this newly opened window as we examine the properties of a Finder window.

Finder windows display the contents of folders or disks.

A WORD ABOUT FINDER WINDOWS

Finder windows are different from other windows used by the Finder application, in that they display the contents of folders and, may contain a Toolbar and Sidebar. The remaining script examples of this chapter we will use the term Finder window instead of the generic term window when referring to Finder windows.

The Name Property

The first property of a Finder window we’ll examine is its name property.

A window’s name is the window title displayed in the title bar of the window. In the case of Finder windows, the value of the name property is the name of the folder or disk whose contents are displayed within the Finder window.

To retrieve the value of the name property of a window, we’ll use the command “get.” This verb is used when we want to extract information or data from a scriptable element or object.

Delete the previous script from the open script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script to retrieve the title of the frontmost Finder window.
 


tell application "Finder" to get the name of front Finder window

To see the result of our request, look in the Result Pane at the bottom the script window. To activate the Result Pane, click the tab titled Result at the bottom of the script window. In the Result pane you’ll see the result, if any, of the last script action. In the previous example, the result is the title of the open Finder window, which also happens to be the name of your startup disk.

A script window displays the result of the last script action in the Results pane at the bottom of the window.

For Finder windows, the name property is a read-only property. It can be used to refer to a Finder window, however, its value cannot be changed by a script. The value of the name property of a Finder window will always be the name of the folder or disk whose contents it displays.

Delete the previous script from the script window, then enter, compile, and run the following script. Be sure to replace “Macintosh HD” with the name of the open Finder window if it is different on your computer.

Click to open example in the Script Editor applicationA script that closes a specific Finder window.
 


tell application "Finder" to close Finder window "Macintosh HD"

As the previous script demonstrates, you can use the name property as a means to refer to a specific Finder window. When the script is run, the Finder window named “Macintosh HD” is closed.

The previous script worked because it is a fully qualified tell statement, in that it both refers to the object receiving the commands, in this case the open window, and indicates the desired action to be performed, closing the window. All tell statements are constructed in this manner.

A script consisting of a single tell statement targeting a Finder window.

Also note that the result of the script action is a set of curly brace characters. This is an AppleScript list. We’ll talk more about that in a couple pages.

The Index Property

If you’re writing a script that will be used on multiple computers, using the name property to refer to Finder windows is not always the most reliable way to locate a specific window. It’s possible that two windows may have the same name. Another more generic way to refer to an open Finder window is through itsindex property.

The value of this read-only property is a number corresponding to the window’s layer position in the stacking order of open Finder windows. On the computer, no two windows can occupy the same layer. One window is always on top of or in front of another window. The index property reflects this fact.

For example, the front Finder window will always have an index value of “1,” since it is the first window in the stack of open window, while the last Finder window will always have an index value equal to the number of open Finder windows.

Let’s see how the index property can be used to refer to Finder windows.

First, let’s re-open the previous window using this script:

Click to open example in the Script Editor applicationA script that creates a new Finder window displaying the contents of the startup disk.
 

tell application "Finder" to open the startup disk

Now delete the previous script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script that retrieves the value of the index property of the frontmost Finder window.
 

tell application "Finder" to  get the index of Finder window "Macintosh HD"

The result of this script, shown in the Results pane, will be the numeric value “1,” since there is only one window currently open on the desktop.

IMPORTANT: Note the use of the special character (¬) in the script text in the following example. This character, generated by typing option-L or option-Return, is used by the Script Editor to indicate that a single line statement has been placed on multiple lines in order to make it easier read. Due to the space restrictions involved in displaying scripts in a book, this character will be used in all script examples containing long statements. The Script Editor has an auto-wrapping feature that makes the use of this character unnecessary. If you are using the Script Editor, ignore the special character and continuing entering the script on the same line.

Let’s open a second window. Delete the previous script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script to open a second Finder window.
 

tell application "Finder" to open home

A second window displaying the contents of your home directory will now appear on the desktop.

TIP: Note the use of the word “home” and “startup disk” in the previous scripts. “Startup disk” and “home” are special terms, reserved by the Finder application, to identify important locations. These terms are generic and will work regardless of how drives and folders are named on the computer.

Now, let’s see if the addition of the new window on the Desktop has effected the index value of our previously targeted window. Delete the existing script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script that retrieves the value of the index property of a Finder window specified by its name.
 

tell application "Finder" to  get the index of Finder Window "Macintosh HD"

The result of this script is now the numeric value “2” since the target window is the second window in the stack of open windows on the desktop.

In the Finder, all windows occupy a layer in the stack of open windows. No two windows can occupy the same layer and therefore can overlap each other.

The index property can be also be used to refer to any open window. Try these scripts one a time and note their results:

Click to open example in the Script Editor applicationScript statements using the value of the index property to retrieve the name of specified Finder windows. 
 

tell application "Finder" to get the name of Finder Window 1
 --> returns the name of your home directory

Click to open example in the Script Editor application
 

tell application "Finder" to get the name of Finder Window 2
 --> returns the name of your startup disk

DESCRIPTIVE INDEX VALUES

As you've seen in the previous scripts, the AppleScript language is designed to be “English-like” and can be written in a conversational manner. Because of this, the value of the index property can also be described using descriptive terms as well as numeric values. For example, try these two scripts:

Click to open example in the Script Editor applicationScript statements using descriptive index values.
 

tell application "Finder" to  get the index of the first Finder window
 --> returns: 1

Click to open example in the Script Editor application
 

tell application "Finder" to  get the index of the second Finder window
 --> returns: 2

Note the use of the words “first” and “second” for the value of the index property instead of the numbers “1” and “2”. The AppleScript language will accept the terms: first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, and tenth, in place of their corresponding numeric character equivalents.

As a matter of fact, the value of the index property of the previous scripts could also be written like this:

tell application "Finder" to get the index of the 1st Finder window
--> returns: 1

tell application "Finder" to get the index of the 2nd Finder window
--> returns: 2

The use of descriptive suffixes works with any number, not just the first ten: 22nd, 312th, 3rd, etc.

RELATIVE POSITION

In addition to recognizing index values written as text, AppleScript will also accept index values described in terms of a window’s position relative to other windows. For example:

tell application "Finder" to  get the index of the front Finder window
 --> returns: 1
tell application "Finder" to  get the index of the back Finder window
 --> returns: 2
tell application "Finder" to  get the index of the last Finder window
 --> returns: 2
tell application "Finder" to get the index of the  Finder window before the last Finder window
 --> returns: 1
tell application "Finder" to get the index of the  Finder window after the front Finder window
 --> returns: 2

The index values in the previous scripts examples were written using the terms: frontback, and last. AppleScript will accept the term middle as well. Also note that the additional terms before and after were used to further define the target window’s location.

FINDER WINDOW INDEX REFERENCES

The value of the index property can be expressed using any of the previous methods. All are valid and can be used freely and interchangeably. Here’s a summary of the ways a Finder window can be referenced:

by name:
Finder window "Documents"
by numeric index:
Finder window 1
by descriptive index:
the first Finder window
the second Finder window
the fifth Finder window
the 1st Finder window
the 23rd Finder window
by relative position index:
the front Finder window
the middle Finder window
the back Finder window
the last Finder window
by random index:
some Finder window

CHANGING A FINDER WINDOW’S INDEX VALUE

So far we’ve examined the name and index properties by using them to refer to specific Finder windows. The name property is a read-only property, in other words, its value can be gotten but not changed. However, the index property of a Finder window is an editable property, meaning its value can be altered.

Next, we’ll change the value of the index property of the open Finder windows. To change the value of a property, we’ll use the verb “set” in our scripts. Set is the verb or command used to change the value of a property.

Delete the previous script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script statement that moves the last Finder window to the front.
 

tell application "Finder" to  set the index of the last Finder window to 1

The Finder window displaying the contents of your home directory is now the front Finder window again. The script accomplishes this by using the value of the index property of the last Finder window as the value for the index property of the front Finder window.

NOTE: When you change the value of the index property of a Finder window, you may change the index value of some of the open Finder windows behind it.

The Target Property

The value of the target property is a reference to the folder or disk whose contents are displayed in the Finder window. This value can be both read and changed. Let's examine both actions.

First, let’s get the value of the target property of the frontmost window:

Click to open example in the Script Editor applicationThe value of the target property of a Finder window is a reference to the folder whose contents are displayed in that window.
 

tell application "Finder" to get the target of the front window
--> returns: folder <name of your home directory> of folder "Users" of startup disk of application "Finder"

A script getting the value of the target property of a Finder window.

As you can see, the result of this script is a reference to the folder whose contents are displayed in the Finder window, in this case your home directory. This reference describes the target folder in terms of its position in its object hierarchy or where it is in its “Chain of Command.”

The returned object reference clearly shows, through the use of the possessive “of,” that the target folder is contained by the “Users” folder which is on the startup disk which is an element of the Finder application. You’ll use this hierarchical reference structure often in the scripts you write.

Next, we’ll change the targets of the open Finder windows. To change the value of a property, we’ll use the verb “set” in our scripts. Set is the verb or command used to change the value of a property.

Delete the previous script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationChanging the value of a Finder window’s target property will change the contents displayed in the window.
 

tell application "Finder" to ¬
 set the target of the front Finder window to the startup disk

You’ll notice that the frontmost Finder window now displays the contents of the startup disk:

The frontmost Finder window now displays the contents of the startup disk.

Now try this script:

Click to open example in the Script Editor applicationA script to set the target of the last Finder window.
 

tell application "Finder" to ¬
 set the target of the last Finder window to home

The second Finder window now displays the contents of your home directory:

The rear Finder window now displays the contents of the home directory.

In summary, the target property of a Finder window has a value that is a reference to a specific folder or disk whose contents are displayed within the Finder window. This value can be changed by using the verb “set” in conjunction with a reference to a new target folder. A reference describes an object in terms of its position in its object hierarchy, or in the case of a folder object, where it is on its parent disk.

Finder References

Since you'll often use object references in the scripts you write, here's a short overview of how to create an object reference for use with the Finder application.

First, in the front Finder window, navigate to your Documents folder in your Home directory. In the Documents folder, create a new folder named “Smith Project.” We’ll use this folder in the following examples.

To construct an object reference to a specific Finder disk item, simply start with the item to be referenced and list each folder or containing item of the object hierarchy until you've reached the disk containing the item.

For example, to create a Finder reference to the folder named “Smith Project” in the Documents folder in your Home directory, begin the Finder reference with the name of the referenced item preceded by a class identifier indicating the type of item it is, such as a “folder” or “document file.”

folder "Smith Project"

Next, you add the class identifier and name of the previous object’s parent or containing folder or object, preceded with the possessive “of” to indicate its ownership of the previous item.

folder "Smith Project" of folder "Documents"

Again, add the class identifier and name of the previous object’s parent or containing folder or object, preceded with the possessive “of” to indicate ownership.

folder "Smith Project" of folder "Documents" of ¬
 folder <name of your home directory>

This process will continue until we’ve reached the disk containing the referenced object:

folder "Smith Project" of folder "Documents" of ¬
 folder <name of your home directory> of ¬
 folder "Users" of disk "Macintosh HD"

Note the use of the class identifier “disk” for the disk object.

You’ve now constructed an object reference to the Finder item “Smith Project” located in the Documents folder in your Home directory.

Object references to Finder items can sometimes be very long. To shorten our example reference, and make it more generic and eaiser to write, we can optionally replace the section of the reference pertaining to your Home directory and it’s parent containers with the special Finder term “home,” mentioned earlier in this chapter:

folder "Smith Project" of folder "Documents" of home

This shorten version will function exactly as the longer reference.

If we wanted to use this object reference as the value for the target property, the script would be this:

tell application "Finder" to set the target of ¬
 the front Finder window to folder "Smith Project" of ¬
 folder "Documents" of home

Of course, this script will not work if there is no folder named “Smith Project” in the referenced location.

TIP: To view the object heirarchy of a Finder disk item, click on the title in its Finder window or its parent Finder window while holding down the Command key. Each segment in the object heirarchy will be listed on the popup menu.

Before we continue our tutorial, let’s reset the front Finder window back to displaying the contents of the startup disk by running this script:

Click to open example in the Script Editor applicationA script to make the frontmost Finder window display the contents of the startup disk.
 

tell application "Finder" to set the target of ¬
 the front Finder window to the startup disk

Quick Summary

That's a short explanation and demonstration of Finder disk item references. This topic is covered in great detail in a later chapter. For now, it is enough to understand that:

Scriptable objects are referenced by describing their object hierarchy or “Chain of Command.”

Now, let’s continue our overview of the properties of a Finder window.

The Toolbar Visible Property

In Mac OSX, Finder windows were redesigned for greater functionality and ease of use. One of the new window features is the Toolbar area located at the top of a Finder window. This area contains display, navigation, and action tools available in the Toolbar options sheet that appears when you’ve chosen “Customize Toolbar…” from the Finder’s View menu.

The toolbar visible property, introduced in Mac OSX version 10.3, has a value of true or false to indicate whether the Toolbar is visible on the targeted Finder window. If the value is true, then the Toolbar is visible. If the value is false, then the window displays without a Toolbar.

As a read/write property, meaning its value can be accessed and edited, the value of the toolbar visible property can be changed to toggle the display of a Finder window’s Toolbar. Try these scripts:

Click to open example in the Script Editor applicationScripts can show or hide a Finder window’s toolbar.
 

tell application "Finder" to  set toolbar visible of the front Finder window to false

A Finder window without a toolbar.

Click to open example in the Script Editor applicationA script to restore the toolbar to the frontmost Finder window.
 

tell application "Finder" to  set toolbar visible of the front Finder window to true

A Finder window with a toolbar.

Property values that are either true or false are called boolean values. You’ll see this term used throughout the rest of this book.
 

The Statusbar Visible Property

Introduced in Mac OS X version 10.4, the statusbar visible property determines whether a Finder window displays a status bar or not. Like the toolbar visible property, this property also has a value that is aboolean, in other words: true or false.

Since a statusbar is only visible when the toolbar is not shown, alter the previous script to set the toolbar visible property to false:

Click to open example in the Script Editor applicationA script to hide the front Finder window’s toolbar.
 

tell application "Finder" to set toolbar visible of  Finder window 1 to false

Now, write and execute this script:

Click to open example in the Script Editor applicationA script to show the Finder window’s status bar.
 

tell application "Finder" to set statusbar visible of  Finder window 1 to true

A Finder window without a toolbar but displaying a status bar below the title bar.

The Finder window now displays a status bar beneath the title bar.

Return the window to normal by setting the value of the toolbar visible property back to true:

Click to open example in the Script Editor applicationA script to restore the toolbar to the frontmost Finder window.
 

tell application "Finder" to set toolbar visible of  Finder window 1 to true

The Sidebar Width Property

Another Finder window property introduced in Mac OS X version 10.4 is the sidebar width property. The value of this property is an integer, indicating the width of the sidebar in pixels, and can be both read and changed.

Try this script that will set the sidebar width to 240 pixels:

Click to open example in the Script Editor applicationThe width of a Finder window’s sidebar can be set using a script.
 

tell application "Finder" to set the sidebar width of  Finder window 1 to 240

The sidebar width of the front Finder window has been set to 240 pixels.

Now, set the width of the sidebar in the second window:

Click to open example in the Script Editor applicationA script to set the value of the sidebar width property of a Finder window.
 

tell application "Finder" to set the sidebar width of  the second Finder window to 240

Both Finder windows have their sidebar width set to 240.

Now, set the sidebar width to the minimum value for both windows at the same time:

Click to open example in the Script Editor applicationA script to set the sidebar width of all open Finder windows simultaneously.
 

tell application "Finder" to set the sidebar width of  every Finder window to 0

NOTE: In Mac OS X v10.4 (Tiger), the sidebar could be completely closed by setting the value of the sidebar width to 0. In Mac OS X v10.5 (Leopard), the sidebar has a minimum width of 135. Any value less than 135 will be ignored and 135 used instead.

Note, you can even set the value of the sidebar width property of one window to match another window using a script like this:

tell application "Finder" to set the sidebar width of ¬
 Finder window 1 to the sidebar width of Finder window 2

 

 

The Current View Property

The next Finder window property we’ll examine is the current view property. The value of this property is the method used to display the contents of the Finder window, and can be one of four enumerations: icon viewlist viewcolumn view, and (new in Mac OS X v10.5) flow view. Like the target and toolbar visibleproperties, this property can be both read and edited:

Click to open example in the Script Editor applicationThe value of the current view property matches the view mode currently used by the Finder window.
 

tell application "Finder" to ¬
 get the current view of the front Finder window
 --> returns either: icon view, list view, flow view, or column view

Try these scripts and watch as the front Finder window changes its method of display:

Click to open example in the Script Editor applicationScripts to change the view mode of the frontmost Finder window.
 

tell application "Finder" to ¬
 set the current view of the front Finder window to list view

tell application "Finder" to ¬
 set the current view of the front Finder window to column view

tell application "Finder" to ¬
 set the current view of the front Finder window to flow view
 --> flow view is new in Mac OS X v10.5 (Leopard)

tell application "Finder" to ¬
 set the current view of the front Finder window to icon view

The flow view in Mac OS X v10.5 (Leopard)

Window management is an issue that most of us deal with on a daily basis. We’re often moving, resizing, and adjusting windows to facilitate the access and control of information. The current view property controls how the contents of Finder window are displayed. The next two properties pertain to the placement and sizing of Finder windows.

TIP: If you’re the kind of person who likes all folders to open in the same view mode, here’s a simple tell statement that will change the view display mode of every folder within an indicated folder, such as your home directory:

tell application "Finder" to set the current view of ¬
 the window of every folder of home to icon view

The Position Property

The value of the position property indicates where a Finder window is placed on the desktop. Its value is displayed as a list of two numbers describing the position of the top left corner of the Finder window in relation to the top left corner of the desktop display. The value of the position property can be both read and edited.

Delete the previous script from the script window, then enter, compile, and run the following script:

Click to open example in the Script Editor applicationA script to extract the position of the front Finder window.
 
 
tell application "Finder" to get the position of the front Finder window
--> returns a list of two numbers, similar to: {97, 364}

The result of the script is a list of two numbers describing the window’s position relative to the top left point of the desktop display.

In AppleScript, lists are enclosed in curly braces with each list item separated by a comma. Lists begin with the open brace “{” character and end with the close brace “}” character. AppleScript lists can contain any kind of information, such as text strings, numbers, references, or any combination of data types.

In a position list, the first list item is a number describing the horizontal distance in pixels from the left side of the desktop display. The second list item is a number describing the vertical distance in pixels from the top of the desktop display. Together, these two numbers describe the specific point on the screen where the top left of the window begins.

Let’s change the value of the position property of the front Finder window to move the window near the top left of the screen.

Delete the previous script from the script window, then enter, check, and run the following script:

Click to open example in the Script Editor application
 
tell application "Finder" to set the position of the front Finder window to {94, 134}

The front Finder window has been moved so that its top-left corner is now 94 pixels from the left side of the Desktop and 134 pixels from the top of the Desktop.

To move the window toward the right side of the Desktop, increase the horizontal offset by adding to the first value in the position list, as shown in this script:

Click to open example in the Script Editor application
 
tell application "Finder" to set the position of the front Finder window to {300, 134}

To move the window toward the bottom of the Desktop, increase the vertical offset by adding to the second value in the position list, as shown in this script:

Click to open example in the Script Editor application
 
tell application "Finder" to set the position of the front Finder window to {300, 240}

VERTICAL OFFSET EXCEPTION

Unlike most other scriptable applications that use the distance from the top of the screen to the top of a window to determine its vertical position, the Finder uses the distance from the top of the screen to just below the title bar of the window, thus adding the height of the title bar, an extra 22 pixels, to the measurement. This applies whether the Finder window is displaying its toolbar or not. This exception applies only to the Finder application.

In the figure below, the vertical offset of both Finder windows is 44, which consists of 22 pixels for the height of the Desktop’s menu bar plus 22 pixels for the height of the Finder window’s title bar, for a total vertical offset of 44 pixels. As shown, the tops of the two windows are located in the same position vertically, immediately below the bottom of the menu bar.



The Bounds Property

If you find yourself always resizing windows, you will probably write many scripts using the boundsproperty.

The value of the bounds property describes both the size and the position of the target window. This is accomplished by specifying two points: the top-left point of the window and the bottom-right point of the window. These two coordinates, combined into a four-item list, are used to outline the rectangular shape of the window.

Like the position property, the value of the bounds property can be read and edited. First, let’s get the bounds of the frontmost window using this script:

Click to open example in the Script Editor application
 
tell application "Finder" to get the bounds of the front window
--> returns something like: {72, 90, 512, 481}

The value of the bounds property is returned as a four-item list of integers representing the area of the window like this: {72, 90, 512, 481}

By changing the value of the bounds property, you can resize and reposition a Finder window anywhere on the Desktop. For example, the following script places the front Finder window near the top left of the Desktop and resizes it to 500 pixels in width and 300 pixels in height. Again, the verb set is used to change the value of the property.

Click to open example in the Script Editor application
tell application "Finder" to set the bounds of the front Finder window to {24, 96, 524, 396}

The Finder window is now repositioned to the top left of the Desktop and resized.

TIP: to set the size of a window to a specific size, such as 500 pixels wide by 300 pixels tall, add the value of the first bounds list item to the desired width to create the third bounds list item: {24, 96, (24 + 500), 396}. Do the same for the window height, and add the value of the second list item to the desired window height to create the fourth list item: {24, 96, 524, (96 + 300)}.

By the way, if you want to know the size of the current computer display, access the value of the bounds property for the Desktop window as shown in the following script. It returns the bounds of the entire Desktop, even if you have more than one monitor:

Click to open example in the Script Editor application
tell application "Finder" to get the bounds of the window of the desktop
--> returns: {0, 0, 1920, 1200}

The third item of the resulting bounds list is the desktop width, and the fourth item of the bounds list is the desktop height.


Verbs Used with Windows

In addition to properties, Finder windows respond to a specific set of verbs or commands. Some of these have been incorporated into our previous scripts:

get: used to access the current values of a window property
set: used to apply a new value to a window property
open: causes a window to display in the Finder
close: causes a window to close

With these commands we’ve been able to manipulate the size, position, and display of Finder windows. Now we’ll add another command for controlling windows to our vocabulary: select

Although the select verb can be applied to other scriptable objects, it can be used to make a window active so that it moves in front of any other open windows:

select: causes a window to come to the front

Delete the previous script from the script window, and then enter, compile, and the following script:

Click to open example in the Script Editor application
tell application "Finder" to select the last Finder window

The Finder window that was behind the front Finder window now moves to the front of the open windows.

NOTE: you could accomplish the same result by using the set verb to change the value of the indexproperty of the last Finder window:

Click to open example in the Script Editor application
tell application "Finder" to set the index of the last Finder window to 1

 

The Desktop Setup Script

Using all the properties and verbs we’ve covered so far, you now have the tools to create a script you can use to quickly return a cluttered Desktop to a default window configuration. Follow these steps for preparing the script.

First, set up the Desktop to what you want to be the finished state. For the purposes of this tutorial, follow the example shown in the figure below.

Close all the open Finder windows on your Desktop. Open two Finder windows and arrange them as shown in the following illustration. Note that the window on the left is displaying its toolbar, while the window on the right is not. Don’t worry about setting the target folders in each window; just set the shape and position of the two windows. Leave the window on the left selected as the frontmost window.

An example window arrangement for the Desktop Setup script.

NOTE: The display mode for the Documents folder in the Desktop Setup script example uses the flow view introduced in Mac OS X 10.5 (Leopard). If you are currently using an earlier version, substitute list view for flow view.

Next, use the follwoing scripts to extract the bounds of both windows, and write them down for later use in the Desktop Setup Script.

Click to open example in the Script Editor application
tell application "Finder" to get the bounds of Finder window 1
 --> returns something like: {36, 116, 511, 674}

Click to open example in the Script Editor application
tell application "Finder" to get the bounds of Finder window 2
 --> returns something like: {528, 116, 1016, 674}

 

The Tell Block

To set the Desktop window display to the arrangement you have set up, the following script performs a series of 12 commands that open and manipulate the two windows:

tell application "Finder" to close every window
tell application "Finder" to open home
tell application "Finder" to set toolbar visible of the front Finder window to true
tell application "Finder" to set the sidebar width of the front Finder window to 135
tell application "Finder" to set the current view of the front Finder window to column view
tell application "Finder" to set the bounds of the front Finder window to {36, 116, 511, 674}
tell application "Finder" to open folder "Documents" of home
tell application "Finder" to set toolbar visible of the front Finder window to false
tell application "Finder" to set statusbar visible of the front Finder window to true
tell application "Finder" to set the current view of the front Finder window to flow view
tell application "Finder" to set the bounds of the front Finder window to {528, 116, 1016, 674}
tell application "Finder" to select the last Finder window

Don’t bother entering this script in Script Editor. As you see, it is rather long, is very dense, and would take some effort to type into Script Editor. There’s an easier way to compose your scripts.

Notice that the script is a series of tell statements targeting the same application, namely, the Finder.

Instead of writing a group of 12 tell statements, each beginning with tell application "Finder" to, we’ll shorten the time it takes to write the script and make it easier to read by enclosing the commands within a single tell block.

tell block is used to target multiple actions at a single scriptable object, in this case the Finder application, which makes scripts easier to understand. You’ll always want to use a tell block in your scripts when addressing more than one action at one scriptable object.

tell block begins with the verb tell followed by a reference to a target object. The various actions to be performed by or to that object are then listed, each on its own line. After all the actions have been entered, the tell block ends with the closing statement end tell. All actions inside the tell block target the object referenced in the first line of the tell block.

Enter, compile, and run the following script as shown, except you may optionally substitute the windowbounds values you previously wrote down.

Click to open example in the Script Editor applicationThe individual script statements have been placed inside of a tell block targeting the Finder application.
 
tell application "Finder"
 close every window
 open home
 set toolbar visible of the front Finder window to true
 set the sidebar width of the front Finder window to 135
 set the current view of the front Finder window to column view
 set the bounds of the front Finder window to {36, 116, 511, 674}
 open folder "Documents" of home
 set toolbar visible of the front Finder window to false
 set the current view of the front Finder window to flow view
 set the bounds of front Finder window to {528, 116, 1016, 674}
 select the last Finder window
end tell

You should now see two Finder windows placed side by side on the Desktop, one in column view, the other in flow view, with your home directory the active window and your Documents folder displayed in the other window. Instant Desktop organization!

We’ll do more with this script in a moment, but first let’s return to the subject of tell blocks. A tell block is a much cleaner, more concise, and easier to read than a series of separate tell statements. Compare the previous script to the same script written as a series of tell statements (top of this page).

It is not only easier to write the script using a tell block, but you can clearly see the relationship between scriptable objects and the commands that target them, because of the indentations automatically placed in the script text by Script Editor when you compile the script. It’s very easy to see where a section of a script targeting a specific object begins (tell) and ends (end tell).

In summary, tell blocks are easy to use if you remember these simple rules:

  • If you begin a tell block, you must end a tell block with an end tell statement.
  • Commands within a tell block target the object addressed in the tell block’s opening statement.

Next we’ll examine to improve and save the Desktop Cleanup script.

Nested Tell Blocks

To further improve script readability and understanding, tell blocks can contain other tell blocks that target scriptable elements or objects belonging to the scriptable element or object targeted in the outermost tell block. For example, the Desktop Setup script can be rewritten so that the actions targeting the front window are enclosed within their own tell blocks within the outer Finder tell block, as shown in the following script:

Click to open example in the Script Editor applicationThe Desktop Setup script re-written to use nested tell blocks.
 
 
tell application "Finder"
 close every window
 open home
 tell the front Finder window
 set toolbar visible to true
 set the sidebar width to 135
 set the current view to column view
 set the bounds to {36, 116, 511, 674}
 end tell
 open folder "Documents" of home
 tell the front Finder window
 set toolbar visible to false
 set the current view to flow view
 set the bounds to {528, 116, 1016, 674}
 end tell
 select the last Finder window
end tell

The technique of placing tell blocks within other tell blocks is referred to as nesting tell blocks and is found quite often in scripts. And, since scripts are read from top to bottom and from left to right, the use of tell blocks makes it very easy to quickly see how a script is designed.

For example, the previous script starts with two commands to the Finder followed by four commands to the front Finder window followed by a single command to the Finder followed by four commands to the front Finder window again and then finishes with a single command to the Finder.

Since you’ll often edit your scripts later (perhaps a long time later), it’s important to write your scripts in a manner that is easy to understand and review. Using tell blocks and nested tell blocks in your scripts enables you to write scripts that are readable and that make sense to yourself and others. You can use as many nested tell blocks as you like in your scripts, just remember:

If you begin a tell block, you must end the tell block with an end tell statement.

If you entered the original version Desktop Setup script in the Script Editor, edit it now to match the version with the nested tell blocks. Be sure to remove the possessive phrase of the front Finder windowwhen you create the nested tell blocks. The function played by that phrase in defining the containment hierarchy of the front Finder window object is now played by the nested tell statement, tell the front Finder window.

Notice there are two nested tell blocks addressing the front Finder window in the Desktop Setup script. Why? Shouldn’t the second nested tell block be addressing the second Finder window?

No, when the second Finder window is opened, it automatically becomes the frontmost Finder window in the stack of open Finder windows. Therefore, it is now the front Finder window and can be targeted in the same manner as the previous window.

S

aving the Desktop Setup Script

Now back to our script. Since this script is a useful mechanism for resetting the Desktop display, let’s save the script as a script application, or applet, and install it in the Finder toolbar for easy accessibility from within any open Finder window.

Choose Save from Script Editor’s File menu. In the sheet, navigate to your home directory. Click the New Folder button, and create a new folder in the home folder named Toolbar Scripts.

Next, save the script as a self-running application named Setup by choosing Application from the File Format pop-up menu in the sheet. Do not select any of the Options check boxes at the bottom of the sheet. Click the Save button, and the new applet is saved in the newly created folder in your home folder.

The Script Editor Save sheet.

Now, in your home directory, open the Toolbar Scripts folder you just created. Drag the Setup script applet icon to the Finder window toolbar, and release the mouse once the cursor changes to include a plus sign (+).

Add items to a Finder window’s toolbar by dragging them onto the toolbar.

A script application in the Finder toolbar.

The script is now available from within any open Finder window. Anytime you want to return your Desktop to your default setup, just click the script icon in the toolbar!

Be sure to customize the properties of the Setup script to your preferences for open windows, view methods, and window sizes and positions.


Chapter Review

Congratulations, you’ve finished your initial foray into the world of AppleScript. You’ve learned what AppleScript is, how it works, and how to script the Finder application to control the display of Finder windows.

In addition to creating a useful script tool, you’ve learned these important AppleScript concepts:

  • On the computer, everything is an object.
  • On the computer, everything belongs to, is related to, is contained in, or is part of something else. For example, the Finder application contains windows and folders.
  • Scriptable objects are referred to by their positions in their object hierarchy or where they are in their “chain of command.” For example:
    file "cars.pdf" of folder "Documents" of folder "sal" of folder "Users" of startup disk
  • Scriptable objects have properties with values that can be read and sometimes manipulated. For example, a Finder window has nameposition, and bounds properties.
  • The AppleScript verb get is used to retrieve the value of a property, as in:
    get the name of the front window
  • The AppleScript verb set is used to alter the value of editable properties, as in:
    set the position of the front window to {0, 44}
  • Scripts are written using single-line tell statements or multiple-line tell blocks that target one or more actions at a scriptable object.
  • Textual content used in a script is placed within straight quotation marks ( " " ).
  • Lists in AppleScript begin with the opening brace character ( { ), contain items separated by commas, and end with a closing brace character ( } ).

Finder Window Properties

For reference, the following is a summary of the Finder window properties and commands used to create the Desktop Setup script. Review these items, keeping in mind that the principles you’ve learned here apply to all scriptable applications, not just the Finder.

READ-ONLY PROPERTIES

Read-only properties are properties whose corresponding values can be accessed or read only; they cannot be changed.

name: the text displayed in the title bar of the window
tell application "Finder" to get the name of the front window

EDITABLE PROPERTIES

Editable properties are properties whose corresponding values can be both read and changed.

index: an integer (whole number) indicating the position of the window in the stack of open windows
tell application "Finder" to get the index of the front window

bounds: a list of coordinates defining the top-left and bottom-right corners of a window
tell application "Finder" to set the bounds of Finder window 1 to {0, 44, 400, 300}

collapsed: a true or false value indicating whether the window has been minimized to the Dock
tell application "Finder" toset collapsed of every window to false

current view: the method currently used to display content in the window. Values for this property are one of the following: icon view, list view, column view, and, in Leopard, flow view
tell application "Finder" to set the current view of Finder window 1 to icon view

position: a list of coordinates indicating the horizontal and vertical offset of the window from the left and top sides of the screen
tell application "Finder" to set the position of the front Finder window to {0, 22}

target: a reference to the folder or directory whose contents are displayed in the window.
tell application "Finder" to set the target of the front Finder window to home

toolbar visible: (Mac OS X 10.3) a true or false value that indicates whether the Finder window displays a toolbar.
tell application "Finder" to set toolbar visible of the front Finder window to false

statusbar visible: (Mac OS X 10.4) a true or false value that indicates whether the Finder window displays a status bar. This works only when the toolbar is not visible.
tell application "Finder" to set statusbar visible of the front Finder window to false

sidebar width: (Mac OS X 10.4) an integer value that indicates the width of the Finder window’s sidebar in pixels. To close the sidebar in Mac OS X 10.4 (Tiger) without hiding the toolbar or the status bar, assign this property a value of 0. In Leopard, setting the sidebar width property to 0 reduces it to a width of 135 pixels.
tell application "Finder" to set the sidebar width of the front Finder window to 0

zoomed: a true or false value that indicates whether the window has been expanded.
tell application "Finder" to set zoomed of the front Finder window to true

Referring to a Finder Window

Finder windows, and other scriptable objects as well, can be referenced in a variety of ways:

by name:
Finder window "Documents"
by numeric index:
Finder window 1
by descriptive index:
the first Finder window
the second Finder window
the fifth Finder window
the 1st Finder window
the 23rd Finder window
by By position relative to other windows:
the front Finder window
the middle Finder window
the back Finder window
the last Finder window
the Finder window before the last Finder window
the Finder window after the first Finder window
by random index:
some Finder window

Verbs Used with Finder Windows

AppleScript verbs are the commands targeted at scriptable objects to retrieve or manipulate property values and to perform actions with the scriptable objects.

ACCESSING THE VALUES OF A WINDOW’S PROPERTY

get: used to access the current values of a window property.
tell application "Finder" to get the target of the front Finder window

CHANGING THE VALUES OF A WINDOW’S PROPERTY

set: used to apply a new value to a window property.
tell application "Finder" to set the target of the front Finder window to home

CONTROLLING WINDOWS

open: causes a window to become visible in the Finder
tell application "Finder" to open the Finder window of the startup disk
tell application "Finder" to open the startup disk

close: causes a window to close
tell application "Finder" to close every Finder window

select: causes a window to come to the front
tell application "Finder" to select the last Finder window

The Tell Statement

tell statement is a single AppleScript statement, beginning with the verb tell, that contains a reference to the target object and the action to be performed:

tell application "Finder" to set the target of the last Finder window to home

The target object in this example is the last Finder window displayed on the Desktop. The action to be performed is to change the contents of the window by altering the value of the window’s target property to be the user’s home directory.

The Tell Block

Use tell blocks to replace multiple tell statements and target multiple actions at a scriptable object or objects. All tell blocks begin with the verb tell followed by a reference to a target object or parent application. Statements defining the actions to be performed are placed after the opening line, with each statement getting its own line. The tell block is closed with the statement end tell.

tell application "Finder"
 set the target of the front Finder window to home
 set the current view of the front Finder window to icon
 set the position of the front Finder window to {0, 22}
end tell

tell blocks within other tell blocks are called nested tell blocks. When compiled, the hierarchy of the scriptable objects is revealed by the indentation applied to the formatted script text.

tell application "Finder"
 tell the front Finder window
 set the target to home
 set the current view to icon
 set the position to {0, 22}
 end tell
end tell