AppleScript
AppleScriptでポップアップメニューのアイテムをリスト化して繰り返し処理する方法

はじめに

今回は、ポップアップメニューのアイテムをリスト化して繰り返し処理する方法

一般的には使い所がなさそうだけれども・・・

アプリケーションの動作チェックで、ポップアップの項目を一つずつ処理させたかった。とは言え、何十もの項目を書くのはばかばかしいので、ポップアップボタンのメニューをリストとして保存して、それを繰り返し処理させることで対応させた。

ブログ用に、環境設定で処理

と言うことで、ブログ用に環境設定の"一般"で強調表示色の項目を取得して、一件ずつクリックして変えていく処理を作成してみた。


tell application "System Preferences"
	activate
end tell

tell application "System Events"
	tell application "System Events"
		tell process "System Preferences"
			tell window 1
				click button "すべてを表示" of group 1 of group 2 of toolbar 1
				delay 1
				tell scroll area 1
					click button "一般"
				end tell
			end tell
			delay 3
			tell window 1
				click pop up button "強調表示色:"
				tell menu 1 of pop up button "強調表示色:"
					set scroll_List to name of every UI element
					click menu item 1
				end tell
				repeat with curItem in scroll_List
					click pop up button "強調表示色:"
					delay 1
					set select_color to curItem as string
					click menu item select_color of menu 1 of pop up button "強調表示色:"
				end repeat
			end tell
		end tell
	end tell
end tell




SierraとCatalinaでも動作を確認した。コアとなる部分は、二つ


click pop up button "強調表示色:"
	tell menu 1 of pop up button "強調表示色:"
		set scroll_List to name of every UI element
		click menu item 1
	end tell

次にrepeat処理。Applescriptでよくやる方法。変数 in リスト で行う。これでリストの最初から最後まで処理を行える。その時の値は、curItemで取り出すことができる。アプリにもよるみたいで、環境設定ではする必要がないのだけれども、キャストしないと失敗するときがあったので、set select_color to curItem as string で一回キャストしている。クリック動作させるときにさせても駄目なときがあったのでこれが一番っぽい


repeat with curItem in scroll_List
	click pop up button "強調表示色:"
	delay 1
	set select_color to curItem as string
	click menu item select_color of menu 1 of pop up button "強調表示色:"
end repeat


あと、リストの値に "missing value" が入る場合があって、その場合スクリプトが失敗して止まる事があった。もしそのようなことになる場合は、条件式を追加して、"missing value"の時は処理をスキップさせるのがいい。