2444 lines
111 KiB
Python
2444 lines
111 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
|
||
import os
|
||
import sys
|
||
import subprocess
|
||
import json
|
||
import re
|
||
import threading
|
||
import tkinter as tk
|
||
import atexit
|
||
from tkinter import ttk, scrolledtext, filedialog, messagebox, simpledialog
|
||
from pathlib import Path
|
||
from urllib.request import urlopen, Request
|
||
from urllib.error import URLError, HTTPError
|
||
from urllib.parse import urlencode
|
||
from datetime import datetime
|
||
import zipfile
|
||
try:
|
||
import pyzipper
|
||
except ImportError:
|
||
pyzipper = None
|
||
import shutil
|
||
import time
|
||
|
||
|
||
def get_app_dir():
|
||
return Path(sys.executable).resolve().parent if getattr(sys, 'frozen', False) else Path(__file__).resolve().parent
|
||
|
||
|
||
def resource_candidates(file_name):
|
||
base_dir = get_app_dir()
|
||
candidates = []
|
||
if getattr(sys, 'frozen', False):
|
||
candidates.append(Path(getattr(sys, '_MEIPASS', base_dir)) / file_name)
|
||
candidates.extend([
|
||
base_dir / file_name,
|
||
base_dir / 'tools' / file_name,
|
||
base_dir / 'shared' / file_name,
|
||
base_dir.parent / 'tools' / file_name,
|
||
base_dir.parent / 'shared' / file_name,
|
||
base_dir.parent / file_name,
|
||
])
|
||
unique = []
|
||
for candidate in candidates:
|
||
if candidate not in unique:
|
||
unique.append(candidate)
|
||
return unique
|
||
|
||
|
||
def find_resource(file_name):
|
||
candidates = resource_candidates(file_name)
|
||
for candidate in candidates:
|
||
if candidate.exists():
|
||
return candidate
|
||
return candidates[0]
|
||
|
||
|
||
def find_tool(file_name, fallback=None):
|
||
path = find_resource(file_name)
|
||
if path.exists():
|
||
return str(path)
|
||
return fallback or str(path)
|
||
|
||
|
||
def set_windows_app_user_model_id():
|
||
if sys.platform != 'win32':
|
||
return
|
||
try:
|
||
import ctypes
|
||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
|
||
"yibin.keyi.mazda.ez60.language.installer"
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
class ADKAPKGUI:
|
||
CACHE_DIR_NAME = "apps_cache_Mazda_EZ60_1_0"
|
||
PACKAGE_KEY_VEHICLE_NAME = "EZ60_1.0"
|
||
|
||
def __init__(self):
|
||
set_windows_app_user_model_id()
|
||
self.root = tk.Tk()
|
||
self.root.title("长安语言安装工具")
|
||
self.root.geometry("650x640")
|
||
self.root.resizable(True, True)
|
||
self.set_window_icon()
|
||
|
||
# 固定颜色
|
||
self.colors = {
|
||
'bg_dark': '#1e1e2e',
|
||
'bg_light': '#2a2a3e',
|
||
'accent': '#6c5ce7',
|
||
'accent_hover': '#5b4bc4',
|
||
'success': '#00b894',
|
||
'error': '#d63031',
|
||
'warning': '#fdcb6e',
|
||
'info': '#0984e3',
|
||
'text': '#dfe6e9',
|
||
'text_secondary': '#b2bec3',
|
||
'border': '#3d3d5e'
|
||
}
|
||
|
||
# 多语言
|
||
self.lang = 'zh'
|
||
self.T = {
|
||
'zh': {
|
||
'title': '马自达EZ60刷机工具_OS-1.0',
|
||
'btn_root': '🔓 获取权限',
|
||
'btn_push': '📦 刷入语言包',
|
||
'btn_install': '📱 安装App',
|
||
'btn_language': '🌐 语言设置',
|
||
'btn_timezone': '⏰ 时区设置',
|
||
'btn_settings': '⚙️ 安卓设置',
|
||
'btn_reboot': '🔄 重启设备',
|
||
'btn_disable_upgrade': '❌ 禁用升级',
|
||
'btn_clear_log': '🗑 清空日志',
|
||
'btn_query_pwd': '查询密码',
|
||
'btn_debug_extract': '解压测试',
|
||
'device_label': '设备:',
|
||
'vin_label': 'VIN码:',
|
||
'auth_label': '授权:',
|
||
'log_title': '📋 运行日志',
|
||
'status_ready': '就绪',
|
||
'status_connected': '已连接',
|
||
'status_disconnected': '未连接',
|
||
'status_detecting': '未检测',
|
||
'vin_none': '未获取',
|
||
'auth_none': '未验证',
|
||
'auth_yes': '已授权',
|
||
'auth_no': '未授权',
|
||
'btn_refresh': '🔄 检查',
|
||
'hint_factory': '🔧 关闭车辆WI-FI和4G网络,拨号获取的密码进入工程模式',
|
||
'warn_no_device': '设备未连接',
|
||
'warn_connect_first': '请先连接设备并点击「检查」按钮刷新状态!',
|
||
'warn_no_vin': '请先刷新设备状态并获取VIN码',
|
||
'err_auth_fail': '授权失败',
|
||
'err_device_not_auth': '设备未授权',
|
||
'err_resource_fail': '资源准备失败!',
|
||
'err_no_resource_dir': '资源目录未找到',
|
||
'info_flash_start': '开始刷入语言包...',
|
||
'info_flash_done': '语言包刷入完成,重启设备后生效',
|
||
'info_flash_fail': '语言包刷入失败',
|
||
'warn_no_apk': '未找到语言包文件',
|
||
'info_installing': '安装中...',
|
||
'info_install_done': '安装完成',
|
||
'info_log_cleared': '日志已清空',
|
||
'confirm_reboot': '确定要重启设备吗?',
|
||
'info_rebooting': '设备正在重启...',
|
||
'warn_device_disconnected': '设备已断开连接',
|
||
'info_device_connected': '设备已连接',
|
||
'info_checking_auth': '正在验证授权状态...',
|
||
'info_auth_pass': '✅ 授权验证通过!',
|
||
'info_auth_fail': '❌ 授权验证失败',
|
||
'info_preparing': '正在准备资源...',
|
||
'err_no_package': '错误:未找到资源包',
|
||
'err_no_password': '错误:解压密码未设置',
|
||
'err_no_7za': '错误:未找到 7za.exe',
|
||
'err_extract_fail': '解压失败',
|
||
'info_extracting': '资源准备中...',
|
||
'info_extract_done': '资源准备完成',
|
||
'err_extract_user': '资源准备失败,请检查网络连接后重试',
|
||
'warn_no_app_dir': '警告:未找到 app/priv-app 目录',
|
||
'progress_resource_loading': '资源准备中...',
|
||
'progress_resource_done': '资源准备完成',
|
||
'progress_extracting_percent': '资源准备中 {percent}%',
|
||
'progress_flashing': '正在刷入',
|
||
'progress_flash_done': '刷入完成',
|
||
'progress_aborted': '已终止',
|
||
'progress_installing': '安装中',
|
||
'progress_installing_name': '安装中 ({name})',
|
||
'progress_done': '完成',
|
||
'lang_zh': '中',
|
||
'lang_en': 'EN',
|
||
'switch_lang': '语言 / Language',
|
||
'pwd_query_label': '工程密码查询:',
|
||
'vin_placeholder': '请输入VIN',
|
||
'pwd_success': '密码: *#{password}#*',
|
||
'pwd_failed': '失败: {message}',
|
||
'pwd_request_failed': '请求失败',
|
||
'tip_1': '1. 安装语言过程中请保持车辆和电脑的电量充足,不可中途停止。',
|
||
'tip_2': '2. 获取权限以后,车辆自动重启以后再进入语言刷入。',
|
||
'tip_3': '3. 部分语言需要重启后生效,可以一切工作完成以后再重启。',
|
||
'warn_flash_warning': '⚠️ 重要提示',
|
||
'warn_flash_msg': '刷入过程中请勿:\n ● 重启车机\n ● 退出本程序\n ● 关闭电脑\n\n否则可能导致车机系统损坏!',
|
||
'err_wrong_password': '请检查密码是否正确',
|
||
'title_pop_lang': '快捷语言设置',
|
||
'quick_lang_header': '选择目标语言',
|
||
'quick_lang_hint': '点击按钮即可将系统语言切换为对应语言,重启后生效',
|
||
'quick_lang_system': '⚙️ 打开系统语言设置(手动选择)',
|
||
'msg_warn_title': '警告',
|
||
'msg_error_title': '错误',
|
||
'msg_done_title': '完成',
|
||
'msg_success_title': '成功',
|
||
'msg_auth_failed_title': '授权失败',
|
||
'msg_device_unauthorized': '设备未授权',
|
||
'msg_input_vin': '请输入VIN码',
|
||
'msg_resource_prepare_failed': '资源准备失败!',
|
||
'msg_resource_dir_missing': '资源目录未找到',
|
||
'msg_no_apk_in_folder': '所选文件夹中没有APK文件!',
|
||
'msg_confirm_install_title': '确认安装',
|
||
'msg_confirm_install_many': '已选择 {count} 个APK文件\n\n是否开始安装?',
|
||
'msg_confirm_install_folder': '找到 {count} 个APK文件\n\n是否开始批量安装?',
|
||
'msg_install_success_many': '成功安装 {count} 个APK!',
|
||
'msg_install_partial': '成功: {success}\n失败: {failed}',
|
||
'msg_install_all_failed': '所有APK安装失败!',
|
||
'msg_install_exception': '安装过程异常:{error}',
|
||
'msg_quick_lang_success': '系统语言已设置为 {language}\n\n⚠️ 请重启设备使其生效。',
|
||
'msg_quick_lang_failed': '语言设置失败!\n\n{output}',
|
||
'msg_disable_confirm_title': '确认禁用升级',
|
||
'msg_disable_confirm': '⚠️ 警告:禁用系统升级后,将无法接收系统更新!\n\n是否确定要禁用系统升级应用?',
|
||
'msg_disable_success': '系统升级已成功禁用!',
|
||
'msg_disable_failed': '禁用失败:{output}',
|
||
'msg_reboot_confirm_title': '确认重启',
|
||
'file_apk': 'APK文件',
|
||
'file_all': '所有文件',
|
||
'dialog_select_apk': '选择APK文件',
|
||
'dialog_select_apk_folder': '选择包含APK文件的文件夹',
|
||
'unknown_error': '未知错误',
|
||
'status_debug': '调试模式',
|
||
'debug_password_prompt': '请输入调试密码:',
|
||
'debug_password_verifying': '正在校验调试密码...',
|
||
'debug_wrong_password': '密码错误',
|
||
'debug_verify_failed': '调试密码校验失败: {message}',
|
||
'debug_need_enable': '请先按 Ctrl+Shift+D 进入调试模式',
|
||
'debug_need_vin': '调试解压测试需要 VIN。请先连接设备刷新,或在调试模式中手动设置 VIN。',
|
||
'log_debug_on': '🔧 调试模式已开启 - 跳过授权和设备校验,显示详细ADB日志',
|
||
'log_debug_off': '调试模式已关闭',
|
||
'log_lang_switched': '语言已切换为中文',
|
||
'log_cache_invalid': '已解压缓存无效: {reason}',
|
||
'log_cache_reuse_invalid': '缓存资源无效,已清理: {reason}',
|
||
'log_package_missing': '未找到资源包文件: {path}',
|
||
'log_adb_missing': '未找到adb命令,请将ADB文件放入本目录',
|
||
'log_device_connected': '设备已连接',
|
||
'log_device_disconnected': '设备已断开连接',
|
||
'log_current_vin': '当前VIN: {vin}',
|
||
'log_vin_unavailable': '无法读取VIN',
|
||
'log_refresh_failed': '刷新设备状态失败: {error}',
|
||
'log_auth_skip_debug': '调试模式:跳过授权',
|
||
'log_auth_checking': '正在验证授权状态...',
|
||
'log_auth_ok': '授权验证通过',
|
||
'log_auth_failed': '授权验证失败',
|
||
'log_vehicle_name': '车型名称: {name}',
|
||
'log_adb_required': '请先连接 ADB 并获取 VIN',
|
||
'log_data_prepare_failed_detail': '资源准备失败: {error}',
|
||
'log_extract_password_missing': '错误:解压密码未设置',
|
||
'log_7za_missing': '错误:未找到 7za.exe ({path})',
|
||
'log_extracted_resource_invalid': '解压后的资源无效: {reason}。已停止刷入,请检查解压密码或资源包。',
|
||
'log_extract_done': '资源准备完成',
|
||
'log_extract_exception': '资源准备失败: {error}',
|
||
'err_extract_wrong_password': '解压密码错误,请重新确认 package.bin 密码',
|
||
'err_extract_data': '资源包数据错误,可能是密码错误或 package.bin 损坏',
|
||
'err_extract_corrupt': '资源包损坏或不完整,请检查 package.bin',
|
||
'err_extract_failed': '解压失败: {error}',
|
||
'err_extract_failed_code': '解压失败 (返回码 {code}),请检查密码是否正确',
|
||
'log_root_failed': '获取失败',
|
||
'log_permission_failed': '获取失败',
|
||
'log_permission_running': '正在获取权限中',
|
||
'log_reboot_failed': '重启失败',
|
||
'log_permission_ok': '获取成功',
|
||
'log_flash_readonly': '请先点击「获取权限」获取权限后再试',
|
||
'log_flash_complete_count': '刷入完成,共 {count} 个语言包',
|
||
'log_flash_effect_after_reboot': '语言包已刷入完成,重启设备后生效,您可在适当时候重启',
|
||
'log_flash_partial': '部分刷入成功({success}/{total})',
|
||
'log_flash_failed_item_detail': '刷入失败: {name} - {error}',
|
||
'log_install_start': '开始安装 {count} 个APK...',
|
||
'log_install_done_all': '安装完成:全部 {count} 个成功',
|
||
'log_install_done_partial': '安装完成:{success}/{total} 成功',
|
||
'log_install_failed': '安装失败',
|
||
'log_install_exception': '安装过程异常: {error}',
|
||
'log_install_success_item': '✓ {name}',
|
||
'log_install_failed_item': '✗ {name}',
|
||
'log_menu_key_ready': '辅助组件已安装',
|
||
'log_menu_key_install_failed': '辅助组件安装失败',
|
||
'log_menu_key_permission_failed': '辅助组件权限设置失败',
|
||
'log_quick_lang_setting': '正在设置系统语言为: {language} ({locale})',
|
||
'log_quick_lang_success': '✓ 语言已设置为 {language}',
|
||
'log_quick_lang_failed': '✗ 语言设置失败: {output}',
|
||
'log_rebooting': '设备正在重启...',
|
||
'log_disable_cancelled': '已取消禁用升级操作',
|
||
'log_disable_success': '系统升级已禁用',
|
||
'log_disable_failed': '禁用系统升级失败',
|
||
'log_preclean_start': '正在清理预置应用...',
|
||
'log_preclean_done': '预置应用清理完成',
|
||
'log_preclean_partial': '预置应用部分清理失败',
|
||
'log_preclean_item_done': '清理项已完成: {package}',
|
||
'log_preclean_item_failed': '清理项执行失败: {package}',
|
||
'log_package_key_failed': 'package-key 获取失败',
|
||
'log_package_extract_success': '资源准备完成',
|
||
'log_package_extract_failed': 'package.bin 解压测试失败',
|
||
'log_pwd_success': '密码查询成功',
|
||
'log_pwd_failed': '密码查询失败: {message}',
|
||
'log_pwd_request_failed': '密码查询请求失败: {error}',
|
||
'err_no_usable_apk': '未找到可用 APK',
|
||
'err_zero_apk': '发现 0KB APK: {files}',
|
||
'err_push_failed': 'push失败: {error}',
|
||
'err_cp_failed': 'cp失败: {error}',
|
||
},
|
||
'en': {
|
||
'title': 'Mazda EZ60 Flash Tool_OS-1.0',
|
||
'btn_root': '🔓 Get Root',
|
||
'btn_push': '📦 Flash Lang Pkg',
|
||
'btn_install': '📱 Install App',
|
||
'btn_language': '🌐 Language',
|
||
'btn_timezone': '⏰ Timezone',
|
||
'btn_settings': '⚙️ Settings',
|
||
'btn_reboot': '🔄 Reboot',
|
||
'btn_disable_upgrade': '❌ Disable OTA',
|
||
'btn_clear_log': '🗑 Clear Log',
|
||
'btn_query_pwd': 'Query Pwd',
|
||
'btn_debug_extract': 'Extract',
|
||
'device_label': 'Device:',
|
||
'vin_label': 'VIN:',
|
||
'auth_label': 'Auth:',
|
||
'log_title': '📋 Log',
|
||
'status_ready': 'Ready',
|
||
'status_connected': 'Connected',
|
||
'status_disconnected': 'Disconnected',
|
||
'status_detecting': 'Detecting',
|
||
'vin_none': 'None',
|
||
'auth_none': 'Unknown',
|
||
'auth_yes': 'Authorized',
|
||
'auth_no': 'Unauthorized',
|
||
'btn_refresh': '🔄 Check',
|
||
'hint_factory': '🔧 Turn off WiFi & 4G, enter factory mode with dial code',
|
||
'warn_no_device': 'Device not connected',
|
||
'warn_connect_first': 'Please connect device and click Check button!',
|
||
'warn_no_vin': 'Please refresh device status and get VIN',
|
||
'err_auth_fail': 'Authorization failed',
|
||
'err_device_not_auth': 'Device not authorized',
|
||
'err_resource_fail': 'Resource preparation failed!',
|
||
'err_no_resource_dir': 'Resource directory not found',
|
||
'info_flash_start': 'Starting language pack flashing...',
|
||
'info_flash_done': 'Flashing complete, reboot device to take effect',
|
||
'info_flash_fail': 'Flashing failed',
|
||
'warn_no_apk': 'No APK files found',
|
||
'info_installing': 'Installing...',
|
||
'info_install_done': 'Install complete',
|
||
'info_log_cleared': 'Log cleared',
|
||
'confirm_reboot': 'Are you sure you want to reboot?',
|
||
'info_rebooting': 'Device rebooting...',
|
||
'warn_device_disconnected': 'Device disconnected',
|
||
'info_device_connected': 'Device connected',
|
||
'info_checking_auth': 'Verifying authorization...',
|
||
'info_auth_pass': '✅ Authorization passed!',
|
||
'info_auth_fail': '❌ Authorization failed',
|
||
'info_preparing': 'Preparing resources...',
|
||
'err_no_package': 'Error: package.bin not found',
|
||
'err_no_password': 'Error: password not set',
|
||
'err_no_7za': 'Error: 7za.exe not found',
|
||
'err_extract_fail': 'Extraction failed',
|
||
'info_extracting': 'Preparing resources...',
|
||
'info_extract_done': 'Resource preparation complete',
|
||
'err_extract_user': 'Resource preparation failed, check network and retry',
|
||
'warn_no_app_dir': 'Warning: app/priv-app directory not found',
|
||
'progress_resource_loading': 'Preparing resources...',
|
||
'progress_resource_done': 'Resources ready',
|
||
'progress_extracting_percent': 'Preparing resources {percent}%',
|
||
'progress_flashing': 'Flashing',
|
||
'progress_flash_done': 'Flash complete',
|
||
'progress_aborted': 'Aborted',
|
||
'progress_installing': 'Installing',
|
||
'progress_installing_name': 'Installing ({name})',
|
||
'progress_done': 'Done',
|
||
'lang_zh': '中',
|
||
'lang_en': 'EN',
|
||
'switch_lang': 'Language',
|
||
'pwd_query_label': 'Factory password:',
|
||
'vin_placeholder': 'Enter VIN',
|
||
'pwd_success': 'Password: *#{password}#*',
|
||
'pwd_failed': 'Failed: {message}',
|
||
'pwd_request_failed': 'Request failed',
|
||
'tip_1': '1. Keep the vehicle and PC powered during language installation.',
|
||
'tip_2': '2. After permission is obtained, wait for the vehicle to reboot before flashing.',
|
||
'tip_3': '3. Some languages take effect after reboot; reboot after all work is finished.',
|
||
'warn_flash_warning': '⚠️ Warning',
|
||
'warn_flash_msg': 'During flashing, DO NOT:\n ● Reboot vehicle\n ● Close this app\n ● Power off PC\n\nSystem damage may occur!',
|
||
'err_wrong_password': 'Please check password',
|
||
'title_pop_lang': 'Quick Language Setting',
|
||
'quick_lang_header': 'Select target language',
|
||
'quick_lang_hint': 'Click a button to set the system language. Reboot to apply.',
|
||
'quick_lang_system': '⚙️ Open system language settings',
|
||
'msg_warn_title': 'Warning',
|
||
'msg_error_title': 'Error',
|
||
'msg_done_title': 'Done',
|
||
'msg_success_title': 'Success',
|
||
'msg_auth_failed_title': 'Authorization failed',
|
||
'msg_device_unauthorized': 'Device unauthorized',
|
||
'msg_input_vin': 'Enter VIN',
|
||
'msg_resource_prepare_failed': 'Resource preparation failed!',
|
||
'msg_resource_dir_missing': 'Resource directory not found',
|
||
'msg_no_apk_in_folder': 'No APK files found in the selected folder!',
|
||
'msg_confirm_install_title': 'Confirm install',
|
||
'msg_confirm_install_many': '{count} APK files selected.\n\nStart installation?',
|
||
'msg_confirm_install_folder': '{count} APK files found.\n\nStart batch installation?',
|
||
'msg_install_success_many': '{count} APKs installed successfully!',
|
||
'msg_install_partial': 'Success: {success}\nFailed: {failed}',
|
||
'msg_install_all_failed': 'All APK installations failed!',
|
||
'msg_install_exception': 'Installation error: {error}',
|
||
'msg_quick_lang_success': 'System language set to {language}.\n\n⚠️ Reboot the device to apply.',
|
||
'msg_quick_lang_failed': 'Language setting failed!\n\n{output}',
|
||
'msg_disable_confirm_title': 'Confirm Disable OTA',
|
||
'msg_disable_confirm': '⚠️ Warning: after disabling OTA, the system will no longer receive updates.\n\nDisable the OTA app?',
|
||
'msg_disable_success': 'System upgrade has been disabled!',
|
||
'msg_disable_failed': 'Disable failed: {output}',
|
||
'msg_reboot_confirm_title': 'Confirm reboot',
|
||
'file_apk': 'APK files',
|
||
'file_all': 'All files',
|
||
'dialog_select_apk': 'Select APK file',
|
||
'dialog_select_apk_folder': 'Select a folder containing APK files',
|
||
'unknown_error': 'unknown error',
|
||
'status_debug': 'Debug mode',
|
||
'debug_password_prompt': 'Enter debug password:',
|
||
'debug_password_verifying': 'Verifying debug password...',
|
||
'debug_wrong_password': 'Wrong password',
|
||
'debug_verify_failed': 'Debug password verification failed: {message}',
|
||
'debug_need_enable': 'Press Ctrl+Shift+D first.',
|
||
'debug_need_vin': 'Extract test needs a VIN. Refresh a connected device or set VIN in debug mode.',
|
||
'log_debug_on': '🔧 Debug mode enabled - authorization and device checks are skipped, detailed ADB logs are shown',
|
||
'log_debug_off': 'Debug mode disabled',
|
||
'log_lang_switched': 'Language switched to English',
|
||
'log_cache_invalid': 'Extract cache invalid: {reason}',
|
||
'log_cache_reuse_invalid': 'Cached resources invalid and cleaned: {reason}',
|
||
'log_package_missing': 'Resource package not found: {path}',
|
||
'log_adb_missing': 'adb not found. Put ADB files in this directory.',
|
||
'log_device_connected': 'Device connected',
|
||
'log_device_disconnected': 'Device disconnected',
|
||
'log_current_vin': 'Current VIN: {vin}',
|
||
'log_vin_unavailable': 'Unable to read VIN',
|
||
'log_refresh_failed': 'Refresh device status failed: {error}',
|
||
'log_auth_skip_debug': 'Debug mode: skip authorization',
|
||
'log_auth_checking': 'Checking authorization...',
|
||
'log_auth_ok': 'Authorization passed',
|
||
'log_auth_failed': 'Authorization failed',
|
||
'log_vehicle_name': 'Vehicle name: {name}',
|
||
'log_adb_required': 'Connect ADB and get VIN first',
|
||
'log_data_prepare_failed_detail': 'Resource preparation failed: {error}',
|
||
'log_extract_password_missing': 'Extraction password is not set',
|
||
'log_7za_missing': '7za.exe not found: {path}',
|
||
'log_extracted_resource_invalid': 'Extracted resources are invalid: {reason}. Flashing stopped. Check the password or package.',
|
||
'log_extract_done': 'Resources ready',
|
||
'log_extract_exception': 'Resource preparation failed: {error}',
|
||
'err_extract_wrong_password': 'Incorrect extraction password. Check the package.bin password.',
|
||
'err_extract_data': 'Package data error. The password may be wrong or package.bin may be damaged.',
|
||
'err_extract_corrupt': 'Package is damaged or incomplete. Check package.bin.',
|
||
'err_extract_failed': 'Extraction failed: {error}',
|
||
'err_extract_failed_code': 'Extraction failed (exit code {code}). Check whether the password is correct.',
|
||
'log_root_failed': 'Permission failed',
|
||
'log_permission_failed': 'Permission failed',
|
||
'log_permission_running': 'Getting permission',
|
||
'log_reboot_failed': 'Reboot failed',
|
||
'log_permission_ok': 'Permission granted',
|
||
'log_flash_readonly': 'Click Get Root first, then try again',
|
||
'log_flash_complete_count': 'Flashing complete, {count} language packages',
|
||
'log_flash_effect_after_reboot': 'Language package flashed. Reboot the device when convenient.',
|
||
'log_flash_partial': 'Partially flashed ({success}/{total})',
|
||
'log_flash_failed_item_detail': 'Flash failed: {name} - {error}',
|
||
'log_install_start': 'Installing {count} APKs...',
|
||
'log_install_done_all': 'Installation complete: all {count} succeeded',
|
||
'log_install_done_partial': 'Installation complete: {success}/{total} succeeded',
|
||
'log_install_failed': 'Installation failed',
|
||
'log_install_exception': 'Installation error: {error}',
|
||
'log_install_success_item': '✓ {name}',
|
||
'log_install_failed_item': '✗ {name}',
|
||
'log_menu_key_ready': 'Helper component installed',
|
||
'log_menu_key_install_failed': 'Helper component installation failed',
|
||
'log_menu_key_permission_failed': 'Helper component permission setup failed',
|
||
'log_quick_lang_setting': 'Setting system language to: {language} ({locale})',
|
||
'log_quick_lang_success': '✓ Language set to {language}',
|
||
'log_quick_lang_failed': '✗ Language setting failed: {output}',
|
||
'log_rebooting': 'Device rebooting...',
|
||
'log_disable_cancelled': 'Disable OTA cancelled',
|
||
'log_disable_success': 'System upgrade disabled',
|
||
'log_disable_failed': 'Failed to disable system upgrade',
|
||
'log_preclean_start': 'Cleaning preinstalled apps...',
|
||
'log_preclean_done': 'Preinstalled apps cleaned',
|
||
'log_preclean_partial': 'Some preinstalled apps failed to clean',
|
||
'log_preclean_item_done': 'Cleanup item completed: {package}',
|
||
'log_preclean_item_failed': 'Cleanup item failed: {package}',
|
||
'log_package_key_failed': 'package-key fetch failed',
|
||
'log_package_extract_success': 'Resources ready',
|
||
'log_package_extract_failed': 'package.bin extract test failed',
|
||
'log_pwd_success': 'Password query succeeded',
|
||
'log_pwd_failed': 'Password query failed: {message}',
|
||
'log_pwd_request_failed': 'Password query request failed: {error}',
|
||
'err_no_usable_apk': 'No usable APK found',
|
||
'err_zero_apk': '0KB APK found: {files}',
|
||
'err_push_failed': 'push failed: {error}',
|
||
'err_cp_failed': 'cp failed: {error}',
|
||
}
|
||
}
|
||
|
||
# 从 exe/py 所在目录查找资源文件
|
||
self.base_dir = get_app_dir()
|
||
self.adb = find_tool('adb.exe', 'adb')
|
||
self.sz = find_tool('7za.exe')
|
||
self.package_file = self._find_package_file()
|
||
self.extract_password = None
|
||
self.apps_dir = None
|
||
self.priv_apps_dir = None
|
||
self.menu_key_apk = None
|
||
self.temp_dir = None
|
||
self.api_url = "https://api.changan.softwindy.cn/api/authorizations/auth-check"
|
||
self.debug_password_api_url = "https://api.changan.softwindy.cn/api/authorizations/verify-debug-mode-password"
|
||
self.vin = None
|
||
self.vehicle_name = ""
|
||
self.device_connected = False
|
||
self._refreshing = False # 防止并发刷新
|
||
self.debug_mode = False # 调试模式
|
||
self.mazda_disable_packages = [
|
||
"com.carinno.p1",
|
||
"com.wtcl.electronicdirections",
|
||
"com.ximalaya.ting.android.car",
|
||
"com.tinnove.netease.music",
|
||
"com.migu.miguplay.car",
|
||
"cn.cmvideo.car.play",
|
||
"com.tinnove.carshow",
|
||
"com.tinnove.changba",
|
||
"com.qiyi.video.iv",
|
||
"com.changan.appmarket",
|
||
"com.incall.apps.softmanager",
|
||
]
|
||
atexit.register(self.cleanup_cache_on_exit)
|
||
|
||
# 设置样式
|
||
self.setup_styles()
|
||
self.setup_ui()
|
||
self.root.after(200, self.set_window_icon)
|
||
self.center_window()
|
||
|
||
# 检查环境
|
||
self.check_environment()
|
||
|
||
# 启动设备状态监控
|
||
self.start_device_monitor()
|
||
|
||
def set_window_icon(self):
|
||
"""Set the Tk window/taskbar icon at runtime; PyInstaller --icon only sets the exe file icon."""
|
||
try:
|
||
icon_path = find_resource("app.ico")
|
||
if icon_path.exists():
|
||
self.root.iconbitmap(str(icon_path))
|
||
self._set_windows_hwnd_icon(icon_path)
|
||
except Exception:
|
||
pass
|
||
|
||
def _set_windows_hwnd_icon(self, icon_path):
|
||
if sys.platform != 'win32':
|
||
return
|
||
try:
|
||
import ctypes
|
||
user32 = ctypes.windll.user32
|
||
hwnd = self.root.winfo_id()
|
||
image_icon = 1
|
||
lr_loadfromfile = 0x00000010
|
||
wm_seticon = 0x0080
|
||
icon_small = 0
|
||
icon_big = 1
|
||
path = str(icon_path)
|
||
small = user32.LoadImageW(None, path, image_icon, 16, 16, lr_loadfromfile)
|
||
big = user32.LoadImageW(None, path, image_icon, 32, 32, lr_loadfromfile)
|
||
if small:
|
||
user32.SendMessageW(hwnd, wm_seticon, icon_small, small)
|
||
if big:
|
||
user32.SendMessageW(hwnd, wm_seticon, icon_big, big)
|
||
except Exception:
|
||
pass
|
||
|
||
def setup_styles(self):
|
||
"""设置自定义样式"""
|
||
style = ttk.Style()
|
||
style.theme_use('clam')
|
||
|
||
# 配置主颜色
|
||
style.configure('TFrame', background=self.colors['bg_dark'])
|
||
style.configure('TLabel', background=self.colors['bg_dark'], foreground=self.colors['text'])
|
||
style.configure('TLabelframe', background=self.colors['bg_dark'], foreground=self.colors['text'])
|
||
style.configure('TLabelframe.Label', background=self.colors['bg_dark'], foreground=self.colors['accent'])
|
||
|
||
# 配置进度条
|
||
style.configure('TProgressbar',
|
||
background=self.colors['accent'],
|
||
troughcolor=self.colors['bg_light'],
|
||
borderwidth=0)
|
||
|
||
def setup_ui(self):
|
||
"""设置UI界面"""
|
||
# 配置根窗口
|
||
self.root.title(self.t('title'))
|
||
self.root.configure(bg=self.colors['bg_dark'])
|
||
|
||
# 创建主框架
|
||
main_frame = tk.Frame(self.root, bg=self.colors['bg_dark'])
|
||
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
|
||
|
||
# 顶部标题栏
|
||
title_frame = tk.Frame(main_frame, bg=self.colors['bg_dark'], height=45)
|
||
title_frame.pack(fill=tk.X, pady=(0, 10))
|
||
title_frame.pack_propagate(False)
|
||
|
||
# 标题
|
||
title_inner = tk.Frame(title_frame, bg=self.colors['bg_dark'])
|
||
title_inner.place(relx=0.5, rely=0.5, anchor='center')
|
||
self.title_icon_label = tk.Label(title_inner,
|
||
text="🚗",
|
||
font=('Microsoft YaHei', 17, 'bold'),
|
||
fg=self.colors['accent'],
|
||
bg=self.colors['bg_dark'])
|
||
self.title_icon_label.grid(row=0, column=0, padx=(0, 8), sticky='e')
|
||
self.title_label = tk.Label(title_inner,
|
||
text=self.t('title'),
|
||
font=('Microsoft YaHei', 18, 'bold'),
|
||
fg=self.colors['accent'],
|
||
bg=self.colors['bg_dark'])
|
||
self.title_label.grid(row=0, column=1, sticky='w')
|
||
|
||
self.btn_lang_switch = tk.Button(title_frame, text="EN",
|
||
command=self.toggle_lang,
|
||
font=('Microsoft YaHei', 9, 'bold'),
|
||
fg='white',
|
||
bg=self.colors['accent'],
|
||
activebackground=self.colors['accent_hover'],
|
||
activeforeground='white',
|
||
relief=tk.FLAT,
|
||
cursor='hand2',
|
||
width=8,
|
||
height=1)
|
||
self.btn_lang_switch.place(relx=1.0, rely=0.5, x=-2, anchor='e')
|
||
|
||
# 工程密码查询区域
|
||
pwd_query_frame = tk.Frame(main_frame, bg=self.colors['bg_light'], relief=tk.RAISED, bd=1)
|
||
pwd_query_frame.pack(fill=tk.X, pady=(0, 5), padx=5)
|
||
|
||
self.pwd_query_label = tk.Label(pwd_query_frame, text=self.t('pwd_query_label'),
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text'],
|
||
bg=self.colors['bg_light'])
|
||
self.pwd_query_label.pack(side=tk.LEFT, padx=(10, 5), pady=5)
|
||
|
||
self.vin_input = tk.Entry(pwd_query_frame,
|
||
font=('Consolas', 9),
|
||
bg='#2d2d3d',
|
||
fg='#636e72',
|
||
insertbackground='white',
|
||
relief=tk.FLAT,
|
||
width=20)
|
||
self.vin_input.insert(0, self.t('vin_placeholder'))
|
||
self.vin_input.bind("<FocusIn>", self._on_vin_input_focus_in)
|
||
self.vin_input.bind("<FocusOut>", self._on_vin_input_focus_out)
|
||
self.vin_input.pack(side=tk.LEFT, padx=5, pady=5)
|
||
|
||
self.btn_query_pwd = tk.Button(pwd_query_frame, text=self.t('btn_query_pwd'),
|
||
command=self.query_password_by_vin,
|
||
font=('Microsoft YaHei', 8),
|
||
fg='white',
|
||
bg=self.colors['accent'],
|
||
activebackground=self.colors['accent_hover'],
|
||
activeforeground='white',
|
||
relief=tk.FLAT,
|
||
cursor='hand2')
|
||
self.btn_query_pwd.pack(side=tk.LEFT, padx=5, pady=5)
|
||
|
||
self.pwd_result_label = tk.Label(pwd_query_frame, text="",
|
||
font=('Microsoft YaHei', 9, 'bold'),
|
||
fg=self.colors['success'],
|
||
bg=self.colors['bg_light'])
|
||
self.pwd_result_label.pack(side=tk.LEFT, padx=10, pady=5)
|
||
|
||
# 按钮区域(两排,每排5个)
|
||
button_frame = tk.Frame(main_frame, bg=self.colors['bg_light'], relief=tk.RAISED, bd=1)
|
||
button_frame.pack(fill=tk.X, pady=(0, 10), padx=5)
|
||
|
||
# 按钮样式参数
|
||
btn_params = {
|
||
'font': ('Microsoft YaHei', 9),
|
||
'fg': 'white',
|
||
'relief': tk.FLAT,
|
||
'cursor': 'hand2',
|
||
'height': 1,
|
||
'width': 14
|
||
}
|
||
|
||
# 第一排按钮
|
||
row1_frame = tk.Frame(button_frame, bg=self.colors['bg_light'])
|
||
row1_frame.pack(pady=(8, 4))
|
||
|
||
self.btn_root = tk.Button(row1_frame, text="🔓 获取权限",
|
||
command=self.get_root_permission,
|
||
bg=self.colors['success'],
|
||
**btn_params)
|
||
self.btn_root.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.btn_push = tk.Button(row1_frame, text="📦 刷入语言包",
|
||
command=self.push_all_apks,
|
||
bg=self.colors['accent'],
|
||
**btn_params)
|
||
self.btn_push.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.btn_install_all = tk.Button(row1_frame, text="📱 安装App",
|
||
command=self.install_apps,
|
||
bg=self.colors['accent'],
|
||
**btn_params)
|
||
self.btn_install_all.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.btn_language = tk.Button(row1_frame, text="🌐 语言设置",
|
||
command=self.open_language_quick_set,
|
||
bg=self.colors['accent'],
|
||
**btn_params)
|
||
self.btn_language.pack(side=tk.LEFT, padx=4)
|
||
|
||
# 第二排按钮
|
||
row2_frame = tk.Frame(button_frame, bg=self.colors['bg_light'])
|
||
row2_frame.pack(pady=(4, 8))
|
||
|
||
self.btn_timezone = tk.Button(row2_frame, text="⏰ 时区设置",
|
||
command=self.open_timezone_settings,
|
||
bg=self.colors['accent'],
|
||
**btn_params)
|
||
self.btn_timezone.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.btn_settings = tk.Button(row2_frame, text="⚙️ 安卓设置",
|
||
command=self.open_android_settings,
|
||
bg=self.colors['accent'],
|
||
**btn_params)
|
||
self.btn_settings.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.btn_reboot = tk.Button(row2_frame, text="🔄 重启设备",
|
||
command=self.reboot_device,
|
||
bg=self.colors['warning'],
|
||
**btn_params)
|
||
self.btn_reboot.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.btn_exit = tk.Button(row2_frame, text="❌ 禁用升级",
|
||
command=self.on_disable_upgrade,
|
||
bg=self.colors['error'],
|
||
**btn_params)
|
||
self.btn_exit.pack(side=tk.LEFT, padx=4)
|
||
|
||
self.debug_button_frame = tk.Frame(button_frame, bg=self.colors['bg_light'])
|
||
self.btn_debug_extract = tk.Button(self.debug_button_frame, text=self.t('btn_debug_extract'),
|
||
command=self.debug_test_package_extract,
|
||
bg=self.colors['info'],
|
||
**btn_params)
|
||
self.btn_debug_extract.pack(side=tk.LEFT, padx=4)
|
||
|
||
# 设备状态栏(横条)
|
||
status_bar_frame = tk.Frame(main_frame, bg=self.colors['bg_light'], relief=tk.RAISED, bd=1)
|
||
status_bar_frame.pack(fill=tk.X, pady=(0, 5))
|
||
|
||
# 状态指示器
|
||
status_indicator_frame = tk.Frame(status_bar_frame, bg=self.colors['bg_light'])
|
||
status_indicator_frame.pack(side=tk.LEFT, padx=10, pady=5)
|
||
|
||
self.status_indicator = tk.Canvas(status_indicator_frame, width=10, height=10,
|
||
bg=self.colors['bg_light'], highlightthickness=0)
|
||
self.status_indicator.pack(side=tk.LEFT)
|
||
self.status_dot = self.status_indicator.create_oval(2, 2, 8, 8, fill='#636e72')
|
||
|
||
self.device_label = tk.Label(status_indicator_frame, text="设备:",
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text'],
|
||
bg=self.colors['bg_light'])
|
||
self.device_label.pack(side=tk.LEFT, padx=(5, 3))
|
||
|
||
self.device_status_label = tk.Label(status_indicator_frame, text=self.t('status_detecting'),
|
||
font=('Microsoft YaHei', 9, 'bold'),
|
||
fg='#636e72',
|
||
bg=self.colors['bg_light'],
|
||
anchor='w', width=4)
|
||
self.device_status_label.pack(side=tk.LEFT)
|
||
|
||
# VIN信息
|
||
vin_frame = tk.Frame(status_bar_frame, bg=self.colors['bg_light'])
|
||
vin_frame.pack(side=tk.LEFT, padx=20, pady=5)
|
||
self.vin_label_title = tk.Label(vin_frame, text="VIN码:",
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text'],
|
||
bg=self.colors['bg_light'])
|
||
self.vin_label_title.pack(side=tk.LEFT)
|
||
self.vin_label = tk.Label(vin_frame, text=self.t('vin_none'),
|
||
font=('Microsoft YaHei', 9, 'bold'),
|
||
fg='#636e72',
|
||
bg=self.colors['bg_light'],
|
||
anchor='w', width=17)
|
||
self.vin_label.pack(side=tk.LEFT, padx=(5, 0))
|
||
|
||
# 授权状态
|
||
auth_frame = tk.Frame(status_bar_frame, bg=self.colors['bg_light'])
|
||
auth_frame.pack(side=tk.LEFT, padx=20, pady=5)
|
||
self.auth_label_title = tk.Label(auth_frame, text="授权:",
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text'],
|
||
bg=self.colors['bg_light'])
|
||
self.auth_label_title.pack(side=tk.LEFT)
|
||
self.auth_label = tk.Label(auth_frame, text=self.t('auth_none'),
|
||
font=('Microsoft YaHei', 9, 'bold'),
|
||
fg='#636e72',
|
||
bg=self.colors['bg_light'],
|
||
anchor='w', width=4)
|
||
self.auth_label.pack(side=tk.LEFT, padx=(5, 0))
|
||
|
||
# 刷新按钮
|
||
self.btn_refresh = tk.Button(status_bar_frame, text="🔄 检查",
|
||
command=self.refresh_device_status,
|
||
font=('Microsoft YaHei', 8),
|
||
fg=self.colors['accent'],
|
||
bg=self.colors['bg_light'],
|
||
relief=tk.FLAT,
|
||
cursor='hand2')
|
||
self.btn_refresh.pack(side=tk.RIGHT, padx=10, pady=5)
|
||
|
||
# 提示信息区域(设备状态下方)
|
||
tips_frame = tk.Frame(main_frame, bg=self.colors['bg_light'], relief=tk.RAISED, bd=1)
|
||
tips_frame.pack(fill=tk.X, pady=(5, 5), padx=5)
|
||
|
||
tips = [self.t('tip_1'), self.t('tip_2'), self.t('tip_3')]
|
||
|
||
for i, tip in enumerate(tips):
|
||
tip_row = tk.Frame(tips_frame, bg=self.colors['bg_light'])
|
||
tip_row.pack(fill=tk.X, padx=10, pady=(5 if i == 0 else 0, 5 if i == len(tips) - 1 else 0))
|
||
label = tk.Label(tip_row, text=tip,
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['warning'],
|
||
bg=self.colors['bg_light'],
|
||
wraplength=600,
|
||
justify=tk.LEFT)
|
||
label.pack(side=tk.LEFT)
|
||
setattr(self, f'tip_label_{i + 1}', label)
|
||
|
||
# 解压进度条框架
|
||
progress_frame = tk.Frame(main_frame, bg=self.colors['bg_dark'])
|
||
progress_frame.pack(fill=tk.X, pady=(5, 5))
|
||
|
||
self.progress_label = tk.Label(progress_frame, text="",
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text_secondary'],
|
||
bg=self.colors['bg_dark'])
|
||
self.progress_label.pack()
|
||
|
||
self.progress = ttk.Progressbar(progress_frame, mode='determinate', style='TProgressbar')
|
||
self.progress.pack(fill=tk.X, pady=(2, 0))
|
||
|
||
# 推送进度条
|
||
self.push_progress_label = tk.Label(progress_frame, text="",
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text_secondary'],
|
||
bg=self.colors['bg_dark'])
|
||
|
||
self.push_progress = ttk.Progressbar(progress_frame, mode='determinate', style='TProgressbar')
|
||
|
||
# 日志区域(下方)
|
||
log_card = tk.Frame(main_frame, bg=self.colors['bg_light'], relief=tk.RAISED, bd=1)
|
||
log_card.pack(fill=tk.BOTH, expand=True, pady=(5, 0))
|
||
|
||
# 日志标题栏
|
||
log_title_frame = tk.Frame(log_card, bg=self.colors['bg_dark'], height=30)
|
||
log_title_frame.pack(fill=tk.X)
|
||
log_title_frame.pack_propagate(False)
|
||
|
||
self.log_title_label = tk.Label(log_title_frame, text="📋 运行日志",
|
||
font=('Microsoft YaHei', 10, 'bold'),
|
||
fg=self.colors['accent'],
|
||
bg=self.colors['bg_dark'])
|
||
self.log_title_label.pack(side=tk.LEFT, padx=10)
|
||
|
||
self.btn_clear = tk.Button(log_title_frame, text="🗑 清空日志",
|
||
command=self.clear_log,
|
||
font=('Microsoft YaHei', 8),
|
||
fg=self.colors['text_secondary'],
|
||
bg=self.colors['bg_dark'],
|
||
relief=tk.FLAT,
|
||
cursor='hand2')
|
||
self.btn_clear.pack(side=tk.RIGHT, padx=10)
|
||
|
||
# 日志文本框
|
||
text_frame = tk.Frame(log_card, bg=self.colors['bg_light'])
|
||
text_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
|
||
|
||
self.log_text = scrolledtext.ScrolledText(text_frame,
|
||
height=12,
|
||
wrap=tk.WORD,
|
||
font=('Consolas', 9),
|
||
bg='#2d2d3d',
|
||
fg='#e0e0e0',
|
||
insertbackground='white',
|
||
relief=tk.FLAT,
|
||
borderwidth=0)
|
||
self.log_text.pack(fill=tk.BOTH, expand=True)
|
||
|
||
# 配置日志颜色标签
|
||
self.log_text.tag_config('INFO', foreground='#74b9ff')
|
||
self.log_text.tag_config('SUCCESS', foreground='#55efc4')
|
||
self.log_text.tag_config('ERROR', foreground='#ff7675')
|
||
self.log_text.tag_config('WARNING', foreground='#ffeaa7')
|
||
self.log_text.tag_config('CMD', foreground='#a29bfe')
|
||
|
||
# 底部状态栏
|
||
bottom_status = tk.Frame(main_frame, bg=self.colors['bg_light'], height=22)
|
||
bottom_status.pack(fill=tk.X, pady=(5, 0))
|
||
bottom_status.pack_propagate(False)
|
||
|
||
self.status_text = tk.Label(bottom_status, text="就绪",
|
||
font=('Microsoft YaHei', 8),
|
||
fg=self.colors['text_secondary'],
|
||
bg=self.colors['bg_light'])
|
||
self.status_text.pack(side=tk.LEFT, padx=10)
|
||
|
||
# 调试模式快捷键
|
||
self.root.bind('<Control-Shift-D>', self._toggle_debug)
|
||
self.root.bind('<Control-Shift-E>', self._debug_test_extract)
|
||
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
|
||
|
||
# 绑定悬停效果
|
||
self.bind_hover_effects()
|
||
|
||
def bind_hover_effects(self):
|
||
"""绑定按钮悬停效果"""
|
||
buttons = [self.btn_root, self.btn_push, self.btn_install_all,
|
||
self.btn_language, self.btn_timezone, self.btn_settings,
|
||
self.btn_reboot, self.btn_clear, self.btn_exit,
|
||
self.btn_debug_extract]
|
||
|
||
for btn in buttons:
|
||
original_bg = btn.cget('bg')
|
||
def on_enter(e, btn=btn, bg=original_bg):
|
||
btn.config(bg=self.lighten_color(bg))
|
||
def on_leave(e, btn=btn, bg=original_bg):
|
||
btn.config(bg=bg)
|
||
btn.bind('<Enter>', on_enter)
|
||
btn.bind('<Leave>', on_leave)
|
||
|
||
def lighten_color(self, color):
|
||
"""调亮颜色"""
|
||
if color == self.colors['accent']:
|
||
return self.colors['accent_hover']
|
||
elif color == self.colors['warning']:
|
||
return '#feca57'
|
||
elif color == self.colors['info']:
|
||
return '#0984e3'
|
||
elif color == self.colors['error']:
|
||
return '#e17055'
|
||
elif color == self.colors['success']:
|
||
return '#00a884'
|
||
return color
|
||
|
||
def center_window(self):
|
||
"""将窗口居中显示在屏幕上"""
|
||
self.root.update_idletasks()
|
||
screen_w = self.root.winfo_screenwidth()
|
||
screen_h = self.root.winfo_screenheight()
|
||
win_w = self.root.winfo_reqwidth()
|
||
win_h = self.root.winfo_reqheight()
|
||
x = (screen_w - win_w) // 2
|
||
y = (screen_h - win_h) // 2
|
||
self.root.geometry(f"+{x}+{y}")
|
||
|
||
def run_on_ui_thread(self, func, *args, **kwargs):
|
||
"""将函数调度到主线程执行,确保线程安全"""
|
||
self.root.after(0, lambda: func(*args, **kwargs))
|
||
|
||
def _adb_cmd(self):
|
||
return subprocess.list2cmdline([self.adb])
|
||
|
||
def _find_package_file(self):
|
||
return find_resource("package.bin")
|
||
|
||
def t(self, key):
|
||
"""获取翻译文本"""
|
||
return self.T.get(self.lang, self.T['zh']).get(key, key)
|
||
|
||
def tf(self, key, **kwargs):
|
||
try:
|
||
return self.t(key).format(**kwargs)
|
||
except Exception:
|
||
return self.t(key)
|
||
|
||
def is_placeholder_vin(self, value):
|
||
return value in (
|
||
self.T['zh'].get('vin_placeholder'),
|
||
self.T['en'].get('vin_placeholder'),
|
||
)
|
||
|
||
def toggle_lang(self):
|
||
"""切换语言"""
|
||
self.lang = 'en' if self.lang == 'zh' else 'zh'
|
||
self.btn_lang_switch.config(text=self.t('lang_en') if self.lang == 'zh' else self.t('lang_zh'))
|
||
self._refresh_ui_texts()
|
||
self.log(self.t('log_lang_switched'), "INFO")
|
||
|
||
def _refresh_ui_texts(self):
|
||
"""刷新所有UI文本"""
|
||
t = self.t
|
||
self.root.title(t('title'))
|
||
widgets = [
|
||
(getattr(self, 'title_label', None), 'title', None),
|
||
(getattr(self, 'btn_root', None), 'btn_root', None),
|
||
(getattr(self, 'btn_push', None), 'btn_push', None),
|
||
(getattr(self, 'btn_install_all', None), 'btn_install', None),
|
||
(getattr(self, 'btn_language', None), 'btn_language', None),
|
||
(getattr(self, 'btn_timezone', None), 'btn_timezone', None),
|
||
(getattr(self, 'btn_settings', None), 'btn_settings', None),
|
||
(getattr(self, 'btn_reboot', None), 'btn_reboot', None),
|
||
(getattr(self, 'btn_exit', None), 'btn_disable_upgrade', None),
|
||
(getattr(self, 'btn_debug_extract', None), 'btn_debug_extract', None),
|
||
(getattr(self, 'btn_query_pwd', None), 'btn_query_pwd', None),
|
||
(getattr(self, 'btn_clear', None), 'btn_clear_log', None),
|
||
(getattr(self, 'pwd_query_label', None), 'pwd_query_label', None),
|
||
(getattr(self, 'log_title_label', None), 'log_title', None),
|
||
(getattr(self, 'device_label', None), 'device_label', None),
|
||
(getattr(self, 'vin_label_title', None), 'vin_label', None),
|
||
(getattr(self, 'auth_label_title', None), 'auth_label', None),
|
||
(getattr(self, 'btn_refresh', None), 'btn_refresh', None),
|
||
(getattr(self, 'hint_label', None), 'hint_factory', None),
|
||
(getattr(self, 'tip_label_1', None), 'tip_1', None),
|
||
(getattr(self, 'tip_label_2', None), 'tip_2', None),
|
||
(getattr(self, 'tip_label_3', None), 'tip_3', None),
|
||
]
|
||
for w, key, _ in widgets:
|
||
if w:
|
||
w.config(text=t(key))
|
||
if getattr(self, 'status_text', None):
|
||
self.status_text.config(text=t('status_debug') if self.debug_mode else t('status_ready'))
|
||
self.btn_lang_switch.config(text=t('lang_en') if self.lang == 'zh' else t('lang_zh'))
|
||
if getattr(self, 'vin_input', None) and self.is_placeholder_vin(self.vin_input.get()):
|
||
self.vin_input.delete(0, tk.END)
|
||
self.vin_input.insert(0, t('vin_placeholder'))
|
||
self._update_device_status_impl(
|
||
self.device_connected,
|
||
self.vin,
|
||
getattr(self, '_last_authorized', False)
|
||
)
|
||
|
||
def set_debug_buttons_visible(self, visible):
|
||
if not hasattr(self, 'debug_button_frame'):
|
||
return
|
||
if visible:
|
||
self.debug_button_frame.pack(pady=(0, 8))
|
||
else:
|
||
self.debug_button_frame.pack_forget()
|
||
|
||
def _log_impl(self, message, level="INFO"):
|
||
"""日志写入的实际实现(必须在主线程调用)"""
|
||
timestamp = datetime.now().strftime("%H:%M:%S")
|
||
log_entry = f"[{timestamp}] [{level}] {message}\n"
|
||
self.log_text.insert(tk.END, log_entry, level)
|
||
self.log_text.see(tk.END)
|
||
|
||
def log(self, message, level="INFO"):
|
||
"""添加日志(线程安全)"""
|
||
self.run_on_ui_thread(self._log_impl, message, level)
|
||
|
||
def clear_log(self):
|
||
"""清空日志"""
|
||
self.log_text.delete(1.0, tk.END)
|
||
self.log(self.t('info_log_cleared'), "INFO")
|
||
|
||
def _show_progress_impl(self, show=True, is_push=False):
|
||
"""显示/隐藏进度条的实际实现(必须在主线程调用)"""
|
||
if is_push:
|
||
if show:
|
||
self.push_progress_label.pack()
|
||
self.push_progress.pack(fill=tk.X, pady=(2, 0))
|
||
self.push_progress['value'] = 0
|
||
else:
|
||
self.push_progress_label.pack_forget()
|
||
self.push_progress.pack_forget()
|
||
else:
|
||
if show:
|
||
self.progress_label.pack()
|
||
self.progress.pack(fill=tk.X, pady=(2, 0))
|
||
self.progress['value'] = 0
|
||
else:
|
||
self.progress_label.pack_forget()
|
||
self.progress.pack_forget()
|
||
|
||
def show_progress(self, show=True, is_push=False):
|
||
"""显示/隐藏进度条(线程安全)"""
|
||
self.run_on_ui_thread(self._show_progress_impl, show, is_push)
|
||
|
||
def _update_progress_impl(self, value, max_value=100, label="", is_push=False):
|
||
"""更新进度条的实际实现(必须在主线程调用)"""
|
||
if is_push:
|
||
percent = (value / max_value) * 100
|
||
self.push_progress['value'] = percent
|
||
self.push_progress_label.config(text=f"{label}: {value}/{max_value} ({percent:.1f}%)")
|
||
else:
|
||
percent = (value / max_value) * 100
|
||
self.progress['value'] = percent
|
||
self.progress_label.config(text=f"{label}: {value}/{max_value} ({percent:.1f}%)")
|
||
self.root.update_idletasks()
|
||
|
||
def update_progress(self, value, max_value=100, label="", is_push=False):
|
||
"""更新进度条(线程安全)"""
|
||
self.run_on_ui_thread(self._update_progress_impl, value, max_value, label, is_push)
|
||
|
||
def update_device_status(self, connected, vin=None, authorized=False):
|
||
"""更新设备状态显示(线程安全:立即设状态变量,UI走主线程)"""
|
||
self.device_connected = connected
|
||
if vin is not None:
|
||
self.vin = vin
|
||
self.run_on_ui_thread(self._update_device_status_impl, connected, vin, authorized)
|
||
|
||
def _update_device_status_impl(self, connected, vin, authorized):
|
||
"""设备状态UI更新的实际实现(必须在主线程调用)"""
|
||
self._last_authorized = authorized
|
||
t = self.t
|
||
if connected:
|
||
self.status_indicator.itemconfig(self.status_dot, fill=self.colors['success'])
|
||
self.device_status_label.config(text=t('status_connected'), fg=self.colors['success'])
|
||
if vin:
|
||
self.vin_label.config(text=vin, fg=self.colors['success'])
|
||
if authorized:
|
||
self.auth_label.config(text=t('auth_yes'), fg=self.colors['success'])
|
||
else:
|
||
self.auth_label.config(text=t('auth_no'), fg=self.colors['error'])
|
||
else:
|
||
self.vin_label.config(text=t('vin_none'), fg=self.colors['error'])
|
||
self.auth_label.config(text=t('auth_none'), fg=self.colors['error'])
|
||
else:
|
||
self.status_indicator.itemconfig(self.status_dot, fill=self.colors['error'])
|
||
self.device_status_label.config(text=t('status_disconnected'), fg=self.colors['error'])
|
||
self.vin_label.config(text=t('vin_none'), fg=self.colors['error'])
|
||
self.auth_label.config(text=t('auth_none'), fg=self.colors['error'])
|
||
|
||
def check_device_connection(self):
|
||
"""检查设备是否连接"""
|
||
if self.debug_mode:
|
||
return True
|
||
if not self.device_connected:
|
||
messagebox.showwarning(self.t('warn_no_device'), self.t('warn_connect_first'))
|
||
return False
|
||
return True
|
||
|
||
def start_device_monitor(self):
|
||
"""启动设备状态监控(每5秒检查一次)"""
|
||
def monitor():
|
||
while True:
|
||
try:
|
||
result = subprocess.run(f'{self._adb_cmd()} -d devices', shell=True, capture_output=True, text=True)
|
||
lines = result.stdout.strip().split('\n')
|
||
devices = [line for line in lines[1:] if line.strip() and 'device' in line and 'offline' not in line]
|
||
|
||
if devices and not self.device_connected and not self._refreshing:
|
||
# 设备新连接,刷新状态
|
||
self.refresh_device_status()
|
||
elif not devices and self.device_connected:
|
||
# 设备断开连接
|
||
self.update_device_status(False)
|
||
self.log(self.t('log_device_disconnected'), "WARNING")
|
||
|
||
time.sleep(5)
|
||
except:
|
||
time.sleep(5)
|
||
|
||
threading.Thread(target=monitor, daemon=True).start()
|
||
|
||
def get_root_permission(self):
|
||
"""获取 root/remount 权限,不触发重启。"""
|
||
if not self.check_device_connection():
|
||
return
|
||
|
||
def get_root():
|
||
self.show_progress(True, is_push=False)
|
||
self.log(self.t('log_permission_running'), "INFO")
|
||
|
||
ok_root, out_root = self.run_adb_command('adb -d root')
|
||
if not ok_root:
|
||
self.log(self.t('log_root_failed'), "ERROR")
|
||
self.show_progress(False, is_push=False)
|
||
return
|
||
|
||
time.sleep(1)
|
||
|
||
ok_remount, out_remount = self.run_adb_password_command('adb -d remount', timeout=60)
|
||
if not ok_remount:
|
||
self.log(self.t('log_permission_failed'), "ERROR")
|
||
self.show_progress(False, is_push=False)
|
||
return
|
||
|
||
self.log(self.t('log_permission_ok'), "SUCCESS")
|
||
|
||
self.show_progress(False, is_push=False)
|
||
|
||
threading.Thread(target=get_root, daemon=True).start()
|
||
|
||
def check_package_extracted(self):
|
||
"""检查语言包是否已解压"""
|
||
has_app = self.apps_dir and self.apps_dir.exists() and len(list(self.apps_dir.glob("*.apk"))) > 0
|
||
has_priv = self.priv_apps_dir and self.priv_apps_dir.exists() and len(list(self.priv_apps_dir.glob("*.apk"))) > 0
|
||
if has_app or has_priv:
|
||
ok, reason = self._validate_extracted_apks()
|
||
if not ok:
|
||
self.log(self.tf('log_cache_invalid', reason=reason), "ERROR")
|
||
self._clear_extracted_cache()
|
||
return False
|
||
return has_app or has_priv
|
||
|
||
def _validate_extracted_apks(self):
|
||
apks = []
|
||
if self.apps_dir and self.apps_dir.exists():
|
||
apks.extend(self.apps_dir.glob("*.apk"))
|
||
if self.priv_apps_dir and self.priv_apps_dir.exists():
|
||
apks.extend(self.priv_apps_dir.glob("*.apk"))
|
||
if not apks:
|
||
return False, self.t('err_no_usable_apk')
|
||
|
||
zero_apks = [apk.name for apk in apks if apk.stat().st_size <= 0]
|
||
if zero_apks:
|
||
preview = ", ".join(zero_apks[:5])
|
||
suffix = "..." if len(zero_apks) > 5 else ""
|
||
return False, self.tf('err_zero_apk', files=f"{preview}{suffix}")
|
||
return True, ""
|
||
|
||
def _clear_extracted_cache(self):
|
||
if self.temp_dir and self.temp_dir.exists():
|
||
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
||
time.sleep(0.5)
|
||
self.apps_dir = None
|
||
self.priv_apps_dir = None
|
||
self.menu_key_apk = None
|
||
self.temp_dir = None
|
||
|
||
def _cache_dir_path(self):
|
||
local_appdata = os.environ.get('LOCALAPPDATA', os.path.expanduser('~\\AppData\\Local'))
|
||
return Path(local_appdata) / ".cache" / "system" / ".android" / self.CACHE_DIR_NAME
|
||
|
||
def _scan_root_level_apks(self):
|
||
if not self.apps_dir:
|
||
return
|
||
root_dir = self.apps_dir.parent
|
||
menu_key_candidate = root_dir / "MenuKey-release.apk"
|
||
if menu_key_candidate.exists():
|
||
self.menu_key_apk = menu_key_candidate
|
||
|
||
def cleanup_cache_on_exit(self):
|
||
self._clear_extracted_cache()
|
||
|
||
def on_close(self):
|
||
self.cleanup_cache_on_exit()
|
||
self.root.destroy()
|
||
|
||
def _format_extract_error(self, err_msg, return_code):
|
||
text = (err_msg or "").lower()
|
||
if any(marker in text for marker in (
|
||
"wrong password",
|
||
"incorrect password",
|
||
"password is incorrect",
|
||
"data error in encrypted file",
|
||
"can not open encrypted archive",
|
||
)):
|
||
return self.t('err_extract_wrong_password')
|
||
if "data error" in text:
|
||
return self.t('err_extract_data')
|
||
if "headers error" in text or "unexpected end" in text:
|
||
return self.t('err_extract_corrupt')
|
||
if err_msg.strip():
|
||
return self.tf('err_extract_failed', error=err_msg.strip()[:300])
|
||
return self.tf('err_extract_failed_code', code=return_code)
|
||
|
||
def _decode_7z_output(self, output):
|
||
for enc in ('gbk', 'utf-8'):
|
||
try:
|
||
return output.decode(enc)
|
||
except UnicodeDecodeError:
|
||
continue
|
||
return output.decode('utf-8', errors='replace')
|
||
|
||
def _seven_zip_supports_progress_stream(self):
|
||
try:
|
||
result = subprocess.run(
|
||
[self.sz],
|
||
capture_output=True,
|
||
text=True,
|
||
errors='ignore',
|
||
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
|
||
)
|
||
return '-bs{o|e|p}' in (result.stdout + result.stderr)
|
||
except Exception:
|
||
return False
|
||
|
||
def _extract_with_7za_progress(self):
|
||
self.update_progress(0, 100, self.t('progress_resource_loading'))
|
||
cmd = [
|
||
self.sz, 'x', str(self.package_file),
|
||
f'-p{self.extract_password}',
|
||
f'-o{self.temp_dir}', '-y'
|
||
]
|
||
use_progress_switch = self._seven_zip_supports_progress_stream()
|
||
if use_progress_switch:
|
||
cmd.extend(['-bsp1', '-bso0', '-bse1'])
|
||
|
||
proc = subprocess.Popen(
|
||
cmd,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.STDOUT,
|
||
stdin=subprocess.DEVNULL,
|
||
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0,
|
||
bufsize=0
|
||
)
|
||
|
||
output = bytearray()
|
||
last_percent = -1
|
||
while True:
|
||
chunk = proc.stdout.read(1) if proc.stdout else b''
|
||
if not chunk:
|
||
if proc.poll() is not None:
|
||
break
|
||
time.sleep(0.05)
|
||
continue
|
||
|
||
output.extend(chunk)
|
||
if len(output) > 60000:
|
||
del output[:-60000]
|
||
|
||
matches = re.findall(rb'(\d{1,3})%', bytes(output[-512:]))
|
||
if matches:
|
||
percent = min(100, int(matches[-1]))
|
||
if percent != last_percent:
|
||
last_percent = percent
|
||
self.update_progress(
|
||
percent,
|
||
100,
|
||
self.tf('progress_extracting_percent', percent=percent)
|
||
)
|
||
|
||
return_code = proc.wait()
|
||
decoded_output = self._decode_7z_output(bytes(output))
|
||
if return_code == 0:
|
||
self.update_progress(100, 100, self.t('progress_resource_done'))
|
||
return True, decoded_output
|
||
if use_progress_switch and "incorrect command line" in decoded_output.lower():
|
||
return self._extract_with_7za_basic()
|
||
return False, decoded_output
|
||
|
||
def _extract_with_7za_basic(self):
|
||
cmd = [
|
||
self.sz, 'x', str(self.package_file),
|
||
f'-p{self.extract_password}',
|
||
f'-o{self.temp_dir}', '-y'
|
||
]
|
||
result = subprocess.run(
|
||
cmd,
|
||
capture_output=True,
|
||
stdin=subprocess.DEVNULL,
|
||
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
|
||
)
|
||
decoded_output = self._decode_7z_output(result.stdout + result.stderr)
|
||
if result.returncode == 0:
|
||
self.update_progress(100, 100, self.t('progress_resource_done'))
|
||
return True, decoded_output
|
||
return False, decoded_output
|
||
|
||
def extract_package_silent(self):
|
||
"""Extract package.bin silently with progress."""
|
||
if not self.package_file.exists():
|
||
self.log(self.tf('log_package_missing', path=self.package_file), "ERROR")
|
||
return False
|
||
|
||
if not self.extract_password:
|
||
self.log(self.t('log_extract_password_missing'), "ERROR")
|
||
return False
|
||
|
||
if not os.path.exists(self.sz):
|
||
self.log(self.tf('log_7za_missing', path=self.sz), "ERROR")
|
||
return False
|
||
|
||
try:
|
||
hidden_path = self._cache_dir_path().parent
|
||
hidden_path.mkdir(parents=True, exist_ok=True)
|
||
|
||
self.temp_dir = self._cache_dir_path()
|
||
|
||
if self.temp_dir.exists():
|
||
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
||
time.sleep(0.5)
|
||
|
||
self.temp_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
if sys.platform == 'win32':
|
||
subprocess.run(f'attrib +h "{self.temp_dir.parent}"', shell=True, capture_output=True)
|
||
subprocess.run(f'attrib +h "{self.temp_dir}"', shell=True, capture_output=True)
|
||
|
||
self.log(self.t('info_extracting'), "INFO")
|
||
|
||
ok, err_msg = self._extract_with_7za_progress()
|
||
if not ok:
|
||
self.log(self._format_extract_error(err_msg, 1), "ERROR")
|
||
self._clear_extracted_cache()
|
||
return False
|
||
|
||
self.apps_dir = None
|
||
self.priv_apps_dir = None
|
||
self.menu_key_apk = None
|
||
|
||
app_candidates = list(self.temp_dir.rglob("app")) or list(self.temp_dir.rglob("apps"))
|
||
if app_candidates:
|
||
self.apps_dir = app_candidates[0]
|
||
self._scan_root_level_apks()
|
||
|
||
priv_app_candidates = list(self.temp_dir.rglob("priv-app")) or list(self.temp_dir.rglob("priv-apps"))
|
||
if priv_app_candidates:
|
||
self.priv_apps_dir = priv_app_candidates[0]
|
||
|
||
if not self.apps_dir and not self.priv_apps_dir:
|
||
self.log(self.t('warn_no_app_dir'), "WARNING")
|
||
self._clear_extracted_cache()
|
||
return False
|
||
|
||
ok, reason = self._validate_extracted_apks()
|
||
if not ok:
|
||
self.log(self.tf('log_extracted_resource_invalid', reason=reason), "ERROR")
|
||
self._clear_extracted_cache()
|
||
return False
|
||
self.log(self.t('log_extract_done'), "SUCCESS")
|
||
return True
|
||
|
||
except Exception as e:
|
||
if getattr(self, 'debug_mode', False):
|
||
self.log(self.tf('log_extract_exception', error=str(e)), "ERROR")
|
||
import traceback
|
||
self.log(traceback.format_exc(), "ERROR")
|
||
else:
|
||
self.log(self.t('err_extract_user'), "ERROR")
|
||
self._clear_extracted_cache()
|
||
return False
|
||
|
||
def check_environment(self):
|
||
"""检查环境"""
|
||
try:
|
||
result = subprocess.run(f'{self._adb_cmd()} version', shell=True, capture_output=True, text=True)
|
||
if result.returncode == 0:
|
||
self.refresh_device_status()
|
||
if not self.package_file.exists():
|
||
self.log(self.tf('log_package_missing', path=self.package_file), "WARNING")
|
||
else:
|
||
self._try_reuse_extracted()
|
||
else:
|
||
self.log(self.t('log_adb_missing'), "ERROR")
|
||
except FileNotFoundError:
|
||
self.log(self.t('log_adb_missing'), "ERROR")
|
||
|
||
def _try_reuse_extracted(self):
|
||
"""检查磁盘上是否已有解压好的资源,有则直接复用"""
|
||
cache_dir = self._cache_dir_path()
|
||
if not cache_dir.exists():
|
||
return
|
||
|
||
app_candidates = list(cache_dir.rglob("app")) or list(cache_dir.rglob("apps"))
|
||
priv_candidates = list(cache_dir.rglob("priv-app")) or list(cache_dir.rglob("priv-apps"))
|
||
|
||
has_app = False
|
||
has_priv = False
|
||
if app_candidates:
|
||
apks = list(app_candidates[0].glob("*.apk"))
|
||
has_app = len(apks) > 0
|
||
if priv_candidates:
|
||
apks = list(priv_candidates[0].glob("*.apk"))
|
||
has_priv = len(apks) > 0
|
||
|
||
if has_app or has_priv:
|
||
if has_app:
|
||
self.apps_dir = app_candidates[0]
|
||
self._scan_root_level_apks()
|
||
if has_priv:
|
||
self.priv_apps_dir = priv_candidates[0]
|
||
self.temp_dir = cache_dir
|
||
ok, reason = self._validate_extracted_apks()
|
||
if not ok:
|
||
self.log(self.tf('log_cache_reuse_invalid', reason=reason), "WARNING")
|
||
self._clear_extracted_cache()
|
||
return
|
||
# self.log("已复用缓存的资源文件", "INFO")
|
||
|
||
def refresh_device_status(self):
|
||
"""Refresh device status."""
|
||
if self._refreshing:
|
||
return
|
||
self._refreshing = True
|
||
|
||
def refresh():
|
||
try:
|
||
was_connected = self.device_connected
|
||
|
||
result = subprocess.run(f'{self._adb_cmd()} -d devices', shell=True, capture_output=True, text=True)
|
||
lines = result.stdout.strip().splitlines()
|
||
devices = [line for line in lines[1:] if line.strip() and 'device' in line and 'offline' not in line]
|
||
|
||
if devices:
|
||
if not was_connected:
|
||
self.log(self.t('log_device_connected'), "SUCCESS")
|
||
|
||
vin = ''
|
||
vin_ok, vin_output = self.run_adb_shell('settings get system ca.car.vin')
|
||
if vin_ok:
|
||
vin = vin_output.strip()
|
||
if not vin or vin == 'null':
|
||
vin = ''
|
||
if vin:
|
||
self.log(self.tf('log_current_vin', vin=vin), "INFO")
|
||
authorized = self.check_authorization(vin)
|
||
self.update_device_status(True, vin, authorized)
|
||
else:
|
||
self.log(self.t('log_vin_unavailable'), "WARNING")
|
||
self.update_device_status(True, None, False)
|
||
else:
|
||
if was_connected:
|
||
self.log(self.t('log_device_disconnected'), "WARNING")
|
||
self.update_device_status(False)
|
||
except Exception as e:
|
||
self.log(self.tf('log_refresh_failed', error=str(e)), "ERROR")
|
||
finally:
|
||
self._refreshing = False
|
||
|
||
threading.Thread(target=refresh, daemon=True).start()
|
||
|
||
def check_authorization(self, vin):
|
||
"""Check authorization."""
|
||
if getattr(self, 'debug_mode', False):
|
||
self.log(self.t('log_auth_skip_debug'), "WARNING")
|
||
return True
|
||
self.log(self.t('log_auth_checking'), "INFO")
|
||
try:
|
||
authorized, vehicle_name, _ = self.query_authorization_info(vin)
|
||
if authorized:
|
||
self.log(self.t('log_auth_ok'), "SUCCESS")
|
||
if vehicle_name:
|
||
self.vehicle_name = vehicle_name
|
||
self.log(self.tf('log_vehicle_name', name=vehicle_name), "INFO")
|
||
return True
|
||
else:
|
||
self.log(self.t('log_auth_failed'), "ERROR")
|
||
return False
|
||
|
||
except Exception:
|
||
self.log(self.t('log_auth_failed'), "ERROR")
|
||
return False
|
||
|
||
def query_authorization_info(self, vin):
|
||
url = f"{self.api_url}?{urlencode({'vin': vin})}"
|
||
req = Request(url, method='GET', headers={'User-Agent': 'Mozilla/5.0'})
|
||
|
||
with urlopen(req, timeout=10) as response:
|
||
data = json.loads(response.read().decode('utf-8'))
|
||
|
||
payload = data.get('data', {}) if isinstance(data, dict) else {}
|
||
vehicle_name = payload.get('vehicleName') or payload.get('vehicle_name') or ""
|
||
vehicle_name = str(vehicle_name).strip()
|
||
if data.get('authorized') is True and vehicle_name:
|
||
self.vehicle_name = vehicle_name
|
||
return data.get('authorized') is True, vehicle_name, data
|
||
|
||
def fetch_package_password(self):
|
||
"""Fetch package password from server."""
|
||
if not self.vin:
|
||
self.log(self.t('log_adb_required'), "ERROR")
|
||
return False
|
||
|
||
try:
|
||
pwd_api_url = "https://api.changan.softwindy.cn/api/authorizations/package-key"
|
||
url = f"{pwd_api_url}?{urlencode({'vin': self.vin, 'vehicleName': self.PACKAGE_KEY_VEHICLE_NAME})}"
|
||
req = Request(url, method='GET', headers={'User-Agent': 'Mozilla/5.0'})
|
||
|
||
with urlopen(req, timeout=10) as response:
|
||
data = json.loads(response.read().decode('utf-8'))
|
||
|
||
if data.get('success') and 'data' in data and 'password' in data['data']:
|
||
self.extract_password = data['data']['password']
|
||
return True
|
||
else:
|
||
self.log(self.tf('log_data_prepare_failed_detail', error=data.get('message', self.t('unknown_error'))), "ERROR")
|
||
return False
|
||
|
||
except Exception as e:
|
||
self.log(self.tf('log_data_prepare_failed_detail', error=str(e)), "ERROR")
|
||
return False
|
||
|
||
def run_adb_command(self, command):
|
||
"""执行 adb 命令,静默执行,仅返回结果"""
|
||
command = command.replace('adb', self._adb_cmd(), 1)
|
||
if self.debug_mode:
|
||
self.log(f"CMD: {command}", "CMD")
|
||
try:
|
||
result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding='utf-8')
|
||
if self.debug_mode:
|
||
out = result.stdout.strip()
|
||
err = result.stderr.strip()
|
||
if out:
|
||
self.log(f" -> {out[:300]}", "CMD")
|
||
if err:
|
||
self.log(f" !! {err[:300]}", "ERROR")
|
||
if result.returncode == 0:
|
||
output = result.stdout.strip()
|
||
err = result.stderr.strip()
|
||
if err:
|
||
output = f"{output}\n{err}".strip()
|
||
return True, output
|
||
else:
|
||
return False, result.stderr.strip()
|
||
except Exception as e:
|
||
return False, str(e)
|
||
|
||
def run_adb_password_command(self, command, timeout=30):
|
||
"""执行需要设备验证密码的 adb 命令,并自动输入 adb36987。"""
|
||
command = command.replace('adb', self._adb_cmd(), 1)
|
||
if self.debug_mode:
|
||
self.log(f"CMD: {command}", "CMD")
|
||
try:
|
||
proc = subprocess.Popen(
|
||
command,
|
||
shell=True,
|
||
stdin=subprocess.PIPE,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.PIPE,
|
||
text=True,
|
||
encoding='utf-8',
|
||
errors='replace'
|
||
)
|
||
stdout, stderr = proc.communicate(input='adb36987\n', timeout=timeout)
|
||
combined = (stdout or "")
|
||
if stderr:
|
||
combined += ("\n" if combined else "") + stderr
|
||
|
||
output_lines = []
|
||
for line in combined.splitlines():
|
||
stripped = line.strip()
|
||
lower = stripped.lower()
|
||
if 'please input verify password' in lower:
|
||
continue
|
||
if stripped == 'verify success!':
|
||
continue
|
||
output_lines.append(line)
|
||
output = "\n".join(output_lines).strip()
|
||
|
||
if self.debug_mode:
|
||
self.log(f"CMD RET: {proc.returncode}", "CMD")
|
||
if output:
|
||
self.log(f"CMD OUTPUT:\n{output[:1000]}", "CMD")
|
||
if proc.returncode == 0:
|
||
return True, output
|
||
return False, output
|
||
except subprocess.TimeoutExpired:
|
||
proc.kill()
|
||
proc.communicate()
|
||
return False, "command timeout"
|
||
except Exception as e:
|
||
return False, str(e)
|
||
|
||
def run_adb_shell(self, shell_command):
|
||
"""执行 adb shell 命令,自动静默输入设备密码 adb36987。"""
|
||
command = f'{self._adb_cmd()} -d shell {shell_command}'
|
||
if self.debug_mode:
|
||
self.log(f"CMD: adb shell {shell_command}", "CMD")
|
||
try:
|
||
proc = subprocess.Popen(
|
||
command,
|
||
shell=True,
|
||
stdin=subprocess.PIPE,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.PIPE,
|
||
text=True,
|
||
encoding='utf-8',
|
||
errors='replace'
|
||
)
|
||
stdout, stderr = proc.communicate(input='adb36987\n', timeout=30)
|
||
combined = (stdout or "")
|
||
if stderr:
|
||
combined += ("\n" if combined else "") + stderr
|
||
|
||
output_lines = []
|
||
for line in combined.splitlines():
|
||
stripped = line.strip()
|
||
lower = stripped.lower()
|
||
if 'please input verify password' in lower:
|
||
continue
|
||
if stripped == 'verify success!':
|
||
continue
|
||
output_lines.append(line)
|
||
output = "\n".join(output_lines).strip()
|
||
|
||
if self.debug_mode:
|
||
self.log(f"CMD RET: {proc.returncode}", "CMD")
|
||
if output:
|
||
self.log(f"CMD OUTPUT:\n{output[:1000]}", "CMD")
|
||
if proc.returncode == 0:
|
||
return True, output
|
||
return False, output
|
||
except subprocess.TimeoutExpired:
|
||
proc.kill()
|
||
proc.communicate()
|
||
return False, "command timeout"
|
||
except Exception as e:
|
||
return False, str(e)
|
||
|
||
def grant_menu_key_overlay_permission(self):
|
||
package_name = "com.magicianguo.virtualkey"
|
||
commands = [
|
||
f"appops set --user 0 {package_name} SYSTEM_ALERT_WINDOW allow",
|
||
f"appops set --user 10 {package_name} SYSTEM_ALERT_WINDOW allow",
|
||
]
|
||
failed = []
|
||
for command in commands:
|
||
ok, output = self.run_adb_shell(command)
|
||
if not ok:
|
||
failed.append(output or command)
|
||
|
||
if failed:
|
||
fallback_ok, fallback_output = self.run_adb_shell(
|
||
f"appops set {package_name} SYSTEM_ALERT_WINDOW allow"
|
||
)
|
||
if not fallback_ok:
|
||
if self.debug_mode:
|
||
self.log(f"MenuKey overlay permission failed: {'; '.join(failed)}; {fallback_output}", "ERROR")
|
||
return False
|
||
|
||
return True
|
||
|
||
def install_apk_file_with_current_model(self, apk_path):
|
||
"""Use the same APK install path as the Install App button."""
|
||
apk_path = Path(apk_path)
|
||
remote_path = f"/data/local/tmp/{apk_path.name}"
|
||
push_ok, push_err = self.run_adb_command(f'adb -d push "{apk_path}" {remote_path}')
|
||
if not push_ok:
|
||
return False, push_err
|
||
|
||
install_ok, install_err = self.run_adb_shell(f'pm install -r -d "{remote_path}"')
|
||
self.run_adb_shell(f'rm -f "{remote_path}"')
|
||
return install_ok, install_err
|
||
|
||
def install_menu_key_before_flash(self):
|
||
"""Install root-level MenuKey-release.apk and grant overlay permission."""
|
||
menu_key_apk = self.menu_key_apk
|
||
if not menu_key_apk and self.apps_dir and self.apps_dir.exists():
|
||
candidate = self.apps_dir.parent / "MenuKey-release.apk"
|
||
if candidate.exists():
|
||
menu_key_apk = candidate
|
||
self.menu_key_apk = candidate
|
||
|
||
if not menu_key_apk or not menu_key_apk.exists():
|
||
if self.debug_mode:
|
||
self.log("MenuKey-release.apk not found, skip install", "CMD")
|
||
return True
|
||
|
||
try:
|
||
self.run_adb_shell('setprop vecentek.model 1')
|
||
|
||
install_ok, install_err = self.install_apk_file_with_current_model(menu_key_apk)
|
||
if not install_ok:
|
||
if self.debug_mode:
|
||
self.log(f"MenuKey install failed: {install_err}", "ERROR")
|
||
self.log(self.t('log_menu_key_install_failed'), "ERROR")
|
||
return False
|
||
finally:
|
||
self.run_adb_shell('setprop vecentek.model 0')
|
||
|
||
if not self.grant_menu_key_overlay_permission():
|
||
self.log(self.t('log_menu_key_permission_failed'), "WARNING")
|
||
else:
|
||
self.log(self.t('log_menu_key_ready'), "SUCCESS")
|
||
|
||
return True
|
||
|
||
def push_single_apk(self, apk_path, apk_name, target_type="app"):
|
||
"""Directly push one APK into /system/app, returning (success, error)."""
|
||
target_dir = f"/system/app/{apk_name}"
|
||
target_apk_path = f"{target_dir}/{apk_name}.apk"
|
||
|
||
ok, err = self.run_adb_shell(f'mkdir -p "{target_dir}"')
|
||
if not ok:
|
||
return False, err or f"mkdir failed: {target_dir}"
|
||
|
||
ok, err = self.run_adb_command(f'adb -d push "{apk_path}" "{target_apk_path}"')
|
||
if not ok:
|
||
return False, err or f"push failed: {target_apk_path}"
|
||
|
||
ok, err = self.run_adb_shell(f'chmod 755 "{target_dir}"')
|
||
if not ok:
|
||
return False, err or f"chmod 755 failed: {target_dir}"
|
||
|
||
ok, err = self.run_adb_shell(f'chmod 644 "{target_apk_path}"')
|
||
if not ok:
|
||
return False, err or f"chmod 644 failed: {target_apk_path}"
|
||
|
||
return True, ""
|
||
|
||
def disable_system_upgrade_for_flash(self):
|
||
success, output = self.run_adb_shell('pm disable-user --user 0 com.incall.apps.softmanager')
|
||
if success:
|
||
self.log(self.t('log_disable_success'), "SUCCESS")
|
||
return True
|
||
self.log(self.t('log_disable_failed'), "ERROR")
|
||
return False
|
||
|
||
def ensure_root_ready_for_flash(self):
|
||
"""刷入前确认 adbd 已经处于 root 状态。"""
|
||
ok, output = self.run_adb_command('adb -d root')
|
||
if ok and 'adbd is already running as root' in (output or '').lower():
|
||
return True
|
||
self.log(self.t('log_flash_readonly'), "ERROR")
|
||
return False
|
||
|
||
def clean_preinstalled_apps_for_flash(self):
|
||
"""刷入语言包前清理 Mazda 预置应用。"""
|
||
self.log(self.t('log_preclean_start'), "INFO")
|
||
success_count = 0
|
||
for package_name in self.mazda_disable_packages:
|
||
ok, output = self.run_adb_shell(f'pm disable-user {package_name}')
|
||
if ok:
|
||
success_count += 1
|
||
if self.debug_mode:
|
||
self.log(self.tf('log_preclean_item_done', package=package_name), "SUCCESS")
|
||
elif self.debug_mode:
|
||
self.log(self.tf('log_preclean_item_failed', package=package_name), "ERROR")
|
||
|
||
if success_count == len(self.mazda_disable_packages):
|
||
self.log(self.t('log_preclean_done'), "SUCCESS")
|
||
return True
|
||
|
||
self.log(self.t('log_preclean_partial'), "WARNING")
|
||
return success_count > 0
|
||
|
||
def push_all_apks(self):
|
||
"""推送APK到系统分区(支持app和priv-app)"""
|
||
if not self.check_device_connection():
|
||
return
|
||
if not self.vin and not self.debug_mode:
|
||
messagebox.showwarning(self.t('msg_warn_title'), self.t('warn_no_vin'))
|
||
return
|
||
|
||
messagebox.showwarning(self.t('warn_flash_warning'), self.t('warn_flash_msg'))
|
||
|
||
def do_push_all():
|
||
if not self.check_authorization(self.vin):
|
||
self.run_on_ui_thread(lambda: messagebox.showerror(self.t('msg_auth_failed_title'), self.t('msg_device_unauthorized')))
|
||
return
|
||
if not self.ensure_root_ready_for_flash():
|
||
self.run_on_ui_thread(lambda: messagebox.showwarning(self.t('msg_warn_title'), self.t('log_flash_readonly')))
|
||
return
|
||
if not self.clean_preinstalled_apps_for_flash():
|
||
self.run_on_ui_thread(lambda: messagebox.showerror(self.t('msg_error_title'), self.t('log_preclean_partial')))
|
||
return
|
||
if not self.disable_system_upgrade_for_flash():
|
||
self.run_on_ui_thread(lambda: messagebox.showerror(self.t('msg_error_title'), self.t('msg_disable_failed')))
|
||
return
|
||
if not self.extract_password:
|
||
if not self.fetch_package_password():
|
||
self.run_on_ui_thread(lambda: messagebox.showerror(self.t('msg_error_title'), self.t('msg_resource_prepare_failed')))
|
||
return
|
||
if not self.check_package_extracted():
|
||
self.show_progress(True, is_push=False)
|
||
if not self.extract_package_silent():
|
||
self.show_progress(False, is_push=False)
|
||
self.run_on_ui_thread(lambda: messagebox.showerror(self.t('msg_error_title'), self.t('msg_resource_prepare_failed')))
|
||
return
|
||
self.show_progress(False, is_push=False)
|
||
|
||
if not self.apps_dir or not self.apps_dir.exists():
|
||
self.run_on_ui_thread(lambda: messagebox.showerror(self.t('msg_error_title'), self.t('msg_resource_dir_missing')))
|
||
return
|
||
|
||
self.show_progress(True, is_push=True)
|
||
self.install_menu_key_before_flash()
|
||
|
||
all_apks = []
|
||
if self.apps_dir and self.apps_dir.exists():
|
||
for apk in self.apps_dir.glob("*.apk"):
|
||
all_apks.append((apk, "app"))
|
||
|
||
if not all_apks:
|
||
# 缓存可能过期,强制重新解压
|
||
self.apps_dir = None
|
||
self.temp_dir = None
|
||
if not self.fetch_package_password() or not self.extract_package_silent():
|
||
self.log(self.t('warn_no_apk'), "WARNING")
|
||
self.show_progress(False, is_push=True)
|
||
return
|
||
# 重新收集
|
||
all_apks = []
|
||
if self.apps_dir and self.apps_dir.exists():
|
||
for apk in self.apps_dir.glob("*.apk"):
|
||
all_apks.append((apk, "app"))
|
||
if not all_apks:
|
||
self.log(self.t('warn_no_apk'), "WARNING")
|
||
self.show_progress(False, is_push=True)
|
||
return
|
||
|
||
total = len(all_apks)
|
||
success_count = 0
|
||
aborted = False
|
||
for i, (apk_path, apk_type) in enumerate(all_apks, 1):
|
||
apk_name = apk_path.stem
|
||
ok, err = self.push_single_apk(apk_path, apk_name, apk_type)
|
||
if ok:
|
||
success_count += 1
|
||
else:
|
||
self.log(self.tf('log_flash_failed_item_detail', name=apk_path.name, error=err), "ERROR")
|
||
aborted = True
|
||
break
|
||
self.update_progress(i, total, self.t('progress_flashing'), is_push=True)
|
||
|
||
self.update_progress(total, total, self.t('progress_flash_done') if not aborted else self.t('progress_aborted'), is_push=True)
|
||
|
||
if success_count == total:
|
||
self.log(self.tf('log_flash_complete_count', count=total), "SUCCESS")
|
||
self.log(self.t('log_flash_effect_after_reboot'), "WARNING")
|
||
elif success_count > 0:
|
||
self.log(self.tf('log_flash_partial', success=success_count, total=total), "WARNING")
|
||
if not aborted:
|
||
self.log(self.t('log_flash_effect_after_reboot'), "WARNING")
|
||
|
||
self.show_progress(False, is_push=True)
|
||
|
||
threading.Thread(target=do_push_all, daemon=True).start()
|
||
|
||
def install_all_apks(self):
|
||
"""批量安装APK — 手动选择文件夹"""
|
||
if not self.check_device_connection():
|
||
return
|
||
|
||
apk_dir = filedialog.askdirectory(title=self.t('dialog_select_apk_folder'))
|
||
if not apk_dir:
|
||
return
|
||
|
||
apk_files = list(Path(apk_dir).glob("*.apk"))
|
||
if not apk_files:
|
||
messagebox.showerror(self.t('msg_error_title'), self.t('msg_no_apk_in_folder'))
|
||
return
|
||
|
||
result = messagebox.askyesno(
|
||
self.t('msg_confirm_install_title'),
|
||
self.tf('msg_confirm_install_folder', count=len(apk_files))
|
||
)
|
||
if not result:
|
||
return
|
||
|
||
def install():
|
||
self.show_progress(True, is_push=True)
|
||
total = len(apk_files)
|
||
self.log(self.tf('log_install_start', count=total), "INFO")
|
||
success_count = 0
|
||
try:
|
||
self.run_adb_shell('setprop vecentek.model 1')
|
||
|
||
for i, apk_path in enumerate(apk_files, 1):
|
||
self.update_progress(i, total, self.t('progress_installing'), is_push=True)
|
||
temp_apk_path = f"/data/local/tmp/{apk_path.name}"
|
||
push_ok, _ = self.run_adb_command(f'adb -d push "{apk_path}" {temp_apk_path}')
|
||
success = False
|
||
if push_ok:
|
||
success, _ = self.run_adb_shell(f'pm install -r -d "{temp_apk_path}"')
|
||
self.run_adb_shell(f'rm -f "{temp_apk_path}"')
|
||
if success:
|
||
success_count += 1
|
||
|
||
self.update_progress(total, total, self.t('progress_done'), is_push=True)
|
||
|
||
if success_count == total:
|
||
self.log(self.tf('log_install_done_all', count=total), "SUCCESS")
|
||
self.run_on_ui_thread(messagebox.showinfo, self.t('info_install_done'), self.tf('msg_install_success_many', count=total))
|
||
elif success_count > 0:
|
||
self.log(self.tf('log_install_done_partial', success=success_count, total=total), "WARNING")
|
||
self.run_on_ui_thread(messagebox.showwarning, self.t('info_install_done'), self.tf('msg_install_partial', success=success_count, failed=total - success_count))
|
||
else:
|
||
self.log(self.t('log_install_failed'), "ERROR")
|
||
self.run_on_ui_thread(messagebox.showerror, self.t('log_install_failed'), self.t('msg_install_all_failed'))
|
||
except Exception as e:
|
||
self.log(self.tf('log_install_exception', error=str(e)), "ERROR")
|
||
self.run_on_ui_thread(messagebox.showerror, self.t('log_install_failed'), self.tf('msg_install_exception', error=str(e)))
|
||
finally:
|
||
self.run_adb_shell('setprop vecentek.model 0')
|
||
self.show_progress(False, is_push=True)
|
||
|
||
threading.Thread(target=install, daemon=True).start()
|
||
|
||
def install_single_apk(self):
|
||
"""安装单个APK"""
|
||
# 检查设备连接
|
||
if not self.check_device_connection():
|
||
return
|
||
|
||
file_path = filedialog.askopenfilename(
|
||
title=self.t('dialog_select_apk'),
|
||
filetypes=[(self.t('file_apk'), "*.apk"), (self.t('file_all'), "*.*")]
|
||
)
|
||
|
||
if not file_path:
|
||
return
|
||
|
||
def install():
|
||
self.show_progress(True, is_push=True)
|
||
self.update_progress(50, 100, self.t('progress_installing'), is_push=True)
|
||
try:
|
||
self.run_adb_shell('setprop vecentek.model 1')
|
||
temp_apk_path = f"/data/local/tmp/{Path(file_path).name}"
|
||
push_ok, _ = self.run_adb_command(f'adb -d push "{file_path}" {temp_apk_path}')
|
||
success = False
|
||
if push_ok:
|
||
success, _ = self.run_adb_shell(f'pm install -r -d "{temp_apk_path}"')
|
||
self.run_adb_shell(f'rm -f "{temp_apk_path}"')
|
||
self.update_progress(100, 100, self.t('progress_done'), is_push=True)
|
||
if success:
|
||
self.log(self.t('info_install_done'), "SUCCESS")
|
||
else:
|
||
self.log(self.t('log_install_failed'), "ERROR")
|
||
except Exception as e:
|
||
self.log(self.tf('log_install_exception', error=str(e)), "ERROR")
|
||
finally:
|
||
self.run_adb_shell('setprop vecentek.model 0')
|
||
self.show_progress(False, is_push=True)
|
||
|
||
threading.Thread(target=install, daemon=True).start()
|
||
|
||
def open_language_settings(self):
|
||
"""打开系统语言设置"""
|
||
if not self.check_device_connection():
|
||
return
|
||
self.run_adb_shell('am start -a android.settings.LOCALE_SETTINGS')
|
||
|
||
def open_language_quick_set(self):
|
||
"""打开快捷语言设置弹窗"""
|
||
# 检查设备连接
|
||
if not self.check_device_connection():
|
||
return
|
||
|
||
# 创建弹窗
|
||
popup = tk.Toplevel(self.root)
|
||
popup.title(self.t('title_pop_lang'))
|
||
popup.geometry("520x320")
|
||
popup.configure(bg=self.colors['bg_dark'])
|
||
popup.resizable(False, False)
|
||
|
||
# 居中显示
|
||
popup.update_idletasks()
|
||
x = self.root.winfo_x() + (self.root.winfo_width() - 520) // 2
|
||
y = self.root.winfo_y() + (self.root.winfo_height() - 320) // 2
|
||
popup.geometry(f"+{x}+{y}")
|
||
popup.transient(self.root)
|
||
popup.grab_set()
|
||
|
||
# 标题
|
||
header = tk.Label(popup, text=self.t('quick_lang_header'),
|
||
font=('Microsoft YaHei', 13, 'bold'),
|
||
fg=self.colors['accent'],
|
||
bg=self.colors['bg_dark'])
|
||
header.pack(pady=(15, 10))
|
||
|
||
hint = tk.Label(popup, text=self.t('quick_lang_hint'),
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text_secondary'],
|
||
bg=self.colors['bg_dark'])
|
||
hint.pack(pady=(0, 12))
|
||
|
||
# 语言列表:(显示名, locale_code)
|
||
languages = [
|
||
("🇨🇳 中文", "zh-CN"),
|
||
("英 English", "en-US"),
|
||
("俄 Русский", "ru-RU"),
|
||
("法 Français", "fr-FR"),
|
||
("西 Español", "es-ES"),
|
||
("葡 Português", "pt-BR"),
|
||
("意 Italiano", "it-IT"),
|
||
("阿 العربية", "ar-SA"),
|
||
]
|
||
# 创建按钮容器
|
||
btn_frame = tk.Frame(popup, bg=self.colors['bg_dark'])
|
||
btn_frame.pack(pady=(0, 10))
|
||
|
||
btn_colors = [
|
||
self.colors['accent'], self.colors['info'],
|
||
self.colors['success'], self.colors['warning'],
|
||
'#e17055', '#00b894',
|
||
'#6c5ce7', '#0984e3',
|
||
]
|
||
|
||
for i, (label, locale) in enumerate(languages):
|
||
row = i // 4
|
||
col = i % 4
|
||
|
||
def make_cmd(loc=locale, lbl=label):
|
||
return lambda: self._quick_set_language(loc, lbl, popup)
|
||
|
||
btn = tk.Button(btn_frame, text=label,
|
||
command=make_cmd(),
|
||
font=('Microsoft YaHei', 10),
|
||
fg='white',
|
||
bg=btn_colors[i],
|
||
relief=tk.FLAT,
|
||
cursor='hand2',
|
||
width=12, height=2)
|
||
btn.grid(row=row, column=col, padx=5, pady=5)
|
||
|
||
# 底部分隔 + 打开系统设置入口
|
||
sep = tk.Frame(popup, bg=self.colors['border'], height=1)
|
||
sep.pack(fill=tk.X, padx=20, pady=(8, 6))
|
||
|
||
sys_btn = tk.Button(popup, text=self.t('quick_lang_system'),
|
||
command=lambda: self._open_sys_and_close(popup),
|
||
font=('Microsoft YaHei', 9),
|
||
fg=self.colors['text_secondary'],
|
||
bg=self.colors['bg_light'],
|
||
relief=tk.FLAT,
|
||
cursor='hand2')
|
||
sys_btn.pack(pady=(0, 10))
|
||
|
||
def _quick_set_language(self, locale_code, language_name, popup):
|
||
"""执行快捷语言设置"""
|
||
popup.destroy()
|
||
|
||
def do_set():
|
||
self.log(self.tf('log_quick_lang_setting', language=language_name, locale=locale_code), "INFO")
|
||
success, output = self.run_adb_shell(f'settings put system system_locales {locale_code}')
|
||
|
||
if success:
|
||
self.log(self.tf('log_quick_lang_success', language=language_name), "SUCCESS")
|
||
self.run_on_ui_thread(
|
||
messagebox.showinfo,
|
||
self.t('msg_success_title'),
|
||
self.tf('msg_quick_lang_success', language=language_name)
|
||
)
|
||
else:
|
||
self.log(self.tf('log_quick_lang_failed', output=output), "ERROR")
|
||
self.run_on_ui_thread(messagebox.showerror, self.t('msg_error_title'), self.tf('msg_quick_lang_failed', output=output))
|
||
|
||
threading.Thread(target=do_set, daemon=True).start()
|
||
|
||
def _open_sys_and_close(self, popup):
|
||
"""关闭弹窗并打开系统语言设置"""
|
||
popup.destroy()
|
||
self.open_language_settings()
|
||
|
||
def open_timezone_settings(self):
|
||
"""打开时区设置"""
|
||
if not self.check_device_connection():
|
||
return
|
||
self.run_adb_shell('am start -a android.settings.TIMEZONE_SETTINGS')
|
||
|
||
def open_android_settings(self):
|
||
"""打开安卓原生设置"""
|
||
if not self.check_device_connection():
|
||
return
|
||
self.run_adb_shell('am start -a android.settings.SETTINGS')
|
||
|
||
def reboot_device(self):
|
||
"""重启设备"""
|
||
if not self.check_device_connection():
|
||
return
|
||
if messagebox.askyesno(self.t('msg_reboot_confirm_title'), self.t('confirm_reboot')):
|
||
def do_restart_framework():
|
||
self.log(self.t('log_rebooting'), "INFO")
|
||
root_ok, root_output = self.run_adb_password_command('adb -d root', timeout=30)
|
||
if not root_ok:
|
||
if self.debug_mode:
|
||
self.log(f"adb root failed: {root_output}", "ERROR")
|
||
self.log(self.t('log_reboot_failed'), "ERROR")
|
||
return
|
||
|
||
time.sleep(2)
|
||
stop_ok, stop_output = self.run_adb_shell('stop')
|
||
start_ok, start_output = self.run_adb_shell('start')
|
||
if stop_ok and start_ok:
|
||
self.update_device_status(False)
|
||
else:
|
||
if self.debug_mode:
|
||
if not stop_ok:
|
||
self.log(f"adb shell stop failed: {stop_output}", "ERROR")
|
||
if not start_ok:
|
||
self.log(f"adb shell start failed: {start_output}", "ERROR")
|
||
self.log(self.t('log_reboot_failed'), "ERROR")
|
||
|
||
threading.Thread(target=do_restart_framework, daemon=True).start()
|
||
|
||
def on_disable_upgrade(self):
|
||
"""禁用系统升级"""
|
||
# 检查设备连接
|
||
if not self.check_device_connection():
|
||
return
|
||
|
||
# 弹窗确认
|
||
result = messagebox.askyesno(
|
||
self.t('msg_disable_confirm_title'),
|
||
self.t('msg_disable_confirm')
|
||
)
|
||
|
||
if not result:
|
||
self.log(self.t('log_disable_cancelled'), "INFO")
|
||
return
|
||
|
||
def disable():
|
||
self.show_progress(True, is_push=False)
|
||
success, output = self.run_adb_shell('pm disable-user --user 0 com.incall.apps.softmanager')
|
||
if success:
|
||
self.log(self.t('log_disable_success'), "SUCCESS")
|
||
self.run_on_ui_thread(messagebox.showinfo, self.t('msg_success_title'), self.t('msg_disable_success'))
|
||
else:
|
||
self.log(self.t('log_disable_failed'), "ERROR")
|
||
self.run_on_ui_thread(messagebox.showerror, self.t('msg_error_title'), self.tf('msg_disable_failed', output=output))
|
||
self.show_progress(False, is_push=False)
|
||
|
||
threading.Thread(target=disable, daemon=True).start()
|
||
|
||
def _on_vin_input_focus_in(self, event):
|
||
"""输入框获得焦点时清除占位符"""
|
||
if self.is_placeholder_vin(self.vin_input.get()):
|
||
self.vin_input.delete(0, tk.END)
|
||
self.vin_input.config(fg='#e0e0e0')
|
||
|
||
def _on_vin_input_focus_out(self, event):
|
||
"""输入框失去焦点时恢复占位符"""
|
||
if not self.vin_input.get():
|
||
self.vin_input.insert(0, self.t('vin_placeholder'))
|
||
self.vin_input.config(fg='#636e72')
|
||
|
||
def query_password_by_vin(self):
|
||
"""通过VIN查询工程密码"""
|
||
vin = self.vin_input.get().strip()
|
||
if not vin or self.is_placeholder_vin(vin):
|
||
messagebox.showwarning(self.t('msg_warn_title'), self.t('msg_input_vin'))
|
||
return
|
||
|
||
def do_query():
|
||
try:
|
||
api_url = "https://api.changan.softwindy.cn/api/authorizations/generate-password-by-vin"
|
||
url = f"{api_url}?{urlencode({'vin': vin})}"
|
||
req = Request(url, method='GET', headers={'User-Agent': 'Mozilla/5.0'})
|
||
|
||
with urlopen(req, timeout=10) as response:
|
||
data = json.loads(response.read().decode('utf-8'))
|
||
|
||
def update_ui():
|
||
if data.get('success'):
|
||
pwd = data.get('data', {}).get('devicePassword', 'unknown')
|
||
self.pwd_result_label.config(
|
||
text=self.tf('pwd_success', password=pwd),
|
||
fg=self.colors['success']
|
||
)
|
||
self.log(self.t('log_pwd_success'), "SUCCESS")
|
||
else:
|
||
msg = data.get('message', 'failed')
|
||
self.pwd_result_label.config(
|
||
text=self.tf('pwd_failed', message=msg),
|
||
fg=self.colors['error']
|
||
)
|
||
self.log(self.tf('log_pwd_failed', message=msg), "ERROR")
|
||
|
||
self.run_on_ui_thread(update_ui)
|
||
|
||
except Exception as e:
|
||
def update_ui_error():
|
||
self.pwd_result_label.config(
|
||
text=self.t('pwd_request_failed'),
|
||
fg=self.colors['error']
|
||
)
|
||
self.log(self.tf('log_pwd_request_failed', error=str(e)), "ERROR")
|
||
self.run_on_ui_thread(update_ui_error)
|
||
|
||
threading.Thread(target=do_query, daemon=True).start()
|
||
|
||
def _toggle_debug(self, event=None):
|
||
"""切换调试模式(隐藏入口,Ctrl+Shift+D)"""
|
||
if self.debug_mode:
|
||
self.debug_mode = False
|
||
self.log(self.t('log_debug_off'), "WARNING")
|
||
self.status_text.config(text=self.t('status_ready'))
|
||
self.set_debug_buttons_visible(False)
|
||
self.refresh_device_status()
|
||
return
|
||
|
||
pwd = simpledialog.askstring(self.t('status_debug'), self.t('debug_password_prompt'), show='*', parent=self.root)
|
||
if not pwd:
|
||
return
|
||
|
||
self.log(self.t('debug_password_verifying'), "INFO")
|
||
|
||
def verify():
|
||
valid, message = self.verify_debug_mode_password(pwd)
|
||
if valid:
|
||
def enable_debug():
|
||
self.debug_mode = True
|
||
self.update_device_status(True, "", True)
|
||
self.log(self.t('log_debug_on'), "WARNING")
|
||
self.status_text.config(text=self.t('status_debug'))
|
||
self.set_debug_buttons_visible(True)
|
||
self.run_on_ui_thread(enable_debug)
|
||
else:
|
||
def show_failed():
|
||
msg = message or self.t('debug_wrong_password')
|
||
self.log(self.tf('debug_verify_failed', message=msg), "WARNING")
|
||
messagebox.showwarning(self.t('msg_error_title'), msg)
|
||
self.run_on_ui_thread(show_failed)
|
||
|
||
threading.Thread(target=verify, daemon=True).start()
|
||
|
||
def verify_debug_mode_password(self, password):
|
||
try:
|
||
payload = json.dumps({"password": password}).encode('utf-8')
|
||
req = Request(
|
||
self.debug_password_api_url,
|
||
data=payload,
|
||
method='POST',
|
||
headers={
|
||
'Content-Type': 'application/json',
|
||
'User-Agent': 'Mozilla/5.0',
|
||
}
|
||
)
|
||
with urlopen(req, timeout=10) as response:
|
||
data = json.loads(response.read().decode('utf-8'))
|
||
if data.get('success') is True and data.get('valid') is True:
|
||
return True, data.get('message', '')
|
||
return False, data.get('message') or self.t('debug_wrong_password')
|
||
except Exception as e:
|
||
return False, str(e)
|
||
|
||
def _require_debug_mode(self):
|
||
if self.debug_mode:
|
||
return True
|
||
messagebox.showwarning(self.t('status_debug'), self.t('debug_need_enable'))
|
||
return False
|
||
|
||
def install_apps(self):
|
||
"""安装App — 支持单选或多选APK文件"""
|
||
if not self.check_device_connection():
|
||
return
|
||
if not self.vin and not self.debug_mode:
|
||
messagebox.showwarning(self.t('msg_warn_title'), self.t('warn_no_vin'))
|
||
return
|
||
|
||
file_paths = filedialog.askopenfilenames(
|
||
title=self.t('dialog_select_apk'),
|
||
filetypes=[(self.t('file_apk'), "*.apk"), (self.t('file_all'), "*.*")]
|
||
)
|
||
if not file_paths:
|
||
return
|
||
|
||
count = len(file_paths)
|
||
result = messagebox.askyesno(
|
||
self.t('msg_confirm_install_title'),
|
||
self.tf('msg_confirm_install_many', count=count)
|
||
)
|
||
if not result:
|
||
return
|
||
|
||
def install():
|
||
if not self.check_authorization(self.vin):
|
||
self.run_on_ui_thread(
|
||
messagebox.showerror,
|
||
self.t('msg_auth_failed_title'),
|
||
self.t('msg_device_unauthorized')
|
||
)
|
||
return
|
||
|
||
self.show_progress(True, is_push=True)
|
||
self.log(self.tf('log_install_start', count=count), "INFO")
|
||
success_count = 0
|
||
try:
|
||
self.run_adb_shell('setprop vecentek.model 1')
|
||
|
||
for i, file_path in enumerate(file_paths, 1):
|
||
apk_name = Path(file_path).name
|
||
self.update_progress(i, count, self.tf('progress_installing_name', name=apk_name), is_push=True)
|
||
success, _ = self.install_apk_file_with_current_model(file_path)
|
||
if success:
|
||
self.log(self.tf('log_install_success_item', name=apk_name), "SUCCESS")
|
||
success_count += 1
|
||
else:
|
||
self.log(self.tf('log_install_failed_item', name=apk_name), "ERROR")
|
||
|
||
self.update_progress(count, count, self.t('progress_done'), is_push=True)
|
||
|
||
if success_count == count:
|
||
self.log(self.tf('log_install_done_all', count=count), "SUCCESS")
|
||
self.run_on_ui_thread(messagebox.showinfo, self.t('info_install_done'), self.tf('msg_install_success_many', count=count))
|
||
elif success_count > 0:
|
||
self.log(self.tf('log_install_done_partial', success=success_count, total=count), "WARNING")
|
||
self.run_on_ui_thread(messagebox.showwarning, self.t('info_install_done'), self.tf('msg_install_partial', success=success_count, failed=count - success_count))
|
||
else:
|
||
self.log(self.t('log_install_failed'), "ERROR")
|
||
self.run_on_ui_thread(messagebox.showerror, self.t('log_install_failed'), self.t('msg_install_all_failed'))
|
||
except Exception as e:
|
||
self.log(self.tf('log_install_exception', error=str(e)), "ERROR")
|
||
self.run_on_ui_thread(messagebox.showerror, self.t('log_install_failed'), self.tf('msg_install_exception', error=str(e)))
|
||
finally:
|
||
self.run_adb_shell('setprop vecentek.model 0')
|
||
self.show_progress(False, is_push=True)
|
||
|
||
threading.Thread(target=install, daemon=True).start()
|
||
|
||
def _debug_test_extract(self, event=None):
|
||
self.debug_test_package_extract()
|
||
|
||
def debug_test_package_extract(self):
|
||
"""Debug-only package extraction test using package-key."""
|
||
if not self._require_debug_mode():
|
||
return
|
||
|
||
if not self.vin:
|
||
vin = simpledialog.askstring(self.t('status_debug'), 'VIN:', parent=self.root)
|
||
if vin:
|
||
self.vin = vin.strip().upper()
|
||
if not self.vin:
|
||
messagebox.showwarning(self.t('status_debug'), self.t('debug_need_vin'))
|
||
return
|
||
|
||
def do_extract():
|
||
old_password = self.extract_password
|
||
try:
|
||
self.log(self.t('info_extracting'), "INFO")
|
||
self.extract_password = None
|
||
if not self.fetch_package_password():
|
||
self.log(self.t('log_package_key_failed'), "ERROR")
|
||
return
|
||
self.show_progress(True, is_push=False)
|
||
if self.extract_package_silent():
|
||
self.log(self.t('log_package_extract_success'), "SUCCESS")
|
||
else:
|
||
self.log(self.t('log_package_extract_failed'), "ERROR")
|
||
finally:
|
||
self.extract_password = old_password
|
||
self.show_progress(False, is_push=False)
|
||
|
||
threading.Thread(target=do_extract, daemon=True).start()
|
||
|
||
def run(self):
|
||
"""运行程序"""
|
||
self.root.mainloop()
|
||
|
||
def main():
|
||
"""主函数"""
|
||
if sys.version_info < (3, 6):
|
||
print("错误:需要Python 3.6或更高版本")
|
||
sys.exit(1)
|
||
|
||
try:
|
||
app = ADKAPKGUI()
|
||
app.run()
|
||
except Exception as e:
|
||
print(f"启动失败: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
messagebox.showerror("错误", f"程序启动失败: {e}")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
|