Free AppleScript Code Examples

1 - I can do better 2 - Jury's out 3 - Pretty darn good 4 - Splendiferous 5 - Awesometastic by 0 people | Log in to rate

Ranked #1,384 in Tech & Geek, #33,413 overall

How to Write AppleScript Code without any Prior Knowledge

AppleScripting, with emphasis on tutorials for those new to scripting. Example scripts of general utility, as well as some that relate to specific applications (FileMaker Pro, AppleWorks, Script Editor, specialized scripts and others). Some discussion of HyperCard and AppleScript and the Classic (OS9) environment.

Note that I approach things as a step-by-step progression, therefore, for the more basic scripts, please scroll to the posts toward the bottom of the page.
For an explanation of some common terms with examples, check out: http://www.squidoo.com/applescriptExplained

For some basic JavaScript, check out: http://www.squidoo.com/how-to-write-javascript

RSS: Scripting with AppleScript 

More Examples on Writing AppleScripts

Loading Fetching RSS feed... please stand by

The Simpsons - Steve Mobs 

Mapple Computer ? Steve Mobs ?

powered by Youtube

Extracting Text Using Offset and Reverse vs Text Item Delimiters 

Airport ExtremeExtracting Text Using Offset and Reverse vs Text Item Delimiters

There are times when you want to extract part of a text string from another for some specific purpose. There are two basic methods and each has its advantages and disadvantages. We'll start with a combination of offset and reverse to remove the suffix from "seattleSunset.jpg":

set jpgFile to characters of "seattleSunset.jpg"

--This gives us the characters as a list: {"s", "e", "a", "t", "t", "l", "e", "S", "u", "n", "s", "e", "t", ".", "j", "p", "g"}

set jpgFile to (reverse of jpgFile) as string

-->result: "gpj.tesnuSelttaes"


Or we can combine the statements into one:



set jpgFile to (reverse of characters of "seattleSunset.jpg") as string

-->result: "gpj.tesnuSelttaes"


Next we extract the file name without the prefix:


set periodDelimiter to offset of "." in jpgFile

set jpgFile to text (periodDelimiter + 1) thru -1 of jpgFile

-->result: "tesnuSelttaes"


set AppleScript's text item delimiters to {""} --we must reset the item delimiters to empty for this to work correctly

set jpgFile to (reverse of characters of jpgFile) as string

--After resetting the item delimiters, we use the same syntax as above.


First, remembering that what is in parentheses is performed first, jpgFile is coerced to list form and converted to the reverse order.


Then it is coerced back to a string: "seattleSunset"


If we start with set jpgFile to characters of "seattleSunset.jpeg" we still get the result: "seattleSunset"


Note that we could set the text item delimiters to "." to get the same result:


set AppleScript's text item delimiters to "."

set jpgFile to text item 1 of "seattleSunset.jpg"

-->result: "seattleSunset"



The problem with this method is that if we have something such as "http://www.scriptsforapple.com/" (my website), the result is: "http://www", which is probably not the result that we want. The original version, however gives us "http://www.scriptsforapple" which is useful if we want to change ".com/" to ".org/":


set AppleScript's text item delimiters to "."

set theURL to "http://www.scriptsforapple.com/"

set AppleScript's text item delimiters to {""}

set trimURL to (reverse of characters of theURL) as string

set periodDelimiter to offset of "." in trimURL

set trimURL to text (periodDelimiter + 1) thru -1 of trimURL

set trimURL to (reverse of characters of trimURL) as string

set theURL to trimURL & ".org/"

-->"http://www.scriptsforapple.org/"


The point here being that if you use this method, you can get the correct result for many, if not most, cases that you will encounter. That is not to say that there are not times when using text item delimiters alone will not be the right way to go depending upon the situation.



Give me your opinion on my site. Please go to the AppleScript Guestbook and leave a comment or suggestion. If you like this site, please click on one of the stars at the top of the page to rate me.

New Drawing Document with AppleWorks 6 

The basics of creating a drawing document with AppleWorks 6 are similar to those for creating a text document.

Apple iMac G5The script below, appropriately named 'Graphics Hodgepodge', shows a variety of graphics objects that can be created and some of the properties that can be set with a script. There are a lot of details in this script, so we won't go into all of them. Reading the script should be explanation enough for most of this:

property cyan : {0, 65534, 65534}
property yellow : {65534, 65534, 0}
property red : {65534, 0, 0}
property blue : {0, 0, 65534}
property violet : {55000, 0, 65534}
tell application "AppleWorks 6"
make new document at front with properties ¬
{document kind:drawing document, name:"Graphics Hodgepodge"}
tell document "Graphics Hodgepodge"
set firstObject to (make new oval at front with properties {fill color:cyan})
set {xleft, ytop, xright, ybottom} to bounds of firstObject
make new rectangle at end with properties ¬
{fill color:yellow, bounds:{0, 250, 800, 500}, fill pattern:18}
make new rounded rectangle at end with properties ¬
{fill gradient:8, bounds:{xleft + 0, ytop + 40, xright + 400, ybottom + 40}, fill color:blue}
make new polygon at end with properties {fill color:red, fill pattern:16} with data ¬
{{xleft + 60, ytop + 60}, {xleft + 60, ytop + 160}, {xleft + 160, ytop + 160}, {xleft + 60, ytop + 60}}
set lastOval to (make new oval at front with properties {fill color:red})
select lastOval
set properties of firstObject to {bounds:{xleft + 0, ytop + 40, xright + 400, ybottom + 40}}
set properties of firstObject to {fill color:violet, fill pattern:64}
end tell
end tell



First we use properties to store RGB info on the colors we will use (saves some typing).

Next we tell AppleWorks to create a drawing document for us:

make new document at front with properties ¬
{document kind:drawing document, name:"Graphics Hodgepodge"}


In the next part, we direct statements to our new document "Graphics Hodgepodge":

set firstObject to (make new oval at front with properties {fill color:cyan})
set {xleft, ytop, xright, ybottom} to bounds of firstObject


This creates our first object, an oval, with the variables 'xleft, ytop, xright, ybottom' for the default object dimensions that will be used later and assigns a reference to the object (also needed later) to the variable firstObject.

The rest of the script pretty much explains itself. To create a new object use the syntax: 'make new objectType', where objectType can be oval (used also for circle), rectangle (used also for square), rounded rectangle and polygon. Use the bounds parameter to determine the size of the object.
You use fill gradient and fill pattern with an integer reference to the gradients (there are 32) and patterns (there are 64) available from their respective palettes.

Add to Technorati Favorites



By the way, for other types of AppleWorks documents, document kind can be any of the following: drawing document,text document,spreadsheet document,database document, painting document, presentation document

For example:

 



Questions or comments? Contact me at: hyperscripter@gmail.com or if you like this site, click on the twitter icon at the top of or bottom of the page the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Creating a Calendar in TextEdit with Shell Script 

Apple IIc ImageThis is sort of a fun script which gives you some idea of the power behind the UNIX side of Mac OS X. Impressive as this little bit of shell code is though, it only scratches the surface on what you can do combining the power of AppleScript with the shell.

display dialog "Choose a color for your calendar" buttons {"OK"} default button 1 giving up after 1
choose color default color {65535, 5786, 28421}
set calendarColor to the result
set defaultYear to year of (current date)
display dialog "Enter desired calendar year:" default answer defaultYear buttons {"Cancel", "Make Calendar"} default button 2
copy the result as list to {calendarYear, returnedButton}
if returnedButton = "Make Calendar" then
set cmdResult to (do shell script "cal " & calendarYear)
tell application "TextEdit"
activate
set yearCalendar to make new document with properties {text:cmdResult}
set properties of text of yearCalendar to {size:12.0, color:calendarColor, font:"Monaco"}
--Font must be monospaced type like Andale Mono,Monaco,Courier,Courier New for correct formatting
set bounds of window 1 to {0, 22, 612, 792}
end tell
else
try
on error errorMsg number errorNumber
set errorText to "Error: " & the errorNumber & ". " & errorMsg
display dialog errorText buttons {"OK"} default button 1
return errorText
end try
end if

Delicious
Bookmark this on Delicious




Give me your opinion on my site. Please scroll to the feedback section below and leave me a comment or follow me on twitter: http://twitter.com/hyperscripter
.

Amazon Featured Book on AppleScript 

This Book was Quite a Find

If you aspire to be an AppleScript Guru, I highly recommend AppleScript 1-2-3. It has expanded my knowledge of AppleScript Immensely.

Apple Training Series: AppleScript 1-2-3

Amazon Price: $31.49 (as of 12/20/2009)Buy Now
List Price: $49.99
Used Price: $29.13

If you aspire to be an AppleScript Guru, I highly recommend AppleScript 1-2-3. It has expanded my knowledge of AppleScript Immensely.

Release Date: 12/31/1969

Avg. Customer Rating: Amazon Rating

Usually ships in 24 hours

Engadget Clips 

Exclusive: Klipsch introduces iPhone-friendly Image X10i and black / white S4i earbuds
We recently had the opportunity to tour Klipsch's headquarters in Indianapolis, Indiana, and while w...
Panasonic Lumix DMC-FP8 reviewed: as good as 'a loaf of plain white bread'
It's hard to imagine complaining about a stylish compact camera that packs a stabilized 28-128mm zoo...
Re transforms your iPhone into a universal remote (which seems like a step backwards, to be honest)
OK, so we know a thing or two about the "convenience" of using your iPhone as a remote control. For...

Formatting and Editing Text Objects with Word 2008 

Microsoft Word 2008While Microsoft has its own scripting language (Visual Basic for Applications or 'VBA') to do all (most) of the same things as presented here, it is rather clunky and difficult to use compared with the more natural syntax of AppleScript.

Here we will look at some of the most necessary scripting elements for Word 2008 through a single document named 'MyText.doc'.

First creating and opening the newly created document:


tell application "Microsoft Word"
activate
set createDoc to make new document
set name of font object of text object of createDoc to "Lucida Grande"
set size of font object of text object of createDoc to "14"
save as createDoc file name "MyText.doc"
open createDoc
end tell

'set createDoc to make new document' creates the new document and places a file reference to the new document into the variable 'createDoc'

Once that reference to the document is made, you can direct individual statements to the reference named createDoc or within a tell block:

tell createdoc
...
end tell

Now, let's look at a few ways that you can edit text in the document given this initial text:

It was a stormy day as I set out on my journey to learn how to write my first AppleScript with Microsoft Word 2008.



tell createDoc
select word 4 of createDoc (or select word 4 of active document)
set bold of font object of selection to true
set content of text object of selection to "sunny"
end tell

This results in:

It was a sunny day as I set out on my journey to learn how to write my first AppleScript with Microsoft Word 2008.



The fourth word is selected, its font style set to bold, and its content changed to 'sunny'.

Note that changing styles of the selected text requires the use of the expression 'font object' and to replace the content with the word 'sunny' you must use 'text object'.

Then to add text to the end of the document by way of a text entry dialog:


set appendText to text returned of (display dialog "Enter text to append to the end of this document:" default answer "" buttons {"Cancel","Insert"} default button "Insert")
set appendText to (return & return & appendText)
insert text appendText at end of text object of active document



Questions or comments? Contact me at: hyperscripter@gmail.com or if you like this site, click on the twitter icon at the top of or bottom of the page the page. For RSS feed, click the RSS icon at the top or bottom of the page.

 

Apple Mac OS X Fade Blue

Enhanced - New Doc for AppleWorks 6 

A more detailed script with text entry fields.

Apple Mac CubeIt has become abundantly clear to me that there is still a lot of interest in AppleScripts for AppleWorks 6 and questions on implementation of scripts that my previous posts on this topic have not addressed to the satisfaction of those who use AppleWorks 6 and, since it is an application that is still fairly universal in the Mac OS, I guess it is worth further examination. So, here's an enhancement of an earlier script that I hope will be useful:

set theDocName to text returned of (display dialog "Enter new document name:" default answer "" buttons {"Set"} default button {"Set"})
set paragraph1 to text returned of (display dialog "Enter text for first paragraph of document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
-->Given this entered text: Notes on AppleScript and AppleWorks 6:
set paragraph2 to text returned of (display dialog "Enter text for second paragraph of document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
-->Given this entered text: As it appears in this document, this is the second paragraph but, to AppleScript,this is the third paragraph, because even an empty return is a paragraph in AppleScript.
set paragraph3 to text returned of (display dialog "Enter text for third paragraph of document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
-->Given this entered text: This, it would seem is the fourth paragraph but, it is actually the fifth to AppleScript.
set theData to paragraph1 & return & return & paragraph2 & return & return & paragraph3
tell application "AppleWorks 6"
activate
make new document with data theData with properties {name:theDocName}
tell front document
select paragraph 1
set the properties of the selection to {font:"Lucida Grande", size:18}
set color of the selection to {9960, 12194, 65535} --blue, an RGB value
select (paragraphs 3 thru 5)
set the properties of the selection to {font:"Monaco", size:9}
select word 14 of paragraph 3
set the properties of the selection to {size:12}
set size of the selection to 12
--Two ways to express things (look above)

set colorPref to default color {65535, 5195, 6617} --red, an RGB value
set color of the selection to colorPref
select (text 1 thru -1 of last word of paragraph 3)
set size of the selection to 12
set color of the selection to colorPref --red, an RGB value
select (text 1 thru -1 of last word of last paragraph)
set size of the selection to 12
set color of the selection to colorPref --red, an RGB value
save document theDocName in alias (path to desktop folder) as file type {"CWWP"}
end tell
end tell



Most of this is pretty straightforward. Take note of my use of negative indexes to groups of text above.

This could be used to change the color of a number of words in the initial script all at once:


tell application "AppleWorks 6"
tell front document
try
set everyWord to (every text)
set textCount to (count everyWord)
repeat with x from 7 to textCount
if word x = "AppleScript" then
select word x
set color of the selection to {65535, 5195, 6617} --red
end if
end repeat
on error
return
end try
end tell
end tell



This is how the initial script would appear:

AppleWorks Text

To change the text style is a bit more complicated, something like this would work:


tell paragraph 1
select (words 3 thru 4)
set size of the selection to 14
set style of the selection to {class:text style info, on styles:{bold, italic}}
select word 6
set size of the selection to 14
set style of the selection to {class:text style info, on styles:{bold, outline}}
end tell

Which would look something like this:

EnhancedDoc2

If you run this script in the Script editor with our document in front...

tell application "AppleWorks 6"
activate
tell front document
select paragraph 1
get properties of the selection
end tell
end tell

The result for the text below (our first line), gives us some idea of the kinds of information we have at our disposal for writing scripts:

EnhancedProperties

Out of this, we can see that we have these styles available:

{plain, bold, italic, underline, outline, shadow, condensed, expanded, strikethrough, superscript, subscript, superior, inferior, double underline}

Give me your opinion on my site. Please go to the AppleScript Guestbook and leave a comment or suggestion. If you like this site, please click on one of the stars at the top of the page to rate me,

The Mactini - Smallest Mac in the World 

Humor from BBC Two

powered by Youtube

Using Aliases and POSIX Paths 

Getting the Location of Files and Folders

Apple IIe Disk IIOver the time that I have been writing AppleScripts, I have found that one of the most difficult, if not frustrating, tasks of writing scripts is referencing files by path so that they can be accessed by other applications.

As you'll see below, creating a reference that is understandable by the Finder is fairly simple (not always though). These are common alias references, most of which are understood by pre-OSX versions of the system as well as OSX. In the following section we will not only take a look at how to get 'regular' file paths, but also how to get POSIX paths (like UNIX) that are sometimes useful in deriving a path in a format that you may need. First, a number of examples of regular, alias paths:

tell application "Finder" to get folder "FileMaker Databases" of desktop

--> result: folder "FileMaker Databases" of folder "Desktop" of folder "administrator" of folder "Users" of startup disk of application "Finder"

tell application "Finder"
set targetFolder to (get folder "FileMaker Databases" of desktop as alias)
open targetFolder
end tell
--> result: alias "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:"

set monthReportDoc to "Monthly Reports " & "2008.fp5"
tell application "Finder" to set targetDoc to (get file monthReportDoc of folder "FileMaker Databases" of desktop as alias)

--> result: alias "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:Monthly Reports 2008.fp5"

This script gets the path to a folder on the desktop containing FileMaker Pro databases and concatenates it together with a file name and sends it to FileMaker Pro to open it:

set monthReportDoc to "Monthly Reports " & "2008.fp5"
tell application "Finder" to set targetDoc to (get file monthReportDoc of folder "FileMaker Databases" of desktop)

--> result: document file "Monthly Reports 2008.fp5" of folder "FileMaker Databases" of folder "Desktop" of folder "administrator" of folder "Users" of startup disk of application "Finder"

tell application "FileMaker Pro"
activate
open targetDoc
end tell

Delicious
Bookmark this on Delicious



Sometimes you must specify the POSIX path. The only real difference is that the regular Mac OS path and the POSIX version differ in that the POSIX (UNIX) path separates the heirarchy (deliminates) with the forward slash '/', omitting the actual name of the HD, while the regular Mac path is delimited by ':' and includes the name of the hard Disk. Examine these two statements:

POSIX: "/Users/administrator/Desktop/FileMaker Databases/"

Mac Path: "Macintosh HD:Users:administrator:Desktop: FileMaker Databases:"

Follow this to go from an Alias to a POSIX path:

First, the path to the folder "FileMaker Databases" :

tell application "Finder" to get folder "FileMaker Databases" of desktop

--> result: folder "FileMaker Databases" of folder "Desktop" of folder "administrator" of folder "Users" of startup disk of application "Finder"

Then, the alias path to the folder:

tell application "Finder" to get folder "FileMaker Databases" of desktop as alias

--> result: alias "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:"

tell application "Finder" to get the POSIX path of (folder "FileMaker Databases" of desktop as alias)

(folder "FileMaker Databases" of desktop as alias) This, since it is enclosed in parenthesis, will be evaluated first. Then the POSIX path of that is derived.

--> result: "/Users/administrator/Desktop/FileMaker Databases/"

Then going from a POSIX to an Alias. Using the previous example:

"/Users/administrator/Desktop/FileMaker Databases/" as POSIX file
--> result: file "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:"

Since this is executed from left to right:

"/Users/administrator/Desktop/FileMaker Databases/" as POSIX file as alias

--> result: alias "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:"



Finally, if you're not exhausted by now, look at these comparisons, which give the same result:

folder "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:"

item "Macintosh HD:Users:administrator:Desktop:FileMaker Databases:"

As do these:

folder "FileMaker Databases" of folder "Desktop" of folder "administrator" of folder "Users" of startup disk of application "Finder"

item "FileMaker Databases" of folder "Desktop" of folder "administrator" of folder "Users" of startup disk of application "Finder"

A little precursor for what is to come:

tell application "Finder" to get the URL of home
--"file://localhost/Users/administrator/"


--you can use file://localhost/Users/administrator/ to show your HD in Firefox.


Digg!



Contact me if you have any questions or comments at: hyperscripter@gmail.com or if you like this site, click on the twitter icon at the top of or bottom of the page the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Using Info Window Data to Write Scripts 

Apple 1 PrototypeIn the initial section of this post, I leave the AppleScript code formatted as it would appear in the Script Editor pane to show that keywords, statements and other expressions that appear in blue in the Script Editor are part of the AppleScript language and syntax and knowing that is helpful when writing scripts.

Let's start with this statement:



The first statement get the full path to a document, in this case, "My Document.cwk" and the second, all of the information on the document:



This all looks pretty intense, but some of the info is only relevant for certain types of files (folders as opposed to documents, for instance) and although Applescript will return info in the form of an empty string or 'false' on some items, the info is usually of little use unless you are targeting the right file type.

With that in mind, let's look at some of the results that are relevant for the file "My Document.cwk" which is an AppleWorks Document:

Creation Date:

set filedate to creation date of (info for theFile) result--> date "Monday, June 8, 2009 8:24:34 AM"

Modification Date:

set fileModDate to modification date of (info for theFile) result--> date "Friday, July 17, 2009 10:48:20 PM"

File Size:

set fileSize to size of (info for theFile) result--> 1.9715E+4

Miscellaneous Info:

set isFolder to folder of (info for theFile)
set isAlias to alias of (info for theFile)
set isPackage to package folder of (info for theFile)
set isVisible to visible of (info for theFile)
set extHidden to extension hidden of (info for theFile)
set fileLocked to locked of (info for theFile) --all of these return a boolean (true or false) value and some are only relevant when the target is a folder.


The following, I find the most useful for what I usually need to do:


set extName to name extension of (info for theFile) --> result: "cwk"

set displayName to displayed name of (info for theFile) --> result: "My Document.cwk"

set defaultApp to default application of (info for theFile) --> result: alias "Macintosh HD:Applications:AppleWorks 6:AppleWorks 6.app:"

set fileKind to kind of (info for theFile) --> result: "com.apple.appleworks.document"

set fileType to file type of (info for theFile) --> result: "CWWP"

set fileCreator to file creator of (info for theFile) --> result: "BOBO"

set fileTypeIdentifier to type identifier of (info for theFile) --> result: "com.apple.appleworks.cwk"

Just something to note on a similar subject:

short version of (info for theFile) and long version of (info for theFile) are mainly only relevant for applications such as this case with AppleWorks 6:

"AppleWorks 6.2.4 for Mac OS X Copyright Apple Computer, Inc. 1991-2002" --> the long version of AppleWorks 6

If you get the info for a file and place it into a variable, then you can use that to simplify and extract specific items of the info variable and place them into their own specifice variables such as this one using our original document:

set theFile to choose file with prompt "Please select a file:"
set fileInfo to (info for theFile)
set fileDate to creation date of fileInfo

Here's an 'all purpose' script to open a document. It gives you some idea of how you can use data from a documents 'Get Info' window. What is shown here will work with most documents, provided you have the application on your desktop.

set theFile to choose file with prompt "Please select the file you want to open:"
set fileInfo to info for theFile
set theFile to theFile as alias
set defaultString to ((default application of fileInfo) as string)
set AppleScript's text item delimiters to ":"
set AppString to (text item -2 of defaultString)
set AppleScript's text item delimiters to "."
set theApp to (text item -2 of AppString)
openDoc(theFile, theApp)
on openDoc(fileName, defaultApp)
tell application defaultApp
activate
open fileName
end tell
end openDoc



If you have any questions or comments please scroll up to my Guestbook above or, if you like this site, give me a star rating at the top of the page.

AppleScript Guestbook 

Give me your opinion, topics you'd like covered, or whatever else you want to say...

submit

AppleScript for Sending Email with Apple Mail 

This is a very straightforward script to send data to Apple's Mail application.

Apple Mac Mail There isn't really anything difficult here. It should suffice to note here the AppleScript terms and expressions used here that are unique to the Mail application. You'll often find that an application has, along with the standard terms that are used by all applications, some that are specific to the application and therefore must be enclosed in a tell block that directs them to the app you're using.



set theRecipient to text returned of (display dialog "Enter recipient:" with icon note default answer "yourEmail@domain.com" buttons {"Cancel","OK"} default button {"OK"})
set theSubject to text returned of (display dialog "Enter subject of email:" with icon note default answer "Re: New Subject"
buttons {"Cancel","OK"} default button {"OK"})
set emailText to text returned of (display dialog "Enter your email message here:" with icon note default answer "This is the text of your email message"
buttons {"Cancel","Send"} default button {"Send"})
tell application "Mail"
activate
set theMessage to make new outgoing message
tell theMessage

set the subject to theSubject
set the content to emailText
make new to recipient at end of to recipients with properties {address:theRecipient}
end tell
save theMessage
end tell

The statement: 'set theMessage to make new outgoing message' sets things up so that the following commands in the tell block can be directed to the variable theMessage as an object.

The next two statements set the values of the subject and content fields to the variables
'theSubject' and 'emailText' respectively.

Next, the value of the Mail property 'address' is set to the value of the variable
'theRecipient'.

Finally, the save command is directed to the Mail application, since it cannot be handled by 'theMessage' as it is, in effect a document.

Please leave a comment in my AppleScript Guestbook above or if you like this site, click on the twitter icon at the top or bottom of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Add to Technorati Favorites

Books at Amazon.com 

I have had a great experience with Amazon, so I highly recommend them...

Concatenation or Parsing and Editing of Text Strings 

In this section we deal with various methods to extract different parts of text from lists and other text and at the end, how to put it all together to make a new text string.

Apple AppleScript DocumentThis is sort of lengthy, but it is pretty easy to follow

First, to extract text from a list. Both of these result in the text "Computer":

set theTextList to {"Apple", "Computer"} as list
last item of theTextList
last text item of theTextList --> both statements yield 'Computer'



And then using the 'reverse' keyword:

set theTextList to {"Apple", "Computer", "Inc"} as list
last text item of theTextList --> yields "Inc"
set theTextList to reverse of theTextList --> yields {"Inc", "Computer", "Apple"}
last text item of theTextList --> yields "Apple"


As you can see, the keyword 'reverse' changes the order of items in a list.

If we want to extract a specific word:

set theTextString to "Apple Computer, Inc"
set theAppleString to word 1 of theTextString
display dialog theAppleString --> yields "Apple"



If we want to extract a specific paragraph:

set theTextString to "Apple Computer, Inc" & return & "Home of Mac OS X"
set theAppleString to paragraph 2 of theTextString
display dialog theAppleString --> yields "Home of Mac OS X"



Extracting by numerical index:

set theTextString to "Apple Computer"
set computerStringStart to offset of "Computer" in theTextString
display dialog computerStringStart --> yields 7: position of first letter in the word 'Computer'
set computerText to (text computerStringStart thru -1 of theTextString)
display dialog computerText --> yields 'Computer'-1 is the index for the last letter of the text string, no matter how long the string is; a lot easier than having to determine how long the string is every time!



The same as saying:

set computerText to (text 7 thru -1 of theTextString)
Of course, if we wanted to, we could say:
'set computerText to (text 7 thru 14 of theTextString)' but why?





set theTextString to "Apple Computer"
set theAppleString to text 7 thru -2 of theTextString
display dialog theAppleString --> yields 'Compute'-2 gets the numeric index of the letter in 'Computer' that is 2 from the end.



set theTextString to "Apple Computer, Inc"
set theAppleString to text 1 thru -1 of theTextString
display dialog theAppleString --> yields: "Apple Computer, Inc"



set theTextString to "Apple Computer, Inc"
set theAppleString to (words 1 thru -1 of theTextString) as text
display dialog theAppleString --> yields "AppleComputerInc"



set AppleScript's text item delimiters to ","
set theTextString to "Apple Computer, Inc"
set theAppleString to (text items 1 thru -2 of theTextString) as text
display dialog theAppleString --> yields "Apple Computer"



The following would give the same result:

set AppleScript's text item delimiters to ","
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 1 of theTextString) as text
display dialog theAppleString



Why? Because with 'set AppleScript's text item delimiters to ","' , what is found before a comma is a text item and what is after a comma is another text item - this can be very useful.

Look at this:


set AppleScript's text item delimiters to " "
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 1 of theTextString) as text
display dialog theAppleString --> this yields "Apple", because the space determines the value of text items.



set AppleScript's text item delimiters to " "
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 2 of theTextString) as text
display dialog theAppleString --> this yields "Computer,", because the space determines the value of text items.




Digg!



This illustrates how to concatenate some text to display a dialog:

set AppleScript's text item delimiters to " "
set theTextString to "Apple Computer, Inc"
set theAppleString to (text item 1 of theTextString) as text



--> the result is "Apple", because the space determines the value of text items.

set theComputerString to (text 1 thru -2 of text item 2 of theTextString) as text



--> the result is "Computer", because the space determines the value of text items and 'text 1 thru -2' eliminates the comma.

Now we can put it all together:

set dialogString to "Too bad all " & theComputerString & "'s aren't " & theAppleString & "s!"
display dialog dialogString with icon note buttons {"No Doubt"} default button {"No Doubt"} giving up after 5



Contact me if you have any questions or comments at: hyperscripter@gmail.com

Using Say and Listen Commands with iTunes 

In this post we look at the say and listen commands. It is a natural transition from the previous iTunes script.

Apple iTunes
Before you try to run this script, go to the Speech Preferences and click on the Speech Recognition tab and click speech on. Also, if you have not used speech recognition before, click on the 'Calibrate...' button. It adjusts speech recognition to your personal voice to optimize its responsiveness. To refresh your memory, here is the script from the previous post, which we will use (in part) in this post. The key statements used in the script to follow are in bold text:


tell application "iTunes"
activate
set visible of front window to true
set view of front window to playlist "Hall & Oates"
copy (get view of front window) to thePlaylist

set soundValue to (choose from list {"25", "50", "75", "100"} with prompt "Select volume level:" OK button name "Play" cancel button name "Abort")
set soundValue to soundValue as integer
set sound volume to soundValue
play thePlaylist
end tell


The new script:

tell application "iTunes"
activate
set visible of front window to true
set myMusic to (name of every playlist)
end tell
set the userResponse to voiceQuery("Which playlist would you like to hear?", myMusic, 30)
if the userResponse is false then error number -128
say "Playing " & userResponse & " please wait"
tell application "iTunes"
activate
set thePlaylist to userResponse
set view of front window to playlist thePlaylist
copy (get view of front window) to thePlaylist
play thePlaylist
end tell

on voiceQuery(userPrompt, theseItems, timeoutValue)
set the cancelCmds to {"Cancel"}
set the matchItems to cancelCmds & theseItems
try
tell application "SpeechRecognitionServer"
set the userResponse to listen for matchItems with prompt userPrompt giving up after timeoutValue displaying theseItems
end tell
if the userResponse is in the cancelCmds then
error "user cancelled"
end if
return userResponse
on error
display dialog "The music did not play!"
return false
end try
end voiceQuery



The statement '
set myMusic to (name of every playlist)' gets all of the playlists on your hard drive and puts them into the variable myMusic.

The statement
'voiceQuery("Which playlist would you like to hear?", myMusic, 30)' calls the function 'on voiceQuery(userPrompt, theseItems, timeoutValue)' and places the values into the corresponding variable parameters.

voiceQuery(...) returns a value in the variable userResponse and, if it is not false, plays the desired playlist.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, click on the twitter icon at the top or bottom of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Music From Amazon MP3 

Some of My Favorite Bands and Artists

Growing up in the 70's and 80's, whether it was Elton John or Stevie Wonder, The Beatles or Aerosmith, Boston or Steely Dan, Patti Labelle or ELO and so on, this was my true era of music.

Whatever your musical inclinations, you can find your favorite music at amazon.com. Click on the arrow in the center of the music window to hear previews of my favorites.

Enjoy!

An AppleScript for iTunes Playlists 

Here is a simple AppleScript for iTunes which chooses a pre-determined playlist from your iTunes library, then prompts for the volume level. After all of this is done, it plays the selected playlist at the specified volume level:

Apple iPod Shuffle Bluetell application "iTunes"
activate
set visible of front window to true
set view of front window to playlist "Hall & Oates"
copy (get view of front window) to thePlaylist
set soundValue to (choose from list {"25", "50", "75", "100"} with prompt "Select volume level:" OK button name "Play" cancel button name "Abort")
set soundValue to soundValue as integer
set sound volume to soundValue
play thePlaylist
end tell

The line
'copy (get view of front window) to thePlaylist' assigns, in this case, "Hall & Oates" to the variable thePlaylist (the name assigned must be the actual name of an existing playlist). The second important thing to note here: set soundValue to soundValue as integer. This is required because the list dialog returns a text value, so we must coerce the value to integer.

There is one problem with this script. If we click on the 'Abort' button the playlist is still played. This problem can be handled with a conditional which will 'trap' for this such as:
if soundValue is not "false" then play thePlaylist.

An enhancement of the above script:


tell application "iTunes"
activate
set visible of front window to true
set thePlaylist to (choose from list {"Hall & Oates", "Aja", "Elton John", "ELO"} with prompt "Select a playlist:" OK button name "Choose" cancel button name "Abort") as text
if thePlaylist is not "false" then
set view of front window to playlist thePlaylist
copy (get view of front window) to thePlaylist
set soundValue to (choose from list {0, 25, 50, 75, 100} with prompt "Select volume level (0 for mute):" OK button name "Play" cancel button name "Abort")
if soundValue is not "false" then
set sound volume to soundValue
play thePlaylist
end if
end if
end tell

In this second script we use a choose list command to get the playlist we will use. Also in this script, we assign names to the button choices: OK button name "Play" cancel button name "Abort"

Finally, we use 0 for when we want to make the sound mute:
{0, 25, 50, 75, 100} and since the number list items are not enclosed in quotes, AppleScript does not need to coerce the chosen value to integer.

If you wanted to get all of your playlists to appear in a choose from list dialog it would go something like this:

set thePlaylists to (name of every playlist)
set thePlaylist to (choose from list thePlaylists with prompt "Select a playlist:" OK button name "Choose" cancel button name "Abort") as text

If you have further questions on scripting with iTunes or would like to suggest a post on another AppleScript issue, please scroll to my AppleScript Guestbook above

Choosing a Color from the Color Picker 

Apple Color Picker WindowThe final 'choose' command, 'choose color' will be covered here. The choose color dialog is somewhat obscure and you aren't as likely to use it as the others, but it is worth mention. It is not complicated at all. The script below results in the color picker window, with the rainbow effect as in the image to the left:

set colorPref to choose color default color {31270,38327,65535}

If the user clicks on the "OK" button without choosing a color, the RGB value {31270,38327,65535} is assigned to the variable colorPref, otherwise its value is set to whatever RGB value results from where the user clicked in the color wheel.


We can then use that value in a script such as this which changes the background color of the frontmost finder window:


set colorPref to choose color default color {31270,38327,65535}
tell application "Finder"
activate
tell the icon view options of the front Finder window
set the background color to colorPref
end tell
set the current view of the front Finder window to icon view
end tell



