Archive for the AppleScript category

April 1st, 2007

Put XHTML template on Clipboard AppleScript

Posted in AppleScript, Coding / Development, Mac OS X by Diggory

Here’s another AppleScript: This one puts an xHTML template on the clipboard: Again, remove the Growl parts if you don’t use Growl.

set XHTMLTemplate to "< !DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">



"

set the clipboard to the XHTMLTemplate

tell application "GrowlHelperApp"
-- notify title "AppleScript Notification" description (noteText as string) icon of application "Script Editor.app"

set myAllNotesList to {"XHTMLTemplateToClipboard"}
register as application "XHTML Template to Clipboard" all notifications myAllNotesList default notifications {"XHTMLTemplateToClipboard"} icon of application "Finder.app"

notify with name "XHTMLTemplateToClipboard" title "XHTML Template 2 Clipboard" description "The XHTML Template has been put on the clipboard" application name "XHTML Template to Clipboard"
end tell"


Click this link to make a new Script in ScriptEditor containing the above script

April 1st, 2007

Put current IP address on Clipboard AppleScript

I never remember to post these scripts which I write and often use onto the web, so that Google can index them.

So in an attempt to solve that, here we go: Here’s an AppleScript that I use often via QuickSilver. It calls Growl so – if you don’t have Growl, remove the growl parts otherwise AppleScript will ask you where GrowlHelperApp is.


set theIP to do shell script "ifconfig | grep 'broadcast' | awk '{print $2}'"

set the clipboard to theIP

tell application "GrowlHelperApp"
set defaultNotification to "Put IP address on Clipboard"
set myAllNotesList to {defaultNotification}
register as application defaultNotification all notifications myAllNotesList default notifications {defaultNotification} icon of application "Finder.app"
notify with name defaultNotification title defaultNotification description "Your IP Address (" & theIP & ") has been put on the clipboard" application name defaultNotification
end tell

Click this link to make a new Script in ScriptEditor containing the above script

January 31st, 2005

Mental Note to Self – AppleScript MultiLine Comments

Posted in AppleScript by Diggory

(* Use block comments for comments that
occupy more than one line *)

I wish applescript used c-style comments.
I can never remember the format for multi-line comments , and frequently put // instead of — which, of course, causes an error.

March 31st, 2004

Voice Chapterisation

Posted in AppleScript by Diggory

I was reading about Speakable Items and QuickTime and made this script

It will allow you to chapterise (add chapters to) the front Movie in QuickTime Player – by voice. Simply move the play head to the appropriate points and say “Chapter” – then when the last chapter has been added say “Finish”.

Requires Panther and QuickTime Pro.

you can get the script into Script Editor by clicking Here

global blurb, targetBlurb, sourceMovie, sourceMovieDuration, sourceMovieName, sourceMovieWidth, sourceMovieHeight, chapterTrackText, sourceMovieWidth, sourceMovieHeight, numChaps, lastChapTime



on run

my chapterise()

end run



to chapterise()

set lastChapTime to 0

– Quit if QT Pro is not installed

if not my checkForQTPro() then

return

end if



– pre-check for a front movie

my movieIsForemostPreCheck()


tell application “QuickTime Player”

– Show Info Dialog — explains what the script does.

set the blurb to “This script will add chapters to a QuickTime Movie. Make sure that the movie you want is foremost in QuickTime Player.



” & targetBlurb

display dialog blurb buttons {“OK”} default button 1 giving up after 5

– Now we’re off and ready to go…

– Get the info for the movie we want to chapterise

if not my getFrontMovieInfo() then

activate

display dialog “There is no front movie to chapterise.” buttons {“Whoops!”} default button 1 giving up after 5

return

end if

display dialog “Initial Chapter Title:” default answer (“Start”) buttons {“OK”, “cancel”} default button 1

copy the result as list to {text_returned, button_pressed}

if button_pressed is “OK” then

set initalChapterName to text_returned

else

return

end if



set chapterTrackText to “{QTtext}{font:Geneva}{plain}{size:12}{textColor: 65535, 65535, 65535}{backColor: 0, 0, 0}{justify:center}{timeScale:30}{width:” & sourceMovieWidth & “}{height:” & sourceMovieHeight & “}{timeStamps:absolute}{language:0}{textEncoding:0}
[00:00:00.00]
{textBox: 0, 0, 50, 160}” & initalChapterName & “




– Get the chapters

set numChaps to 0

set another to true

repeat while another is true

set commandSpoken to my listenForChapterCommand()

if commandSpoken is “chapter” then

my addMarker()

else if commandSpoken is “finish” then

my finishChapterise()

set another to false

else if commandSpoken is “debug” then

log (“debug command used”)

else

set another to false

end if

log commandSpoken

end repeat

end tell

end chapterise


– Script subRoutines

to checkForQTPro()

tell application “QuickTime Player”

if QuickTime Pro installed is false then

display dialog “QT Pro is required for this script” buttons {“OK”} default button 1

return false

end if

end tell

return true

end checkForQTPro


to finishChapterise()

set chapterTrackText to chapterTrackText & “[" & my explodeTime(sourceMovieDuration) & "]“

set chapterFile to my writeOut(chapterTrackText)

tell application “QuickTime Player”

activate

tell sourceMovie to rewind

make new track at sourceMovie with data alias chapterFile

end tell

tell application “Finder” to move file chapterFile to trash

my attachChapterTrackToVideo()

end finishChapterise



to attachChapterTrackToVideo()

tell application “QuickTime Player”

tell sourceMovie

set textTracks to every track whose name is “Text Track”

set chapTrack to first item of textTracks



set videoTracks to every track whose name is “video Track”

set videoTrack to first item of videoTracks

tell videoTrack

set chapterlist to chapTrack

end tell

tell chapTrack

set enabled to false

end tell

end tell

end tell

end attachChapterTrackToVideo


to writeOut(someData)

activate

set chapFile to ((path to home folder as string) & “tempChapterMovie.txt”)

– set chapFile to choose file name with prompt “where should I save the chapter file?” default name (sourceMovieName & “_chapters.txt”)

set chapFileRef to open for access chapFile with write permission

write someData to chapFileRef

close access chapFileRef

return chapFile

end writeOut


to listenForChapterCommand()

tell application “SpeechRecognitionServer”

set chapteriserLanguageModel to {“chapter”, “marker”, “mark”, “now”}

set finishLanguageModel to {“end”, “finish”, “stop”}

set cancelLanguageModel to {“quit”, “cancel”}

set debugLanguageModel to {“time”}

set thePrompt to “listening…”

try

set theResultstring to listen for chapteriserLanguageModel & finishLanguageModel & cancelLanguageModel & debugLanguageModel with prompt thePrompt

if theResultstring is in finishLanguageModel then

say “finishing up”

return “finish”

else if theResultstring is in cancelLanguageModel then

say “cancelling”

return “cancel”

else if theResultstring is in chapteriserLanguageModel then

say “adding chapter marker”

return “chapter”

else if theResultstring is in debugLanguageModel then

say “debug”

return “debug”

end if

end try

end tell

return “error”

end listenForChapterCommand


to addMarker()

tell application “QuickTime Player”

tell front movie to set currentTime to the current time of sourceMovie

if currentTime is less than lastChapTime then

display dialog “Sorry, you must add chapters in Chronological order.” buttons {“OK”} default button 1

return

else

set lastChapTime to currentTime

end if



set chapTime to my explodeTime(currentTime)



display dialog “Chapter Title:” default answer (“Chapter ” & numChaps + 1) buttons {“OK”, “cancel”} default button 1

copy the result as list to {text_returned, button_pressed}

if button_pressed is “OK” then

–[00:00:19.00]

–{textBox: 0, 0, 50, 160}Chapter Two

set markerText to “[" & chapTime & "]
{textBox: 0, 0, 50, 160}” & text_returned & “



set chapterTrackText to chapterTrackText & markerText

set numChaps to numChaps + 1

– log markerText

end if

end tell

end addMarker



to movieIsForemostPreCheck()

tell application “QuickTime Player”

try

set sourceMovie to front movie

tell sourceMovie

set frontMovieName to name

end tell

set targetBlurb to “Current targetted movie: ‘” & frontMovieName & “‘.”

on error theError

set targetBlurb to “There is currently NO movie targetted. Make sure a movie is open before pressing OK in this dialog.”

end try

end tell

end movieIsForemostPreCheck


to getFrontMovieInfo()

tell application “QuickTime Player”

activate

try

set sourceMovie to front movie

tell sourceMovie

rewind

set sourceMovieDuration to duration

set sourceMovieName to name

set dims to (dimensions)

set sourceMovieWidth to first item of dims

set sourceMovieHeight to last item of dims

return true

end tell

on error

return false

end try

end tell

end getFrontMovieInfo



to explodeTime(durationInSeconds)

set secondsLeft to durationInSeconds div 600

set secPerMin to 60

set secPerHour to secPerMin * 60



set numHours to “00″

set numMins to “00″

set numSecs to “00″



if secondsLeft is greater than or equal to secPerHour then

set numHours to secondsLeft div secPerHour

log (“number of hours: ” & numHours)

set excessSeconds to numHours * secPerHour

set secondsLeft to secondsLeft – excessSeconds

if numHours < 10 then

log (“padding hour int”)

set numHours to (“0″ & numHours) as string

end if

end if



if secondsLeft is greater than or equal to secPerMin then

set numMins to secondsLeft div secPerMin

set excessSeconds to numMins * secPerMin

set secondsLeft to secondsLeft – excessSeconds

if numMins < 10 then

set numMins to (“0″ & numMins) as string

end if

end if


set numSecs to secondsLeft

if numSecs < 10 then

set numSecs to (“0″ & numSecs) as string

end if



set output to (numHours & “:” & numMins & “:” & numSecs) as string

return output

end explodeTime

February 23rd, 2004

Your Network is now available

Posted in AppleScript by Diggory

I had another DSL outage this afternoon – the Bayswater exchange seems a little temperamental.

Being a total geek I whipped-up this applescript to alert me when the Network was up again. Simple, but effective…

Of course if your net connection goes down and you want to use it you won’t be able to copy and paste from here – so you’d better copy it now :)

The script needs to be saved as an “application” and it should “stay open”. (there are options for both of those in Script Editor’s “Save As…” menu item.)

[edit] – I posted the script on MacOSXHints and after a few comments have tweaked the code to be more friendly to users with Proxies and people who listen to iTunes:

on idle
set secondsToWaitBetweenChecks to 120 — 2 Minutes between checks

set availText to “Your Network Connection is now available.”
set unavailText to “The network is still down.”

set hostToCheck to “www.apple.com”
set checkNetScript to “scutil -r ” & hostToCheck

try
set netStatus to do shell script checkNetScript
if netStatus is “Reachable” then
my announceText(availText)
activate
quit
else
– my announceText(unavailText)
end if
on error
display dialog “Could not check the net status this time.” buttons {“OK”} default button 1 giving up after 5 — seconds
end try
return secondsToWaitBetweenChecks
end idle

to announceText(textToSpeak)
tell application “System Events”

– If iTunes is running dip the Audio.
if (exists process “iTunes”) then
tell application “iTunes”
set oldVolume to sound volume
set sound volume to (sound volume * 0.25)
delay 1
say textToSpeak
delay 1
set sound volume to oldVolume
end tell
else
say textToSpeak
end if

– If the User has Salling Clicker show a funky alert.
if (exists process “SEC Helper”) then
tell application “SEC Helper”
show screen message textToSpeak
end tell
else
display dialog textToSpeak
end if
end tell
end announceText

Announce Network availability source as Applescript Link (requires MacOS X Panther or Script Editor 2)

October 30th, 2003

Speak Unread Mail Summary

Posted in AppleScript by Diggory

This script will speak a summary of your unread mail in Mac OS X’s Mail application. In Panther’s Mail.app you can have an AppleScript run as part of a rule – so you can effectively have your computer announce who your mail is from and what the subjects are as it arrives – without having to even switch to the Mail app. You can also refine your rule so that the script is only executed for certain Mail Accounts, or whatever criteria you please.

tell application “Mail”
repeat with thisAccount in every account
set thisInBox to mailbox named “INBOX” of thisAccount
set thisUnreadCount to unread count of thisInBox

if thisUnreadCount is not 0 then
set unreadMessages to (messages of thisInBox whose read status is false)

if thisUnreadCount > 1 then
set pluralText to “s”
set verbText to “are”
else
set pluralText to “”
set verbText to “is”
end if
set speechCountText to “There ” & verbText & ” ” & thisUnreadCount & ” message” & pluralText & ” in ” & (name of thisAccount) & “.”
say speechCountText

repeat with i from 1 to number of items in unreadMessages
set thisMessage to item i of unreadMessages
set theSender to sender of thisMessage

set savedTextItemDelimiters to AppleScript’s text item delimiters
try
set AppleScript’s text item delimiters to {“<"}
set realName to (first text item of (theSender as string))
--finally, reset the text item delimiters:
set AppleScript's text item delimiters to savedTextItemDelimiters
on error m number n from f to t partial result p
log ("Error: " & m & number)
--also reset text item delimiters in case of an error:
set AppleScript's text item delimiters to savedTextItemDelimiters
--and resignal the error: error m number n from f to t partial result p
end try

set messageSpeechText to "From: " & realName & ". Title: " & subject of thisMessage
say messageSpeechText
end repeat
end if
end repeat

end tell

October 13th, 2003

HTML Validation AppleScript

Posted in AppleScript by Diggory
SafariScriptMenu.jpg Paste this into Script Editor:

tell application “Safari”
set frontURL to the URL of the front document
end tell

set newURL to “http://validator.w3.org/check?uri=” & frontURL

tell application “Safari”
set the URL of the front document to newURL
end tell

and then save it as a compiled script, drop it into ~/Library/Scripts/Applications/Safari/

If you have the Script Menu installed [/Applications/AppleScript/Script Menu.menu] then, whenever Safari is the front application, the script menu contains an option to validate the HTML of the front web page.
n.b. this will only work for pages that are on a public web-server – it can’t validate local HTML that is not published.