はじめに
Macユーザのみなさま,AppleScript使っていらっしゃいますでしょうか?XcodeでSwiftやObjective-Cを使って普通にアプリを作って色々やるぞっと奮起してもSandBoxの壁に悩まされたりして,思いついたアイデアを実現できないことありますよね!そんなときに活躍するのがAppleScriptです!権限やセキュリティなんか知ったことか!となんでもござれな無法地帯の世界に足を踏み入れることができて最高です!
今回は,別件でデスクトップ上のアイコンの座標を把握する必要に迫られ,AppleScriptならばそれが容易に可能だと判明したことから,AppleScriptの勉強としてフォルダと鬼ごっこができるクソアプリを作ってみました.
フォルダと鬼ごっこ
広大なデスクトップの敷地を舞台として,Don't touch me!
と題された恥ずかしがり屋なフォルダを追いかけましょう!制限時間は10秒間!鬼のあなたがフォルダを開ければ勝利です!
遊び方
MacにプリインストールされているScript Editorを起動して,以下のソースを貼り付け,実行すれば鬼ごっこ開始!
use scripting additions
use framework "Foundation"
tell application "Finder"
tell icon view options of window of desktop
set iconSize to icon size
set textSize to text size
end tell
set folderName to "Don't touch me!"
if not (exists folder folderName) then
make new folder at desktop with properties {name:folderName}
end if
set aim to folder folderName of desktop
set desktopBounds to bounds of window of desktop
set desktopWidth to item 3 of desktopBounds
set desktopHeight to item 4 of desktopBounds
set minDistance to 100
set r to (0.6 * iconSize)
repeat 100 times
set aimPos to desktop position of aim
set aimX to item 1 of aimPos
set aimY to item 2 of aimPos
set mousePos to current application's class "NSEvent"'s mouseLocation()
set mouseX to x of mousePos
set mouseY to desktopHeight - (y of mousePos)
set distance to len(mouseX, aimX, mouseY, aimY) of me
set vectorX to (aimX - mouseX) / distance
set vectorY to (aimY - mouseY) / distance
repeat while (distance is less than minDistance)
set aimX_ to min(desktopWidth - r, max(r, (aimX + vectorX)) of me) of me
set aimY_ to min(desktopHeight - r, max(r, (aimY + vectorY)) of me) of me
if (aimX = aimX_) and (aimY = aimY_) then
set aimX to mouseX - ((minDistance + 1) * vectorX)
set aimY to mouseY - ((minDistance + 1) * vectorY)
else
set aimX to aimX_
set aimY to aimY_
end if
set distance to len(mouseX, aimX, mouseY, aimY) of me
end repeat
set desktop position of aim to {aimX, aimY}
delay 0.05
end repeat
end tell
on min(x, y)
if x ≤ y then
return x
else
return y
end if
end min
on max(x, y)
if x > y then
return x
else
return y
end if
end max
on len(x0, x1, y0, y1)
return ((x1 - x0) ^ 2 + (y1 - y0) ^ 2) ^ 0.5
end len
仕様
フォルダを開くことができたら勝利!とは書きましたが,画面の角に追い詰めても,ワープして逃げるので勝利することはできません(笑
感想
AppleScriptはかなり独特な書き方をしますが,できることの幅が非常に広がるので,使える手段の1つにしておくといいかもしれません.