Archive for the 'システム情報取得(sys info)' Category

05/13 モニタの解像度を取得する(複数モニタ対応)

Mac本体に接続されたディスプレイ(モニタ)の解像度を取得するAppleScriptについて、これまでにいろいろなものを紹介してきました。

なぜ、1つのやり方ですまないかといえば……System Eventsなどで直接ディスプレイ解像度を取得するような命令セットが用意されてこなかったためで……さまざまなやり方を組み合わせて求めてきました(とくに、AppleScript Studioのプログラム内に入れたときに使えるかどうかが問題でした。けっこう、Finderに対する命令がきかない場合があったりで、冷や汗をかかされました)。

scrn1.png

このような環境で試してみましたが、iPad 3をAir Displayを使って外付けディスプレイとして接続した場合には、「環境設定」には表示されるものの、OSの各種コマンドでAir Display接続したiPadの情報は取得できません。

disp5.png

scrn3.png

scrn2.png

注:以下のサンプルAppleScriptは、Air Display経由のiPad 3を「外した」状態で(MacBook Pro本体+外付けLCDの2モニタ構成で)実行しています

■方法1 FinderのDesktop WindowのScroll Areaのsizeを取得

複数ディスプレイのトータルのサイズを取得。個別のディスプレイのサイズについては取得できません。

スクリプト名:displaySize1
–http://piyocast.com/as/archives/73
tell application “System Events” to set {rightLimit, bottomLimit} to size of scroll area 1 in process “Finder”
–> {3840, 1251}

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

■方法2 FinderのDesktop WindowのScroll Areaのsizeを取得

1つのモニタの情報のみ取得。

スクリプト名:displaySize2
–http://piyocast.com/as/archives/1560
tell (do shell script “/usr/sbin/system_profiler SPDisplaysDataType | grep Resolution”) to set {newR, newB} to {word 2 as number, word 4 as number} – get screen size for monitor

–> {1920, 1200}

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

■方法3 com.apple.windowserverの設定ファイルを読み込む方法

1つのモニタだけの情報を取得するようになっているので、そもそも複数のモニタには対応していません。

スクリプト名:displaySize3
–http://piyocast.com/as/archives/1561
return {word 3 of (do shell script “defaults read /Library/Preferences/com.apple.windowserver | grep -w Width”), word 3 of (do shell script “defaults read /Library/Preferences/com.apple.windowserver | grep -w Height”)}

–> {”1920″, “1200″}

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

■方法4 Finderでdesktop Windowのサイズを取得

複数モニタのトータルのデスクトップサイズを取得できます。モニタの位置によっては、マイナスの数値なども返ってきます。

スクリプト名:displaySize4
–http://piyocast.com/as/archives/1562
tell application “Finder”
  get bounds of window of desktop
  
–> {0, -51, 3840, 1200}
end tell

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

とりあえず、いままでのやり方を見直して……とりあえず、system_profilerコマンドを経由して複数のモニタの解像度を取得するようにしてみました。

スクリプト名:モニタの解像度を取得する(複数モニタ対応)
–17インチMacBook Pro本体ディスプレイ
set aRes to retDisplayResolution() of me
–> {{1920, 1200}}

–17インチMacBook Pro本体ディスプレイ(Main) + 外付け24インチモニタ(1920 x 1080)(Sub)の場合
set aRes to retDisplayResolution() of me
–> {{1920, 1200}, {1920, 1080}}

–17インチMacBook Pro本体ディスプレイ(Sub) + 外付け24インチモニタ(1920 x 1080)(Main)の場合
set aRes to retDisplayResolution() of me
–> {{1920, 1200}, {1920, 1080}}

–モニタ解像度を取得。複数モニタ接続時にはリストで列挙
on retDisplayResolution()
  
  
set sRes to do shell script “/usr/sbin/system_profiler SPDisplaysDataType | grep Resolution”
  
  
set sList to paragraphs of sRes
  
set resList to {}
  
  
repeat with i in sList
    set j to contents of i
    
set x1 to word 2 of j as number
    
set y1 to word 4 of j as number
    
set the end of resList to {x1, y1}
  end repeat
  
  
return resList
  
end retDisplayResolution

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

01/13 画面の解像度を取得するv5

画面の解像度を取得するAppleScriptです。

スクリプト名:画面の解像度を取得するv5
return {word 3 of (do shell script "defaults read /Library/Preferences/com.apple.windowserver | grep -w Width") as number, word 3 of (do shell script "defaults read /Library/Preferences/com.apple.windowserver | grep -w Height") as number}

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

01/13 画面の解像度を取得するv4

画面の解像度を取得するAppleScriptです。

スクリプト名:画面の解像度を取得するv4
tell application "Finder"
  get bounds of window of desktop
  
–> {0, 0, 1440, 900}
end tell

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

01/13 画面の解像度を取得するv3

画面の解像度を取得するAppleScriptです。

スクリプト名:画面の解像度を取得するv3
return {word 3 of (do shell script "defaults read /Library/Preferences/com.apple.windowserver | grep -w Width"), word 3 of (do shell script "defaults read /Library/Preferences/com.apple.windowserver | grep -w Height")}

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

01/13 画面の解像度を取得するv2

画面の解像度を取得するAppleScriptです。

スクリプト名:画面の解像度を取得するv2
tell (do shell script “/usr/sbin/system_profiler SPDisplaysDataType | grep Resolution”) to set {newR, newB} to {word 2 as number, word 4 as number} – get screen size for monitor

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

12/30 Mac添付の赤外線リモコンのon,off_v2

Mac添付の赤外線リモコンのon/offを行うAppleScriptです。

スクリプト名:Mac添付の赤外線リモコンのon,off_v2
try
  set currentValue to (((do shell script "defaults read /Library/Preferences/com.apple.driver.AppleIRController DeviceEnabled") as integer) + 1)
  
set status to item currentValue of {"disabled", "enabled"}
  
set button to (display dialog "Set remote control infrared. Right now it is " & status & "." buttons {"Cancel", item currentValue of {"Enable", "Disable"}} default button 2)
  
do shell script "defaults write /Library/Preferences/com.apple.driver.AppleIRController " & quote & "DeviceEnabled" & quote & " -bool " & item currentValue of {"yes", "no"} with administrator privileges
end try

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

08/12 現在のユーザーの権限を調べる v2

現在のユーザーの権限を調べ、管理者権限があるかないかを調べて返すAppleScriptです。

Mac OS X 10.4まではnetinfo系のコマンドで調べられたのですが、10.5でnetinfoが廃止になり……代わりのコマンドで取得できるようにしてみました。10.4までと10.5および10.6以降をサポートできるようにしてみました。

現在のユーザーに管理者権限がある場合にはtrueが、ない場合にはfalseが返ってきます。

スクリプト名:現在のユーザーの権限を調べる v2
set aPriv to getCurUsersPrivileges() of me

–現在実行中のユーザーの権限を得る(管理者か、それ以外か) 10.4および10.5以降両用
–管理者だとtrueが、それ以外だとfalseが返る
on getCurUsersPrivileges()
  set aVer to system attribute "sys2" –OSメジャーバージョンを取得する(例:Mac OS X 10.6.4→6)
  
  
set current_user to (do shell script "whoami") –実行中のユーザー名を取得
  
  
if aVer > 4 then
    –Mac OS X 10.5以降の処理
    
set adR to (do shell script "/usr/bin/dsmemberutil checkmembership -U " & current_user & " -G admin users")
    
    
if adR = "user is a member of the group" then
      return true
    else
      return false
    end if
    
  else
    –Mac OS X 10.4までの処理
    
set admin_users to (do shell script "/usr/bin/niutil -readprop . /groups/admin users")
    
tell (a reference to AppleScript’s text item delimiters)
      set {old_atid, contents} to {contents, " "}
      
set {admin_users, contents} to {text items of admin_users, old_atid}
    end tell
    
    
if current_user is in admin_users then
      return true
    else
      return false
    end if
  end if
  
end getCurUsersPrivileges

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

11/11 Web共有がオンになっているかどうかを検出する

Web共有がオンになっているかどうかを検出するAppleScriptです。

スクリプト名:Web共有がオンになっているかどうかを検出する
set webRes to retWebSharingEnabled() of me

–Web共有がオンになっているかどうかを検出する
on retWebSharingEnabled()
  return (do shell script "ps -ax | grep httpd") contains "/usr/sbin/httpd"
end retWebSharingEnabled

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

11/11 System EventsでScreen Saverの設定にアクセスする

System Eventsで、Screen Saver関連の設定情報を取得するAppleScriptです。

Screen Saverが動作中かどうかなど、かなり細かい情報を取得できます。

スクリプト名:System EventsでScren Saverの設定にアクセスする
–System EventsでScren Saverの設定にアクセスする
tell application “System Events”
  set pObj to a reference to screen saver preferences
  
tell pObj
    properties
    
–> {running:false, show clock:false, class:screen saver preferences object, delay interval:1200, main screen only:false}
  end tell
end tell

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

11/11 System EventsでScreen Saverの情報にアクセスする

System Events経由でScreen Saverの情報にアクセスするAppleScriptです。

使用中のシステムにインストールされているScreen Saverの情報を取得したり、使用中のScreen Saver(current screen saver)の情報を取得したり、Screen Saverを動作(start)させたり停止(stop)したりします。

スクリプト名:System EventsでScreen Saverの情報にアクセスする
–System EventsでScreen Saverの情報にアクセスする
tell application "System Events"
  
  
–システムにインストールされているScreen Saverの情報を取得する
  
set sList to every screen saver
  
–> {screen saver "QuaternionJulia", screen saver "Word of the Day", screen saver "Paper Shadow", screen saver "MacLampsSS", screen saver "Beach", screen saver "Flurry", screen saver "A Very 3D Christmas", screen saver "Shell", screen saver "iTunes Artwork", screen saver "screensaver.shuffle", screen saver "Abstract", screen saver "Computer Name", screen saver "FloatingMessage", screen saver "RSS Visualizer", screen saver "Forest", screen saver "Spectrum", screen saver "Random", screen saver "Cosmos", screen saver "ElectricSheep2", screen saver "Big Time", screen saver "Time Machine", screen saver "Arabesque", screen saver "Nature Patterns", screen saver "NightLights"}
  
  
–使用中のScreen Sverの情報を取得する
  
set curSaver to properties of current screen saver
  
–> {path:file "Macintosh HD:System:Library:Screen Savers:Shell.qtz", displayed name:"Shell", class:screen saver, picture display style:missing value, name:"Shell"}
  
  
–使用中のScreen Saverを実行する
  
start current screen saver
  
end tell

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

10/31 System EventsでDockの設定を取得、変更する

System Eventsで各種システム環境設定の内容を確認したり変更したりするサンプルの一環として作ってみました。System EventsでDockの設定を取得、変更するというものです。

AppleScript用語辞書に「r/o」(read only)と書かれているからといって、本当にリードオンリーかどうかはやってみないと分かりませんし、設定できると書かれていてもread onlyだった……という話は珍しくありません。

とりあえず、実際に動作を確認しておくことが重要です。それを自分一人でやっているほどの時間はないので、海外のScripterとの日常的な情報交換というのが、ものすごく重要になってくるわけです。

スクリプト名:System EventsでDockの設定を取得、変更する
tell application "System Events"
  tell dock preferences
    properties
    
–> {minimize effect:scale, magnification size:1.0, dock size:0.0, autohide:false, animate:true, magnification:true, screen edge:right, class:dock preferences object}
    
    
set a1 to animate
    
–> true
    
set animate to false
    
    
set a2 to autohide
    
–> false
    
set autohide to false
    
    
set a3 to dock size
    
–> 0.0
    
set dock size to 0.0
    
    
set a4 to magnification
    
–> true
    
set magnification to true
    
    
set a5 to minimize effect
    
–> scale
    
set minimize effect to scale
    
    
set a6 to screen edge
    
–> right
    
set screen edge to right
    
  end tell
end tell

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

10/30 System Eventsでハイライト色の情報にアクセス

System Eventsでシステム環境設定の内容にアクセスするサンプル。テキストを選択したときの強調表示色を指定するものです。

sys2.jpg

カラーピッカーで色を指定すると……

sys3.jpg

テキスト選択時のハイライト色が変更されます。

sys4.jpg

システム環境設定の内容も同様に変更されていることが確認できます。

スクリプト名:System Eventsでハイライト色の情報にアクセス
set aCol to choose color

tell application "System Events"
  set ap1 to a reference to appearance preferences
  
tell ap1
    set highlight color to aCol
  end tell
end tell

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

10/30 System Eventsでfont smoothing関連の情報にアクセスする

System Events経由でシステム環境設定>アピアランスのフォントスムージング関連の情報にアクセスするAppleScriptサンプルです。

sys1.jpg

ただ、font smoothing関連は、設定はできるものの内容を取得しようとすると、ちゃんとした結果が返ってこないようで……font smoothing styleの情報を取得すると、ごらんのとおりです。

スクリプト名:System Eventsでfont smoothing関連の情報にアクセスする
tell application "System Events"
  set ap1 to a reference to appearance preferences
  
tell ap1
    set fRes to font smoothing
    
–> true or false
    
    
set font smoothing to true –falseにしてもスムージング処理がオフになるわけではない?
    
    
set fRes1 to font smoothing limit
    
–> 6
    
    
–情報を取得すると結果がおかしい
    
set fRes2 to (font smoothing style)
    
–> «constant ****ˇˇˇˇ»
    
    
–set font smoothing style to automatic–automaticだけエラーになる
    
set font smoothing style to light
    
set font smoothing style to medium
    
set font smoothing style to standard
    
set font smoothing style to strong
  end tell
end tell

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

10/30 System Eventsでappearance情報を取得、変更する

Mac OS X 10.5になって、システム環境設定の設定内容をSystem Events経由で取得したり変更したりできるようになりました。それを実際に行うサンプルです。

ただ、探し回ってみてなかなか実例が見当たらず、首をひねっていたところ……取得はできるものの、設定変更については一筋縄では行かないことが分かりました。

しかも、階層化されたオブジェクトの中のプロパティの情報を書き換えるなんて、まっとうな方法でアプローチしているだけでは到達できようはずがありません。

そこで、「a reference to」でオブジェクト階層の奥にあるプロパティまで一気に参照して、値を書き換えるという大技を繰り出すことに。

これは、本当にAppleの開発者も動作確認を行っているのでしょうか? appearanceの変更などを行うと、えらく待たされたり切り替わらなかったりするのですが……

スクリプト名:System Eventsでappearance情報を取得、変更する
tell application “System Events”
  set aP to properties
  
set appP to appearance preferences of aP
  
set aPprop to properties of appP
  
  
–appearance preferencesのプロパティすべてを取得
  
  
–> {font smoothing style:«constant ****ˇˇˇˇ», font smoothing limit:6, recent servers limit:50, class:appearance preferences object, recent documents limit:50, recent applications limit:50, smooth scrolling:true, scroll arrow placement:together, highlight color:{46516, 54741, 65535}, font smoothing:true, scroll bar action:jump to next page, double click minimizes:true, appearance:blue}
  
  
–どうやっても情報にアクセスできなかったので、a reference toでアクセスしてみた
  
set ap2 to a reference to appearance preferences
  
tell ap2
    –情報の取得
    
set aRes to appearance
    
–> graphite もしくは blueが返る
    
    
–情報の変更
    
set appearance to blue –ブルー
    
set appearance to graphite –グラファイト
    
  end tell
end tell

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

06/16 機種IDを取得する

Macの機種IDを取得するAppleScriptです。

本AppleScriptを実行すると、いま使っているMacBook Pro Core 2 Duo 2.4GHz 17インチのマシンでは、「MacBookPro3,1」が返ってきます。

こうした機種IDと実際の製品名の一覧については、フリー・ソフトウェアの「MacTracker」に情報が掲載されているため、これを参照するのがよいでしょう。

mactrack1.jpg

スクリプト名:機種IDを取得する
set machineID to getMachineID() of me

機種IDを取得する
on getMachineID()
  set a to do shell script ioreg -c CPU -w 0 | head -n 2 | tail -n 1
  
  
set sPos to offset of < in a
  
if sPos = 0 then return “”
  
  
set spPos to offset of +-o in a
  
if spPos = 0 then return “”
  
  
set cpuText to text (spPos + 3) thru (sPos - 1) of a
  
return cpuText
end getMachineID

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

06/16 起動ディスクの空き容量が搭載メモリ+1Gバイトを切ったら警告

起動ディスクの空き容量が、搭載メモリ(Swap分?)+1Gバイトを切ったら警告するAppleScriptです。

大量の画像をコピーして編集/合成するとかムービーの合成をするといった場合、HDDの空き容量を一度確認しておく必要があります。HDDが湯水のように使える昨今では珍しくなりましたが、マシンによっては空き容量ギリギリで動いているものもあります。そうした状況を回避するため、事前にこうしたAppleScriptでチェックしておくとよいでしょう。

MacBook Airなどのマシンでは空き容量ギリギリで動いていることもあるかもしれないので、実行中のマシンの機種IDを取得して、MacBook AirであればHDD空き容量の制限をゆるくするとかいった処理を行ってみてもいいかもしれません。

スクリプト名:起動ディスクの空き容量が搭載メモリ+1Gバイトを切ったら警告
起動ディスクの空き容量が実装メモリ+1Gバイトを切ったら警告
set myRAM to physical memory of (system info) 搭載メモリを求める
set requireHDDspace to myRAM + 1024 メモリ実装分+1GB
set requreHDDspaceStr to (requireHDDspace as string) & 000000

set freRes to chkDiskSpace(requreHDDspaceStr) of me
if freRes = false then
  display dialog HDDの空き容量が足りません with title エラー buttons {”OK“} default button 1
  
return
end if

起動ディスクの空き容量をチェックする
on chkDiskSpace(aLimitStr)
  tell application Finder
    set a to free space of startup disk
  end tell
  
set numberString to Stringify(a) of me
  
  
この記法(considering numeric strings)はMac OS X 10.4以降でないと通じない
  
considering numeric strings
    if aLimitStr > numberString then
      return false
    else
      return true
    end if
  end considering
end chkDiskSpace

指数表示数値を文字列化
on Stringify(x) for E+ numbers
  set x to x as string
  
set {tids, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, {”E+“}}
  
if (count (text items of x)) = 1 then
    set AppleScript’s text item delimiters to {tids}
    
return x
  else
    set {n, z} to {text item 1 of x, (text item 2 of x) as integer}
    
set AppleScript’s text item delimiters to {tids}
    
set i to character 1 of n
    
set decSepChar to character 2 of n “.” or “,”
    
set d to text 3 thru -1 of n
    
set l to count d
    
if l > z then
      return (i & (text 1 thru z of d) & decSepChar & (text (z + 1) thru -1 of d))
    else
      repeat (z - l) times
        set d to d & 0
      end repeat
      
return (i & d)
    end if
  end if
end Stringify

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

04/23 Localeを取得する

現在実行中のユーザー環境の言語(Locale)を取得するAppleScriptです。

スクリプト名:Localeを取得する
set aLocale to getLocale() of me

Localeを取得する
on getLocale()
  set X to “”
  
try
    set X to system attribute LANG
    
if X = “” then set X to do shell script defaults read -g AppleLocale
  end try
  
if X = “” then set X to en
  
return X
end getLocale

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

03/11 USBに接続されたUSBメモリの情報を取得する

MLでUSBメモリのシリアル番号の調べ方について話が出ていたので、自分で納得できるレベルまで作り込んでみました。

USBに接続されたストレージの、シリアル番号、ベンダー(メーカー)ID、マウントポイント、名前、書き込み可/不可、bsd名称、空き容量、ファイルシステム種別、ドライブ総容量について返します。USB系ストレージが接続されていない場合にはカラのリストを返します。

usbmems.jpg

drives.jpg

ただ、すべてのUSBメモリの情報を抽出して動作確認したわけではありませんし、ましてSANYOのICレコーダー「Xacti」のように、USB端子につなぐと「Untitled」と「Untitled 1」の2つのボリウムがマウントされる仕様になっている製品に対してでも理想的なデータを返すといった保証はありませんので……ごく当たり前のUSBメモリの情報を抜き出す、というレベルです。

実戦投入するには、もうちょっといろいろといじめてみる必要性を感じます。

スクリプト名:USBに接続されたUSBメモリの情報を取得する
set tmpPath to POSIX path of (path to temporary items from system domain)
set aFileName to (do shell script /usr/bin/uuidgen“)
set outPath to tmpPath & aFileName & .plist
do shell script system_profiler -xml SPUSBDataType > & outPath

tell application System Events
  set vRec to value of property list file (outPath as string)
  
