ウィンドウを半分にするAppleScriptをAlfredから起動する

Alfredとは

俗に言うlauncher appです。アプリを起動するアプリで非常に便利です。Alfredは直感的でアプリやFinderでのファイル検索を大変楽にしてくれます。細かい使い方は公式をご参照下さい。

Alfredはアプリを検索するのでシェルスクリプトのファイル名を.shから.appに変更すると、シェルスクリプトも検索対象に含め更に実行することが出来ます。

$ mv half_half.sh half_half.app

ウィンドウ操作AppleScript

ウィンドウサイズ取得

まずはウィンドウサイズを取得するスクリプトを作成・実行して下さい。

tell application "System Events"
	set topProcess to item 1 of (every process whose frontmost is true)
	tell topProcess
		set topDocWindow to item 1 of (every window whose subrole is "AXStandardWindow")
		set bestSize to size of topDocWindow
	end tell
end tell
display dialog ((item 1 of bestSize) as text) & " x " & (item 2 of bestSize) as text

osascript window_size.scptと実行すると現在のウィンドウサイズが表示されると思います。このサイズを後述のスクリプトで使用します。

ウィンドウサイズ変更

下記はChromeブラウザを左半分に、iTerm2を右半分に配置するスクリプトです。3行目と7行目のサイズ指定部分の4つの数字はそれぞれ、「ウィンドウの左上が」{x座標始点, y座標始点, x座標終点, y座標終点}という意味を指します。

tell application "Google Chrome"
activate
set bounds of window 1 to {0, 0, 960, 1055}
end tell
tell application "iTerm2"
activate
set bounds of window 1 to {960, 0, 1920, 1055}
end tell

お分かりかと思いますが横幅を先程取得したウィンドウサイズの半分で、縦幅はそのまま指定しています。※このハードコーディング部分は改修予定です。

改修版

ウィンドウサイズ確認スクリプトとウィンドウサイズ変更部分を結合することで動的に配置することにしました。

(*Window Size*)
tell application "System Events"
	set topProcess to item 1 of (every process whose frontmost is true)
	tell topProcess
		set topDocWindow to item 1 of (every window whose subrole is "AXStandardWindow")
		set bestSize to size of topDocWindow
	end tell
end tell

(*Window Move*)
tell application "Google Chrome"
activate
set bounds of window 1 to {0, 0, (item 1 of bestSize) / 2, (item 2 of bestSize)}
end tell
tell application "iTerm2"
activate
set bounds of window 1 to {(item 1 of bestSize) / 2, 0, (item 1 of bestSize), (item 2 of bestSize)}
end tell

AppleScriptを実行するシェルスクリプト

作成したAppleScriptを実行するためのシェルスクリプトを作成します。最初に述べた通りファイル名は.appとしています。

#!/bin/zsh
osascript half_half.scpt

シェルスクリプトを作成したら実行権限を付与します。

$ chmod +x half_half.app

以上です。Alfredで検索し実行してみて下さい。

終わりに

ブラウザを開きながらコーディングする時などにサッとウィンドウを移動したいと思いこのスクリプトを作成しました。

また最近GhostTextという自前のエディタでブラウザのフォーム入力が出来るというChrome拡張機能の存在を知り、一層この自動化スクリプトのメリットが増すことと思います。ちょっとした文章入力だと仰々しいと感じるかもしれませんが、構造的な文章になればなるほどの入力は使い慣れたエディタの方が心地いいです。

ついでにもとに戻すスクリプトも

(*Window Size*)
tell application "System Events"
	set topProcess to item 1 of (every process whose frontmost is true)
	tell topProcess
		set topDocWindow to item 1 of (every window whose subrole is "AXStandardWindow")
		set bestSize to size of topDocWindow
	end tell
end tell

(*Window Move*)
tell application "Google Chrome"
activate
set bounds of window 1 to {0, 0, (item 1 of bestSize) * 2, (item 2 of bestSize)}
end tell
tell application "iTerm2"
activate
set bounds of window 1 to {0, 0, (item 1 of bestSize) * 2, (item 2 of bestSize)}
end tell

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA