Skip to content

Instantly share code, notes, and snippets.

@arubdesu
Created January 12, 2021 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arubdesu/d0f68e30b794990d47404852e1d69e41 to your computer and use it in GitHub Desktop.
Save arubdesu/d0f68e30b794990d47404852e1d69e41 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""Originally written for Apple's py2, detects keyboard layout/loads localization
Last tested on ~10.14, sets input/region/language for Japan and assumed US OS version
Commented-out formats for other regions, not implemented"""
import copy
import json
import subprocess
import plistlib
import sys
cmd = ['ioreg', '-rln', 'AppleHIDKeyboardEventDriverV2', '-a']
results = subprocess.check_output(cmd)
structured = plistlib.readPlistFromString(results)
FROM_IOREG = structured[0].get('KeyboardLanguage')
DEF_WRITE = ['/usr/bin/defaults', 'write']
if FROM_IOREG == 'U.S.':
print 'US, no customizations needed'
sys.exit(0)
else:
login_cmd = list(DEF_WRITE)
login_cmd.extend(['/Library/Preferences/com.apple.loginwindow', 'showInputMenu',
'-bool', 'TRUE'])
subprocess.call(login_cmd)
# layouts_dict = {'Japanese Keyboard': 15,
# 'British': 2,
# 'German': 3,
# 'French': 1}
if FROM_IOREG == 'Japanese Keyboard':
globpref_cmd = list(DEF_WRITE)
globpref_cmd.extend(['/Library/Preferences/.GlobalPreferences',
'AppleLocale', 'ja_JP'])
subprocess.call(globpref_cmd)
country_cmd = globpref_cmd[:-2]
country_cmd.extend(['Country', 'JP'])
subprocess.call(country_cmd)
lang_cmd = globpref_cmd[:-2]
lang_cmd.extend(['AppleLanguages', '-array', 'ja'])
subprocess.call(lang_cmd)
hitool_dict = {'AppleCurrentKeyboardLayoutInputSourceID': 'com.apple.keylayout.US'}
def_ascii = {'InputSourceKind': 'Keyboard Layout',
'KeyboardLayout Name': 'U.S.',
'KeyboardLayout ID': 0}
inmode = 'Input Mode'
input_prefix = 'com.apple.inputmethod.'
dict_base = {'InputSourceKind': inmode,
'Bundle ID': 'com.apple.inputmethod.Kotoeri'}
nest_one, nest_two, nest_three = dict_base.copy(), dict_base.copy(), dict_base.copy()
nest_one[inmode] = input_prefix + 'Roman'
nest_two[inmode] = input_prefix + 'Japanese'
nest_three[inmode] = input_prefix + 'Japanese.Katakana'
enabled_list = [nest_one, nest_two, nest_three]
hitool_dict['AppleDefaultAsciiInputSource'] = def_ascii
hitool_dict['AppleEnabledInputSources'] = enabled_list
hitool_dict['AppleInputSourceHistory'] = enabled_list
hitool_dict['AppleSelectedInputSources'] = [nest_one]
plistlib.writePlist(hitool_dict, '/Library/Preferences/com.apple.HIToolbox.plist')
else:
print 'not a JP keyboard, will be extended/made applicable for UK/DE/FR layouts'
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment