Section 5.2. Displaying Folders


5.2. Displaying Folders

When you're working on a bunch of related documents at once, you might want to jump quickly to their folder in the Finder. Normally, of course, you'd switch to the Finder and navigate through your hard drive to get to the correct folder. Or perhaps, if you're a power user, you've already put the folder in the Finder's Sidebar for easy access. Either way, though, you have to switch to the Finder and open a new window, which is a massive waste of time.

Why go through all those steps when you can get AppleScript to do it for you? Using AppleScript, you can save a folder-opening script as an application (Section 2.2.2) and place the script on the Dock for easy access. From then on, all you'll need to do is click the script's icon in the Dock, and a Finder window pops open and takes you right to the folder you want.

"But wait," you say, "I could just put the folder's icon on the Dock, no script required." You are, of course, correctand your method is what most people use for accessing commonly used folders. The trouble is, when you click a folder's icon on the Dock, you never know where the folder's window will open onscreen, or whether it'll be in List, Column, or Icon view. Plus, a folder icon on the Dock can open only one specific folder, whereas a script can open multiple folders at oncelike your Music and Pictures foldersas shown the following example:

tell application "Finder"     activate     open the folder "Users:yourUsername:Music"     open the folder "Users:yourUsername:Pictures" end tell

Again, just save this script as an application (Section 2.2.2), and then drag the script's icon to your Dock. From then on, you'll be just one click away from opening two folders at once.

Of course, if you have more than two folders you'd like to open simultaneously, you can insert extra open commands in the previous script for those folders as well.

5.2.1. Opening a Folder with AppleScript (Reprise)

As you've seen, there's more than one way to open a folder from AppleScript. If you want to open your Applications folder, for example, you'd have five separate choices:

tell application "Finder"     activate     make new Finder window to alias "Macintosh HD:Applications:" --Option 1     make new Finder window to POSIX file "/Applications/"        --Option 2     open alias "Macintosh HD:Applications:"                      --Option 3     open POSIX file "/Applications/"                             --Option 4     open the folder "Applications" of the startup disk           --Option 5 end tell

If you don't have any Finder windows open and you use one of these commands, the same thing would happen: a new Finder window would appear, taking you right to the Applications folder.

Gem in the Rough
AppleScript Shortcuts

After using AppleScript for a while, you might be wondering what exactly the word the does. The answer? Nothing. Using the in your scripts just makes them easier for humans to readit makes no difference to AppleScript. You can prove it to yourself by running this script, for example:

tell application "Finder"     open the the the folder "Applications" of startup disk end tell

The fact that you have three the's in a row makes no differenceAppleScript ignores them all.

That's not the only word you can omit in AppleScript, though. If you're writing a series of nested statements (like if , tell, or repeat) for commanding a program, you can omit the second half of the end commands, and AppleScript fills them in for you automatically when you compile the script. For instance, you could write this script:

(* This script creates a bunch of new folders in your Home folder; well, 15 of them  at least. *) tell application "Finder"     repeat 15 times         if (count every folder in home) ¬             is less than 15 then             make new folder at home         end     end end

When you compile or run this script (Section 2.1.1.3), the last three lines are automatically expanded to include the correct commands (end if, end repeat, and end tell). You can even shorten the word application to app (on the fourth line), and AppleScript expands it automatically.

Finally, you can replace the nerdy-sounding word of with the more English-like 's. For instance, the following script would work just as well as the one shown at the top of this sidebar:

tell application "Finder"     open the startup disk's folder ¬         "Applications"     (*Note the apostrophe-S instead of     the word "of"*) end tell


However, if you already have your Applications folder open, the commands behave differently:

  • Options 1 or 2 create new windows, each of which drops you off in the Applications folder. Option 1 employs the alias data type to do so, while Option 2 uses the new-age POSIX file data type. The make command, used in both Options, is described in detail on Section 4.5.1.

  • Options 3, 4, or 5 simply bring the existing Applications folder to the front, without opening a new Finder window. Option 3 uses the aforementioned alias type, Option 4 uses the POSIX file type, and Option 5 uses neither (it simply tells the Finder which disk to look in). That's how open works.

The difference between these approaches is pretty small, of course, but it's important to understand: the make command always creates a new copy of something (in this case, a window), while the open command opens a new copy only if one doesn't already exist.

5.2.2. Changing a Finder Window's View

Why stop with just opening a folder when you can change the Finder window's view, too? If you've been using Mac OS X for more than a few days, you probably already know that the Finder has three viewing options (available at the top of the View menu), each of which provides a different, potentially timesaving way of looking at your files:

  • Icon view shows you the icons for each item in a folder (Figure 5-1, top). That way, if you're browsing a folder full of Photoshop images, for example, you can find the particular image you want just by glancing at its icon.

  • List view organizes the items in a folder alphabetically, by the dates they were created, or by just about any other criterion you want (Figure 5-1, middle). As an added benefit, list view shows more files in the same space than Icon view does.

  • Column view gives you a hierarchical view of your hard drive, showing you the order of folders that contain the item you're looking at (Figure 5-1, bottom). This is the most compact way of looking through a folder, so it's worth using if you need to locate a file in a hurry.

But the fun doesn't stop there; each Finder view also has its own options. For example, you can change a window's background color from the default white to some other coloror post a picture behind a Finder window. Simply open the Finder's dictionary (Section 3.2.2) and navigate to the Finder window entry (Figure 5-2).

As you can see, there are several useful properties you can set for Finder windows. If you want your script to automatically open the Applications folder in Column view, for example, you could modify your script like this:

tell application "Finder"     activate     open the folder "Applications" of the startup disk     set the current view of the front Finder window to column view end tell

Now when you run your script, the Applications folder comes to the front and then quickly switches into Column view.

Figure 5-1. The three ways of looking at your Library Desktop Pictures folder. Top: Icon view (-1) shows only four items in a window this small, but their icons are quite large. Use this view if you have bad vision.Middle: List view (-2) shows nine items in a window this small, and lets you sort the items however you'd like. Click the Date Created column to sort your files and folders from newest to oldest, for example, or click the Size column to sort the items from biggest to smallest. (Click either column a second time to reverse the sorting order.) Bottom: Column view (-3) shows 10 items in a window this smallthe most of any of the three views. As a nice side effect, Column view also lets you see where the folder you're looking at is stored (in the left columns).


If you'd prefer, you can replace column view with icon view or list view to suit your file-viewing tastes.

Figure 5-2. In AppleScript, the properties of an object are all the attributes it has. Here you can see the properties of a Finder window: its current view, whether its toolbar is visible, and so on. Options marked with an [r/o] label are generally read onlythat is, you can ask AppleScript for their values, but you can't change them.


5.2.3. More Finder Window Settings

As you can see from the Finder's dictionary, there are a good number of extra properties you can set for Finder windows. You might have noticed with some puzzlement, however, that there's a big bold <Inheritance> label inside the entry for Finder window.

Your first instinct might be to assume that this property is off-limits to youafter all, it's got the [r/o] label, which usually means that you can't change the setting. As it turns out, however, inheritance is a powerful tool in AppleScript that puts even more control at your fingertips.

When you see the <Inheritance> label in a dictionary, look at the word immediately to its right. In the entry for Finder window, for instance, you'll see window next to <Inheritance>. That means that a Finder window, along with all its own properties, also has all the properties of a regular, everyday AppleScript window.

So what's that mean to you when you're up late at night writing scripts? It tells you to look in the dictionary entry for window in addition to the entry for Finder window (Figure 5-3), essentially doubling the number of commands you can send to a Finder window.

Armed with this information, you can add an extra command to your script:

tell application "Finder"     activate     open the folder "Applications" of the startup disk     set the current view of the front Finder window to column view     --Minimize the window to the Dock.     set the collapsed of the front Finder window to true end tell

Figure 5-3. Since Finder windows inherit from plain old windows, you should read the entry for window, too. You'll come across several additional properties you can control: where the window is onscreen (the position property), whether the window is big on the screen (the zoomed property), and even whether the window is minimized to the Dock (the collapsed property).


5.2.4. Working with More than One Window

The current script is great for showing your Applications folder, but it won't save you that much time; you can always just click once on the desktop and use a keyboard shortcut (Shift--A) to launch the Applications folder instead.

