05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

AppleScript<br />

CHAPTER 23 MAC <strong>OS</strong> X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 413<br />

AppleScript is a simple programming language for controlling applications. Although Apple-<br />

Script and Automator are different around the edges, it’s not a bad metaphor to think of<br />

AppleScript as writing Automator workflows in longhand.<br />

To demonstrate that point, here is our Keyword Screensaver application written entirely in<br />

AppleScript:<br />

-- Remove any existing images<br />

tell application "Finder"<br />

set _imageFolder to path to pictures folder<br />

set _imageFolder to folder "Keyword Screensaver" of folder _imageFolder<br />

delete every file in _imageFolder<br />

end tell<br />

-- Ask for Text<br />

display dialog "What keyword shall I search for?" default answer ""<br />

set _keyword to text returned of result<br />

set _queryURL to "http://images.google.com/images?q=" & _keyword<br />

-- Query Google<br />

tell application "Safari"<br />

open location _queryURL<br />

set _timeoutInSeconds to 20<br />

delay 2<br />

repeat with _waitInSeconds from 1 to _timeoutInSeconds<br />

if (do JavaScript "document.readyState" in document 1) is "complete" then<br />

exit repeat<br />

else if _waitInSeconds is _timeoutInSeconds then<br />

number -128<br />

else<br />

delay 1<br />

end if<br />

end repeat<br />

set _searchResults to source of document 1<br />

end tell<br />

-- Extract image URLs from page source, then download them<br />

set AppleScript's text item delimiters to "\",\""<br />

set _rawResults to text items in _searchResults<br />

set AppleScript's text item delimiters to ""<br />

repeat with _text in _rawResults<br />

if _text starts with "http://" and _text does not end with "/images" then<br />

do shell script "cd ~/Pictures/Keyword\\ Screensaver;<br />

curl -sO " & quoted form of (_text as string)<br />

end if<br />

end repeat<br />

-- Activate screen saver<br />

tell application "ScreenSaverEngine"<br />

activate<br />

end tell<br />

To use this script, open the Script Editor application in /Applications/AppleScript. The<br />

Script Editor is extremely simple. AppleScript goes in the main window, with runtime logging<br />

occurring below. The Run button in the toolbar parses, formats, corrects, compiles, and runs the<br />

script.<br />

Even its biggest fans have to admit that AppleScript is a quirky language. Its English-like<br />

syntax makes it friendly to look at but tricky to write. Unlike C, which is rigid in its syntax,

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!