set v1Rec to _items of (first item of vRec)
  
  
set dList to {}
  
set sList to {}
  
repeat with i in v1Rec
    set hitF to false
    
try
      set j to _items of i
      
set hitF to true
    end try
    
    
if hitF = true then
      repeat with jj in j
        try
          set jjj to volumes of jj
          
set sNum to d_serial_num of jj
          
set vStr to b_vendor_id of jj
          
          
repeat with ii in jjj
            set the end of dList to {serialNum:sNum, venderName:vStr, dData:contents of ii}
          end repeat
        end try
      end repeat
    end if
  end repeat
end tell

dList

> {{serialNum:”7f12db856195ef”, venderName:”0×056e (Elecom Co., Ltd.)”, dData:{mount_point:”/Volumes/NO NAME”, _name:”NO NAME”, writable:”yes”, bsd_name:”disk2s1″, free_space:”3.75 GB”, file_system:”MS-DOS FAT32″, |size|:”3.77 GB”}}, {serialNum:”M004101800001″, venderName:”0×4146″, dData:{mount_point:”/Volumes/ぴよまる”, _name:”ぴよまる”, writable:”yes”, bsd_name:”disk1s9″, free_space:”56 MB”, file_system:”HFS+”, |size|:”123.1 MB”}}}

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

03/10 Safariのダウンロードフォルダを求めるv4

Mark J Reedとメールでやりとりしつつ、あーでもないこーでもない、と数日間チャット状態で相談していたところ「そうか、shell使いたくないんだったらこうじゃない?」と、Phillip AkerのScriptにちょっとだけ手を加えたものを採用ということに。

ただ……shellを多用するものも、キラリと光るテクニックが随所に使われており、もったいないので全部掲載しておこうと思った次第です。

スクリプト名:Safariのダウンロードフォルダを求めるv4

getSafariDownloadFolder() of me
> alias "Cherry:Users:maro:Documents:ダウンロード:"

By Phillip Aker, Mark J Reed
on getSafariDownloadFolder()
  set preferencesPath to POSIX path of (path to preferences)
  
set bundleId to bundle identifier of (info for (path to application "Safari"))
  
set safariPrefsFile to preferencesPath & bundleId & ".plist"
  
tell application "System Events" to set folderName to get value of property list item "DownloadsPath" of property list file safariPrefsFile
  
set downloadFolder to (POSIX file (do shell script "echo " & folderName)) as alias
  
return downloadFolder
end getSafariDownloadFolder

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

03/10 Safariのダウンロードフォルダを求めるv3

Mark J Reedによる、Shell使いまくりのルーチン。ちょっと手直ししてエラー対策などを行っています。

パスに日本語の文字が入っていたときにJava風エンコードされた文字が返ってきてしまうのですが、それを強制的にデコードする処理が入っており……これはなかなか便利だと思われます。

スクリプト名:Safariのダウンロードフォルダを求めるv3
set dFol to getSafariDownloadFolder() of me
> alias “Cherry:Users:maro:Documents:ダウンロード:”

By Mark J Reed
on getSafariDownloadFolder()
  try
    set folderName to do shell script defaults read com.apple.safari DownloadsPath
    
set dPOSIXpath to do shell script python -c ‘import os; print os.path.expanduser(u\” & folderName & \”.encode(\”utf-8\”))’
    
set downloadFolder to POSIX file dPOSIXpath as alias
  on error
    set downloadFolder to “”
  end try
  
return downloadFolder
end getSafariDownloadFolder

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

03/10 Safariのダウンロードフォルダを求めるv2

Shell Scriptを併用せずに、Safariのダウンロードフォルダを求めるPhillip AkerのAppleScriptです。

結局、最後に得られるパスがホームディレクトリからの相対パスのテキストだったので、それをMac OSのパスに直す(v4)のにshell scriptが必要になってしまうわけですが、極力AppleScriptネイティブの機能を使って書くとこうなるという見本でしょうか。

スクリプト名:Safariのダウンロードフォルダを求めるv2
By Phillip Aker
set pp to POSIX path of (path to preferences)
set bid to bundle identifier of (info for (path to application "Safari"))
set sp to pp & bid & ".plist"
tell application "System Events"
  set dldir to get value of property list item "DownloadsPath" of property list file sp
end tell
> "~/Documents/ダウンロード"

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

03/10 Safariのダウンロードフォルダを求めるv1

AppleScript Users ML上で盛り上がった「Safariで指定したダウンロードフォルダを求める」というScriptのスレッド。なんでそんなに盛り上がっているのか理解できなかったのですが、気付けば自分までどっぷり議論に入り込んで、あーでもないこーでもない、とやりとりしていました。

なるべくシンプルかつShell Scriptの力を借りないでAppleScriptだけでできるといいなぁ、などと考えて議論していましたが、やっぱりShellの力を借りつつトリッキーなワザの集大成に。

スクリプト名:Safariのダウンロードフォルダを求めるv1
By Luther Fuller, Mark J. Reed
set prefPath to path to preferences from user domain
tell application Finder to set prefsAlias to (file com.apple.Safari.plist of prefPath) as alias
tell application System Events
  set propPpath to POSIX path of prefsAlias
  
set prefsRec to (value of property list file propPpath)
  
set dlLoc to (|DownloadsPath| of prefsRec) > “~/Documents/ダウンロード”
  
set downloadFolder to (POSIX file (do shell script echo & dlLoc)) as alias
end tell

> alias “Cherry:Users:maro:Documents:ダウンロード:”

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

12/27 モニターの数を数えるv1

USのAppleScript StudioのMLで、「接続されているモニタ(ディスプレイ)の数を調べる方法について教えてほしい」という投稿があったので、5パターンぐらい提案したのですが、その中に入っていない例がよその人から提示され、AppleScript Studio環境で使うのでなければ割といい方法だったので、サブルーチンにまとめておきました。
(more…)

12/14 International Settingsの言語で第一優先になっているものを取得

システム環境設定の「言語環境」(International Settings)の「言語」で第一優先になっているものを取得します。
(more…)

10/12 ColorSync Scriptingで各種情報を取得

ColorSync関連の情報を取得するサンプルです。ここらへんの情報は、Mac系の開発者でも取得する方法を知っている人が少なくて……Cocoa系のMLでもColorSync系のMLでも答えが見つからなかった(質問もしてみたものの、誰も分らない)のですが、ふつーにAppleScriptを書いてみたらアッサリ求められた(脱力)ということがありました。

スクリプト名:ColorSync Scriptingで各種情報を取得
tell application ColorSyncScripting
  run
  
system profile location
  
> file “Cherry:Library:ColorSync:Profiles:Displays:Color LCD-4271840.icc”
  
  
default RGB profile location
  
> file “Cherry:System:Library:ColorSync:Profiles:Generic RGB Profile.icc”
  
  
default CMYK profile location
  
> file “Cherry:System:Library:ColorSync:Profiles:Generic CMYK Profile.icc”
  
  
default Lab profile location
  
> file “Cherry:System:Library:ColorSync:Profiles:Generic Lab Profile.icc”
  
  
default XYZ profile location
  
> file “Cherry:System:Library:ColorSync:Profiles:Generic XYZ Profile.icc”
  
  
default Gray profile location
  
> file “Cherry:System:Library:ColorSync:Profiles:Generic Gray Profile.icc”
  
  
system profile
  
> profile “カラー LCD”
  
  
default RGB profile
  
> profile “一般 RGB プロファイル”
  
  
default CMYK profile
  
> profile “一般 CMYK プロファイル”
  
  
default Lab profile
  
> profile “一般 Lab プロファイル”
  
  
default XYZ profile
  
> profile “一般 XYZ プロファイル”
  
  
default Gray profile
  
> profile “一般グレイプロファイル”
  
  
preferred CMM
  
> “appl”
  
  
profile folder
  
> file “Cherry:System:Library:ColorSync:Profiles:”
  
end tell

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

10/12 10.5で(登録してある)プリンタ名称の一覧を取得するv3

Mac OS X 10.5で、システムに登録してあるプリンタの一覧を取得し、さらにデフォルトプリンタとして登録してあるプリンタ名を取得。ダイアログでプリンタ名一覧を表示し、デフォルトプリンタを選択状態にしておきます。

ダイアログで選択されたプリンタ名を返すサブルーチンです。デフォルトプリンタの設定もルーチン内で行っています。

