AppleScriptことはじめ

オンラインで映画を見るYahooのオンラインシアターというサービスを利用しているのだけど、例によってIE専用ということで、Parallels Desktop経由で見ている。

Parallels経由でもパフォーマンスは足りているようで、描画が追いつかない事態はほとんど発生しない。ただ問題は、視聴中にOS Xのスクリーンセーバが動き出すことだ。

丁度以前からAppleScriptを勉強してみたかったので、スクリーンセーバとスリープを有効/無効に設定するスクリプトを作ってみることにした。

ちなみにAppleScriptとは:
 ・Mac OS標準バンドルのスクリプト実行環境
 ・アプリケーションの操作もできるので、位置づけはWindows Script Hostに近い
 ・文法はCやらBASICとは全然違う。オブジェクト指向。

TheaterMode.scpt

set theaterMode to false

tell application "System Preferences"
set current pane to pane "com.apple.preference.desktopscreeneffect"
end tell

tell application "System Events"
tell process "System Preferences"
click radio button "スクリーンセーバ" of tab group 1 of window "デスクトップとスクリーンセーバ"
tell slider 1 of group 1 of tab group 1 of window "デスクトップとスクリーンセーバ"
if value < 360 then set theaterMode to true
if theaterMode then
set value to 360
else
set value to 180
end if
end tell
end tell
end tell

tell application "System Preferences"
set current pane to pane "com.apple.preference.energysaver"
end tell

tell application "System Events"
tell process "System Preferences"
click radio button "電源アダプタ" of tab group 1 of window "省エネルギー"
repeat with n from 1 to 2
tell slider n of tab group 1 of window "省エネルギー"
if theaterMode then
set value to 901
else
set value to 421
end if
end tell
end repeat
end tell
end tell

if theaterMode then
set msg to "スクリーンセーバとスリープを無効にしました"
else
set msg to "スクリーンセーバとスリープを有効にしました"
end if

display dialog msg buttons {"OK"} with title "シアターモード"

半日、あれやこれやしてみて、何となくできた。
3つの異なる場所にあるスライダーの値を変えるので、スライダーを配列に入れてやろうと思ったけど、うまくできなかった。
公式のリファレンスが英語版しかないみたいで、今ひとつつかみきれない。

オブジェクトの属性には attr of object というようにofでアクセスする。
tell ステートメントは、C#やVBにあるwithステートメントと同じかと思うと、そうでもないようだ。

たとえば

tell application "System Events"
tell process "System Preferences"
get it
end tell
end tell

は動くのだけど(「process “System Preferences” of application “System Events”」が表示されて)、

tell process "System Preferences" of application "System Events"
get it
end tell

は、文法エラーになって動かない。

そういうものなのだろうと思うけど、いまいち腑に落ちない。

【参考】
「UIElementInspector」(http://developer.apple.com/samplecode/uielementinspector/index.html
→これでGUIの構造や、変更する属性の名前を調べる

「マイキーボード計画、AppleScriptに挑戦した」(http://www.kototone.jp/com/setkeyboard_applescript.html
→システム環境設定を変更するスクリプトを作られている

「備忘録:メモ:AppleScriptでGUIを操作する」(http://www.measure-zero.jp/blog/2009/feb/19
→上に同じ。初AppleScriptというのが私と同じ

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>