Skip to content

Instantly share code, notes, and snippets.

@rbreaves
Last active January 28, 2020 04:00
Show Gist options
  • Save rbreaves/f15e46c7f14e40634cd76e2c66bb57c4 to your computer and use it in GitHub Desktop.
Save rbreaves/f15e46c7f14e40634cd76e2c66bb57c4 to your computer and use it in GitHub Desktop.
VirtualBox macOS keyswap for alt and cmd
#!/usr/bin/python
# Fixes the macOS keymap on the host to swap Alt & Cmd
# This allows for proper key location when using Virtual Machines under VirtualBox
# Support for Vmware and Parallels can easily be added via the app names
# Also Virtualbox does not detect the keyswap initially, so another app has to
# steal focus and then return focus to VirtualBox. Unknown if the same applies
# to the other VM solutions.
from AppKit import NSWorkspace
import os
from datetime import datetime
from time import sleep
vmkeyswap = '/usr/bin/hidutil property --set \'{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x7000000e7,"HIDKeyboardModifierMappingDst":0x7000000e6},{"HIDKeyboardModifierMappingSrc":0x7000000e6,"HIDKeyboardModifierMappingDst":0x7000000e7},{"HIDKeyboardModifierMappingSrc":0x7000000e3,"HIDKeyboardModifierMappingDst":0x7000000e2},{"HIDKeyboardModifierMappingSrc":0x7000000e2,"HIDKeyboardModifierMappingDst":0x7000000e3}]}\''
vmkeyswapUndo = '/usr/bin/hidutil property --set \'{"UserKeyMapping":[]}\''
actSI = '/usr/bin/osascript -e \'tell application "System Information" to activate\' -e \'delay 0.1\' -e \'tell application "System Information" to quit\' -e \'tell application "VirtualBox VM" to activate\''
last_active = None
autoswap = 0
while True:
active = NSWorkspace.sharedWorkspace().activeApplication()
if active:
if active['NSApplicationName'] != last_active:
prior_app = str(last_active)
last_active = active['NSApplicationName']
print active['NSApplicationName'] + ' ' + prior_app + ' ' + str(autoswap)
if prior_app == 'VirtualBox VM' and autoswap == 1:
# print 'autoswap ' + str(autoswap)
# print 'We will run the undo script here ' + active['NSApplicationName'] + ' ' + prior_app
os.system(vmkeyswapUndo)
autoswap = 0
if active['NSApplicationName'] == 'VirtualBox VM' and prior_app != 'System Information':
# print 'We will run the script here'
os.system(vmkeyswap)
os.system(actSI)
autoswap = 1
else:
if last_active:
print '%s: %s' % (
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'*** no active app ***'
)
last_active = None
sleep(0.05)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment