Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Introduction

Introduction

The AppleScript language evolved from a revolutionary language called HyperTalk, which was developed in 1987 by Bill Atkinson. HyperTalk, which was part of the programming environment called HyperCard, allowed you to write English-like sentences to accomplish your tasks. Several commercial applications, most notably the popular game Myst, were developed in HyperCard. However, due to various marketing decisions, HyperCard and HyperTalk never gained widespread popularity and support.

Like HyperTalk, AppleScript remained a language embraced by a relatively small circle of enthusiasts. With the surge in popularity of Mac OS X, a powerful operating system based on UNIX, came a surge in the popularity of AppleScript. This was partly due to the fact that more and more applications became scriptable, meaning you could talk to them from an AppleScript program. AppleScript was also found to be well suited for automating repetitive tasks in the workplace, a process known as workflow automation. Finally, AppleScript's growth in popularity was partly owed to Apple's recognition and adoption of AppleScript as a key technology component in Mac OS X.

AppleScript is called a scripting language. Scripting languages are programming languages designed primarily to control or coordinate the operation of other programs. Examples of other popular scripting languages include JavaScript, Perl, Ruby, VBScript, the UNIX shell, and Python.

On your Mac, a scripting language might ask the Safari browser to display a particular web page. Or it might ask iTunes to play a particular song. Scripting languages are also often used to coordinate the transfer of data between multiple applications to accomplish a task. So a script might contain code to go to the website for some data, put it into an Excel spreadsheet, and then email the spreadsheet to your boss.

In the past, scripting languages were not well suited for accomplishing general-purpose programming tasks because they either lacked sufficient programming capabilities or were simply too inefficient. However, the line between a scripting language and a general purpose programming language has become blurred over the years. In some situations, AppleScript can work just fine as a way to implement a solution to a general programming problem.

0.1. Who This Book Is For

This book is a tutorial on the AppleScript language. Most of the existing books on AppleScript concentrate on its use in the workplace for workflow automation. However, AppleScript is a great language for the hobbyist and computer enthusiast to learn, and those groups are the intended audience for this book. Instead of focusing on how to use AppleScript to format data for an Excel spreadsheet, edit some images in PhotoShop, or create a document with FrameMaker, this book shows how easy it is to use AppleScript to control some of the fun applications on your system. As a result, the programs in this book show you how do things like write a simple alarm clock program, create a simple iTunes player, or take a folder of images and make a DVD slide show.

That's not to say that programmers who intend to use AppleScript for workflow automation should not read this book. This book teaches you what you need to know to get started and how to write your scripts. However, be forewarned: you will be having some fun along the way!

0.2. How This Book Is Structured

As I just noted, the purpose of this book is to teach you how to write programs in AppleScript. It is designed to appeal to both the novice and experienced programmer alike and assumes no prior programming experience. Readers with prior programming experience will find that AppleScript has a unique way of doing things that most likely differs significantly from any other programming language you have used.

The approach taken in this text is to teach by example, using small, well-chosen, complete programming examples. These are presented using the Wrox trademark "Try It Out" format. By typing each example, running it, and examining the results, you gain experience with the entire process of entering, running, and debugging programs. Experience has shown that this hands-on approach is one of the most effective ways to learn.

You will find that most of the programs in this book illustrate a specific concept, such as how to write a loop, how to get a list of files, and so on. These examples are not designed for industrial use. That is, they do not avoid all possible errors in all possible situations. In many cases, that would make the programs too hard to follow. However, defensive programming is taught in the text, and an entire chapter is devoted to error handling.

At the end of each chapter, you will find exercises. To gain maximum benefit from this book, I strongly suggest that you work through each exercise before proceeding to the next chapter. Not only will this help to solidify the concepts presented in the chapter, but also it will help prepare you for the material covered in the following chapter. Answers to the exercises are supplied in Appendix A, but I urge you to first try solving the problems on your own before you consult the appendix.

Here's a rundown of what you'll find in the each chapter:

In Chapter 1, "Writing You First AppleScript Program," you waste no time getting started. Right off the bat, I show you how to start up the Script Editor application, type in a program, and run the program to see your results. The chapter then shows you how to write a program that puts up a simple dialog using the display dialog command. You use this command extensively throughout the book.

Chapter 2, "Variables, Classes, and Expressions," covers some of the more mundane aspects of the language, but these are concepts you need to learn to master the language. In this chapter, you learn the rules for forming variable names, writing arithmetic expressions, and working with many of AppleScript's built-in classes. One unique aspect of AppleScript is its support for a built-in date class, which allows you to easily work with dates in your programs.

In Chapter 3, "Making Decisions," you learn how to use the if statement to make comparisons and affect the flow of control in your program based on the result of your comparisons. In this chapter, you also learn how to get input from the user.

Chapter 4, "Program Looping," covers the many forms of AppleScript's repeat statement. This is the fundamental statement for repeatedly executing a group of statements. You see how to write a simple guessing game program that allows a user to try to guess a number between 1 and 10 that has been randomly selected by your program.

In Chapter 5, "Working with Strings," I show you how to work with character strings. You learn how to get elements such as characters and words from a string, how to get the length of a string, and how to compare two strings.

Chapter 6 is titled "Working with Lists and Records." List and Records are the fundamental data structures supported in AppleScript. This chapter shows you how to use them effectively in your programs, how to access elements from them, and how to form more complex data structures such as lists containing lists and lists containing records.

In Chapter 7, "Working with Files," you learn about file name paths and POSIX paths. The chapter shows you how to use AppleScript's built-in commands to open a file, read data from it, and write data to it. You also learn how to get information about a file, such as its size, its modification date, and its type. The chapter shows how to use commands to allow a user to choose a file or a folder on the system and how you can enumerate the contents of a folder in your program.

A handler is AppleScript's equivalent of a function or subroutine in other languages. In Chapter 8, "Handlers," this topic is covered in detail. You learn the different ways you can write a handler, how to pass arguments to and return values from a handler, and the differences between local and global variables. In this chapter, you also develop a set of handlers for performing common operations with lists.

Sometimes errors can occur in your program at unexpected times and in unexpected places. In Chapter 9, "Error Handling," you learn how to plan for such events and how to intelligently handle them when they occur. You learn how AppleScript provides a mechanism so that you can "catch" an error when it occurs and handle it accordingly.

Because AppleScript is a scripting language, it was designed to enable you to easily communicate with other applications. This is done primarily through a feature of the language called the tell statement. In Chapter 10, "Working with Applications," you learn how to use this statement in detail. The Finder is the primary application illustrated in this chapter. You learn how to ask the Finder to do things that you can't handle directly in AppleScript, such as renaming, moving, or deleting a file. The chapter also shows you how to write a droplet, which is an application that gets executed whenever someone drops files onto its icon.

Chapter 11, "Scripting iLife Applications," provides the most fun of any chapter in the book! iLife is a suite of applications that includes iTunes, iPhoto, iDVD, iMovie, and GarageBand. Of these five applications, only the first three were scriptable as of the writing of this book. In this chapter, you develop a simple application that allows you to prompt the user for a song title and then ask iTunes to play it. The iPhoto example shows you how to create a new album in your photo library from a folder of image files. Finally, The iDVD example shows you how to write an AppleScript program to create a DVD slide show presentation from a folder of images.

Chapter 12, "Script Objects," goes into detail about script objects, showing you how to store them in a file and subsequently load them into your programs. You also learn how defining a script object inside a handler allows you to write programs that are consistent with an object-oriented programming (OOP) style.

Chapter 13, "Loose Ends," serves the purpose implied by its name: to tie up some loose ends. Topics covered in this chapter are those that are either of a more advanced nature or did not fit neatly into the structure of earlier chapters. These include web services, the Script Menu, GUI scripting, and recording scripts.

Chapter 14 is the last chapter in the book and is titled "Introducing AppleScript Studio." AppleScript Studio was released with the Panther version of Mac OS X (v. 10.3). AppleScript Studio, makes the bridge between AppleScript and GUI applications. With AppleScript Studio, you can develop a sophisticated user interface and have AppleScript as the underlying code to respond to events like the clicking of a button or the movement of a slider. Chapter 14 is an introduction to AppleScript Studio and guides you through the steps involved in creating a simple application.

There are also three appendices provided in this book: Appendix A, "Exercise Answers," provides solutions for the exercises presented in the text. Appendix B, "Language Reference," provides a quick reference to AppleScript's operators and commands. Appendix C, "Resources," contains a list of resources and places you can look for more information about AppleScript and some of the tools mentioned in the text.

0.3. What You Need to Use This Book

This book covers the latest version of AppleScript. At the time of this writing, the latest version was 1.9.3. You use a separate program to enter and run AppleScript programs. On the Mac, Script Editor is the primary tool used for such purposes. The version of Script Editor I cover in this book is 2.0. There are other third-party script editors available for use with AppleScript, including Smile and Script Debugger. These are mentioned throughout the text but are not covered in detail.

The chapter covering scripting iLife applications was developed using the following versions: iTunes v4.6, iPhoto v4.0.3, and iDVD v4.0.1. The iLife suite comes preinstalled on many Mac systems. Alternatively, you can buy iLife from Apple's website. iTunes is also available for no charge from that website if you don't want to purchase the entire iLife suite.

The chapter on AppleScript Studio is based on version 1.5 of Xcode. The latest version of Xcode can be obtained at no charge from Apple's website. You just need to register there as an online developer, again, at no cost to you.

Although AppleScript is a fairly stable programming language that has not changed much, it is widely recommended that you use the latest versions of the software with this book. In that way, you are assured that the features used in the examples are supported by the applications being used.

All the programs in this book were tested on my Titanium PowerBook G4 running Mac OS X version 10.3.5. Compatibility with earlier versions of OS X or the applications cited previously is not guaranteed.

0.4. Conventions

To help you get the most from the text and keep track of what's happening, we've used a number of conventions throughout the book.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles used in the text

  • We highlight important words when we introduce them

  • We show keyboard strokes like this: Ctrl-A

  • We show file and folder names, URLs, and code within the text in a special monofont typeface, like this: persistence.properties

  • We present code in two different ways:

    In code examples we highlight new and important code with a gray background.
    
    					  

    The gray highlighting is not used for code that is less important in the present context or has been shown before.
    
    					  

0.5. Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or use the source code files that accompany the book. All of the source code used in this book is available for download at http://www.wrox.com. Once at the site, simply locate the book's title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book's detail page to obtain all the source code for the book.

Because many books have similar titles, you may find it easiest to search by ISBN; for this book the ISBN is 0-7645-7400-0.

After you download the code, just decompress it with your favorite compression tool. Alternatively, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

0.6. Errata

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration; at the same time, you are helping us provide higher quality information.

To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the Book Search Results page, click the Errata link at the bottom of the book entry. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book's errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don't spot "your" error on the book's Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We'll check the information and, if appropriate, post a message to the book's errata page and fix the problem in subsequent editions of the book.

0.7. p2p.wrox.com

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

  1. Go to p2p.wrox.com and click the Register link.

  2. Read the terms of use and click Agree.

  3. Complete the required information to join as well as any optional information you want to provide and click Submit.

  4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P but in order to post your own messages, you must join.

After you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.