Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

  • Print
  • + Share This
This chapter is from the book

The Obligatory "Hello World" Tutorial

Tradition dictates that the first project you attempt with a new computer language be the "Hello World" project (look up the history on http://en.wikipedia.org). The project usually entails creating a small program to write "Hello World" onscreen. Not very exciting maybe, but tradition is tradition. Thus, our first project will be to draw, with the aid of AppleScript, a circle in Illustrator (the world) with a blue fill and no stroke. Our script will then write the word hello centered in the circle with a white fill.

To begin the tutorial, carefully type the following script in Script Editor:

tell application "Adobe Illustrator"
   activate
   make new document with properties {height:792, width:612, ruler origin:{0.0, 0.0}}

   make new ellipse in document 1 with properties {position:{256.0,
   446.0}, width:100.0, height:100.0, fill color:{class:CMYK color
   info, cyan:84.0, magenta:63.0, yellow:0.0, black:0.0}, stroked:false}

   set theText to make new text frame in document 1 with properties
   {kind:point text, contents:"hello", position:{306.0, 396.0}}

   set properties of text of theText to {fill color:{class:CMYK color
   info, cyan:0, magenta:0, yellow:0, black:0}, text font:text font
   "Myriad-Roman", size:32, justification:center}
end tell

Click the Run button (if Illustrator isn't already open, Script Editor will automatically open it for you). You should see the Hello World circle and text as shown in Figure 4.6.

Figure 4.6

Figure 4.6 The output of your Hello World script.

After you've typed the text in Script Editor, click the Compile button (which resembles a hammer). This causes the editor to check the script's syntax to ensure that it's consistent with the AppleScript language. If you get an error message, make sure you typed it in exactly as shown.

Creating a New Page

Take a look at the preceding script and see if you can make some sense of it. The line tell application "Adobe Illustrator" directs the script to Illustrator. It's a way of saying, "Take this note to Illustrator and have it do the things that follow." The last line of the script is end tell which closes what's called the tell block. Because an AppleScript can change which application it's referring to mid-script, application tell blocks provide a means of indicating where the instructions for a particular program are contained.

The second line (activate) brings Illustrator to the front so that you can watch the show.

The third line starts with make new document—which is precisely what the script does. Documents have properties, and this specifies its height and width in pixels (AppleScript's default). Since the Macintosh has 72 pixels per inch, we can see that this creates a page that is 11 inches tall (792 pixels divided by 72 pixels per inch) and 8.5 inches wide (612 pixels divided by 72)—or a letter-size page. The ruler origin {0.0, 0.0} portion of the script sets the horizontal ruler to start in the top left corner and the vertical ruler to start in the lower left corner—important because all commands will use this origin to set or return positioning properties.

Building the Circle

As you've already learned, all objects have properties. In this case, the ellipse, or circle, is drawn using five characteristics, or properties. The first property is its position (256.0, 446.0), which is its x,y coordinates on the page expressed in pixels. (You could substitute inches for pixels by typing 3.5 inches, 6.2 inches.) Our circle will be drawn 256 pixels (3.5 inches) from the left edge of the page and 446 pixels (6.2 inches) down from the top of the page.

The second and third properties we'll use to draw our circle are its width (100.0) and height (100.0). Again, these measurements are expressed in pixels and will result in a circle about 1.4 inches in diameter (100 pixels divided by 72). If we wanted an ellipse, we'd only have to specify two measurements.

The fourth property of our circle is its fill color, which we build by specifying its CMYK mix (though we could also use an RGB mix or even a swatch color).

The fifth and final property is the stroke. Known as a Boolean data type, the stroke can only be one of two values: If its value is "true," our circle will have a stroke; if it's "false," it won't. So stroked:false means no stroke.

There are many other properties you can set, and if you don't specify a property, AppleScript will use Illustrator's defaults. For instance, one of the circle's properties is "fill overprint." Again, it's a Boolean data type, and the default is false. Since the circle is not on top of another object, the default of no overprint is fine—and we don't need to specify it.

Adding the Text

Let's look at the line that starts with set theText. "theText" is a variable name I created so that I could refer to the text by that name in the next line. Variables are nothing more than placeholders—like the x's and y's in your high school algebra class—used to store values that change over time. We use variables all the time in our daily lives—take, for example, the expression "my car." You may have many cars over the years ; "my car" simply serves as the label (or variable name) for the vehicle that's sitting in your driveway right now.

In Figure 4.7, the variable text shows up in green thanks to color-coding (you can change the color in Script Editor's Preferences), which helps you quickly understand a script's structure. In this example I've also used blue to indicate language and application keywords, and black for operators and values.

Figure 4.7

Figure 4.7 The Hello World AppleScript in Script Editor. The events that result from running the script are shown in the lower pane because the Event Log button has been selected. The bar separating the two panes is draggable to adjust the size of or hide either window.

A text frame is Illustrator's scripting term for any text created using the Text tool. The three types (or "kinds") of text frames are point (text anchored by a single point), area (text within an object), and path (text attached to a path). We can see that the three properties specified in this script are kind (point text), contents ("hello"), and position (306.0, 396.0).

We now want to set the fill color, font, size, and justification of the word hello. These are not properties of a text frame but of the text contained within the frame. Thus, in the next line (starting with set properties), we set those properties for the text of theText. This may seem weird, but remember that everything is contained within something else, and certain objects have certain properties. The fill color is set the same way it was for the circle. The font thing is a little interesting because text font:text font looks like a mistake but it's not. The first "text font" is the property and the second "text font" is the class of the value. Size and justification are self-explanatory.

During the early stages of scripting, you'll spend some (OK, a lot) of your time trying to figure out how to address objects (containment) and what properties you can change. This is where using (read: stealing) someone else's scripts (with that person's explicit or implied consent, of course) can come in handy. If you can find a script that does approximately what you want, it's often easier to adapt code that someone else has written than to write your own from scratch. Not only do you save yourself time and grief, it's a great way to learn.

Playing with Your Script

Now it's time to make a copy of your script (copying and pasting it into a new window) and start moving and changing things—in short, play. Some of the most important lessons we learned as children were acquired through play. And playing is a great way to learn scripting, too. For instance, what would happen if you were to change the ellipse bounds? Would its shape change? And what if you were to change the contents of the text frame to, say, your name? Or if you were to change the font and color? What would happen if you were to change the text frame position, add other text frames, or change the "stroked" property to "true"? Try to get into the mode of experimentation. If you screw up, your script won't work, but nothing will catch fire. Just as you would do when editing an image, make a copy so that you can't destroy all your previous work (in this case, typing in all that code).

Here's something cool: In Illustrator select just the circle and then go back to Script Editor and type the following in a new window:

tell application "Adobe Illustrator"
   get properties of selection
end tell

Click the Result button (in the middle at the bottom of the window), and you'll get back a wealth of information about our little circle (Figure 4.8).

Figure 4.8

Figure 4.8 After running this script, the bottom pane will display information that Illustrator records for your circle. If the bottom window is hidden, drag the horizontal bar (with the dot in the center of it) up to reveal the Result text.

You'll get an idea of what Illustrator tracks for every object and what you potentially have access to. Unfortunately, you can't modify the Result window's tangle of text in Script Editor to make it more readable. Still, it's worth taking some time to wade through it, seeing if you can use any of the information there to change the circle. For instance, toward the bottom of the window you'll see that the name property has a value of nothing (name:""). Let's go ahead and name our circle Gaia, which means "living planet." To do that, return to Script Editor, create a new script window, and type the following (with the circle still selected in Illustrator):

tell application "Adobe Illustrator"
   set name of selection to "Gaia"
end tell

Click the Run button in Script Editor, then go to the Layers panel in Illustrator and expand Layer 1 to see Gaia in the lineup (Figure 4.9). Note that Illustrator automatically gave the text frame a name matching its contents—"hello."

Figure 4.9

Figure 4.9 The circle is now named Gaia, as shown in the Layers panel. In future scripts you can refer to it by name.

If you run the "get properties of selection" script again (with the circle selected in Illustrator), you'll see that the value for the name property is now, in fact, Gaia. In future scripts you can refer to our little planet by its name—which means you could write and run something like the following (the circle doesn't need to be selected now since you're referring to it by name):

tell application "Adobe Illustrator"
   set the opacity of path item "Gaia" of document 1 to 50.0
end tell

This sets the circle's transparency to 50 percent. Just to confuse you, in the Illustrator application this property is called transparency. But when scripting Illustrator you have to refer to it as opacity. It seems Adobe used the scripting word transparency already as a GIF property and had to call it something else for path items.

Now, let's change the text as follows:

tell application "Adobe Illustrator"
   set contents of text frame 1 in document 1 to "bye"
end tell

For our last trick, let's do something more interesting. Although I'm sure I'm not the first to discover it, I've found that scripting lets you animate objects in the host program (in our case, Illustrator). The following script will fade the circle Gaia from white (or zero opacity) to full blue (100 percent opacity). You can also make objects fade in or out and move incrementally (as if sliding), and you can incrementally change text (to make it look as if someone were typing it manually). Here's the fade-in script:

tell application "Adobe Illustrator"
   activate
   repeat with i from 0 to 100
      set opacity of path item "Gaia" of document 1 to i
      redraw
   end repeat
end tell

The preceding script introduces the concept of loops, which are useful for controlling the flow of scripts. Loops generally repeat a task until a condition is met, usually changing something incrementally with each pass. In this case, the stop, or end, condition occurs when the variable i equals 100. (For no particular reason, the letter i is commonly used in AppleScript for loops. I could have just as easily used the letter g or z, or a variable name like LoopCounter.) In AppleScript, a loop starts with repeat and ends, appropriately enough, with end repeat. The part that says with i from 0 to 100 means that it will loop 100 times (actually 101 times, since we're starting with 0 instead of 1).

For the first go-round, i has a value of 0; the second time it's 1; and so on. At the end of the set opacity line, we see the variable i again. In our example, i is doing double duty, acting as both a counter for the loop and as the opacity percentage for the circle. If we didn't use variables, we would have to write 101 set opacity lines in the script, which would look something like the following:

set opacity of path item "Gaia" of document 1 to 0
set opacity of path item "Gaia" of document 1 to 1
set opacity of path item "Gaia" of document 1 to 2

and so on up through 100.

If we decided that we wanted to change the progression of opacity and had, in fact, written 101 lines of code, we'd have to go back and rewrite the whole thing. Since the script uses a variable, however, all I would have to do to change it would be to alter the values. For instance, if I wanted the circle to fade out rather than in, all I'd have to do is change one line, which would look like this:

tell application "Adobe Illustrator"
   activate
   repeat with i from 100 to 0 by -1
      set opacity of path item "Gaia" of document 1 to i
      redraw
   end repeat
end tell

You'll notice that I added by –1, which tells the script to count backwards by 1. I didn't have to write by 1 in the first script because AppleScript defaults to the value of 1 when counting loops. If the animation fades out too slowly for your tastes, try setting the count to –2 or –5 and see what happens. Can you make it fade in faster?

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020