スクリプト名:10.5で(登録してある)プリンタ名称の一覧を取得するv3
set pRes to setDefaultPrinter() of me

マシンにエントリされているプリンタから1つを選択してデフォルトプリンタに設定する
設定したプリンタの名称を文字列で返す
on setDefaultPrinter()
  tell application Printer Setup Utility
    set curPr to name of current printer
    
set curPrList to {curPr}
    
set myList to name of every printer
    
tell me
      set aRes to (choose from list myList default items curPrList)
    end tell
    
if aRes = false then return
    
set newPrinterName to item 1 of aRes
    
set current printer to printer newPrinterName
  end tell
  
return newPrinterName
end setDefaultPrinter

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

10/12 10.5で(登録してある)プリンタ名称の一覧を取得するv1

Mac OS X 10.5で、システムに登録してあるプリンタの一覧を取得します。

スクリプト名:10.5で(登録してある)プリンタ名称の一覧を取得するv1
tell application Printer Setup Utility
  set myList to name of every printer
end tell

> {”DC4055P”, “PM-T960″, “PS-NX650_Print”}

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

08/16 MACアドレスを取得する(Mac OS X 10.5のバグ回避版)

EthernetのMACアドレスを取得して、コロンを外すのにシェルからの戻り値を分解するのに「word of〜」を使用していたのですが、Mac OS X 10.5になってからこのword ofの挙動が変わったためにバグレポートを書いたりAppleの担当とやりあっていました。

word ofは自然言語のテキストを単語分解するために使うものであって、shellの結果をパターン分解するためのものではないというのがApple側の主張。

しかし、日本語の単語分解なんかAppleScriptのword ofでできるわけではないし、やってみてもただ「文字種類の変わり目で適当に区切っているだけ」という、ナメた結果が返ってくるだけです。

Apple側の主張はともかく、従来のMac OS X 10.4までの挙動と変わってしまったので、これを回避するルーチンが、MLにいろいろ投稿されました。海外のScripter連中には、いつも世話になっています。

スクリプト名:MACアドレスを取得する(Mac OS X 10.5のバグ回避版)
Original By Philip Aker (Thanks!)
set myMacAdr to (words of (do shell script ifconfig en0 ether | grep ether | tr : ‘ ‘ | cut -d ‘ ‘ -f 2-“)) as string

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

07/18 GUI Scriptingのenable/disableを取得する

UI Element Scripting(GUI Scripting)が有効になっているかどうかを調べるAppleScriptです。UI Element Scriptingといえば、もうただ黙ってPrefab UI Browserを買えという話にしかならないのですが、このPrefab UI Browserが書き出すUI Scriptingの調査用コードというやつが、Mac OS X 10.5(日本語環境)ではそのままでは動かないことに気付きました。

そこで、エラーが出ないように、Mac OS X 10.4でも10.5でも動くように書き換えてサブルーチン化したのがこれです。

prefs.jpg

スクリプト名:GUI Scriptingのenableを取得する
retGUIScriptingEnabled() of me

GUI Scriptingの設定判定。10.4/10.5対応
on retGUIScriptingEnabled()
  set v2 to system attribute sys2 > 4, 5
  
  
Mac OS X 10.4以上なら実行
  
if v2 > 3 then
    tell application System Events
      set anUIe to UI elements enabled
    end tell
    
    
if anUIe = true then
      return true UI Element Scripting (GUI Scripting)がイネーブルならtrueを返す
    else
      beep
      
display dialog UI Element Scriptingが有効になっていません。 & return & return & 「システム環境設定」の「ユニバーサルアクセス」で、「補助装置を使用可能にする」のチェックボックスにチェックを入れてから再実行してください。 with icon stop
      
if button returned of result is OK then
        tell application System Preferences
          activate
          
set current pane to pane com.apple.preference.universalaccess
        end tell
        
return false
      end if
    end if
  end if
end retGUIScriptingEnabled

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

04/15 GUI Scriptingの確認

GUI Scripting(Apple的にはUI Element Scriptingなんだけど、長いので誰もそう呼ばない)のオン/オフ検出は、System Eventsに問い合わせると分ります。

スクリプト名:GUI Scriptingの確認
tell applicationSystem Events
  set aRes to UI elements enabled
end tell
> trueだとオン、falseだとオフ

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