Safariのテキストエンコーディングを循環的に切り替えるサービスメニュー

最近Safariを使ってて文字化けにあうことが多くなった気がする。
テキストエンコーディングの自動判別がどうも切れているみたい。
旧・Macの手書き説明書 - FC2 BLOG パスワード認証
ここに書いてあるようにdefaultを書き換えてみたりもしたけど効果がよくわからなかった。

基本的に文字化けで困るのは日本語のときだから、
前まではSystem Preferences/Keyboard/Keyboard Shortcutsに
それぞれのエンコーディングに切り替える専用のショートカットを登録してた。

でもいざ文字化けに合うと正しい文字コードがどれかなんてよくわからないことが多い上に、自分で登録したショートカットは覚えられないしで結局メニューバーから自分で選んだりしていた。何にしても面倒だった。
これは一つのショートカットでいろんなエンコーディングを切り替えてくれるようなメニューがあれば解決する。
という訳で、Safariで使えるServiceメニューをAutomator+Applescriptで作った。
Safari/Servicesにこんな感じのメニューが追加される。

作り方

1. Applications/Automatorを開いてdocument type で歯車マークのServiceを選ぶ。
2. Service receives "no input" in "Safari.app"に設定する。
3. Actions/Utilities/Run Applescriptを右側の編集ボックスにドラッグアンドドロップする。
4. (* Your script goes here *)のところを下のようなコードで置き換える。

tell application "System Events"
	tell process "Safari"
		tell menu bar 1
			tell menu bar item "View"
				tell menu "View"
					tell menu item "Text Encoding"
						tell menu "Text Encoding"
							if (value of attribute "AXMenuItemMarkChar" of menu item "Default" as string) is "✓" then
								click menu item "Unicode (UTF-8)"
							else if (value of attribute "AXMenuItemMarkChar" of menu item "Unicode (UTF-8)" as string) is "✓" then
								click menu item "Japanese (Shift JIS)"
							else if (value of attribute "AXMenuItemMarkChar" of menu item "Japanese (Shift JIS)" as string) is "✓" then
								click menu item "Japanese (ISO 2022-JP)"
							else if (value of attribute "AXMenuItemMarkChar" of menu item "Japanese (ISO 2022-JP)" as string) is "✓" then
								click menu item "Japanese (EUC)"
							else if (value of attribute "AXMenuItemMarkChar" of menu item "Japanese (EUC)" as string) is "✓" then
								click menu item "Japanese (Shift JIS X0213)"
							else
								click menu item "Default"
							end if
						end tell
					end tell
				end tell
			end tell
		end tell
	end tell
end tell


5. 名前を付けて保存する(~/Library/Servicesに保存される)。
6. System Preferences/Keyboard/Keyboard Shortcutsで作ったサービスメニューにショートカットを割り当てる。

ちなみに、Accessibility/Enable access for assistive devicesのチェックボックスをオンにしないとうまく動かない。

これでショートカット一つで文字コードを循環的に切り替えてくれるようなサービスメニューが出来上がる。

動作は、Text Encodingで"Default"が選ばれてたら"Unicode (UTF-8)"にする。
"Unicode (UTF-8)"が選ばれてたら"Japanese (Shift JIS)"にする。
...
みたいな感じでエンコーディングを循環的に変えるという感じにした。


AppleScriptを書くのは初めてだったのでここらへんがとても参考になった。
3/3 AppleScriptの構造を上手に調べる [Mac OSの使い方] All About
macos - How to tell if a menu item is 'checked'? - Stack Overflow

AppleScriptシンタックスハイライトってどうやるんだろう?