Skip to content

Instantly share code, notes, and snippets.

@macmule
Created April 27, 2016 08:05
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 macmule/dff63550eeb297e4f7fdc02f5c4c94fb to your computer and use it in GitHub Desktop.
Save macmule/dff63550eeb297e4f7fdc02f5c4c94fb to your computer and use it in GitHub Desktop.
localiser.py - WIP
#!/usr/bin/python
# Standard Imports
import os
import plistlib
import re
import sys
# Other imports
import objc
from Foundation import NSBundle, NSDictionary, NSLocale, NSLocaleIdentifier
# Use US as locale to perform name of country & language lookups
US = NSLocale.alloc().initWithLocaleIdentifier_('en_US')
def get_country():
country_iso = raw_input("Enter A Country ISO Code: ").upper()
print
# Pull Country codes
country_codes = NSLocale.ISOCountryCodes()
# Add _ to name
country_local_identifier = '_' + country_iso
# Get country name
country_name = US.displayNameForKey_value_(NSLocaleIdentifier, country_local_identifier)
# Check that we've been parse a valid country code
if country_iso in country_codes:
print 'Country: %s' % country_name
print
# Exit if not...
else:
print 'Not Matched:', country_iso
# Quit
sys.exit(1)
get_localisation(country_iso)
def get_localisation(country_iso):
found_timezones = []
try:
countryTimeZonesPlist = plistlib.readPlist("/System/Library/PrivateFrameworks/SetupAssistantSupport.framework/Versions/A/Resources/TimeZones.plist")
if country_iso == 'US':
for zones in countryTimeZonesPlist['US'].values():
found_timezones.extend(zones)
else:
countryTimeZones = countryTimeZonesPlist[country_iso]
for zones in countryTimeZones:
found_timezones.append(zones)
except:
pass
try:
adj_times_plist = plistlib.readPlist("/System/Library/PreferencePanes/DateAndTime.prefPane/Contents/Resources/TimeZone.prefPane/Contents/Resources/all_cities_adj.plist")
for entry in adj_times_plist:
if country_iso in entry[4]:
found_timezones.append(entry[3])
except:
pass
found_timezones = sorted(set(found_timezones))
print 'Timezones: %s' % found_timezones
print
# Get a list of all available locales
availableLocales = NSLocale.availableLocaleIdentifiers()
# Create an empty list
matched_locales = []
# For each locale in the availableLocales list
for locales in availableLocales:
# Check to see if ends with country_iso
if locales.endswith(country_iso):
# If it does, append to list
matched_locales.append(locales)
# Sort alphabetically
matched_locales.sort()
# If array is not empty
if not len(matched_locales):
print 'Locales: None matched'
print 'Locales: %s' % matched_locales
print
# Create an empty list
language_name = []
found_languages = {}
# If array is not empty
if len(matched_locales):
# For each language in MatchedLocales
for language in list([i.split('_', 3)[0] for i in matched_locales]):
# Add matched to list
language_name.append(US.displayNameForKey_value_(NSLocaleIdentifier, language ))
#print len(country_language_codes_list)
for lang_2 in language_name:
found_languages[language] = lang_2
# If array is empty
else:
print 'Matched Languages: None matched'
print 'Languages: %s' % found_languages
print
# Create empty list
countryInputSource = []
try:
countryInputSourcePlist = plistlib.readPlist("/System/Library/PrivateFrameworks/SetupAssistantSupport.framework/Versions/A/Resources/SALocaleToInputSourceID.plist")
sa_country_input = plistlib.readPlist("/System/Library/CoreServices/Setup Assistant.app/Contents/Resources/SALocaleToInputSourceID.plist")
try:
countryInputSource.extend(countryInputSourcePlist['_' + country_iso])
except:
pass
try:
countryInputSource.extend(sa_country_input['_' + country_iso])
except:
pass
#if not countryInputSource:
try:
for lang in found_languages.keys():
countryInputSource.extend(countryInputSourcePlist[lang])
except:
pass
try:
for lang in found_languages.keys():
countryInputSource.extend(sa_country_input[lang])
except:
pass
try:
for locale in matched_locales:
countryInputSource.extend(countryInputSourcePlist[locale])
except:
pass
try:
for locale in matched_locales:
countryInputSource.extend(sa_country_input[locale])
except:
pass
except:
pass
countryInputSource = sorted(set(countryInputSource))
# Get list of keyboard layouts including identifier.
HIToolbox_bundle = NSBundle.bundleWithIdentifier_("com.apple.HIToolbox")
objc.loadBundleFunctions(HIToolbox_bundle, globals(), [('TISCreateInputSourceList','@@B')])
objc.loadBundleVariables(HIToolbox_bundle, globals(), [('kTISPropertyInputSourceType', '@')])
kb_layout_strs = map(lambda x: x.__repr__(), TISCreateInputSourceList({kTISPropertyInputSourceType: 'TISTypeKeyboardLayout'}, True))
name_id = re.compile(r'.+?KB Layout: (.+?) \(id=([-0-9]+)\)')
kb_layouts = [name_id.match(x).groups() for x in kb_layout_strs]
country_kbs = {}
for layout in kb_layouts:
for source in countryInputSource:
if layout[0].replace(" ", "").replace(".", "").lower().startswith(source.split('com.apple.keylayout.')[1].replace(".", "").lower().split('-')[0]):
country_kbs[layout[1]] = layout[0], ('com.apple.keylayout.' + (layout[0].replace(" ", "").replace(".", "")))
for language in found_languages.values():
if language in layout[0]:
country_kbs[layout[1]] = layout[0], ('com.apple.keylayout.' + (layout[0].replace(" ", "").replace(".", "")))
country_kbs = sorted(country_kbs.iteritems())
print 'KB Layouts: %s' % country_kbs
if __name__ == '__main__':
get_country()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment