Advertisement
Automation

Launch Your Favorite Apps in Groups with AppleScript

by

This AppleScript tutorial will show you how to set up groups of apps that can be launched all at once. Along the way we'll learn how to implement lists, handlers, if statements and how to work with the results of a user's actions.

What We're Building

The basic idea here is that you probably have different groups of apps that you like to have open for different tasks, say for web design or writing. Wouldn't it be nice if you could easily open all of these apps at once as you go into different parts of your day?

We can accomplish this fairly easily with AppleScript. The algorithm here is only four steps long:

  1. Set up various app groups
  2. Allow the user to choose from a list of app groups
  3. Grab the result of the user's selection
  4. Use the result to launch a group of apps
applescript
Launch a group of apps with a single click!

From a user's perspective, you'll see a list of different application groups pop up on the screen (work, play, etc.). You'll choose the group that you want to launch, hit "OK" and they will all be launched for you. Pretty cool


Step 1. Set Up Groups

The first thing that we need to do is establish our various app groups. We'll be using three different groups for this tutorial: work, play and productivity, each of which contains its own list of apps.

Lists in AppleScript

In Applescript, a list is a lot like a variable, only it holds multiple distinct items instead of just one. A list containing the vowels of the English alphabet would look like this:

[applescript]
set vowelsList to {"a", "e", "i", "o", "u", "y"}
[/applescript]

From here, we can grab and work with individual list items. For instance, the following returns "e."

[applescript]
--Returns "e"
set vowelsList to {"a", "e", "i", "o", "u", "y"}
return item 2 of vowelsList
[/applescript]

Note that many programming languages are "zero indexed" so the first item in an array or list is actually item zero. This is not the case with AppleScript. The first item in a list is item one.

javascript vs. applescript
Notice how the two languages are indexed differently

Our Four Lists

For the first step, we're going to set up a total of four different lists. The first three will contain exact app names as they appear in OS X and the last will contain the three categories that we've divided our app groups into: Work, Play and Productivity.

[applescript]
--Set Groups
set workGroup to {"Mail", "Safari", "TextEdit"}
set playGroup to {"Safari", "App Store", "iTunes"}
set productivityGroup to {"Notes", "Reminders", "Mail"}
set appGroups to {"Work", "Play", "Productivity"}
[/applescript]

Here, the first line of code sets up a variable, which holds a list of application names: Mail, Safari and TextEdit. I repeat this process twice more for the other groups.

The last line of code repeats the same process, but this time fills the list with three essentially arbitrary group names that I made up: Work, Play and Productivity.

Coding is all about taking large amounts of information and placing it into easily manageable constructs.

The benefit of this step is that we've crammed a ton of information into four easily recalled variables. Coding is all about taking large amounts of information and placing it into easily manageable constructs. We'll see this on an even larger scale in the next step.

Tip: I used all default apps for my groups, but if you're not on Mountain Lion, you won't have Notes & Reminders. Change the apps in the list to those that you actually have installed.


Step 2. Create an App Launcher Handler

After setting up my variables, I like to move on to any handlers that need to be built.

In the previous step, we took several items and placed them into a list to be tied to a single variable. With a handler you do something similar an take an entire list of commands, actions, etc. and tie them into a variable.

As with Functions in other languages, handlers can be set up to accept a piece of information when they are called. This piece of information will then be "passed in" and used throughout the handler.

Which Actions Merit a Handler?

How can we know which actions should be declared by themselves and which should be wrapped up into a handler? The rule of thumb to live by is that if you find yourself repeating a sizable chunk of code more than once, it's probably time to set up a handler.

If you find yourself repeating a sizable chunk of code more than once, it's probably time to set up a handler.

Later in our script, we'll have a repeated need to launch all of the apps within a provided list. This is the perfect place to implement a handler. The syntax to set this up looks like this:

[applescript]
on appLauncher(selectedGroup)
end appLauncher
[/applescript]

As you can see, it's a little like a tell block, only it begins with the word "on" to indicate that it's a handler. Here "appLauncher" is simply the name that I've chosen for my handler. As with variables, always keep these simple and descriptive.

The next part of this line appears in parentheses: (selectedGroup). This is where we pass in a variable that can then be accessed and processed throughout the handler. In our case, when we use this handler later, we'll pass in one of our three app group lists.

applescript handler
The Anatomy of a Handler

The Full Handler

Now that we have a shell that defines the bounds of the handler, we can fill it with commands.

[applescript]
--App Launcher Handler
on appLauncher(selectedGroup)
repeat with i from 1 to (count of items in selectedGroup)
tell application (item i of selectedGroup)
activate
end tell
end repeat
end appLauncher
[/applescript]

First, I set up a repeat that goes through every item in whatever list we pass in, then I use each of these items as a variable to serve as the app name in a tell block. Finally, a simple "activate" command launches the apps in the list.


Step 3. Present the List to the User

Now that we have our variables declared and our handler set up, it's time to begin interacting with the user. What we're looking to do is create a dialog window that contains a list of options.

This sounds like it'll be a lot of work, but in reality it's super simple. We've already set up our appGroups list, now we just need a short line of code to tell AppleScript to present the list.

[applescript]
--Let the user select a group
set theSelection to choose from list appGroups with title "Which app group?"
[/applescript]

Here I used the "choose from list" command to bring up a standard built-in dialog and used "title" to assign some text at the top of the dialog.

applescript
The Choose From List Dialog

Getting the Result

Notice that we didn't merely tell AppleScript to give the user a list. We actually set the whole process up like a variable with the "set" command.

This is a short and sweet way to create a dialog and get the result all in a single step. The dialog will pop up, the user will choose an app group, and the result will be assigned to "theSelection" as a variable.


Step 4. Account for Cancels

Now comes the tricky part. The user has seen and interacted with the dialog and we have to process the result. To do this, we literally have to consider every possible scenario and account for it. Never assume that users will be logical or competent. Instead, assume that they'll take every possible route, especially those that are likely to cause an error.

Never assume that users will be logical or competent.

What Does a Cancel Look Like?

The first scenario that I'd like to account for is a cancellation. The window pops up, the user changes his/her mind, and presses cancel... now what?

In a previous step, we threw the result of the window into theSelection. If the user cancels, the value of this variable will be set to "false." This knowledge makes the scenario easy to handle with an if statement:

[applescript]
--If User Cancels
if theSelection is false then
error number -128
end if
[/applescript]

So what's this error number -128 business? AppleScript has a whole list of possible errors, each of which is assigned a unique number. It just so happens that "user cancelled" is -128.

All we're doing here is reporting what happened so that if you looked at the results of our script in Script Editor, you would see that the user cancelled the operation. As this action happens, the script terminates and disappears from the user's view, which is exactly what we want in this case, so this is as far as we'll go here.


Step 5. Determine Which Group was Selected

Now comes the big finish. If the user doesn't cancel the operation, then he/she must have selected one of our three groups. Our job is to find out which and act accordingly.

Fixing Our Variable

Before we launch into those three scenarios, we have to process our variable a little bit. When the user selects an item and hits "ok," we're actually assigning a list to theSelection (it only has one item, but it's a list nonetheless).

To fix this, simply override the variable as follows.

[applescript]
--If User Cancels
if theSelection is false then
error number -128
else
set theSelection to item 1 of theSelection
end if
[/applescript]

This seems a little weird, but if you don't do it, the script will throw an error, so be sure not to skip this step!

If The User Chooses the Work Group

Now that we've done that bit of housework, we can proceed to comparing the user result with the various possibilities. The first option is that the user chose the app group "Work."

In this case, the variable "theSelection" should be equal to the first item in our "appGroups" list (they'll both hold a value of "Work"). Let's set up another if statement to test the truth of the equality.

[applescript]
--If User Cancels
if theSelection is false then
error number -128
else
set theSelection to item 1 of theSelection

--If selection is workGroup
if theSelection = (item 1 of appGroups) then
appLauncher(workGroup)
end if
end if
[/applescript]

As you can see, if the statement proves true, then we're going to run our handler from before with "workGroup" passed in as the list that we want to work with.

At this point, our handler will count the number of items in workGroup, then repeat a tell block with an "activate" command for each of these items. This will cause Mail, Safari and TextEdit to launch successfully and the script will terminate.

applescript
How our if statement is structured to work with the handler.

Finishing Up

Using these same steps, we can finish up our script by adding in two "else if" statements that compare theSelection to the other two items in appGroups and launch our handler with the appropriate list as an input.

In each case, the handler will go through and launch the apps from the selected group.

[applescript]
--If User Cancels
if theSelection is false then
error number -128
else
set theSelection to item 1 of theSelection

--If selection is workGroup
if theSelection = (item 1 of appGroups) then
appLauncher(workGroup)

--If selection is playGroup
else if theSelection = (item 2 of appGroups) then
appLauncher(playGroup)

--If selection is productivityGroup
else if theSelection = (item 3 of appGroups) then
appLauncher(productivityGroup)
else
return
end if
end if
[/applescript]

Advanced User Tip: This is a lot of if statements to cram together. Can you rewrite this code using a repeat statement similar to what we used at the beginning?


Putting it All Together

Hopefully, we went through that slowly enough that you'll fully understand each piece of the script. Here's a look at the full script in one shot:

[applescript]
--Set Groups
set workGroup to {"Mail", "Safari", "TextEdit"}
set playGroup to {"Safari", "App Store", "iTunes"}
set productivityGroup to {"Notes", "Reminders", "Mail"}
set appGroups to {"Work", "Play", "Productivity"}

--App Launcher Handler
on appLauncher(selectedGroup)
repeat with i from 1 to (count of items in selectedGroup)
tell application (item i of selectedGroup)
activate
end tell
end repeat
end appLauncher

--Let the user select a group
set theSelection to choose from list appGroups with title "Which app group?"

--If User Cancels
if theSelection is false then
error number -128
else
set theSelection to item 1 of theSelection

--If selection is workGroup
if theSelection = (item 1 of appGroups) then
appLauncher(workGroup)

--If selection is playGroup
else if theSelection = (item 2 of appGroups) then
appLauncher(playGroup)

--If selection is productivityGroup
else if theSelection = (item 3 of appGroups) then
appLauncher(productivityGroup)
else
return
end if
end if
[/applescript]

Now that you have the full script, save it out as an application, give it a fancy icon and toss it in your dock.


Write Your Own!

If you successfully followed through this tutorial and understand all of the steps, congratulations! You're definitely a more than competent AppleScripter and it's time to branch out on your own and create some awesome scripts.

Leave a comment below and tell me about the scripts that you've built for your Mac. Also, if you have any other ideas for scripts that I should cover, let me know.

Related Posts
  • Computer Skills
    App Training
    Writing Destinations for DropzoneDropzone400
    Dropzone is not just another FTP upload client, but a great utilities platform for processing files and text. Dropzone is a collection of destinations that can have two types of actions: drag and drop action and/or a click action. There are a lot of pre-programmed destinations to use, but you can also write your own destinations in Ruby!Read More…
  • Computer Skills
    App Training
    Alfred Workflows for IntermediatesAlfred400
    Welcome back! Since you are reading this, you must have enjoyed the beginner's tutorial. Great! Now, let’s dig a little deeper by making a workflow that will help manage our Downloads folder, as well as a Projects Manager.Read More…
  • Computer Skills
    Office
    Intermediate Formulas in NumbersNumbers logo
    Put Numbers to work for you with functions, statements, and AppleScript that'll let you turn a simple spreadsheet into a powerful tool for your numbers and data.Read More…
  • Computer Skills
    Automation
    Effortless Paperless Nirvana With Mail, Hazel and EvernotePaperlessnirvana large
    With the relentless onslaught of the digital era, paperless systems have been gaining increasing traction and relevance. While the benefits are undeniable, there are times when workflows are far from frictionless and often tedious, making them less appealing. There is hope however and in this screencast I'll teach you how to leverage apps such as Mail, Hazel and Evernote to automate at least one aspect of your paperless workflow.Read More…
  • Computer Skills
    Automation
    Creating an AppleScript to Switch Between Multiple iTunes AccountsItunes account switch preview2x
    Introduction If you own an Apple device, you'll have an Apple ID which will also be your account for shopping in iTunes. Some Apple owners may have multiple Apple IDs: perhaps work, personal, for shared content with family members or even Apple IDs for iTunes stores in different countries. If you have multiple Apple IDs that you use with iTunes, you'll already be familiar with the hassle of changing accounts frequently and having to type the credentials each time. In this tutorial, I'll be showing you how create an AppleScript that enables easy switching, between all of your Apple IDs, with a single click inside iTunes.Read More…
  • Computer Skills
    Automation
    Save Time and Effort with AppleScript Repeat LoopsAsrepeatloops 5
    Continuing along in our ongoing series of AppleScript articles, today we're going to learn about the power of repeat loops, which can save you tons of effort by automating repeating tasks and groups of commands. After you learn to use repeats, you'll be able to significantly cut down on the amount of work it takes to automate tasks, which translates to faster, easier coding and higher productivity.Read More…