You really start saving time when your script opens more than one folder. That way, you can have a quick way to view your Applications, Documents, Music, and Movies folders, for exampleall with a single click.

Up to Speed
Inheritance

Inheritance is such a simple word. It means you get something for nothing, and when it comes to scripting, you can't get any better than that.

AppleScript's system of inheritance is pretty confusing at first, especially if you've never programmed before. The key to understanding it is seeing how similar it is to the real world, where some things have properties of others.

Say you have a Subaru. Now, your Subaru has properties that are different from most other cars: it uses four-wheel drive, for example. However, your Subaru also has properties in common with other cars: it has tires, a steering wheel, and brakes (you hope).

Think of it like this: your Subaru is a specific kind of car. In AppleScript, you'd explain the relationship like this: "Subaru inherits from car." Your Subaru has all the properties of a car, plus some extras of its own.

Keep in mind, however, that inheritance is a one-way street. While every Subaru has the properties of a generic car, not every generic car has the properties of a Subaru.

Now, applied to AppleScript, this whole scheme just means that an object can use all the properties of the object marked <Inheritance>, but not the other way around. That's why you can use the properties from a window in your script that controls a Finder window, but you wouldn't be able to use the properties from a Finder window in a script that controlled a generic window.


One approach to opening multiple folders from your script is to simply copy and paste the existing commands repeatedly. (Then you'd insert the names of the folders as appropriate.) Using this method, your final script would look something like this:

tell application "Finder"     activate     open the folder "Applications" of the startup disk     set the current view of the front Finder window to column view     set the collapsed of the front Finder window to true     open the folder "Documents" of home     set the current view of the front Finder window to column view     set the collapsed of the front Finder window to true     open the folder "Music" of home     set the current view of the front Finder window to column view     set the collapsed of the front Finder window to true     open the folder "Movies" of home     set the current view of the front Finder window to column view     set the collapsed of the front Finder window to true end tell

Power Users' Clinic
Moving a Window

Normally, moving a Finder window to a more convenient place on your screen is easy: you just drag any gray area of the window, and the rest of the window follows. This simple task, however, masks the fact that moving a window precisely where you want it is an exceptionally difficult task. In fact, getting a window to the exact top-left corner of your screenso you can see everything on the right side of your monitoris harder than writing a computer book.

That's why AppleScript's window-placing features are so convenient. By setting a window's position property, you can send the window anywhere on (or off) the screen. Here's how:

tell application "Finder"     activate     open the folder "Applications" ¬         of the startup disk     set the current view of the front ¬         window to column view Move the window where you want it:set the position of the front window ¬        to {200, 100} end tell

In that script, you place the Applications window 200 pixels from the left edge of the screen and 100 pixels from the top edge of the screena good position if you want to leave room for additional windows at the bottom of your screen.

Keep in mind when writing scripts like this, however, that the menu bar is 83 pixels tall. Also, a Finder window needs a 5 pixel "barrier" from the left edge of the screen, so you can see the entire window. Therefore, if you wanted to place a window at exactly the top-left pixel on the screen, you would have to substitute the following command in the bold part of the previous script:

set the position of the front window ¬     to {5, 83}

For a more detailed explanation of Mac OS X's odd window-positioning system, see Sidebar 6.3.


This kind of approach, unfortunately, has several downsides:

  • It repeats a lot of commands. That means your script is longer than it has to be, which can become a problem if you start writing scripts that are hundreds of lines long.

  • It's annoying to use. Each time you paste the commands again, you have to go back and change the portion of the command that needs modifying. Again, if you're working with a long script, this can be quite a nuisance.

  • If you want to change a command, you have to change it in multiple places. For instance, if you wanted to change column view to list view, you'd have to do it four times.

Luckily, there's a solution to these problems: breaking the redundant commands into a separate portion of your script, known as a subroutine.

5.2.5. Subroutines

In AppleScript (and in other programming languages), a subroutine is a section of code that's meant to be used over and over again. Rather than having to retype a big block of code, a subroutine lets you write that code just once, assign a name to the code, and then simply use the subroutine's name whenever you want to run the corresponding code. Think of it like using a kitchen appliance: no matter what time of day it is, you can expect the "coffeemaker" appliance to behave the same way. Similarly, no matter what part of your script you run a subroutine from, you can expect the subroutine to run the exact same lines of code.

You can do anything you want in a subroutine: tally the points from a sports game, connect to a Web site, or anything else you're likely to do more than once in your script. (And incidentally, subroutines are sometimes called handlers, too.)

Now that you know what subroutines can do, it's time to put them to use in simplifying your Finder window script.

5.2.5.1 Defining a subroutine

In general, a subroutine looks something like this:

on subroutineName( <any variables being passed into the subroutine> )     --Any commands you want in the subroutine go here end subroutineName

You'll notice that, unlike repeat, if, and tell statements, subroutines begin with the keyword on. That's your way of telling AppleScript, "Hey! There's a subroutine here, and whenever I refer to this name, please run the lines of code that follow."

Some people use the word to instead of on to introduce their subroutines. Either way is valid.

5.2.5.2 Running a subroutine

Calling a subroutine from your script couldn't be easier. (Calling is just geek-speak for "running the code contained in a subroutine.") You simply type the name of the subroutine, followed by parentheses, like this:

subroutineName( <any variables you want to pass into the subroutine> )

On the other hand, if your code is inside a tell statement, you have to preface your subroutine with the word my. That's your way of telling AppleScript, "I know I'm targeting a particular program with my script, but take a break for a second and run my personal subroutine, will ya?"

5.2.5.3 Variables in subroutines

When defining a subroutine, you don't have to put anything between the parentheses on the subroutine's first line. If you do choose to put variable names there, however, you'll need to use the same number of values when you call the subroutine from your script.

In other words, if you defined your subroutine like this:

on displayGreater(a, b) --Note that there are two variables     if a > b then         set theResult to a     else         set theResult to b     end if     display dialog "The greater number is: " & theResult end displayGreater

you'd have to run the subroutine from your code like this:

displayGreater(10, 88) --You must provide two values

On the other hand, your subroutines don't have to accept variables at all. AppleScript is perfectly happy to run a subroutine defined like this, for example:

on displayPi( )     display dialog pi end displayPi

In that case, since the subroutine doesn't expect any values (indicated by the lack of variables between its parentheses), you'd run this subroutine with this simple command:

displayPi( ) --Display a dialog box showing pi

pi is a special AppleScript keyword, a namesake of the famous irrational number.

5.2.5.4 Writing the appropriate subroutine

Now that you know how to write and call subroutines, you can eliminate the redundant portions of your Finder-window script. First, add this subroutine to the bottom of that script:

on columnAndMinimize( )     tell application "Finder"         set the current view of the front Finder window to column view         set the collapsed of the front Finder window to true     end tell end columnAndMinimize

In writing this subroutine, you've isolated your script's redundant code. Now you can erase your script's redundant code by calling the columnAndMinimize subroutine as follows:

tell application "Finder"     activate     open the folder "Applications" of the startup disk     my columnAndMinimize( )     open the folder "Documents" of home     my columnAndMinimize( )     open the folder "Music" of home     my columnAndMinimize( )     open the folder "Movies" of home     my columnAndMinimize( ) end tell --Here's the subroutine: on columnAndMinimize ( )     tell application "Finder"         set the current view of the front Finder window to column view         set the collapsed of the front Finder window to true     end tell end columnAndMinimize

Remember, you must use the word my before these subroutine-running commands because you're using those commands inside a tell statement.

Now, with this final script, you've not only saved several lines of code, but you've also made it easier to change your script's behavior in the future. If you ever want to modify the code now, it's simply a matter of modifying the subroutine once, rather than modifying four separate lines. Here are a few possible tweaks:

  • To keep all your newly opened windows from minimizing, delete set the collapsed of the front Finder window to true from your subroutine.

  • If you'd rather your new windows appear in List view or Icon view (Section 5.2.2), replace column view with either list view or icon view in your subroutine.

  • Finally, if you don't care what view your new windows use, just delete the entire set the current view of the front Finder window to [whatever] line from your subroutine.



AppleScript. The Missing Manual
AppleScript: The Missing Manual
ISBN: 0596008503
EAN: 2147483647
Year: 2003
Pages: 150

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net