This changes the background color for the icon view only. All of the other views remain unchanged.

Contact me with your questions or suggestions at: hyperscripter@gmail.com or visit my AppleScript Guestbook above.
If you are interested in similar subject matter to this, be sure to scroll up and down this area of the page for other examples using 'choose'

Add to Technorati Favorites

Choose Application 

The 'choose application' command is very similar in syntax to the 'choose file' command.

Apple Mac Performa CDThe two commands are so similar that I will not go into too much detail. As I have done in some other posts, I will present a script and then explain the purpose of the parameters used as needed:

set theApp to choose application with title "Installed Applications:" with prompt "Select an application:"

With a result in the form:application "Adobe ImageReady 7.0". The application is automatically opened.


Both of the parameters here, you should recognize.

Here is an example of how the
'choose file' and 'choose application' commands can be used together to open a text file:

set theFile to choose file of type "TEXT" with prompt "Locate a text document to open"
set theApp to choose application with title "Installed Applications:" with prompt "Select an application to open '" & theFile & "':" as alias
tell application "Finder"
open thefile using theApp
end tell



This is all pretty straightforward, so if you carefully look over the syntax of this, I don't expect you will have any difficulty with this.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, click on the twitter icon at the top or bottom of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Enhanced Choose from List (Tiger and Leopard) 

New parameters that are available in Tiger (10.4) and Leopard (10.5)

Apple iMac ZoomIn case you need to refresh your memory, here is the basic command:

set theName to (choose from list {"John", "Joe", "Bill"} with prompt "Choose a name:")
if theName is false then
display dialog "You clicked cancel to exit." with icon stop buttons {"Exit"} default button {"Exit"}
else
set theName to (item 1 of theName)
display dialog theName with icon note buttons {"Info"} default button {"Info"}
end if

Since there are a number of enhancements to cover here, I will start by presenting a script which uses all of them (they are highlighted), and then explain their significance:

set theName to (choose from list {"John", "Joe", "Bill"} with prompt "Choose a name:" with title "Database Names" default items {"Joe"} with multiple selections allowed OK button name "Choose" cancel button name "Abort")
if theName is false then
display dialog "You clicked cancel to exit." with icon stop buttons {"Exit"} default button {"Exit"}
else
set theName to (item 1 of theName)
display dialog theName with icon note buttons {"Info"} default button {"Info"}
end if

with title "Database Names": sets the text in the titlebar to "Database Names"
default items {"Joe"}: The dialog selection 'Joe' is selected when the dialog opens.
with multiple selections allowed: If you click on more than 1 item while holding down the shift key a comma-delimited list of the items is returned as the result.
OK button name "Choose": The OK button is renamed "Choose" and behaves as the "OK" button would.
cancel button name "Abort": The cancel button is renamed "Abort" and behaves as the "Cancel" button would.

The 'choose application' command will be covered in the next post. It is somewhat similar to the 'choose file' dialog.

Please scroll to my AppleScript Guestbook above and leave a comment or suggestion on this or another AppleScript topic.

Choose File Name Command 

The 'choose file name' command is similar to the 'choose file' command

Apple Choose File NameUnlike the choose file command, 'choose file name' returns a reference pointer to a file that does not yet exist without actually creating the file:

set theFile to choose file name with prompt "Set file name and location:"

With a result such as:file "Macintosh HD:Users:administrator:Desktop:Untitled"

Choose file name dialogs have 3 optional parameters: 'with prompt' , 'default name' and 'default location'.

Here with the optional parameters:

set theFile to choose file name with prompt "Set file name and location:" default name "Document 1" default location (path to documents folder)

It is pretty simple to see that the last two parameters determine the name of the yet to be created document and its location.

Finally, a TextEdit example that actually creates a document:

set fileReference to choose file name with prompt ("Create new document:") default name "My Text Document" default location (path to desktop)
set newDocText to text returned of (display dialog "Enter initial text for document '" & fileReference & "':" default answer "" with icon note buttons "OK" default button "OK")
open for access fileReference
close access fileReference

tell application "TextEdit"
activate
open fileReference
set text of document 1 to newDocText
end tell

Where fileReference is the reference for the new document and newDocText is the initial text for the new document.

These lines create the new document and then close it:

open for access fileReference
close access fileReference

TextEdit reopens the document and inserts the text stored in the variable
newDocText. TextEdit refers to the document as document 1 because it is the front document.

In the next post, I will backtrack a little bit to show you the enhanced parameters for 'choose from list' which are available in Tiger and Leopard.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, click on the twitter icon at the top or bottom of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Choose File Dialogs 

Getting a reference to a specific document for further script execution.

Apple Choose FileIn this post, we continue with the 'choose file' command. Like the 'choose folder' command, it returns a reference pointer to the actual file that it represents. In this case, it returns an alias reference to a document such as:

set theFile to choose file with prompt "Select a file to open:"

With the following result:alias "Macintosh HD:Users:administrator:Documents:My Document.cwk"



Choose file dialogs have 3 of the same 4 optional parameters, which function identically to the ones used with choose folder dialogs (there is no showing package contents parameter): default location, with (or without) invisibles and with multiple selections allowed.

One additional parameter, not available with the choose folder command is the 'of type' parameter. This is used when you want to specify what types of files to show:

set theFile to choose file of type {"public.jpg","public.gif"} with prompt "Select a file to open:"

If you like this site, click on the twitter icon at the top or bottom of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Choose Folder Dialogs 

Apple MacBook Clamshell TangerineIn the next few posts, we will look at dialogs where the user chooses among items in directories on the desktop that return reference pointers to the actual files (most are aliases) that they represent. The dialogs we will deal with here are 'choose folder', 'choose file', 'choose file name' and 'choose color'.

First, a simple 'choose folder' dialog:

set theFolder to choose folder with prompt "Select a folder:"

Which brings up the following dialog with the result:alias "HyperMac HD:Users:administrator:Documents:"




SimpleChooseFolder






Where 'prompt' is the text string that appears at the top of the dialog window. When the user selects a folder the alias to that folder is placed in the variable 'thefolder'

There are 4 optional parameters: default location, with (or without) invisibles, with multiple selections allowed and showing package contents. Together they look like this:

set theFolder to choose folder with prompt ("Select a folder:") default location (path to documents folder) with invisibles, multiple selections allowed and showing package contents

Although you aren't likely to use all of the possible parameters, I will explain each one here:

default location: The dialog opens with the specified path shown
with invisibles: This shows files that aren't ordinarily visible. Most of you will not need to use this parameter, it can be dangerous to tinker with these files, but if you have a reason...
multiple selections allowed: This allows you to choose more than one folder; each folder alias is separated by a comma in the form: {alias 1,alias 2.....}
showing package contents: This is also not ordinarily visible to the user; it displays bundle contents of application packages.

The next post will cover the
'choose file' command, which allows you to select a specific document and get its alias for further script execution. It has parameters that are very similar to the 'choose folder' command, so it should be very easy to pick up how to use it.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Discerning Between When to Use Set and When to Use Copy 

Sometimes set and copy can be used interchangeably, sometimes not!

Apple Mac for the restThis one can be a difficult one, but if you have been following my posts so far, or otherwise are that much interested in learning AppleScript, this is an important issue to get straight.

Even if you have been using AppleScript for a while, as I have, you may still be unclear as to the difference between using set and using copy. In fact you may, as I thought for the longest time think that they are synonyms. This is in many cases true, such as in statements like:


set clientName to "Joe Gonzalez"

copy "Joe Gonzalez" to clientName

In both cases, the variable
clientName is set to the value of "Joe Gonzalez".

If we try to use these interchangeably in the following statements, however, we get very different results. To illustrate this, have a look at these two scripts, which, on the surface would appear to have the same result:


set todaysDate to current date
set tomorrowsDate to todaysDate
set day of tomorrowsDate to (day of todaysdate) + 1
return date string of todaysDate

The previous statement, it would seem, would give us the current date: say 'Tuesday, June 9, 2009'. Unexpectedly, the value of the variable 'todaysDate' is now 'Wednesday, June 10, 2009' - not what we want. The reason for this anomaly is that when we use set to 'set' the value of a second variable, any changes to the value of the second are also changed in the former. This is because 'set' makes the second variable a clone to the original.

If we want to use the original variable as an initial value for the second without effecting the value of the original then we must use the keyword
'copy':

set todaysDate to current date
copy todaysDate to tomorrowsDate
set day of tomorrowsDate to (day of todaysDate) + 1
return date string of todaysDate

In the second case with 'copy', todaysdate retains its original value; using copy instead of set makes the new variable tomorrowsDate an independent variable.

This principle holds true for lists, records and script objects as well. In other words, the set keyword is a reference to the original item which is why, with ordinary text strings they can be used interchangeably.

This is one of those things that you will encounter with AppleScript, where you can get the correct result every time you run a script and think that it will always work, and then you try to use it with another data type and get a big surprise.


Delicious
Bookmark this on Delicious



Questions or comments are always welcome (positive - hopefully or negative - if that is the case). Contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter.

Order Folder Items by Creation Date 

List items of a specified folder numerically by date of creation.

Apple IIc Abovetell application "Finder"
set itemGroup to sort (get every document file of the front Finder window) by creation date
repeat with x from 1 to count of itemGroup
set groupItem to item x of itemGroup
set the name of groupItem to ((x as string) & "-" & (the name of groupItem))
end repeat
end tell

First note that in statements such as the second line above, what is enclosed in parentheses is executed first (a list of the documents contained in the specified folder). Next that list is sorted by creation date and the value is placed in the variable itemGroup.

The repeat block takes that sorted list and places a number and a hyphen before each item name:

'((x as string) & "-" & (the name of groupItem))'

In place of creation date, you could also use
'name', 'size' or 'kind' as your sort criteria.

If after running this script, you decide that you want to restore things back to the way they were, this script will do it (BE SURE THAT YOU HAVE THE CORRECT WINDOW AS THE FRONT FINDER WINDOW):

tell application "Finder"
set itemGroup to (every document file of the front Finder window)
repeat with x from 1 to count of itemGroup
set groupItem to item x of itemGroup
set nameItem to the name of groupItem
set the hyphenOffset to (the offset of "-" in nameItem) + 1
set the originalName to text from the hyphenOffset to -1 of nameItem
set the name of groupItem to the originalName
end repeat
end tell

If you like this site, click on the twitter icon at the top or bottom of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

RSS: HTML Example Code 

Exploring the World of HTML and CSS Scripting

Loading Fetching RSS feed... please stand by

The Finder's Standard Suite 

These are the core commands that the Finder and every scriptable application should be able to handle.

Apple Computer Rosa ParksIn my last post, we took a look at how to use the Finder's print command, which is part of the Standard Suite. As promised, in this post we will now look at the remaining commands that make up the Standard Suite, namely: open,quit and activate.

While the last two are pretty simple to implement, the open command requires some explantion. First, the basic open syntax:


tell application "Finder" to open home

This is easy to understand, it simply tells the Finder to open home of your HD.

If you want to open a specific document, you would use a form such as:


tell application "Finder"
open document file "My Document.cwk" of folder "Documents" of home
end tell

Here, 'My Document.cwk' is replaced with your document residing in your 'Documents' folder (or which ever folder you desire).

To get the full path of a document, open the document and hold down the command key while clicking on the window's title bar. The result is something like:

(alias "Macintosh HD:Users:administrator:Documents:My Document.cwk")

Each level of the path is separated by a colon. The script would look like this:

tell application "Finder"
open document file (alias "Macintosh HD:Users:administrator:Documents:My Document.cwk")
end tell

Delicious
Bookmark this on Delicious



The basic quit and activate (bring app to front) commands take no parameters:

tell application "Finder" to quit

tell application "Finder" to activate

tell application "FileMaker Pro" to activate

tell application "AppleWorks 6" to activate

Remember that I covered the print command in my previous post.
If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

A Fun AppleScript for iTunes 

tell application "iTunes"
activate
set visible of front window to false
set view of front window to playlist "Hall & Oates"
copy (get view of front window) to thePlaylist
set soundValue to text returned of (display dialog "Enter sound volume (a number between 0 and 100-full volume):" default answer "25" buttons {"Cancel", "Play"} default button {"Play"})
set soundValue to soundValue as integer
set sound volume to soundValue
play playList

Basic Printing Scripts 

A few simple AppleScripts to automate your printing routine.

Apple Steve Jobs MacWorld Conference San FranciscoThe first script below is for printing a document in "TextEdit". Before running the script, you must bring the desired document to the front:


tell application "TextEdit"
print the front document with properties {copies:2, collating:true, starting page:1, ending page:1, pages across:1, pages down:1, error handling:standard} without print dialog
end tell



Most of what appears in 'with properties {....}' above should be fairly obvious. If you want to specify the printer, you could follow the last parameter in the list with a comma and 'target printer:' and the actual name of the desired printer enclosed in quotes.

If you want to use different printers in certain cases, replace 'without print dialog' with 'print dialog'

Add to Technorati Favorites



This second script, so that you aren't required to specify the application file targeted by the print command:


tell application "Printer Setup Utility"
set the current printer to printer "Deskjet D2400 series"
(alias "Macintosh HD:Users:administrator:Documents:My Document.cwk")
end tell



Replace 'Deskjet D2400 series' with the name of your printer and replace '(alias "Macintosh HD:Users:administrator:Documents:My Document.cwk")' with the path to the document that you wish to print (Don't forget to precede the path name by 'alias' - this is important).

The print command is part of the 'Standard Suite' of the Finder's Dictionary, and so, in my next post, We will look at the remaining commands that make up the Standard Suite (there are 3). If you have questions on printing or would like to suggest a post on an AppleScript issue you need help with, Please visit my AppleScript Guestbook

Display Dialog with Password 

A password dialog where text entered appears as bullets.

Apple Store Nagoya JapanThis script presents a text entry dialog where the text entered by the user is encrypted as bullets so that nosy people, for instance, cannot see what is being entered on your screen.

Seriously, though, the main purpose of this type of dialog is as a security measure to restrict access to critical files.


set thePass to "pass90805"
--Here, depending upon the application, you could have 'thePass' set to the value stored in a global field, In FileMaker it would be something like 'set thePass to data of cell "passwordStorage"'

considering case
repeat with x from 1 to 3
display dialog ("Enter the password for access to this file:") default answer "" with icon stop with hidden answer
if the text returned of the result is thePass then
exit repeat
end if
if x is 3 then return "You have attempted to access this file too many times. Your access is denied. Please try again."
end repeat
end considering

The considering case block tells AppleScript to require that the text entered match the particular case of the pre-determined password (upper or lower).

By the way, the part that gives the bullets instead of the actual text entered is
'with hidden answer'

The repeat block allows the user 3 attempts at entering the password for access and after that, terminates the script.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Get a Mac! 

#18 - Apple - Get a mac - Security

Why you'll love a mac ...

Runtime: 30
5314 views
8 Comments:

curated content from YouTube

'Display Alert' Dialogs 

Dialogs that display additional information to user.

Apple Hypercard Myst GearThese are a type of dialog, introduced in OS 10.4 (Tiger), which are similar to regular dialogs (in use as well as syntax), the noteable difference being that their purpose is to expand upon the standard 'display dialog'. They are used when it is important to impart further information on the state of the Finder or another application, where, for instance, some data loss could occur as a result of an incorrect action being taken.

try
display dialog ("Enter a number") default answer ("") buttons {"OK"} default button "OK"
set userEntry to text returned of result
return userEntry as number
on error
set alertString to "The text entered is not a number"
set messageString to ("" & userEntry & "is not a number. ") & "Run the script again and use only number keys."
display alert alertString message messageString buttons {"OK"} default button "OK" giving up after 20
end try

This is fairly straightforward, below the resulting dialog when the user happens to enter 'abc' (a non-numerical value):

displayalertdlog

Add to Technorati Favorites



If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Creating a New Document with Microsoft Word 2004 

Simple AppleScript to create a new text document with default text.

Apple Mac Cube and MonitorFor those of you who prefer to use Word for your text documents, this is a fairly straightforward script to create a new document with a default font and text and save it to your hard drive:

tell application "Microsoft Word"
activate
try
set newDoc to make new document
set name of font object of text object of newDoc to "Arial"
--Here you could have a 'text returned of' dialog to set the text font for the new document to a font of your choice. Of course, the font would have to exist on the target hard drive.

set documentName to text returned of (display dialog "Enter name for new document:" default answer "Untitled Document" with icon note buttons {"Cancel","Save"} default button {"Save"})
save as newDoc file name documentName
--By default, the document is created in the currently active folder.

set initialText to text returned of (display dialog "Enter initial text for new document:" default answer "" with icon note buttons {"Cancel","Insert"} default button {"Insert"})
if initialText<>"" then
set documentRange to create range active document start 0 end 0
insert text initialText at documentRange
end if
--If initialText has no value, then a text document is opened with no initial text.
on error
if documentName = "" then
display dialog "Document creation aborted!" with icon stop buttons {"OK"} default button {"OK"}
else
end if
end try
end tell

g5guts



The else part of the conditional above instructs AppleScript to ignore the fact that no initial text was requested for the new document and creates the document anyway. The value of 0 for start and end tells Word that it is a document that does not yet have any text or if there is existing text, to place it before the existing text .

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Add to Technorati Favorites

ArtByUs Artist Listings 

K.Warwel Cruise 2 Paintings 50x100cm landscape seascape
Current Price: $299.00
Buy it now: $340.00
End Date: Sunday Dec-20-2009 10:11:00 MST
Bid now | Buy it now | Watch this item
COBWEBS OF MY MIND ORIGINAL ABSTRACT OIL PAINTINGS GAYS ART
Current Price: $45.00
Buy it now: $45.00
End Date: Sunday Dec-20-2009 10:32:15 MST
Bid now | Buy it now | Watch this item

Powered by ArtByUs

Trapping for List Dialog Errors 

Intercepting the Dreaded 'Cancel' error (Error Number -128)

Apple Lisa FrontalWith 'List Dialog' type dialogs, since errors cannot be intercepted in an 'on error' handler, there is no 'normal' way to trap for 'Cancel' which, of course, would result in some sort of undesirable error dialog such as 'User cancelled. Error number -128'. Here is an example of one simple way I have found to trap for this type of error:

set x to (choose from list {"Joe","Amy","Bill"} with prompt "Choose a record:")
if x is false then
else
set targetItem to (x as text)
show every record whose cell "Name" contains x
end if

imacrainbow

When the user clicks on 'Cancel', the variable x is assigned the boolean value false. So all you have to do is set up a conditional clause to deal with that (notice it does nothing at all) and to perform the usual statements otherwise.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

AppleScript for Creating a New Document with AppleWorks 6 

Simple script to create a new AppleWorks document followed by a more detailed script with text entry fields.

Apple Mac Performa InsideIf you use AppleWorks 6, you may find this script useful in creating new documents. it should be fairly easy to see how this can be adapted to your specific needs:

set theDocName to "Simple Text Document"
set theData to "Basic text for new document"
tell application "AppleWorks 6"
activate
make new document with data theData with properties {name:theDocName}
tell front document
select paragraph 1
set the properties of the selection to {font:"Helvetica", size:24}
--Here, you could substitute for 'Helvetica', any font that you have available (Arial,Monaco,Geneva etc), and size, in this case '24', any size that you have available.
end tell
end tell

You could set 'theDocName' to the result of a query dialog where the user enters a specific name for the new document and 'theData' to the result of a dialog where the user enters the initial text for the new document.

Here's an idea of how this enhancement of the previous script would work:


set theDocName to text returned of (display dialog "Enter new document name:" default answer "" buttons {"Set"} default button {"Set"})
set theData to text returned of (display dialog "Enter initial text for document '" & theDocName & "':" default answer "" buttons {"OK"} default button {"OK"})
tell application "AppleWorks 6"
activate
make new document with data theData with properties {name:theDocName}
tell front document
select paragraph 1
set the properties of the selection to {font:"Helvetica", size:24}
end tell
end tell

Because I approach things as a progression, If you have read my previous posts, you will probably have a pretty good idea of how to write the dialog statements that I have suggested here. If you haven't seen my previous posts, I encourage you to check them out. My older posts are at the bottom of this page.

Delicious
Bookmark this on Delicious



Questions or comments are always welcome. If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

FileMaker Pro AppleScript to Backup Files 

Backup a specific folder of FileMaker documents, replacing previous backup files.

FileMaker Pro AppleScript BackupThis script was adapted from one written specifically for a FileMaker Pro program, although it could easily be used in any database program you use that supports AppleScript:

Most of what appears here builds upon the information presented in previous posts to this point.


tell application "Finder"
try
set todaysDate to (current date)
set bkpYear to (year of todaysDate)
set monthlyBkp to ("Monthly Reports " & bkpYear) as text
if not (folder "Database Backups" exists) then
set targetFolder to (make new folder at folder "Desktop" of startup disk with properties {name:"Database Backups"})
end if
set replaceExecute to button returned of (display dialog "Are you sure you want to replace current backup contents with the selected items?" with icon caution buttons {"Cancel","OK"} default button {"OK"} giving up after 60) -give user the chance to exit in case there is already a folder 'database backups' containing items that the user does not want to replace
if replaceExecute = "OK" then
select {file "Home Database" of folder "Database Programs)", ¬
file "Appointments" of folder "Database Programs", ¬
file monthlyBkp of folder "Database Programs", ¬
file "Accounts Receivable" of folder "Database Programs", ¬
file "Calendar" of folder "Database Programs"}
duplicate the selection to folder "Database Backups" replacing true -if we proceed, 'replacing true' replaces the contents of the folder "Database Backups"
end if
on error
display dialog "Backup cancelled!" with icon stop buttons {"OK"} default button {"OK"} giving up after 3
end try
end tell
tell application "FileMaker Pro" to activate

The next subject I will deal with addresses scripting for text formatting with AppleWorks 6 specifically, it is a simple but powerful script that can get you started with what you may want to do with text documents in general. Even if you use other text programs, you may find with a little knowledge of applescripting of the specific app that you use, this can be adapted to work with your document scripts.

If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

More on List Dialogs 

Continuing with list dialogs with an example that goes into more detail.

This post will deal with what I consider a very concrete use of the 'choose from list' dialog. After reading this (and perhaps trying it out in the Script Editor) you will probably be totally confused (just kidding!!) It gets a little complicated, but it is basically a cut-and-paste script.

If you pay close attention to my comments, I'm sure you'll understand most of what is going on and, after all, it's understanding how a script works that allows you adapt it to other applications that you may have in mind.



So anyway, here it is:

set AppleScript's text item delimiters to ","

-This first line is needed, because it sets things up for extracting the info we need.

set theLongDate to (current date)
set theLongDate to (date string of theLongDate)

-The next two lines set us up for calculating the numerical data for month and day.

set currentMonth to (word 1 of text item 2 of theLongDate)
set currentDay to (word 2 of text item 2 of theLongDate)

-This gets the numerical value for the month.

set currentYear to (word 1 of text item 3 of theLongDate)
set monthList to {January, February, March, April, May, June, July, August, September, October, November, December}
repeat with x from 1 to 12
if currentMonth = ((item x of monthList) as string) then
set theRequestNumber to (text -2 thru -1 of ("0" & x))
exit repeat
end if
end repeat
set currentMonth to theRequestNumber
set currentDay to (text -2 thru -1 of ("0" & currentDay))
set theShortDate to (currentMonth & "/" & currentDay & "/" & currentYear) as string

-Previous code sets up the default text (current date in the form 'MM/DD/YYYY' - something like '02/03/2009') for dialog below :

set theDefaultDate to text returned of (display dialog "Enter a date in the form MM/DD/YYYY:" default answer theShortDate buttons {"Calc Date"} default button {"Calc Date"} giving up after 20)

-This line converts the text supplied by the dialog to class 'date' (the long form of the date, including the time):
set calcLongDate to date theDefaultDate

-This line extracts the date portion and leaves the time portion behind:
set calcLongDateTrunc to (date string of calcLongDate)

-This converts calcLongDateTrunc back into the form 'text' so that it can be displayed in a dialog:
set calcLongDateTrunc to calcLongDateTrunc as string
display dialog calcLongDateTrunc buttons {"Done"} default button {"Done"} giving up after 15

-Yields - 'Tuesday, February 3, 2009'

Delicious
Bookmark this on Delicious



In my next post, I will shift gears and present an AppleScript which I have derived from one of my Filemaker programs, which serves as a convenient file backup program.

In conclusion, please note that in the future I will be featuring (here and there) little snippets of HyperTalk code (and others as they occur to me)


If you have questions or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Dialogs for Lists 

Making a Choice from a List of Options.

In this post, we will deal with situations when you want to choose from multiple options within a list. You can have lists that are preset, such as choosing from a list of months of the year, for instance, or perhaps a list such as that which might be generated from a database program when certain criteria are specified (ie names beginning with the surname Bill).

Take a look at this example:


set theName to (choose from list {"John", "Joe", "Bill"})
if theName is false then
display dialog "You clicked cancel to exit." with icon stop buttons {"Exit"} default button {"Exit"}
else
set theName to (item 1 of theName)
display dialog theName with icon note buttons {"Info"} default button {"Info"}
end if

-First note in the first line that 'choose from list' prompts you to choose from the three names given {"john", "joe", "bill"}. the name chosen is assigned to the variable 'thename'.

-if the user clicks cancel from a 'choose from list' dialog such as this, then the variable 'thename' takes on the value false indicating that the user decided not to make a choice of the items listed in the dialog.

-if the user makes a choice, say for instance
"bill", then 'thename' takes on that value and can be used for further script execution.

Adapting the previous dialog, assuming you had a list of items (whatever criteria relevant to what you want) compiled from a database of your own design, in this case we will call the list
'recentOrders', a list of customer names who have ordered products or services from you in recent months. Another version of the list dialog that could be used based on these premises:

set recentOrders to recentOrdersArray as list
try
set recentCustomer to (choose from list recentOrders)
if recentCustomer <> false then
set recentCustomer to (item 1 of recentCustomer)
set scriptAction to button returned of (display dialog "Get information for last order from '" & recentCustomer & "' ?" with icon note buttons {"Cancel","Info"} default button {"Info"})
display dialog "Info for last order from: " & recentCustomer
-here you would return to the user the info from your database on 'recentCustomer'
end if
on error
end try

-Here, we choose a particular item (customer) from 'recentorders'. next, if we do not cancel execution, the variable 'recentcustomer' is assigned. if we do not cancel the next request dialog, the data on the requested customer can be displayed (based upon info stored in whatever the referenced database).

As list type dialogs deviate from the standard dialogs dealt with up until now, it is important to note that, although computers are supposed to follow some sort of logic, you sometimes have to 'go with the flow' on things that don't seem to follow that logic.

I have tried to emphasize from the beginning, the whole process of learning how to applescript builds upon itself. In my coming posts, I will strive to make things easier to grasp by continuing with in a step-by-step manner, as I have found it is the most effective way of learning something new.


I hope all of you have found this post useful in furthering your knowledge of scripting with AppleScript. As always, if you have any questions or comments or would like to suggest a post on another AppleScript issue, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

Using AppleScript Dialogs to Invoke Actions 

Attaching an action to user interaction dialog.

Apple iMac Rebirth PosterIf you remember from my last post, we ended up with this dialog which had to be encompassed by a 'TRY CLAUSE' to prevent an error message from being generated by activating the 'Cancel' button. In this post, I will begin by modifying the script below to show you how you can use data returned from a dialog to invoke an action from AppleScript.

try
display dialog "Your text here" with icon caution buttons {"OK","Cancel"} default button {"Cancel"} giving up after 30
on error
end try

Taking our original script I will make a few additions:

try
set theAction to button returned of ( display dialog "Quit application AppleWorks 6" with icon caution buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30 )
if theAction = "OK" then tell application "AppleWorks 6" to quit
on error
end try

You can see by the text in bold, that I have set the variable 'theAction' to take on the value of the name of the button chosen (note parentheses). As before, if the user clicks on the 'Cancel' button the script halts without any action being taken. If, however the 'OK' button is chosen, then AppleScript sends the quit message to AppleWorks 6.

Now suppose we wanted a dialog that quits an application, but we want to be able to enter in the name of a specific application ahead of time.

try
set dialogResult to ( display dialog "Enter name of application to quit:" default answer "" with icon caution buttons {"OK", "Cancel"} default button {"Cancel"} giving up after 30)
set appToQuit to (text returned of dialogResult)
if (button returned of dialogResult) = "OK" then tell application appToQuit to quit

on error
end try

As before, I have highlighted the changes to be noted, and there are a few, but it's not as complicated as it may seem.

First, I have enclosed the dialog part of the script in parentheses and before that I have inserted 'set dialogResult to'. This tells AppleScript to give the variable dialogResult the values that will be derived from executing the dialog part of the script.

The text
'default answer ""' inserted into the dialog section tells AppleScript to give us a blank text field where the name of the app to quit will be entered. The variable dialogResult will contain both the text entered and the name of the button clicked.

Next, the variable
appToQuit extracts the text part of dialogResult (the application name)

The next line determines if the 'OK' button was activated and, if so, quits the application supplied by the variable appToQuit, otherwise the script ends with no further action.

I hope by now you're having a little bit of fun and seeing just how powerful the AppleScript language can be. If you have any questions or comments, contact me at: hyperscripter@gmail.com or scroll up to my AppleScript Guestbook and leave a comment.

AppleScript and Technology 

capturaVisorFlickr1 by trebol-a

capturaVisorFlickr1

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Html5Dojo by mor10am

Html5Dojo

Dmitry talks prototypes by Lachlan Hardy

Dmitry talks prototy...

345/365 I'm a Mac by Mykl Roventine

345/365 I'm a Mac

Hatena Bookmark Related Tree by hail2u

Hatena Bookmark Rela...

automatically generated by Flickr

Getting Started with AppleScript Dialogs 

A basic notification dialog.

Apple Mac OS 9 SoftwareThis is a very simple dialog script to notify the user of the result of some action:

display dialog "Your text here" with icon stop buttons {"OK"} default button {"OK"}

-Note in the above script that you could substitute 'note' or 'caution' for 'stop' to indicate varying degrees of importance or urgence.

-Taking the above script a step further, you could include 'giving up after 5 (or 15, 20, 60 etc) so that a dialog will automatically close itself after the indicated interval of time:


display dialog "Your text here" with icon stop buttons {"OK"} default button {"OK"} giving up after 5

-You can also have multiple button choices (up to 3). take special note of the formatting required for multiple buttons:

display dialog "Your text here" with icon note buttons {"OK","Cancel"} default button {"Cancel"} giving up after 30

-note in the above example, if you click on 'cancel' or strike the enter or return keys, it will generate an error message. to avoid this and to get your dialog to close 'silently', the above must be enclosed within a 'try clause' such as:

try
display dialog "Your text here" with icon caution buttons {"OK","Cancel"} default button {"Cancel"} giving up after 30
on error
end try


I hope that those of you who are new to appleScripting will find these sample dialog scripts useful as you begin to explore the magic of AppleScript. If you still don't understand how these scripts work, I strongly urge you to cut and paste them into your Script Editor and run them - this should clear up any questions you may still have.

If you have questions, please scroll up to my AppleScript Guestbook or if you like this site, please 'star rate' me at the top of the page. For RSS feed, click the RSS icon at the top or bottom of the page.

If you want a more detailed script on dialogs like this with an action attached to it, see: Using AppleScript Dialogs to Invoke Actions above. Please subscriibe to my RSS feed at the top or bottom of the page (look for the icon)

Amazon Voting 

Rate a Digital Camera or Webcam

Logitech Z-2300 THX-Certified 200-Watt 2.1 Speaker System (Silver)

Logitech Z-2300 THX-Certified 200-Watt 2.1 Speaker System (Silver)

If you love music, youll love the Logitech Z-2300, more...0 points

Sony Cyber-shot DSC-W290 12.1 MP Digital Camera with 5x Optical Zoom and Super Steady Shot Image Stabilization (Black)

Sony Cyber-shot DSC-W290 12.1 MP Digital Camera with 5x Optical Zoom and Super Steady Shot Image Stabilization (Black)

The Sony Cyber-shot DSC-W290 camera combines style more...0 points

Olympus Stylus Tough-8000 12 MP Digital Camera with 3.6x Wide Angle Optical Dual Image Stabilized Zoom and 2.7-Inch LCD (Black)

Olympus Stylus Tough-8000 12 MP Digital Camera with 3.6x Wide Angle Optical Dual Image Stabilized Zoom and 2.7-Inch LCD (Black)

The STYLUS TOUGH-8000 is virtually indestructible. more...0 points

Olympus Stylus Tough-6000 10 MP Waterproof Digital Camera with 3.6x Wide Angle Optical Dual Image Stabilized Zoom and 2.7-Inch LCD (Blue)

Olympus Stylus Tough-6000 10 MP Waterproof Digital Camera with 3.6x Wide Angle Optical Dual Image Stabilized Zoom and 2.7-Inch LCD (Blue)

For the first time, Dual Image Stabilization will more...0 points

 

This Webpage Designed on Apple Macintosh

Boing Boing Feed 

Interesting Headlines from Everywhere

"rRan" by Pronto. Video by Michael Lascarides.
Video by generative video artist Michael Lascarides for "rRan" by Pronto, from their digitally-relea...
Steampunk Music: Guest art-dispatch from Kristen Philipkoski
A guest dispatch on cool things spotted at Art | Basel in Miami, from Kristen Philipkoski: People of...
Kids book about parasites: WHAT'S EATING YOU?
The publishers of What's Eating You?: Parasites -- The Inside Story were kind enough to send me a co...

by Hyperscripter

A 1988 graduate of The Ohio State University, I had very limited experience in programming (I had some experience using MacPascal, TurboPascal (simila... (more)

Explore related pages

Create a Lens!