[Automator & AppleScript] Automator: アクション・変数を AppleScript で表現する

さわっている内に、AppleScript でスッキリ書きたくなってきたので、いろいろ調べてみました。

[markdown]
こちらが大変参考になりました。

> * [MacOSX – Bash でやってることを AppleScript でやろうとするとこうなる – Qiita](http://qiita.com/mattintosh4/items/353c57ba75eda20af3c4)
> * [life log: AppleScript 最速基本文法マスター](http://mc909j.blogspot.jp/2013/03/applescript.html)
> * [AppleScriptを使ってみるよ!(言語編1/2) – seraphyの日記](http://d.hatena.ne.jp/seraphy/20100408)
> * [AppleScriptを使ってみるよ!(言語編2/2) – seraphyの日記](http://d.hatena.ne.jp/seraphy/20100411)
> * [Applescriptサンプル](http://www.asahi-net.or.jp/~va5n-okmt/factory/applescript/sample_code/)
> * [AS Hole(AppleScriptの穴) By Piyomaru Software » BEGINNERS](http://piyocast.com/as/master/)

## 変数をセットする

`set foo to bar` で代入する。
値は `&` で繋げることができる。

“`prettyprinted
set msg to “ピクセルの最大値を指定して下さい。” & return & return & ¬
“入力した数値(px)になるまで、画像の最も長い辺をアスペクト比を保ったまま縮小します。” & return & ¬
“それ以下は縮小しません。”
“`

なにげに以下の細かいところが分からなかった。

### スクリプト内で改行する

読みやすくしたいが、改行で意味が変わってしまう。
`option + return` でスクリプト内での改行ができる。

### 表示テキスト内で改行させる

`\n` は展開されてしまい、動くけれどもスクリプトが汚いことに。
`return` とすればよい。

## ダイアログを表示する

> * [AutomatorでシェルスクリプトをGUI化 « TORQUES LABS](http://labs.torques.jp/2010/10/19/1431/)

`returned of` で入力値を受け取れるよう。

“`prettyprinted
tell application “System Events”
display dialog msg as text default answer “400” buttons {“OK”, “Cancel”}
set maxpxl to text returned of result
end tell
“`

`result` で全てを受けることができる。

## エラー処理

> * [try catch – AppleScript: on error (try) line number – Stack Overflow](http://stackoverflow.com/questions/5978199/applescript-on-error-try-line-number)

`try` でひろう。

“`prettyprinted
try
tell application “System Events”
display dialog msg as text default answer “400” buttons {“Cancel”, “OK”}
end tell
set maxpxl to text returned of result
on error errMsg number errNo
tell application “System Events”
display alert errMsg & return & “ERROR: ” & errNo as warning
end tell
return
end try
“`

### キャンセルした場合は、アプリを終了する

cancel もエラー扱い。メッセージとエラー番号がとれる。
`return` で、処理が終了できる。以降のスクリプトは実行されない。

> * [osx – Check if variable is number: Applescript – Stack Overflow](http://stackoverflow.com/questions/20313799/check-if-variable-is-number-applescript)

が、Automator の処理は止まらないので、エラーナンバーなどを利用してアプリを止める必要がある。
`tell me to quit`

> * [automator applescript restart workflow – Stack Overflow](http://stackoverflow.com/questions/8106568/automator-applescript-restart-workflow)

“`prettyprinted
try
display dialog dialogMsg as text default answer defaultMaxpxl buttons {“Cancel”, “OK”}
set maxpxl to text returned of result
on error errMsg number errno
if errno is (-128) then
tell me to quit
else
tell application “System Events”
display alert errMsg & return & “ERROR: ” & errno as warning
end tell
end if
return
end try
“`

> * [Error number -128 Applescript – Stack Overflow](http://stackoverflow.com/questions/18189807/error-number-128-applescript)

## アプリの起動と終了

“`prettyprinted
tell application “ImageOptim” to activate
delay 5
tell application “ImageOptim”
quit
end tell
“`

起動した後の動かし方がまだ分からない。

## 新規フォルダを作成する

> * [osx – Applescript to make new folder – Stack Overflow](http://stackoverflow.com/questions/4493335/applescript-to-make-new-folder)

“`prettyprinted
tell application “Finder”
set p to path to desktop
make new folder at p with properties {name:”ConvertImages”}
end tell
“`

`path to desktop` でデスクトップのパスを取得。

## フォルダの複製

> * [MacScripter / Duplicate folder + change folder name…](http://macscripter.net/viewtopic.php?id=29700)

“`prettyprinted
set srcFolder to alias ((path to desktop folder as text) & “TestFolder”)
set destFolder to alias ((path to documents folder as text))
tell application “Finder”
duplicate srcFolder to destFolder
end tell
“`

`items of folder (srcFolder)` とすると、フォルダ内のアイテムを複製してくれる。

## ファイルを削除する

> * [Friday Favorite: Use AppleScript to delete files from a folder | TUAW – The Unofficial Apple Weblog](http://www.tuaw.com/2014/01/03/friday-favorite-use-applescript-to-delete-files-from-a-folder/)

フォルダ内のアイテムを削除する。

“`prettyprinted
delete (every item of folder destFolder)
“`

> * [Applescript:Check folder exists: Apple Support Communities](https://discussions.apple.com/thread/3126610?tstart=0)

フォルダの存在確認はこんな形。

“`prettyprinted
if exists destFolder then
“`

## アイテム名を取得する

フォルダ内のアイテム名は、このような形で配列(list)に収めてくれる。

“`prettyprinted
set fileNamelist to list folder destFolder without invisibles
“`

`without invisibles` は、`.`で始まるファイルを除外してくれる。

## アイテムを取得する

名前ではなく、アイテムを扱うために。

> * [MacOSX – Automator の「選択された Finder 項目を取得」を高速化 – Qiita](http://qiita.com/mattintosh4/items/e9d10d2f48ec51e0e2ff)

`as alias list` がポイントみたい。

“`prettyprinted
tell application “Finder” to set elements to input as alias list
return elements
“`

> * [list – Get full directory contents with AppleScript – Stack Overflow](http://stackoverflow.com/questions/2097263/get-full-directory-contents-with-applescript)

## 配列から取り出して処理する

> * [鳶嶋工房 / AppleScript / Introduction / 繰り返しで処理しよう](http://tonbi.jp/AppleScript/Introduction/08/)

配列(list) からひとつずつ取り出して処理する。

“`prettyprinted
repeat with this_file in targetItems
display alert this_file
end repeat
“`

## コマンドを実行する

`do shell script` で、コマンドラインのコマンドを実行できる。

“`prettyprinted
try
tell application “Finder”
set targetItems to items of folder (destFolder) as alias list
set targetItems to get POSIX path of (targetItems)
set myScript to “open ”
end tell
tell application “Terminal”
do shell script myScript & quoted form of targetItems
end tell
on error errMsg number errno
tell application “System Events”
display alert errMsg & return & “ERROR: ” & errno as warning
end tell
return
end try
“`

`do script` と違い、アクティブにならずにこっそり動いてくれるよう。

> * [Automator: OpenInTerminal を修正 | deadwood](https://www.d-wood.com/blog/2014/02/09_5494.html)

シェルを指定して do shell script する。

> * [MacOSX – AppleScript の do shell script をバックグランドで実行する – Qiita](http://qiita.com/mattintosh4/items/3220a75ae6229553b87b)

## 補遺

> * [AppleScriptのファイル参照にまつわるメモ – ザリガニが見ていた…。](http://d.hatena.ne.jp/zariganitosh/20100924/apple_script_alias_posix_file)
[/markdown]