Enable/Disable Fn keys from the command line on the Mac - macos

I hardly ever use the function keys on my macbook pro. I mostly just use them for volume, brightness, etc. Now that I've started playing Starcraft 2 a bunch, I want to use them without having to press the fn key down.
I want to write a little shell script that will flip the "Use all F1, F2, etc keys as standard function keys" check box. I was thinking I could use the defaults command to change it but I wasn't sure what values to use. This way I don't have to change the the preferences every time I want to play. I can just run the script that'll switch the keys and even launch the game.
Any ideas?

An AppleScript that should do the trick -- taken from http://scriptbuilders.net/files/fn1.1.html, with slight modifications
--Check if GUI Scripting is Enabled
tell application "System Events"
if not UI elements enabled then
set UI elements enabled to true
end if
end tell
--Enable/Disable "Use all F1, F2, etc. keys as standard function keys" option in Keyboard & Mouse Preference pane and close System Preferences
tell application "System Events"
tell application "System Preferences"
reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"
end tell
click checkbox 1 of tab group 1 of window 1 of application process "System Preferences"
end tell
if application "System Preferences" is running then
tell application "System Preferences" to quit
end if
Tested on MacOS 10.6.4

The command is defaults write -g com.apple.keyboard.fnState, although I've had problems in the past changing it. I ended up just using an AppleScript. Give it a try.
defaults write -g com.apple.keyboard.fnState -boolean true
EditTo elaborate, the problems I've had is that the actual value is changed, but it doesn't actively change the setting in System Preferences nor does the fnState toggle, because the file is only read at boot/login etc. Also, making changes to a config file that's opened by another task sounds like a good way to corrupt the file.

You can install the awsome Karabiner-Elements.
Under System Preferences-> Keyboard preferences, make sure "Use all F1, F2, etc. keys as standard function keys" is checked as a perquisites.
Open KeyRemap4MacBook preferences.
Navigate to "Pass Through Mode" option.
Check the 'Change Fn+Escape to toggle "Pass Through Mode"'
Open "Change F1..F19 Key" and check the "Macbook Pro" or "Macbook Air" option choosing your correct mac type.

