Archive for the 'アプリケーション操作(app control)' Category

05/04 iPhotoで選択中の写真から曜日別の件数を個別にカウント

iPhotoで選択中の写真からファイル作成日付を取得し、それぞれの写真の撮影曜日を取得して日曜日〜土曜日の各曜日の撮影枚数を集計するAppleScriptです。

iPhoto上で写真を(複数、かつ大量に)選択状態にしておき、本AppleScriptを実行すると撮影曜日ごとの枚数を集計します。

やはりというか、当然というべきなのか、土曜日と日曜日の撮影が多いという結果に。

スクリプト名:iPhotoで選択中の写真から曜日別の件数を個別にカウント
script spdUp
  property selList : missing value
  
property dList : {}
end script

–set t1 to current date

–データの初期化
set dList of spdUp to {}
set selList of spdUp to {}

–iPhotoからデータを取得する
tell application "iPhoto"
  set selList of spdUp to selection
  
  
if (selList of spdUp) = {} then
    display dialog "何も選択されていません。" buttons {"OK"} default button 1
    
return
  end if
  
  
repeat with i in (selList of spdUp)
    set the end of (dList of spdUp) to (date of i)
  end repeat
end tell

set {n1, n2, n3, n4, n5, n6, n7} to {0, 0, 0, 0, 0, 0, 0}

repeat with i in (dList of spdUp)
  set j to contents of i
  
set aWDnum to weekday of j as number
  
if aWDnum = 1 then
    set n1 to n1 + 1
  else if aWDnum = 2 then
    set n2 to n2 + 1
  else if aWDnum = 3 then
    set n3 to n3 + 1
  else if aWDnum = 4 then
    set n4 to n4 + 1
  else if aWDnum = 5 then
    set n5 to n5 + 1
  else if aWDnum = 6 then
    set n6 to n6 + 1
  else if aWDnum = 7 then
    set n7 to n7 + 1
  end if
end repeat

return {n1, n2, n3, n4, n5, n6, n7}

