Nicer fallback logic when deriving LANG from NSLocale

This commit is contained in:
Kovid Goyal 2023-07-01 11:53:09 +05:30
parent 503a0bdd4d
commit 22c2687432
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
3 changed files with 18 additions and 19 deletions

View file

@ -782,19 +782,10 @@ cocoa_get_workspace_ids(void *w, size_t *workspace_ids, size_t array_sz) {
static PyObject*
cocoa_get_lang(PyObject UNUSED *self) {
@autoreleasepool {
NSString* locale = nil;
NSString* lang_code = [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];
NSString* lang_code = [[NSLocale currentLocale] languageCode];
NSString* country_code = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
if (lang_code && country_code) {
locale = [NSString stringWithFormat:@"%@_%@", lang_code, country_code];
} else {
locale = [[NSLocale currentLocale] localeIdentifier];
}
if (!locale) { Py_RETURN_NONE; }
const char* locale_utf8 = [locale UTF8String];
return Py_BuildValue("s", locale_utf8);
NSString* identifier = [[NSLocale currentLocale] localeIdentifier];
return Py_BuildValue("sss", lang_code ? [lang_code UTF8String]:"", country_code ? [country_code UTF8String] : "", identifier ? [identifier UTF8String]: "");
} // autoreleasepool
}

View file

@ -740,7 +740,7 @@ def cocoa_set_global_shortcut(name: str, mods: int, key: int) -> bool:
pass
def cocoa_get_lang() -> Optional[str]:
def cocoa_get_lang() -> Tuple[str, str, str]:
pass

View file

@ -294,12 +294,20 @@ def ensure_macos_locale() -> None:
# https://github.com/kovidgoyal/kitty/issues/90
from .fast_data_types import cocoa_get_lang, locale_is_valid
if 'LANG' not in os.environ:
lang = cocoa_get_lang()
if lang is not None:
if not locale_is_valid(lang):
lang = 'en_US'
os.environ['LANG'] = f'{lang}.UTF-8'
set_LANG_in_default_env(os.environ['LANG'])
lang_code, country_code, identifier = cocoa_get_lang()
lang = 'en_US'
if identifier and locale_is_valid(identifier):
lang = identifier
elif lang_code and country_code and locale_is_valid(f'{lang_code}_{country_code}'):
lang = f'{lang_code}_{country_code}'
elif lang_code:
if lang_code != 'en':
with suppress(OSError):
found = sorted(x for x in os.listdir('/usr/share/locale') if x.startswith(f'{lang_code}_'))
if found:
lang = found[0].partition('.')[0]
os.environ['LANG'] = f'{lang}.UTF-8'
set_LANG_in_default_env(os.environ['LANG'])
@contextmanager