IF statement based on condition of mouse keys - applescript

I want to be able to check the state of Mouse Keys via Applescript, so that the script can spam the 5 key (which will trigger left mouse clicks) ONLY if sticky keys is on. This will allow the script to be turned off using the shortcut to turn off sticky keys (pressing the option key 5 times).
My code so far:
on idle
tell application "System Preferences"
activate
set current pane to pane id "com.apple.preference.universalaccess"
end tell
tell application "System Events"
tell process "System Preferences"
click menu item 6 of menu 1 --pseudocode
if value of checkbox "Enable Mouse Keys" is 1 then
key code 87 --press the "5" key, triggers mouse press
end if
end tell
end tell
set rn to (random number from 0.8 to 1.0) as text
return rn
end idle
My problem is with the line click menu item 6 of menu 1 and how to access the "Mouse & Keyboard" section of the Accessibility pane. If it wasn't already obvious, I have very little experience with applescript. >_>

You can avoid having to open the prefpane. By directly reading the value from the Universal Access preference file
set plistFile to (path to preferences from user domain) & "com.apple.universalaccess.plist" as string -- Get the Universal Access plist path of this use
tell application "System Events" to set mouseDriver to value of property list item "mouseDriver" of contents of property list file plistFile -- read only the value for mouse keys
This will return true or false depending if it is on or not.
One caveat with reading the plist directly is any changes done in the User interface may take about 5 seconds more or less to be written to the file.
You can read here more about property list items

Update to #markhunte post above for OS 10.14 Mojave (might work on earlier versions too):
set plistFile to (path to preferences from user domain) & "com.apple.universalaccess.plist" as string -- Get the Universal Access plist path of this use
tell application "System Events" to set mouseDriver to value of property list item "stickyKey" of contents of property list file plistFile -- read only the value for mouse keys
plist item name "mouseDriver" changed to "SickyKey"

Related

Getting AppleScript to click button "+" and select "Language" and click Add

I am trying to automate via AppleScript the addition and the selection of a specific language in macOS Big Sur (for example Spanish) from System Preferences > Language & Region.
I can display the UI via this code, but I cannot get the "+" button to click.
tell application "System Preferences"
reveal anchor "Language" of pane id "com.apple.Localization"
activate
tell application "System Events"
tell window 1 of application process "System Preferences"
set i to 0
repeat until exists button 1 of group 1
delay 0.1
set i to i + 1
if i ≥ 30 then return
end repeat
-- # Click the [+] button.
click button 1 of group 1
end tell
end tell
end tell
The example AppleScript code, shown below, was tested in Script Editor under macOS Big Sur with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
The value of the property thisLanguage needs to be set to that which will show in the list of the Select a preferred language to add: sheet, as it is set to the value of the text box on the Select a preferred language to add: sheet. This is necessary so AppleScript does not have to spend a lot of time searching the entire list as the target should now be it the top portion of the list.
Note that for, e.g., Español this script as is, is all that was necessary, however, on some languages one may get an additional sheet to reply to. For example, with 简体中文 (Simplified Chinese) one gets an additional Select input sources to add: sheet, and you will need to add additional code to handle it. You should be able to, from the example AppleScript code shown below, figure out how to deal with it as there is already an example therein.
Example AppleScript code:
property thisLanguage : "Español"
-- # Check to see if System Preferences is
-- # running and if yes, then close it.
-- #
-- # This is done so the script will not fail
-- # if it is running and a modal sheet is
-- # showing, hence the use of 'killall'
-- # as 'quit' fails when done so, if it is.
-- #
-- # This is also done to allow default behaviors
-- # to be predictable from a clean occurrence.
if running of application "System Preferences" then
try
tell application "System Preferences" to quit
on error
do shell script "killall 'System Preferences'"
end try
delay 0.1
end if
-- # Make sure System Preferences is not running before
-- # opening it again. Otherwise there can be an issue
-- # when trying to reopen it while it's actually closing.
repeat while running of application "System Preferences" is true
delay 0.1
end repeat
-- # Reveal the General tab of the Language
-- # & Region pane in System Preferences.
tell application "System Preferences"
reveal anchor "Language" of ¬
pane id "com.apple.Localization"
activate
end tell
-- # System Events handles the rest.
tell application "System Events"
launch
delay 0.2
tell application process "System Preferences"
-- # Click the [+] button.
click button 1 of group 2 of tab group 1 of window 1
-- # Wait for sheet 1 to be available.
set i to 0
repeat until exists text field 1 of sheet 1 of window 1
delay 0.1
set i to i + 1
if i ≥ 30 then return
end repeat
-- # Search for: thisLanguage
set the value of ¬
text field 1 of ¬
sheet 1 of ¬
window 1 to ¬
thisLanguage
delay 1 -- # May need to be increased.
-- # Get the row that matches thisLanguage.
set theTargetRow to ¬
the first row of ¬
table 1 of ¬
scroll area 1 of ¬
sheet 1 of ¬
window 1 whose value of ¬
static text 1 of ¬
UI element 1 is thisLanguage
-- # Select the row that matches thisLanguage.
select theTargetRow
-- # Click the Add button.
click button 3 of sheet 1 of window 1
-- # Wait for the sheet to change.
set i to 0
repeat until exists ¬
button "Use English (US)" of ¬
sheet 1 of window 1
delay 0.1
set i to i + 1
if i ≥ 30 then return
end repeat
-- # The button for thisLanguage
-- # should have focus, press enter.
keystroke return
end tell
end tell
delay 0.2
tell application "System Preferences" to quit
Notes:
The use of the launch command after tell application "System Events" is to try and help with a systemic issues in UI Scripting as a result of changes Apple had made in macOS Big Sur.
Also note that UI Scripting is often kludgy and prone to failure for a variety of reasons and why I have used the error handling that I have, however, one may need to add addition error handling and or delay commands and or adjust the value of existing ones, as needed.
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

How to "Wait until web page loaded" in Firefox (applescript)?

This code from here works perfect, but doesn't work in Firefox. Why and how to fix it in applescript?
tell application "Google Chrome"
repeat until (loading of tab 1 of window 1 is false)
1 + 1 --just an arbitary line
end repeat
loading of tab 1 of window 1 --this just returns final status
end tell
As Firefox does not contain a specific AppleScript dictionary, e.g. Firefox.sdef file, it is not considered to be AppleScript scriptable in the same way as e.g. Google Chrome, and while it will respond to some of the basic commands, such as activate, quit, etc., it will require UI Scripting to do what you are asking.
The following example AppleScript code requires Firefox version 87 or newer, and setting its accessibility.force_disabled preference to: -1
First, in Firefox, in the Address/Search combo box, type about:config and press enter.
If applicable, click the Accept the Risk and Continue button.
In the Search preference name text box, type accessibility.force_disabled and press enter.
Click the Edit button and change its value to: -1
Click the the Save button.
Here is an example of how I would instruct Firefox to open a new window to a given URL and wait for the page to finish loading.
Example AppleScript code:
set theURL to "https://news.google.com/"
tell application "Firefox" to activate
delay 0.5 -- # Value may need to be adjusted if Firefox is closed.
my clickApplicationMenuCommand("Firefox", "File", "New Window")
delay 0.5
my setURLofFirefoxFrontWindowTo(theURL)
my waitForFirefoxPageToFinishLoading()
say "foobar"
-- # Handler(s) #
to clickApplicationMenuCommand(appName, appMenuName, appMenuCommand)
tell application appName to activate
delay 0.25
tell application "System Events" to ¬
click ¬
menu item appMenuCommand of ¬
menu appMenuName of ¬
menu bar item appMenuName of ¬
menu bar 1 of ¬
application process appName
end clickApplicationMenuCommand
to setURLofFirefoxFrontWindowTo(theURL)
tell application "System Events"
tell application process "Firefox"
set the value of UI element 1 of ¬
combo box 1 of toolbar "Navigation" of ¬
first group of front window to theURL
key code 36 -- # enter key
end tell
end tell
end setURLofFirefoxFrontWindowTo
to waitForFirefoxPageToFinishLoading()
-- # Requires Firefox version 87 or newer.
-- # Requires accessibility.force_disabled set to: -1
tell application "System Events"
tell application process "Firefox"
repeat until exists UI element "Reload" of ¬
toolbar "Navigation" of group 1 of window 1
delay 0.1
end repeat
repeat while (name of UI elements of ¬
toolbar "Navigation" of group 1 of ¬
window 1 whose description is "Reload") ¬
is not {"Reload"}
delay 0.1
end repeat
end tell
end tell
end waitForFirefoxPageToFinishLoading
Notes:
The example AppleScript code, shown above, was tested in Script Editor under macOS Catalina with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
Tested using Firefox version 91.0 (64-bit).
Note that UI Scripting is very kludgy and is prone to failure, especially as the version of the OS and or application change, or the value of the delay commands are not sufficient. That said however, with Firefox, this as described herein is what it takes.
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Applescript System Preferences automation

I'm working on automating setting system preferences, but I have a problem. This code should select Wi-Fi tab but scroll area 1 does not exist unless I click any element that belongs to scroll area manually. I tried emulating click with many external programs but even then I can't access scroll area
tell application "System Preferences"
activate
reveal pane id "com.apple.preference.dock"
end tell
tell application "System Events" to tell application process "System Preferences"
delay 1
tell scroll area 1 of window 1
select row 3 of outline 1
end tell
end tell
Is there any other way to change Dock & Menu Bar settings or just to access scroll area items?
Edit: The end goal is to hide Wi-Fi icon from menu bar.
The end goal is to hide Wi-Fi icon from menu bar.
UI Scripting of System Preferences in macOS Big Sur has become a nightmare, as many of the methods that used to work in previous versions of macOS just no longer do in macOS Big Sur. Many UI elements report Parent does not report element as one of its children when using Accessibility Inspector of Xcode, which then make it impossible to communicate with them. Or some code may work one time and then not the next. I wrote some code that opened to Wi-Fi and clicked the Show in Menu Bar checkbox. It worked a few times and now it doesn't.
The original code I wrote which sporadically worked I'll not post, however, the following example AppleScript code does consistently work as tested under macOS Big Sur 11.4, albeit it is what I consider kludgy UI Scripting, as it's visible on screen, is prone to failure due to timing issues, or if the hierarchical UI element structures change due to macOS updates/upgrades.
The example AppleScript code, shown below, was tested in Script Editor under macOS Big Sur 11.4 with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate setting in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
This script requires that the Use keyboard navigation to move focus between controls checkbox is checked on the System Preferences > Keyboard > Shortcuts tab, and as coded, the script checks its status and toggles the checkbox, as necessary, based on its current status.
This script also first checks to see if the Wi-Fi icon is shown on the Menu Bar and if not, then halt execution of the script, as its purpose is to act only if it is shown on the Menu Bar.
Example AppleScript code:
-- # Get the fully qualified POSIX pathname of the target .plist file.
set thePropertyListFilePath to ¬
the POSIX path of ¬
(path to preferences from user domain as string) & ¬
"com.apple.controlcenter.plist"
-- Get the value of 'NSStatusItem Visible WiFi' to determine if the
-- Wi-Fi icon is showing on the Menu Bar, and if it's not, then halt
-- execution of the script, as its purpose is to act only if it is.
tell application "System Events" to ¬
tell the property list file thePropertyListFilePath to ¬
set |Wi-Fi Menu Bar Icon Status| to the value of ¬
the property list item ¬
"NSStatusItem Visible WiFi"
if |Wi-Fi Menu Bar Icon Status| is false then return
-- # Check to see if System Preferences is
-- # running and if yes, then close it.
-- #
-- # This is done so the script will not fail
-- # if it is running and a modal sheet is
-- # showing, hence the use of 'killall'
-- # as 'quit' fails when done so, if it is.
-- #
-- # This is also done to allow default behaviors
-- # to be predictable from a clean occurrence.
if running of application "System Preferences" then
try
tell application "System Preferences" to quit
on error
do shell script "killall 'System Preferences'"
end try
delay 0.1
end if
-- # Make sure System Preferences is not running before
-- # opening it again. Otherwise there can be an issue
-- # when trying to reopen it while it's actually closing.
repeat while running of application "System Preferences" is true
delay 0.1
end repeat
-- # Get the fully qualified POSIX pathname of the target .plist file.
set thePropertyListFilePath to ¬
the POSIX path of ¬
(path to preferences from user domain as string) & ¬
".GlobalPreferences.plist"
-- # Get the value of AppleKeyboardUIMode to determine if the
-- # 'Use keyboard navigation to move focus between controls'
-- # checkbox is checked on the System Preferences >
-- # Keyboard > Shortcuts tab.
tell application "System Events" to ¬
tell the property list file thePropertyListFilePath to ¬
set keyboardNavigation to the value of ¬
the property list item "AppleKeyboardUIMode"
if keyboardNavigation = 0 then
-- # Check the checkbox.
my toggleKeyboardNavagition()
end if
-- # Open System Preferences to the Dock & Menu Bar pane.
-- #
-- # This UI Script needs it to be visible, hence the activate command.
tell application "System Preferences"
activate
reveal pane id "com.apple.preference.dock"
end tell
tell application "System Events"
set i to 0
repeat until exists window "Dock & Menu Bar" of ¬
application process "System Preferences"
delay 0.1
set i to i + 1
if i ≥ 30 then return
end repeat
end tell
-- # Tab to the 'Show in Menu Bar' checkbox and uncheck it.
tell application "System Events"
key code 48 -- # tab key
delay 0.2
key code 125 -- # down arrow key
delay 0.2
key code 48 -- # tab key
delay 0.2
key code 49 -- # spacebar
delay 0.1
end tell
if keyboardNavigation = 0 then
-- # Uncheck the checkbox if it
-- # was previously unchecked.
my toggleKeyboardNavagition()
end if
delay 0.2
tell application "System Preferences" to quit
-- # Handler(s) #
-- # Toggles checkbox: 'Use keyboard navigation
-- # to move focus between controls'
on toggleKeyboardNavagition()
tell application "System Preferences"
activate
reveal anchor "shortcutsTab" of ¬
pane id "com.apple.preference.keyboard"
end tell
tell application "System Events"
tell front window of ¬
application process "System Preferences"
set i to 0
repeat until (exists checkbox 1 of tab group 1)
delay 0.1
set i to i + 1
if i ≥ 30 then return
end repeat
click checkbox 1 of tab group 1
end tell
end tell
end toggleKeyboardNavagition
Notes:
If the normal state of the Use keyboard navigation to move focus between controls checkbox is unchecked, then do not run the script immediately back to back as it takes a second or two for the value of the property list item "AppleKeyboardUIMode" in the users global preferences file to update the change. I'm mentioning this mainly for when doing testing more so than when in normal production use, as it shouldn't be an issue then.
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