–> {309, 10, 9, 10, 17, 51, 375}
–{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

05/03 iPhotoで選択中の写真から各月の件数を個別にカウント

iPhotoで選択中の写真から、1か月単位で撮影枚数を個別にカウントするAppleScriptです。

iPhotoの「人々」を用いて任意の人物の写真をすべて選択しておき、

iphoto2.png

その状態で本AppleScriptを実行すると、各写真の日付情報を取得。日付情報をソートして開始月、終了月の情報を求め、各月にどの程度の写真撮影が行われたかを順次カウントして集計します。

iPhotoにいちいちアクセスするとスピードの低下が心配されるところですが、選択中の写真の日付情報を取得したらあとはiPhotoにアクセスせずに処理を行うため、781枚の写真を選択した状態で、93秒(MacBook Pro 2010 Core i7 2.66GHz、Mac OS X 10.6.8、8GB)で処理を終了しました。処理のほとんどは、iPhotoで選択中の写真の情報を取得する部分で、ソートや集計はほぼ一瞬です。

「○月には遊びに行ってなかったので1枚も撮っていなかったが、さすがに正月は撮影枚数が多いな」

などという、プログラムで分析するまでもない、予想どおりの傾向が分かります。

年ごとの集計、曜日ごとの集計などいろいろ集計のバリエーションを増やしてみると楽しいことでしょう。たぶん、「土日に撮影している枚数が多い」という結果が出るんでしょうけれども。期間で集計するほかに、撮影時の緯度・経度で集計するなど、さまざまな応用が考えられます。

スクリプト名:iPhotoで選択中の写真から各月の件数を個別にカウント
script spdUp
  property selList : missing value
  
property dList : {}
  
property eList : {}
  
property fList : {}
end script

–set t1 to current date

–データの初期化
set dList of spdUp to {}
set eList of spdUp to {}
set selList of spdUp to {}

–iPhotoからデータを取得する
tell application “iPhoto”
  set selList of spdUp to selection
  
  
if (selList of spdUp) = {} then
    display dialog “何も選択されていません。” buttons {“OK”} default button 1
    
return
  end if
  
  
repeat with i in (selList of spdUp)
    set the end of (dList of spdUp) to date of i
  end repeat
end tell

–ソート
set (dList of spdUp) to shellSort5(dList of spdUp) of me

–選択中の写真の最初の日付、最近の日付を求める
set minDate to contents of first item of (dList of spdUp)
set maxDate to contents of last item of (dList of spdUp)

–開始日、終了日の間の{年,月}のリストを取得する
set mmList to retYearMonthWithinPeriod(minDate, maxDate) of me

set aLen to length of (dList of spdUp)
set hitList to {}

set aCount to 0

set aPointer to 1
set hitF to false

repeat with i in mmList
  set {aYear, aMonth} to i
  
set sDate to (aYear as string) & “/” & (aMonth as string) & “/1″
  
set eDate to (aYear as string) & “/” & (aMonth as string) & “/” & getMlen(aYear, aMonth) of me as string
  
set sDateObj to date sDate
  
set eDateObj to date eDate
  
  
  
repeat
    set j to contents of item aPointer of (dList of spdUp)
    
if (sDateObj j) and (j eDateObj) then
      
      
if hitF = false then
        set hitF to true
        
set aCount to 1
        
        
set aPointer to aPointer + 1
        
      else
        set aCount to aCount + 1
        
set aPointer to aPointer + 1
      end if
      
    else
      
      
if hitF = true then
        set the end of hitList to {aYear, aMonth, aCount}
        
set aCount to 0
        
set hitF to false
        
exit repeat
      else
        set the end of hitList to {aYear, aMonth, 0}
        
exit repeat
      end if
      
    end if
    
    
if aPointer > aLen then
      exit repeat
    end if
    
  end repeat
  
  
if aPointer > aLen then
    exit repeat
  end if
  
end repeat

if hitF = true then
  set the end of hitList to {aYear, aMonth, aCount}
end if

–set t2 to current date
–set t3 to t2 -t1
–> 93 sec

hitList
–> {{2009, 4, 2}, {2009, 5, 0}, {2009, 6, 0}, {2009, 7, 25}, {2009, 8, 0}, {2009, 9, 0}, {2009, 10, 1}, {2009, 11, 2}, {2009, 12, 7}, {2010, 1, 38}, {2010, 2, 41}, {2010, 3, 4}, {2010, 4, 36}, {2010, 5, 5}, {2010, 6, 3}, {2010, 7, 36}, {2010, 8, 26}, {2010, 9, 49}, {2010, 10, 8}, {2010, 11, 61}, {2010, 12, 23}, {2011, 1, 32}, {2011, 2, 40}, {2011, 3, 0}, {2011, 4, 26}, {2011, 5, 44}, {2011, 6, 10}, {2011, 7, 32}, {2011, 8, 41}, {2011, 9, 0}, {2011, 10, 0}, {2011, 11, 39}, {2011, 12, 51}, {2012, 1, 25}, {2012, 2, 0}, {2012, 3, 51}, {2012, 4, 23}}

on retYearMonthWithinPeriod(sDate, eDate)
  
  
set sYear to year of sDate
  
set sMonth to month of sDate as number
  
  
set eYear to year of eDate
  
set eMonth to month of eDate as number
  
  
set mList to {}
  
  
if sYear is equal to eYear then
    
    
repeat with i from sMonth to eMonth
      set the end of mList to {sYear, i}
    end repeat
    
  else if sYear + 1 = eYear then
    
    
repeat with i from sMonth to 12
      set the end of mList to {sYear, i}
    end repeat
    
    
repeat with i from 1 to sMonth
      set the end of mList to {eYear, i}
    end repeat
    
  else
    
    
repeat with i from sMonth to 12
      set the end of mList to {sYear, i}
    end repeat
    
    
repeat with i from (sYear + 1) to (eYear - 1)
      repeat with ii from 1 to 12
        set the end of mList to {i, ii}
      end repeat
    end repeat
    
    
repeat with i from 1 to sMonth
      set the end of mList to {eYear, i}
    end repeat
    
  end if
  
  
return mList
end retYearMonthWithinPeriod

–最大値を取得する
on maximumFromList(nList)
  script o
    property nl : nList
  end script
  
  
set max to item 1 of o’s nl
  
repeat with i from 2 to (count nList)
    set n to item i of o’s nl
    
if n > max then set max to n
  end repeat
  
return max
  
end maximumFromList

–最小値を取得する
on minimumFromList(nList)
  script o
    property nl : nList
  end script
  
  
set min to item 1 of o’s nl
  
repeat with i from 2 to (count nList)
    set n to item i of o’s nl
    
if n < min then set min to n
  end repeat
  
return min
  
end minimumFromList

–指定月の長さを得る(日数)
on getMlen(aYear, aMonth)
  
  
set aDat to (aYear as text) & “/” & (aMonth as text) & “/1″
  
if aMonth is not equal to 12 then
    set eDat to ((aYear as text) & “/” & (aMonth + 1) as text) & “/1″
  else
    set eDat to ((aYear + 1) as text) & “/” & (1 as text) & “/1″
  end if
  
  
–set sDat to date aDat
  
set eDat to date eDat
  
set eDat to eDat - 1
  
  
set mLen to day of eDat
  
return mLen
  
end getMlen

–プレーンなAppleScriptベースでは最速ソート
on shellSort5(aSortList) – スクリプトオブジェクトを使用
  script oBj
    property list : aSortList
  end script
  
set len to count oBj’s list’s items
  
set gap to 1
  
repeat while (gap len)
    set gap to ((gap * 3) + 1)
  end repeat
  
repeat while (gap > 0)
    set gap to (gap div 3)
    
if (gap < len) then
      repeat with i from gap to (len - 1)
        set temp to oBj’s list’s item (i + 1)
        
set j to i
        
repeat while ((j gap) and (oBj’s list’s item (j - gap + 1) > temp))
          set oBj’s list’s item (j + 1) to oBj’s list’s item (j - gap + 1)
          
set j to j - gap
        end repeat
        
set oBj’s list’s item (j + 1) to temp
      end repeat
    end if
  end repeat
  
return oBj’s list
end shellSort5

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

04/30 Microsoft Office v2011 14.2.1アップデートで辞書に変更なし

先日公開された「Microsoft Office 2011 14.2.1 更新プログラム」でアップデートされた、Excel、Outlook、PowerPoint、WordのAppleScript用語辞書にとくに変更がないことを確認しました。

04/29 QuickTime Xで録画して任意のファイル名で保存

QuickTime Xで録画して任意のファイル名で保存するAppleScriptです。

QuickTime Player 7+Mac OS X 10.7で動作するScriptを見て海外の友人が「QuickTime Player Xは機能が少ないよな〜」などとぼやいていたので、この程度ならできるだろうと考えてQuickTime Player X用に書き換えてみました。

相変わらず、時間計測にお手軽にdelayコマンドを使っていますが、録画開始時のGUIアニメーションで2秒近くロスがあります。このため、指定録画時間に2秒追加しています。

スクリプト名:QuickTime Xで録画
property recTime : 10 –録画時間(秒で指定する)

set aFilepath to choose file name with prompt "ムービーを保存するファイル名を入力"
set outFilepathPOSIX to POSIX path of aFilepath

tell application id "com.apple.QuickTimePlayerX"
  –確実に処理を行うためにムービーをすべてクローズ
  
close every document without saving
  
  
–録画開始
  
set recMov to (new movie recording)
  
tell recMov to start
end tell

–録画時間経過待ち
delay (recTime + 2) –秒単位でウェイト(UI系の動作により2秒程度ロスが発生するもよう)

tell application id "com.apple.QuickTimePlayerX"
  –録画停止
  
tell recMov to stop –この操作で、QT7の設定に従ってムービーが保存される
  
  
delay 1 –時間待ち
  
  
tell document 1
    –properties
    
set aProp to properties
    
close
  end tell
end tell

set originPath to file of aProp

–QT Player 7が自動保存したファイルを移動&リネーム
–ただし、自動保存したファイルのパスと移動先の衝突判定は省略
set movieOriginalFile to POSIX path of originPath
set sText to "mv " & quoted form of movieOriginalFile & " " & quoted form of outFilepathPOSIX
do shell script sText

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

04/29 Terminalで全Window中の全Tabのうち、指定タイトルのものをクローズする

Terminal.appの全Window内のTabのうち、指定タイトルのものをクローズするAppleScriptです。

Mac OS X 10.7上のTerminalの各ウィンドウには、任意のタイトルを指定できるようになっています。Mac OS X 10.6上では、カスタマイズしたタイトルについてはAppleScriptからは参照するだけでした。

term00.jpg

スクリプト名:teminal.appでtabを操作する
tell application "Terminal"
  tell window 1
    tell tab 1
      set custom title to "ぴよまる"
    end tell
    
    
tell tab 2
      set custom title to "ぴよぴよ"
    end tell
    
  end tell
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

term01.jpg

term3.jpg

Tabのクローズについては、Window内のTabを指定してclose命令を実行してみても、クローズはできない状況です。GUI Scriptingで行うのもアレなので(最前面に持ってこないと実行できないというのは、ちょっとめんどう)、別の方法でクローズを実現することに。

Terminal.appの環境設定で、シェル終了後にWindowをどうするか指定することができます。

term1.jpg

term4.jpg

「ウィンドウを閉じる」「シェルが正常終了した場合には閉じる」「ウィンドウを閉じない」の3つから選択可能。

term2.jpg

これを「ウィンドウを閉じる」に設定しておき、指定Tabに「exit」コマンド(シェルコマンド)を送ることで、指定Tabをクローズできるようになります。

まあそんなわけで、Tabのカスタム名称を文字列で指定して該当するTabをすべてクローズできるようになったわけですが、これがどの程度有用かは…………ちょっと分かりません。

スクリプト名:Terminalで全Window中の全Tabのうち、指定タイトルのものをクローズする
set targTabTitle to “ぴよまる”

tell application “Terminal”
  set tabRef to a reference to (every tab of every window whose custom title is equal to targTabTitle)
  
  
repeat with i in tabRef
    do script “exit” in i
  end repeat
  
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

04/29 QuickTime 7で録画して任意のファイル名で保存

QuickTime Player 7+Mac OS X 10.7で、所定の時間だけムービー録画(おそらく、内蔵のiSight/Face Time Cameraから取り込み)を行い、指定のパスにファイル保存を行うAppleScriptです。

コメント欄の質問から、試しに組んでみましたが……意外と試行錯誤が必要でした。

所定時間だけ録画する、というScriptは簡単です。しかし、録画内容を別のパスに保存するというのがなかなかやっかいです。本来のQuickTime Playerの機能にのっとって処理することを考えるなら、指定の(あらかじめ保存してある)ムービーファイルから保存形式などを読み取って、その内容に基づいてムービーを「export」することになります。

しかし、そこまでまじめに処理をやりだすと相当の長さになってしまうため、サンプルとしてはいささかおおげさです。

そこで、とりあえずQuickTime Playerの設定に基づいて「ムービー 1.mov」などといったファイル名で保存を行わせておき、そのフルパスを取得。ムービーをクローズしたのちに、一時保存したファイルを指定パスに移動させればよいだろう、と考えてこのようなものに。

録画時間の指定にdelay命令を用いていますが、あくまで説明を簡単に行うために用いているものであって、本来はidleハンドラを使ってタイマー割り込みで実装するべきです。

スクリプト名:QuickTime 7で録画
property recTime : 3 –録画時間(秒で指定する)

set aFilepath to choose file name with prompt "ムービーを保存するファイル名を入力"
set outFilepathPOSIX to POSIX path of aFilepath

tell application id "com.apple.quicktimeplayer"
  –確実に処理を行うためにムービーをすべてクローズ
  
close every document without saving
  
  
–録画開始
  
new movie recording
  
start recording 1
end tell

–録画時間経過待ち
delay recTime –秒単位でウェイト(ちょっとバカっぽい処理。本来はタイマー割り込みで時間待ちすべき)

tell application id "com.apple.quicktimeplayer"
  –録画停止
  
stop recording 1 –この操作で、QT7の設定に従ってムービーが保存される
  
  
delay 1 –時間待ち
  
  
tell document 1
    set originPath to original file –保存先のファイルのパスを取得しておく
    
close
  end tell
end tell

–QT Player 7が自動保存したファイルを移動&リネーム
–ただし、自動保存したファイルのパスと移動先の衝突判定は省略
set movieOriginalFile to POSIX path of originPath
set sText to "mv " & quoted form of movieOriginalFile & " " & quoted form of outFilepathPOSIX
do shell script sText

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

04/21 Safariの最前面のWindowの内容を1枚もののPDFにレンダリングしてデスクトップへ

Safariでオープン中の最前面のWindowの内容をデスクトップにPDF出力するAppleScriptです。

Web関係の仕事をすると、地味に必要になってくる「指定ページを1枚ものの画像にまとめた」PDF。Keynoteの書類などに貼り付けてページ遷移の説明を行ったりするのは、よくある話です。

Safariの最前面のWindowでオープン中のURLを取得し、CLI Webレンダラー「Wkpdf」でPDFにレンダリング出力します。

safario.png

その際に、ファイル名は日付をもとに生成。1枚ものの「長いPDF」として出力するためにWkpdfのレンダリングオプションを指定してページネーションを抑止したり、背景画像の表示をイネーブルにしたりと、見所はそのぐらいで、あとはたいしたことのないあっさりとした処理ばかりです。

Script Menuに入れて使うと便利です。ただ、使用頻度は人によって個人差がありそうなので、実用性がきわめて高い便利なScriptの割には忘れ去られそうな可能性も(自分でも、作っていたことを忘れていました)。

Wkpdf自体のインストールについては、Terminalからコマンドを叩いて行っておく必要がありますが、たいして難しくないので大丈夫でしょう。

スクリプト名:最前面のWindowの内容を1枚もののPDFにレンダリングしてデスクトップへ
tell application “Safari”
  set wCount to count every window
  
if wCount < 1 then
    display dialog “Windowが存在しません” buttons {“OK”} default button 1
    
return
  end if
  
  
tell window 1
    set aInfo to properties
  end tell
  
  
set aDoc to document of aInfo
  
  
tell aDoc
    set aURL to URL
  end tell
  
end tell

set aFileName to “webOut” & (do shell script “date +%Y%m%d%H%M%S”)
renderURLtoPDF(aURL, aFileName) of me

on renderURLtoPDF(aURL, aFileName)
  set s1Text to “cd ~/Desktop && “
  
set outPath to POSIX path of (path to desktop) & aFileName & “.pdf”
  
  
set s2Text to “wkpdf –source “ & aURL & ” –paginate false –print-background –output “ & outPath
  
  
set sAll to s1Text & s2Text
  
do shell script sAll
end renderURLtoPDF

(*
–指定URLの内容をレンダリングしてPDFに書き出す
on renderURLtoPDF(aURL, aFileName)
  set dDir to POSIX path of (path to desktop from user domain)
  set outFile to dDir & aFileName & “.pdf”
  try
    do shell script “cd /usr/local/bin && /usr/local/bin/coral -f PDF -o ” & quoted form of outFile & ” ” & aURL & ” &”
  on error
    return false
  end try
  –return outFile
end renderURLtoPDF
*)

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

04/21 iPhoto, iTunes, Safariアップデートについて

iPhoto 9.2.3、iTunes 10.6.1、Safari 5.1.5の各アップデートが提供されていますが、これらのアプリケーションのAppleScript用語辞書に変更はありません。

04/21 Office v.2011 Service Pack 2による変更点

2012/4/13にOffice v.2011 サービスパック2(バージョン14.2.0)がオンライン配布開始となりました。

例によって、アップデート後にAppleScript用語辞書をAS Dictionaryで書き出して,前バージョンの用語辞書の内容と比較を行ってみました。

 Excel 14.1.2→14.2 変更なし
 Outlook 14.1.2→14.2 変更あり(大規模な変更)
 PowerPoint 14.1.4→14.2 変更あり(「player」関連のオブジェクト、命令が追加に)
 Word 14.1.4→14.2 変更なし

……Outlookについては、日常的に使用していないので用語辞書変更の影響度合いはなんとも言えないのですが、SP2で加えるレベルではないほどの追加(あくまで個人的な意見)が行われています。

04/13 AppleScriptObjCアプリをAppleScript対応に(3)

AppleScriptObjCのアプリをスクリプタブルにする話の続きです。

とりあえず、30分もかからずにASOCアプリをスクリプタブルにできました。超簡単です。

そこで、以前から疑問に思っていたことをテストしてみました。

Xcode上では、プロジェクトを構成するさまざまなファイルをローカライズすることが可能です。つまり、各国語環境用に個別にファイルを用意しておいて、対応する言語環境で別々の内容を表示させることができるようになっています。

そこで、sdefファイルをローカライズして、日本語環境下では日本語の解説文が入ったAppleScript用語辞書を表示させられるかを試してみました。

asocs8.png

▲ローカライズされたAppleScript用語辞書。日本のユーザーしか使わないようなツールに英語だけの用語辞書を付けておくことはナンセンス。このようにして分かりやすくできる

結果はばっちり大成功。日本語環境では、日本語で説明の入ったAppleScript用語辞書がオープンされることが確認できました。こうして英語の用語辞書のほかに日本語の用語辞書を用意しておけばよいのではないか? と思われました。

→ プロジェクトのダウンロード(90Kバイト)

※記事掲載当初はアーカイブのダウンロードリンクが切れていました。2012/4/15現在は修正してあります

■総評

正直、AppleScriptで書かれたプログラムをAppleScriptから呼び出すのだから、処理内容自体を呼び出し側に書けばよいようにも思えますし、速度の面でもあまりメリットが感じられません。

リスト要素のソートなど、Cocoaの機能を用いると高速化できるものもありますが、Mac OS X 10.7以降であればAppleScriptエディタ上で直接AppleScriptObjCのプログラムが記述でき、Cocoaの機能も呼び出すことができます。わざわざ、操作が繁雑なXcode上でそれを行うメリットが大きいとも思えません。

AppleScriptでOSAX(のようなもの……つまり、Invisible Processでウィンドウとかメニューなどを持たないアプリ)に近いものが作れるわけで、それについてはなかなか便利でしょう(ライブラリを整備するのと自前OSAX作成とどちらが労力が少なくて済むかは、判断つきかねます)。

ですが……単純にやってみて「おもしろい」と感じられました。もっと高度な命令も実装できることが確認できれば、応用範囲がいろいろと広がるのではないかと思われました。

AppleScript用語辞書の(言語環境に応じた)ローカライズや、一部のAppleのアプリケーションで試行されているサンプルスクリプトの用語辞書への同梱など、「こうできた方が便利では?」というアイデアを試す場として利用できる、とは思っています。

スクリプタブルなアプリケーションを作るのがここまで簡単だとは思わなかったので、そのことが分かったことが最大の成果だと感じました。他人のプログラムを見ながら試して、動くようになるのに30分もかかりませんでした。

04/13 AppleScriptObjCアプリをAppleScript対応に(2)

AppleScriptObjCアプリをスクリプタブルにした話の続きです。

r/oの属性ばかりではなく、書き換えできる属性値を用意し、これをGUIにつないで書き換えが目で見て分かるようにしてみました。

さきほどの用語辞書の属性値「message」はsdefファイルの定義によりAppleScriptObjCプログラム中の「theMessage」プロパティに対応。さらに、Xcode上でtheMessageプロパティをNSTextFieldのvalueにバインドしてみました。

AppleScriptObjCファイル名:asoc1AppDelegate.applescript

– asoc1AppDelegate.applescript
– asoc1

– Created by 長野谷 隆昌 on 12/04/12.
– Copyright 2012 Piyomaru Software. All rights reserved.


– http://macscripter.net/viewtopic.php?id=36000

– MacScripters Meetingの投稿をもとに、いらない部分をそぎ落として分かりやすいように整理したもの
– Original post by akader

script asoc1AppDelegate
  
  
property parent : class “NSObject”
  
  
property tF : missing value –bind to NSTextField
  
  
property theMessage : missing value –bind to tF’s value
  
  
  
  
  
on applicationWillFinishLaunching_(aNotification)
    
– Insert code here to initialize your application before any files are opened
  
end applicationWillFinishLaunching_
  
  
  
on applicationShouldTerminate_(sender)
    
– Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNow
  
end applicationShouldTerminate_
  
  
  
  
on application_delegateHandlesKey_(sender, theKey)
    
    
return theKey is in {“theMessage”}
    
  
end application_delegateHandlesKey_
  
  
end script

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

アプリケーション「asoc1」を実行すると、こんな感じです。

asocs5.png

スクリプト名:asoc1のメッセージを書き換える
tell application “asoc1″
  set message to “ぴよまるソフトウェア”
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

上記のAppleScriptを実行すると、

asocs6.png

のようにテキストフィールドの内容が変化します。逆に、テキストフィールドの内容を「message」属性を介して取得することもできます。

ただし、テキストフィールドに文字入力中の内容を取得しようとした場合、すぐにテキストフィールドの内容に対する変更が値に反映されないなどの現象が見られました。そこで、Xcode上でテキストフィールドのvalueをバインドしているところで、

asocs7.png

「Continuously Updates Value」のチェック項目があるので、チェックを入れると……入力した内容がすぐに属性「message」に反映されるようにはなるのですが、今度はアプリケーションの動作が若干もたつく感じがしました。外すとそのようなことはなくなったので、少しひかえめな連動を行うべきなのかもしれません。

「ひかえめな連動」というのは、GUI上で入力中のフィールド内容を即座に求めるのではなく、内容が確定して環境設定に書き込んだ内容に対してアクセスするような連動、ということです。キーボード入力された内容をすぐ取得するのは避けたほうがよいでしょう。

04/12 AppleScriptObjCアプリをAppleScript対応に(1)

MacScripter.netで探してAppleScriptObjCアプリをAppleScript対応(スクリプタブル)にする方法を確認してみました。貴重な情報を提供してくれている投稿者の方々には深く感謝しています。

実際の投稿記事はこちら。この一連の記事は同投稿を精査して、より単純化して資料を加え解説するものです。

■Info.plistを編集

まずはXcode上でAppleScriptObjCのプロジェクトを1つ作成してみましょう。サンプルでは、「asoc1」という名前のプロジェクトを作成しました。

asocs2.png

最初に、Info.plist(各Xcodeプロジェクト内でのファイル名は異なります。上の画面では「asoc1-info.plist」が該当)を編集し、キーが「Scriptable」値が「Yes」(Boolean)、キーが「Scripting Definition file name」値が「myApp.sdef」のエントリ(合計2つ)を作成します。

asocs1.png

■sdefファイルをプロジェクトに追加する

sdef(Scripting DEFinition)ファイルをプロジェクトに追加します。Xcodeで「New File」を実行し、「empty file」をプロジェクトに追加。追加ファイルのファイル名を「myApp.sdef」とします。

内容はこんな感じ。画像では内容が見えない場合には、あとでアーカイブ中の実物を見てください。

asocs3.png

なお、sdefファイルの記述がもっと簡単にできる、Shadow Labの「Sdef Editor」というフリー・ソフトウェアが存在します。もっと込み入ったAppleScript用語辞書を作成する場合には、同ソフトウェアを併用するとよいでしょう。

asocs9.png
▲Shadow LabのSdef Editor

■AppleScriptObjCプログラム側にハンドラ追加

on application_delegateHandlesKey_(sender, theKey) ハンドラを追加。予約語messageに対応する「theMessage」を受信したときにtrueを返します。ただ、それだけ。

■AppleScriptObjCプログラム側にプロパティ追加

property theMessage : missing value

これだけ追加しておきましょう。

■ためしに、ビルド

これでXcode上でCommand-Rでビルド&実行するだけで、スクリプタブルなアプリケーション(AppleScript用語辞書つき)になります。アプリケーションに対してプロパティを取得すると、これだけでアプリ名やバージョン番号などの最低限の情報を取得できます。

AppleScript用語辞書をAppleScriptエディタでオープンして内容を確認することも可能です。

スクリプト名:asoc1でアプリのプロパティを取得する
tell application “asoc1″
  properties
end tell

–> {message:missing value, frontmost:false, class:application, name:”asoc1″, version:”1.0″}

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

04/03 AppleScriptObjC Explorer2で編集中のScriptをすべて保存してXcodeでビルド実行 v2

AppleScriptObjC Exlorer 2で、編集中のScriptをすべて保存してXcodeの最前面の(アクティブな)プロジェクトをビルドして実行するAppleScriptです。

……なるべく1行で内容が分かるように心がけていますが、さすがになんのことやら分かりにくいので、説明します。

本ScriptはMac OS X 10.6.8+Xcode 4.1+AppleScriptObjC Explorer 2 2.2.1で作成。Mac OS X 10.7上でも動くはずです。

Xcode 4.0以降でAppleScriptObjCのサポートは「悲惨」のひとことに尽きます。インデントは狂うわ、構文確認時の各種ブロックの補完は行われないわ、AppleScript構文色分けがまったくきかないわで、生産性がダダ下り。AppleScript Studioの頃には、Mac OS X 10.5の頃まではなんとか構文色分けは維持されてきたものですが……。

asoc1.png

さすがに、Xcode 4.x内蔵のテキストエディタに愛想が尽きて、AppleScriptObjC専用外部エディタである「AppleScriptObjC Explorer 2」をお買い上げ。Xcode上のファイル一覧でAppleScriptを選択した状態でコンテクストメニューを表示。「Open With External Editor」を実行してAppleScriptObjC Explorer 2でAppleScriptのテキストを編集させるようにしています。

asoc2.png

これで、構文確認時の各種ブロック(ifブロックとかrepeatブロックとかtellブロックとか)の入力補完や、AppleScript構文色分けなどが利用できます。

ただ……Mac OS X 10.6/10.7ともに、Xcodeの外部エディタとして使用した場合に、AppleScriptObjC Explorer 2からはXcodeプロジェクトのビルドやら実行やらはできません(Mac OS X 10.7上でAppleScriptエディタ上と同様にAppleScriptObjCプログラムを単体で作成・実行できます)。

そこで、AppleScriptObjC Explorer 2側からXcodeのプロジェクトをビルド&実行するようにしてみたのが本AppleScriptです。

ただし、Xcode 4.x系のAppleScript対応機能は、いまだ実装の発展途上というか、工事中で機能不全な状態なので……まともにXcodeのオブジェクト階層をたどっていく気になりません。なげやりに、GUI Scripting経由でメニュー項目を呼び出したりしています。また、ビルド&実行対象は最前面のXcodeプロジェクトであって……複数のプロジェクトをXcode上でオープンしている場合に、外部エディタで編集しているScriptの所属するプロジェクトが、Xcode上でかならずしも最前面になっているわけではありませんので……そのへんは割り切って使っています。

Xcode 4でビルドを行わせる前に、AppleScriptObjC Explorer 2側でオープン中のScriptをすべてファイル保存させています。未保存のAppleScriptが存在した場合には保存をスキップします。

AppleScriptObjC Explorer 2用のScript Menuに入れて呼び出して使っています。

スクリプト名:AppleScriptObjC Explorer2で編集中のScriptをすべて保存してXcodeでビルド実行 v2
tell application “AppleScriptObjC Explorer 2″
  set dList to every document
  
  
set sList to {}
  
repeat with i in dList
    –documentのfile属性を取得(未保存だとmissing valueになっている)  
    
set tmpFile to file of i
    
    
if tmpFile is not equal to missing value then
      tell i –保存済みのdocumentのみ保存を実行
        save
        
set the end of sList to tmpFile
      end tell
    end if
  end repeat
end tell

–複数のプロジェクトをオープンしている場合にはアクティブ(最前面)のプロジェクトを対象に
–すごい投げやりな処理……
tell application “Xcode”
  set curPrjDoc to active workspace document
  
  
–最前面のプロジェクトが、必ずしもAppleScriptObjC Explorer 2で編集中のScriptが所属するプロジェクトとは限らない
  
–編集中のScriptのファイルパスから上位フォルダに存在するXcode書類を探索して、プロジェクトを特定してもいいかも
  
–ただ、Xcodeのタコさ加減にめまいがして、真剣にXcodeをAppleScriptからつっつく気になれない……
  
  
tell curPrjDoc
    build –ビルド
  end tell
  
end tell

–GUI Scriptingから実行指定
activate application “Xcode”
tell application “System Events”
  tell process “Xcode”
    click menu item “Run” of menu 1 of menu bar item “Product” of menu bar 1
  end tell
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

03/27 Safari 5.1.5でAppleScript用語辞書に変更なし

本日ソフトウェア・アップデートから配布されたSafari 5.1.5のAppleScript用語辞書を確認したところ、とくに前バージョンとの差異は検出されませんでした。

………………………………Safari 5.1.5で「www.apple.co.jp」を表示させると、ちゃんと「www.apple.com/jp」にリダイレクトされるようですが……目の錯覚でしょうか。それとも、サーバーの転送設定が修正されたのでしょうか。

03/24 インストールされているアプリのAS辞書を書き出すv2

インストールされているアプリのAppleScript用語辞書をHTMLに一括書き出しするAppleScriptです。

実行したMac上にインストールされている/Applicationsフォルダ、ユーティリティーフォルダ、/Library/CoreServicesフォルダ、/Library/ScriptingAdditionsフォルダなどのアプリケーションのうち、Scriptableなもの(通常のAppleScriptからコントロール可能なもの。GUI Scriptingを経由ではなく)をピックアップして、AppleScript用語辞書をHTML書き出し、それを指定フォルダに出力します。

# 最新のXcodeは/Applicationsフォルダに入るので、一部の処理は無駄になっています

本バージョンでは、AppleScript用語辞書のHTML書き出しに伴い、プロセスが起動されてメモリーが圧迫されるのを防ぐために、対象アプリケーションのプロセスが起動したら、つぶさにkillコマンドで強制終了させています。ただし、killするのはvisible process(Dockにアイコンが表示されるプログラム)だけであり、Help Viewerのような「Dockには表示されないが、表示ウィンドウを持つ」ものはkillできていません。

また、実際に使ってみたところ……光学ドライブが内蔵されていないMacBook Air上でDVD PlayerのAppleScript用語辞書をHTML書き出ししようとして、DVDドライブが装備されていない旨エラーのダイアログが表示され……肝心のAppleScript用語辞書は書き出されていませんでした。実行時には外付けのDVDドライブでもつないでおくとよいでしょう。

OSのアップデートや、β版のOSの新版がリリースされたときに、AppleはAppleScript関連の用語辞書の修正などはアナウンスしないため、ユーザー側でマイナーバージョンごとに用語辞書をHTML書き出ししておき、前バージョンとの差分をFileMergeなどのdiffツールで比較。どこに修正が加わったかをチェックする必要があります。

ただし、このようなツールで分るのはAppleが用語辞書に対して加えた修正点だけであり、構文レベルでバグが潜んでいるとか(Mac OS X 10.3のときには「is in」演算子がバグっていて死ぬほどひどい目に遭わされました、、)、アプリケーションやOSそのものにバグがある場合には検出できません。

本気で、Appleが作るバグを検出するために数百とか数千本のAppleScriptを各種言語(英語、仏語、独語、日本語、中国語、韓国語など)環境でチェックを行うシステムを作ることを考えないではないですが、それはApple自身がとっくの昔にやっておくべき話であって、ユーザーがやる種類のものではないような気が…………。

スクリプト名:インストールされているアプリのAS辞書を書き出すv2

set outPath to choose folder with prompt “AS辞書HTML書き出し先フォルダを選択”

tell application “ASDictionary” to launch

set apList to getScriptableAppPathList() of me

set ngList to {} –処理実行時にエラーになったアプリケーション/OSAXのパスが入る

–メインループ
repeat with i in apList
  set j to contents of i
  
if j is not equal to {} or j is not equal to “” then
    
    
–アプリケーションファイルの情報を取得
    
tell application “Finder”
      set aInfo to info for j
      
set sVer to short version of aInfo
      
set sVer2 to prepareShortVersionStringNum(sVer) of me
      
set sVerStr to replaceText(sVer2 as string, “.”, “”) of me
      
set prodName to displayed name of aInfo
    end tell
    
    
set outPathStr to (outPath as string) & prodName & ” “ & sVerStr & “.html”
    
    
    
–HTML書き出し前のプロセス一覧を取得
    
tell application “System Events”
      set beforeList to (unix id of every process whose visible is true)
      
log beforeList
    end tell
    
    
    
–HTML書き出し(実行すると、当該のアプリケーションが起動するケース多し)
    
set htmlRes to false
    
tell application “ASDictionary”
      set exRes to export j to outPath using file formats {single file HTML} using styles {AppleScript} with showing hidden items without compacting classes
      
      
if success of (first item of exRes) = false then
        –Export失敗時
        
set the end of ngList to j
      else
        
        
–Export成功時
        
set htmlRes to true
        
set outFile to destination of (first item of exRes)
      end if
      
    end tell
    
    
    
–HTML書き出し後のプロセス一覧を取得(書き出し時に起動されたアプリケーションが増えている)
    
tell application “System Events”
      set afterList to (unix id of every process whose visible is true and name of it is not equal to “AppleScript Editor”)
      
–set afterList to (unix id of every process whose visible is true)
      
log afterList
    end tell
    
    
    
–プロセスIDの差分を取得する
    
set dRes to getListDiff(beforeList, afterList) of me
    
    
if dRes is not equal to {} then
      repeat with tmpUNIXID in dRes
        set anUNIXID to (contents of tmpUNIXID) as string
        
set killRes to killProcessByID(anUNIXID) of me
        
log killRes
      end repeat
    end if
    
    
    
–書き出したHTMLのリネーム
    
if htmlRes = true then
      tell application “Finder”
        tell file outFile
          set aName to name
          
          
–書き出したHTMLファイルにバージョン番号を反映させる
          
set bName to replaceText(aName, “-AS.html”, (” “ & sVerStr & “.html”)) of me
          
set name to bName
        end tell
      end tell
    end if
  end if
end repeat

ngList –書き出せなかったアプリの一覧

–デフォルトでインストールされているAS対応アプリケーションのリストを取得する
on getScriptableAppPathList()
  set apFol to path to applications folder
  
set utilFol to path to utilities folder
  
set sysFol to ((path to system folder) as string) & “Library:CoreServices:”
  
set sysLibFol to ((path to system folder) as string) & “Library:ScriptingAdditions:”
  
set devFol to ((path to startup disk) as string) & “Developer:Applications:”
  
set libPath to (path to library folder) & “ScriptingAdditins:”
  
  
tell application “Finder”
    –一般アプリケーション
    
tell folder apFol
      set ap1List to (every application file whose accepts high level events is true and has scripting terminology of it is true) as alias list
    end tell
    
    
–ユーティリティーフォルダー
    
tell folder utilFol
      set ap2List to (every application file whose accepts high level events is true and has scripting terminology of it is true) as alias list
    end tell
    
    
–SystemのCoreServicesフォルダ
    
tell folder sysFol
      set ap3List to (every application file whose has scripting terminology is true) as alias list
    end tell
    
    
–Developerフォルダ
    
try
      tell folder devFol
        set ap4List to (every application file whose has scripting terminology is true) as alias list
      end tell
    on error
      set ap4List to {}
    end try
    
    
–/System/Library/ScriptingAdditions フォルダのOSAX
    
try
      tell folder sysLibFol
        set osax1List to (every file whose name ends with “.osax”) as alias list
      end tell
    on error
      set osax1List to {}
    end try
    
    
    
–/Library/ScriptingAdditions フォルダのOSAX
    
try
      tell folder libPath
        set osax2List to (every file whose name ends with “.osax”) as alias list
      end tell
    on error
      set osax2List to {}
    end try
    
    
    
set appList to ap1List & ap2List & ap3List & ap4List & osax1List & osax2List
    
  end tell
  
  
return appList
  
end getScriptableAppPathList

–任意のデータから特定の文字列を置換
on replaceText(origData, origText, repText)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {origText}
  
set origData to text items of origData
  
set AppleScript’s text item delimiters to {repText}
  
set origData to origData as text
  
set AppleScript’s text item delimiters to curDelim
  
–set b to origData as text
  
return origData
end replaceText

–short version文字列をよろしく処理する(major.minor1.minor2)
–short versionに英語や日本語の文字をズラズラ並べていた場合には所期の動作を行えない
on prepareShortVersionStringNum(sVer)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {“.”}
  
set sList to text items of sVer
  
set AppleScript’s text item delimiters to curDelim
  
  
set sLen to length of sList
  
if sLen = 2 then
    set sVer to sVer & “.0″
  else if sLen = 1 then
    set sVer to sVer & “.0.0″
  end if
  
  
return sVer
end prepareShortVersionStringNum

–リスト間のdiffを取る
–aList: before List, bList: after List
on getListDiff(aList, bList)
  set diffList to {}
  
  
repeat with i in bList
    set j to contents of i
    
if j is not in aList then
      set the end of diffList to j
    end if
  end repeat
  
  
return diffList
end getListDiff

–指定プロセスをしつこくkillする
on killProcessByID(anID)
  set anID to anID as string
  
  
set errorCount to 20 –10 seconds to wait
  
  
repeat
    
    
tell application “System Events”
      set dID to every process whose unix id is equal to (anID as number)
    end tell
    
    
if dID = {} then return true
    
    
do shell script “kill -9 “ & anID
    
    
set errorCount to errorCount - 1
    
if errorCount = 0 then return false
    
    
delay 0.5
    
  end repeat
  
end killProcessByID

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

03/14 Safari 5.1.4 AppleScript用語辞書に変更なし

Safariの5.1.4アップデートがリリースされましたが、AppleScript用語辞書に変更はありませんでした。

03/12 Find same file name with different extension in same directory

This is a simple AppleScript to find same file name with different extension in same directory.

Sample Data:
finder1.jpg

Output Data:
–> {{”D120_a.jpg”, “D120_a.png”}, {”D120_c.gif”, “D120_c.jpg”, “D120_c.png”, “D120_c.txt”}}

スクリプト名:find same file name with different extension in same directory
–Speed up technic
script aRef
  property aList : {} –every file name of user selected folder ( work)
  
property bList : {} – every file name list (without duplicates) (work)
  
property cList : {} –duplicated file name list (work)
  
property dList : {} –output duplicated file names with different extensions
end script

–Initialize variables
set aList of aRef to {}
set bList of aRef to {}
set cList of aRef to {}
set dList of aRef to {}

set a to choose folder with prompt "Choose check Folder"

tell application "Finder"
  tell folder a
    set aList of aRef to name of every file
  end tell
end tell

–make pure file name list(without extension) to cList
repeat with i in aList of aRef
  set j to contents of i
  
set jj to retFileNameWithoutExt(j) of me
  
  
if jj is in bList of aRef then
    –duplicated file name & does not exist in cList
    
if jj is not in cList of aRef then
      set the end of cList of aRef to jj
    end if
    
    
set tmpName to jj & "."
    
    
tell application "Finder"
      tell folder a
        –set dList of aRef to dList of aRef & (name of every file whose name starts with tmpName)
        
set the end of dList of aRef to (name of every file whose name starts with tmpName)
      end tell
    end tell
    
  end if
  
  
set the end of bList of aRef to jj
end repeat

–Remove duplicates from List
set aRes to removeDuplicates(dList of aRef) of me

–> {{"D120_a.jpg", "D120_a.png"}, {"D120_c.gif", "D120_c.jpg", "D120_c.png", "D120_c.txt"}}

–Remove Duplicated Item from List
on removeDuplicates(aList)
  set newList to {}
  
repeat with i from 1 to (length of aList)
    set anItem to item 1 of aList
    
set aList to rest of aList
    
if {anItem} is not in aList then set end of newList to anItem
  end repeat
  
return newList
end removeDuplicates

–delete extension from file name
on retFileNameWithoutExt(fileNameStr)
  set fLen to length of fileNameStr
  
set revText to (reverse of (characters of fileNameStr)) as string –make reversed string
  
set anOffset to offset of "." in revText
  
set fRes to text 1 thru (fLen - anOffset) of fileNameStr
  
return fRes
end retFileNameWithoutExt

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

03/11 NSTextViewからのテキストデータ取得、テキスト設定サンプル

NSTextViewへのデータ設定、データ取得を行うAppleScriptObjCのサンプルです。

AppleScript Studioで作ってあったOpenSSLのユーティリティをAppleScriptObjCで作り直そうとしたときに、どうも一定文字以上のデータのエンコード時に文字化けが発生。その問題検証のために作成したサンプルです。

実際に試してみて、NSTextViewからの値の取得/設定時にはとくに問題がないことがはっきりしました。やはり、実際に組んで試してみないと。

tv1.jpg

→ プロジェクトのダウンロード(Xcode 4.1 on Mac OS X 10.6.8で検証)

AppleScriptObjCファイル名:textview1AppDelegate.applescript

– textview1AppDelegate.applescript
– textview1

– Created by 長野谷 隆昌 on 12/01/13.
– Copyright 2012 Piyomaru Software. All rights reserved.

script textview1AppDelegate
  
property parent : class “NSObject”
  
  
property aTV : missing value
  
property bTV : missing value
  
  
on applicationWillFinishLaunching_(aNotification)
    
– Insert code here to initialize your application before any files are opened
  
end applicationWillFinishLaunching_
  
  
on applicationShouldTerminate_(sender)
    
– Insert code here to do any housekeeping before your application quits
    
return current application’s NSTerminateNow
  
end applicationShouldTerminate_
  
  
on clicked_(sender)
    
    
set textStorage to (my aTV’s textStorage())
    
set theText to textStorage’s |string|()
    
display dialog (theText as string)
    
  
end clicked_
  
  
on clicked2_(sender)
    
    
    
set textStorage to (my aTV’s textStorage())
    
set theText to textStorage’s |string|()
    
    
set theText to theText as Unicode text
    
    
my bTV’s setString_(theText)
    
  
end clicked2_
  
  
on clicked3_(sender)
    
    
set textStorage to (my aTV’s textStorage())
    
set theTextA to textStorage’s |string|()
    
set theTextA to theTextA as Unicode text
    
    
set textStorage to (my bTV’s textStorage())
    
set theTextB to textStorage’s |string|()
    
set theTextB to theTextB as Unicode text
    
    
if theTextA = theTextB then
      
display dialog “左右のテキスト内容はイコールです”
    
else
      
display dialog “左右のテキスト内容は合っていません”
    
end if
    
  
end clicked3_
  
end script

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

03/07 InDesign CS3で指定のオプジェクトを、JPEG書き出ししてiPhoneへ

InDesign CS3上で指定したオブジェクトをJPEG書き出ししてiPhoneに転送するAppleScriptです。

ことのはじまりは、目下開発中のiPhoneアプリ(私はプロジェクト管理やら仕様書書きやらを)で、Welcome画面の表示を行うのに「文字詰めや行送りをいろいろ指定できないと!」という話になったこと。

……そもそも、iPhoneの文字表示部品に、そんな気の利いたものはありません。そこで、InDesignやらIllustrator上で気の済むまで行間や文字間にこだわっていただいて、それをそのまま「画像」として書き出して表示しようではないか、と。

ただし、その指定内容をすぐにiPhoneの実機で見たいという話に。

その場で10分もかけずにInDesign書類上の指定レイヤー(「コンテンツ」)上に存在する指定名称(スクリプトラベル「screen」)のグループをJPEG書き出しして、書き出したJPEG書類をiPhotoにインポートして、iTunesに命令して接続しているすべてのiOSデバイスにシンクロを行うようAppleScriptで指令を出すようにしてみました。

できた瞬間はかなりガッツポーズでしたが、冷静に考えるとInDesignから書き出されるJPEG画像のクオリティが「残念なレベル」です。また、シンクロが終わるまでにちょっと時間がかかるので、実用性がいまひとつ。

結局、Good Reader for iPhoneをインストールして、iTunes経由でGood Readerに対してInDesignから書き出したPDFを渡す、という方法に落ち着きました。本Scriptは何らかの「可能性」を感じさせてくれはしたのですが、結局おクラ入りに。

スクリプト名:InDesign CS3で指定のオプジェクトを、JPEG書き出ししてiPhoneへ
–v1 InDesign CS3から直接JPEG書き出し。画像クオリティが低くて難あり

set dtPath to (path to desktop) as string
set fName to do shell script "date +%Y%m%d%H%M%S"

set fullPath to dtPath & fName & ".jpg"
set fullPathPOSIX to POSIX path of fullPath

tell application "Adobe InDesign CS3"
  tell document 1
    tell layer "コンテンツ"
      set aList to every group whose label is equal to "screen"
    end tell
    
    
set expItem to contents of first item of aList
    
export expItem format JPG to fullPath without with grids
    
  end tell
end tell

–iPhotoに書き出したJPEGファイルをインポートする
tell application "iPhoto"
  import from fullPathPOSIX
end tell

–アップデート可能なiOSデバイスをアップデートする
tell application "iTunes"
  repeat with i in sources
    if (kind of i is iPod) then update i
  end repeat
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

03/06 Excelの表中のデータを拾ってセルに色を付ける

Excelの表中のデータを拾ってセルに色を付けるAppleScriptです。

Excelの表の中にR,G,Bのデータが1〜5セット、空きのセットには-1,-1,-1が入っている状態で表のI〜W列を拾って、A〜E列のセルに色を付けます。行は1行目から41行目までサーチしますが、このあたりはお好きに直して使うとよろしいでしょう。

xls.jpg

スクリプト名:表中のデータを拾ってセルに色を付ける
set colCellList to {“A”, “B”, “C”, “D”, “E”}
set dataCellList to {{“I”, “J”, “K”}, {“L”, “M”, “N”}, {“O”, “P”, “Q”}, {“R”, “S”, “T”}, {“U”, “V”, “W”}}

tell application “Microsoft Excel”
  tell sheet 1
    repeat with i from 1 to 41
      
      
–1行分のループ
      
repeat with j from 1 to 5
        
        
set aColCell to (contents of item j of colCellList) & i as string
        
        
set aDataRangeBeginStr to (contents of first item of item j of dataCellList) & i as string
        
set aDataRangeEndStr to (contents of last item of item j of dataCellList) & i as string
        
        
set aRange to range (aDataRangeBeginStr & “:” & aDataRangeEndStr)
        
set aData to value of aRange
        
        
if aData = {{-1.0, -1.0, -1.0}} then –データが入っていない箇所には-1を入れてある
          exit repeat
        end if
        
        
set color of interior object of cell aColCell to first item of aData
        
      end repeat
      
    end repeat
  end tell
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/29 Excel 2011で現在表示中のウィンドウのすべてのタブのズーム倍率を変更する

Excel 2011で現在表示中のウィンドウのすべてのシートのズーム倍率を変更するAppleScriptです。

Windowsユーザーの方からExcelの書類をメールでいただいたりすると……表示倍率が75%だったり50%だったりで、そのままMacBook Pro 17インチの1920×1200ドットの本体画面で表示すると、小さすぎて……見えません。

下手にタブ(シート)が大量に存在していたりすると、表示倍率を変更するのがうっとおしいことこの上ありません。そこで、すべてのシートを順次表示させて表示倍率を変更するAppleScriptを書いてみました。

Excelのファイルオープンの動作すべてをトラップして、ファイルオープン後に必ずこの処理を加えたくなるほどです。PFiddleSoft(旧称:PreFab Software)の「UI Actions」を併用して、メニュー項目にフォルダアクションよろしくScriptを仕掛けて、「ファイルを開く」メニュー項目の実行後に本Scriptを実行できるとよいのですが……

スクリプト名:Excel 2011で現在表示中のウィンドウのすべてのタブのズーム倍率を変更する
set zoomNum to 150 –表示倍率(10〜400)

tell application “Microsoft Excel”
  
  
tell window 1
    set curSheetNum to entry_index of active sheet –あとでこのシートの表示状態に戻す  
  end tell
  
  
tell workbook 1
    set sList to every sheet
    
repeat with i in sList
      set j to contents of i
      
      
–表示対象のWorksheet(タブ)を切り替える
      
tell j
        activate object
      end tell
      
      
–現在表示中のExcelのウィンドウの表示倍率を変更する
      
changeZoomOfCurrentExcelWindow(zoomNum) of me
    end repeat
  end tell
  
  
tell workbook 1
    activate object worksheet curSheetNum –初期表示状態に戻す
  end tell
  
end tell

–Excel 2011で現在表示中のウィンドウのズーム倍率を変更する
on changeZoomOfCurrentExcelWindow(aZoomPercent)
  tell application “Microsoft Excel”
    tell window 1
      set zoom to aZoomPercent
    end tell
  end tell
end changeZoomOfCurrentExcelWindow

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/28 tellブロックの書き方いろいろ

Mac OS X 10.5以降、tellブロックの書き方が拡張され、いろいろと柔軟性を持たせたAppleScriptを書けるようになりました。日常的には、Mac OS X 10.4で動かすケースを考えると積極的には採用してこなかったところですが、以下のように書けるようになっています。

スクリプト名:tell block
–Mac OS X 10.5以降で可能なtell文の記述方法の一覧

tell application “Address Book” –通常パターン
  set mCard to my card
  
set aP to properties of mCard
end tell

tell application id “com.apple.addressbook” –Bundle ID指定パターン
  set mCard to my card
  
set aP to properties of mCard
end tell

tell application “/Applications/Address Book.app” –フルパス指定パターン
  set mCard to my card
  
set aP to properties of mCard
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

Mac OS X標準搭載のアプリケーションが、バージョンアップ時に名称変更になることは、ごくまれにあります。身近な例では、Script EditorがAppleScript Editorに変更になったりしました。

この夏にやってくるOS X 10.8では、OS標準添付アプリもiOSに合わせて微妙に名称変更してくることが予想されます。すでにきな臭いところでは、iChatがMessagesに変わることは間違いありません。

これまでに作った(膨大な)AppleScriptを書き換える必要があるかといえば、アプリケーションのBundle IDが変わっていなければ大丈夫だろうかといったところ。System Eventsでプロセス一覧を取得して特定アプリケーションの起動をプロセス名称で確認する、とかいった処理「以外」はそれほど書き換える必要はないものと見ています。

ただ、冒頭で紹介したtellブロックのうち、フルパスを指定するタイプは書き換えが必要になります。そもそもファイル名が異なるので、書き換えなくてはなりません。

AppleScript EditorをAppleScriptからコントロールして、絶対パスでアプリケーションを指定している箇所があれば、自動で書き換える……といったことも、それほど難しくはないため作っておいてもよいでしょう。

02/23 Excel 2011ですべてのタブのデータを取得して1つにまとめる v3

Excel 2011で現在オープン中の書類のすべてのタブのデータを取得して新規ドキュメントで1つにまとめるAppleScriptの改良版です。

最初のバージョンでは、すべてのタブを順次表示しながらデータを集めていましたが、別にデータを集めるだけなら表示を切り替える必要はまったくないので、表示を切り替えるのをやめたのがこのバージョンです。

元のバージョンから比べると、かなり速くなっています(見てわかるほどに)。

スクリプト名:Excel 2011ですべてのタブのデータを取得して1つにまとめる v3
–アクティブなExcelワークブック(書類)中のすべてのワークシートの内容を取得して、新規作成したワークブック(書類)にまとめる

global aList, aList_r

set aList to {}
set aList_r to a reference to aList

tell application "Microsoft Excel"
  
  
–最前面のドキュメント中の各シート名を取得
  
tell active workbook
    set sList to name of every worksheet
    
set aCount to count every item of sList
  end tell
  
  
–各ワークシートの呼び出しループ
  
repeat with i from 1 to aCount
    set aList to aList_r & getCurrentSheetData(i, 100, "C", "L") of me –これ以上は存在していない筈の行数
  end repeat
  
end tell

–新規ワークシートを作成してそこに連結したデータを入れる
set dataLen to (length of aList)
tell application "Microsoft Excel"
  set newWS to make new workbook
  
tell newWS
    tell active sheet
      set tmpRangeStr to "A2:L" & ((dataLen + 1) as string)
      
set tmpRange to range tmpRangeStr
      
set value of tmpRange to aList
    end tell
  end tell
end tell

–現在表示中のワークシートから、データの入っている範囲を求めて中のデータを返す
on getCurrentSheetData(workSheetIndex, maxRowNum, checkColumnStr, endColumnStr)
  –Excelからデータを取得する
  
using terms from application "Microsoft Excel"
    tell application "Microsoft Excel"
      tell active workbook
        tell sheet workSheetIndex
          
          
set tmpRange to checkColumnStr & (maxRowNum as string)
          
set a to range tmpRange –B列にはかならずデータが入っている & 100行もデータは存在していない
          
set b to get end a direction toward the top
          
set endRow to first row index of b
          
          
set aRangeStr to "A2:" & endColumnStr & (endRow as string) –1行目には凡例が入っているためスキップ
          
set aRangeObj to range aRangeStr
          
          
set rangeDat to string value of aRangeObj
          
          
return rangeDat
          
        end tell
      end tell
    end tell
  end using terms from
end getCurrentSheetData

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/21 Excel 2011で現在オープン中の書類の選択中のシートをCSV書き出し

Excel 2011のCSV書き出しのサンプルを探していたら、現在オープン中の書類(Workbook)中のすべてのシート(Worksheet)をCSV書き出しするAppleScriptを見つけました。

そこまでの処理は必要なかったので、逆に機能を切り捨てて、最低限の機能に絞り込んでサンプルコードとして掲載しておくことに。

スクリプト名:Excel 2011で指定書類の現在のワークシートをCSV書き出し
–オリジナル作者および引用元:
– Excel Spreadsheet to CSV Files
– by Scott Wilcox <scott@dor.ky>
– https://github.com/dordotky/applescripts
– https://github.com/dordotky/applescripts/blob/master/Excel%20Worksheets%20to%20CSV.applescript

– CSV ファイルを書き出すフォルダを選択
set outFol to (choose folder with prompt "CVSファイルの書き出し先フォルダを選択:")

tell application "Microsoft Excel"
  activate
  
  
tell active sheet
    set wName to name
    
    
– Save the worksheet as a CSV file
    
set theSheetsPath to outFol & wName & ".csv" as string
    
save as filename theSheetsPath file format CSV file format with overwrite
  end tell
  
  
close every workbook saving no –クローズ
  
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/21 PhotoshopでRGB→CMYK、CMYK→RGB変換

PhotoshopでRGB⇄CMYKの色変換を行うAppleScriptです。

choose colorで選択した色を、Photoshopを用いてRGB⇄CMYKの色変換を行うものです。PhotoshopをAppleScriptから制御して画像フォーマットを変換させるのは「よくある使い方」ですが、Mac OS X 10.6でColorSync Scriptingが廃止されたいまとなっては、色空間の変換を行う処理エンジンとして使うケースもけっこうあります。

CMYKへの色変換を行う機能がまともにないOS向けに、RGB⇄CMYK変換のテーブルを作成するさいの処理エンジンとして使ってみたりと、割と大活躍しています。InDesignと違って、AppleScriptから連続してコントロールしてもクラッシュしにくい、というのもいいところです。

スクリプト名:PhotoshopでRGB→CMYK、CMYK→RGB変換
–色選択
set {rCol, gCol, bCol} to choose color

–16ビット値→8ビット値 変換
set rCol to rCol div 256
set gCol to gCol div 256
set bCol to bCol div 256

set aCMYK to retCMYKfromRGBnumList(rCol, gCol, bCol) of me
–> {0, 82, 82, 0} –結果は選択した色によって異なります。返ってくる値が4つの数字で構成されることを示しています

copy aCMYK to {cNum, mNum, yNum, kNum}

set bRGB to retRGBfromCMYKnumList(cNum, mNum, yNum, kNum) of me
–> {154, 192, 57}–結果は選択した色によって異なります。返ってくる値が3つの数字で構成されることを示しています

–与えられたテキストをRGBデータと評価してCMYK値を返す
on retCMYKfromRGBnumList(rNum, gNum, bNum)
  
  
tell application "Adobe Photoshop CS3"
    set myCMYKColor to convert color {class:RGB color, red:rNum, green:gNum, blue:bNum} to CMYK
    
    
set cyanNum to cyan of myCMYKColor
    
set magentaNum to magenta of myCMYKColor
    
set yellowNum to yellow of myCMYKColor
    
set kuroNum to black of myCMYKColor
  end tell
  
  
set cyanNum to round cyanNum rounding as taught in school –四捨五入
  
set magentaNum to round magentaNum rounding as taught in school –四捨五入
  
set yellowNum to round yellowNum rounding as taught in school –四捨五入
  
set kuroNum to round kuroNum rounding as taught in school –四捨五入
  
  
return {cyanNum, magentaNum, yellowNum, kuroNum}
  
end retCMYKfromRGBnumList

–与えられたCMYKデータをRGBに変換して返す
on retRGBfromCMYKnumList(cNum, mNum, yNum, kNum)
  
  
tell application "Adobe Photoshop CS3"
    set myRGBColor to convert color {class:CMYK color, cyan:cNum, magenta:mNum, yellow:yNum, black:kNum} to RGB
    
    
set redNum to red of myRGBColor
    
set greenNum to green of myRGBColor
    
set blueNum to blue of myRGBColor
  end tell
  
  
set redNum to round redNum rounding as taught in school –四捨五入
  
set greenNum to round greenNum rounding as taught in school –四捨五入
  
set blueNum to round blueNum rounding as taught in school –四捨五入
  
  
  
return {redNum, greenNum, blueNum}
  
end retRGBfromCMYKnumList

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/18 AppleScriptObjC Explorer 2 v2.2

AppleScriptObjCの世界をほぼ1人で引っ張っている感のある、Shane StanleyによるAppleScriptObjCに特化したスクリプトエディタが「AppleScriptObjC Explorer 2」です。

exp1.jpg

▲構文色分けがまったくできていないXcode 4(左)と構文色分けに対応しているAppleScriptObjC Explorer(右)

exp2.jpg
▲インデントも正確なAppleScript Explorer 2

まだ使い始めて日が浅いのですが、その特徴を紹介すると……

・Xcode 4ではまったく効かない「AppleScriptの構文に応じた色分け」ができる(これはでかい! というか、Xcode 4がダメすぎ)
・Xcode 4ではまったくダメな「インデント」が正確(Xcode 4、本当にダメすぎ)
・Xcode 4では絶望的な、ログ表示機能を備える
・単体で動作可能なAppleScriptObjCベースのアプリケーションを作成可能
・Xcode 4の外部エディタとして動作可能(XcodeでScriptのファイルを選択して、コンテクストメニューから「Open With External Editor」を実行。あらかじめFinder上で拡張子とアプリケーションの関連を変更しておく必要がある)

exp3.jpg

・定番の処理(Arrayを作るとか、ソートするとか)はメニューからScript本文中にInsert可能

exp4.jpg

exp5.jpg

・Script文中で入力補完機能を利用可能(ここだけ、まだ試していない)

といったところでしょうか。AppleScriptObjCが使えるMac OS X 10.6/10.7で動作します。

構文色分けができないとプログラミング効率が悪すぎるのと、インデントが正確でないXcode 4にシビレを切らしてAppleScriptObjC Explorerを購入(5,000円……為替レートの変動で変わる??)。

ただ、デバッグ機能についてはアプリケーション起動時に呼ばれる「applicationWillFinishLaunching_」イベントハンドラの中で実行されるコードしかデバッグできなさそうなので、デバッグ機能に期待して購入すると、期待外れになってしまうかもしれません。

総合的には……残念ながら、値段の割には……と、感じる点が多々あります。

AppleのCocoaについてのヘルプからAppleScriptObjC用のヘルプとして変換して表示するとか、既存のObjective-Cのコードをプロジェクトにインポートすると、その呼び出し用のAppleScriptObjCコードがScript本文中に展開されるとか……そういう機能を期待したいところです。

いまの段階では、ちょっと気の利いた構文色分けエディタ、というレベルです。それ以上でもそれ以下でもありません(Shane Stanleyへのお布施、という意味ではとても意義があるかもしれない)。

とりあえず30日間は試用ができるため、Xcode 4にブチ切れまくっている方は試してみるとよいでしょう。

02/17 OS X 10.8 Mountain Lion発表。Messages Beta

OS X 10.8「Mountain Lion」が発表になり、その特徴のうちのひとつである「Messages」のOS X 10.7用 Betaの配布が開始されました。

Messagesは、iChatとFaceTimeを一緒にしたアプリケーションで、iChatを置き換えるものになるようです。

messages.jpg

msg1.jpg

さっそく、10.7.3環境のMacBook AirにMessagesをインストール。AppleScript用語辞書を調べてみると、なぜか「iChat」の辞書としてオープンされました。

それもそのはず。アクティビティ・モニタで見る限りは「メッセージ」という名前で見えますが、psコマンドで見ると「iChat」。System Events経由でプロセス名を確認するとやはり「iChat」。Info.plistのBundle Nameが「Messages」になってはいるものの、これはやはりiChat。

msg2.jpg

msg3.jpg

OS X 10.8の登場は2012年夏とか。登場が予想よりあまりに早いので、いろんな意味で悩ましいところですが、Siriが載ってくるんだろうなとかCarbonが削られたりするんだろうなとか、いろいろ考えてしまうわけですが……目下Lionでいろいろ不満が集まっている仕様が直ることを期待したいところです。

02/14 Google Chromeでpresentation modeを開始、終了

Google Chromeでpresentation mode(全画面表示モード)に移行するAppleScriptです。

chrome1.jpg

Google Chromeの新バージョン(17.x)が出ていたので、アップデートしたところAppleScript用語辞書の内容が追加されており、実際に動くかどうか試してみました。

「enter presentation mode」で全画面モードに入り、「exit presentation mode」で全画面表示を終了します。

About画面からアップデートを行おうとするとサーバーと接続できない、と表示するところは相変わらず。お間抜けさ加減も健在です。

chrome2.jpg

スクリプト名:Google Chromeでpresentation modeを開始、終了
tell application “Google Chrome”
  tell window 1
    enter presentation mode
    
–exit presentation mode
  end tell
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/14 Excel 2011ですべてのタブのデータを取得して1つにまとめる

Excel 2011で最前面のドキュメント中のすべてのワークシートの内容を新規書類にまとめるAppleScriptです。

最前面のドキュメント(workbook)内のすべてのワークシート(worksheet)のデータ存在行範囲を(C列のデータをもとに)検出して、横方向にはA〜Lまでのデータを取り出します。

ex1.jpg

すべてのワークシート内のデータを取り出したあと、Excelで新規書類を作成して、そこにまとめたデータを入れます。

Excelで書類に大量のワークシート(タブ)を作って、快調にデータを入力していたところ、ワークシートに別れているのでデータの見通しがきかなくなって……手作業でまとめるのがいやだったので、その場でAppleScriptを組んでまとめさせるようにしてみました。

スクリプト名:Excel 2011ですべてのタブのデータを取得して1つにまとめる
–アクティブなExcelワークブック(書類)中のすべてのワークシートの内容を取得して、

global aList, aList_r

set aList to {}
set aList_r to a reference to aList

tell application "Microsoft Excel"
  
  
–現在表示中のワークシートのindex番号を取得する
  
tell window 1
    set curSheetNum to entry_index of active sheet –あとでこのシートの表示状態に戻す
  end tell
  
  
–最前面のドキュメント中の各シート名を取得
  
tell active workbook
    set sList to name of every worksheet
    
set aCount to count every item of sList
  end tell
  
  
repeat with i from 1 to aCount
    tell workbook 1
      activate object worksheet i –★★ 表示切り換え用の変な命令
    end tell
    
    
set aList to aList & getCurrentSheetData(100) of me –これ以上は存在していない筈の行数
    
  end repeat
  
  
–表示状態を元に戻す
  
tell workbook 1
    activate object worksheet curSheetNum –初期表示状態に戻す
  end tell
  
end tell

–新規ワークシートを作成してそこに連結したデータを入れる
set dataLen to (length of aList)
tell application "Microsoft Excel"
  set newWS to make new workbook
  
tell newWS
    tell active sheet
      set tmpRangeStr to "A2:L" & ((dataLen + 1) as string)
      
set tmpRange to range tmpRangeStr
      
set value of tmpRange to aList
    end tell
  end tell
end tell

aList

–現在表示中のワークシートから、データの入っている範囲を求めて中のデータを返す
on getCurrentSheetData(maxRowNum)
  –Excelからデータを取得する
  
using terms from application "Microsoft Excel"
    tell application "Microsoft Excel"
      tell active workbook
        tell active sheet
          set tmpRange to "C" & (maxRowNum as string)
          
set a to range tmpRange –B列にはかならずデータが入っている & 100行もデータは存在していない
          
set b to get end a direction toward the top
          
set endRow to first row index of b
          
          
set aRangeStr to "A2:" & "L" & (endRow as string)
          
set aRangeObj to range aRangeStr
          
          
set rangeDat to string value of aRangeObj
          
        end tell
      end tell
    end tell
  end using terms from
end getCurrentSheetData

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

02/14 iPhoneアプリで指定されているサイズのアイコンをPhotoshopで機械的に作成する

iPhoneアプリ用の各種サイズ/各種ファイル名のPNG書類を作成するAppleScriptです。

iPhoneアプリの作成用には、iPhoneアプリ/iPadアプリ/iPhoneとiPadのUniversalアプリとで、数種類のサイズのアイコンを用意する必要があり、それぞれ決められたファイル名で保存する必要があって、けっこうダルい感じです。

画像のリサイズといえば、ぼかしフィルタをかけてからリサイズ、リサイズ後にシャープネスフィルタをかけるなど、いろいろやり方はありますが、ここでは単に機械的にリサイズするだけです。

Photoshop(もしくはElements)で縦と横のピクセル数が同じ画像をオープンしておいて、本Scriptを実行すると出力先のフォルダをきいてきます。フォルダを選択すると、各サイズにリサイズして指定ファイル名で保存します。

例によって、Photoshop CS3とPhotoshop Elements 6で動作確認していますが、Photoshop CS4/5/5.5やPhotoshop Elementsの新しいバージョンでも動くはずです。

スクリプト名:iPhoneアプリで指定されているサイズのアイコンをPhotoshopで機械的に作成する
–iPhoneアプリで指定されているサイズのアイコンを機械的に作成する
–元画像は512 x 512以上のサイズであることを前提としている(ただし正方形であること)
–元画像をオープンした状態で本AppleScriptを実行する

–参考資料:
–https://developer.apple.com/library/ios/#qa/qa1686/_index.html

–iPhoneアプリに必要な各アイコン用PNGファイルのサイズとファイル名
set sizeList to {{512, 512, "iTunesArtwork"}, {57, 57, "Icon.png"}, {114, 114, "Icon@2x.png"}, {72, 72, "Icon-72.png"}, {29, 29, "Icon-Small.png"}, {50, 50, "Icon-Small-50.png"}, {58, 58, "Icon-Small@2x.png"}} –iPhoneアプリ

–set sizeList to {{512, 512, "iTunesArtwork"}, {72, 72, "Icon-72.png"}, {50, 50, "Icon-Small-50.png"}, {29, 29, "Icon-Small.png"}} –iPadアプリ

–set sizeList to {{512, 512, "iTunesArtwork"}, {57, 57, "Icon.png"}, {114, 114, "Icon@2x.png"}, {72, 72, "Icon-72.png"}, {50, 50, "Icon-Small-50.png"}, {29, 29, "Icon-Small.png"}, {58, 58, "Icon-Small@2x.png"}} –iPhone/iPad Universaslアプリ

tell application "Adobe Photoshop CS3"
  
  
–最前面のドキュメント(処理対象)を取得する
  
set aDoc to document 1
  
tell aDoc
    set curRes to resolution
  end tell
  
  
–出力先フォルダを求める
  
set outFol to choose folder with prompt "ファイルの保存先フォルダを取得"
  
  
–単位を取得
  
set oldUnits to ruler units of settings
  
set ruler units of settings to pixel units
  
  
–最前面のドキュメント(処理対象)を取得する
  
set aDoc to document 1
  
tell aDoc
    set curRes to resolution
    
set {origX, origY} to {width, height}
  end tell
  
  
–縦横サイズが同一でない場合へのエラー警告
  
if origX is not equal to origY then
    display dialog "縦横のドット数が異なるため、処理後に縦横比がゆがむ可能性があります。調整したのちに再度おためしください。" with title "エラー" buttons {"OK"} default button 1 with icon 1
    
return
  end if
  
  
–コピー、リサイズ、保存の処理ループ
  
repeat with i in sizeList
    
    
set xSize to contents of item 1 of i
    
set ySize to contents of item 2 of i
    
set fileName to contents of item 3 of i
    
    
–コピー
    
set dupDoc to (doc duplicate aDoc)
    
    
–リサイズ
    
tell dupDoc
      resize image width xSize height ySize resolution curRes resample method bicubic –bicubic/bicubic sharper/bicubic smoother/bilinear/closest neighbor/none
    end tell
    
    
–保存
    
set newFilePath to (outFol as string) & fileName
    
set myOptions to {class:PNG save options, interlaced:false}
    
save dupDoc in newFilePath as PNG with options myOptions appending lowercase extension with copying
    
close dupDoc saving no –リサイズ保存したPhotoshop Documentを破棄(保存したので不要になった)
    
  end repeat
  
  
–単位を元にもどす
  
set ruler units of settings to oldUnits
  
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

スクリプト名:iPhoneアプリで指定されているサイズのアイコンをPhotoshop Elementsで機械的に作成する
–iPhoneアプリで指定されているサイズのアイコンを機械的に作成する
–元画像は512 x 512以上のサイズであることを前提としている(ただし正方形であること)
–元画像をオープンした状態で本AppleScriptを実行する

–参考資料:
–https://developer.apple.com/library/ios/#qa/qa1686/_index.html

–iPhoneアプリに必要な各アイコン用PNGファイルのサイズとファイル名
set sizeList to {{512, 512, "iTunesArtwork"}, {57, 57, "Icon.png"}, {114, 114, "Icon@2x.png"}, {72, 72, "Icon-72.png"}, {29, 29, "Icon-Small.png"}, {50, 50, "Icon-Small-50.png"}, {58, 58, "Icon-Small@2x.png"}} –iPhoneアプリ

–set sizeList to {{512, 512, "iTunesArtwork"}, {72, 72, "Icon-72.png"}, {50, 50, "Icon-Small-50.png"}, {29, 29, "Icon-Small.png"}} –iPadアプリ

–set sizeList to {{512, 512, "iTunesArtwork"}, {57, 57, "Icon.png"}, {114, 114, "Icon@2x.png"}, {72, 72, "Icon-72.png"}, {50, 50, "Icon-Small-50.png"}, {29, 29, "Icon-Small.png"}, {58, 58, "Icon-Small@2x.png"}} –iPhone/iPad Universaslアプリ

tell application id "com.adobe.PhotoshopElements" –Photoshop Elements
  
  
–最前面のドキュメント(処理対象)を取得する
  
set aDoc to document 1
  
tell aDoc
    set curRes to resolution
  end tell
  
  
–出力先フォルダを求める
  
set outFol to choose folder with prompt "ファイルの保存先フォルダを取得"
  
  
–単位を取得
  
set oldUnits to ruler units of settings
  
set ruler units of settings to pixel units
  
  
–最前面のドキュメント(処理対象)を取得する
  
set aDoc to document 1
  
tell aDoc
    set curRes to resolution
    
set {origX, origY} to {width, height}
  end tell
  
  
–縦横サイズが同一でない場合へのエラー警告
  
if origX is not equal to origY then
    display dialog "縦横のドット数が異なるため、処理後に縦横比がゆがむ可能性があります。調整したのちに再度おためしください。" with title "エラー" buttons {"OK"} default button 1 with icon 1
    
return
  end if
  
  
–コピー、リサイズ、保存の処理ループ
  
repeat with i in sizeList
    
    
set xSize to contents of item 1 of i
    
set ySize to contents of item 2 of i
    
set fileName to contents of item 3 of i
    
    
–コピー
    
set dupDoc to (doc duplicate aDoc)
    
    
–リサイズ
    
tell dupDoc
      resize image width xSize height ySize resolution curRes resample method bicubic –bicubic/bicubic sharper/bicubic smoother/bilinear/closest neighbor/none
    end tell
    
    
–保存
    
set newFilePath to (outFol as string) & fileName
    
set myOptions to {class:PNG save options, interlaced:false}
    
save dupDoc in newFilePath as PNG with options myOptions appending lowercase extension with copying
    
close dupDoc saving no –リサイズ保存したPhotoshop Documentを破棄(保存したので不要になった)
    
  end repeat
  
  
–単位を元にもどす
  
set ruler units of settings to oldUnits
  
end tell

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に