AppleScript Studio® Programming for the Absolute Beginner
JERRY LEE FORD, JR.
© 2007 Thomson Course Technology, a di...
183 downloads
2488 Views
10MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
AppleScript Studio® Programming for the Absolute Beginner
JERRY LEE FORD, JR.
© 2007 Thomson Course Technology, a division of Thomson Learning Inc. All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system without written permission from Thomson Course Technology PTR, except for the inclusion of brief quotations in a review. The Thomson Course Technology PTR logo and related trade dress are trademarks of Thomson Course Technology, a division of Thomson Learning Inc., and may not be used without written permission.
Publisher and General Manager, Thomson Course Technology PTR: Stacy L. Hiquet Associate Director of Marketing: Sarah O’Donnell Manager of Editorial Services: Heather Talbot Marketing Manager: Mark Hughes
AppleScript, AppleScript Studio, Finder, iTunes, Mac OS, and Xcode are trademarks of Apple Computer, Inc., registered in the U.S. and other countries.
Acquisitions Editor: Mitzi Koontz
All other trademarks are the property of their respective owners.
Marketing Coordinator: Adena Flitt
Important: Thomson Course Technology PTR cannot provide software support. Please contact the appropriate software manufacturer’s technical support line or Web site for assistance.
Project Editor: Jenny Davidson
Thomson Course Technology PTR and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer. Information contained in this book has been obtained by Thomson Course Technology PTR from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, Thomson Course Technology PTR, or others, the Publisher does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from use of such information. Readers should be particularly aware of the fact that the Internet is an ever-changing entity. Some facts may have changed since this book went to press. Educational facilities, companies, and organizations interested in multiple copies or licensing of this book should contact the Publisher for quantity discount information. Training manuals, CD-ROMs, and portions of this book are also available individually or can be tailored for specific needs. ISBN-10: 1-59863-303-1 ISBN-13: 978-1-59863-303-0 eISBN-10: 1-59863-781-9 Library of Congress Catalog Card Number: 2006904399 Printed in the United States of America 07 08 09 10 11 PH 10 9 8 7 6 5 4 3 2 1
Thomson Course Technology PTR, a division of Thomson Learning Inc. 25 Thomson Place Boston, MA 02210 http://www.courseptr.com
Technical Reviewer: John Flynt PTR Editorial Services Coordinator: Erin Johnson Interior Layout Tech: Digital Publishing Solutions Cover Designer: Mike Tanamachi Indexer: Larry Sweazy Proofreader: Gene Redding
To my wonderful children, Alexander, William, and Molly, and my beautiful wife, Mary.
ACKNOWLEDGMENTS his book represents the hard work and effort of many individuals. I would like to thank Mitzi Koontz,, this book’s acquisitions editor. Thanks also go out to John Flynt, who served as the book’s technical editor. I’d be remiss if I did not thank Jenny Davidson for lending her considerable talents as both project and copy editor. Finally, I’d like to thank everyone else at Thomson Course Technology for all their contributions and hard work.
T
ABOUT THE AUTHOR erry Lee Ford, Jr. is an author, educator, and an IT professional with over 17 years of experience in information technology, including roles as an automation analyst, technical manager, technical support analyst, automation engineer, and security analyst. Jerry has a master’s degree in Business Administration from Virginia Commonwealth University in Richmond, Virginia. He is the author of 18 books and co-author of 2 additional books. His published works include Beginning REALbasic, Perl Programming for the Absolute Beginner, Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner, VBScript Professional Projects, Microsoft Windows Shell Scripting and WSH Administrator’s Guide, Learn VBScript in a Weekend, Microsoft Windows Shell Scripting for the Absolute Beginner, Learn JavaScript in a Weekend, and Microsoft Windows XP Professional Administrator’s Guide. He has over five years’ experience as an adjunct instructor teaching networking courses in Information Technology. Jerry lives in Richmond, Virginia, with his wife, Mary, and their children William, Alexander, and Molly.
J
Table of Contents
Introduction........................................................... xii Why AppleScript Studio?................................................................................................. xiii Who Should Read This Book?.......................................................................................... xiv What You Need to Begin.................................................................................................... xv How This Book Is Organized............................................................................................ xvi Conventions Used in This Book...................................................................................... xix
Part I
Introducing AppleScript Studio...............................1
Chapter 1
AppleScript Studio Basics.........................................3 Project Preview: The Knock-Knock Application............................................................. 4 Introducing AppleScript Studio......................................................................................... 6 A Little AppleScript Studio History .......................................................................... 6 A Quick Overview of AppleScript Studio Components ....................................... 6 A Few Words About Object-Oriented Programming..................................................... 8 AppleScript: AppleScript Studio’s Programming Language....................................... 9 When to Write AppleScript ...................................................................................... 11 When to Develop AppleScript Studio Applications ........................................... 11 Working with the Script Editor............................................................................... 12 Accessing Application Dictionaries........................................................................ 15 Back to the Knock-Knock Application............................................................................ 17 Designing the Game ................................................................................................... 18 Step 1: Creating a New AppleScript Studio Application................................... 19 Step 2: Creating a Graphical User Interface......................................................... 21 Step 3: Modifying Control Attributes and Attaching Controls to Event Handlers......................................................................................................................... 25 Step 4: Editing Your AppleScript............................................................................. 28 Step 5: Building and Running Your Mac OS X Application.............................. 30 Summary................................................................................................................................ 30
vi
AppleScript Studio Programming for the Absolute Beginner
Chapter 2
The AppleScript Studio Application Development Environment............................................................. 31 Project Preview: The AppleScript Studio Fortune Teller Game............................... 32 Project Templates................................................................................................................ 33 Setting Xcode Preferences................................................................................................. 36 Working with the Xcode Project Window.................................................................... 37 The Project Window Toolbar.................................................................................... 38 Groups & Files .............................................................................................................. 38 The Project Windows Detail View........................................................................... 40 The Editor Window..................................................................................................... 41 The Info Window......................................................................................................... 46 Integration with the Interface Builder.......................................................................... 48 The Terminology Browser.................................................................................................. 48 Debugging Capabilities...................................................................................................... 49 The Apple Developer Reference Library......................................................................... 50 Back to the AppleScript Studio Fortune Teller Game................................................ 51 Designing the AppleScript Studio Fortune Teller Game .................................. 51 Step 1: Creating a New Project................................................................................. 52 Step 2: Creating the User Interface......................................................................... 52 Step 3: Attaching Controls to Event Handlers..................................................... 55 Step 4: Adding a Little Programming Logic ......................................................... 56 Step 5: Testing the Execution of the AppleScript Studio Fortune Teller Application.................................................................................................................... 57 Summary................................................................................................................................ 58
Chapter 3
Building a Graphical User Interface................... 59 Project Preview: The Typo-Matic Typing Test Game................................................... 60 Create Graphical User Interfaces..................................................................................... 63 Cocoa Controls ............................................................................................................. 65 MainMenu.nib .............................................................................................................. 67 MainMenu.nib – MainMenu ..................................................................................... 67 Window.......................................................................................................................... 68 Cocoa Interface Elements.................................................................................................. 68 Cocoa Menus................................................................................................................. 68 Cocoa Controls and Indicators ................................................................................ 74 Cocoa Text Controls.................................................................................................... 80 Cocoa Windows............................................................................................................ 83 Cocoa Data Views ........................................................................................................ 93 Cocoa Container Views .............................................................................................. 94 Back to the Typo-Matic Typing Test Game.................................................................... 95 Designing the Game ................................................................................................... 95 Step 1: Creating a New Project................................................................................. 96
Contents
vii
Step 2: Creating the User Interface......................................................................... 96 Step 3: Customizing Menus and Control Attributes, and Associating Controls with Event Handlers.................................................................................. 97 Step 4: Adding a Little Programming Logic ....................................................... 100 Step 5: Testing the Execution of the Typo-matic Typing Test Game Application.................................................................................................................. 104 Summary.............................................................................................................................. 105
Part II
Learning How to Write AppleScripts..................107
Chapter 4
Working with Values, Variables, and Classes. 109 Project Preview: The Star Trek Trivia Game............................................................... 109 AppleScript—The Technology......................................................................................... 112 AppleScript—The Scripting Language.......................................................................... 112 Language Extensibility............................................................................................. 112 Language Features .................................................................................................... 113 Managing Data Using Variables..................................................................................... 116 Storing Values in Variables..................................................................................... 116 Retrieving Variable Values...................................................................................... 117 Naming Variables.............................................................................................................. 118 Case Sensitivity .......................................................................................................... 119 Undefined Variables ................................................................................................. 120 Working with Different Variable Classes.................................................................... 121 The String Class ......................................................................................................... 121 The Real Class ............................................................................................................. 121 The Integer Class ....................................................................................................... 121 The Date Class ............................................................................................................ 122 The Boolean Class...................................................................................................... 124 Back to the Star Trek Trivia Game................................................................................ 124 Designing the Game ................................................................................................. 124 Step 1: Creating a New Project............................................................................... 125 Step 2: Creating the User Interface....................................................................... 125 Step 3: Customizing Control Properties.............................................................. 128 Step 4: Adding a Little Programming Logic ....................................................... 129 Step 5: Testing the Execution of the Star Trek Trivia Game .......................... 138 Application Code Review......................................................................................... 139 Summary.............................................................................................................................. 142
viii
AppleScript Studio Programming for the Absolute Beginner
Chapter 5
Applying Conditional Logic and Building Loops........................................................................ 145 Project Preview: The Guess a Number Game............................................................. 146 Implementing Conditional Logic.................................................................................. 149 The if Statement ........................................................................................................ 149 The if…else Statement .............................................................................................. 150 The if…else if Statement .......................................................................................... 151 Nested if Statements ................................................................................................ 152 Different Types of Comparisons.................................................................................... 153 Building Compound Tests............................................................................................... 154 Iterative Processing........................................................................................................... 155 Creating an Endless Loop ........................................................................................ 156 Iterating a Set Number of Times ........................................................................... 157 Looping While a Condition Proves true .............................................................. 157 Looping Until a Condition Proves false............................................................... 158 Controlling Loop Execution with a Counter...................................................... 159 Processing List Contents.......................................................................................... 159 Back to the Guess a Number Game............................................................................... 160 Step 1: Creating a New Project............................................................................... 160 Step 2: Creating the User Interface....................................................................... 161 Step 3: Customizing Control Properties.............................................................. 163 Step 4: Adding a Little Programming Logic ....................................................... 165 Step 5: Testing the Execution of the Guess a Number Game ........................ 171 Summary.............................................................................................................................. 171
Chapter 6
Working with Strings, Lists, and Records......... 173 Project Preview: Alexander’s Tall Tale......................................................................... 174 Manipulating Strings........................................................................................................ 176 Assigning Strings to Variables ............................................................................... 176 Getting Information About a String .................................................................... 176 Concatenating Strings ............................................................................................. 177 Controlling String Format ...................................................................................... 177 Advanced Comparisons ........................................................................................... 178 Working with Characters, Words, and Paragraphs ......................................... 180 Defining and Accessing Lists.......................................................................................... 181 Working with Lists.................................................................................................... 181 Retrieving Elements from a List............................................................................ 182 Making Changes to Lists.......................................................................................... 183 Storing and Retrieving Data Using Records............................................................... 184 Creating and Accessing Records............................................................................ 184 Modifying Record Property Values ....................................................................... 185 Working with a List of Records ............................................................................. 185
Contents
ix
Back to Alexander’s Tall Tale.......................................................................................... 186 Step 1: Creating a New Project............................................................................... 187 Step 2: Creating the User Interface....................................................................... 187 Step 3: Customizing Control Properties.............................................................. 188 Step 4: Adding a Little Program Code .................................................................. 191 Step 5: Testing the Execution of Alexander’s Tall Tale Game ....................... 195 Summary.............................................................................................................................. 195
Chapter 7
Organizing Scripts with Handlers..................... 197 Project Preview: The Rock, Paper, Scissors Game...................................................... 198 Working with Event Handlers....................................................................................... 200 Creating Custom Event Handlers ......................................................................... 201 Defining and Calling Handlers.............................................................................. 201 Passing Arguments to Handlers ............................................................................ 202 Returning a Result from an Event Handler ....................................................... 204 Understanding Scope....................................................................................................... 205 Local Scope .................................................................................................................. 205 Global Scope ............................................................................................................... 206 Back to the Rock, Paper, Scissors Game....................................................................... 208 Step 1: Creating a New Project............................................................................... 209 Step 2: Creating the User Interface....................................................................... 209 Step 3: Customizing Control Properties.............................................................. 211 Step 4: Adding a Little Programming Logic ....................................................... 212 Step 5: Testing the Execution of the Rock, Paper, Scissors Game ................ 220 Summary.............................................................................................................................. 221
Part III
Advanced Topics.....................................................223
Chapter 8
Working with Files and Folders......................... 225 Project Preview: The Slot Machine Game.................................................................... 225 Mac and POSIX Paths........................................................................................................ 228 Full and Relative Paths..................................................................................................... 230 Establishing a File Reference.......................................................................................... 231 Working with Text Files................................................................................................... 233 Accessing Files and Folders..................................................................................... 233 Reading from and Writing to Files....................................................................... 234 Creating Small Database Files........................................................................................ 238 Creating and Saving the Database File................................................................ 238 Retrieving and Accessing Database Records ...................................................... 239 Back to the Slot Machine Game..................................................................................... 242 Step 1: Creating a New Project............................................................................... 243
x
AppleScript Studio Programming for the Absolute Beginner
Step 2: Creating the User Interface....................................................................... 243 Step 3: Customizing Control Properties.............................................................. 244 Step 4: Adding a Little Programming Logic ....................................................... 245 Step 5: Testing the Execution of the Slot Machine Game .............................. 253 Summary.............................................................................................................................. 253
Chapter 9
Controlling Other Applications........................ 255 Project Preview: The Tic-Tac-Toe Game........................................................................ 256 Automating Mac OS X Applications............................................................................. 258 Accessing Application Terminology............................................................................. 258 Application Dictionaries ......................................................................................... 259 Using tell to Direct Messages to Application Targets ...................................... 261 Automating Mac OS X Applications............................................................................. 261 TextEdit........................................................................................................................ 261 Finder............................................................................................................................ 263 iTunes ........................................................................................................................... 263 Terminal ...................................................................................................................... 264 DVD ............................................................................................................................... 264 Address Book .............................................................................................................. 265 Safari............................................................................................................................. 265 Mail ............................................................................................................................... 266 System Events............................................................................................................. 266 Help Viewer................................................................................................................. 267 Back to the Tic-Tac-Toe Game......................................................................................... 268 Step 1: Creating a New Project............................................................................... 268 Step 2: Creating the User Interface....................................................................... 268 Step 3: Customizing Control Properties.............................................................. 269 Step 4: Adding a Little Programming Logic ....................................................... 273 Step 5: Testing the Execution of the Tic-Tac-Toe Game................................... 283 Summary.............................................................................................................................. 283
Chapter 10
Debugging and Error Handling......................... 285 Project Preview: The Poker Dice Game........................................................................ 286 Finding Ways of Handling Errors.................................................................................. 289 Different Types of Errors................................................................................................. 290 Syntax Errors .............................................................................................................. 290 Logical Errors.............................................................................................................. 291 Runtime Errors .......................................................................................................... 291 Handling Errors.................................................................................................................. 292 Using the try Statement to Catch Errors............................................................. 292 Catching Specific Types of Errors.......................................................................... 295 Keeping a Watchful Eye on Your AppleScript Studio Applications..................... 296
Contents
xi
Writing Output to the Log ...................................................................................... 296 Displaying Useful Information in Popup Dialogs ............................................ 297 Using Sound to Indicate When Key Events Occur ............................................ 298 Reviewing Error Messages....................................................................................... 298 Debugging Your AppleScript Studio Applications................................................... 300 Running Your AppleScript Studio Applications in the Debugger ............... 300 Setting Breakpoints .................................................................................................. 302 Controlling Statement Execution......................................................................... 303 Back to the Poker Dice Game.......................................................................................... 304 Step 1: Creating a New Project............................................................................... 304 Step 2: Creating the Game’s Windows ................................................................ 304 Step 3: Customizing Control Properties.............................................................. 307 Step 4: Adding a Little Programming Logic ....................................................... 311 Step 5: Testing the Execution of the Poker Dice Game ................................... 321 Summary.............................................................................................................................. 321
Part IV
Appendices...............................................................323
Appendix A
What’s on the Companion Website?.................... 325 The Book’s Source Code................................................................................................... 326
Appendix B
What Next?............................................................. 327 Recommended Reading................................................................................................... 327 Locating AppleScript Studio Resources Online......................................................... 329 Apple’s AppleScript Studio Web Pages ................................................................ 329 Apple’s AppleScript Web Pages.............................................................................. 330 MacScripter.net.......................................................................................................... 331 Cocoa Dev Central ..................................................................................................... 332 AppleScript Studio Mailing Lists................................................................................... 333 Apple’s Applescript-Studio Mailing List .............................................................. 333 Apple’s Applescript-implementors Mailing List................................................ 334 Apple’s Applescript-users Mailing List................................................................. 335 MacScripter’s AppleScript Studio and Xcode Mailing List ............................. 336 Yahoo! Groups: AppleScript Mailing List ............................................................ 337 The AppleScript Studio – How to Mailing List................................................... 338
Glossary..................................................................341 Index..........................................................................351
INTRODUCTION elcome to AppleScript Studio Programming for the Absolute Beginner. AppleScript Studio is a collection of tools that work together to create a powerful application development environment that supports the development of native Mac OS X applications. AppleScript Studio supports the creation of graphical desktop applications using the AppleScript scripting language to provide the underlying program code. AppleScript is an English-like scripting language that provides the ability to interact with the Mac OS X operating system and to control the execution of desktop applications.
W
AppleScript is a popular scripting language that is native to Mac OS X. It comes preinstalled and ready to run. Apple users, hobbyists, and programmers have used it for many years to develop scripts that automate tasks by developing workflows that control multiple applications in order to perform specific tasks. AppleScript is especially useful for automating tasks that you find yourself performing repeatedly. For example, you might use AppleScript to automate the process of moving downloaded image files from your digital camera to a particular folder, changing the file type of each image to .gif or .jpeg, and then using your preferred photo manager application to print them. AppleScript provides minimal support for interaction with users, limited to a small collection of popup dialogs. AppleScript Studio fills this gap by providing you with all the tools necessary to build a graphical user interface or GUI for your AppleScripts. AppleScript Studio lets you build full-featured, user-friendly desktop applications using AppleScript instead of more complicated programming languages like C or Objective-C. Your AppleScript Studio applications can include buttons, text boxes, sliders, and just about any other graphical element that is found on even the most advanced Mac OS X application. In short, AppleScript Studio significantly simplifies the process of developing desktop applications that run on Mac OS X, making it a perfect programming language for first-time programmers and hobbyists, while at the same time providing professional programmers with a powerful tool that rivals other high-powered programming languages. This book is focused on teaching you everything that you need to know to begin developing your own AppleScript Studio applications. This includes instruction on learning how to program using AppleScript. In addition, you will also learn
Introduction
xiii
about other technologies that AppleScript Studio taps into in order to enable application development.
WHY APPLESCRIPT STUDIO? ppleScript Studio is a free application development tool provided by Apple. AppleScript Studio does more than simply allow you to develop graphical user interfaces for AppleScripts. AppleScript Studio is actually a suite of programming tools that work together to provide a powerful application development environment. These tools include:
A
• AppleScript. The scripting language used to develop the programming logic that drives AppleScript Studio applications. • Xcode. A program editor that provides sophisticated editing and script debugging capabilities as well as easy access to online AppleScript Studio documentation. • Interface Builder. A tool that provides everything needed to easily and quickly add windows to your AppleScript Studio applications and then customize them by adding buttons, text controls, sliders, image controls, menus, and a host of other graphical elements. • The Cocoa Application Framework. A behind the scenes technology that provides AppleScript Studio applications with numerous built-in features. These features include the ability to use controls found in the Interface Builder without having to develop the program code that makes windows maximize and minimize or that makes interface controls operate as you would expect. AppleScript Studio provides Mac users and programmers with the ability to develop graphical applications that interact with users via the mouse and keyboard. Because these applications use AppleScript as the underlying scripting language, it takes less time to learn how to develop applications using AppleScript Studio than it does with other Mac OS X programming languages. Its simplicity, combined with the English-like syntax of the AppleScript language, makes AppleScript Studio a perfect place to start for first-time programmers and hobbyists. However, professional programmers can benefit from AppleScript Studio as well. AppleScript Studio provides everything that is needed to quickly create prototype applications and demonstrate proof of concept before investing the time required to build an application using another
xiv
AppleScript Studio Programming for the Absolute Beginner
programming language. Professional programmers will find that AppleScript Studio applications can be developed in a fraction of the time that it might take to create the same application in different programming languages such as C or Objective-C. In short, anyone who aspires to develop applications that run on Mac OS X, can benefit from learning AppleScript Studio. It can be used to add a GUI to any existing AppleScript and to develop entirely new applications from scratch. It is a perfect tool for developing time-saving applications that automate repetitive tasks. Not only will it help you to work more quickly, but it can eliminate the errors that inevitably occur when humans are forced to perform mundane tasks, especially those tasks that are repeated time and time again. As you will see as you work your way through this book, AppleScript Studio and the AppleScript scripting language are both easy and fun to learn, although they may take you many years to fully master. If your operating system of choice is Mac OS X, AppleScript Studio is a perfect programming environment in which to begin learning application development. In addition, all of the programming techniques that you learn while mastering AppleScript and AppleScript Studio will provide you with a strong jumping-off point from which you can begin learning other programming languages. This book will teach you how to write computer games using AppleScript to build AppleScript Studio applications. However, AppleScript Studio applications can tackle just about any challenge, large and small, simple or complex.
WHO SHOULD READ THIS BOOK? designed this book to teach you how to work with AppleScript Studio and to help you become an effective programmer. No assumption is made regarding your previous programming experience, although prior programming experience is admittedly helpful. It is expected that you have access to a computer running Mac OS X and that you have a working familiarity with that operating system and the applications that come with it, such as Finder and TextEdit.
I
This book’s unique approach of teaching through the development of computer games helps make it a lot more fun and enjoyable than most other computer books. First-time programmers and Mac hobbyists will find this book’s systematic building block approach to learning how to program especially helpful. You will find that the programming skills that you develop
Introduction
xv
by mastering AppleScript Studio will lend themselves well to other programming languages that you may later want to learn. Professional programmers can also benefit from reading this book by using it as a jumpstart guide. This includes programmers who might be interested in learning another programming language as well as those who are looking to expand their skill set to include application development on Mac OS X.
WHAT YOU NEED TO BEGIN ppleScript Studio runs on computers with Mac OS X 10.1.2 or higher. When writing this book, I worked on a computer running Mac OS X 10.4. Therefore, all of the examples that you will see demonstrated will be run on that version of Mac OS X, although in most cases the examples should also run just as well on any version of Mac OS X after 10.1.2. A big portion of this book focuses on learning how to create AppleScripts. Fortunately, AppleScript ships as a standard component on Mac OS X, as does the Script Editor, which is a custom-built code editor designed specifically for AppleScript.
A
In addition to a computer running an appropriate version of Mac OS X, you also need to make sure that Xcode is installed on your computer. As of the writing of this book, the current version of Xcode was 2.3. AppleScript Studio is automatically installed along with Xcode, as are other resources that are needed for you to start developing AppleScript Studio applications. To determine if Xcode is already installed on your computer, look for it in the /Developer/Applications folder. If it is present, then Xcode is installed on your computer. If Xcode is not installed, you can download it from http://developer.apple.com/tools/download/ and then install it like any other Mac OS X application. Apple distributes Xcode for free. However, before you can download and install it, you must first join the Apple Developer Connection or ADC, which you can do at http://developer.apple.com/membership/.
xvi
AppleScript Studio Programming for the Absolute Beginner
HOW THIS BOOK IS ORGANIZED s I wrote this book, I did so with the intention that it be read from cover to cover. However, if you have previous programming experience, you may want to begin by reading the first three chapters in order to grasp the high-level fundamentals of AppleScript Studio application development and then begin jumping around to the particular topics that suit you. However, unless you are particularly adept at learning new programming language statements and syntax on sight or unless you already know how to program using AppleScript, you probably will be better off reading Chapters 4–7. These chapters cover the basics of AppleScript programming, before you begin exploring other parts of the book.
A
AppleScript Studio Programming for the Absolute Beginner is organized into four parts. Part I consists of three chapters that are designed to provide you with an introduction to AppleScript Studio, its application development environment, and the steps involved in building graphical application interfaces. Part II is made up of four chapters that focus on providing you with an overview of AppleScript and the programming statements that make up that scripting language. This material includes coverage of how to work with and store data, apply conditional programming logic, create loops to process large amounts of data or perform repetitive tasks, as well as how to store and manipulate data in a list and organize scripts using handlers. Part III consists of three additional chapters that cover advanced topics, including how to work with files, folders, and disk drives; how to control other applications; and how to locate and fix programming errors. Finally, Part IV is made up of two appendices and a glossary. The appendices provide you with information about the content stored on the book’s companion website and additional learning resources that you may want to look into as you continue your AppleScript Studio education. The glossary contains a listing of terms used throughout the book. A detailed outline of the material covered in this book is provided below. • Chapter 1, “AppleScript Studio Basics”. This chapter provides you with an overview of AppleScript Studio. This includes a review of each of the major development tools that make up AppleScript Studio. You will learn steps involved in creating and running AppleScripts. You will also learn how to build your first AppleScript Studio application, complete with a graphical user interface. Finally, you will learn how to write your first AppleScript Studio game.
Introduction
xvii
• Chapter 2, “The AppleScript Studio Application Development Environment”. This chapter provides a thorough review of AppleScript Studio’s application development environment, Xcode. You will learn how to add, edit, and execute AppleScript code. In addition, you will learn how to navigate Xcode’s menus and toolbar and to work with numerous editor features. You will also learn how to use Xcode to access application dictionaries in order to learn how to automate Mac OS X applications and create workflows. • Chapter 3, “Building a Graphical User Interface”. This chapter reviews the graphical elements supported by AppleScript Studio that you can use when developing the graphical user interfaces for your applications. You will learn how to add interface elements such as buttons, text boxes, and slider controls. You will also learn how to move, resize, and configure these controls and to connect these interface controls to AppleScripts in order to programmatically interact with and control them. • Chapter 4, “Working with Values, Variables, and Classes”. This chapter shows you how to store and reference data using variables. You will learn how to work with different types of data, including strings, numbers, and dates, and how to interact with and manipulate different types of data classes. You will also learn how to convert data from one data type to another and to build mathematical expressions. You will learn about AppleScript operators and the order in which they are applied to mathematic operations. • Chapter 5, “Applying Conditional Logic and Building Loops”. This chapter teaches you how to use conditional logic to create AppleScripts that behave differently based on the data they are provided. You will learn how to evaluate different types of values, including string, numeric, and Boolean data. This chapter also provides you with instruction on how to set up loops in order to perform repetitive operations or to process large amounts of information. • Chapter 6, “Working with Strings, Lists, and Records”. In this chapter, you learn more about how to work with strings, including how to manipulate string contents and to keep track of string elements. This chapter teaches you how to store groups of related data in lists and to access and process this data efficiently. You will also learn how to store data in records, including learning how to define and record contents. • Chapter 7, “Organizing Scripts with Handlers”. This chapter shows you how to improve the overall organization of your scripts using handlers. This includes learning how to call on handlers for execution and how to pass optional arguments to handlers for processing. You also learn how to write handlers that can return data back to the statements that call them. Handlers also have an impact on variable access and this chapter will show you how to control local and global variable scope using handlers.
xviii
AppleScript Studio Programming for the Absolute Beginner
• Chapter 8, “Working with Files and Folders”. The primary focus of this chapter is to teach you how to programmatically interact with and control files, folders, and disks. This will include learning how to create and open files, as well as learning how to read and write to and from these resources. You will also learn how to retrieve file information and to access folders and disk drives. • Chapter 9, “Controlling Other Applications”. This chapter teaches you how to create AppleScripts that control the execution of other applications such as Finder and TextEdit. This will enable you to create automation workflows that tie the actions of multiple applications together into a single process. You will learn how to work with application dictionaries in order to determine which commands applications are designed to work with. • Chapter 10, “Debugging and Error Handling”. This chapter teaches you how to track down and fix errors that may occur when you attempt to compile your AppleScript studio applications. The material covered includes the remediation of syntax and logical errors. You will also learn how to use Xcode’s debugger and to set breakpoints in order to pause application execution and to examine variable values and logical program flow. • Appendix A, “What’s on the Companion Website?”. This appendix provides a review of the materials that you will find on the book’s companion website. This material includes copies of all the AppleScript Studio game applications that are developed in this book. In addition, you will find links to shareware application editors that you may want to explore. • Appendix B, “What Next?”. This appendix provides you with ideas and tips for furthering your AppleScript Studio education. It includes pointers to additional reading material and a list of links to AppleScript and AppleScript Studio websites that I have found particularly helpful and informative. • Glossary. This unit provides a glossary of terms used throughout the book.
Introduction
xix
CONVENTIONS USED IN THIS BOOK
T
o help streamline the presentation of this book and to make your learning experience as enjoyable as possible, I have implemented a number of helpful conventions to improve the overall organization and presentation of the material in this book. These conventions are described below.
HIN
TRA
TRI
As you read along, I will provide suggestions and point out different ways of doing things to help make you a better and more efficient AppleScript Studio programmer.
T
P
CK
Whenever possible, I will try to point out areas where mistakes are sometimes likely to occur and provide you with advice on how to avoid these types of situations.
Whenever possible, I will provide you with shortcuts and programming tips that can help you to work faster and more efficiently.
IN THE REAL WORLD In addition to teaching you the basics of AppleScript Studio programming, I will pause at various places in the book to explain how certain programming techniques can be applied to specific real-world situations.
xx
AppleScript Studio Programming for the Absolute Beginner
CHALLENGES I will close out each chapter by teaching you how to create a new computer game. I will then wrap things up by providing you with a series of suggestions that you can follow up on in order to enhance and improve the chapter’s game project and to further advance your programming skills.
Part
I
Introducing AppleScript Studio
Chapter 1
AppleScript Studio Basics
Chapter 2
The AppleScript Studio Application Development Environment
Chapter 3
Building a Graphical User Interface
This page intentionally left blank
1
C H A P T E R
APPLESCRIPT STUDIO BASICS ppleScript Studio is an application development environment that supports the development of applications on Mac OS X 10.1.2 or higher. AppleScript Studio leverages the capabilities of a number of Apple technologies, including AppleScript, the Cocoa framework, Xcode, and the Interface Builder. In doing so, it provides both novice and professional programmers with the ability to develop graphical applications that can run natively on Mac OS X. This chapter will introduce you to AppleScript Studio and provide a high-level review of its key components. This chapter will also provide you with a brief introduction to AppleScript, the programming language that drives AppleScript Studio applications.
A
Specifically, you will learn • How the technologies used by AppleScript Studio work together to provide a powerful application development environment • How to use the Script Editor to create AppleScripts • How to use Xcode and the Interface Builder to create AppleScript Studio applications
4
AppleScript Studio Programming for the Absolute Beginner
PROJECT PREVIEW: THE KNOCK-KNOCK APPLICATION In this chapter and in each chapter that follows, you will learn how to create a computer game using AppleScript Studio. I hope you will find that learning through game development is both fun and effective. In this chapter, you will learn how to use AppleScript Studio to create the Knock-Knock game. When first started, the Knock-Knock game displays the window shown in Figure 1.1 and waits for the user to click on the Tell Joke button.
FIGURE 1.1 The user begins the Knock-Knock game by clicking on the Tell Joke button.
Once the user clicks on the Tell Joke button, the popup dialog shown in Figure 1.2 is displayed, prompting the user to respond to the Knock-Knock! prompt.
FIGURE 1.2 To continue, the user must click on OK.
Rather than force the user to type in the phrase “Who is there?”, the application automatically provides the required response as the default entry for the popup dialog, requiring only that the user click on the OK button to submit it. If the user clicks on the Cancel button, the popup dialog closes, leaving the application’s opening window still visible. This allows the user to start over or to close the Knock-Knock application. If the user changes the default response to something other than “Who is there?” and then clicks on the OK button, the error message shown in Figure 1.3 is displayed. Assuming that the user leaves the default response alone and clicks on the OK button, the popup dialog shown in Figure 1.4 is displayed, prompting the user to respond to the game’s next query.
Chapter 1 • AppleScript Studio Basics
5
FIGURE 1.3 The Knock-Knock game only accepts specific user input.
FIGURE 1.4 The user helps to set up the game’s punch line by asking “Orange Who?”.
Again, if the user clicks on the Cancel button, the popup dialog is closed, leaving only the game’s main window visible. If the user alters the default response and clicks on the OK button, the error message shown in Figure 1.5 is displayed. FIGURE 1.5 To continue game play, the user must submit the default response by clicking on the OK button.
Assuming that the user clicks on the OK button without altering the default response, the popup dialog shown in Figure 1.6 is displayed, showing the game’s punch line.
FIGURE 1.6 Finally, the game delivers the punch line for its joke.
6
AppleScript Studio Programming for the Absolute Beginner
By the time you have finished creating the Knock-Knock application, you will have learned the five basic steps required to create an AppleScript Studio application and will be ready to tackle more complex challenges.
INTRODUCING APPLESCRIPT STUDIO AppleScript Studio provides you with the ability to create native Mac OS X applications that include full-featured graphical user interfaces that can interact with and control other Mac OS X applications and parts of the Mac OS X operating system. AppleScript Studio applications use AppleScript as the programming language for driving application execution, making it much easier to master than other programming language environments available on the Mac OS X.
A Little AppleScript Studio History AppleScript Studio first appeared in December 2001 when it was released as version 1.0. This version of AppleScript Studio ran on Mac OS X 10.1.2. A few months later, Apple released AppleScript Studio version 1.1. A second version 1 update occurred in mid-2002 when Apple updated AppleScript to version 1.2 and made it available for execution on Mac OS X 10.2. The next update to AppleScript Studio occurred in December 2002 (version 1.2.1), which was made available for Mac OS X 10.2.3. The next update of AppleScript Studio, version 1.3, occurred in 2003 when Apple released Mac OS X 10.3. Finally, in 2005 Apple released AppleScript Studio 1.4 along with Mac OS X 10.4. This remains the current version of AppleScript Studio. During its short lifespan, AppleScript Studio has remained relatively unchanged. As a result, when Mac OS X 10.5 (Leopard) is released, it is unlikely that you will find any significant differences in AppleScript Studio. Therefore, the knowledge you pick up from this book is likely to remain current and serve you well for many years to come.
A Quick Overview of AppleScript Studio Components AppleScript Studio consists of a number of different application development technologies, including AppleScript, Xcode, the Cocoa framework, and the Interface Builder. Each of these technologies is reviewed briefly in the sections that follow and will be covered more fully throughout the remainder of this book.
AppleScript AppleScript is a scripting language supplied as part of Max OS X. If you are a long-time Mac user, then AppleScript is almost certainly going to be the easiest new programming language for you to learn. Not only is it more English-like than any other programming language
Chapter 1 • AppleScript Studio Basics
7
available on Mac OS X, it is also a lot friendlier. For example, AppleScript does away with a lot of syntactical requirements required by other programming languages, such as the addition of semicolons at the end of every statement and the bombardment of brackets, curly braces, and parentheses throughout program code. While capable of serving as a general purpose scripting language, AppleScript is primarily designed as a scripting language to be used in the creation of automated workflows, which control the operating system and other applications. By providing you with the ability to create workflows that leverage the best features of different applications, AppleScript lets you develop scripts that surpass the capabilities of any individual application. TIP
AppleScript grew out of a scripting language known as HyperTalk, which was created by Bill Atkinson in the late 1980s. HyperTalk was known for its Englishlike syntax. Its primary purpose was to facilitate the development of simple automated tasks.
Although AppleScript runs on earlier generations of the Mac operating systems, this book limits its coverage to Mac OS X. The primary reason for this limitation is that the focus of this book is on using AppleScript to support AppleScript Studio programming, and AppleScript Studio only runs on Mac OS X 10.1.2 or higher. Still, most of what you will learn about AppleScript in this book can be directly applied to earlier versions of Mac operating systems. TIP
AppleScript is just one of many scripting languages that are available on Mac OS X. These other scripting languages include Perl, Python, JavaScript, Ruby, and Unix Shell scripting. For Mac users, AppleScript is the easiest of these scripting languages to learn. Each of these scripting languages has its own particular set of strengths and weaknesses. However, when it comes to the automation of other applications, AppleScript really shines, and of course, AppleScript Studio is specifically designed to work with AppleScript.
Xcode Xcode is an application development tool that provides editing and debugging capabilities for your AppleScript Studio applications. In addition, Xcode also provides direct access to application dictionaries, making it easy for you to search for and find the commands used to automate and control individual applications. TRI
CK
Xcode is going to be the tool you will use to begin the development of new AppleScript Studio applications. Since you will be using it so much, you may find it helpful to add it to the Dock for quick access. This is accomplished by dragging and dropping it from /Developer/Applications/onto the Dock.
8
AppleScript Studio Programming for the Absolute Beginner
The Cocoa Framework The Cocoa framework provides AppleScript Studio with access to powerful application development resources. The Cocoa framework is a powerful collection of resources grouped together in an application programming interface or API. Cocoa was originally developed to support application development using a variation of the C programming languages known as Objective-C. However, because Cocoa is an open framework, Apple has made its resources accessible to other programming technologies, including AppleScript Studio. TIP
Cocoa is one of two APIs provided by Apple for the Mac OS X. The other framework is Carbon. AppleScript Studio does not use the Carbon framework; as such, a discussion of that framework is outside the scope of this book.
As you will see, AppleScript Studio applications use Cocoa in many different ways to simplify the creation and operation of graphical user interfaces. It is from the Cocoa framework that AppleScript Studio gets access to the graphical controls you will use when building application interfaces. Cocoa is also responsible for automatically ensuring that these controls look and operate as expected, saving you the effort and responsibility of creating and programming these controls yourself.
Interface Builder Another major technology used by AppleScript Studio is the Interface Builder. As outlined below, the Interface Builder consists of four windows, each of which serves a particular purpose. • Window. Each new AppleScript Studio application is automatically assigned a default window that serves as the basis for creating the application’s graphical user interface. • Cocoa Controls Palette. A collection of user interface controls, organized by category, that are used to create graphical interfaces using drag-and-drop interface design. • MainMenu.nib. Provides control over the various components that make up an application’s user interface (e.g., windows, controls, menus, sound files, images, etc.). • MainMenu.nib—MainMenu. Provides the ability to customize application menus.
A FEW WORDS ABOUT OBJECT-ORIENTED PROGRAMMING AppleScript Studio applications are Cocoa applications. Since AppleScript Studio is integrated into the Cocoa framework, it has access to Cocoa classes. This provides the ability to develop object-oriented applications capable of instantiating objects based on those classes, as well as the ability to access and manipulate object properties and methods.
Chapter 1 • AppleScript Studio Basics
9
Object-oriented programming or OOP is a programming methodology whereby objects, as well as object data and the program code that manipulates the object and its data, are stored together as a unit. Objects are things like windows, buttons, and other types of interface controls. In OOP, any information about an object such as a button, including its color or caption, is stored as object attributes. An attribute is simply a property of an object that defines it in some manner. As already stated, one of the application development technologies used by AppleScript Studio is the Cocoa framework. This framework greatly simplifies application development by providing AppleScript Studio applications with access to pre-defined collections of classes. A class is a template used to instantiate an object. For example, Cocoa defines a large number of pre-built interface control classes, representing buttons, sliders, text fields, and so on. As you will see later in this chapter, you can add instances of these classes by simply dragging and dropping them onto a window to build a graphical user interface for your AppleScript Studio applications. Once added, your application has access to all of the functionality provided by the object, as well as the ability to modify its attributes and to execute program code in order to manipulate them.
APPLESCRIPT: APPLESCRIPT STUDIO’S PROGRAMMING LANGUAGE AppleScript is a scripting language advertised by Apple as a core component of Mac OS X. AppleScript is also part of an integrated system-level interface that facilitates communications between applications. AppleScript is designed to allow you to tap into this resource and to use it to automate tasks. These tasks may be as simple as starting the Safari web browser and loading a particular web page or as complex as tying together the actions of several different applications in order to create a workflow that accomplishes something that none of the applications are capable of doing independently. AppleScript was first introduced to the world with the release of Mac OS 7. Initially, it enjoyed lukewarm success. Even Apple often seemed to be less than enthusiastic about it, with rumors occurring from time to time that AppleScript was on the endangered species list and thus close to being dropped by Apple. However, the amazing rise of Mac OS X has given new life to AppleScript. Not only has Mac OS X attracted millions of new users, but it also has provided many scriptable applications, making AppleScript a lot more useful. AppleScript is different from any other scripting language that you may have worked with in the past. In and of itself, AppleScript is a somewhat limited scripting language. It lacks many of the functions and capabilities that are typically built in to other programming languages. Instead of integrating a large collection of built-in functions and features into AppleScript, Apple chose to design the language so that it could control and automate other
10
AppleScript Studio Programming for the Absolute Beginner
Mac applications—thus enabling AppleScript to leverage functionality found in other applications without instead adding that functionality to the scripting language itself. TRI
CK
Without access to the functionality provided by other applications, AppleScript cannot be fully exploited. For example, AppleScript has very limited mathematical capabilities, lacking built-in functions provided by other scripting languages such as Perl. In addition, AppleScript has limited support for manipulating strings, files, and folders. However, by leveraging the functionality of applications like TextEdit or the Finder, you can develop AppleScripts that can perform complex string manipulations or administer files and folders.
Apple markets AppleScript as a simple English-like scripting language that is easy to learn and master. It is true that many of AppleScript’s keywords and commands follow an Englishlike structure. As previously stated, AppleScript is a little more limited than other modern scripting languages in regards to the features built in to the language itself. However, I would be doing AppleScript a great injustice if I left you with the impression that AppleScript was not a powerful, robust programming language capable of rivaling and often surpassing the capabilities of other scripting languages. AppleScript provides sophisticated programming features, including the ability to write object-oriented code that interfaces with classes and objects provided by the Cocoa framework and AppleScript Studio. According to Apple, everything about Mac OS X is easy and intuitive. Therefore, it is only natural that Apple makes the same claim about AppleScript. The reality is that learning AppleScript takes the same level of effort and commitment as learning any other scripting language. While AppleScript may not support as complete a set of built-in functionality as some other scripting languages, its ability to interact with and control other applications provides AppleScript with capabilities that often far exceed the capabilities of other scripting languages. One of the best things about AppleScript is the strength of its user community. If you check on the Internet, you will find that AppleScript programmers have posted tons of free AppleScripts, ready for you to download and use. In fact, chances are fairly good that if you need an AppleScript to perform a particular task, somebody else has already come across that same need and written an AppleScript to do it. In addition to the Internet, you will find a large collection of sample AppleScript Studio applications on your computer. These applications were automatically installed as part of the Xcode installation process. You will find them in /Developer/Examples/AppleScript Studio/. You can learn a lot from these sample applications, and you can use them as a repository from which you can copy and paste sample code into your own AppleScript Studio applications.
Chapter 1 • AppleScript Studio Basics
11
In the Real World Any time you start learning a new programming language, it is important to make sure that you understand key terminology relative to the language. In this book, the term AppleScript refers to both the programming language and to individual script files. A script file is an executable file containing script statements. Also, a scriptable application is an application that has a dictionary and is designed to interact programmatically with a script.
When to Write AppleScript Many times, tasks do not require you to develop AppleScript Studio applications in order to automate or simplify them. In fact, many times all that is needed is a small AppleScript. AppleScript is appropriate for situations where a graphical user interface is not required or desired. AppleScript is especially helpful when automating the following types of tasks. • Automating functionality for specific applications like the Finder or TextEdit • Simplifying complex tasks involving many steps into a script that can be run by doubleclicking on it • Performing repetitive tasks like cleaning out temporary files or renaming a large number of files • Creating workflows that combine the features of different applications in order to perform operations that each application is otherwise incapable of performing Because AppleScript is an integrated system-level technology, you can count on it being available on any computer running Mac OS X. In addition, it is present on older versions of the Mac operating system going back to Mac OS 7. This means that AppleScript can be used to solve problems on older operating systems where AppleScript Studio is not supported (e.g., operating systems prior to Mac OS X 10.1.2). This also means that once you have written and tested an AppleScript, you can copy it to any computer running Mac OS X, and it should run without issue. Of course, if your AppleScript utilizes the features provided by a third-party application, like Adobe Photoshop, that third-party application will have to reside on any computer where your script is deployed if you want it to run.
When to Develop AppleScript Studio Applications While AppleScript may be well suited to smaller applications that do not require a graphical user interface, AppleScript Studio applications are better suited to addressing tasks when:
12
AppleScript Studio Programming for the Absolute Beginner
• Interacting with users requires a graphical user interface • It is necessary to display output in a manner that requires visual organization • You are developing applications that will only run on computers that you know in advance support the execution of AppleScript Studio applications • You are developing applications of sufficient complexity to require the use of Xcode’s build and debugging environment TR
AP
While AppleScript Studio greatly simplifies the development of desktop applications, it does have a couple of shortcomings compared to other programming languages such as Objective-C, Python, and Perl. For starters, compared to these other programming languages, AppleScript Studio applications are slow. In addition, AppleScript Studio does not perform well when asked to display large amounts of data or to perform complex calculations. In addition, AppleScript Studio is also known to slow down when asked to perform intensive file system operations.
Working with the Script Editor In order to develop AppleScripts, you need a script or text editor. Mac OS X ships with Script Editor, a built-in script editor. Although you can use Script Editor to create other types of scripts, it comes preconfigured only for AppleScripts. Script Editor provides you with numerous helpful features that facilitate script development, including: • Color code highlighting • Automatic statement indentation • Built-in debugging capabilities • Code compilation and execution capabilities Script Editor resides, by default, inside /Applications/AppleScript/. You can start it by doubleclicking on its icon. When you do, Script Editor starts, as demonstrated in Figure 1.7. Once you have opened Script Editor, you can create a new AppleScript by entering one or more AppleScript statements in the main text area. For example, as your first AppleScript, enter the following statement in the main text area. display dialog "Hello World!"
As you type in this statement, take note of the color used to represent the text. Once you have keyed in the entire statement, click on the Compile button, which is represented by an icon that looks like a hammer. In response, Script Editor checks every AppleScript statement for errors. If an error is found, an error message is displayed. Otherwise, you will notice that the
Chapter 1 • AppleScript Studio Basics
13
color of the text representing the code statement you just keyed in has changed. In this case, language keywords are shown in blue, and everything else is displayed in black. In addition, if your AppleScript consists of multiple statements, indents are applied to help make the code more readable. At this point, Script Editor should look like the example shown in Figure 1.8.
FIGURE 1.7 Script Editor provides advanced editing features that simplify the development of AppleScripts.
TIP
Compiling is the process of converting application code statements into a format that can be efficiently executed by the operating system. During the compile process, code statements are checked to ensure that they follow the syntax rules required by the programming language.
To run this example, click on the Run icon located in Script Editor’s toolbar. In response, the popup dialog shown in Figure 1.9 is displayed, showing the output produced by the AppleScript.
14
AppleScript Studio Programming for the Absolute Beginner
FIGURE 1.8 Script Editor uses color coding to help make code statements easier to read and understand.
FIGURE 1.9 A simple popup dialog.
If you go back and look at the code statement that you entered to generate this popup dialog, you should be able to interpret what has happened. Namely, you have written an AppleScript that executed the display dialog command, telling that command to display the text string Hello World!. This is an excellent example of just how English-like AppleScript command syntax can be. Unfortunately, AppleScript command syntax is not always this straightforward. Click on the popup dialog’s OK button to dismiss it. When you do, the popup dialog closes, leaving the Script Editor visible, as shown in Figure 1.10.
Chapter 1 • AppleScript Studio Basics
15
FIGURE 1.10 Feedback regarding the button selected by the user is provided in the Result area at the bottom of Script Editor.
To save your new AppleScript so that you can execute it again later, select the Save option located on the File menu. This opens a new window that allows you to specify a name for your AppleScript and the folder where you would like it stored. TIP
You will learn more about how to work with Script Editor in Chapters 4–7, which provide you with instruction on how to create AppleScripts.
Accessing Application Dictionaries Every scriptable Mac OS X application includes a component known as a dictionary. The dictionary documents the commands required to programmatically communicate with and control the application. Unfortunately, there are many inconsistencies in the different commands that various applications support. As you might expect, a big part of AppleScript programming involves reading through application dictionaries looking for the commands needed to automate key application functionality. In order to create a workflow that automates the functionality provided by a given application, the application must be designed to accept Apple events sent to it by AppleScript. The
16
AppleScript Studio Programming for the Absolute Beginner
inclusion of this capability is up to the developer of the application. Depending on the application developer’s commitment to and knowledge of Mac OS X, third-party applications may or may not include this support. Applications such as Microsoft Word, Microsoft Excel, and FileMaker Pro, as well as Adobe Acrobat, Photoshop, and Illustrator, include this support, just to name a few. TIP
AppleScripts send messages to other applications and to the Mac OS X operating system in the form of Apple events.
To determine whether an application is scriptable, you can start up the Script Editor and then select the Open Dictionary option located on the File menu. This opens the Open Dictionary window, as demonstrated in Figure 1.11.
FIGURE 1.11 Using the Open Dictionary window to search for scriptable applications.
The Open Dictionary window displays a listing of applications that have registered themselves with Mac OS X as being scriptable. To view the dictionary for a given application, select it and click on the Open button. For example, Figure 1.12 shows the dictionary for the TextEdit application. Dictionary commands are organized into suites. You can select a suite by clicking on its name in the upper left-hand pane of the window. All of the available commands within that suite are then displayed in the lower half of the window, along with a description and syntax information. Most of the time you will find that the commands you will need to work with reside in the Standard Suite.
Chapter 1 • AppleScript Studio Basics
17
FIGURE 1.12 Examining the commands listed in the TextEdit application’s dictionary.
TIP
You can also access the Open Dictionary window when working with AppleScript Studio by starting Xcode and selecting the Open Dictionary option located under the File menu.
As you begin developing AppleScripts and AppleScript Studio applications in order to create automated application workflows, you will find yourself spending a lot of time working with application dictionaries. More detailed information on how to use application dictionaries is provided in Chapter 9, “Controlling Other Applications.”
BACK TO THE KNOCK-KNOCK APPLICATION Okay, that is enough AppleScript and AppleScript Studio background information for now. Let’s move on to something fun. It is time for you to create the first of many new AppleScript Studio applications. Admittedly, this first application is rather simplistic. Still, it is a good starting point, allowing you to learn the basic mechanics involved in creating a new AppleScript Studio application without overburdening you with layers of complexity that you do not need to deal with yet.
18
AppleScript Studio Programming for the Absolute Beginner
Do not worry if not everything makes sense as you go through the steps involved in building the Knock-Knock application. It takes time to absorb and understand everything that is going on. This is especially true of the program code statements that you will have to add to make the application work. For now, just focus on the overall process and try to get a feel for the order in which each step is performed. Things will become clearer as you read later chapters and become more comfortable with the AppleScript Studio application development environment and the AppleScript programming language.
Designing the Game The Knock-Knock application is a straightforward implementation of the classic children’s knock-knock joke. It may seem strange to be creating your first AppleScript Studio application this early in the book, especially given that you have not learned how to program using AppleScript yet. That is part of the beauty of AppleScript Studio; even with just a little knowledge, you can begin programming and write an application that really works. The Knock-Knock application is small and very straightforward. Still, by working your way through this example and duplicating everything that you see, you will learn the basic mechanics involved in developing AppleScript Studio applications, which is the real reason for creating this application so early in the book. The Knock-Knock game will start by displaying its user interface and waiting for the player to click on a button labeled Tell Joke. In response, the game will begin asking the player questions in order to set up the joke’s punch line. Once you have finished creating and testing your new application, you should take note that even though the application consists of just a handful of short programming statements, it contains all of the functionality and features that Max OS X users expect from their applications. For example, the Knock-Knock application’s user interface can be minimized, maximized, and resized. In addition, it interacts with the player using graphical elements like button controls and interactive popup dialogs. All this functionality is provided to your applications behind the scenes by the Cocoa framework, allowing you to create fully functional Mac OS X applications with surprising ease. As the development of the Knock-Knock application will show you, AppleScript Studio applications are generally developed in five basic steps. 1. 2. 3. 4. 5.
Open Xcode and create a new AppleScript Studio application. Create the graphical user interface using the Interface Builder. Attach interface controls to event handlers. Edit the AppleScript that controls the application. Build and run the application.
Each of these steps is covered in detail in the sections that follow.
Chapter 1 • AppleScript Studio Basics
19
Step 1: Creating a New AppleScript Studio Application The first step in creating a new AppleScript Studio application is to start up Xcode and create a new AppleScript Studio project as outlined in the following procedure. 1. Double-click on the Xcode icon located in /Developer/Applications. The only evidence that Xcode has started is the display of the Xcode menu at the top of the script, as demonstrated in Figure 1.13. FIGURE 1.13 When Xcode starts, only its menu bar is visible.
2. The next step is to tell Xcode to create a new project. To accomplish this, click on the New Project menu item located on the File menu. Xcode responds by launching an Assistant, as shown in Figure 1.14.
FIGURE 1.14 The Assistant presents a list of application templates.
3. The Assistant displays a list of templates, each representing a different type of Cocoa application. Cocoa supports the creation of three different types of AppleScript Studio applications.
20
AppleScript Studio Programming for the Absolute Beginner
• AppleScript Application. A Cocoa application written using AppleScript that does not support the creation of documents. • AppleScript Document-based Application. A Cocoa application written using AppleScript that supports documents. • AppleScript Droplet. A Cocoa application written using AppleScript that executes when files are dropped on it. Select the AppleScript Application template, located under the Application category, and click on Next. The Assistant next prompts you to specify a file name and location where you would like to store your new AppleScript Studio application, as demonstrated in Figure 1.15.
FIGURE 1.15 Assigning the name and path to the Knock-Knock application.
TIP
I recommend creating a new folder for storing all your AppleScript Studio applications. For example, you might want to create a new folder named MyApps in your home directory. AppleScript Studio will remember this folder name and its location the next time you create a new AppleScript Studio application.
4. To finish creating your new project, click on the Finish button. Xcode responds by displaying the Editor dialog shown in Figure 1.16.
Chapter 1 • AppleScript Studio Basics
21
FIGURE 1.16 Xcode displays a listing of all of the files that make up your new AppleScript Studio project.
The title bar displays the name assigned to the new application. The files that make up the new AppleScript Studio project are listed in a hierarchical fashion on the left-hand side of the dialog in the Groups & Files pane. By clicking on the disclosure triangles, you can drill down into different groupings of files. The Scripts folder contains all of the AppleScript files associated with the project. Within it, one file has been automatically created for the Knock-Knock application, the Knock-Knock.applescript file. This file is the default AppleScript file for the application. The right-hand side of this dialog displays the contents of the select file or resource. TIP
You will find more information on how to work with Xcode and the files that make up AppleScript Studio projects in Chapter 2, “The AppleScript Studio Application Development Environment.”
Step 2: Creating a Graphical User Interface Now that you have created a new AppleScript Studio project, the next step is to begin work setting up the application’s graphical user interface. This is accomplished by executing the steps outlined in the following procedure.
22
AppleScript Studio Programming for the Absolute Beginner
TRI
CK
The Cocoa framework provides your AppleScript Studio applications with the underlying object-oriented functionality required by any desktop application that runs on Mac OS X, thus greatly simplifying application development. To see what I mean by this, click on the Build and Go icon located at the top of the Xcode Editor window. In response, Xcode will compile your project into an executable program and run it. As you will see, even though you have not written a single line of code, your new application benefits from functionality provided by the Cocoa framework. It displays a blank window, which you can move, resize, and even minimize to the Dock. In addition, it has a title bar with the standard set of buttons located on the left-hand side. When done, close the application and the Run Log window that was also opened when you ran the application.
1. Click on the disclosure triangle for the Resources folder located in the Groups & Files pane. This exposes the MainMenu.nib file. This file contains information used to build the main window for the application. TRI
CK
If you prefer, you can also start the Interface Builder using Finder. However, it’s almost always more convenient to let Xcode start it for you.
2. Double-click on the MainMenu.nib file. In response, the Interface Builder starts, displaying the four windows shown in Figure 1.17. MainMenu.nib
Application window
Cocoa-Controls palette
MainMenu.nib - MainMenu
FIGURE 1.17 The Interface Builder provides all the tools you need to create your application’s graphical user interface.
Chapter 1 • AppleScript Studio Basics
TRI
CK
23
At this point, you may find that your screen is becoming too crowded and that it is becoming difficult to keep track of all the windows that are currently open. If you want, you can simplify things a bit by clicking on the Hide Others option located on the Interface Builder menu. This hides the Xcode Editor window (on the Dock) and the four Interface Builder windows from view.
3. Using the resize handle located in the lower right-hand side of the default application window, resize the window as shown in Figure 1.18. FIGURE 1.18 Changing the size of the window to be used as the interface for the Knock-Knock application.
4. The Knock-Knock application’s window contains a single button control. To add a button control, click on the Cocoa Controls and Indicators icon located at the top of the Cocoa Controls palette (second button from the right) and then drag and drop an instance of the button control onto the window, as demonstrated in Figure 1.19. Using drag and drop, center the button control in the middle of the application window.
FIGURE 1.19 Adding a button control to the Knock-Knock application window.
5. At this point, the application’s user interface should look like the example shown in Figure 1.20.
24
AppleScript Studio Programming for the Absolute Beginner
FIGURE 1.20 You can reposition the button control by clicking on it and dragging it to a new location within the window.
6. The application also displays instruction in the form of a text string displayed directly on the application’s window. To add this text, click on the Cocoa Text Controls icon (third from the right), located on the Interface Builder toolbar. In response, a new set of controls is displayed in the Interface Builder, as shown in Figure 1.21.
FIGURE 1.21 Adding a static text control to the Knock-Knock application.
7. Select the small system font text control and then drag and drop an instance of it onto the Knock-Knock application window, centering it just above the button control. 8. Double-click on the small system font text control that you just added to the window. This places you in input mode, allowing you to enter whatever text you want in the control. Type Welcome to the Knock-Knock application. To play, click on the Tell Joke button. 9. The next step is to customize the appearance of the button. Begin by double-clicking on the control. This places the cursor inside the control, allowing you to enter text in order to label the control. Enter Tell Joke and then click on an open area of the window. The control should immediately update and change its appearance and size as necessary to reflect the change you just made to its label.
Chapter 1 • AppleScript Studio Basics
TIP
25
You find more detailed information on how to work with the Interface Builder in Chapter 3, “Building a Graphical User Interface.”
At this point, the user interface for the Knock-Knock application is complete. The next step is to modify attributes belonging to the application window and to associate the button control with the AppleScript that will execute when the user clicks on it, as outlined in the next section.
Step 3: Modifying Control Attributes and Attaching Controls to Event Handlers The next step in setting up the Knock-Knock application is to configure a couple of attributes, or properties, belonging to its window. This can be done via the Inspector window. For the Knock-Knock application, you will want to use the Inspector window to assign a name to the application’s window. In addition, you will want to set up the window such that the user won’t be able to change window size, as outlined in the following procedure. 1. Select the button control and then click on the Show Inspector option located under the Tools menu. The Inspector window opens as shown in Figure 1.22.
FIGURE 1.22 The Inspector window provides access to window and control attributes and events.
2. To view window attributes, select Attributes from the popup control located at the top of the Inspector window. 3. Enter Knock-Knock in the Window Title field.
26
AppleScript Studio Programming for the Absolute Beginner
4. Under the Title bar controls section, clear the Zoom (and resize) checkbox as shown in Figure 1.23. This will disable the green Zoom button control located on the left-hand side of the title bar, preventing the user from being able to change the size of the application window.
FIGURE 1.23 Modifying the attributes associated with the application window.
5. Close the Interface Builder by selecting the Quit Interface Builder option located on the Interface Builder menu and click on Save when prompted. Now that the Knock-Knock application’s interface is complete and you have finished modifying the required window attributes, it is time to set things up so that an AppleScript script, which you will write in the next section, is executed whenever the user clicks on the button control located on the application’s user interface. This is accomplished using the following procedure. 1. Select the button control and then click on the Show Inspector option located under the Tools menu. The Inspector window opens. 2. Select the AppleScript option from the popup located at the top of the Inspector window. 3. A list of the different types of events that the button control can respond to is in the event handler section of the Inspector window. For the Knock-Knock application, we want to set the button up to respond whenever the user clicks on it. This is accomplished by clicking on the disclosure triangle just to the left of the Action event handler, exposing the clicked event handler. Select this event handler by clicking on its associated checkbox.
Chapter 1 • AppleScript Studio Basics
TIP
27
An event is an action for which a control can detect and respond. Controls respond to events through event handlers. Event handlers are organized into related groups in the Inspector window.
4. Now that you have specified that you want to set up the button to respond when clicked, you need to associate a clicked event handler with an AppleScript that you want to execute. This is accomplished by selecting the radio control associated with the KnockKnock.applescript script listed in the Script section at the bottom of the Inspector window, as demonstrated in Figure 1.24.
FIGURE 1.24 Associating a control with an AppleScript.
As a result of executing the previous procedure, Xcode reappears, displaying the code statements that currently make up the Knock-Knock application. As you will see, the following event handler statements have been added to Knock-Knock.applescript. These statements will automatically be executed every time the user clicks on the button. on clicked theObject (*Add your script here.*) end clicked
By entering AppleScript code statements inside this event handler, you can set up the KnockKnock application to perform any commands you specify.
28
AppleScript Studio Programming for the Absolute Beginner
You’ll find more detailed information on how to work with the Inspector window in Chapter 3.
TIP
Step 4: Editing Your AppleScript Now that you have finished setting up the Knock-Knock application’s graphical user interface and have configured the button control to respond to a click event, you need to add program code statements to the clicked event handler. This is accomplished by the steps outlined in the following procedure. 1. While still in the Inspector window (with Knock-Knock.applescript selected), select AppleScript from the popup control located at the top of the Inspector window and click on the Edit button located at the bottom of the window. 2. Xcode’s Editor window reappears, displaying the newly added clicked event handler in the editing section, located on the bottom right-hand side of the window. 3. Select and delete the (*Add your script here.*) statement. 4. In its place, enter the following statements, as demonstrated in Figure 1.25. on clicked theObject set userResponse to the text returned of (display dialog ¬ "Knock-Knock!" default answer "Who is there?") if not (userResponse = "Who is there?") then display dialog "Sorry, you must enter 'Who is there?' to play." end if set userResponse to the text returned of (display dialog ¬ "Orange!" default answer "Orange who?") if not (userResponse = "Orange who?") then display dialog "Sorry, you must enter 'Orange who?' to play." end if display dialog "Orange you glad you created your first AppleScript " & ¬ "Studio application?" end clicked
Chapter 1 • AppleScript Studio Basics
TRI
CK
29
The ¬ character is an AppleScript continuation character. To type this character, you must press the l key while holding down the Option key. It is used to arbitrarily split a programming statement over two or more lines. By default, the Xcode Code editor lets you type in code statements that are as long as you want. The more you type, the more the editor slides over to the right to make room. As you will see later in this chapter, you can configure the editor to automatically wrap long code lines for you. The decision as to whether to turn on automatic line wrapping versus inserting a continuation character to break up long code statements is entirely up to you.
These AppleScript statements generate a series of popup dialogs that interact with the player, guiding him through to the game’s punch line.
FIGURE 1.25 Adding the AppleScript code required to control the Knock-Knock application.
TIP
For now, do not worry about trying to figure out what these statements are doing. Simply key them in and move on, remembering to focus on the mechanics involved in the creation of AppleScript Studio scripts. Later chapters delve into the ins and outs of AppleScript code statements.
30
AppleScript Studio Programming for the Absolute Beginner
That is it. You have completed all the steps required to create the Knock-Knock application. All that remains is to compile and run it. Before doing so, you might want to pause and save your work by selecting the Save All option located on Xcode’s File menu.
Step 5: Building and Running Your Mac OS X Application Let’s test the Knock-Knock application. To do so, you need to compile it. You can compile your application by selecting the Build option located on the Build menu or by clicking on one of the Build icons located in the editor’s toolbar. Once it is compiled, you can run your new application by selecting the Run option located on the Build menu. In response, your application is started. Try it out and see how it works. When done, you can close it like any other Mac OS X application.
SUMMARY This chapter introduced you to AppleScript Studio and its basic components. These technologies include AppleScript, the Cocoa framework, Xcode, and the Interface Builder. AppleScript is the programming language that helps to drive AppleScript Studio applications. You also learned how to use the Script Editor to create and execute your first AppleScript. Finally, you learned how to work with Xcode and the Interface Builder to create your first AppleScript Studio application, the Knock-Knock game. In doing so, you learned the basic steps involved in AppleScript Studio application development. Now, before you move on to the next chapter, I suggest that you set aside a few extra minutes to see if you can improve on the Knock-Knock application by implementing the following list of challenges.
CHALLENGES 1.
2.
The Knock-Knock application currently tells a single joke. Try making it more interesting by modifying it to tell additional jokes. The text currently displayed in the small system font text control and on the button control is somewhat cryptic. Replace these text strings with text that is more meaningful and instructive.
2
C H A P T E R
THE APPLESCRIPT STUDIO APPLICATION DEVELOPMENT ENVIRONMENT code provides AppleScript Studio’s development environment. Through Xcode you create and modify AppleScript Studio projects. Xcode provides project templates for generating new applications. In addition, it provides the tools required to edit program code, browse application terminology, debug code errors, access documentation, and interact with the Interface Browser. In this chapter, you will learn how to use Xcode to develop new AppleScript Studio projects and to turn those projects into Max OS X applications. In addition, you will also develop a new computer game, the AppleScript Studio Fortune Teller.
X
Specifically, you will learn how to • Create new AppleScript Studio projects • Determine how Xcode interfaces with the Interface Builder to connect interface elements to code statements • Use Xcode’s built-in code editor • Use Xcode to access application terminology • Use Xcode to access the Apple Developer Reference Library • Customize Xcode’s operation by modifying preference settings
32
AppleScript Studio Programming for the Absolute Beginner
PROJECT PREVIEW: THE APPLESCRIPT STUDIO FORTUNE TELLER GAME In this chapter, you will learn how to create a new computer game using AppleScript Studio. The AppleScript Fortune Teller game prompts the player to ask questions and then responds with randomly generated answers. When started, the game displays the window shown in Figure 2.1.
FIGURE 2.1 The AppleScript Fortune Teller prompts the player to ask a question.
The game checks to verify that the player entered a question each time the OK button is pressed. In the event the player fails to enter something, the error dialog shown in Figure 2.2 is displayed.
FIGURE 2.2 The game issues an error message in the event the player clicks on OK without entering any text.
Figure 2.3 demonstrates a typical question that might be asked of the AppleScript Studio Fortune Teller game.
FIGURE 2.3 The player must click on Ask to submit her question.
In response, the game generates a random response to the player’s question, as demonstrated in Figure 2.4.
Chapter 2 • The AppleScript Studio Application Development Environment
33
FIGURE 2.4 The answer to each question is displayed in a popup dialog.
As Figures 2.5 and 2.6 show, the game can generate a number of different answers. FIGURE 2.5 Because the AppleScript Studio Fortune Teller game’s answers are randomly generated, the player can never be certain how a given question will be answered.
FIGURE 2.6 The player may ask as many questions as she wants.
When finished asking questions, the player can close the AppleScript Studio Fortune Teller game by clicking on its Close icon or by clicking on the Quit New Application item located on the Fortune Teller menu.
PROJECT TEMPLATES In Xcode, the project is the container that is used to organize the files and resources that make up applications. Xcode supports the development of both Cocoa and Carbon applications written in C, Objective-C, C++, Java, and AppleScript. Of course, for this book we are only concerned with Xcode’s ability to support AppleScript Studio applications written using AppleScript.
34
AppleScript Studio Programming for the Absolute Beginner
Xcode allows you to open and modify existing projects and to build new Mac OS X applications based on project contents. You do so by selecting one of the New or Open options located on the Xcode File menu, as shown in Figure 2.7.
FIGURE 2.7 The Xcode’s File menu provides commands for creating and accessing projects.
TIP
By selecting a project template, you identify for Xcode the default target for your application. In the case of AppleScript Studio, the target is usually a Mac OS X desktop application. Xcode then packages up all the files, resources, and framework information needed to build your new application.
To open an existing AppleScript Studio project, you can select the File menu’s Open option and specify the location of the project file. Projects are stored in a project folder and assigned a file extension of .xcodeproj. To create a new AppleScript Studio application, you click on the File menu’s New Project menu item. In response, Xcode starts an Assistant that prompts you to specify the type of application you are building, as demonstrated in Figure 2.8. For this book, you will select the AppleScript Application project template for each game project that you’ll be creating.
Chapter 2 • The AppleScript Studio Application Development Environment
35
FIGURE 2.8 An Assistant provides you with access to project templates that specify all the resources needed to build a given type of application.
After you select AppleScript Application and click on the Next button, the Assistant will prompt you to provide a name for your new application and to specify the folder where you want to save it, as demonstrated in Figure 2.9.
FIGURE 2.9 Specifying the name of your AppleScript Studio project.
36
AppleScript Studio Programming for the Absolute Beginner
By default, the Assistant will save your new application in your home directory. However, you can click on the Choose button and specify a different location. TIP
The ∼ character shown in Figure 2.9 is a special character that represents your home directory. On Unix-based operating systems, like Mac OS X, the home directory is a personal folder assigned to each unique user of the system where you can store personal files.
Once you have specified the name of your project and the location where you want your new project saved, you will notice that the Next button located in the lower right-hand corner of the Assistant is replaced with the Finish button. Click on Finish to create your new AppleScript Studio project. The Assistant will close, and Xcode’s Project window will appear. From this window, you will manage the rest of the project development process. When you are done, you will also build your new Mac OS X application from this window as well.
SETTING XCODE PREFERENCES Xcode is an extremely powerful and complex application development tool. It has so many features and capabilities that it is easy to get lost in. Having so many options is a good thing. As you spend more time working with Xcode, you will become much more comfortable navigating its many windows and menus. You can make Xcode a little more user friendly by modifying some of its preference settings. For example, there are preference settings that allow you to specify and control syntax coloring, the default project build folder, custom key bindings, line numbering, window color schemes, code statement wrapping, and indentation. To access the Xcode Preferences windows, click on the File menu and select the Preferences option. A window similar to that shown in Figure 2.10 will appear.
FIGURE 2.10 Configuring Xcode preferences.
Chapter 2 • The AppleScript Studio Application Development Environment
37
Xcode preferences are organized into groups that are accessed by clicking on icons located in the toolbar at the top of the window.
WORKING WITH THE XCODE PROJECT WINDOW Xcode is the central point from which you will work as you create AppleScript Studio applications. Therefore, to be an effective AppleScript Studio application developer, it is important that you have a strong working knowledge of Xcode. The first time you create a new AppleScript Studio application, Xcode opens, as shown in Figure 2.11, and displays the default resources and files associated with AppleScript Studio applications. Groups & Files
Toolbar
FIGURE 2.11
Status bar
Detail view
Xcode’s Project window is the primary location from which you will manage the creation of AppleScript Studio applications.
As Figure 2.11 shows, the default Xcode Project window layout consists of four major sections. At the top of the windows is the toolbar, which contains icons representing commonly used commands. Beneath the toolbar, on the left-hand side of the window, is the Groups & Files pane, which displays a hierarchical listing of all the files and resources that make up the current project. To the right is the Detail view, in which the currently selected resource in the Groups & Files pane is displayed. At the bottom of the Project window is the status bar, which displays helpful messages as you work with the Project window.
38
AppleScript Studio Programming for the Absolute Beginner
The Project Window Toolbar The Xcode Project window toolbar, shown in Figure 2.12, provides single-click access to commonly used Xcode commands. Active Target menu
Build button
Tasks button
Editor button
FIGURE 2.12 The Xcode Project window toolbar provides quick access to commonly used Xcode commands.
Action button
Build and Go button
Info button
Search field
By default, the following buttons are provided on the Xcode toolbar. • Active Target menu. Lists the active target (e.g., your Mac OS X application). • Action button. Provides access to a list of commands applicable to the currently selected item. • Build button. Runs Xcode’s application build process, creating a compiled version of your application if no errors are found. • B uild and Go button. Runs Xcode’s application build process, creating and then running a compiled version of your application if no errors are found. • Tasks button. Stops any currently executing operation. • Info button. Displays the Info window, which is used to view and modify group and file items that make up application projects. • Editor button. Opens or closes the Xcode code editor within the detailed section of the Project window. • Search field. Provides the ability to perform search operations on the currently displayed item or file in the Detail view.
Groups & Files Xcode automatically assembles the necessary resources and files required to build your application when you tell the Xcode Assistant to create an AppleScript Studio application. The Groups & Files listing, shown in Figure 2.13, provides access to all of the resources and files that Xcode generates on your behalf in order to create an AppleScript Studio project. The Groups & Files section provides you with the ability to view all of the items that make up your AppleScript Studio projects. Items listed in Groups & Files are organized hierarchically by group and are displayed as individual files. A folder icon represents groups. Individual
Chapter 2 • The AppleScript Studio Application Development Environment
39
FIGURE 2.13 The Groups & Files section of the Xcode Project window provides access to all the items that make up your AppleScript Studio projects.
items are represented by unique icons based on their type. It is important that you have a basic understanding of a number of the groups and items listed in the Groups & Files section. These are described in the following list. • Scripts Group. Contains the AppleScript files that drive your AppleScript Studio application. By default, this group contains one script, named after the project name you assigned when you created the project. This script has a file extension of .applescript. • Resources Group. Contains resource files required by the application. Any required resource files, such as graphic or sound files, should be added to this group. Included in this group is the MainMenu.nib file, which stores instructions for building the application’s user interface. The user interface is created using Interface Builder, which can be accessed by double-clicking on this .nib file. • Other Sources. This group contains a file named main.m, which contains the Cocoa code required to build your AppleScript Studio application. • Frameworks. applications.
Contains frameworks required to support AppleScript Studio
• Products. This group stores the product specified for each project target. By default, AppleScript Studio projects contain a single target that results in a single application, which is assigned an .app file extension and stored in a subgroup named Build. When
40
AppleScript Studio Programming for the Absolute Beginner
you are ready to deploy your AppleScript Studio application, copy the application files stored in the Build subgroup. • Targets. A target specifies the instructions required to build a particular application. For example, your project may build desktop, server, or command-line applications. New AppleScript Studio projects contain a single target that is assigned the same name that you assigned to the project, without any file extension. • Errors and Warnings. Contains a listing of any errors generated during the application build process. You will learn how to work with error and warning messages later in Chapter 10, “Debugging and Error Handling.” TRI
CK
Although you do not have to store files—such as sound and graphics files—used by your AppleScript Studio applications in the Resources group, doing so makes it easier to keep the resources needed to build your application together.
Using drag and drop, you can rearrange the items listed in Groups & Files. In addition, you can drag and drop items needed by your applications, such as sound files or graphics, into groups that you create within the Groups & Files section. For example, you can add a new group within Groups & Files by selecting the New Group option located on Xcode’s File menu and then dragging and dropping any number of files into it. Likewise, you can remove any item from Groups & Files by selecting it and pressing the Delete key or by selecting the Delete command located on the Edit menu.
The Project Window Detail View The Detail view of the Xcode Project window displays detailed information about the currently selected file, resource, or group. If the selected item is a group, information is provided for all group items, including any subgroups that may be present. By default, the Detail view shows the following columns. • File Type • Build Status • Errors • Warnings • Code • Target
Chapter 2 • The AppleScript Studio Application Development Environment
41
However, additional data is available for display. You can add or remove columns from the Detail view by clicking on the View menu and selecting Detail View Columns. Alternatively, you can Control+click on any column header in the Detail view to display a context menu from which you can also add or remove columns, as demonstrated in Figure 2.14.
FIGURE 2.14 Configuring the information you want displayed in the Detail view of the Xcode Project window.
You can also reorder column headings by dragging and dropping headings to new locations. Also, using the Search field located in the Xcode Project window toolbar, you can perform searches on the items listed in the Detail view.
The Editor Window Xcode provides a full-featured code editor that includes a number of convenient and powerful features. Some of these features are enabled by default. Others are not. To get the most out the Xcode code editor, you will need to configure it to best suit your personal needs and preferences. Xcode’s code editor includes features such as: • Syntax checking • Syntax color coding • Automatic code indentation • Automatic matching of closing brackets and parentheses • Code completion Xcode assigns an .applescript file extension to the default script file for each new AppleScript project and stores it in the Scripts group located in the Groups & Files section of the Xcode Project window. If you select this script file and click on the Show Editor button, located in the Xcode Project window’s toolbar, Xcode will display the script file in the detail window, allowing you to modify and edit the script as demonstrated in Figure 2.15.
42
AppleScript Studio Programming for the Absolute Beginner
FIGURE 2.15 Editing an AppleScript file from within the Xcode Project window.
At the top of the edit area, you will see the Editor Navigation Bar, which has the following features. • Previous and Next arrow buttons. Allows you to switch between script files when more than one file is being edited. • Script icon. An icon identifying the type of file being edited. • File Name menu. A popup menu displaying the name of the script currently being edited and providing access to any other currently open script files. • Function menu. A popup menu that provides quick access to the handlers within the currently edited script file. • Bookmarks menu. Provides access to any bookmarks stored for the current script file. • Breakpoints menu. Provides access to any breakpoints that have been set for the current script file. • Go To Counterpart button. This option does not apply to AppleScript files. • Included Files menu. This option does not apply to AppleScript files. • Lock Status button. By clicking on this button, you can lock and unlock the script file’s edit status.
Chapter 2 • The AppleScript Studio Application Development Environment
43
If you prefer, you can open and edit your AppleScript files in a separate editor window. To do so, double-click on the script file in the Script group located in the Group & Files section. This opens an editor window similar to the one shown in Figure 2.16.
FIGURE 2.16 Editing an AppleScript file using a separate editor window.
In addition to the Editor Navigation Bar, the standalone version of the Xcode code editor includes its own toolbar, which contains buttons that allow you to perform build operations, set breakpoints, and jump to the location of the script file within the Project window. TIP
A breakpoint is a marker that identifies a point in a script file where you want Xcode’s built-in debugger to pause when executing the script. When paused, you can use the debugger to examine variable values and monitor the logical flow of the script as its executes. You will learn how to set breakpoints and debug AppleScript Studio applications in Chapter 10.
Regardless of whether you are working with the editor inside the Project window or in its own window, it provides the same functionality and features, as shown in Figure 2.17.
44
AppleScript Studio Programming for the Absolute Beginner
The Navigation Bar
The Gutter
The Editing Area
FIGURE 2.17 The components of the Xcode code editor.
As has already been discussed, the Editor Navigation Bar provides access to menus and buttons that allow you to move quickly to various parts of your script files. The gutter is used to display optional line numbers as well as the location of breakpoints and errors. The Editing area is where you enter your AppleScript code statements.
Statement Color Coding The Xcode code editor provides a number of formatting options that can help you when you are keying in your AppleScript statements. One of these features is syntax statement coloring, which is using different colors to display the different parts of script statements. Color-coding is enabled by default. You can disable color-coding or configure how it is applied by opening the Preferences window and then clicking on the Fonts & Colors button. From there, you can specify the colors that you want applied to any of the following: • Comments • Strings • Characters • Numbers • Keywords TIP
More information regarding how to access Xcode Preferences windows is available later in this chapter.
Statement Wrapping Another useful editing feature provided by the Xcode code editor is line wrapping. Line wrapping occurs when you type a code statement that is too long to be displayed on your screen. Line wrapping is not enabled by default. To enable it, open the Xcode Preferences window
Chapter 2 • The AppleScript Studio Application Development Environment
45
and click on the Indentation button and select the Wrap Line in Editor option. From here you can also specify how many blank spaces should be used when indenting.
Statement Indentation The editor can help you format your code statements by automatically indenting your code statements. This feature is not enabled by default. To enable it, open Xcode Preferences and click on the Indentation button and select the Syntax-Aware Indenting option. From here, you can also configure how Xcode indents comments.
Code Sense Another very handy Xcode editing feature is Code Sense. With Code Sense, Xcode keeps track as you enter the text for code statements and provides suggestions for completing your statements. By default, Code Sense is enabled but runs silently in the background. Whenever Xcode see an opportunity for suggesting how to complete a portion of a code statement, it notifies you by underlining the text entered so far. To see the list of options proposed by Code Sense, press the Escape key, or you can click on the Edit menu and select the Completion option. In response, a list of possible code completion suggestions is displayed, as demonstrated in Figure 2.18.
FIGURE 2.18 Using Code Sense as a tool for entering code statements.
46
AppleScript Studio Programming for the Absolute Beginner
TRI
CK
If you prefer, you can configure Code Sense so that it automatically makes suggestions every time it sees an opportunity by opening the Xcode Preferences window, clicking on the Code Sense button, and selecting the Always option in the Automatically Suggest popup menu. Enabling this option may prove especially helpful when you are just beginning to learn how to program. However, as you grow more experienced, you will most likely find this feature to be too intrusive.
If you want, you can select a code completion suggestion by clicking on it and pressing the Return key. In response, Xcode enters the specified text, inserting placeholders for any arguments that you may need to fill in.
The Info Window Another Xcode window that you should be familiar with is the Info window. This window provides you with the ability to view and modify items in the Project window. To use the Info window, select an item in the Project window and then click on the Info button, located in the Xcode Project window’s toolbar. The Info window opens and displays information about the selected item. Depending on the item selected, the data that is presented may be organized into multiple views. For example, if you select the item representing your AppleScript Studio project and then click on the Info button, you will see information similar to that shown in Figure 2.19.
FIGURE 2.19 Examining the General view provided on the Info window.
Chapter 2 • The AppleScript Studio Application Development Environment
47
In this example, the General view of the Info window shows you the location where your project files are stored. If you prefer, you can change the location where Xcode stores project files.
In the Real World It is very important that you document your AppleScript Studio applications, explaining in detail why you created the project the way you did. One way of doing this is to embed comments throughout your application code, as explained later in this chapter. However, there is more to AppleScript Studio projects than just adding program code statements. Xcode provides you with the ability to document items displayed within the Project window by selecting the item, clicking on the Info button located in the Project toolbar, and selecting the Comments view, as demonstrated in Figure 2.20.
FIGURE 2.20 Adding documentation to the script file for an AppleScript Studio application.
By making liberal use of this documentation feature, you can fully document your AppleScript Studio applications. If you add URLs or email addresses, they will be recognized as such and can be accessed by simply clicking on them. Also, if you want, you can view item comments by configuring the display of the Comments header in the Detail view.
48
AppleScript Studio Programming for the Absolute Beginner
INTEGRATION WITH THE INTERFACE BUILDER As you already know, when developing AppleScript Studio applications, you use Xcode to create new projects, manage the files that make up that project, edit the AppleScript code required for the application to run, and debug and build the application. However, to complete your AppleScript Studio applications, you also need to work with the Interface Builder. As you have already seen, you can start the Interface Builder from within Xcode by doubleclicking on the application’s nib file. Once your application’s user interface is complete, you need a means of associating or connecting it and its component elements with the AppleScript files that drive your AppleScript Studio applications. This can be accomplished using the Inspector window. The Inspector window acts as a sort of bridge between Xcode and Interface Builder. You open it from within Interface Builder by clicking on the Show Inspector option in the Tools menu. More information on how to work with the Inspector window is provided in Chapter 3, “Building a Graphical User Interface.”
THE TERMINOLOGY BROWSER As you learned in Chapter 1, “AppleScript Studio Basics,” you can develop AppleScripts that automate the operation of other Mac OS X applications. In order to do so, you must be familiar with the command terminology supported by the applications to be automated. Unfortunately, there are many inconsistencies in the different commands that various applications support. Fortunately, each scriptable Mac OS X application provides access to this terminology through its own dictionary. Rather than access these dictionaries through the Script Editor application that you were introduced to in Chapter 1, Xcode makes things easy for you by allowing you to access the Open Dictionary window from within the Xcode Project window. The Open Dictionary window, shown in Figure 2.21, is accessed by clicking on the Open Dictionary option located on the Xcode File menu.
FIGURE 2.21 Accessing application dictionaries from within the Xcode Project window.
Chapter 2 • The AppleScript Studio Application Development Environment
49
Easy access to application dictionaries greatly simplifies the process of developing automated workflow applications. You will learn more about how to work with the application dictionaries in Chapter 9, “Controlling Other Applications.” AppleScript Studio also has its own dictionary, which you can access within the Xcode Project window by double-clicking on the AppleScriptKit.sdef item located in the detail view of the Groups & Files list. For example, Figure 2.22 shows the AppleScript Studio dictionary entry for the button control. Here you will find, for example, detailed information on all of the properties associated with a particular control. This information can be helpful when you want quick access to information about a particular AppleScript Studio object.
FIGURE 2.22 Accessing the AppleScript Studio application dictionary.
DEBUGGING CAPABILITIES The Xcode Project window also provides an integrated source code debugger, as shown in Figure 2.23. Xcode’s debugger is based on the open source GNU Debugger, GDB. Using the debugger, you can control the execution of your application, pausing it at predefined points in order to inspect the values of variables and to trace the order in which statements are executing. The debugger also provides a Fix and Continue feature that allows you to make changes in your source code and recompile it without having to stop your current debug session.
50
AppleScript Studio Programming for the Absolute Beginner
FIGURE 2.23 Xcode’s built-in debugger provides detailed control over program execution, allowing you to track down and fix hard to find errors.
Xcode also provides command-line debugging capabilities. You will learn more about Xcode’s debugging capabilities later, in Chapter 10.
THE APPLE DEVELOPER REFERENCE LIBRARY Xcode comes equipped with a full copy of the Apple Developer Reference Library documentation. You can view and perform searches on this documentation from within Xcode by selecting the Help menu and clicking on the Documentation menu item. In response, Xcode displays a window similar to the one shown in Figure 2.24. TIP
The Apple Developer Reference Library provides access to documentation, release notes, sample code, and much more. Apple makes this documentation available on its website. Xcode keeps an eye out for updates to the Apple Developer Reference Library and will automatically prompt you to update it when newer documentation is available. You can determine when the last update occurred and configure the update process from the Documentation page on the Xcode Preferences window. From this page you can also click on the Check Now button to initiate an immediate documentation update.
Chapter 2 • The AppleScript Studio Application Development Environment
51
FIGURE 2.24 Accessing the Apple Developer Reference Library from within Xcode.
BACK TO THE APPLESCRIPT STUDIO FORTUNE TELLER GAME Now it is time to turn your attention back to the AppleScript Studio Fortune Teller game. The point of emphasis for this exercise is your interaction with Xcode and its various windows and features. However, in order to build the application, you will also have to work with the Interface Builder (covered in Chapter 3), and you will have to add the required program code, which you will learn about in Chapters 4 through 7. Again, for now, limit your focus on understanding your overall interaction with Xcode and the steps required to build AppleScript Studio applications.
Designing the AppleScript Studio Fortune Teller Game As you have already seen, the AppleScript Studio Fortune Teller game is a relatively simple little Mac OS X application. In Chapter 1, you learned how to build an application using the button control, the small system font text control, and the display dialog function. In order to build the AppleScript Studio Fortune Teller game, you will have to learn how to work with a new control, the text input field control. Using the text input field control, you can build custom user interfaces that collect and display text data.
52
AppleScript Studio Programming for the Absolute Beginner
The development of the AppleScript Studio Fortune Teller game will follow the same basic procedure that you used when building the Knock-Knock Joke application. Specifically, the AppleScript Studio Fortune Teller game will be developed in five steps. 1. 2. 3. 4. 5.
Opening Xcode and creating a new AppleScript Studio application. Building the application’s graphical user interface. Customizing controls and attaching interface controls to event handlers. Adding the AppleScript code required to make the application work. Building and running the application.
Each of these steps is covered in detail in the sections that follow.
Step 1: Creating a New Project The first step in building the AppleScript Studio Fortune Teller game is to start Xcode and create a new AppleScript Studio project as outlined in the following procedure. 1. Double-click on the Xcode icon located in /Developer/Applications. 2. Tell Xcode to create a new project by clicking on the File menu and selecting the New Project menu item. Xcode responds by launching an Assistant, which displays a listing of application templates. 3. Select the AppleScript Application template and click on Next. 4. When prompted by the Assistant to specify a file name and location where you would like to store your new AppleScript Studio application, enter F ortune Teller as the project name and specify the folder where you have decided to store your AppleScript Studio application. Next, tell Xcode to finishing setting up a new project for the application by clicking on the Finish button. At this point Xcode has created a new project, complete with all the files and resources required to build the application. Now the real work begins. Your job is to take this project shell and customize it in order to provide everything needed to build the AppleScript Fortune Teller application.
Step 2: Creating the User Interface Now that you have created a new project for the AppleScript Studio Fortune Teller application, it is time to assemble the controls that will make up the game’s user interface, using the procedure outlined here. 1. Click on the disclosure triangle for the Resources group located in the Groups & Files section in order to expose the MainMenu.nib file. 2. Double-click on the MainMenu.nib file to start the Interface Builder.
Chapter 2 • The AppleScript Studio Application Development Environment
53
3. Use the default application window’s resize handle (located in the lower right-hand side of the window) to resize the window, as shown in Figure 2.25.
FIGURE 2.25 Modifying the size of the application’s user interface.
4. The game’s window is made up a button control, a text field control, and a system font text control. To add and instance of the system font text control to the window, click on the Cocoa Text Control icon located on the Cocoa Text palette toolbar. Select the system font text control and then drag and drop an instance of it onto the application window, centering it in the upper half of the window. 5. To add the text field control, drag and drop an instance of the text field control to the window, resizing it so that it takes up all but about an inch and a half of the lower half of the window. 6. To add a button control, click on the Cocoa Controls and Indicators icon located at the top of the Cocoa Controls palette. Using drag and drop, place the button control just to the left of the text field control. At this point, the application window should resemble Figure 2.26. FIGURE 2.26 The controls that make up the AppleScript Fortune Teller game still require attribute modifications.
Now that the required controls have been added to the application’s windows, it is time to modify window and control attributes, as outlined in the following procedure. 1. Double-click on the button control. This places the cursor inside the control, allowing you to enter text. Type Ask. 2. Resize the system font text control so that it is approximately a half- inch high and takes up most of the available width of the application window. Double-click on the system
54
AppleScript Studio Programming for the Absolute Beginner
font text control that you just added to the window. Type your question in the space provided below and click on Ask to pose your question to the fortune teller. 3. Click on an open area in the application window and then click on the Tools menu and select Show Inspector. 4. If necessary, select Attributes from the popup dialog located at the top of the Inspector window and enter AppleScript Studio Fortune Teller in the Windows Title field and then clear the Zoom (and resize) checkbox. 5. Next, select the window’s text field control. Then click on the Text Color color well in the Inspector window. The Colors window appears, as shown in Figure 2.27. Click on a blue color area within the rainbow colored circle in the middle of the window to set blue as the color for any text entered into the text field.
FIGURE 2.27 Configuring the text color attribute for the text field control.
6. Click on the Background Color color well and set the background color of the text field by making a cream-colored selection. 7. Click on the Line Breaking popup dialog and select the Word Wrap option and select the Wraps radio button for the Layout option on the Inspector window. Together these modifications ensure that any text entered by the player will wrap and break on a clean word boundary. At this point, the game’s interface has been assembled and configured. The next step is to associate the button control’s click event with an event handler, as outlined in the next section.
Chapter 2 • The AppleScript Studio Application Development Environment
55
Step 3: Attaching Controls to Event Handlers It is time to associate the button control with the on clicked event handler, thus allowing the application to react whenever the button is clicked. This is accomplished using the following procedure. 1. Select the button control and, if necessary, click on the Show Inspector option located under the Tools menu to display the Inspector window. 2. Select the AppleScript option from the popup dialog located at the top of the Inspector window. 3. Click on the disclosure triangle just to the left of the of the Action event handler in order to expose the clicked event handler. Select this event handler by clicking on its associated checkbox. 4. Select the radio button associated with the Fortune Teller.applescript script listed in the Script section at the bottom of the Inspector window. 5. Click on the Edit button. Xcode reappears, displaying its code editor. Code statements similar to the following should be displayed. -- Fortune Teller.applescript -- Fortune Teller --
Created by Jerry Ford on 6/30/06.
--
Copyright 2006 __MyCompanyName__. All rights reserved.
on clicked theObject (*Add your script here.*) end clicked
The first four lines are comment statements. A comment is a line of text used to internally document a script that is ignored by the compiler when the application is built and executed. The last three statements represent the on clicked event handler that you just added to the application when you selected the button control’s clicked event and clicked on the Edit button. In the next section, you’ll add the required AppleScript statement inside this event handler to make the AppleScript Fortune Teller application run. TIP
AppleScript supports two types of comments. Typing two consecutive dashes, as demonstrated in the first four statements shown in the previous example, creates the first type of comment. Any text typed after two dashes is considered to be a comment. The second type of comment supported by AppleScript is created by enclosing the text to be commented in between opening, (*, characters and closing, *), characters. You can see an example of this type of comment
56
AppleScript Studio Programming for the Absolute Beginner
in the previous example as well. The advantage of this second type of comment is that is can be used to create comments that span more than one line. By making liberal use of comments, you can make your AppleScript code a lot easier to understand, leaving behind remarks that explain what is going on.
Step 4: Adding a Little Programming Logic Okay, it is time to get down to the business of adding the program code statement required to actually make the application work like you want it to. This is accomplished by embedding the following code statements inside the on clicked event handler, as shown next. -- This code runs whenever the player clicks on the Ask button on clicked theObject -- Assign the text entered by the player to the question variable set question to contents of text field "textbox" of window "main" -- Display an error message if the player did not enter any text if question = "" then display dialog ¬ "Sorry, but you did not ask a question. Please try again." ¬ buttons {"OK"} return end if -- Assign a random number between 1 and 3 to a variable named randomNo set randomNo to random number from 1 to 3 -- If the randomly generated number equals 1 assign an answer of Yes if randomNo = 1 then set answer to "Yes" end if -- If the randomly generated number equals 2 assign an answer of No if randomNo = 2 then set answer to "No" end if -- If the randomly generated number equals 3 assign an answer of Maybe
Chapter 2 • The AppleScript Studio Application Development Environment
57
if randomNo = 3 then set answer to "Maybe" end if beep
-- Play a beep sound to get the player’s attention
-- Display the game's randomly generated answer display dialog "Question: " & question & " Answer: " & ¬ answer buttons {"OK"} end clicked TR
AP
AppleScript Studio is a robust and powerful application development environment. In order to use it to develop new Mac OS X applications, you must first learn how to interact and work with both Xcode and the Interface Builder. In addition to becoming comfortable with these two tools, you must also learn AppleScript. The approach that I have chosen for this book is to get you working with Xcode and the Interface Builder first and then to move on and learn AppleScript. Each of these topics is hard enough to learn on its own, much less simultaneously. So for now, just key in the code statements as instructed. Once you have become comfortable with Xcode and the Interface Builder, you’ll learn the ins and outs of AppleScript coding in Chapters 4 through 7. To help the following code statements make at least a little sense for now, I have embedded a number of comments explaining what various parts of the code are doing.
Step 5: Testing the Execution of the AppleScript Studio Fortune Teller Application Okay, it is time to build and execute the AppleScript Studio Fortune Teller game. Assuming that you carefully followed along each step and that you did not make any typos when entering the application’s program statements, the application should compile and run without incident. To compile the application, click on the Build and Go button located on the Xcode code editor toolbar. Xcode will respond by compiling and then executing your application. Once you have it running, try it out and make sure that everything works as expected.
58
AppleScript Studio Programming for the Absolute Beginner
TIP
If your application fails to run, then you have made a mistake somewhere. Begin by clicking on the Errors and Warnings entry in the Group & Files section of the Xcode Editor window to see if any errors have been reported. You may get a hint of what went wrong from these messages. If the error message(s) don’t help, then go back and make sure that you have followed each of the required steps exactly and that you did not make any typos when keying in the application’s code statements. You will learn the ins and outs of tracking down and debugging program errors later, in Chapter 10.
SUMMARY This chapter introduced you to Xcode and explained each of its major components. This included learning how to add files to projects, view application dictionary terminology, and access the Apple Developer Reference Library. You also learned how to take advantage of many of the features provided by the Xcode code editor and to customize specific Xcode functionality by modifying Xcode preferences. Finally, you learned how to create your second AppleScript Studio application, the AppleScript Studio Fortune Teller game. Before moving on to the next chapter, why don’t you take a few extra minutes to work on the AppleScript Studio Fortune Teller game, adding the improvements outlined in the following list of challenges.
CHALLENGES 1.
2.
The AppleScript Studio Fortune Teller game currently has only a limited collection of replies that it can generate. Improve the game by adding a number of answers such as “Ask again later”, “The answer is unclear”, and “Only time will tell”. You will also need to expand the range of randomly generated numbers. The text on the AppleScript Studio Fortune Teller game’s main window is very basic. Improve the game by adding additional text that explains to the player that the game is intended for only Yes/No type questions.
3
C H A P T E R
BUILDING A GRAPHICAL USER INTERFACE n order to build GUI-based applications using AppleScript Studio, you must become comfortable working with Interface Builder. In addition, you must become familiar with the various Cocoa interface elements that are made available through Interface Builder. Using Interface Builder and Cocoa interface elements, you can create nib files, which are then used to build application interfaces and connect the components that make up the interface to program code residing in event handlers inside AppleScripts. This chapter provides you with instruction on how to work with Interface Builder and its major features. In addition, you will receive an overview of the interface controls needed to build application interfaces. On top of all this, you will learn how to create another computer game, the Typo-matic Typing Test.
I
Specifically, you will learn how to • Work with different types of application windows • Use Cocoa interface controls to build application windows • Access and configure windows and control attributes • Create and modify application menus
60
AppleScript Studio Programming for the Absolute Beginner
PROJECT PREVIEW: THE TYPO-MATIC TYPING TEST GAME In this chapter you will learn how to develop the Typo-matic Typing Test game. This game challenges players to complete a test that measures their typing skills. Two tests are available, Easy and Hard. Players select between these two options using a slider control located at the bottom of the application window, as demonstrated in Figure 3.1.
FIGURE 3.1 The Typo-matic Typing Test game presents players with two levels of play.
In addition to the controls displayed on the application window, the game also has a menu system, which can be used to control the game and display additional information, as shown in Figure 3.2.
FIGURE 3.2 The Typo-matic Typing Test game’s menu system.
By clicking on the About menu item located on the Typo-matic menu, players can access additional information about the game, as shown in Figure 3.3.
Chapter 3 • Building a Graphical User Interface
61
FIGURE 3.3 Viewing the information presented in the application’s About window.
If necessary, players can click on the Instructions button to display a popup dialog where instructions for playing the game are presented, as shown in Figure 3.4.
FIGURE 3.4 Accessing instructions for playing the Typo-matic Typing Test game.
Play begins after the player selects the level of difficulty and then clicks on the Take Test button. Figure 3.5 shows the test that is presented when the Easy level is selected.
FIGURE 3.5 The sentences that make up the Easy level follow a predictable pattern and are not particularly long.
62
AppleScript Studio Programming for the Absolute Beginner
Figure 3.6 shows the sentences that make up the test when the Hard level is selected. As you can see, these sentences are considerably longer and vary in content.
FIGURE 3.6 The advanced test is intended to provide players with a more difficult challenge.
After retyping each of the five sentences that make up the test, players must click on the Grade Test button to see how well they did. In response, the game displays the player’s score in a popup window similar to the one shown in Figure 3.7.
FIGURE 3.7 The game keeps track of correctly and incorrectly typed sentences.
After dismissing the popup window, the game displays any mistyped sentences in red (will appear gray in the book) in order to help players locate their errors, as demonstrated in Figure 3.8.
Chapter 3 • Building a Graphical User Interface
63
FIGURE 3.8 The game identifies sentences with errors by displaying them in a red font.
This game introduces a number of new programming features. For starters, you learn how to work with the slider control. You also learn how to control the availability of interface controls. For example, the player is prevented from entering text in the five text field controls except during game play. This is accomplished by manipulating the text field control’s Enabled attribute during game play. Similarly, the slider control and Take Test button are only enabled at the beginning of each new game and are both disabled once game play begins. As soon as the player finishes taking the test and clicks on the Grade Test button, the slider control and Take Test button are re-enabled to allow for a new game play.
CREATE GRAPHICAL USER INTERFACES Mac OS X 10.4 employs a user interface called Aqua. Aqua defines the standards used by Mac OS X and its applications that control the appearance of interface elements such as windows, menus, controls, and so on. In order to build effective applications that are both intuitive and easy to use, it is important that you adhere to the Aqua guidelines. Since virtually all professionally developed Mac OS X applications adhere to this standard, you won’t find any shortage of examples to follow.
64
AppleScript Studio Programming for the Absolute Beginner
In the Real World In order to build Mac OS X applications that meet the needs and expectation of Mac users, it is important that you adhere to the standards outlined by the Apple Human Interface Guidelines. These guidelines outline standards for specifying the appropriate application window type, the proper placement of interface elements, and the correct way to organize and present menus, menu items, and so on. To help application developers follow these guidelines, Apple publishes them in a PDF document called, apply enough, Apple Human Interface Guidelines. You can view and download a copy of this PDF document at http://developer.apple.com/documentation/UserExperience/ Conceptual/OS XHIGuidelines/. The Apple Human Interface Guidelines document goes to great lengths to define the right way to create Mac OS X application interfaces and provides examples that demonstrate how things should be done.
Fortunately, the Interface Builder assists you in creating GUIs that adhere to Aqua standards. Interface Builder, as you have already seen, is a graphical interface development tool that lets you create GUI application windows. By providing access to predefined collections of Cocoa controls, the Interface Builder facilitates the creation of GUIs using a simple drag and drop approach. Interface Builder lets you move and resize controls added to windows and provides visual indicators that helps keep things straight in even the most complicated GUIs. Interface Builder also provides the ability to modify application attributes and to connect interface elements to AppleScripts using the Inspector window. By default, Interface Builder resides in the /Developer/Applications folder. It can be started by double-clicking on the Interface Builder icon located in this folder. However, it’s far more common to start it by double-clicking on the MainMenu.nib file located in the Xcode Project window’s Files & Groups area. When started, Interface Builder displays a number of windows, as shown in Figure 3.9.
Chapter 3 • Building a Graphical User Interface
Cocoa Controls
MainMenu.nip
65
Window
MainMenu.nib - MainMenu
FIGURE 3.9 Interface Builder consists of a number of interrelated windows, each of which provides a different type of functionality.
As you work with Interface Builder to create a GUI, all of the changes that you made are defined in a nib file. Each new AppleScript Studio application is assigned a default nib file named MainMenu.nib. When the application is later compiled, the instructions defined in the nib file are used to build the interface.
Cocoa Controls The window that displays all sorts of interface controls is referred to as the Cocoa Controls palette. Icons located in the toolbar at the top of the window control when different sets of controls are visible. Interface controls are grouped by category. An overview of the categories and controls is provided later in this chapter. TRI
CK
Interface Builder displays a list of toolbar configuration options when you click on the Cocoa Control palette toolbar while pressing the Control key.
Interface controls provide the basic building blocks for GUIs. To use them, simply drag and drop the appropriate control onto an application window. In addition to interface
66
AppleScript Studio Programming for the Absolute Beginner
controls, you can also add additional windows to your applications by dragging and dropping the appropriate type of window onto the MainMenu.nib window. Interface Builder provides visual indicators that help you properly lay out and align controls. Once they are added to a window, you can modify the size and location of these controls by clicking on them and using the resizing handles that appear around the control. As you resize and move interface controls around a window, the Interface Builder displays visual indicators that help you align the control with other controls already on the window, as demonstrated in Figure 3.10. In addition, as you move controls near the edge of the window, visual indicators also appear, showing you the proper distance to maintain from the side of the window. This helps you to design GUIs that follow the Aqua guidelines.
FIGURE 3.10 Using Interface Builder’s visual indicators to align interface controls.
For controls that display a title, you can change the text of that title by simply double-clicking on it and entering new text. You can further configure these and any other windows or interface controls by selecting them, opening the Inspector window, and then selecting the Attributes view. For example, many interface controls allow you to modify their size and color through attribute changes. As you have already seen a number of times in this book, you can also use the AppleScript view of the Inspector window to associate control events with specific types of event handlers, which are then automatically added to the AppleScript you specify. The AppleScript view also allows to you assign names to each window or control, allowing you to then programmatically reference and control them using AppleScript code statements.
Chapter 3 • Building a Graphical User Interface
67
MainMenu.nib The Interface Builder’s MainMenu.nib window displays a number of different views. By default, the Instances view is displayed when the window is opened, making the following icons visible. • File Owner. An object outside of the nib file that is responsible for facilitating communication between objects defined within the nib when a GUI is created. • First Responder. Specifies the interface element that receives focus when the GUI is opened. • MainMenu. Stores the definitions that describe the contents and organization of the application’s menu. • Window. Represents the default application window for the AppleScript Studio application. TIP
Focus is a term used to identify the interface element that is the target for keystrokes. Users set focus by clicking on or selecting Window objects.
You will not need to do anything with the File Owner object. You don’t usually need to do anything with First Responder either. However, you will spend a lot of time working with MainMenu and Window. MainMenu represents an instance of an application menu. If need be, you can add additional menu instances to your application in order to develop other menus. Window represents an instance of a Window object. Although AppleScript Studio projects begin with a single instance of the Window object, you can add as many instances as your project requires. TIP
The Cocoa framework is object-oriented. Each time you use Interface Builder to add a window or control to an AppleScript Studio project, you are actually creating a new instance of a Window or Control object. This new instance inherits its characteristics and attributes from the class it is based on. A class is a template, which outlines the characteristics and attributes of a particular type of object, such as a window, button, or slider control.
MainMenu.nib – MainMenu The MainMenu.nib – MainMenu window provides you with an interactive copy of your AppleScript Studio application’s menu system. You will use this window to modify the application’s menus. By default, each AppleScript Studio project includes a default set of menus and menu items. You can modify these menus and menu items by changing their names and attributes. In addition, you can delete any unneeded menus or menu items or add new ones
68
AppleScript Studio Programming for the Absolute Beginner
to meet the particular needs of your application. More information on how to work with and modify menus is provided later in this chapter.
Window The last window displayed by Interface Builder is the window representing an AppleScript Studio application’s default or main window. This window is blank for any new project. You can use its title bar to move it around and change its height and length using its resize handle. Windows make up the foundation of GUIs. Your AppleScript Studio project can include as many windows as necessary. As you will learn later in this chapter, Interface Builder allows you to add and modify many different types of windows, each of which has its own particular sets of characteristics.
COCOA INTERFACE ELEMENTS Cocoa provides the AppleScript Studio application with access to an abundant collection of interface elements. These elements include menus, controls, and windows. You will learn how to work with each of these resources in the remainder of this chapter.
Cocoa Menus Menus represent a key component of most Mac OS X applications. They provide users with access to a list of commands that can be executed and used to present and control attribute information. As an AppleScript Studio application developer, it is important that you have a solid understanding of how to construct and organize application menus. Mac OS X menus are made up of numerous parts, as demonstrated in Figure 3.11. Menu
Separator Bar Menu Item Submenu
FIGURE 3.11 The contents of a typical Mac OS X application menu.
Keyboard Equivalent
Chapter 3 • Building a Graphical User Interface
69
Mac OS X application menus are displayed in a menu bar that is located at the top of the screen. This menu bar is always visible, except in situations where an application temporarily hides it, as would be the case when playing a full screen movie or computer game. By standardizing the location of menus, Aqua simplifies the Mac OS X desktop by providing a predictable location where the user will always know to look. Menus contain one or more menu items. Logically related menu items are grouped under the same menu. A menu item may be used as a submenu, which when clicked displays a subgrouping of additional menu items. Menu items may also have keyboard equivalents assigned to them. Using the keystroke combinations assigned to a keyboard equivalent, users can access menu items directly from the keyboard without having to use a mouse. Menus may also contain Separator Bars, which are graphical lines used to visually group related menu items and help set them off from other menu items.
Default Menus By default, each new AppleScript Studio project is assigned a default set of menus, as demonstrated in Figure 3.12. These menus consist of the following. • Application • File • Edit • Window • Help
FIGURE 3.12 Each AppleScript Studio application is assigned a default set of menus.
Deleting Menus and Menu Items If your application does not need some of the menu items or menus that are provided by default, you can delete them. To delete a menu item, click on the menu that contains it, select
70
AppleScript Studio Programming for the Absolute Beginner
the menu item, and then press the Delete key. Likewise, to delete an entire menu, including all of its menu items, select the menu and press the Delete key.
Adding New Menus, Menu Items, and Submenus In order to add new menus and menu items to a menu, click on the Cocoa Menus button located in the Cocoa Control palette to display the list of available menu items, as shown in Figure 3.13.
FIGURE 3.13 Click on the Cocoa Menus button to view the available palette of menu building options.
As you will see, the list of menu items shown in Table 3.1 is displayed. Except for the Separator and Item entries, each of the menu and submenus listed in Table 3.1 comes already configured with default menu items. For example, when you add the Format menu, it already has two submenus attached to it (Font and Text), and both of these submenus are populated with numerous menu items. TIP
In addition to each of the menus outlined in Table 3.1, each Mac OS X application’s menu system always includes an Apple and a Spotlight menu. Both of these menus are automatically created and maintained by Mac OS X and are outside of your control.
You add new menus, menu items, and submenus to application menus by selecting a menu item displayed in Interface Builder and dragging and dropping it to the appropriate location in the MainMenu.nib window. For example, you can add a new menu to your application using the following procedure.
Chapter 3 • Building a Graphical User Interface
TABLE 3.1
71
COCOA MENUS LISTED ON INTERFACE BUILDER’S COCOA MENUS VIEW
Menu
Description
Application
This menu displays items that affect the entire application. Common menu items typically found on this menu include About, Hide, and Quit. This menu typically displays items that control operations like Save, Print, Open, and Close. This menu provides access to commands that facilitate editing operations and the movement of data between applications, including commands like Cut, Copy, and Paste. This menu provides access to commands that control the display of application windows, generally including commands like Minimize and Zoom. This menu provides access to commands that are used to perform search operations within a window. This menu provides access to commands used to control the display of text, including Bold, Italic, and Underline. This item is used to insert a graphic separator line between submenu items. This menu provides access to commands that control the display and alignment of text. This item is used to add a new custom menu or to create a submenu under a menu. This item is used to add a new custom item to a menu or submenu. This menu provides access to commands that control the formatting and presentation of text. This icon is added to the MainMenu.nib window in order to create a new instance of a menu bar.
File Edit Window Find Font Separator Text Submenus Item Format Menu
TIP
While you can programmatically create menus, the focus of this book is on the creation of menus using Interface Builder. Menu creation through Interface Builder has many advantages. For starters, it is easier and faster, allowing for rapid development. In addition, Interface Builder provides a WYSIWYG view of your menus, allowing you to view and navigate them without having to first compile and run your AppleScript Studio application.
1. Click on the Cocoa Menus button in the Interface Builder toolbar. 2. Drag and drop the Submenu option onto the menu area in the MainMenu.nib – MainMenu window, as shown in Figure 3.14. 3. Double-click on the new menu and give it a new name. 4. Click on the new menu to display its initial default menu item. 5. Double-click on the menu item and give it a new name. 6. Add as many additional menu items or submenus as needed to the menu.
72
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.14 Adding a new menu to the default application menu bar.
In similar fashion, you can add a menu item to any menu using the steps outlined in the following procedure. 1. Click on the Cocoa Menus button in the Interface Builder toolbar. 2. Drag and drop the Item option onto a menu in the MainMenu.nib – MainMenu window, as shown in Figure 3.15. FIGURE 3.15 Adding a new menu item to an existing menu.
3. Double-click on the menu item and give it a new name. 4. Repeat steps 2 and 3 as many times as necessary. Adding a submenu is a straightforward process as well, as outlined in the following procedure. 1. Click on the Cocoa Menus button in the Interface Builder toolbar. 2. Drag and drop the Submenu option onto a menu in the MainMenu.nib – MainMenu window, as shown in Figure 3.16.
FIGURE 3.16 Adding a new submenu item to an existing menu.
3. Double-click on the submenu item and give it a new name. 4. Double-click on its default menu item and give it a new name. 5. Add more menu items or submenus as needed to the submenu.
Chapter 3 • Building a Graphical User Interface
73
Configuring Menus, Menu Items, and Submenus Once they are added, you can rearrange menus by dragging and dropping them to new locations. You can also rearrange menu items and submenus by dragging and dropping them to different locations on a menu. Mac OS X applications also support the addition of keyboard equivalents to menu items. This allows users to access menu items from the keyboard without having to use the mouse. Keyboard equivalents are set using the Inspector window, as outlined in the following procedure. 1. Select the menu item to which you want to assign a keyboard equivalent and open the Inspector window. 2. Select the Attributes view from the popup control location at the top of the window. 3. Enter the character to be assigned or click on the <no key> popup control and select one of the available special function keys. 4. Select a combination of one or more Key Modifier keys, as shown in Figure 3.17.
Shift
Option
Command
Control
FIGURE 3.17 Assigning a keystroke equivalent to a menu item.
5. Close the Inspector window. 6. The new keyboard equivalent should be immediately visible on the menu item to which it was added, as demonstrated in Figure 3.18.
74
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.18 A keyboard equivalent of Shift+Command+J has been assigned to the Screen menu item.
TR
AP
Do not assign the same keyboard equivalent to more than one menu item. Many keyboard equivalents have predefined standard uses, so avoid assigning these except when appropriate. For example, Command+C and Command+V keyboard equivalents should only be assigned to Copy and Paste menu items located on the Edit menu. Experienced Mac OS X users will expect you to follow these types of standards. Failure to do so will result in confusion and frustration for your users.
Cocoa Controls and Indicators Application GUIs are created by adding instances of interface controls to windows. The Interface Builder’s Cocoa Controls view, shown in Figure 3.19, provides AppleScript Studio application developers with access to an assortment of Cocoa controls, including button, selection, progress indicator, and level indicator controls. The sections that follow briefly describe the controls provided on the Cocoa Controls view.
FIGURE 3.19 Use the Cocoa Controls view to add various controls to windows.
Buttons Button controls are used to initiate an immediate action within your AppleScript Studio applications. Button controls have rounded corners and can display a text label, as demonstrated in Figure 3.20.
Chapter 3 • Building a Graphical User Interface
75
FIGURE 3.20 Use the button control as a means of allowing users to initiate a specific action.
Color Well Controls The color well control, shown in Figure 3.21, is a button-sized rectangle that displays the current color setting for a specific resource. When clicked, it displays the Colors window, from which the user can select a new color. FIGURE 3.21 When clicked, the color well control opens the Color window.
Metal Buttons Metal button controls are used to initiate immediate actions within AppleScript Studio applications made up of metal windows. Metal buttons can display text, graphics, or icons. Metal buttons also have rounded corners, as demonstrated in Figure 3.22. FIGURE 3.22 The metal button control is used on metal brushed windows.
Round Buttons A round button control, as you’d expect, is a button that is round, as demonstrated in Figure 3.23. Round buttons can be used to display a graphic or can be used in conjunction with a label. Round buttons are often used to build navigation controls. FIGURE 3.23 Round buttons can be blank or display a graphic, but are not able to display text.
76
AppleScript Studio Programming for the Absolute Beginner
Help Buttons A help button control provides users with easy access to the Help Viewer, allowing you to configure it to open a specific help page. The Help button is identified by the presence of a question mark character, as shown in Figure 3.24. The Help button is usually placed in the lower left-hand corner. FIGURE 3.24 Help buttons display a question mark sign.
Bevel Buttons Bevel button controls have beveled edges that give them a three-dimensional look. Bevel buttons can have square or rounded edges. They can be configured to work like standard buttons or grouped in bunches and treated like checkboxes or radio buttons. Bevel buttons can also display text, icons, or images, as demonstrated in Figure 3.25. FIGURE 3.25 The bevel button control can be customized to display a graphic image.
Stepper Controls The stepper control, shown in Figure 3.26, is used to give the user the ability to increment or decrement a value. Typically, the stepper control is used along with a text field that displays a value controlled by the stepper control. FIGURE 3.26 Using the stepper control to control a value displayed in a text box.
Slider Controls The slider control, shown in Figure 3.27, provides the user with the ability to select from a range of values by dragging the thumb to a different location on the slider bar. Slider controls
Chapter 3 • Building a Graphical User Interface
77
can be displayed horizontally or vertically and can display optional tick marks in order to help identify different values. FIGURE 3.27 Slider controls allow users to pick from a range of values.
Disclosure Triangles A disclosure triangle, shown in Figure 3.28, is used to control the display (disclosure) of additional information on controls on windows. For example, you might develop a window that displays summary information at the top and detailed information at the bottom and then use a disclosure triangle to control the expansion of the window in order to allow the detailed information to be displayed. FIGURE 3.28 Disclosure triangles are used to control the view of information within a window.
Checkbox Controls A checkbox control, demonstrated in Figure 3.29, is used to provide the user with the ability to select between predefined options. Checkboxes are typical used in conjunction with a text field control that provides labels that describe the purpose of the checkbox controls. FIGURE 3.29 Checkbox controls are used to present users with a selection between two values.
Radio Button Controls Radio button controls, shown in Figure 3.30, are used in groups of two or more in order to allow users to make a selection from a list of available choices. Radio buttons are used to allow users to make selections and not to initiate an action like other button controls.
78
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.30 Radio buttons are used to allow users to make a selection from a list of different choices.
Popup Controls A popup control, shown in Figure 3.31, is used to display a list of two or more choices from which the user can make a selection. Popup controls provide an alternative to radio buttons when space is limited. FIGURE 3.31 A popup control provides a spacesaving way to display a list of possible choices.
Once a control is added to a window, you can define the list of available choices by doubleclicking on the control and then double-clicking on each of the default entries and overtyping them. Additional choices can be added using the Attributes view of the Inspector window.
Level Indicators A level indicator control is used to display a graphical depiction regarding the level of something. A level indicator can be configured to display data in different ways. For example, Figure 3.32 shows two level indicators. The first level indicator is displaying data in a discrete view. The second level indicator is displaying data in a continuous view and includes tick marks that identify different levels. You can also configure level indicators to display a different color when values exceed predefined levels. FIGURE 3.32 Level indicators let you visually communicate a value to a user.
Chapter 3 • Building a Graphical User Interface
79
Progress Bar Indicators Progress bar controls are used to indicate the status of a process or operation. Three types of progress bars are supported, as outlined here. • Determinate. Used when the duration of an operation is known in advance and can be tracked. • Indeterminate. Used when the duration of an operation is not known in advance and cannot be tracked. • Asynchronous. Used when there is limited space available to display the control. Each of these different types of progress bars is demonstrated in Figure 3.33. Determinate Indeterminate Asynchronous
FIGURE 3.33 Different types of progress bars are supported based on the needs of your application.
Segmented Controls Like checkbox and radio button controls, the segmented control, shown in Figure 3.34, can be used to present users with access to two or more choices, the results of which affect the view or mode of the applications. Segmented controls can display either text or icons or can also be used to initiate an action. FIGURE 3.34 A segmented control is used to present the user with access to two or more choices.
Box Controls The final set of interface elements made available on the Cocoa Controls view of the Cocoa Controls window are the box controls, which are displayed as horizontal and vertical lines, as shown in Figure 3.35. Their purpose is to help organize and group other interface elements.
80
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.35 Box controls are used to organize and group other interface elements.
Cocoa Text Controls Application GUIs typically display a lot of text and are often used to collect text input from users. The Interface Builder’s Cocoa Text controls, shown in Figure 3.36, provide AppleScript Studio application developers with access to an assortment of text-based Cocoa controls. The sections that follow briefly describe the controls provided by the Cocoa Controls view.
FIGURE 3.36 Use Cocoa Text controls to display and collect text data.
Static Text Static text field controls display read-only text and are typically used to provide instruction and to label other controls. The Interface Builder provides easy access to a number of static text fields in different fonts, as shown in Figure 3.37. FIGURE 3.37 Static text fields are used to display text that does not change.
Chapter 3 • Building a Graphical User Interface
81
Text Fields A text field control, shown in Figure 3.38, is a rectangular field that allows users to enter text. Text fields can also be modified to make them display-only and can be configured to display with different kinds of borders. FIGURE 3.38 Text fields provide a simple way for collecting information typed in by the user.
Token Fields A token field control, shown in Figure 3.39, is one that builds a token based on the text entered into it. Since the text entered into the token field is treated as a token, it can be dragged and dropped onto other token fields. FIGURE 3.39 Token fields provide a convenient way of allowing data to be copied from field to field.
Number and Date Formatters The number and date formatter controls, shown in Figure 3.40, are used in conjunction with text field controls. By dragging and dropping one of these controls onto a text field, you set the text field up to store and format the specified type of data. Using the Inspector window, you can specify the precise formatting to be applied. FIGURE 3.40 The number and date formatter controls are used to control the formatting of data entered into text fields.
82
AppleScript Studio Programming for the Absolute Beginner
Text View Fields A text view control, demonstrated in Figure 3.41, is a multi-line text entry field that displays built-in slider controls when the amount of text entered exceeds the display area of the control.
FIGURE 3.41 The text view field can be used as the basis for creating a simple text editor.
Date Pickers The date picker control, demonstrated in Figure 3.42, is used to display and collect date and time information. It can be configured to display either in a simple text field or graphically as a calendar and clock.
FIGURE 3.42 The date picker control supports two distinct formats.
Form Fields Form field controls, demonstrated in Figure 3.43, are just text fields that are designed to be used within the context of a form. FIGURE 3.43 A simple two-field form.
Combo Box Controls Combo box controls, demonstrated in Figure 3.44, are a combination of a text field and a popup control. Combo box controls allow users either to enter text or to select from a predefined set of entries.
Chapter 3 • Building a Graphical User Interface
83
FIGURE 3.44 Combo box controls provide programmers with the flexibility of setting up a field that accepts both predefined and ad-hoc text input.
Search Fields A search field control, shown in Figure 3.45, is a text field into which users type a text string in order to initiate a search. Search fields display a small magnifying glass icon and have distinct rounded edges. FIGURE 3.45 Search fields are used to support text search operations.
Cocoa Windows Windows provide a framework for building graphical user interfaces. Mac OS X applications can consist of many different types of windows, each of which has its own particular set of characteristics, such as the ability to minimize, zoom, or display a title bar. These windows can be organized into the following groups. • Document. These windows are used to display the contents of files such as text documents and spreadsheets. A document window is automatically created in any new AppleScript Studio application created using the AppleScript document-based Application template. • Application. These windows typically make up the main window for non-document applications. An application window is automatically created for any new AppleScript Studio application created using the AppleScript Studio Application template. • Dialog. These are specialized popup dialogs designed to retrieve a specific form of input from the user. Examples of dialogs include Save and Print dialogs as well as popup dialogs created using the display dialog command. • Utility. These windows are typically used to provide access to commands or tools that affect other parts of an application. These windows typically float on top of other windows, making them visible at all times. An example of this type of window is Interface
84
AppleScript Studio Programming for the Absolute Beginner
Builder’s Inspector window, which can be used to set attribute settings and associate windows and controls with event handlers.
Basic Window Components and Characteristics Mac OS X windows generally share a number of common features or components. All windows must have a title bar, even if it does not display a title. The title bar allows users to drag and drop windows, thus moving them to different locations. Except for popup dialog windows, windows should always display a Close button in the title bar. Dialog windows display button controls within the window that control window closure. In addition, document windows may also include scroll bars that allow documents that appear larger than the window to be fully examined and edited. Document windows also typically include other controls such as the resize handle. Utility windows, on the other hand, typically cannot be resized and do not display Close and Minimize buttons. Mac OS X windows can also sport either of two different appearances. The first is the standard default look, and the other is a metal brushed look. Standard windows are turned into metal windows by changing their Has Texture attribute. Metal windows are different from standard windows in other ways than just their appearance. For example, you can move a standard window only by dragging its toolbar. Dragging any part of the window’s surface, on the other hand, can move a metal window. General use of brushed metal windows is discouraged. Instead, brushed metal windows are generally reserved for applications that attempt to re-create the interface of a physical device, such as a CD-ROM or DVD player or that serve as an interface for controlling connections to physical devices. A good example of an application that uses brushed metal windows is the Apple iPhoto application, as shown in Figure 3.46. Windows have an additional set of characteristics that define their behavior towards other windows. These characteristics include: • Modeless. This type of window allows you to interact with other parts of the application while the window is displayed. • Document Modal. Once displayed, this type of window prevents you from doing anything to the document it is associated with until you close the document modal window. • Application Modal. This type of window prevents you from interacting with other parts of the application until you close it.
Chapter 3 • Building a Graphical User Interface
85
FIGURE 3.46 A brushed metal window.
Using Interface Builder to Add Windows to Your AppleScript Studio Applications A standard default window is added to each new AppleScript Studio project. You can add additional windows to your application as required by dragging and dropping items from the Interface Builder’s Cocoa Windows view, shown in Figure 3.47, onto the MainMenu.nib window. When you do so, an instance of the new window is displayed in that window. In addition, the new window is displayed so that you can begin configuring it.
FIGURE 3.47 The Cocoa Windows view simplifies the process of adding new windows to your application.
86
AppleScript Studio Programming for the Absolute Beginner
In the Real World Just about every serious Mac OS X application these days provides information about itself and its author, including copyright data, in an About window located on the application’s Application menu. For example, Figure 3.48 shows an example of a typical About menu.
FIGURE 3.48 The About window for an AppleScript Studio application named Typomatic.
About windows typically consist of a standard window that displays a Close button. In addition, the name of the application and its version are displayed, as well as copyright information. A brief description of the application may also be provided in addition to contact information. About windows are different from other windows in your AppleScript Studio applications in that they are automatically created for you based on information that you provide as you work on the project. If you go back and check, you will see that an About window has been automatically built for each AppleScript Studio application that you have created so far. The information provided by default is typically not sufficient for most applications. Fortunately, you can easily modify the data that is displayed in the About window by modifying the contents of the InfoPlist.strings file located in the Groups & Files Resources group. When you double-click on this file, the contents of the InfoPlist.strings file are displayed. You should see a statement similar to the line shown here. NSHumanReadableCopyright = "Copyright 2006 __MyCompanyName__.";
You can then edit the information displayed in this statement to update the contents of your application’s About window.
Chapter 3 • Building a Graphical User Interface
87
In the Real World The next four sections provide instruction on how to add different types of windows to your AppleScript Studio applications. Instances of these windows can be created by dragging and dropping the appropriate window from the Interface Builder’s Cocoa Windows view onto the MainMenu.nib window.
Adding Windows You could add instances of the standard default window to your project by dragging and dropping the window labeled Window from the Interface Builder’s Cocoa Windows view onto the MainMenu.nib window. Once this is added to your project, you can select the window and open the Inspector window in order to configure the window. For example, you can specify whether the Minimize or Zoom button is active by selecting or clearing the Minimize and Zoom checkbox controls listed in the title bar section. You can also specify whether the window is displayed when the application starts by setting or clearing the Visible at Launch Time checkbox located in the lower half of the Inspector window’s Attributes view. If you want, you can convert the window into a brushed metal window by selecting the Has Texture checkbox. By default, any windows that you add are not displayed at application startup. If you want, you can programmatically display a new window within your script code. For example, you might add the following statement to the on click event handler for a button control in order to initiate the display of a window named main. set visible of window " main " to true
Similarly, you could stop displaying this same window using the following code statement. set visible of window " main " to false
Adding Drawers Mac OS X also supports the addition of a drawer to a window. A drawer is a window that slides out from under a parent window in an animated fashion. Drawers are often used to display a control or information that, while useful, is not used enough to justify making it readily available on the parent window. A drawer can only be displayed when its parent window is visible. You can add a drawer to an AppleScript Studio project by dragging and dropping an instance of the Window and Drawer object from the Interface Builder’s Cocoa Windows view onto
88
AppleScript Studio Programming for the Absolute Beginner
MainMenu.nib. This adds three new instances to MainMenu.nib, as shown in Figure 3.49 and outlined below.
FIGURE 3.49 Three new instances are added to the MainMenu.nib window when a Window Drawer object is added.
• Parent Window. Use this instance to add interface items to the parent window. • DrawContentsView. Use this instance to add interface items to the Drawer window. • NSDrawer. Use this instance to connect event handlers for the Drawer object. The following example demonstrates how to add a window with a drawer to an AppleScript Studio application. 1. Create a new AppleScript Studio application project. 2. Open the MainMenu.nib file and delete the default Window object by selecting it and pressing the Delete key. 3. Drag and drop an instance of the Window and Drawer object onto the MainMenu.nib folder. 4. Select the new parent window instance and open the Inspector window. Select the Visible at Launch Time option to have the window displayed when the application first starts. 5. With the Inspector window still open, select the NSDrawer instance located in the MainMenu.nib window. Modify its Preferred Edge attribute by selecting Left from the list of available options. Switch over to the AppleScript view and assign a name of drawerwindow to the object. This name will be used to programmatically control the display of the drawer in the AppleScript portion of the application. Close the Inspector window. 6. Double-click on the parent window instance to open it.
Chapter 3 • Building a Graphical User Interface
89
7. Drag and drop an instance of a button control onto the window. Double-click on it and type Hide to set its default title. Close the parent window. 8. Select the button control and open the Inspector window. Set up the connection with the button control’s on clicked event and the application’s default script file. 9. Add the following code statements inside the on clicked event handler. on clicked theObject tell window of theObject if title of theObject is "Show" then tell drawer "drawerwindow" to open drawer set title of theObject to "Hide" else tell drawer "drawerwindow" to close drawer set title of theObject to "Show" end if end tell end clicked TRI
CK
The statement tell window of theObject tells the application to target the window whose object initiated the on clicked event handler (in this case the button control located on the parent window). The next seven lines of code check to see if the button control displays the text Show or Hide. If it displays Show, a tell command is used to display the drawer, and the set command is used to toggle the text displayed on the button control so that it says Hide. The next several lines of code do just the reverse, closing the drawer and changing the button’s title back to Show. Because AppleScript is very English-like, you should have a pretty good feel for just what is going on in this code, even if the syntax seems a little awkward. Chapters 4–7 will help wash away this awkwardness by providing you with a solid review of AppleScript programming and syntax.
10. Build and run the application. Once started, click on the Show button. In response, the drawer will appear, and the title assigned to the Button control will change to Hide, as demonstrated in Figure 3.50. Clicking on the button again will close the drawer.
90
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.50 An example of a window with a drawer extending from its left-hand side.
Note that you can also add a drawer to an existing window by dragging and dropping the drawer window from the Interface Builder’s Cocoa Windows view onto the MainMenu.nib window and then configuring an existing window to use it. However, this is an advanced exercise that is outside the scope of this book.
Creating Utility Windows Utility windows are good for situations where you want to provide users with access to data or controls while they work on a particular task. Utility windows are designed to float on top of other windows, ensuring that they always remain visible while open. One way to create a utility window is to drag and drop an instance of the panel window onto the MainMenu.nib window and then enable the panel window’s utility window attribute. Figure 3.51 shows an example of a utility window created by configuring a panel window. Note the characteristically squared corners of the utility window. You can add interface controls and configure panel windows just like any other window. If desired, you could set the utility window to automatically open when the application starts by setting its Visible at Launch Time attribute. You can also programmatically control the display of panel windows.
Chapter 3 • Building a Graphical User Interface
91
FIGURE 3.51 An example of an application and a utility window.
Attaching a Sheet to a Window A sheet is a window that is attached to the top of another window. When displayed, a sheet is document modal, meaning that until the sheet is closed, the window to which it is attached cannot be accessed. You can use the Panel object as the basis for adding a sheet to a window. Sheets are typically used for managing the saving or printing of documents. Sheets are often used to collect confirmation information, such as permission to close a particular window. Because a sheet can only be associated with a particular window, they should not be used to perform an operation that affects more than one window. In some ways sheets resemble drawers. Both are associated with specific windows, and both are opened in an animated fashion to provide access to additional content or controls. However, while a drawer appears to open from behind or under a window, sheets open on top of them. In addition, drawers are not document modal like sheets and do not hide parent window contents. The following example demonstrates how to attach a sheet to a window and use it to require the user to respond before allowing any additional activity to continue. 1. Create a new AppleScript Studio application project and add a button control and assign a title of C lose to it. 2. Using the Inspector window, change the name of the window to main. Later, in the script portion of the application, you will use this name to reference this window. 3. Set up the button control’s on clicked event handler. 4. Drag and drop an instance of the Panel object onto the MainMenu.nib folder.
92
AppleScript Studio Programming for the Absolute Beginner
5. Using the Inspector window, change the name of the window to QueryPanel. Later, in the script portion of the application, you will use this name to control the display of the panel. 6. Open the new panel window and configure it as shown in Figure 3.52.
FIGURE 3.52 Using the Panel object as the basis for attaching a sheet to a window.
7. Set up the on clicked event handler associations for both button controls. 8. Add the following code statements inside the on clicked event handler on clicked theObject set confirmation to window "QueryPanel" if title of theObject = "Close" then display confirmation attached to window "main" end if if title of theObject = "No" then close panel confirmation end if if title of theObject = "Yes" then close panel confirmation close window "main" end if end clicked TRI
CK
The previous code example begins by using the set command to associate a reference to the panel (e.g., QueryPanel). The next three sets of statements execute when their associated button control is clicked. The first set of statements runs when the main window’s Close button is clicked and is responsible for displaying the panel window as a sheet attached to the main window. Rather than display the panel as a standalone window, the attached to parameter was added to the
Chapter 3 • Building a Graphical User Interface
93
statement in order to configure the panel to display as a sheet attached to the main window. The second set of statements runs when the No button on the panel window is clicked and is responsible for closing the panel window. Finally, the last set of statements executes when the Yes button is clicked and is responsible for closing both the QueryPanel panel window and the main window.
9. Build and run the application. Once started, click on the Close button. In response, a sheet will appear by dropping down from the top of the window, as demonstrated in Figure 3.53. If you click on No, the sheet will close, and the main window will remain visible. However, if you click on Yes, the sheet disappears, and the main window closes.
FIGURE 3.53 An example of a sheet dropping down from the top of a window.
Cocoa Data Views Interface elements located in the Cocoa Data view of the Interface Builder, shown in Figure 3.54, provide the building blocks needed to create windows that display data in different views. • Browser view. Used to display a list of data and organized in a hierarchical fashion. • Table view. Displays records in a table format. Individual columns are resizable, and the data inside the table can be edited. This control is often used to build a front-end view of data stored in a database. • Outline view. Used to display hierarchical data and is typically used to display the contents of file systems.
94
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.54 Cocoa Data views provide you with the ability to select data from various types of views. Three primary views are provided as outlined below.
Browser view
Table view
Outline view
Examples of each of these controls proliferate Mac OS X applications and windows. For example, Figure 3.55 demonstrates the use of the Browser view used by the standard Save As window.
FIGURE 3.55 An example of the Browser view in action.
Cocoa Container Views The last set of interface controls reviewed in this chapter is the Cocoa Container Views controls shown in Figure 3.56. These controls serve a number of different purposes, as listed next. • Tab view. Used to define an area in a window that consists of two or more views. These views can only be seen one at a time based on the currently selected tab.
Chapter 3 • Building a Graphical User Interface
95
• Box. Used to set up an area in a window that will be used to store and organize a group of related controls. • Custom view. Used to define an area in a window where custom graphics can be programmatically drawn. • Image view. Used to define an area in a window where a graphic can be displayed. This control can also be used to display images that are dropped and dragged on to it at runtime.
FIGURE 3.56 Cocoa Container controls let you group and control access to embedded controls.
BACK TO THE TYPO-MATIC TYPING TEST GAME It is time to turn your attention back to the Typo-matic Typing Test game. The primary point of focus for this game is on the development of the game’s graphical user interface using Interface Builder. Pay particular attention to the attribute changes that are made to the interface controls added to the application window.
Designing the Game In addition to showing you how to work with the slider control, the development of the application will also provide you with insight into the manipulation and control of interface controls, both from within Interface Builder and from program code. The development of the Typo-matic Typing Test game will occur in five distinct steps, as outlined below. 1. Starting Xcode and creating an AppleScript Studio application. 2. Designing the application’s graphical user interface using Interface Builder. 3. Making menu, window, and control attribute modifications and then attaching interface controls to event handlers. 4. The addition of the required AppleScript code statements. 5. Building and compiling the application.
96
AppleScript Studio Programming for the Absolute Beginner
At this point in the book, you have already gained significant experience in working with the Inspector window in order to manipulate windows and control attributes. In addition, you already have an understanding of how to attach interface controls to AppleScripts. Therefore, in this application and all the applications that follow, I will start providing higher-level instructions on attribute changes and interface controls to AppleScript connections, with the expectation that you will be able to make these changes without detailed line-by-line instruction. This will help to simplify the overall instruction required to build the application and provide additional room for me to describe particular aspects of the application.
Step 1: Creating a New Project If Xcode is not already started, start it now and then create a new AppleScript Studio project, as outlined in the following procedure. 1. Click on the File menu and select New Project. An Assistant will launch, displaying a listing of application templates. 2. Select the AppleScript Application template and click Next. 3. When prompted, specify Typo-matic as the file name for the application and then specify the folder where you would like to store this AppleScript Studio application. 4. Finish set up of this new Xcode project by clicking on the Finish button.
Step 2: Creating the User Interface The next step in the development of the Typo-matic Typing Test game is to put together its graphical user interface, as outlined in the following procedure. 1. Expand the Resources group located in the Groups & Files section of the Xcode Project window and then double-click on the MainMenu.nib file to start the Interface Builder. 2. Use the application window’s resize handle (located in the lower right-hand side of the window) to increase the size of the window until it is approximately 10 inches wide and 7 inches tall. 3. The game’s GUI will consist of seven small system font text controls, five text field controls, one slider control, and three button controls. Using the Cocoa Text Controls view of the Interface Builder window, add the first five small system font text controls and the five text field controls, as shown in Figure 3.57.
Chapter 3 • Building a Graphical User Interface
97
FIGURE 3.57 Building the data entry portion of the game’s graphical user interface.
4. Now, using the Cocoa Controls view of the Interface Builder window, add the slider control and the three button controls. 5. Finally, switch back to the Cocoa Text Controls view of the Interface Builder window and add two additional small system font text controls, as shown in Figure 3.58.
Step 3: Customizing Menus and Control Attributes, and Associating Controls with Event Handlers The overall construction of the game’s GUI is now complete. The next step is to configure the application’s menu system, modify window and control attributes, and then associate the button controls with the on clicked event handler, as outlined in the next several sections.
Menu Customization The first step in customizing the menu system for the Typo-matic Typing Test is to remove default menus and menu items that are not required by the application. For starters, like many small applications, the Typo-matic Typing Test game does not contain any help. So you should delete the Help menu by clicking on it and pressing the Delete key. Next, delete all of the menu items located on the Window menu except for the Minimize menu item. Even though the player is unlikely to use them, you may want to keep the Edit menu and its default list of menu items. Next, click on the File menu and remove everything but the Page Setup and Print menu items.
98
AppleScript Studio Programming for the Absolute Beginner
FIGURE 3.58 Adding the rest of the controls required to build the Typo-matic Typing Test GUI.
At this point, all of the basic menus and menu items required by the application are in place. However, before moving on to the next section, there is one more set of tasks to perform on the Application menu. These tasks involve customizing this menu to make it better represent the application, as outlined here. 1. 2. 3. 4.
Double-click on the Application menu and replace its name with Typo-matic. Modify the About Application menu item to read About Typo-matic. Modify the Hide Application menu item to read Hide Typo-matic. Modify the Quit Application menu item to read Quit Typo-matic.
Setting Control Attributes A number of changes need to be made to the window and controls that make up the graphical user interface. These changes, outlined in Table 3.2, must be made on the AppleScript and Attribute views of the Inspector window. Note that the button control labeled Grade Test has been disabled. It should only be available after a test has been started and will be enabled programmatically at the right moment in the code portion of the application.
Setting Up Event Handler Connections Next, set up each of the three button controls so that they will trigger the on clicked event handler whenever the user clicks on them. It is important that you trigger each button
Chapter 3 • Building a Graphical User Interface
TABLE 3.2 MODIFICATIONS TO THE APPLICATION WINDOW CONTROLS Object
Attribute
Modification
Window
Name Window Title Zoom Name Draw Text Border Line Breaking Layout Name Draw Text Border Line Breaking Layout Name Draw Text Border Line Breaking Layout Name Draw Text Border Line Breaking Layout Name Draw Text Border Line Breaking Layout Name Number of Markers Name Name Name Title Name Title Enabled Name Title
main Typo-matic Disable txtEntryOne Enabled Bordered Word Wrap Wraps txtEntryTwo Enabled Bordered Word Wrap Wraps txtEntryThree Enabled Bordered Word Wrap Wraps txtEntryFour Enabled Bordered Word Wrap Wraps txtEntryFive Enabled Bordered Word Wrap Wraps DifficultySlider 2 Easy Hard InstructionButton Instructions GradeButton Grade Test Disable StartButton Take Test
Text Fields
Text Fields
Text Fields
Text Fields
Text Fields
Slider Static Text Static Text Button Button
Button
AND
99
100
AppleScript Studio Programming for the Absolute Beginner
individually; otherwise, they won’t trigger the event handler. The procedure for doing so is outlined next. 1. Select a button control and, if necessary, click on the Show Inspector menu item located under the Tools menu to display the Inspector window. 2. Select the AppleScript option from the popup control located at the top of the Inspector window. 3. Click on the disclosure triangle just to the left of the Action event handler in order to expose the clicked event handler. Select this event handler by clicking on its associated checkbox control. 4. Select the radio button control associated with the Typo-matic.applescript script listed in the Script section at the bottom of the Inspector window. 5. Click on the Edit button. Xcode reappears, displaying its code editor. Repeat this procedure for the application’s other two button controls.
Step 4: Adding a Little Programming Logic Now it is time to add the AppleScript code that drives the Typo-matic Typing Test game. To help you understand the overall gist of what is going on, I have added numerous comments throughout the script. -- Typo-matic.applescript -- Typo-matic --
Created by Jerry Ford on 7/8/06.
--
Copyright 2006 __Jerry Lee Ford, Jr._. All rights reserved.
on clicked theObject --Event handler called whenever a button is clicked tell window of theObject --This code runs when the 'Take Test' button is clicked if name of theObject is "StartButton" then --Enable the slider and button controls set enabled of button "StartButton" to false set enabled of button "GradeButton" to true set enabled of slider "DifficultySlider" to false --Set up the slider control to return numeric data
Chapter 3 • Building a Graphical User Interface
set GameLevel to contents of slider ¬ "DifficultySlider" as integer --Clear out the display of test sentences set contents of text field "txtChallengeOne" to "" set contents of text field "txtChallengeTwo" to "" set contents of text field "txtChallengeThree" to "" set contents of text field "txtChallengeFour" to "" set contents of text field "txtChallengeFive" to "" --Clear out the display of test answers set contents of text field "txtEntryOne" to "" set contents of text field "txtEntryTwo" to "" set contents of text field "txtEntryThree" to "" set contents of text field "txtEntryFour" to "" set contents of text field "txtEntryFive" to "" --Reset the default text color to black for all Text Fields set text color of text field "txtEntryOne" to {0, 0, 0} set text color of text field "txtEntryTwo" to {0, 0, 0} set text color of text field "txtEntryThree" to {0, 0, 0} set text color of text field "txtEntryFour" to {0, 0, 0} set text color of text field "txtEntryFive" to {0, 0, 0} --Execute these statements when the player selects 'Easy' if GameLevel = 0 then --Assign the game's five sentences set contents of text field "txtChallengeOne" to ¬ "See spot run." set contents of text field "txtChallengeTwo" to ¬ "See spot jump high." set contents of text field "txtChallengeThree" to ¬ "See spot leap over the fence." set contents of text field "txtChallengeFour" to ¬ "See spot catch the frisbee in the air." set contents of text field "txtChallengeFive" to ¬ "See spot rest after a hard day of play in the park." else --Execute these statements when the player picks 'Hard'
101
102
AppleScript Studio Programming for the Absolute Beginner
--Assign the game's five sentences set contents of text field "txtChallengeOne" to ¬ "In the end there can be only one." set contents of text field "txtChallengeTwo" to ¬ "This above all else, to thine own self be true." set contents of text field "txtChallengeThree" to ¬ "If only one is to survive, then let that one be " & ¬ "Mighty Molly Ford." set contents of text field "txtChallengeFour" to ¬ "Not everything that can be measured counts and " & ¬ "not everything that counts can be measured." set contents of text field "txtChallengeFive" to ¬ "Alexander the Great looked out across his kingdom " & ¬ "& wept. For there were no more lands left to conquer." end if --Enable each text field control to allow player input set enabled of text field "txtEntryOne" to true set enabled of text field "txtEntryTwo" to true set enabled of text field "txtEntryThree" to true set enabled of text field "txtEntryFour" to true set enabled of text field "txtEntryFive" to true --This code runs when the 'Grade Test' button is clicked else if name of theObject is "GradeButton" then set noIncorrect to 0 --Declare variable used to track typos considering case --Tell AppleScript not to ignore case (*Perform tests to determine if the sentences typed by the player are identical to the test sentences.*) if contents of text field ¬ "txtChallengeOne" is not equal to contents ¬ of text field "txtEntryOne" then set text color of text field "txtEntryOne" to ¬ {65535, 0, 0} --Set text color to red set noIncorrect to noIncorrect + 1 --Track typos end if
Chapter 3 • Building a Graphical User Interface
if contents of text field ¬ "txtChallengeTwo" is not equal to contents ¬ of text field "txtEntryTwo" then set text color of text field "txtEntryTwo" to ¬ {65535, 0, 0} --Set text color to red set noIncorrect to noIncorrect + 1 --Track typos end if if contents of text field ¬ "txtChallengeThree" is not equal to contents ¬ of text field "txtEntryThree" then set text color of text field "txtEntryThree" to ¬ {65535, 0, 0} --Set text color to red set noIncorrect to noIncorrect + 1 --Track typos end if if contents of text field ¬ "txtChallengeFour" is not equal to contents ¬ of text field "txtEntryFour" then set text color of text field "txtEntryFour" to ¬ {65535, 0, 0} --Set text color to red set noIncorrect to noIncorrect + 1 --Track typos end if if contents of text field ¬ "txtChallengeFive" is not equal to contents ¬ of text field "txtEntryFive" then set text color of text field "txtEntryFive" to ¬ {65535, 0, 0} --Set text color to red set noIncorrect to noIncorrect + 1 --Track typos end if end considering --Display popup window showing test results display dialog "Number answered correctly = " & ¬ 5 - noIncorrect & ¬ "Number answered incorrectly = " & ¬ noIncorrect buttons {"OK"} --Enable slider and button controls set enabled of button "StartButton" to true
103
104
AppleScript Studio Programming for the Absolute Beginner
set enabled of button "GradeButton" to false set enabled of slider "DifficultySlider" to true --Disable Text Field control to prevent player input set enabled of text field "txtEntryOne" to false set enabled of text field "txtEntryTwo" to false set enabled of text field "txtEntryThree" to false set enabled of text field "txtEntryFour" to false set enabled of text field "txtEntryFive" to false --This code runs when the 'Instructions' button is clicked else if name of theObject is "InstructionButton" then --Display game instructions in a popup window display dialog "Use the slider control to set difficulty" & ¬ " level. Click on the Start button to play. " & ¬ "Retype each sentence exactly as shown " & ¬ "and then click on the Grade Test button." & ¬ " Errors will display in red." buttons {"OK"} end if end tell end clicked
Step 5: Testing the Execution of the Typo-matic Typing Test Game Application Okay, that’s everything. Assuming that you have not made any errors when keying in the previous script statements, everything should work as advertised. You are ready to build and test your application. If any errors occur, chances are they are in the AppleScript code. Recheck your typing and then compile and run your application again. TIP
You have invested a great deal of time and effort to get to this point in the book and to gain a solid understanding of how to work with Xcode and Interface Builder. These are both powerful and complex applications worthy of their own books. The time that you have invested will serve you well as you move into the next part of the book, learning the ins and outs of writing AppleScript code. As such, I am going to start emphasizing coding syntax, keywords, and commands and place less attention to the inner workings. Therefore, you may want
Chapter 3 • Building a Graphical User Interface
105
to bookmark this section and make a note to come back and re-examine this code that makes up the Typo-matic application once you have completed Chapters 4–7.
SUMMARY In this chapter, you learned how to work with Interface Builder in order to develop graphical user interfaces for your AppleScript Studio applications. This included learning how to add and align Cocoa controls on application windows as well as how to create and modify application menus. You received a review of the major Cocoa interface controls. You also learned about the different application windows that are available, including their strengths and weaknesses. On top of all this, you learned how to create the Typo-matic Typing Test game. Before moving on to the next chapter, why don’t you take a few extra minutes and review the following list of challenges to see if you can improve on the Typo-matic Typing Test game.
CHALLENGES 1.
2.
3.
At present, the graphical user interface for the Typo-matic Typing Test game does not provide a lot of initial information. Consider adding text at the top of the application window that instructs the player to click on the Take Test button to begin game play. In addition, you might want to add descriptive text above the slider control that briefly states its purpose. Currently, the application’s About window provides copyright information and the name of its creator. Modify the InfoPlist.strings file in order to display additional information in the About window. For example, you might want to include information about your website. The popup dialog that displays the player’s final score currently displays the number of sentences typed correctly. Considering adding additional text that further describes the information the player is seeing.
This page intentionally left blank
Part
II
Learning How to Write AppleScripts
Chapter 4
Working with Values, Variables, and Classes
Chapter 5
Applying Conditional Logic and Building Loops
Chapter 6
Working with Strings, Lists, and Records
Chapter 7
Organizing Scripts with Handlers
This page intentionally left blank
4
C H A P T E R
WORKING WITH VALUES, VARIABLES, AND CLASSES p to this point in the book, the focus has been on learning how to work with three primary AppleScript Studio components, Xcode, Interface Builder, and Cocoa Interface controls. Now it is time to switch your focus over to the development of the scripting code that is used to actually make your AppleScript Studio applications do what you want them to do. This is the first of four chapters dedicated to this task. This chapter introduces you to the fundamentals of AppleScript programming, with a focus on learning how to store, retrieve, and manipulate data.
U
Specifically, you will learn how to • Construct AppleScript code statements • Create and assign values to variables • Work with different types of classes
PROJECT PREVIEW: THE STAR TREK TRIVIA GAME This chapter’s game project involves the creation of a computer-based exam. The exam consists of five questions. To pass, the player must correctly answer at least three questions. The game’s GUI consists of two windows, a main window, and a drawer window that slides out from underneath the main window when opened.
110
AppleScript Studio Programming for the Absolute Beginner
The main window, shown in Figure 4.1, consists of text, button controls, a box control, a progress indicator control, and an image view control.
FIGURE 4.1 A graphic image representing a familiar Star Trek uniform insignia helps to emphasize the game’s main theme.
In addition to providing access to game instructions and to initiating game play, the main window uses a progress indicator control to indicate the player’s progress through the exam. To view game instructions, which are displayed on the interface’s drawer window, the player must click on the View Instructions button. In response, the drawer window is displayed, as demonstrated in Figure 4.2.
FIGURE 4.2 A drawer window displays instructions.
After displaying the drawer window, the button control labeled View Instructions is changed to display a label of Hide Instructions. Clicking on this button closes the window and restores the button control’s original View Instructions label. The exam itself consists of five multiplechoice questions made up of two or three possible answers, as demonstrated in Figure 4.3.
Chapter 4 • Working with Values, Variables, and Classes
111
FIGURE 4.3 The player selects an answer by clicking on the appropriate button.
Once every question has been answered, the player’s answers are graded, and the results of the exam are displayed, as demonstrated in Figure 4.4.
FIGURE 4.4 After grading the player’s answers, the game determines whether the player has passed the exam.
After viewing his exam results, the player is returned to the game’s main window. As Figure 4.5 shows, the progress indicator shows that the player has completed the entire exam. At this point the player can close the game or take the test again.
FIGURE 4.5 The game’s main window is displayed at the end of the game.
112
AppleScript Studio Programming for the Absolute Beginner
APPLESCRIPT—THE TECHNOLOGY Underneath the covers, AppleScripts communicate with and control other applications via Apple events. This underlying architecture, also known as interapplication communication, allows AppleScripts to send messages to other applications in order to automate specific application functions. Applications that accept Apple events are referred to as scriptable applications. A scriptable application is one that publishes its terminology in an internal dictionary outlining the Apple events that it understands and can react to. When an AppleScript runs within the context of an AppleScript Studio application, the applications that it interacts with and controls are viewed as objects. In addition, the windows and interface element controls that make up the application’s user interface are also viewed as objects. An object, in this context, is anything to which AppleScript can send an Apple event message. AppleScripts are always focused on a target. A target is the object to which messages are passed. One way to specify the target to which Apple event messages should be sent is to use the tell command. Using tell, for example, you can explicitly identify an external application as the target. Alternatively, you might use the tell command to target a window within your AppleScript Studio application. Another option for specifying a target is the of operator. Using of, you can specify the specific attribute that you wish to access for a given object. For example, you might want to access and change the title attribute of a particular button control on your application window. You’ll learn more about tell and of and see numerous examples of them in action later in this chapter.
APPLESCRIPT—THE SCRIPTING LANGUAGE In addition to providing the under-the-covers technology required to support interapplication communications, AppleScript is also a powerful little computer scripting language and, of course, is the programming language that drives AppleScript Studio applications.
Language Extensibility The idea behind AppleScript is that the core language should be kept small, with additional functionality and capabilities being provided by the applications that AppleScript communicates with and automates. Therefore, you will find that as a programming language, AppleScript has few built-in functions when compared to other programming languages like VBScript, JavaScript, Perl, and Python. For example, you will not find any built-in capability to work with regular expressions or perform complex trigonometry calculations in AppleScript. Nor will you find a large collection of string manipulation functions. You will not even find the ability to work natively with the Mac file system. Instead, by tapping into
Chapter 4 • Working with Values, Variables, and Classes
113
the appropriate external application, you can extend AppleScript capabilities as needed. For example, using capabilities provided by the TextEdit application, you could perform a host of string manipulation tasks; likewise, using Finder, you can create an AppleScript Studio application that can create, copy, move, and delete files and folders.
Language Features The AppleScript scripting language is made up of numerous commands. Commands are keywords that, when executed, perform a specific task. Commands are used in the formulation of statements. A statement is a line of program code. Examples of commands that you have already seen in action in this book include: • beep • display dialog • tell • set In order to use commands to properly formulate code statements, you must be familiar with AppleScript syntax and statement structure.
English-Like Syntax As has already been stated, AppleScript is an uncommonly English-like programming language. AppleScript commands closely resemble their English equivalents. For example, the tell command is used to instruct (or tell) AppleScript which application or resource Apple event messages should be sent to. The AppleScript language is also filled with common transitional words such as is, of, as, and the, which are used to formulate English-like expressions. For example, you might write an AppleScript statement that compares the value of two numbers as shown below. if x is greater than y
As you can see, this statement very closely mimics spoken English. A similar statement in most other programming languages would look like the example shown here (actually, this statement is perfectly valid for AppleScript as well). if x > y
In some ways, AppleScript’s English-like style is a little long winded. For example, most programming languages let you assign a value to a variable as shown here. x = 1
114
AppleScript Studio Programming for the Absolute Beginner
However, AppleScript does not support this highly conventional, albeit somewhat cryptic style. Instead, to assign a variable to a variable in an AppleScript, you must use a lengthier, descriptive statement as shown here. set x to 4
Line-Based Statements AppleScript also differs from many other programming languages in that it is line based, meaning that it does not require a termination character at the end of each line. In AppleScript, unless explicitly extended using a continuation character, each command ends at the end of the line it is written on. For example, in AppleScript, the following statement must be written on a single line. set visible of window "main" to false TRI
CK
The keyword the is provided by AppleScript strictly for the opportunity to make your AppleScript more English like. It is not required nor does it have any impact on any statements in which it is used. Its use is entirely optional and a matter of personal choice. Using the, you could, for example, modify the previous statement, making it a little more English-like, as shown below. set visible of the window "main" to false
In other programming languages, such as Perl, you can spread statements over multiple lines without generating an error. To spread a lengthy statement out over more than one line in AppleScript, you must use the continuation character (¬) as was described back in Chapter 1, “AppleScript Studio Basics.” TRI
CK
To add a continuation character to the end of an AppleScript statement, type Option+L. Note that after compiling your application, you may find that the location of the continuation character might move. There is nothing that you can do about this. When you see continuation characters used in the examples of this book, they show the placement of the continuation character prior to any adjustments that the compiler might make to the code statements.
When used, you cannot type anything else after the continuation character; otherwise, an error will occur. You will also get an error if the line that follows a continuation character is blank. Also, if you need to continue a string over more than one line, you must use the concatenation operator in addition to the continuation character as demonstrated here. display dialog "Once upon a time there were three little children " & ¬ "that this in a magical land."
Chapter 4 • Working with Values, Variables, and Classes
115
As you can see, the AppleScript concatenation operator is the & character. It allows you to logically combine two separate strings together to form a single string.
Code Blocks In addition to working with single line code statements or statements that are continued over two or more lines using the continuation character, AppleScript also supports the ability to define code blocks. A code block, sometimes referred to as a compound statement, is a group of statements executed as a unit. Code blocks are identified by an opening statement that identifies the type of block statement and a closing statement that begins with the end keyword. Event handlers, like the one shown here, are one type of code block. on clicked theObject (*Insert Code here*) end clicked
You can place as many script statement as necessary inside a code block. You have seen event handlers used on numerous occasions in the game applications created in this book. So far event handlers have been added to your AppleScript automatically through the Inspector window. However, as you will learn in Chapter 7, “Organizing Scripts with Handlers,” you can also create your own custom handlers and use them as a means to improve the overall organization and efficiency of your AppleScripts. Another example of a compound statement that you have seen used in various situations involves the use of the tell command. The tell command is used to identify the target on which commands are focused. The tell command can be used to create a single line statement using the syntax shown below. tell target to command target identifies the resource or external application to which a command should be directed,
and command is the command to be passed. For example, the following statement directs an open command to a drawer window named InstructionDrawer, thus causing the drawer to be displayed. tell drawer "InstructionDrawer" to open drawer
The tell command is commonly used to create code blocks that send multiple commands to the specified target. When used in this manner, the following syntax is applied.
116
AppleScript Studio Programming for the Absolute Beginner
tell target statements end tell
To see how to set up a tell code block, consider the following example. on clicked theObject tell window of theObject set title of theObject to "Hide" end tell end clicked TRI
CK
Note the use of the of operator in the preceding example to specify the attribute (Title) of the object (button) that is to be changed.
Here, an on clicked event handler, executed when the user clicks on a button control, executes a tell code block. The code block sends its embedded command (statement) to the window on which the button control resides. The command that is passed changes the Title attribute of the button control to Hide. TRI
CK
To save a few keystrokes, you could type the word end in place of end tell in the previous example. The next time you compile your AppleScript Studio application, the keyword tell will be added automatically to the end statement for you. Also, you should take note that when you compile your application, the contents of compound statements will be indented automatically, making your program code easier to read and understand.
MANAGING DATA USING VARIABLES Just about any AppleScript Studio application needs to manipulate data in some manner. One way of storing individual pieces of data within AppleScripts is to use variables. A variable is a pointer to a location in memory where data is stored. Using variables, you can, for example, collect and store user inputs and then examine and manipulate those inputs at different points within the AppleScript.
Storing Values in Variables One way that AppleScript lets you store values in variables is with the set command. The syntax of the set command is outlined here. set variablename to value
Chapter 4 • Working with Values, Variables, and Classes
117
variablename represents the name assigned to the variable, and value is a placeholder repre-
senting the data associated with the variable. For example, the following statement demonstrates how to define a variable named counter and assign it an initial value of zero. set counter to 0
If you later want to change the value that is assigned to the counter variable, you may do so using another set command as shown here. set x to 11 TRI
CK
AppleScript allows you to modify a variable’s values by modifying its current value as demonstrated here. set x = x + 1
In this example, the value of x is incremented by 1 and then reassigned to itself. The end result is that if x started out with a value of 10, it is incremented and changed to 11.
If you want, rather than declaring multiple variables one at a time, AppleScript will allow you to assign groups of variables using a list as a shortcut, as demonstrated here. set {x, y, z} to {10, 20, 30}
Here, the variable x is assigned a value of 10. The variable y is assigned a value of 20. Lastly, the variable z is assigned a value of 30. Note that this example uses two lists, one on each side of the to keyword, and that each list is enclosed within {} characters.
Retrieving Variable Values Variable values can be retrieved using the get command, which has the following syntax. get variablename
For example, the following statement demonstrates how to retrieve the value assigned to a y variable and assign it to an x variable. set x to get y
However, use of the get command is superfluous and can be omitted, as demonstrated next. As a result, you will almost never see anyone use it. set x to y
118
AppleScript Studio Programming for the Absolute Beginner
NAMING VARIABLES AppleScript has rules that govern the formulation of variable names. For starters, variables must begin with either a letter or an underscore character. The remaining characters that make up variable names can consist of any combination of the characters outlined in Table 4.1. Variable names cannot be assigned the same names as AppleScript keywords, like tell, open, close, etc. In addition, you cannot assign variables the same names as any terms that make up the dictionary of any automated applications. The following list provides examples of valid variable names. userName x COUNTER __temp__ x999
Consists of uppercase and lowercase characters Consists of a single lowercase character Consists of all uppercase characters Consists of lowercase characters and underscore characters Consists of a lowercase character and numbers
To help give you an idea of how not to name your variables, consider the following list of invalid variable names. 1stname dollar$ tell TRI
CK
Variable names cannot begin with a number. Variable names cannot contain special characters. Variables cannot be named after keywords. If you feel too restricted by AppleScript’s rules for naming variables, you do have another option. AppleScript lets you define special variable names by allowing you to define the variable name inside a pair of matching vertical bar characters (|) using the following syntax. set |variablename| to value
When using vertical bars, you can assign any character you want as part of the variable name, including special characters. You can even use AppleScript
TABLE 4.1
RULES
FOR
NAMING VARIABLES
Characters
Description
a-z, A-Z 0-9 _
Uppercase and lowercase letters Numeric digits The underscore character
Chapter 4 • Working with Values, Variables, and Classes
119
commands and language keywords. For example, by enclosing them in vertical bars, all of the following variable name assignments are legal. set |tell| to "Once upon a time…" set |$5| to "Five Bucks" set |my-birthday| to "November 1964"
When defined within matching vertical bars, AppleScript enforces case sensitivity; therefore, the following two variables names would not be viewed as being equal. |my-birthday| |My-Birthday|
Lastly, when you need to refer to a specially named variable elsewhere within your AppleScript, you must include the vertical bars as part of the variable’s name as demonstrated here. set |x| = 5 set y = 10 set z = 0 set z = y + |x|
-- Equals 15
Case Sensitivity AppleScript is a case-insensitive language. It does not differentiate between different uses of capitalization within the spelling of variable names. Therefore, to AppleScript, each of the following variable references is the same thing. • username • userName • UserName • USERNAME • UsErNaMe Another interesting point about the way that AppleScript handles variables is that if you use different case spelling for the same variable’s name, AppleScript will automatically go back through and find each instance of that variable name within your AppleScript and convert it to make each instance match the capitalization of the first instance that it finds. To see what I mean, start up a new AppleScript Studio application, add a button control to the default application window, and assign the following code statements to the button control’s on clicked event handler. Take note of the different capitalization of the variable username as you key in the statements.
120
AppleScript Studio Programming for the Absolute Beginner
on clicked theObject set username to "William Ford" set UserName to "Alexander Ford" set USERNAME to "Molly Ford" end clicked
When you are done, click on the Build button. In response, your code is compiled, and you will see that the spelling of each instance of username has been modified to match the case of the first instance, as shown here. on clicked theObject set username to "William Ford" set username to "Alexander Ford" set username to "Molly Ford" end clicked
Undefined Variables AppleScript variables are not assigned default values. In order to use a variable, it must contain a value; otherwise, an error will occur and you’ll get a The variable variablename is undefined error, as demonstrated in Figure 4.6.
FIGURE 4.6 An error is generated if AppleScript finds a variable without an assigned value.
AppleScript does not require that variables be declared prior to their usage. This makes AppleScript very different from many other programming languages. It also makes it very easy for you to make mistakes because if you accidentally mistype a variable name in your programming code, rather than flag it as an error, AppleScript simply declares it as a new variable, producing unpredictable results. TIP
As I have already stated, it is important that you document your AppleScript code. One way to do so is to imbed comments. Another way to help document your scripts is to assign descriptive names to your variables. This will help to make your code statements easier to understand. For example, you might name a variable that will used to store a user’s name userName. Likewise, you might name a variable set up to store a value representing input collected from the user as userInput.
Chapter 4 • Working with Values, Variables, and Classes
121
WORKING WITH DIFFERENT VARIABLE CLASSES In AppleScript, variables are not strongly associated with specific data types. In other words, AppleScript will let you assign any type of data to any variable, even if that variable already contains a different type of data. Any variable that has been assigned a value has a defined data type, also referred to as its class. AppleScript supports a number of different classes, as discussed in the sections that follow.
The String Class You have seen the String class used many times already in this book. A string is created by enclosing one or more characters inside a pair of quotation marks as demonstrated below. "In the end there can be only one."
Strings can be used to display text using the display dialog command. Strings can also be assigned to variables. You’ll learn more about how to work with strings in Chapter 6, “Working with Strings, Lists, and Records.”
The Real Class The Real class is a numeric data type that represents real numbers. A real number is one that includes a decimal point, such as 99.9 or –10.4. Real numbers are used to display numeric values and to perform mathematic calculations. Real numbers can also be represented using scientific notation. Real numbers are used to store numeric values in the range of –1.797693e308 to 1.797693e308. TRI
CK
AppleScript often converts real numbers written in scientific notation to their non-scientific equivalent when compiling the script file. For example, AppleScript will automatically convert 10.5e-4 to 0.00105. However, this behavior is not consistent and may not happen all the time.
The Integer Class The Integer class is a numeric data type that represents whole numbers (e.g., numbers without a decimal point). The Integer class supports a much smaller range of values than the Real class. Its supported range is –536870911 to 536870911. Integers are used in place of real numbers to more efficiently store numeric data within its range. If you are working with a variable of integer data type and assign it a value outside of its supported range, AppleScript will automatically covert it to a real number.
122
AppleScript Studio Programming for the Absolute Beginner
The Date Class The Date class is used to store and manipulate date and time data. AppleScript stores date and time in the following format. weekday, month day, year hh:mm:ss ampm
Table 4.2 outlines the range of values supported by each of these date parameters. You can use the current date command to retrieve the current date and time as demonstrated here. set d to current date
When executed, this command will retrieve a value similar to that shown here. Sunday, January 12, 2007 2:03:19 PM
Classes like the Date class have different properties from which you can programmatically retrieve data about a given value. For example, the Date class provides access to the properties shown in Table 4.3. Using the properties listed in Table 4.3, you can retrieve date values as demonstrated in the following example. set d to current date display dialog d as string
-- Displays Sunday, January 12, 2007 2:03:19 PM
display dialog weekday of d as string
-- Displays Sunday
display dialog time string of d as string
TABLE 4.2
-- Displays 2:03:19 PM
DATE PARAMETERS
Parameter
Range
weekday month
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday January, February, March, April, May, June, July, August, September, October, November, December 1–31 A four character year A two character number representing hours A two character number representing minutes A two character number representing seconds am or pm
day year hh mm ss ampm
Chapter 4 • Working with Values, Variables, and Classes
TABLE 4.3
DATE PROPERTIES
Property
Description
year month
A four character year A value of January, February, March, April, May, June, July, August, September, October, November, or December An integer in the range of 1–31 An integer representing the number of hours since midnight An integer in the range of 1–60 An integer in the range of 1–60 An integer representing the number of seconds since midnight A value of Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday A string formatted as weekday, month, day, year A string formatted as hh:mm:ss AM/PM A string formatted as mm/dd/yyyy
day hours minutes seconds time weekday date string short date string time string
TRI
CK
123
By default, AppleScript will automatically convert a variable to the appropriate data type based on the data type of the value assigned to it. Data type specification controls how AppleScript treats a given value and the properties that are associated with it. Sometimes it is necessary for you to coerce a value’s data type in order to work with it. For example, the display dialog command is used to display a text string. If you pass it a number instead of a text string, AppleScript will automatically convert it to a string and display it. However, if you pass a date value to the display dialog command, you may not get the results you expect. To ensure that the value passed to the display dialog command is treated as a string, you can use the as operator to explicitly specify the appropriate class to be used. For example, in the three preceding display dialog statements, the as string was added to the end of each statement. Had the as string been left off the first display dialog statement, an error would have been generated. In Chapter 5’s game project, the AppleScript Studio Guess a Number game, you will learn how to use the slider control as a means of allowing the player to select a number from a range of numbers. The slider control returns a real number. However, the AppleScript Studio Guess a Number game requires that all numbers used in the game be integers. As a result, you will have to coerce the value returned by the game’s slider control from a real number to an integer.
When executed, this example displays three popup dialog windows, each showing a different value. You can also use Date class properties to modify date values as demonstrated here.
124
AppleScript Studio Programming for the Absolute Beginner
set d to current date set day of d to 1 set year d as to 2008 display dialog day of d as string display dialog year of d as string
-- Displays 1 -- Displays 2008
The Boolean Class The Boolean class is used to represent a value that is either true or false. Many operations in AppleScripts involved the comparison of values, the result of which is a true or false value. As you’ll learn in Chapter 5, “Applying Conditional Logic and Building Loops,” the if statement, which is used to facilitate conditional logic, results in a Boolean value that is then used to drive the logical flow of script logic. TRI
CK
AppleScript supplies the class command as a means of determining the class or data type assigned to a given value. The use of this command is demonstrated here. set d to current date set x to 100 set y to 999999999999999 set z to "Hello World!" set b to true display dialog class of d as string
-- Displays date
display dialog class of x as string
-- Displays integer
display dialog class of y as string
-- Displays real
display dialog class of z as string
-- Displays string
display dialog class of b as string
-- Displays boolean
BACK TO THE STAR TREK TRIVIA GAME Now it is time to start working on the Star Trek Trivia game. The primary point of focus for this game is on the use of variables to store and retrieve data collected from the user and generated by the application. In addition, you should take note of the construction of code statements that interact with and control the user interface.
Designing the Game During the development of the Star Trek Trivia game, you will learn how to work with a number of new controls. For starters, the game’s GUI will be made up of a window and drawer. You will also learn how to add graphics and sound effects to AppleScript Studio applications.
Chapter 4 • Working with Values, Variables, and Classes
125
Finally, you will learn how to work with and control the automation of the progress indicator control. As with all of the applications in this book, the Star Trek Trivia game will be created in five steps, as outlined here. 1. Start Xcode and create a new AppleScript Studio application named Star Trek Trivia. 2. Design the application’s GUI using Interface Builder. 3. Configure the game’s menu, window, and drawer and control attributes and then attach interface controls to event handlers. 4. Add the AppleScript code statements required to make the application work. 5. Compile and test the application.
Step 1: Creating a New Project If it is not already started, start Xcode and create a new AppleScript Studio project, as outlined in the following procedure. 1. Click on the File menu and select New Project. An Assistant is launched, displaying a list of application templates. 2. Select AppleScript Application template and click on Next. 3. When prompted, specify Star Trek Trivia as the file name for the application and then specify the folder where you would like to store this AppleScript Studio application. 4. Click on the Finish button.
Step 2: Creating the User Interface The next step in the development of the Star Trek Trivia game is to assemble its graphical user interface, as outlined in the following procedure. 1. Locate the MainMenu.nib file located in the Resources group and then double-click on it to start the Interface Builder. 2. Click on the icon representing the default application window in the MainMenu.nib window to select it and then delete it by pressing the Delete key. 3. Click on the Cocoa Windows button located in the Cocoa Controls palette and then drag and drop an instance of the window and drawer window onto the MainMenu.nib window. In response, three icons representing the drawer, parent windows, and drawer content are added to MainMenu.nib. 4. Use the application window’s resize handle to change the size of the window until it is approximately 7.5 inches wide and 4.25 inches tall. 5. Use the DrawContentView window’s resize handle to change the size of the window until it is approximately 4.25 inches wide and 4.25 inches tall.
126
AppleScript Studio Programming for the Absolute Beginner
6. The drawer window consists of two controls. The first is a system font text control whose Title attribute should be set to Instructions, and the second is a text field control. 7. Double-click on the text field control and enter the following text. Star Fleet Academy is now accepting applications for the upcoming freshman class. Before submitting your application, you must correctly answer at least three of the five questions that make up the text. At this point the drawer window should resemble the example shown in Figure 4.7.
FIGURE 4.7 The drawer window consists of two controls and is used to display game instructions.
8. Now it is time to lay out the interface for the main window. Begin by dragging and dropping an instance of the system font text control to the upper left-hand corner of the window. Double-click on it and enter Welcome to the Star Trek Trivia Game!. TRI
CK
Note that the text displayed in the system font text control needs to be increased in size and made bold. To apply a bold font, select the control and then click on the Format menu, select the Font submenu, and click on the Bold menu item. To increase the size of the text that is displayed in this control, select the Format menu, Font submenu, and Bigger menu item. You will need to perform this operation four times to increase the text font to the appropriate size. Note that you may also have to increase the space allocated to the system font text control in order to allow all of its assigned text to be displayed.
9. The main interface will display a graphic image representing a yellow Star Trek badge. You will find a copy of this graphic, named STBadge.jpg, located on the book’s companion website (www.courseptr.com/downloads). Drag and drop this file into the Resources group located inside the Groups & Files pane of the Xcode Project window. In response,
Chapter 4 • Working with Values, Variables, and Classes
10.
11.
12. 13.
14.
15.
16.
127
a sheet appears. Select the Copy Items into Destination Group’s Folder (if needed) option and click on the Add button. Next, drag and drop an instance of the image view control located on the Cocoa Containers View of the Interface Builder palette onto the upper right-hand corner of the main window and resize the control so that it is approximately 1.5 inches tall and 1.25 inches wide. Drag and drop the STBadge.jpg file from the Xcode Project window onto the image view control located on the MainMenu.nib window. A sheet will then appear on the MainMenu.nib window asking for confirmation. Click on the Add button. Now drag and drop an instance of the STBadge icon from the MainMenu.nib window onto the image view control located on the application’s main window. Drag and drop an instance of the button control onto the middle of the application’s main window. Double-click on the button control and enter Begin E xam to set its Title attribute. Drag and drop another instance of the button control onto the lower left-hand corner of the application’s main window. Double-click on the button control and enter V iew Instructions to set its Title attribute. Drag and drop an instance of the horizontal box control onto the lower portion of the application’s main window. Position the control just above the View Instructions button and resize the horizontal box control so that it runs almost the entire width of the window. Finally, drag and drop an instance of the progress indicator control onto the lower righthand side of the application’s main window. Increase the width of the control until it is approximately four inches wide.
At this point, the game’s main window should be fully assembled, as demonstrated in Figure 4.8.
FIGURE 4.8 The game window contains a number of different types of controls.
128
AppleScript Studio Programming for the Absolute Beginner
Step 3: Customizing Control Properties The overall construction of the game’s user interface is now complete. It is now time to configure the application’s menu system, modify its window and drawer, and then set various control attributes and associate the game’s two button controls with the on clicked event handler, as outlined in the next several sections.
Menu Customization The first step in customizing the menu system for the Star Trek Trivia game is to remove unnecessary menus and menu items that were provided by default to the application. For starters, you should delete the Help menu by clicking on it and pressing the Delete key. Next, delete all of the menu items under the Window menu except for Minimize. Select the Edit menu and press Delete to remove it and its contents. Click on the File menu and remove everything but the Page Setup and Print menu items. Lastly, you need to customize the Application menu as outlined here. 1. 2. 3. 4.
Double-click on the Application menu and replace its name with S TTrivia. Modify the About Application menu item to read About STTrivia. Modify the Hide Application menu item to read Hide STTrivia. Modify the Quit Application menu item to read Q uit STTrivia.
Setting Control Attributes As with any AppleScript Studio application, a number of modifications must be made to the window, drawer, and controls that make up the user interface. These changes are outlined in Table 4.4 and must be made from the Inspector window’s AppleScript and Attribute views. Note that to assign a name to the drawer window, you must click on the NSDrawer1 icon located in the MainMenu.nib window and then use the Inspector window to assign its name. TRI
CK
The Sounds view of the MainMenu.nib window contains a number of sound files that you can use to add audio sounds to your AppleScript Studio applications. In Table 4.4, the Submarine sound was associated with the button that controls the display of the drawer window by simply typing its name into the appropriate button control’s Sound attribute field.
Setting Up Event Handler Connections Now it is time to set up both of the game’s two button controls so that they will trigger the on clicked event handler whenever they are clicked. Both of the button controls must be configured to respond to the clicked event; otherwise, they will not be able to trigger their associated code located in the AppleScript’s event handler.
Chapter 4 • Working with Values, Variables, and Classes
TABLE 4.4
MODIFICATIONS OF THE APPLICATION WINDOW, DRAWER, AND CONTROLS
Object
Attribute
Modification
Window
Name Window Title Zoom Visible at launch time Name Name Sound Name Border Name Indeterminate Name Layout Line Breaking Editable
main Star Trek Trivia Disable Enabled btnBegin btnInstructions Submarine STBadge None pgbLevel Cleared InstructionDrawer Wraps Word Wrap Cleared
Button Button Image view Progress Indicator Drawer Text Field
TIP
129
You have performed this exercise a number of times already in this book, so I won’t provide a step-by-step procedure for doing so this time. If necessary, you can refer to the previous chapter’s game script for detailed instructions.
Step 4: Adding a Little Programming Logic It is time to develop the AppleScript statements that drive the Star Trek Trivia game. In order to develop the required program code, you will have to learn how to work with a number of new scripting statements. To help define and explain these statements, I will pause along the way and provide you with additional explanation. I will also embed comments throughout the program code to further help explain what is happening. Two button controls in the Star Trek Trivia game are used to control overall game play. The first button is the Begin Exam button, which when clicked will begin presenting the player with the questions that make up the exam. The second button is the View Instructions button, which when clicked displays a drawer window that provides the player with additional instruction.
130
AppleScript Studio Programming for the Absolute Beginner
The first thing you need to do for both of these button controls is to open the Inspector window and enable the clicked event. Once you have completed this task, the following code statements should be visible in your project’s Star Trek Trivia.applescript file. TR
AP
You must configure the clicked event for each button control; otherwise, any button control that you do not configure will not be able to initiate any actions, even if you add the required scripting statements inside the application’s AppleScript file.
-- Star Trek Trivia.applescript -- Star Trek Trivia --
Created by Jerry Ford on 7/16/06.
--
Copyright 2006 __MyCompanyName__. All rights reserved.
on clicked theObject (*Add your script here.*) end clicked
The first four lines are comments. If you want to change the copyright comment, do so by modifying the InfoPlist.strings file (English) located under Resources in the Groups & Files pane. The last three lines are the AppleScript’s on clicked event handler, which is automatically added to the AppleScript when you configure the two button controls’ clicked events. TRI
CK
As you will learn in later chapters, you can add more than one AppleScript to an AppleScript Studio application. One of the reasons for doing so is to set up one script for each unique control added to your application. This allows you to group all of the code statements associated with a given control in a script dedicated to that control. This is helpful in applications with numerous controls and lots of code. However, in a small application like the Star Trek Trivia game, it is easier just to go with a single AppleScript and to add a little extra code to it to help determine which control has initiated the execution of the AppleScript. This is accomplished by examining the value of theObject, which you will notice is defined at the end of the on clicked statement. By checking the value assigned to theObject, you can determine which interface control called the AppleScript (e.g., the Begin Exam or View Instructions button).
From this point on, all the program code that you will add to the AppleScript will go inside the on clicked event handler. So, let’s begin by adding the following two statements (inside the on clicked event handler).
Chapter 4 • Working with Values, Variables, and Classes
131
tell window of theObject end tell
These two statements define a compound statement or code block. The opening statement uses the tell command to instruct AppleScript to direct all embedded commands at the window that contains the interface control that initiated the execution of the AppleScript. In other words, if the player were to click on the Begin Exam button, this statement would direct all commands to the window named main since it contains the Begin Exam button. The end tell statement simply marks the end of the compound statement. The rest of the code statements that will make up this AppleScript are all directed at the main window; therefore, all of the remaining code statements will be embedded inside the tell compound statement. The first set of statements to be added follows. -- Declare and assign default values to script variables set noCorrect to 0 -- Keep track of correct answers set noIncorrect to 0 -- Keep track of incorrect answers set rawPercentage to 0 -- Used to calculate grade set grade to 0 -- Used to store test grade -- Define variables representing answers to test questions set answer1 to "" set answer2 to "" set answer3 to "" set answer4 to "" set answer5 to ""
As you can see, these statements consist of a series of set statements that define each variable used in the AppleScript, assigning each variable a default value. Comments have been added to document the purpose of each variable. The next set of code statements addresses the actions that need to occur when the View Instructions button is clicked. Add these statements by keying them in immediately after the last variable declaration statement. TIP
The game makes additional instructions available to the player by displaying them on a drawer window attached to the game’s main window. The display of the drawer window is controlled by clicking on the button control named btnScore. Initially this button control’s Title attribute is assigned a value of View Instructions. When clicked, it will initiate the display of the drawer window and
132
AppleScript Studio Programming for the Absolute Beginner
then change its Title attribute to Hide Instructions, thus toggling the label displayed on the button control. -- Execute code that controls the display of the drawer window if title of theObject is "View Instructions" then tell drawer "InstructionDrawer" to open drawer -- Open drawer set title of theObject to "Hide Instructions" -- Change title text else if title of theObject is "Hide Instructions" then tell drawer "InstructionDrawer" to close drawer –- Close drawer set title of theObject to "View Instructions" -- Change title text end if
These statements are controlled by an if…else if code block. The if…else if code block is explained in great detail in Chapter 5. For now, here’s a simple explanation of how this code block works: The opening if statement examines the title attribute of the interface control that has initiated an action as specified by theObject (e.g., the action of clicking on a button control) to see if it’s the button control labeled View Instructions. If it is, the two statements that immediately follow are executed. If this is not the case, then the else if statement executes and checks to see if the button that was clicked has a title of Hide Instructions. And if it does, the two statements that immediately follow are executed. The statements that you should be focusing on for right now are the two pairs of statements embedded inside the if…else if code block. The first of these two sets of statements uses the tell command to direct the instructions provided by the rest of the statement to the drawer window named InstructionDrawer, telling it to open. The next statement sets the label (e.g., the Title attribute) displayed by the button control to Hide Instructions, thus letting the player know that by clicking on the button again the drawer window will close. The second set of statements embedded inside the if…else if code block is responsible for closing the drawer window and restoring the original View Instructions label on the button control. At this point, all that remains is to supply the code statements associated with the button control labeled Begin Exam. When clicked, this code will display each of the five exam questions and then analyze the player’s answers to these questions before displaying the player’s exam score. These first step in entering these code statements is to set up an if statement that determines when the Begin Exam button has been clicked. These statements, shown
Chapter 4 • Working with Values, Variables, and Classes
133
next, should be added immediately following the last set of code statements and before the end tell statement that you keyed in earlier. -- Execute code that collects player answers to test questions if title of theObject is "Begin Exam" then end if
Again, the opening if statement checks the Title attribute of the button control that was clicked to make sure that it is Begin Exam. If it is, the code statements that you are about to place inside this if statement code block will be executed. Otherwise, the if statement code block and all of the code statements inside it are skipped. The first statements that you should add inside the if statement code block follow. tell drawer "InstructionDrawer" to close drawer -- Close drawer --Reset the progress indicator back to zero set content of progress indicator "pgbLevel" to 0
Because the drawer window may or may not be open when the player decides to click on the Begin Exam button, the first statement uses the tell command to close the drawer window. If the drawer window is open, it will close. If it is closed, the command is ignored. Since it is possible that the player may want to take the exam more than once, it is necessary to reset the value of the game’s progress indicator control back to its default value of zero in order to get it ready to begin tracking the exam’s progress. At this point we know that the drawer window is closed and that the progress indicator control has reset to its default value. It is time to begin displaying test questions and to update the progress indicator control so that it reflects the current percentage of the exam that has been completed. This is accomplished by adding the following code statements. --Ask 1st test question set answer1 to the button returned of (display dialog ¬ "Question 1:
The laws that govern the actions of Star " & ¬
"Fleet personnel are referred to as Prime Directives." ¬ buttons {"True", "False"}) -- Increment the progress indicator to show that the first of five -- answers has been collected tell progress indicator "pgbLevel" to increment by 20
134
AppleScript Studio Programming for the Absolute Beginner
The first code statement shown above sets the value of a variable named answer1. It does so by displaying a popup dialog window with buttons labeled True and False. This popup dialog window is displayed using the display dialog command. You will often see the display dialog statement used in applications to display messages. However, in this case it has been embedded in a set statement. This allows the set statement to determine which button the player clicks. This is accomplished by setting the value of the answer1 variable to the value of the button that is returned by (or returned of) the display dialog statement, which in this case will either be True or False.
In the Real World One of the most commonly performed tasks in any window-based application is to display messages and capture text input from the user. While you can certainly create a new custom window each time you want to display a text message or collect a small piece of data from the user, most AppleScript and AppleScript Studio programmers instead take advantage of the display dialog command. While AppleScript has its own display dialog command, when used inside an AppleScript Studio application, the AppleScript Studio version of the display dialog command is used. This display dialog command displays a simple popup window that allows you to display a text message and collect user input. Depending on how you specify the display dialog command, this input can be either the name of a button control clicked by the user or text keyed in by the user. In its simplest format, the display dialog command displays a message and two button controls, OK and Cancel, using the following syntax. display dialog “Message text” This use of the display dialog command is very helpful when you only need to display text that needs to be read by the user. The display dialog command is very flexible and supports a number of optional parameters, as outlined here. • attached to window windowname. When specified, turns the popup dialog that is displayed into a sheet attached to the specified window. • button list. Specifies a list of up to three buttons in the format of {button1, button2, button3}.
Chapter 4 • Working with Values, Variables, and Classes
135
• default answer text. When specified causes the popup window to display with a text field showing the specified default answer, which the user can either accept or overtype. • default button buttonname. When specified, sets the button that is selected by default in the event the user responds by pressing the Return key instead of clicking on a specific button. • giving up after integer. Forces the popup window to close if the user does not respond to it within a specified number of seconds. • with icon iconname. Allows you to specify the name and path of an icon that you would like displayed inside the popup dialog window. Using optional parameters, you can customize the appearance and functionality of popup dialog windows. For example, the following statement displays a popup dialog window that displays a short message, prompting the user to click on either of two buttons. display dialog "It is raining today." buttons {"True", "False"}) The problem with this example is that is does not provide a means of capturing the user’s button selection. This can be accomplished by modifying the example as shown next. set answer1 to the button returned of ("It is raining today." ¬ buttons {"True", "False"})
Once the value of answer1 has been assigned, the last statement shown above updates the display of the progress indicator control by using the tell command to instruct the progress indicator control named pgbLevel to increment its value by 20. Given that the progress indicator control has a default range of 0.0 to 100.0, incrementing it by 20 has the effect of making the control update its display so that it shows as being 1/5th full. Now, you need to key in the code required to display the remaining four exam questions, which is shown here. --Ask 2nd test question set answer2 to the button returned of (display dialog ¬ "Question 2: When initially beaming down to an unknown " & ¬ "planet, the correct setting for phaser weapons is: " ¬ buttons {"Stun", "Kill"}) -- Increment progress indicator to show that two of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20
136
AppleScript Studio Programming for the Absolute Beginner
--Ask 3rd test question set answer3 to the button returned of (display dialog ¬ "Question 3: What is the appropriate speed of travel when" & ¬ " a star ship is leaving space dock? " ¬ buttons {"Warp 10", "Light", "Impulse"}) -- Increment progress indicator to show that three of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20 --Ask 4th test question set answer4 to the button returned of (display dialog ¬ "Question 4: The neutral zone is a term that refers to " & ¬ "an area of space where any space traveler is free to go." ¬ buttons {"True", "False"}) -- Increment progress indicator to show that four of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20 --Ask 5th test question set answer5 to the button returned of (display dialog ¬ "Question 5: According to existing Federation treaties, " & ¬ "are star ships permitted to use cloaking technology?" ¬ buttons {"Yes", "No"}) -- Increment progress indicator to show that five of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20
As you can see, each of these four sets of code statements is simply a small variation of the first set of statement, the primary differences being that the questions and the list of buttons are different. Now it is time to add the program code that analyzes the player’s answers and determines which exam questions were answered correctly and which were answered incorrectly. Begin by adding the following set of statements to your AppleScript. --Analyze test results if answer1 = "True" then -- If the player selected "True" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect
Chapter 4 • Working with Values, Variables, and Classes
137
set noIncorrect to noIncorrect + 1 -- Answer is correct end if
This set of statements uses an if…else code block to examine the player’s answer to the first question, which you will remember was stored in a variable named answer1. The first statement checks to see if the value assigned to answer1 (e.g., the button clicked by the player) was equal to True. Since the answer to the first question was true, the value assigned to a variable name noCorrect is incremented by one. This variable was declared at the beginning of the script and was assigned an initial value of zero. By incrementing it each time the player correctly answers an exam question, you are able to keep track of the total number of correctly answered questions. In the event that the player clicks on the False button, the else portion of the if…else code block is executed and the value of noIncorrect is incremented by one. The code required to grade the next four exam questions is listed next. if answer2 = "Stun" then -- If the player selected "Stun" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if if answer3 = "Impulse" then -- If the player selected Impulse" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if if answer4 = "False" then -- If the player selected "False" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if if answer5 = "No" then -- If the player selected "No" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if
138
AppleScript Studio Programming for the Absolute Beginner
As you can see, these four sets of statements are simply variables of the first set of statements that analyzed the first exam question. Once the answer to every question has been analyzed, it is time to determine whether the player passed the exam. This is accomplished by adding the following statements immediately after the preceding statements. -- Determine whether the player passed the exam if noCorrect • 3 then -- Three or more correct answers passes set grade to "Passed" else --Less than three correct answers fails set grade to "Failed" end if
Another if…else statement code block is used in order to determine whether the player passed the exam. If the value of noCorrect is greater than or equal to three, the player passes, in which case a variable named grade is assigned a value of Passed. Otherwise a value of Failed is assigned to the grade variable. The last thing that needs to be accomplished is adding the programming logic that displays the number of correctly and incorrectly answered questions and the player’s overall exam score. This is accomplished by the following display dialog statement. -- Displays the test results display dialog "Number correct: " & noCorrect & ¬ "Number incorrect: " & noIncorrect & ¬ "Test Results: " & grade buttons {"OK"}
Step 5: Testing the Execution of the Star Trek Trivia Game All right, at this point your new AppleScript Studio game should be complete. Before trying to run it by clicking on the Xcode Build and Go button, click on the Build button instead to see if any errors are generated. Given the amount of code that you had to key in, odds are you may have made a typo or two. When you click on the Build button, Xcode attempts to compile your application without running it. If there are any syntactical errors, they will be identified under the Error and Warnings entry in the Groups & Files section of the Xcode Project window. Using this information, you should be able to get a pretty good idea of the line number where the error resides and fix any typing errors that you may have made. Once you have identified and removed any syntax errors, click on the Build and Go button to run and test out the execution of your new game.
Chapter 4 • Working with Values, Variables, and Classes
139
Application Code Review We stepped through the development of the Star Trek Trivia game’s AppleScript file in a stepby-step fashion. It is important that we make sure that the script you have now assembled contains all of the required script statements and that they are entered in the proper order. So, just to make sure we keep everything straight, I have laid out a copy of the fully assembled AppleScript file here. -- Star Trek Trivia.applescript -- Star Trek Trivia --
Created by Jerry Ford on 7/16/06.
--
Copyright 2006. All rights reserved.
on clicked theObject tell window of theObject -- Declare and assign default values to script variables set noCorrect to 0 -- Keep track of correct answers set noIncorrect to 0 -- Keep track of incorrect answers set rawPercentage to 0 -- Used to calculate grade set grade to 0 -- Used to store test grade -- Define variables representing answers to test questions set answer1 to "" set answer2 to "" set answer3 to "" set answer4 to "" set answer5 to "" -- Execute code that controls the display of the drawer window if title of theObject is "View Instructions" then tell drawer "InstructionDrawer" to open drawer -- Open drawer set title of theObject to "Hide Instructions" -- Change title text else if title of theObject is "Hide Instructions" then
140
AppleScript Studio Programming for the Absolute Beginner
tell drawer "InstructionDrawer" to close drawer –- Close drawer set title of theObject to "View Instructions" -- Change title text end if -- Execute code that collects player’s answers to test questions if title of theObject is "Begin Exam" then tell drawer "InstructionDrawer" to close drawer -- Close drawer --Reset the progress indicator back to zero set content of progress indicator "pgbLevel" to 0 --Ask 1st test question set answer1 to the button returned of (display dialog ¬ "Question 1:
The laws that govern the actions of Star " & ¬
"Fleet personnel are referred to as Prime Directives." ¬ buttons {"True", "False"}) -- Increment progress bar to show that the first of five -- answers has been collected tell progress indicator "pgbLevel" to increment by 20 --Ask 2nd test question set answer2 to the button returned of (display dialog ¬ "Question 2: When initially beaming down to an unknown " & ¬ "planet, the correct setting for phaser weapons is: " ¬ buttons {"Stun", "Kill"}) -- Increment progress bar to show that two of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20 --Ask 3rd test question set answer3 to the button returned of (display dialog ¬ "Question 3: What is the appropriate speed of travel when" & ¬ " a star ship is leaving space dock? " ¬ buttons {"Warp 10", "Light", "Impulse"}) -- Increment progress bar to show that three of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20
Chapter 4 • Working with Values, Variables, and Classes
--Ask 4th test question set answer4 to the button returned of (display dialog ¬ "Question 4: The neutral zone is a term that refers to " & ¬ "an area of space where any space traveler is free to go." ¬ buttons {"True", "False"}) -- Increment progress bar to show that four of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20 --Ask 5th test question set answer5 to the button returned of (display dialog ¬ "Question 5: According to existing Federation treaties, " & ¬ "are star ships permitted to use cloaking technology?" ¬ buttons {"Yes", "No"}) -- Increment progress bar to show that five of five -- answers have been collected tell progress indicator "pgbLevel" to increment by 20 --Analyze test results if answer1 = "True" then -- If the player selected "True" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if if answer2 = "Stun" then -- If the player selected "Stun" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if if answer3 = "Impulse" then -- If the player selected Impulse" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if
141
142
AppleScript Studio Programming for the Absolute Beginner
if answer4 = "False" then -- If the player selected "False" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if if answer5 = "No" then -- If the player selected "No" set noCorrect to noCorrect + 1 -- Answer is correct else -- Otherwise the answer is incorrect set noIncorrect to noIncorrect + 1 -- Answer is correct end if -- Determine whether the player passed the exam if noCorrect • 3 then -- Three or more correct answers passes set grade to "Passed" else --Less than three correct answers fails set grade to "Failed" end if -- Displays the test results display dialog "Number correct: " & noCorrect & ¬ "Number incorrect: " & noIncorrect & ¬ "Test Results: " & grade buttons {"OK"} end if end tell end clicked
SUMMARY In this chapter you began learning how to formulate AppleScript code statements. This included learning how to work with a number of commands. You learned about different classes supported by AppleScript and how to coerce a data type from one type to another. You also learned how to formulate compound or code block statements. Finally, you learned how to create, access, and manipulate the contents of variables as a means of storing data during script execution.
Chapter 4 • Working with Values, Variables, and Classes
143
Before you move on to Chapter 5, why don’t you set aside a few extra minutes to improve the Star Trek Trivia game by addressing the following list of challenges.
CHALLENGES 1.
2.
3.
As is it currently written, the user interface for the Start Trek Trivia game is a little sparse. Add additional text and graphics to give it a more complete appearance. Currently, the test administered by the game consists of five questions. Make the test more challenging by adding additional questions. Do not forget to add the corresponding programming statements required to analyze and grade the additional exam questions. Modify the code statements that are responsible for automating the activity of the game’s progress indicator control so that it increments appropriately based on the number of questions that you add to the game.
This page intentionally left blank
5
C H A P T E R
APPLYING CONDITIONAL LOGIC AND BUILDING LOOPS ne of the fundamental operations performed in most AppleScript Studio applications is the ability to analyze data and make decisions based on the result of that analysis. In AppleScript this is accomplished using the if statement. By analyzing data, you can develop scripts that vary their execution based on the context of the current situation. Another core operation frequently used in AppleScripts is the use of loops to repeat the execution of a given set of programming statements in order to process large amounts of data or to perform a particular task repeatedly. In AppleScript, loops are created using the repeat statement. This chapter will teach you how to work with different variations of the if and repeat statements. In addition, you will learn how to create a new computer program, the Guess a Number game.
O
Specifically, you will learn how to • Use the if statement to define logical tests and control program flow • Use relational operators to test different types of conditions • Use the repeat statement to create different types of loops
146
AppleScript Studio Programming for the Absolute Beginner
PROJECT PREVIEW: THE GUESS A NUMBER GAME In this chapter’s game project, you will learn how to create a number guessing game that challenges players to guess a randomly generated number in the range of 1 to 100. Players enter their guesses using a slider control located in the middle of the game window, as shown in Figure 5.1.
FIGURE 5.1 The player must guess a randomly generated number between 1 and 100.
Game play begins when the player clicks on the New Game button, activating the slider control and readying the game to accept the player’s first guess, as shown in Figure 5.2.
FIGURE 5.2 The New Game button is disabled and remains that way until the end of the current game.
Chapter 5 • Applying Conditional Logic and Building Loops
147
A hint is provided in the text field control located at the bottom of the game window after each player guess. Using this information, the player can gradually close in on the correct answer, as demonstrated in Figure 5.3.
FIGURE 5.3 The player entered a guess that was too low.
The game keeps count of the number of guesses made by the player, allowing the player to keep track of his progress, as demonstrated in Figure 5.4.
FIGURE 5.4 The player’s guess was too high.
148
AppleScript Studio Programming for the Absolute Beginner
Game play ends when the player successfully guesses the game’s secret number. To notify the player, the slider control is disabled and a message of “Winner!” is displayed in the text field located at the bottom of the window, as demonstrated in Figure 5.5.
FIGURE 5.5 The player guessed the game’s secret number in eight guesses.
Game instructions can be viewed at any point during game play. To access these instructions, the player only needs to click on the Instructions tab at the top of the window, as shown in Figure 5.6.
FIGURE 5.6 A tab view control is used to toggle the player between the Play and Instructions views.
Chapter 5 • Applying Conditional Logic and Building Loops
149
IMPLEMENTING CONDITIONAL LOGIC As has been stated, conditional logic provides you with the ability to alter the logical execution flow within AppleScripts. In AppleScript, conditional logic is implemented using the if statement. To see how the if statement works, consider the following example. if the car costs $20,000 then I’ll buy it I’ll drive it straight to my girlfriend’s apartment end if
This English-like or pseudo-code outline provides you with a simple demonstration of the structure and operation of the if statement. As the example shows, the if statement is used to define a code block that begins with the if keyword and ends with end if. If the tested condition evaluates as being true, then all of the statements located inside the if statement code block are executed. Otherwise, if the tested condition evaluates as being false, the if statement code block is skipped, and execution continues at the statement following the code block. HIN
T
Pseudo-code is an English-like outline of the logic that makes up all or part of a script or application. If you develop a pseudo-code version of the programming logic you plan to implement in a script, you organize your thoughts prior to beginning coding. As a result, you are less likely to make logical mistakes.
The if Statement The if statement is used to build conditional tests. There are two basic forms of the if statement. The first is a single line version, which is used in situations where the logic required to write the statement is small enough to fit on a single line. The syntax for this form of the if statement is outlined here. if expression then statement expression is a placeholder representing any valid expression. statement is a placeholder rep-
resenting any valid AppleScript statement. An example of this form of the if statement is shown here. if x = 5 then display dialog "The value of x is five."
In this example the value of a variable named x is checked to see if it is equal to 5. If it is, a popup dialog is displayed using the display dialog command. If it is not equal to 5, the popup dialog is not displayed. An advantage of this form of the if statement is that it lets you define
150
AppleScript Studio Programming for the Absolute Beginner
a simple test and then execute a single code statement only if the test proves true using a minimum of space. The second form of the if statement is used to create if statement code blocks. Its basic syntax is outlined here. if expression then statements end if
If you want, you could rewrite the single line if statement example shown earlier as an if statement code block. if x = 5 then display dialog "The value of x is five." end if
Note that unlike single line if statements, an if statement code block can contain any number of AppleScript statements.
The if…else Statement Sometimes you will want to specify a different course of action to be taken in the event that the expression tested by an if statement is false. One way to do this is to use two if statement code blocks, as demonstrated here. --Apple and orange example if x = "apple" then display dialog "My Favorite." and if if x = "orange" then display dialog "No thanks." end if
You can save a little time and a few keystrokes by rewriting this example using the if…else form of the if statement. The syntax for an if…else code block is outlined here. if expression then statements else statements end if
Using this form of the if statement, the previous example could be rewritten like this.
Chapter 5 • Applying Conditional Logic and Building Loops
151
--Apple and orange example if x = "apple" then display dialog "My Favorite." else display dialog "No thanks." end if
As you can see, this example is slightly smaller, requiring one less statement. It also helps to clarify the overall logic used to guide logical flow within a script.
The if…else if Statement Another form of the if statement allows you to use even more complex logic when developing conditional tests. By adding the else if keywords, you can expand an if statement code block to test any number of different conditions. The syntax for this form of the if statement code block is outlined here. if expression then statements else if expression then statements else if expression then statements . . . else statements end if
Using this form of the if statement code block, you can test for as many conditions as necessary. By adding the optional else keyword, you can even provide for a course of action in the event that none of the tested expressions evaluate as being true. As an example, take a look at the following statements. --Apple, oranges and pairs example if x = "apple" then display dialog "My Favorite." else if x = "orange" then display dialog "No thanks." else
-- x equals pear
152
AppleScript Studio Programming for the Absolute Beginner
display dialog "Maybe just one." end if
Here the value of x is checked to see if it equals apple. If it does, then the embedded display dialog command executes, after which the code block is done, and the next statement immediately following the code block is executed. Otherwise, the first else if statement inside the code block is tested. If its tested expression evaluates as being true, its embedded display dialog command is executed, and the code block stops executing. Otherwise, the display dialog command associated with the example’s else statement is executed.
Nested if Statements An if statement code block can contain any number of embedded, or nested, AppleScript statements. These statements might also include other if statement code blocks. By embedding one code block within another, you can build complex programming logic, as demonstrated here. set today to (current date)
-- Stores the current date
set dayOfWeek to weekday of today as string
-- Stores day of the week
set dayOfMonth to day of today as integer --Stores numeric day of the month if dayOfWeek = "Saturday" then
-- Tasks to complete on Saturdays
if dayOfMonth = 5 then display dialog "Give the dog a bath." else display dialog "Take the dog to the park" end if else if dayOfWeek = "Sunday" then
-- Tasks to complete on Saturdays
display dialog "Remember to go to church today." else
-- Tasks to complete on weekdays display dialog "Sorry, it is another work day."
end if
In this example, three variables are defined. today is used to store the current date and time as stored on the computer. dayOfWeek stores the day of the week and dayOfMonth stores the numeric date for the month. An if…else if code block then determines what tasks needs to be performed based on the day of the week (e.g., Saturday, Sunday, or Monday–Friday). A nested if…else code block is used to select between either of two possible tasks that are performed only on Saturdays.
Chapter 5 • Applying Conditional Logic and Building Loops
153
DIFFERENT TYPES OF COMPARISONS So far, all of the conditional evaluations that you have seen in this chapter use the equals (=) operator to compare two conditions. AppleScript also provides a host of relational operators that you can use to perform different types of comparisons. Like the equals operator, each of these comparison operators is used to compare two values and results in a Boolean value of either true or false. AppleScript supports both symbolic and English-like versions of these comparison operators, as shown in Table 5.1. TRI
Actually, there are considerably more English-like operators available than those listed in Table 5.1. For example, instead of writing the following statement
CK
if x is greater than y then display dialog "Yikes!"
You could write if x comes after y then display dialog "Yikes!"
As an example of how to use the operators, consider the following example. if x > y then statements end if
Here, a statement embedded within an if statement code block is executed when the value of a variable named x is greater than the value assigned to a variable named y. Likewise, the following statement demonstrates the use of the ≠ operator. if x ≠ y then display dialog "Houston , we have a problem!"
TABLE 5.1
APPLESCRIPT RELATIONAL OPERATORS
Operator
English Equivalent
=
is is equal to equals is not is not equal to is greater than is greater than or equal to is less than is less than or equal to
≠ > ≥ < ≤
154
AppleScript Studio Programming for the Absolute Beginner
TRI
To type the 실, 싨, or 싩 characters, hold down the Option key when pressing the , <, or > characters.
CK
If you prefer, you can use the English-like equivalents of any of the operators shown in Table 5.1, as demonstrated below. if x is not equal to y then display dialog "Houston , we have a problem!"
The use of either the symbolic or English-like operators is entirely a matter of personal preference. For readability and consistency, I strongly recommend that you choose one type of operator (symbolic or English-like) and stick with it.
TIP
BUILDING COMPOUND TESTS As you have seen, you can build complex conditional logic by nesting if statement code blocks within one another. As an alternative, you can use any of the compound operators outlined in Table 5.2 to build complex conditional logic. As an example of how to use AppleScript’s compound operators, consider the following instance. if dayOfWeek = "Saturday" then if dayOfMonth = 5 then display dialog "Take the dog to the park" end if end if
As you can see, this example uses two if statement code blocks (one embedded within another) to test two conditions, and if both evaluate to true then a popup dialog is displayed. As an alternative, you could rewrite this example using the and compound command as shown here.
TABLE 5.2
APPLESCRIPT COMPOUND OPERATORS
Operator
Description
and or not
Results in a value of true if both expressions evaluate to true. Results in a value of true if either expression evaluates to true. Inverts or negates the value of an expression
Chapter 5 • Applying Conditional Logic and Building Loops
155
if dayOfWeek = "Saturday" and dayOfMonth = 5 then display dialog "Take the dog to the park" end if
As you can see, not only does using the and compound operator result in fewer lines of code, but it also makes the resulting code statements easier to read and understand. TRI
CK
The and operator, like the or operator, increases its efficiency by shortcircuiting. What this means is that the and operator will skip the evaluation of the expression on the right-hand side of the operator when the expression on the left-hand side evaluates to false. Remember, if either expression evaluates to false, the end results of the overall comparison will ultimately evaluate to false.
An example of the or operator is provided next. As you can see, the statements embedded within the if statement code block will be executed if either of the two tested expressions proves true. if x = 1 or y = 2 then statements end if
The not operator is different from the and and or operators, inverting or negating the value of the tested expression as it evaluates it. if not (x is equal to 100) then statements end if
Note the use of the parentheses. The parentheses used in this example are not required but were added for clarity, in order to clearly identify the expression to be negated and evaluated.
ITERATIVE PROCESSING Like conditional logic, iterative processing or looping is another key programming technique used in most AppleScripts. A loop is a logical construct that provides you with the ability to repeat the execution of a collection of programming statements. For example, you might set up a loop to execute a set of script statements that rename every file located in a folder or perform a set of commands an arbitrary number of times. In AppleScript, loops are created using different variations of the repeat statement, as listed here.
156
AppleScript Studio Programming for the Absolute Beginner
• repeat • repeat x times • repeat while • repeat until • repeat with • repeat with…in Each of these variations of the repeat statement is explained further in the sections that follow.
Creating an Endless Loop The simplest form of the repeat statement creates a code block that runs forever. It is therefore up to you to provide a means to terminate loop execution. The syntax for this form of the repeat statement code block is outlined here. repeat statements end repeat
As you can see, the loop begins with the repeat keyword and ends with the end repeat statement. All statements embedded in between are executed each time the loop repeats or iterates. As an example of how to put this form of loop into action, take a look at the following statements. set x to 1 repeat display dialog "Now looping – Iteration # " & x if x > 2 then exit repeat end if set x to x + 1 end repeat
Here, a variable named x is defined and assigned an initial value of 1. Next, a repeat statement code block is defined, which repeatedly displays a popup dialog. Upon each iteration of the loop, the value of x is incremented by 1 and displayed in the popup dialog, as demonstrated in Figure 5.7.
Chapter 5 • Applying Conditional Logic and Building Loops
157
FIGURE 5.7 The value assigned to the variable named x is displayed each time the loop iterates.
Note the inclusion of the exit repeat statement in the middle of the loop. This statement is wrapped inside an if statement code block and is executed when the value of x exceeds 2 (e.g. upon the third iteration of the loop). When executed, the exit repeat statement terminates the execution of the loop, allowing control to pass onto the next statement after the loop.
Iterating a Set Number of Times The repeat statement can also be used to set up a loop that executes a specified number of times using the following syntax. repeat x times statements end repeat
Using this syntax, the repeat code block executes a specific number of times based on the value of x, as demonstrated in the following example. set x to 1 repeat 3 times display dialog "Now looping – Iteration # " & x set x to x + 1 end repeat
In this example, a variable named x is defined and assigned a starting value of 1. A repeat statement code block is then executed, running three times. Upon each iteration of the loop, the value of x is displayed and then incremented by one.
Looping While a Condition Proves true Another variation of the repeat statement allows you to set up a loop that executes while a tested condition remains true. The syntax for this form of the repeat code block is outlined here.
158
AppleScript Studio Programming for the Absolute Beginner
repeat while expression statements end repeat
As you can see, the while keyword has been added, followed by the expression that is evaluated before each execution of the loop. As long as the value of expression evaluates as being true, the loop iterates. The first time that value of expression evaluates to false, the loop stops executing, allowing control to pass onto the next statement after the loop. An example of this form of the repeat statement code block is provided here. set userInput to "" repeat while userInput is not equal to "quit" set userInput to text returned of ¬ (display dialog "Type quit to exit." default answer "") end repeat
In this example, a variable named userInput is defined. Next, a repeat statement code block executes, assigning the value supplied by the user to the userInput variable. The loop continues to execute as long as the value supplied by the user is not equal to quit.
Looping Until a Condition Proves true The repeat statement also accepts the use of the until keyword, setting up a loop that executes as long as a specified expression evaluates as being false (e.g. the opposite of a repeat statement code block created using the while keyword). The syntax for this form of the repeat code block is outlined here. repeat until expression statements end repeat
As the following example shows, you can use this form of the repeat statement code block in place of the while version by simply inverting the conditional test—in this case, from not equal to to equal to. set userInput to "" repeat until userInput is equal to "quit" set userInput to text returned of ¬ (display dialog "Type quit to exit." default answer "") end repeat
Chapter 5 • Applying Conditional Logic and Building Loops
159
Controlling Loop Execution with a Counter Yet another variation of the repeat statement is the creation of a loop that executes a set number of times using a starting and ending value. The syntax for this form of loop is outlined here. repeat with variablename from start to end [by counter] statements end repeat
Here, variablename is a placeholder for a variable that will be used to control the loop’s execution. When first executed, the value of start and end are evaluated. The value of start is then assigned to variablename. Each time the loop iterates, the value of variablename is incremented by one, unless the optional by counter parameter is specified. If specified, the value of counter is added to variablename upon each iteration of the loop. The loop continues to execute until the value of variablename becomes equal to the value of end. As an example of how to set up this version of a repeat statement code block, take a look at the following example. repeat with x from 1 to 9 by 2 display dialog x end repeat
Here the loop has been set up to execute five times. The first time the loop executes, the value of x is set to 1. On the second execution of the loop, the value of x becomes 3. Upon the fifth execution, the value of x becomes 9, and the loop stops execution. This form of loop is quite flexible. If you want, you can even specify a negative number to be used to decrement the value of x, as demonstrated here. repeat with x from 9 to 1 by –2 display dialog x end repeat
Here, the value of x begins at 9 and is reduced by 2 upon each iteration, until it finally reaches a value of 1 and the loop stops executing.
Processing List Contents A final variation of the repeat statement code block allows you to set up a loop that iterates through the contents of a list. The syntax for this form of loop is outlined here. repeat with variablename in list
160
AppleScript Studio Programming for the Absolute Beginner
The following statements demonstrate how to iterate through each element in a list. repeat with x in {"Molly", "William", "Alexander"} display dialog x end repeat
In this example, a loop is set up that iterates through a list made up of three elements displaying the contents of each list element. As the loop executes, the value of x is implicitly referenced and displayed as x. More information on how to work with lists is available in Chapter 6, “Working with Strings, Lists, and Records.”
BACK TO THE GUESS A NUMBER GAME Okay, let’s turn our attention back to the development of the Guess a Number game. The primary point of focus for this game is the application of the conditional logic required to control game execution and evaluate player guesses. As you work on the Guess a Number game, you will get another chance to work with the slider control. You will also learn how to work with the tab view control. I will also show you a little trick that you can use when testing the execution of your new game. As with all of the applications in this book, the Guess a Number game will be created in five steps, as outlined here. 1. Starting Xcode and creating a new AppleScript Studio application. 2. Designing the application’s graphical user interface. 3. Configuring the game’s menu, window, and control attributes and attaching interface controls to event handlers. 4. Adding the required AppleScript code statements. 5. Compiling and testing the application.
Step 1: Creating a New Project If you have not done so yet, go ahead and start Xcode. Create a new AppleScript Studio project as outlined here. 1. Click on the File menu and then select New Project. Xcode starts an Assistant, displaying a list of application templates. 2. Select AppleScript Application template and then click on Next. 3. When prompted, specify Guess a Number as the file name for the application and then specify the appropriate location where the project should be stored. 4. Click on Finish.
Chapter 5 • Applying Conditional Logic and Building Loops
161
Step 2: Creating the User Interface Now it is time to development the Guess a Number game’s graphical user interface, as outlined in the following procedure. 1. Locate the MainMenu.nib file located in the Resources group and then double-click on it to start the Interface Builder. 2. Drag and drop an instance of the tab view control onto the application’s window. Resize the control so that it takes up the entire window. 3. By default, the tab view control displays two tabs. Double-click on the first tab and change its title to Play. Double-click on the second tab and enter Instructions. 4. Making sure that the Play tab is selected, drag and drop an instance of the small system font text control to the upper left-hand corner of the tab view control. Double-click on it and change its title to read N o. of Guesses made:. 5. Add a text field control just to the right of the small system font text control, reducing its width to about one-half its default size. 6. Add a button control to the upper right-hand side of the tab view control, aligning it with the text field control. Double-click on the button control and change its title to New Game. 7. Next, drag and drop a horizontal box control onto the tab view control. Place it about a half inch below the control already added and resize it to be almost the entire width of the tab view area. 8. Add another small system font text control to the tab view control. Center it about a quarter inch below the horizontal box control and then change its title to Guess. 9. Add a text field control immediately under the small system font text control. Reduce its width to approximately one inch and then change its height to approximately a half inch. 10. Drag and drop another text field control onto the tab view control and place it somewhere to the right of the previous text field control. 11. Add a slider control to the middle of the tab view control. Resize it so that it is approximately five inches wide. 12. Add another button control just under the slider control, and change its title to Check Move. 13. Drag and drop another horizontal box control onto the tab view control, placing it about a quarter inch below the last button control, resizing it to be almost the entire width of the tab view control. 14. Add another small system font text control in the bottom left-hand corner of the tab view control and change its title to Results:.
162
AppleScript Studio Programming for the Absolute Beginner
15. Drag and drop a text field control to the bottom of the tab view control and resize it so that it takes up the remainder of space to the right-hand side of the small system font text control. 16. At this point, the tab view control labeled Play should look like the example shown in Figure 5.8.
FIGURE 5.8 The layout of the Play view of the Guess a Number game.
17. Next, click on the Instructions tab and then drag and drop a small system font text control onto it. Resize this control so that it takes up most of the available space and then enter the following text into it: The objective of this game is to guess the game’s randomly generated secret number i n as few guesses as possible. The range of possible choices is between 1 and 100. Use the slider control to specify a guess. Once you have selected your guess, click on the Check Move button. Your guess will then be evaluated, and the result of this a nalysis will be displayed in the Results text field at the bottom of the game window. Game play ends once the secret number has been guessed. 18. At this point, the Instructions tab should look like the example shown in Figure 5.9.
Chapter 5 • Applying Conditional Logic and Building Loops
163
FIGURE 5.9 The layout of the Instructions tab of the Guess a Number game.
The user interface for the Guess a Number game is complete, and you are ready to begin customizing various control properties.
Step 3: Customizing Control Properties To finish up the configuration of the Guess a Number game, you will need to configure its window and menu system and then various control attributes, as outlined in the next several sections.
Menu Customization To customize its menu system, you will need to remove a number of unnecessary menus and menu items that Xcode automatically adds to your application. Begin by clicking on the Help menu and pressing the Delete key. Delete all of the menu items under the Window menu except for the Minimize menu item. Next, select the Edit menu and press Delete to remove it and its contents. Next click on the File menu and remove everything but the Close menu item. Lastly, you need to customize the Application menu as outlined here. 1. 2. 3. 4.
Double-click on the Application menu and replace its name with Number Guess. Modify the About Application menu item to read About Number Guess. Modify the Hide Application menu item to read Hide Number Guess. Modify the Quit Application menu item to read Q uit Number Guess.
164
AppleScript Studio Programming for the Absolute Beginner
Setting Control Attributes As with the previous AppleScript Studio applications that you have worked on, you must make a number of modifications to this game’s window and interface controls. These changes are outlined in Table 5.3 and must be made from the Inspector window’s AppleScript and Attribute views. Note that the name assigned to the tab view control is tbvDisplay. This control has two tabs, each of which has its own view. Click on the Play tab and assign it a name of p layGame and then click on the Instructions tab and assign it a name of g ameInstructions.
Setting Up Event Handler Connections Like every GUI you have worked on in this book, you need to configure certain interface controls so that they will trigger events when the player uses them. Specifically, in the Guess a Number application, you will need to set up both of the game’s button controls so that they
TABLE 5.3
MODIFICATIONS TO THE APPLICATION WINDOW ITS INTERFACE CONTROLS
Object
Attribute
Modification
Window
Name Window Title Zoom Name Name Editable Selectable Name Name Editable Selectable Name Minimum Maximum Current Name Name Editable Selectable
main Guess a Number Disable tbvDisplay txtCount Disabled Disabled newGame txtGuess Disabled Disabled sdrGuess 1.0 100.0 1.0 checkMove txtResults Disabled Disabled
Tab View Text Field
Button Text Field
Slider
Button Text Field
AND
Chapter 5 • Applying Conditional Logic and Building Loops
165
will trigger the on clicked event handler. In addition, you will also need to configure the slider control’s action event handler (from the AppleScript view in the Inspector window).
Step 4: Adding a Little Programming Logic Now it is time to begin adding the AppleScript statements required to make the Guess a Number game work. In doing so, you will learn a number of new AppleScript programming tricks, including how to manage controls located on different views of a tab view control and the steps involved in interacting with the slider control. In addition, you will learn how to generate random numbers using the random number command. TR
AP
Before adding the code statements provided in this section, it is assumed that you have already configured the clicked event for both of the applications’ button controls and the action event for the slider control. As a result, the application’s AppleScript file should already contain the following statements. -- Number Guess.applescript -- Number Guess --
Created by Jerry Ford on 8/7/06.
--
Copyright 2006 __MyCompanyName__. All rights reserved.
on clicked theObject (*Add your script here.*) end clicked on action theObject (*Add your script here.*) end action
Adding Code to the on clicked Event Handler Let’s begin by working on the code belonging to the on clicked event handler. For starters, modify the code for this event handler as shown here. on clicked theObject tell window of theObject --Execute when the button labeled New Game is clicked if name of theObject is "newGame" then
166
AppleScript Studio Programming for the Absolute Beginner
end if --Execute when the button labeled Check Move is clicked if name of theObject is "checkMove" then end if end tell end clicked
As you can see, this event handler has been organized into two major parts. The first part is an if code block that executes when the player clicks on the button control named newGame (e.g., the Start Game button). The second part is an if control block that executes when the player clicks on the button control named checkMove (e.g. the Check Move button). In addition, both of these if code blocks have been embedded inside a tell block that directs all commands to the application’s window. Now that you have this high-level structure in place, it is time to get busy keying in the rest of the application’s code. Start by adding the following statements inside the if statement control block for the newGame button control. --Generate a random number between 1 and 100 set randomNo to random number from 1 to 100 as integer --Reset text field that displays the number of guesses made set contents of text field "txtCount" ¬ of tab view item "playGame" of tab view "tbvDisplay" to 0 --Reset text field that displays the slider's default value set contents of text field "txtGuess" ¬ of tab view item "playGame" of tab view "tbvDisplay" to 1 --Assign the random number to the secret text field set contents of text field ¬ "txtCheat" of tab view item "playGame" ¬ of tab view "tbvDisplay" to randomNo --Reset the text field labeled Results set contents of text field ¬ "txtResults" of tab view item "playGame" ¬ of tab view "tbvDisplay" to " " --Reset the slider control to a default value of one
Chapter 5 • Applying Conditional Logic and Building Loops
167
set contents of slider "sdrGuess" ¬ of tab view item "playGame" of tab view "tbvDisplay" to 1 set enabled of slider "sdrGuess" of tab view item ¬ "playGame" of tab view "tbvDisplay" to true set enabled of button "newGame" of tab view item ¬ "playGame" of tab view "tbvDisplay" to false set enabled of button "checkMove" of tab view item ¬ "playGame" of tab view "tbvDisplay" to true
This code begins by generating a random number. This is accomplished using the random number command. By default, this command generates a random number between 0 and 1. However, by specifying upper and lower limits, as in this example, you can select a range of any size. The value returned by the random number command is a real number, which means that it includes a decimal point. Since the game requires an integer value, the value generated by the random number command is then converted to an integer and assigned to a variable named randomNo. The next statement displays the number of guesses made so far by the player. Since a new game is being started, this value is set to 0. Since the game and its instructions are presented using a tab view control, a little extra effort is required in order to identify the location of the text field control. Specifically, the text field control is located on the playGame view of the tbvDisplay tab view control. The next command assigns a value of 1 to the text field control that is used to display the slider control’s current value, which you may remember you set to 1.0 from the Inspector window. Next, the game’s random number is displayed as a text field control named txtCheat. I have added this feature to help simplify the testing of the game. As you will see, it will be a lot easier to validate the game’s proper operation when you know what the secret number is during testing. TRI
CK
Later, once you are done testing the Guess a Number game, you can remove the txtCheat text field control and the code that refers to it. Better yet, you can keep it and enable its Hidden attribute to keep it from being seen. This way, if you later come back and make a change to the game, all that you will have to do is clear the Hidden attribute and you’re ready to test again.
The rest of the statement in this code finishes setting and displaying default text field values and then enables and disables button and slider controls as required to start game play. Next, add the following set of code statements to the if statement control block associated with the checkMove control.
168
AppleScript Studio Programming for the Absolute Beginner
--Declare a variable and use it to store the player's guess set playerGuess to contents of slider "sdrGuess" ¬ of tab view item "playGame" of tab view "tbvDisplay" ¬ as integer --Declare a variable and use it to store a random number set secretNo to contents of text field ¬ "txtCheat" of tab view item "playGame" ¬ of tab view "tbvDisplay" as integer --Retrieve value representing the number of guesses made so far --and store it in a variable named x set x to contents of text field ¬ "txtCount" of tab view item "playGame" ¬ of tab view "tbvDisplay" as integer --Increment x by one set x to x + 1 --Store the value of x back in the text field that displays the --total number of player guesses set contents of text field ¬ "txtCount" of tab view item "playGame" ¬ of tab view "tbvDisplay" to x
The first statement sets the value of a variable named playerGuess to the value currently specified by the slider control. The next statement sets the value of a variable named secretNo equal to the game’s randomly generated secret number (which is stored in the txtCheat text field). Next, you need to add the programming logic that addresses the actions that need to be taken when the player correctly guesses the game’s secret number. To do so, add the following set of code statements to the bottom of the if statement control block associated with the checkMove control. Next, a variable named x is assigned a value representing the number of guesses made so far (which is stored in the txtCount text field). The value of x is then incremented, and the contents of the txtCount field are updated by reassigning the updated value of x back to it, in effect updating the display of the number of guess made so far. Now, add the following set of code statements immediately after the preceding set of statements (e.g., to the bottom of the if statement control block associated with the checkMove control).
Chapter 5 • Applying Conditional Logic and Building Loops
169
if playerGuess = secretNo then --The player's guess was correct --Disable the slider control set enabled of slider ¬ "sdrGuess" of tab view item "playGame" ¬ of tab view "tbvDisplay" to false --Disable the button control labeled New Game set enabled of button ¬ "newGame" of tab view item "playGame" ¬ of tab view "tbvDisplay" to true --Disable the button control labeled Check Move set enabled of button ¬ "checkMove" of tab view item "playGame" ¬ of tab view "tbvDisplay" to false --Display a message telling the user the game’s over set contents of text field ¬ "txtResults" of tab view item "playGame" ¬ of tab view "tbvDisplay" to "Winner!" end if
The opening if statement checks to see if the player has guessed the game’s secret number. If he has, all the statements in the if statement code block execute. The first of these statements disables the slider control, thus stopping game play. The next statement enables the New Game button, allowing the player to start a new round of play. Next, the Check Move button is disabled, and then a text string of “Winner!” is posted in the text field located at the bottom of tab view control’s playGame tab. Now let’s add programming logic to address the actions that need to be taken when the player’s guess is too low. To do so, add the following set of code statements to the bottom of the if statement control block associated with the checkMove control. if playerGuess < secretNo then --The player's guess is too low --Display a helpful hint in the text field labeled Results set contents of text field ¬ "txtResults" of tab view item "playGame" of tab view ¬ "tbvDisplay" to "Your guess was too low." end if
As you can see, the only action that needs to be taken when the player’s guess is too low is to update the display of the text string in the txtResults text field control in order to give the player a helpful hint.
170
AppleScript Studio Programming for the Absolute Beginner
Now let’s add programming logic to address the actions that need to be taken when the player’s guess is too high. To do so, add the following set of code statements to the bottom of the if statement control block associated with the checkMove control. if playerGuess > secretNo then --The player's guess is too high --Display a helpful hint in the text field labeled Results set contents of text field ¬ "txtResults" of tab view item "playGame" of tab view ¬ "tbvDisplay" to "Your guess was too high." end if
These statements execute when the player’s guess is too high. All that is required here is to update the display of the text string in the txtResults text field control in order to give the player a helpful hint. This ends the code required to complete the development of the on clicked event handler for both of the GUI’s button controls. Next, you must provide the code required to help manage the execution of the slider control.
Adding Code to the action Event Handler The last bit of AppleScript code needed to finish up the Guess a Number application is shown next. This code goes in the slider control’s action event handler, which should already be defined within your AppleScript file. The action event handler executes every time the slider control’s thumb is moved, thus providing instantaneous feedback of the slider’s current value or setting. tell window of theObject --Focus stays on the window named main --Display the slider control's current value in the text field --control immediately above it set contents of text field ¬ "txtGuess" of tab view item "playGame" of tab view ¬ "tbvDisplay" to contents of slider "sdrGuess" of tab view item ¬ "playGame" of tab view "tbvDisplay" as integer end tell
The sole purpose of this code is to manage the process of displaying the slider control’s current value in the text field control immediately above it. This is accomplished in a single statement, which sets the value of the txtGuess text field control equal to the contents of the sdrGuess slider control, located on the playGame view of the tbvDisplay tab view control.
Chapter 5 • Applying Conditional Logic and Building Loops
171
Step 5: Testing the Execution of the Guess a Number Game Your new AppleScript studio game is now complete. Go ahead and click on Xcode’s Build and Go button and see if it runs. If you receive any errors, use the error information provided to track and find out where you may have made typos. Once everything appears to be running correctly, play a few rounds. Remember that the value of the randomly generated number is displayed in the text field control named txtCheat. Knowing what this number is will help you test your game more quickly and validate that the guesses you are providing are being correctly interpreted. Once you are confident that everything is as it should be, select the txtCheat text field control, open the Inspector window, and modify the control by deselecting the control’s Hidden attribute. Recompile the application and test it one more time before sharing copies of it with your friends.
SUMMARY In this chapter you learned how to apply conditional logic in order to create scripts that alter their execution based on an analysis of the data being worked with. You learned how to use different relational operators to define different types of comparisons. You also learned how to use compound operators in order to perform evaluations using two or more logical comparisons. In addition, you learned how to create loops using a number of different variations of the repeat statement. Before you move on to Chapter 6, why don’t you set aside a few extra minutes to add a few improvements to the Guess a Number game by addressing the following list of challenges.
CHALLENGES 1.
2.
As currently written, the Guess a Number game provides only two types of hints to the user after each guess, “too high” or “too low.” Add additional logic to your application to indicate when the player is beginning to get warmer or colder. Modify the Guess a Number game so that it prompts the player to specify different ranges of numbers from which the player can guess. For example, you might let the player select from ranges of 1 to 10, 1 to 100, or 1 to 1,000.
172
3.
4.
AppleScript Studio Programming for the Absolute Beginner
Consider adding an optional Quit button to your application to provide players with the ability to stop playing in the middle of a game. Also, you might want to display the game’s secret number at the end of each game. Another option to consider is to limit the number of guesses allowed and to declare the game over in the event the user does not guess the secret number within that specified number of guesses.
6
C H A P T E R
WORKING WITH STRINGS, LISTS, AND RECORDS n Chapter 4, “Working with Values, Variables, and Classes,” you learned how to store and retrieve individual pieces of data using variables. You also learned a few basic techniques for working with strings, including how to concatenate strings and extend them over multiple lines. In this chapter, you will expand upon this information by learning how to work with collections of data stored in lists and records. You will learn a number of different ways in which you can control the format of strings. You will also learn how to manipulate string contents. On top of all this, you will learn how to work with a number of new interface controls and to leverage the power of the Mac OS X built-in speech synthesizer. Finally, to wrap things up, you will learn how to create your next computer game, Alexander’s Tall Tale.
I
Specifically, you will learn how to • Create and work with lists • Define and store data using records • Perform a number of string manipulation techniques • Work with the text view, switch, and popup button controls • Use the say command to make your applications talk
174
AppleScript Studio Programming for the Absolute Beginner
PROJECT PREVIEW: ALEXANDER’S TALL TALE In this chapter you will learn how to create the Alexander’s Tall Tale game. When first started, the screen shown in Figure 6.1 is displayed.
FIGURE 6.1 The game’s story is displayed using a text view control.
When the player clicks on the Tell Story button, the text of the story is displayed in a text view control that takes up most of the window, as demonstrated in Figure 6.2. The game’s storyline consists of a number of paragraphs into which variables have been inserted at key points. Each time the player clicks on the Tell Story button, the values of these variables are replaced with different randomly selected strings, thus telling a slightly different story each time.
FIGURE 6.2 The story is told in a slightly different way each time it is told.
Chapter 6 • Working with Strings, Lists, and Records
175
Because the story is rather lengthy, you have to scroll down to read the end of the story. If you prefer to save your eyes a little work, you can have the game read the story to you using any of three built-in Mac OS X voice synthesizer voices. These voices are selected from the popup button control located at the bottom of the window, as demonstrated in Figure 6.3.
FIGURE 6.3 The player can customize the game by selecting the voice used to read the story.
Once a voice has been selected, the player must enable the option to have the game read the story aloud. This is done by selecting the Talk (switch) control before clicking on the Tell Story button, as shown in Figure 6.4.
FIGURE 6.4 To have the game read the story aloud, the Talk option must first be selected.
176
AppleScript Studio Programming for the Absolute Beginner
MANIPULATING STRINGS Somewhere along the line you are going to run into a situation where you need to exercise detailed control over the strings managed by your AppleScript Studio applications. For example, you may want to create an application that renames all of the files in a folder, by either changing their file extension or perhaps adding date information to the end of their file names. Alternatively, you may be interested in searching for information within strings, in order to extract a particular piece of information. Fortunately, AppleScript provides you with several ways of examining and extracting information about strings.
Assigning Strings to Variables As has already been stated, a string is a sequence of one or more characters enclosed within a matching pair of double quotation marks, as demonstrated here. set myName to "Jerry"
There is no practical limit to the size of a string. In addition, you can assign a variable a null string value by assigning it an empty string as demonstrated here. set x to ""
Getting Information About a String Using the count command, you can retrieve a value representing the number of characters that make up a string. The count command has the following syntax. count string string represents a string or a variable containing a string. As an example of how to use the count command, take a look at the following example. set message to “IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES” display dialog “The string:” & message & “contains” & ¬ (count message) & “characters.”
When executed, this example displays a count of the number of characters in a string assigned to the message variable, as demonstrated in Figure 6.5.
FIGURE 6.5 Displaying a count of the number of characters in a string.
Chapter 6 • Working with Strings, Lists, and Records
177
Concatenating Strings Using the & concatenation operator, you can join together any two strings to create a new string, as demonstrated here. set message to “Happy ” & “Birthday!”
Here two strings are concatenated and assigned to a variable named message. As the following example shows, you can concatenate as many strings as necessary. set myName to “Jerry” & “ ” & “Ford”
Here three strings have been concatenated into one string, which is then assigned to a variable named myName.
Controlling String Format AppleScript provides you with a means of specifying how you would like to format a string by providing you with access to a small collection of escape characters. An escape character is a special sequence of characters beginning with the \ character and followed by a letter that AppleScript recognizes and replaces with its ASCII equivalents. Table 6.1 lists the escape characters recognized by AppleScript.
TABLE 6.1
APPLESCRIPT ESCAPE CHARACTERS
Escape Characters
English Equivalent
Description
\r \n \t \\
End of line Newline Tab Backslash
\"
Double quotation mark
Adds an ASCII end of line marker Adds an ASCII newline character Inserts a tab space into the string Inserts a single backslash character into a string Inserts a double quotation mark into a string
The \r and the \n escape characters produce the same results. The \n escape character is used on Unix, while \r is often used on Mac OS X. Both are perfectly valid, though in this book you will see only \n used. The following three statements demonstrate how to use the \n, \t, and \" escape characters. display dialog “ALERT!\n\nThis is a test message” display dialog “ALERT!\t\tThis is a test message” display dialog “ALERT! \“This is a test message\””
178
AppleScript Studio Programming for the Absolute Beginner
The output for each of these three statements is shown in Figures 6.6, 6.7, and 6.8.
FIGURE 6.6 Using the \n escape characters to format a string over two lines.
FIGURE 6.7 Using the \t escape characters to format a string by inserting a tab.
FIGURE 6.8 Using the \" escape characters to embed double quotation marks inside a string.
TR
AP
Do not be surprised when, after compiling your application, escape characters disappear from your AppleScripts, and your strings are reformatted. This is just the way things work. The compiler reformats the strings according to the instructions you provide via escape characters.
Advanced Comparisons You have learned that you can compare strings, for example, to see if they are equal. AppleScript supports two other statements that give you additional control over how certain parts of strings are interpreted during a comparison. • considering. Specifies one or more attributes to be considered when performing a comparison. • ignoring. Specifies one or more attributes to be ignored when performing a comparison. These two statements are used to set up code blocks, within which string comparisons are made. For example, by default, AppleScript ignores case when comparing strings. As a result, the strings “jerry” and “JERRY” are, by default, equivalent. However, as the following example demonstrates, you can change this behavior by enabling case-sensitivity.
Chapter 6 • Working with Strings, Lists, and Records
179
set x to “jerry” set y to “JERRY” considering case if x = y then display dialog “Match!” end considering
In this example, a case attribute is added to the end of the opening considering statement, thus setting up a code block within which all string comparisons are subject to casesensitivity. As a result, since case-sensitivity is now in effect, AppleScript will not evaluate the value of x and y as being equal. AppleScript supports a number of other attributes that can be applied to both considering and ignoring code blocks, as outlined in Table 6.2.
TABLE 6.2
ATTRIBUTES SUPPORTED BY IGNORING BLOCKS
CONSIDERING AND
Attribute
Description
case white space punctuation hyphens
All lowercase and uppercase characters Any white space, including spaces, tabs, and the newline and return characters Any punctuation characters, including ,.?\’”`;: The hyphen (-) character
By default, AppleScript automatically considers all of the attributes listed in Table 6.2, except for case. If you want, you can disable the considering of any of these attributes by using the ignoring statement, as demonstrated here. set x to “Once upon a time.” set y to “Once upon a time” ignoring punctuation if x = y then display dialog “Match!” end ignoring
In this example, a match results even though the first string contains a period that is not present in the second string. If you want, you can set up a code block that specifies more than one attribute, as shown here. set x to “Once upon a time.” set y to “Once upon a time” considering case but ignoring hyphens, punctuation and white space if x = y then display dialog “Match!” end considering
180
AppleScript Studio Programming for the Absolute Beginner
Note that in this example, the but keyword allows you to combine considering and ignoring statements. In addition, you can specify more than one attribute by separating them with commas. The last attribute must be separated from the other attributes using the and keyword.
Working with Characters, Words, and Paragraphs AppleScript allows you to reference different parts of strings using different string elements, as defined here. • character. An individual character within a string. • word. A continuous set of characters within a string, typically separated from other characters by a blank space. • paragraph. A set of characters demarcated by a return or newline character. Using these string elements, along with the element specifiers outlined in Table 6.3, you can perform a host of operations on the contents of strings.
TABLE 6.3
STRING ELEMENT SPECIFIERS
Specifier
Description
first, second, etc. item 1, item 2, etc. 1st, 2nd, etc. some every last end items x through z
Specifies an item within a string Specifies an item within a string Specifies an item within a string Specifies a randomly selected item within a string Specifies every item within a string Specifies the last item within a string Specifies the last item within a string Specifies a range of items within a string
For example, the following statement can be used to extract the fifth word from a string. set x to “Once upon a time there was a little girl named Molly.” set y to fifth word of x
-- y equals there
Similarly, you could retrieve the last word in a string, as demonstrated here. set x to “Once upon a time there was a little girl named Molly.” set y to last word of x
-- y equals Molly
Chapter 6 • Working with Strings, Lists, and Records
181
The string element specifiers listed in Table 6.3 also work with characters and paragraphs attributes. For example, you can extract a range, or substring, of characters from a string as shown here. set x to “Once upon a time there was a little girl named Molly.” set y to characters 1 through 11 x
-- y equals Once upon a
Later, when you develop the Alexander’s Tall Tale game, you’ll see an example of how to use the some item specifier to randomly extract a paragraph from a list of paragraphs.
DEFINING AND ACCESSING LISTS In Chapter 4, you learned how to store and retrieve individual pieces of data using variables. While certainly a powerful programming technique, there are times when working with individual pieces of data is not always easy. For example, suppose you wanted to write an AppleScript Studio application that was designed to collect a list of names from the user. If the user entered just a few names, this would not be too bad. But what if the user decides to enter 10 or 20 names? That is a lot of variables to have to define and keep track of. An easier way of storing and keeping track of groups of related data is through lists. A list is an ordered collection of values, which are referred to as items. Lists can be used to store any type of data type. Lists are defined by placing comma-delimitated values inside a pair of matching curly braces, as demonstrated here. {1, 2, 3, 4, 5} HIN
T
A list is AppleScript’s equivalent to an array in other programming languages.
Working with Lists Here a list has been created that contains three strings. Lists, of course, can be assigned to variables. set nameList to {“Alexander”, “William”, “Molly”}
Above, a list made up of strings is assigned to a variable named nameList. Lists can contain any combination of data types. They can also be empty, as shown next. set emailList to {}
182
AppleScript Studio Programming for the Absolute Beginner
A list can contain any number of elements. You can use the count command to retrieve a value representing the number of elements in the list as shown here. set nameList to {“Alexander”, “William”, “Molly”} set x to count of nameList TIP
-- x equals 3
If necessary, you can use the & concatenation operator to create a new list out of two existing lists as demonstrated here. set x to {1, 2, 3} set y to {3, 4, 5} set z to x & y
-- z equals {1, 2, 3, 4, 5, 6}
Retrieving Elements from a List Back in Chapter 5, “Applying Conditional Logic and Building Loops,” you learned how to work with different variations of the repeat statement in order to iterate through and process the contents of a list. As a reminder, consider the following example. repeat with x in {“Molly”, “William”, “Alexander”} display dialog x end repeat
Here, a repeat statement has been set up that iterates through a list made up of three strings. Upon each iteration, the value of one of the strings is assigned to a variable named x, which is then displayed by a display dialog command. In addition to using the repeat loop to step through a list and examine or manipulate its contents, you can use any of the item specifiers listed in Table 6.4 to access items stored in a list. As an example of how to extract items from a list, take a look at the following examples. set nameList to {“Alexander”, “William”, “Molly”} set x to first item in nameList set x to every item in nameList set x to last item in nameList
-- x equals “Alexander” -- x equals {“Alexander”, “William”, “Molly”} -- x equals “Molly”
set x to items 2 through 3 in nameList
-- x equals {“William”, “Molly”}
The comments on the right-hand side of each statement show the output generated from each statement.
Chapter 6 • Working with Strings, Lists, and Records
TABLE 6.4
ITEM SPECIFIERS THAT CAN BE USED
TO
183
ACCESS LISTS
Specifier
Description
First item, second item, etc. item 1, item 2, etc. 1st item, 2nd item, etc. some item every item beginning middle item last item end items x through z
Specifies an item within a list. Specifies an item in a list. Specifies an item in a list. Specifies a randomly selected item in a list. Specifies every item in a list. Specifies the first item in a list. Specifies the middle item in a list. Specifies the last item in a list. Specifies the last item in a list. Specifies a range of items within a list.
Making Changes to Lists AppleScript provides you with the ability to make specific types of changes to lists. These changes include: • Changing an item • Inserting an item at the beginning of the list • Adding an item to the end of a list You can use the set command to modify any item in a list by specifying its location within the list and a replacement value, as demonstrated here. set nameList to {“Alexander”, “William”, “Molly”} set item 2 in nameList to “William the Great”
You can add a new item to the beginning of any list using the beginning specifier, as demonstrated here. set nameList to {“Alexander”, “William”, “Molly”} set beginning of nameList to “Mary”
Similarly, you can add an item to the end of any list, as shown here. set nameList to {“Alexander”, “William”, “Molly”} set end nameList to “Jerry”
184
AppleScript Studio Programming for the Absolute Beginner
TRI
CK
Unfortunately, AppleScript does not provide you with a command for deleting items from a list. However, if you know the location of the item that you would like to delete, you can work around this limitation. One way of doing so is to extract the range of items before the item to be deleted and the range of items that follow that item and then concatenate these two ranges back together, as demonstrated here. set x to {1, 2, 3, 4, 5, 6} set x to items 1 through 3 of x & items 5 through 6 of x
Here the range of items 1–3 is concatenated to the range of items 5–6 and then assigned back to x, The end result of this operation is that the fourth item in the list has now been removed.
STORING AND RETRIEVING DATA USING RECORDS Lists are ordered collections of data. As such, you can use a loop to iterate through them. You can also access list contents by specifying the location of list items. Another way to work with and manage collections of data is through records. A record is a collection of properties, each of which is assigned a label and a value. HIN
T
A record is AppleScript’s equivalent to a hash or dictionary in other programming languages.
The format of a record is outlined here. {label: value, label: value ….} label is a placeholder representing the name assigned to a specific property, and value is a
placeholder for the data associated with a given property. As you can see, data in a record is stored in label: value pairs.
Creating and Accessing Records As demonstrated next, a record can contain any number of label: value pairs. set childsName to {name: “Alexander”, age: 9, hobby: “Beyblading”}
Once it is set, you can extract any property from a record by referencing its label, as demonstrated here. set x to the name of childsName – x equals Alexander
If necessary, you can retrieve more than one record property at a time, as demonstrated here.
Chapter 6 • Working with Strings, Lists, and Records
185
set myList to {name, age} of childsName –- myList contains {“Alexander”, 9}
Whether you have realized it or not, you have worked with records on a number of occasions in this book. The display dialog command has been used in numerous examples to collect data returned by the user, either by determining the button that the user clicked or by collecting the string that the user entered into the resulting popup dialog. Both the button and text returned by the display dialog command are collected in the form of a record. In Chapter 4, as part of the Star Trek Trivia game, you displayed a popup dialog that displayed two buttons, as shown here. set answer1 to the button returned of (display dialog ¬ “Question 1:
The laws that govern the actions of Star ” & ¬
“Fleet personnel are referred to as Prime Directives.” ¬ buttons {“True”, “False”})
In this example, you determine which button the user clicked on by using the set command to assign a value to a variable named answer1. Take note of the bold portion of this example. It extracts a record property named button returned from a record generated by the display dialog command. Likewise, in the following example, the value keyed in by the user is assigned to a variable named answer by extracting a record property named text returned. set answer to the text returned of (display dialog ¬ “What is your name?” default answer ””)
Modifying Record Property Values You can use the set command to modify the value stored in a given record property. To do so, you must specify the property whose value is to be changed and then supply a new value, as demonstrated here. set childsName to {name: “Alexander”, age: 9, hobby: “Beyblading”} set age of childsName to 10
Here, a value of 10 is assigned to the age property for the record named childsName.
Working with a List of Records By themselves, individual records are of limited value. However, if you group them together in a list, records take on a greater role in helping to organize and retrieve large collections of data. As an example, check out the AppleScript statements shown here.
186
AppleScript Studio Programming for the Absolute Beginner
set childNames to {¬ {name:“Alexander”, age:9, hobby:“beyblading”}, ¬ {name:“William”, age:7, hobby:“beyblading”}, ¬ {name:“Molly”, age:5, hobby:“beyblading”}} set nameList to {} repeat with x in childNames set end of nameList to name of x end repeat
Here, a list made up of three records has been set up. Each record contains information about a different person. Since the records are stored in a list, it is possible to loop through each record and extract data. In the case of this example, a list of names was generated. Although this example is rather small, the real power of working with lists and records occurs as the amount of information stored in records grows and as the number of records stored in the list grows. For example, a company’s list of customer information might include names, addresses, phone numbers, email addresses, and so on and might consist of hundreds of records, each representing a different customer. By organizing customer records into a list and then processing them via a loop, you can quickly extract and process any of the data that you have stored.
BACK TO ALEXANDER’S TALL TALE Now it is time to begin the development of Alexander’s Tall Tale. The primary point of focus for this game is on the application of string manipulation techniques, including concatenation, continuation, and the generation of random paragraph selections. You will also want to pay close attention to the manner in which new controls are managed and how the say command is used. Alexander’s Tall Tale will be created in five steps. 1. Use Xcode to create a new AppleScript Studio application named Alexander’s Tall Tale. 2. Use the Interface Builder to design the application GUI. 3. Configure the game’s menu, window, and interface control attributes and then set up connections to event handlers. 4. Add the script statements required to make the application work. 5. Compile and test the application.
Chapter 6 • Working with Strings, Lists, and Records
187
Step 1: Creating a New Project Start Xcode if it is not already running and create a new AppleScript Studio project using the procedure outlined here. 1. Click on the File menu and select New Project. An Assistant is launched, displaying a list of application templates. 2. Select AppleScript Application template and click on Next. 3. When prompted, specify Alexander’s Tall Tale as the file name for the application and select the location where you want to store the game. 4. Click on the Finish button.
Step 2: Creating the User Interface The next step in the development of Alexander’s Tall Tale is to put together its graphical user interface, as outlined in the following procedure. 1. Locate the MainMenu.nib file located in the Resources group. Double-click on it to start the Interface Builder. 2. Drag and drop an instance of the text view control on to the application’s window and then resize the text view control so that it takes up almost all of the window, except for two-thirds of an inch at the bottom of the window, as demonstrated in Figure 6.9.
FIGURE 6.9 Most of the game’s user interface is taken up by the text view control.
3. Drag and drop an instance of a button control onto the lower left-hand portion of the application’s window. Align it with the left-hand side of the text view control.
188
AppleScript Studio Programming for the Absolute Beginner
4. Drag and drop an instance of the popup button control onto the lower right-hand side of the application’s window and align it with the right-hand side of the text view control. 5. Finally, drag and drop an instance of the switch (checkbox) control onto the application’s window, placing it just to the right of the popup button control, as demonstrated in Figure 6.10.
FIGURE 6.10 At this point, all of the game’s interface controls should be in place.
Okay, at this point the user interface for Alexander’s Tall Tale is now complete. The next step in the development of this game is the customization of its application menus, window, and interface controls.
Step 3: Customizing Control Properties Now that the overall construction of the user interface is complete, let’s begin work on configuring the application’s menus, window, and interface control attributes as outlined in the next three sections.
Menu Customization In order to customize the application’s menu system, you must remove a number of unnecessary menus and menu items. Start by deleting the Edit and Help menu by selecting them and pressing the Delete key. Delete all of the menu items located on the Window menu except for the Minimize menu item. Next, select the File menu and remove everything but the Close menu item. Lastly, customize the Application menu as outlined here.
Chapter 6 • Working with Strings, Lists, and Records
189
1. Double-click on the Application menu and replace its name with Alexander’s Tall Tale. 2. Modify the About Application menu item to read About Alexander’s Tall Tale. 3. Modify the Hide Application menu item to read Hide Alexander’s Tall Tale. 4. Modify the Quit Application menu item to read Q uit Alexander’s Tall Tale.
Modifying Window and Control Attributes In order to complete the development of Alexander’s Tall Tale, a number of modifications need to be made to the game’s window and its interface controls. These modifications are outlined in Table 6.5 and must be made from the Inspector window’s AppleScript and Attribute views.
TABLE 6.5
MODIFICATIONS TO THE APPLICATION WINDOW INTERFACE CONTROLS
Object
Attribute
Modification
Window
Name Window Title Zoom Name Editable Selectable Name Title Title Name
main Alexander’s Tall Tale Disabled textViewForStory Disabled Disabled scrollViewForStory Tell Story Talk computerVoices
Text View
Button Switch Popup Button
AND
Note that Table 6.5 contains two name entries for the text view control. The first entry represents the text area or text view portion of the text view control that accepts and displays text. To access it and configure its attributes, select the text view control, open the Inspector window, and then double-click on the text view control. You can now assign a name of textViewForStory to this portion of the control. The text view portion of the text view control is accessed and addressed separately from the scroll view portion, which represents the area of the control that does not accept and display text, including its scroll bar. To assign the required name to the scroll view portion of this control, with the Inspector window still open, click on a different area in the window in order to remove the focus from the text view control and then single-click on the text view control
190
AppleScript Studio Programming for the Absolute Beginner
again. You can now assign a name of scrollViewForStory to the scroll view portion of the control. As you will see later, in the code portion of the application, you must be able to distinguish between and refer to each of these two components separately. In order to finish the development of the game’s user interface, you need to populate the popup button control with a list of three voices, each of which represents a different voice supported by the Mac OS X voice synthesizer. To add these three entries, double-click on the popup button control. When you do so, a list of three default items for the control is displayed. Double-click on the first entry and type Vicki. Double-click on the second entry and type Victoria. Double-click on the third entry and type G ood News. TRI
CK
FIGURE 6.11 Testing Mac OS X’s built-in voice synthesizer.
Mac OS X comes fully equipped with a built-in voice synthesizer, which you can easily incorporate into your AppleScript Studio applications, as demonstrated through the creation of Alexander’s Tall Tale. To experiment with Mac OS X’s voice synthesizer, click on the Apple menu and select System Preferences. This displays the System Preferences window from which you can double-click on the Speech icon to view the Speech window shown in Figure 6.11.
Chapter 6 • Working with Strings, Lists, and Records
191
To view and select from the list of available built-in voices, click on the System Voice popup button and make a selection from the list of available choices. To listen to the sound of the selected voice, click on the Play button. You can expand the list of voices available in Alexander’s Tall Tale by adding any of the voice names listed in the System Voice popup control.
Setting Up Event Handler Connections Alexander’s Tall Tale only requires that you configure its one button control’s click event in order to set up its on clicked event handler (from the AppleScript view in the Inspector window). Once you have completed this task, you can move on to the next section and begin the code development portion of the application.
Step 4: Adding a Little Program Code It is time to add the code to enable the proper execution of Alexander’s Tall Tale. As you add the code statements outlined in the sections that follow, pay extra attention to the statements that interface with and control the text view control. Also, take note of the manner in which the AppleScript checks on the status of the switch control and determines the currently selected value for the popup button control. Assuming that you have already set up the game’s button control to react when clicked, the following code statements should be visible in your application’s AppleScript file. -- Alexander's Tall Tale.applescript -- Alexander's Tall Tale -- Created by Jerry Ford on 8/8/06. -- Copyright 2006 - Jerry Lee Ford, Jr. All rights reserved. on clicked theObject end clicked
All of the code required by this application will be written inside the on clicked event handler. For openers, add the following code statements inside the on clicked event handler. --Define a variable made up of a string made up of three paragraphs set lineOne to “bravest person in the world fastest man in all the land the most skilled soldier to ever live”
192
AppleScript Studio Programming for the Absolute Beginner
As you can see, a comment precedes the declaration of a variable named lineOne, which is made up of three separate paragraphs. I have separated each paragraph by pressing the Return key. Later in the script, you will add the programming logic required to randomly select one of these three paragraphs in order to supply a string that will be plugged into the game’s main storyline. In total, the game has four storyline plug-ins, thus giving the story a small element of unpredictability. To define the remaining plug-ins, add the following code statements to the end of the on clicked event handler. --Define a variable made up of a string made up of three paragraphs set lineTwo to “overrun and destroyed captured and imprisoned slaughtered like sheep” --Define a variable made up of a string made up of three paragraphs set lineThree to “slain over twenty enemy solders slaughtered a hundred enemy warriors wiped out most of the enemy's forces” --Define a variable made up of a string made up of three paragraphs set lineFour to “stopped fighting and laid down their weapons disappeared in a puff of smoke turned into stone statues”
Next you need to add the program logic required to make random paragraph selections from each of the preceding variables. This is accomplished by adding the following statements to the end of the on clicked event handler. --Randomly select a paragraph from each of the following variables set reputation to some paragraph of lineOne set armyStatus to some paragraph of lineTwo set fightResults to some paragraph of lineThree set soldierStatus to some paragraph of lineFour
As you can see, one statement has been written for each variable to be processed. In this first statement, a variable named reputation is randomly assigned a string value by extracting one of the paragraphs that make up the lineOne variable. Note the use of the some keyword, which is responsible for making the random selection. some is an AppleScript element specifier that provides the ability to make a random selection of a character, word, or paragraph string element.
Chapter 6 • Working with Strings, Lists, and Records
193
Next, you need to lay out the text for the game’s storyline. This is accomplished by adding the following statements to the end of the on clicked event handler. --Define a variable and assign it a string containing the story --Insert randomly generated variable values into the story set storyText to “Once upon a time there was a young man ” & ¬ “named Alexander the Great. Alexander was known far ” & ¬ “and wide as the ” & reputation & “. Whenever ” & ¬ “there was any trouble, the king always called upon ” & ¬ “Alexander to come to his rescue.\n\nOne day, not ” & ¬ “long ago a great army from the east attacked the outer ” & ¬ “regions of the kingdom. The king sent