How do I refer to an object in a window whose Accessibility Inspector description is "<empty description> (group) [NSBox]" in Applescript?

I am trying to interact with iTunes "Export Library.." dialog.
I tried "set choices to every menu item of menu 1 of pop up button 1 of group 1 of window winName" but it says "group 1" is an invalid index?
Here's the relevant code: (the call parameters are: "iMac-8GB", "iTunes", "iTunes", false"
on handleDir(dir, winName, appName, createIt)
local foundIt, ndx
set foundIt to false
if winName is not "" then
tell application "System Events" to tell process "iTunes"
set choices to every menu item of menu 1 of pop up button 1 of group 1 of window winName
You want to use the menu "Export Library…" from iTunes :
The first step is to select the relevant menu. In my iTunes version (12.5.5.5) the menu is in "File" menu, sub menu item "Library" and then sub Menu "Export Library…".
The second step is to fill the export file name and set the destination folder. The Mac "Save as…" window has many shortcuts, valid for all applications. Among others, command G allows to define the complete path to save the file. This path must be in Unix format (with "/" and not ":" for sub levels).
The bellow script does the complete Export Library function. The first 2 rows define the name of the file to save and the path where to save it. Adjust them to your needs.
set myTitle to "test" -- name of the exported file
set myPath to "/Users/myuser/Desktop/Test_folder" -- destination folder for export file
tell application "iTunes" to activate -- make iTunes front
tell application "System Events"
tell process "iTunes"
click menu 3 of menu bar 1 -- open the File menu
click menu item 12 of menu 3 of menu bar 1 -- select the Library menu item
delay 0.1
click menu item 5 of menu 1 of menu item 12 of menu 3 of menu bar 1 -- select the export library… item
delay 0.1
keystroke myTitle -- fill the export file name in the save as… dialog
keystroke "G" using command down -- shortcut to open Go-to folder window
keystroke myPath
keystroke return -- to close the go-to window
delay 0.1
keystroke return -- to close the export window
end tell -- process iTunes
end tell -- system Events
I added several delays to make sure your Mac has enough time to open or close windows.
Using this code, modified to specifically target iTunes':
tell application "System Events"
tell front window of (first application process whose frontmost is true)
set uiElems to entire contents
end tell
end tell
which came from an answer to Use AppleScript to list the names of all UI elements in a window (GUI scripting)
I discovered that a NSBox is referred to as an "outline" by Applescript.

Selecting Pop Up Menu Buttons in AppleScript

I want to automate clicking a specific pop down menu's item.
For Example, I want to change the Value of "Message receive Sound" to something else. How can I do this with AppleScript? And how can I do this with other pop down menus in AppleScript?
(To open the iMessage Settings menu, shown in the image, type CMD COMMA, once you open iMessage)
Note: I have successfully done this Automator, I just want to do it in applescript.
It's called GUI scripting. You have to identify the reference to the UI element(s).
GUI scripting strongly depends on the system version. If an update changes the UI structure the script will brake.
This selects the sound "Popcorn" in the sound popup menu. It's for El Capitan. In systems < 10.11 the UI elements may be different and the process name might be "iChat"
tell application "System Events"
tell process "Messages"
set frontmost to true
if not (exists (1st window whose value of attribute "AXIdentifier" is "MessagesPreferencesWindow")) then
keystroke "," using command down
repeat until exists (1st window whose value of attribute "AXIdentifier" is "MessagesPreferencesWindow")
delay 0.1
end repeat
end if
tell (1st window whose value of attribute "AXIdentifier" is "MessagesPreferencesWindow")
tell pop up button 4 of group 1
click
delay 0.2
click menu item "Popcorn" of menu 1
end tell
end tell
end tell
end tell

Resources