feat: Improve System Language Detection in Translator Class

- Refactor language detection method with separate methods for Windows, macOS, and Linux
- Add more robust language detection for different platforms
- Improve error handling and fallback mechanisms
- Ensure consistent language code formatting (zh_CN, zh_TW)
- Update Windows language detection using windll with additional error checks
This commit is contained in:
yeongpin 2025-02-25 12:09:13 +08:00
parent 72c95e4b4f
commit 5bbba05f69
4 changed files with 130 additions and 59 deletions

4
.env
View File

@ -1,2 +1,2 @@
version=1.4.04
VERSION=1.4.04
version=1.4.05
VERSION=1.4.05

View File

@ -1,5 +1,10 @@
# Change Log
## v1.4.05
1. Fix: macOS Language Detection | 修復macOS語言檢測
## v1.4.04
1. Change Some Language Info to English | 更改一些語言信息為英文

121
main.py
View File

@ -10,6 +10,10 @@ from ctypes import windll
import locale
import platform
# 只在 Windows 系统上导入 windll
if platform.system() == 'Windows':
from ctypes import windll
# 初始化colorama
init()
@ -29,72 +33,81 @@ EMOJI = {
class Translator:
def __init__(self):
self.current_language = self.detect_system_language() # Changed to use system language
self.translations = {}
self.current_language = self._detect_system_language()
self.fallback_language = 'en' # Fallback language if translation is missing
self.load_translations()
def detect_system_language(self):
"""Detect system language and return corresponding language code"""
try:
system = platform.system()
if system == 'Windows':
return self._detect_windows_language()
else:
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_system_language(self):
"""检测系统语言"""
system = platform.system()
if system == 'Windows':
return self._detect_windows_language()
elif system == 'Darwin': # macOS
return self._detect_macos_language()
elif system == 'Linux':
return self._detect_linux_language()
else:
return 'en' # 默认英语
def _detect_windows_language(self):
"""Detect language on Windows systems"""
"""检测 Windows 系统语言"""
try:
# Get the keyboard layout
user32 = ctypes.WinDLL('user32', use_last_error=True)
# 确保我们在 Windows 上
if not hasattr(ctypes, 'windll'):
return 'en'
# 获取键盘布局
user32 = ctypes.windll.user32
hwnd = user32.GetForegroundWindow()
threadid = user32.GetWindowThreadProcessId(hwnd, 0)
layout_id = user32.GetKeyboardLayout(threadid) & 0xFFFF
# Map language ID to our language codes
language_map = {
0x0409: 'en', # English
0x0404: 'zh_tw', # Traditional Chinese
0x0804: 'zh_cn', # Simplified Chinese
}
return language_map.get(layout_id, 'en')
except:
return self._detect_unix_language()
def _detect_unix_language(self):
"""Detect language on Unix-like systems (Linux, macOS)"""
try:
# Get the system locale
system_locale = locale.getdefaultlocale()[0]
if not system_locale:
return 'en'
system_locale = system_locale.lower()
# Map locale to our language codes
if system_locale.startswith('zh_tw') or system_locale.startswith('zh_hk'):
return 'zh_tw'
elif system_locale.startswith('zh_cn'):
return 'zh_cn'
elif system_locale.startswith('en'):
return 'en'
# 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'
# 根据键盘布局 ID 判断语言
if layout_id == 0x0804:
return 'zh_CN' # 简体中文
elif layout_id == 0x0404:
return 'zh_TW' # 繁体中文
else:
return 'en' # 默认英语
except Exception as e:
print(f"Error detecting Windows language: {e}")
return 'en'
except:
def _detect_macos_language(self):
"""检测 macOS 系统语言"""
try:
# 使用 defaults 命令获取系统语言设置
import subprocess
result = subprocess.run(['defaults', 'read', '-g', 'AppleLanguages'],
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'
def _detect_linux_language(self):
"""检测 Linux 系统语言"""
try:
# 检查环境变量
lang = os.environ.get('LANG', '').lower()
if lang.startswith('zh_cn'):
return 'zh_CN'
elif lang.startswith('zh_tw'):
return 'zh_TW'
else:
return 'en'
except Exception as e:
print(f"Error detecting Linux language: {e}")
return 'en'
def load_translations(self):

View File

@ -50,12 +50,25 @@ get_latest_version() {
echo -e "${GREEN}✅ 找到最新版本: ${VERSION}${NC}"
}
# 檢測系統類型
# 檢測系統類型和架構
detect_os() {
if [[ "$(uname)" == "Darwin" ]]; then
OS="mac"
else
# 检测 macOS 架构
ARCH=$(uname -m)
if [[ "$ARCH" == "arm64" ]]; then
OS="mac_arm64"
echo -e "${CYAN} 检测到 macOS ARM64 架构${NC}"
else
OS="mac_intel"
echo -e "${CYAN} 检测到 macOS Intel 架构${NC}"
fi
elif [[ "$(uname)" == "Linux" ]]; then
OS="linux"
echo -e "${CYAN} 检测到 Linux 系统${NC}"
else
# 假设是 Windows
OS="windows"
echo -e "${CYAN} 检测到 Windows 系统${NC}"
fi
}
@ -67,11 +80,51 @@ install_cursor_free_vip() {
local download_url="https://github.com/yeongpin/cursor-free-vip/releases/download/v${VERSION}/${binary_name}"
echo -e "${CYAN} 正在下載到 ${downloads_dir}...${NC}"
echo -e "${CYAN} 下載鏈接: ${download_url}${NC}"
# 先检查文件是否存在
if curl --output /dev/null --silent --head --fail "$download_url"; then
echo -e "${GREEN}✅ 文件存在,开始下载...${NC}"
else
echo -e "${RED}❌ 下载链接不存在: ${download_url}${NC}"
echo -e "${YELLOW}⚠️ 尝试不带架构的版本...${NC}"
# 尝试不带架构的版本
if [[ "$OS" == "mac_arm64" || "$OS" == "mac_intel" ]]; then
OS="mac"
binary_name="CursorFreeVIP_${VERSION}_${OS}"
download_url="https://github.com/yeongpin/cursor-free-vip/releases/download/v${VERSION}/${binary_name}"
echo -e "${CYAN} 新下载链接: ${download_url}${NC}"
if ! curl --output /dev/null --silent --head --fail "$download_url"; then
echo -e "${RED}❌ 新下载链接也不存在${NC}"
exit 1
fi
else
exit 1
fi
fi
# 下载文件
if ! curl -L -o "${binary_path}" "$download_url"; then
echo -e "${RED}❌ 下載失敗${NC}"
exit 1
fi
# 检查下载的文件大小
local file_size=$(stat -f%z "${binary_path}" 2>/dev/null || stat -c%s "${binary_path}" 2>/dev/null)
echo -e "${CYAN} 下載的文件大小: ${file_size} 字節${NC}"
# 如果文件太小,可能是错误信息
if [ "$file_size" -lt 1000 ]; then
echo -e "${YELLOW}⚠️ 警告: 下載的文件太小,可能不是有效的可執行文件${NC}"
echo -e "${YELLOW}⚠️ 文件內容:${NC}"
cat "${binary_path}"
echo ""
echo -e "${RED}❌ 下載失敗,請檢查版本號和操作系統是否正確${NC}"
exit 1
fi
echo -e "${CYAN} 正在設置執行權限...${NC}"
chmod +x "${binary_path}"