refactor: Streamline System Language Detection Logic

- Consolidate language detection methods into a single unified approach
- Improve cross-platform language detection for Windows and Unix-like systems
- Simplify error handling and add more robust language code mapping
- Remove platform-specific detection methods in favor of a more generic approach
- Enhance language fallback mechanism with better default handling
This commit is contained in:
yeongpin 2025-02-25 12:14:54 +08:00
parent 5bbba05f69
commit 24b0a5c09e

92
main.py
View File

@ -5,13 +5,12 @@ import sys
import json import json
from logo import print_logo from logo import print_logo
from colorama import Fore, Style, init from colorama import Fore, Style, init
import ctypes
from ctypes import windll
import locale import locale
import platform import platform
# 只在 Windows 系统上导入 windll # 只在 Windows 系统上导入 windll
if platform.system() == 'Windows': if platform.system() == 'Windows':
import ctypes
from ctypes import windll from ctypes import windll
# 初始化colorama # 初始化colorama
@ -38,21 +37,22 @@ class Translator:
self.fallback_language = 'en' # Fallback language if translation is missing self.fallback_language = 'en' # Fallback language if translation is missing
self.load_translations() self.load_translations()
def _detect_system_language(self): def detect_system_language(self):
"""检测系统语言""" """Detect system language and return corresponding language code"""
try:
system = platform.system() system = platform.system()
if system == 'Windows': if system == 'Windows':
return self._detect_windows_language() return self._detect_windows_language()
elif system == 'Darwin': # macOS
return self._detect_macos_language()
elif system == 'Linux':
return self._detect_linux_language()
else: else:
return 'en' # 默认英语 return self._detect_unix_language()
except Exception as e:
print(f"{Fore.YELLOW}{EMOJI['INFO']} Failed to detect system language: {e}{Style.RESET_ALL}")
return 'en'
def _detect_windows_language(self): def _detect_windows_language(self):
"""检测 Windows 系统语言""" """Detect language on Windows systems"""
try: try:
# 确保我们在 Windows 上 # 确保我们在 Windows 上
if not hasattr(ctypes, 'windll'): if not hasattr(ctypes, 'windll'):
@ -64,50 +64,44 @@ class Translator:
threadid = user32.GetWindowThreadProcessId(hwnd, 0) threadid = user32.GetWindowThreadProcessId(hwnd, 0)
layout_id = user32.GetKeyboardLayout(threadid) & 0xFFFF layout_id = user32.GetKeyboardLayout(threadid) & 0xFFFF
# 根据键盘布局 ID 判断语言 # Map language ID to our language codes
if layout_id == 0x0804: language_map = {
return 'zh_CN' # 简体中文 0x0409: 'en', # English
elif layout_id == 0x0404: 0x0404: 'zh_tw', # Traditional Chinese
return 'zh_TW' # 繁体中文 0x0804: 'zh_cn', # Simplified Chinese
else: }
return 'en' # 默认英语
except Exception as e:
print(f"Error detecting Windows language: {e}")
return 'en'
def _detect_macos_language(self): return language_map.get(layout_id, 'en')
"""检测 macOS 系统语言""" except:
return self._detect_unix_language()
def _detect_unix_language(self):
"""Detect language on Unix-like systems (Linux, macOS)"""
try: try:
# 使用 defaults 命令获取系统语言设置 # Get the system locale
import subprocess system_locale = locale.getdefaultlocale()[0]
result = subprocess.run(['defaults', 'read', '-g', 'AppleLanguages'], if not system_locale:
capture_output=True, text=True)
output = result.stdout.strip()
# 解析输出
if 'zh-Hans' in output:
return 'zh_CN' # 简体中文
elif 'zh-Hant' in output or 'zh_TW' in output:
return 'zh_TW' # 繁体中文
else:
return 'en' # 默认英语
except Exception as e:
print(f"Error detecting macOS language: {e}")
return 'en' return 'en'
def _detect_linux_language(self): system_locale = system_locale.lower()
"""检测 Linux 系统语言"""
try: # Map locale to our language codes
# 检查环境变量 if system_locale.startswith('zh_tw') or system_locale.startswith('zh_hk'):
lang = os.environ.get('LANG', '').lower() return 'zh_tw'
if lang.startswith('zh_cn'): elif system_locale.startswith('zh_cn'):
return 'zh_CN' return 'zh_cn'
elif lang.startswith('zh_tw'): elif system_locale.startswith('en'):
return 'zh_TW'
else:
return 'en' return 'en'
except Exception as e:
print(f"Error detecting Linux language: {e}") # Try to get language from LANG environment variable as fallback
env_lang = os.getenv('LANG', '').lower()
if 'tw' in env_lang or 'hk' in env_lang:
return 'zh_tw'
elif 'cn' in env_lang:
return 'zh_cn'
return 'en'
except:
return 'en' return 'en'
def load_translations(self): def load_translations(self):