For anyone else trying to make this work - I've finally gotten my solution to work. Tested with: MacOS Big Sur, 11.4, June 2021.
The code is based here:
https://github.com/MrSimonC/Toggle-Mac-Function-Keys
but for brevity, here is the contents of the apple script file:
-- Apple Script (i.e. Use in Apple's Script Editor Application) to Toggle Function Keys / Media keys on/off
-- Tested on MacOS Big Sur (11.4) June 2021
-- Project Path: https://github.com/MrSimonC/Toggle-Mac-Function-Keys
tell application "System Preferences"
set current pane to pane "com.apple.preference.keyboard"
end tell
tell application "System Events"
if UI elements enabled then
tell application process "System Preferences"
repeat until exists tab group 1 of window "Keyboard"
delay 0.5
end repeat
click radio button "Keyboard" of tab group 1 of window "Keyboard"
click checkbox "Use F1, F2, etc. keys as standard function keys" of tab group 1 of window "Keyboard"
end tell
tell application "System Preferences" to quit
else
-- GUI scripting not enabled. Display an alert
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.security"
display dialog "UI element scripting is not enabled. Please activate this app under Privacy -> Accessibility so it can access the settings it needs."
end tell
end if
end tell
Hope someone finds it useful!

Related

Automatic Toggle Grayscale on Mac OS Ventura

i got the following problem: i try to toggle the color filter grayscale automatically when using certain websites (to limit the use of those ;)).
I tried several things, however I'm quite new to using Terminal, so that I basical have no clue what i'm doing wrong.
I found an explenation which did not work for me here (https://apple.stackexchange.com/questions/240446/how-to-enable-disable-grayscale-mode-in-accessibility-via-terminal-app?rq=1), however I'm not sure what I'm doing wrong.
I applied the following implementation:
I used the code below in MacOS Automator with the function "Run Apple Script". I gave the terminal as well as the automator the access to the accessibility features via the Security Settings. When using the script an error occures. It states (i had to translate it from Germany, thus the wording might be not 100% correct) „System Settings“ return an Erro: Error in the AppleEvent-Routine.
if running of application "System Preferences" then
try
tell application "System Preferences" to quit
on error
do shell script "killall 'System Preferences'"
end try
end if
repeat while running of application "System Preferences" is true
delay 0.01
end repeat
tell application "System Preferences" to reveal anchor "Seeing_Display" of ¬
pane id "com.apple.preference.universalaccess"
tell application "System Events" to tell process "System Preferences"
repeat until exists checkbox "Use grayscale" of group 1 of ¬
window "Accessibility"
delay 0.01
end repeat
click the checkbox "Use grayscale" of group 1 of window "Accessibility"
end tell
tell application "System Preferences" to quit
Thank you for helping me out.
Best
First, manually go to
system settings -> accessibility -> display
and set the "Filter type" to Greyscale (you only have to do this once).
Once you have done that, here are 2 shortcuts that do what you want:
option-command-F5
quick-press fingerprint key 3 times.

hide menu bar for full screen apps with applescript

This applescript code by user regulus6633 works great for toggling the "Automatically hide and show the menu bar on desktop" system preference in macOS 12.1:
tell application "System Events"
tell dock preferences to set autohide to not autohide
end tell
Does anyone know how to do the same for "Automatically hide and show the menu bar in full screen"?
The same is not applicable to the Menu Bar as with the mentioned Dock preference and as such you can use UI Scripting to achieve the goal.
The example AppleScript code, shown below, was tested in Script Editor under macOS Monterey 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.
Example AppleScript code:
-- # 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
-- # Open to Dock & Menu Bar
tell application "System Preferences" to ¬
reveal pane "com.apple.preference.dock"
-- Toggle the Automatically hide and show the menu bar in full screen checkbox.
tell application "System Events"
tell application process "System Preferences"
tell window 1
repeat until exists (first checkbox whose title is "Automatically hide and show the menu bar in full screen")
delay 0.2
end repeat
click (first checkbox whose title is "Automatically hide and show the menu bar in full screen")
end tell
end tell
end tell
delay 0.2
tell application "System Preferences" to quit

How to programatically switch between touchbar layouts on MacOS?

System
M1 MacBook Pro
MacOS Big Sur
Problem
I like the default Mac touchbar layout for everyday use, but I prefer the F1-F12 keys at my fingertips when programming. I also don't like holding down the fn key. That's why I wrote two AppleScripts to switch the layouts (included below).
The scripts work, but they are buggy. This is because they rely on opening the System Preferences app and navigating through the menus. I made a couple "apps" with Automator
that simply run the scripts and then assigned them to keyboard shortcuts.
This is an ok solution, but I'd like to do something more elegant. Ideally, my script should run behind the scenes and instantly change the touchbar layout instead of opening System Preferences, selecting items from drop-down-lists, and then finally closing System Preferences.
I messed around with the shell for quite awhile with no success before resorting to using Automator. Any suggestions from those who are more savvy with sort of thing?
Code
This one makes the F1-F12 keys the default touchbar layout:
tell application "System Preferences"
set the current pane to pane id "com.apple.preference.keyboard"
delay 0.25
reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"
end tell
tell application "System Events"
tell process "System Preferences"
click pop up button 2 of tab group 1 of window "Keyboard"
end tell
end tell
tell application "System Events"
tell process "System Preferences"
click menu item "F1, F2, etc. Keys" of menu 1 of pop up button 2 of tab group 1 of window "Keyboard"
end tell
end tell
tell application "System Events"
tell process "System Preferences"
click pop up button 4 of tab group 1 of window "Keyboard"
end tell
end tell
tell application "System Events"
tell process "System Preferences"
click menu item "Show App Controls" of menu 1 of pop up button 4 of tab group 1 of window "Keyboard"
end tell
end tell
quit application "System Preferences"
And this one does the reverse (makes app controls the default touchbar layout):
tell application "System Preferences"
set the current pane to pane id "com.apple.preference.keyboard"
delay 0.25
reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"
end tell
tell application "System Events"
tell process "System Preferences"
click pop up button 2 of tab group 1 of window "Keyboard"
end tell
end tell
tell application "System Events"
tell process "System Preferences"
click menu item "App Controls" of menu 1 of pop up button 2 of tab group 1 of window "Keyboard"
end tell
end tell
tell application "System Events"
tell process "System Preferences"
click pop up button 4 of tab group 1 of window "Keyboard"
end tell
end tell
tell application "System Events"
tell process "System Preferences"
click menu item "Show F1, F2, etc. Keys" of menu 1 of pop up button 4 of tab group 1 of window "Keyboard"
end tell
end tell
quit application "System Preferences"
On macOS Catalina when toggling the target setting it changes the value of the PresentationModeGlobal key in ~/Library/Preferences/com.apple.touchbar.agent.plist from appWithControlStrip to functionKeys or vise versa for those two choices. However, toggling it programmatically using the defaults command while it changes it in the UI it does not change it on the Touch Bar without also restarting the ControlStrip process.
The following example shell script code is what I use with a single keyboard shortcut to toggle between between Show App Controls and F1, F2, etc. Keys as that is what they are set to respectively in System Preferences > Keyboard > Keyboard on my system.
Example shell script code:
#!/bin/zsh
pmg="$(defaults read com.apple.touchbar.agent 'PresentationModeGlobal')"
if [[ $pmg == "appWithControlStrip" ]]; then
defaults write com.apple.touchbar.agent 'PresentationModeGlobal' 'functionKeys'
killall "ControlStrip"
else
defaults write com.apple.touchbar.agent 'PresentationModeGlobal' 'appWithControlStrip'
killall 'ControlStrip'
fi
Notes:
Other versions of macOS may require additional settings to be changed and or additional processes to be restarted, e.g., pkill 'Touch Bar agent' if applicable.
In Terminal you can use the read verb of the defaults command to examine changes to com.apple.touchbar.agent.plist as you make them in the UI to see if the value for additional keys needs to be changed too.
Side Note
As to your AppleScript code, here is how I'd do it based on your code as a single script to toggle between the two choices.
You didn't say what version of macOS are you running and since I do not have a pop up button 4 I cannot test the example AppleScript code shown below, however, this should eliminate having two separate scripts and it just toggles between the two with a single keyboard shortcut.
Example AppleScript code:
tell application "System Preferences"
set the current pane to pane id "com.apple.preference.keyboard"
delay 0.25
reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"
end tell
tell application "System Events"
tell tab group 1 of window 1 of process "System Preferences"
if value of pop up button 2 is "Show App Controls" then
click pop up button 2
click menu item "F1, F2, etc. Keys" of menu 1 of pop up button 2
click pop up button 4
click menu item "Show App Controls" of menu 1 of pop up button 4
else
click pop up button 2
click menu item "Show App Controls" of menu 1 of pop up button 2
click pop up button 4
click menu item "F1, F2, etc. Keys" of menu 1 of pop up button 4
end if
end tell
end tell
quit application "System Preferences"
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.

Using AppleScript to modify settings/system preferences

I am trying to make an AppleScript that toggles automatic rearranging of spaces. I am able to get the AppleScript to open system preferences and go into mission control settings, however i am not sure how to check the box which i want to change.
tell application "System Preferences"
activate
end tell
tell application "System Events"
tell process "System Preferences"
click menu item "Mission Control" of menu "View" of menu bar 1
delay 2
tell window "Mission Control"
//additional code goes here
end tell
end tell
end tell
Is there a way to see what the components of the window are so i know if i need to go into a table, or something else, before i am able to access the check boxes that toggle the settings
This is an alternative method using a shell command via AppleScript, which has the benefit of not requiring System Preferences to be open/running/visible. It's also much faster.
If you do happen to have it open in order to monitor whether the script below works, bear in mind that the GUI (what you see) is not updated until you close System Preferences, and open it up again.
To set Automatically rearrange Spaces based on most recent use to true (i.e. so the checkbox is ticked):
do shell script "defaults write com.apple.dock 'mru-spaces' -bool true; killall Dock"
To set it to false, i.e. untick the checkbox, change true to false in the line of code above.
To toggle the setting, this short script will achieve that:
set currentSetting to ¬
(do shell script ¬
"defaults read com.apple.dock 'mru-spaces'") ¬
as integer as boolean
do shell script ¬
"defaults write com.apple.dock 'mru-spaces' -bool " & ¬
(not currentSetting) & ¬
"; killall Dock"
Note: Tested with MacOS High Sierra, but should work (I believe) in OS X Mavericks and later.
Other Settings
When switching to an application, switch to a Space with open windows for the application
do shell script "defaults write -g AppleSpacesSwitchOnActivate -bool true"
(or false if you want the option off.)
Group windows by application
do shell script "defaults write com.apple.dock 'expose-group-apps' -bool true; killall Dock"
(or false if you want the option off.)
Let me start by saying while both of the other answers prior to this one do work, nonetheless I wouldn't use either one of them for the following reasons.
The answer presented by shadowsheep works however it needlessly exposes the System Preferences GUI and I believe unless your system is really slow the value of the delay command is excessive by 50% and only one should be necessary in this use case.
The answer presented by CJK works however it uses killall Dock which is visually distracting and causes all minimized windows on all Desktops to be unminimized leading to further visual distractions, and clutters the Desktop(s), which can then require the User to cleanup the mess. Even without other windows open it's still more so a visual distraction then what I'll present.
Now every User has different work habits so maybe none of the reasons mentioned are of any consequence to you. Personally, I work between four virtual Desktops and can have dozens of windows opened in numerous apps across the Desktops with many, if not most minimized at times. Using killall Dock for me is the last thing I want to do most of the time.
With that said, here's an alternative to both of the existing answers prior to this one.
It's probably safe to say that most Users don't open and leave open System Preferences however the following example AppleScript code checks to see if it's running and if so closes it. This is so it can be opened without showing the GUI, so as not to have to see the the visual distraction of have the GUI change as the script progresses.
This example AppleScript code simply toggles the state of the target checkbox:
if running of application "System Preferences" then
quit application "System Preferences"
delay 1
end if
tell application "System Preferences"
reveal pane id "com.apple.preference.expose"
delay 1
tell application "System Events"
tell group 2 of window 1 of application process "System Preferences"
click checkbox "Automatically rearrange Spaces based on most recent use"
end tell
end tell
quit
end tell
This example AppleScript code conditionally clicks the target checkbox using 0 or 1 in if value is equal to 0 then click it. Use 0 to only click it if it's not checked and 1 to only click it if it's checked.
if running of application "System Preferences" then
quit application "System Preferences"
delay 1
end if
tell application "System Preferences"
reveal pane id "com.apple.preference.expose"
delay 1
tell application "System Events"
tell group 2 of window 1 of application process "System Preferences"
tell checkbox "Automatically rearrange Spaces based on most recent use"
if value is equal to 0 then click it
end tell
end tell
end tell
quit
end tell
Both example AppleScript code blocks shown work fast and without seeing the System Preferences GUI and the only visual effect is the Dock Tile for System Preferences does a single bounce and may not even be noticeable, especially when compared to the visual distraction of killall Dock.
Note that the value of the delay commands may need to be adjusted for your system, and or additional delay commands may or may not be needed. Adjust values of and or add/remove the delay commands as appropriate.
Note: The example AppleScript code is just that and does not employ any other error handling then what's shown and is meant only to show one of many ways accomplish a task. The onus is always upon the User to add/use appropriate error handling as needed/wanted.
This should to what you want.
In this example Automatically rearrange Spaces based on most recent use is the checkbox you want to check.
tell application "System Preferences"
activate
delay 2
set the current pane to pane id "com.apple.preference.expose"
delay 2
tell application "System Events"
click checkbox "Automatically rearrange Spaces based on most recent use" of group 2 of window "Mission Control" of application process "System Preferences"
end tell
quit
end tell
And this if you wanna check it only if it's not checked:
tell application "System Preferences"
activate
delay 2
set the current pane to pane id "com.apple.preference.expose"
delay 2
tell application "System Events"
tell checkbox "Automatically rearrange Spaces based on most recent use" of group 2 of window "Mission Control" of application process "System Preferences"
if (get its value) = 0 then click it
end tell
end tell
quit
end tell
And if you wanna list all the UIElements in the window:
set myArray to {}
tell application "System Preferences"
activate
delay 2
set the current pane to pane id "com.apple.preference.expose"
delay 2
tell application "System Events"
tell window "Mission Control" of application process "System Preferences"
repeat with uiElem in entire contents as list
set myArray to myArray & ((class of uiElem as string) & " : " & name of uiElem as string)
end repeat
end tell
end tell
end tell

applescript - control click

How can I control click with AppleScript?
This script should work, but it doesn't
activate application "Finder"
tell application "System Events"
tell process "Finder"
key down control
delay 1
click at {600, 600} -- {from left, from top}
delay 1
key up control
end tell
end tell
MouseTools is sometimes unreliable. I know of cliclick — still haven't tried it.
I'd prefer an AS only workaround but welcome any suggestions.
Most of the actions from contextual menu you can do using menu bar (File, Edit, etc.). It can simplify your job.
To open contextual menu for particular GUI element you should tell to perform action
"AXShowMenu" to that element. You can use Accessibility Inspector application to find out the GUI elements hierarchy. Take a look at this discussion.
You can try mouse keys. Take a look at this thread for details. Note that "Mouse Keys" settings is in the "System Preferences" -> "Accessibility" -> "Mouse & Trackpad" in Mountain Lion.
For finder scripting AppleScript Finder Guide can be of much help.

Resources