1
This commit is contained in:
1 parent
a59ebed397
commit
6fd164fa6f
12 files changed
+1179
-7
No files matched your search
+16
-1
@@ -994,5 +994,20 @@
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"containerRuntimeMode": "Container Runtime Mode",
|
||||
"containerRuntimeModeAuto": "Auto",
|
||||
"containerRuntimeModeProot": "PRoot",
|
||||
"containerRuntimeModeChroot": "Chroot",
|
||||
"selectContainerRuntimeMode": "Select Container Runtime Mode",
|
||||
"containerRuntimeToast": "Current container runtime: {mode}",
|
||||
"@containerRuntimeToast": {
|
||||
"placeholders": {
|
||||
"mode": {
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
},
|
||||
"chrootDisabledNoRoot": "Unavailable without Root permission",
|
||||
"chrootFailedFallbackToProot": "Chroot mount or permission failed, automatically fell back to PRoot"
|
||||
}
|
||||
@@ -2977,6 +2977,54 @@ abstract class AppLocalizations {
|
||||
/// In zh, this message translates to:
|
||||
/// **'容器重建失败: {error}'**
|
||||
String containerRebuildFailed(String error);
|
||||
|
||||
/// No description provided for @containerRuntimeMode.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'容器运行模式'**
|
||||
String get containerRuntimeMode;
|
||||
|
||||
/// No description provided for @containerRuntimeModeAuto.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'自动'**
|
||||
String get containerRuntimeModeAuto;
|
||||
|
||||
/// No description provided for @containerRuntimeModeProot.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'PRoot'**
|
||||
String get containerRuntimeModeProot;
|
||||
|
||||
/// No description provided for @containerRuntimeModeChroot.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'Chroot'**
|
||||
String get containerRuntimeModeChroot;
|
||||
|
||||
/// No description provided for @selectContainerRuntimeMode.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'选择容器运行模式'**
|
||||
String get selectContainerRuntimeMode;
|
||||
|
||||
/// No description provided for @containerRuntimeToast.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'当前容器运行环境:{mode}'**
|
||||
String containerRuntimeToast(String mode);
|
||||
|
||||
/// No description provided for @chrootDisabledNoRoot.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'未授予 Root 权限不可用'**
|
||||
String get chrootDisabledNoRoot;
|
||||
|
||||
/// No description provided for @chrootFailedFallbackToProot.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'Chroot 挂载或权限失败,已自动降级为 PRoot 运行模式'**
|
||||
String get chrootFailedFallbackToProot;
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate
|
||||
|
||||
@@ -1800,4 +1800,31 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
String containerRebuildFailed(String error) {
|
||||
return 'Failed to rebuild container: $error';
|
||||
}
|
||||
|
||||
@override
|
||||
String get containerRuntimeMode => 'Container Runtime Mode';
|
||||
|
||||
@override
|
||||
String get containerRuntimeModeAuto => 'Auto';
|
||||
|
||||
@override
|
||||
String get containerRuntimeModeProot => 'PRoot';
|
||||
|
||||
@override
|
||||
String get containerRuntimeModeChroot => 'Chroot';
|
||||
|
||||
@override
|
||||
String get selectContainerRuntimeMode => 'Select Container Runtime Mode';
|
||||
|
||||
@override
|
||||
String containerRuntimeToast(String mode) {
|
||||
return 'Current container runtime: $mode';
|
||||
}
|
||||
|
||||
@override
|
||||
String get chrootDisabledNoRoot => 'Unavailable without Root permission';
|
||||
|
||||
@override
|
||||
String get chrootFailedFallbackToProot =>
|
||||
'Chroot mount or permission failed, automatically fell back to PRoot';
|
||||
}
|
||||
@@ -1741,4 +1741,30 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
String containerRebuildFailed(String error) {
|
||||
return '容器重建失败: $error';
|
||||
}
|
||||
|
||||
@override
|
||||
String get containerRuntimeMode => '容器运行模式';
|
||||
|
||||
@override
|
||||
String get containerRuntimeModeAuto => '自动';
|
||||
|
||||
@override
|
||||
String get containerRuntimeModeProot => 'PRoot';
|
||||
|
||||
@override
|
||||
String get containerRuntimeModeChroot => 'Chroot';
|
||||
|
||||
@override
|
||||
String get selectContainerRuntimeMode => '选择容器运行模式';
|
||||
|
||||
@override
|
||||
String containerRuntimeToast(String mode) {
|
||||
return '当前容器运行环境:$mode';
|
||||
}
|
||||
|
||||
@override
|
||||
String get chrootDisabledNoRoot => '未授予 Root 权限不可用';
|
||||
|
||||
@override
|
||||
String get chrootFailedFallbackToProot => 'Chroot 挂载或权限失败,已自动降级为 PRoot 运行模式';
|
||||
}
|
||||
+16
-1
@@ -994,5 +994,20 @@
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"containerRuntimeMode": "容器运行模式",
|
||||
"containerRuntimeModeAuto": "自动",
|
||||
"containerRuntimeModeProot": "PRoot",
|
||||
"containerRuntimeModeChroot": "Chroot",
|
||||
"selectContainerRuntimeMode": "选择容器运行模式",
|
||||
"containerRuntimeToast": "当前容器运行环境:{mode}",
|
||||
"@containerRuntimeToast": {
|
||||
"placeholders": {
|
||||
"mode": {
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
},
|
||||
"chrootDisabledNoRoot": "未授予 Root 权限不可用",
|
||||
"chrootFailedFallbackToProot": "Chroot 挂载或权限失败,已自动降级为 PRoot 运行模式"
|
||||
}
|
||||
@@ -6,6 +6,18 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// 容器运行模式
|
||||
enum ContainerRuntimeMode {
|
||||
/// 自动模式:检测到 Root 权限时优先启用 Chroot,无 Root 或挂载失败自动使用 PRoot
|
||||
auto,
|
||||
|
||||
/// PRoot 模式:纯用户态沙箱运行,无需系统 Root 权限,安全兼容
|
||||
proot,
|
||||
|
||||
/// Chroot 模式:Linux 原生内核执行,无 ptrace 开销,满血性能
|
||||
chroot,
|
||||
}
|
||||
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
//外观
|
||||
static const String _keyAppThemeMode = 'app_theme_mode'; //应用主题
|
||||
@@ -39,6 +51,10 @@ class SettingsProvider extends ChangeNotifier {
|
||||
//语言
|
||||
static const String _keyAppLocale = 'app_locale';
|
||||
|
||||
//容器
|
||||
static const String _keyContainerRuntimeMode = 'container_runtime_mode';
|
||||
static const String _keyHasPromptedRootRequest = 'has_prompted_root_request';
|
||||
|
||||
/// 字号配置常量(编辑区与终端统一)
|
||||
static const double minFontSize = 8.0;
|
||||
static const double maxFontSize = 30.0;
|
||||
@@ -67,12 +83,16 @@ class SettingsProvider extends ChangeNotifier {
|
||||
VirtualKeyboardConfig _terminalKeyboardConfig = VirtualKeyboardConfig.defaultTerminalConfiguration();
|
||||
bool _showHiddenFiles = true;
|
||||
bool _enableLspCompletion = true;
|
||||
ContainerRuntimeMode _containerRuntimeMode = ContainerRuntimeMode.auto;
|
||||
bool _hasPromptedRootRequest = false;
|
||||
Locale? _locale;
|
||||
|
||||
bool get showHiddenFiles => _showHiddenFiles;
|
||||
@Deprecated('本地补全已完全移除')
|
||||
bool get enableLocalCompletion => false;
|
||||
bool get enableLspCompletion => _enableLspCompletion;
|
||||
ContainerRuntimeMode get containerRuntimeMode => _containerRuntimeMode;
|
||||
bool get hasPromptedRootRequest => _hasPromptedRootRequest;
|
||||
|
||||
ThemeMode get appThemeMode => _appThemeMode;
|
||||
Color get appThemeColor => _appThemeColor;
|
||||
@@ -312,10 +332,46 @@ class SettingsProvider extends ChangeNotifier {
|
||||
_locale = null;
|
||||
}
|
||||
|
||||
//设置容器运行模式与 Root 提示标记
|
||||
final savedRuntimeMode = prefs.getString(_keyContainerRuntimeMode);
|
||||
if (savedRuntimeMode != null) {
|
||||
_containerRuntimeMode = ContainerRuntimeMode.values.firstWhere(
|
||||
(e) => e.name == savedRuntimeMode,
|
||||
orElse: () => ContainerRuntimeMode.auto,
|
||||
);
|
||||
}
|
||||
|
||||
final savedPromptedRoot = prefs.getBool(_keyHasPromptedRootRequest);
|
||||
if (savedPromptedRoot != null) {
|
||||
_hasPromptedRootRequest = savedPromptedRoot;
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}catch (_) {}
|
||||
}
|
||||
|
||||
/// 设置容器运行模式 (auto / proot / chroot)
|
||||
Future<void> setContainerRuntimeMode(ContainerRuntimeMode mode) async {
|
||||
if (_containerRuntimeMode == mode) return;
|
||||
_containerRuntimeMode = mode;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyContainerRuntimeMode, mode.name);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 设置是否已主动申请过 Root 权限标记
|
||||
Future<void> setHasPromptedRootRequest(bool value) async {
|
||||
if (_hasPromptedRootRequest == value) return;
|
||||
_hasPromptedRootRequest = value;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyHasPromptedRootRequest, value);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setAppThemeMode(ThemeMode mode) async {
|
||||
if(_appThemeMode == mode) return;
|
||||
_appThemeMode = mode;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// Chroot 环境准备、挂载管理与生命周期服务
|
||||
class ChrootMountManager {
|
||||
static final ChrootMountManager instance = ChrootMountManager._();
|
||||
ChrootMountManager._();
|
||||
|
||||
/// 测试桩:用于单测模拟挂载准备是否成功
|
||||
@visibleForTesting
|
||||
bool? mockPrepareSuccess;
|
||||
|
||||
/// 准备并挂载 Chroot 运行环境
|
||||
///
|
||||
/// 执行步骤:
|
||||
/// 1. 预先执行懒卸载清理旧挂载,保证环境纯净;
|
||||
/// 2. 挂载 /data suid;
|
||||
/// 3. 安全挂载 /dev, /dev/pts, /dev/shm, /proc, /sys;
|
||||
/// 4. 挂载手机外部存储 /sdcard 与工程工作区目录 /workspace;
|
||||
/// 5. 确保 /etc/resolv.conf 存在有效 DNS;
|
||||
/// 6. 执行最小化探针测试,若失败返回 false。
|
||||
Future<bool> prepareChrootEnvironment({
|
||||
required Directory rootDir,
|
||||
String? workspacePath,
|
||||
Duration timeout = const Duration(seconds: 8),
|
||||
}) async {
|
||||
if (mockPrepareSuccess != null) {
|
||||
return mockPrepareSuccess!;
|
||||
}
|
||||
|
||||
if (!kIsWeb && !Platform.isAndroid) {
|
||||
// 非 Android 平台测试环境降级
|
||||
return false;
|
||||
}
|
||||
|
||||
final rootfs = rootDir.path;
|
||||
final workspace = workspacePath ?? '';
|
||||
|
||||
final script = StringBuffer();
|
||||
// 1. 懒卸载陈旧挂载
|
||||
script.writeln('umount -l "$rootfs/workspace" 2>/dev/null');
|
||||
script.writeln('umount -l "$rootfs/sdcard" 2>/dev/null');
|
||||
script.writeln('umount -l "$rootfs/dev/pts" 2>/dev/null');
|
||||
script.writeln('umount -l "$rootfs/dev/shm" 2>/dev/null');
|
||||
script.writeln('umount -l "$rootfs/dev" 2>/dev/null');
|
||||
script.writeln('umount -l "$rootfs/proc" 2>/dev/null');
|
||||
script.writeln('umount -l "$rootfs/sys" 2>/dev/null');
|
||||
|
||||
// 2. 基础目录与权限
|
||||
script.writeln('mount -o remount,suid /data 2>/dev/null');
|
||||
script.writeln('mkdir -p "$rootfs/dev" "$rootfs/proc" "$rootfs/sys" "$rootfs/etc" "$rootfs/root" "$rootfs/sdcard" "$rootfs/workspace" 2>/dev/null');
|
||||
|
||||
// 3. 核心虚拟文件系统挂载
|
||||
script.writeln('mount --bind /dev "$rootfs/dev" 2>/dev/null');
|
||||
script.writeln('mkdir -p "$rootfs/dev/pts" "$rootfs/dev/shm" 2>/dev/null');
|
||||
script.writeln('mount -t devpts devpts -o gid=5,mode=620 "$rootfs/dev/pts" 2>/dev/null');
|
||||
script.writeln('mount -t tmpfs tmpfs -o mode=1777 "$rootfs/dev/shm" 2>/dev/null');
|
||||
script.writeln('mount -t proc proc "$rootfs/proc" 2>/dev/null');
|
||||
script.writeln('mount --bind /sys "$rootfs/sys" 2>/dev/null');
|
||||
|
||||
// 4. 存储与工作区
|
||||
script.writeln('if [ -d /sdcard ]; then mount --bind /sdcard "$rootfs/sdcard" 2>/dev/null; fi');
|
||||
if (workspace.isNotEmpty) {
|
||||
script.writeln('if [ -d "$workspace" ]; then mount --bind "$workspace" "$rootfs/workspace" 2>/dev/null; fi');
|
||||
}
|
||||
|
||||
// 5. DNS 配置
|
||||
script.writeln('if [ ! -s "$rootfs/etc/resolv.conf" ]; then');
|
||||
script.writeln(' echo "nameserver 223.5.5.5" > "$rootfs/etc/resolv.conf" 2>/dev/null');
|
||||
script.writeln(' echo "nameserver 119.29.29.29" >> "$rootfs/etc/resolv.conf" 2>/dev/null');
|
||||
script.writeln(' echo "nameserver 1.1.1.1" >> "$rootfs/etc/resolv.conf" 2>/dev/null');
|
||||
script.writeln(' echo "nameserver 8.8.8.8" >> "$rootfs/etc/resolv.conf" 2>/dev/null');
|
||||
script.writeln('fi');
|
||||
|
||||
// 6. 验证环境是否能通过 chroot 执行最小探针
|
||||
script.writeln('CHROOT_BIN="\$(command -v chroot 2>/dev/null || echo "/system/bin/chroot")"');
|
||||
script.writeln('"\$CHROOT_BIN" "$rootfs" /bin/sh -c "exit 0"');
|
||||
|
||||
try {
|
||||
final result = await Process.run(
|
||||
'su',
|
||||
['-c', script.toString()],
|
||||
).timeout(timeout);
|
||||
|
||||
if (result.exitCode == 0) {
|
||||
return true;
|
||||
} else {
|
||||
debugPrint('[ChrootMountManager] 挂载或探针校验失败 (exitCode ${result.exitCode}): ${result.stderr}');
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[ChrootMountManager] 准备 Chroot 异常: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 安全释放清理挂载点
|
||||
Future<void> cleanupMounts(Directory rootDir) async {
|
||||
if (!kIsWeb && !Platform.isAndroid) return;
|
||||
final rootfs = rootDir.path;
|
||||
final script = '''
|
||||
umount -l "$rootfs/workspace" 2>/dev/null
|
||||
umount -l "$rootfs/sdcard" 2>/dev/null
|
||||
umount -l "$rootfs/dev/pts" 2>/dev/null
|
||||
umount -l "$rootfs/dev/shm" 2>/dev/null
|
||||
umount -l "$rootfs/dev" 2>/dev/null
|
||||
umount -l "$rootfs/proc" 2>/dev/null
|
||||
umount -l "$rootfs/sys" 2>/dev/null
|
||||
''';
|
||||
try {
|
||||
await Process.run('su', ['-c', script]).timeout(const Duration(seconds: 4));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 探测并解析容器内首选 Shell(优先 zsh,其次 bash,兜底 sh)
|
||||
String resolveTargetShell(Directory rootDir) {
|
||||
if (File(p.join(rootDir.path, 'bin', 'zsh')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'zsh')).existsSync()) {
|
||||
return '/bin/zsh';
|
||||
}
|
||||
if (File(p.join(rootDir.path, 'bin', 'bash')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'bash')).existsSync()) {
|
||||
return '/bin/bash';
|
||||
}
|
||||
return '/bin/sh';
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../models/distro_manifest.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import 'chroot_mount_manager.dart';
|
||||
import 'distro_installer.dart';
|
||||
import 'root_service.dart';
|
||||
|
||||
/// 容器启动配置数据
|
||||
class ProotLaunchConfig {
|
||||
@@ -46,6 +52,12 @@ enum DistroFamily {
|
||||
unknown,
|
||||
}
|
||||
|
||||
/// 当前生效的底层容器运行类型
|
||||
enum ContainerRuntimeType {
|
||||
proot,
|
||||
chroot,
|
||||
}
|
||||
|
||||
/// 后台静默命令的取消令牌:把子进程句柄暴露给上层(如任务探测会话),
|
||||
/// 支持"切换工程 / 关闭弹窗 / 用户取消"时立即终止容器内的长时间探测。
|
||||
class HeadlessCancelToken {
|
||||
@@ -99,6 +111,97 @@ class DistroManager {
|
||||
@visibleForTesting
|
||||
String? customSdcardPath;
|
||||
|
||||
/// 当前生效的容器运行环境(PRoot 或 Chroot)
|
||||
ContainerRuntimeType _activeRuntimeType = ContainerRuntimeType.proot;
|
||||
ContainerRuntimeType get activeRuntimeType => _activeRuntimeType;
|
||||
|
||||
@visibleForTesting
|
||||
set activeRuntimeType(ContainerRuntimeType val) => _activeRuntimeType = val;
|
||||
|
||||
/// 根据设置执行容器运行时检测机制:
|
||||
/// - 自动 (auto):用户有 root 权限时尝试申请(永远只会申请一次);
|
||||
/// 被授予 root 权限则尝试挂载 chroot,挂载失败转 proot;没有被授予直接转 proot。
|
||||
/// - proot 显式:直接转 proot。
|
||||
/// - chroot 显式:如果用户设备有 root 但是软件尚未被授予 root 权限,弹出 dialog 尝试申请;
|
||||
/// 被授予则尝试挂载 chroot,失败转 proot;未被授予直接转 proot。
|
||||
///
|
||||
/// 检测完毕后,通过普通 Toast 告知用户当前生效的环境是 PRoot 还是 Chroot。
|
||||
Future<ContainerRuntimeType> detectAndApplyRuntime({
|
||||
BuildContext? context,
|
||||
required SettingsProvider settings,
|
||||
bool showToast = true,
|
||||
}) async {
|
||||
final mode = settings.containerRuntimeMode;
|
||||
final rootDir = await getSystemRootDir(DistroRepository.defaultSystemName);
|
||||
|
||||
ContainerRuntimeType effective = ContainerRuntimeType.proot;
|
||||
|
||||
switch (mode) {
|
||||
case ContainerRuntimeMode.proot:
|
||||
effective = ContainerRuntimeType.proot;
|
||||
break;
|
||||
|
||||
case ContainerRuntimeMode.auto:
|
||||
bool hasRoot = false;
|
||||
if (RootService.instance.isDeviceRootCapable()) {
|
||||
if (!settings.hasPromptedRootRequest) {
|
||||
hasRoot = await RootService.instance.requestRootPermissionOnce(settings);
|
||||
} else {
|
||||
hasRoot = await RootService.instance.isRootAvailablePassive();
|
||||
}
|
||||
}
|
||||
if (hasRoot && rootDir.existsSync()) {
|
||||
final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment(
|
||||
rootDir: rootDir,
|
||||
);
|
||||
effective = chrootReady ? ContainerRuntimeType.chroot : ContainerRuntimeType.proot;
|
||||
} else {
|
||||
effective = ContainerRuntimeType.proot;
|
||||
}
|
||||
break;
|
||||
|
||||
case ContainerRuntimeMode.chroot:
|
||||
bool hasRoot = false;
|
||||
if (RootService.instance.isDeviceRootCapable()) {
|
||||
hasRoot = await RootService.instance.isRootAvailablePassive();
|
||||
if (!hasRoot) {
|
||||
hasRoot = await RootService.instance.promptRequestRootExplicit();
|
||||
}
|
||||
}
|
||||
if (hasRoot && rootDir.existsSync()) {
|
||||
final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment(
|
||||
rootDir: rootDir,
|
||||
);
|
||||
effective = chrootReady ? ContainerRuntimeType.chroot : ContainerRuntimeType.proot;
|
||||
} else {
|
||||
effective = ContainerRuntimeType.proot;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
_activeRuntimeType = effective;
|
||||
|
||||
if (showToast && context != null && context.mounted) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
if (l10n != null) {
|
||||
final modeName = effective == ContainerRuntimeType.chroot ? 'Chroot' : 'PRoot';
|
||||
final message = l10n.containerRuntimeToast(modeName);
|
||||
try {
|
||||
ScaffoldMessenger.of(context).removeCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(message),
|
||||
duration: const Duration(seconds: 2),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
return effective;
|
||||
}
|
||||
|
||||
/// 获取发行版存储基础目录: `<app_dir>/distros`
|
||||
Future<Directory> getBaseDistrosDir() async {
|
||||
if (customBaseDir != null) {
|
||||
@@ -341,6 +444,7 @@ class DistroManager {
|
||||
String prootPath = 'proot',
|
||||
String? customCommand,
|
||||
Directory? customRootDir,
|
||||
SettingsProvider? settingsProvider,
|
||||
}) async {
|
||||
// 1. 本地 Shell 特殊处理
|
||||
if (systemName == 'host') {
|
||||
@@ -360,13 +464,116 @@ class DistroManager {
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Linux 容器 (PRoot 隔离环境)
|
||||
// 2. Linux 容器 (动态判定 Chroot 还是 PRoot)
|
||||
final rootDir = customRootDir ?? await getSystemRootDir(systemName);
|
||||
// 前置守卫:rootfs 必须先真实存在。否则下方一系列 ensure*(DNS/CA 证书/shm/l2s/sysdata)
|
||||
// 会 recursive 地创建出一套空壳目录,把"并不存在的系统"伪造成系统选择器里的已安装项。
|
||||
if (!rootDir.existsSync()) {
|
||||
throw StateError('目标系统未安装,拒绝构建启动配置: $systemName(rootfs 不存在: ${rootDir.path})');
|
||||
}
|
||||
|
||||
ContainerRuntimeMode runtimeMode = settingsProvider?.containerRuntimeMode ?? ContainerRuntimeMode.auto;
|
||||
if (settingsProvider == null) {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final saved = prefs.getString('container_runtime_mode');
|
||||
if (saved != null) {
|
||||
runtimeMode = ContainerRuntimeMode.values.firstWhere(
|
||||
(e) => e.name == saved,
|
||||
orElse: () => ContainerRuntimeMode.auto,
|
||||
);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
bool shouldTryChroot = false;
|
||||
if (runtimeMode == ContainerRuntimeMode.chroot) {
|
||||
shouldTryChroot = true;
|
||||
} else if (runtimeMode == ContainerRuntimeMode.auto) {
|
||||
shouldTryChroot = await RootService.instance.isRootAvailablePassive();
|
||||
}
|
||||
|
||||
if (shouldTryChroot) {
|
||||
final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment(
|
||||
rootDir: rootDir,
|
||||
workspacePath: workspacePath,
|
||||
);
|
||||
if (chrootReady) {
|
||||
_activeRuntimeType = ContainerRuntimeType.chroot;
|
||||
return _buildChrootLaunchConfig(
|
||||
rootDir: rootDir,
|
||||
workspacePath: workspacePath,
|
||||
customCommand: customCommand,
|
||||
);
|
||||
} else {
|
||||
_activeRuntimeType = ContainerRuntimeType.proot;
|
||||
debugPrint('[DistroManager] Chroot 环境准备失败,自动优雅降级回 PRoot 模式');
|
||||
}
|
||||
}
|
||||
|
||||
_activeRuntimeType = ContainerRuntimeType.proot;
|
||||
return _buildProotLaunchConfig(
|
||||
systemName: systemName,
|
||||
rootDir: rootDir,
|
||||
workspacePath: workspacePath,
|
||||
prootPath: prootPath,
|
||||
customCommand: customCommand,
|
||||
);
|
||||
}
|
||||
|
||||
/// 构建原生的 Chroot 满血启动配置
|
||||
ProotLaunchConfig _buildChrootLaunchConfig({
|
||||
required Directory rootDir,
|
||||
String? workspacePath,
|
||||
String? customCommand,
|
||||
}) {
|
||||
final targetShell = ChrootMountManager.instance.resolveTargetShell(rootDir);
|
||||
final targetDir = (workspacePath != null && Directory(workspacePath).existsSync())
|
||||
? '/workspace'
|
||||
: '/root';
|
||||
|
||||
String suPath = 'su';
|
||||
for (final p in ['/system/bin/su', '/system/xbin/su', '/sbin/su', '/su/bin/su']) {
|
||||
try {
|
||||
if (File(p).existsSync()) {
|
||||
suPath = p;
|
||||
break;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
const envPrefix = 'LD_PRELOAD= exec env -i HOME=/root USER=root TERM=xterm-256color LANG=C.UTF-8 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
|
||||
const chrootBin = '/system/bin/chroot';
|
||||
|
||||
String shellCmd;
|
||||
if (customCommand != null && customCommand.isNotEmpty) {
|
||||
final escapedCmd = customCommand.replaceAll("'", "'\\''");
|
||||
shellCmd = '$chrootBin "${rootDir.path}" $targetShell -c \'cd $targetDir && $escapedCmd\'';
|
||||
} else {
|
||||
shellCmd = '$chrootBin "${rootDir.path}" $targetShell -l';
|
||||
}
|
||||
|
||||
final fullCommand = '$envPrefix $shellCmd';
|
||||
|
||||
return ProotLaunchConfig(
|
||||
executable: suPath,
|
||||
arguments: ['-c', fullCommand],
|
||||
environment: {
|
||||
'TERM': 'xterm-256color',
|
||||
'SHELL': '/system/bin/sh',
|
||||
},
|
||||
workingDirectory: rootDir.path,
|
||||
);
|
||||
}
|
||||
|
||||
/// 构建 PRoot 容器隔离运行配置
|
||||
Future<ProotLaunchConfig> _buildProotLaunchConfig({
|
||||
required String systemName,
|
||||
required Directory rootDir,
|
||||
String? workspacePath,
|
||||
String prootPath = 'proot',
|
||||
String? customCommand,
|
||||
}) async {
|
||||
final nativeDir = await getNativeLibraryDir();
|
||||
final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath;
|
||||
final targetShell = _resolveTargetShell(rootDir);
|
||||
@@ -390,13 +597,13 @@ class DistroManager {
|
||||
await DistroInstaller.ensureAptPolicyAndDiversions(rootDir);
|
||||
|
||||
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
|
||||
final shmDir = await _ensureShmDir(systemName, customBaseDir: customRootDir?.parent);
|
||||
final shmDir = await _ensureShmDir(systemName, customBaseDir: rootDir.parent);
|
||||
|
||||
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范,位于 rootfs/.l2s)
|
||||
final l2sDir = await _ensureL2sDir(systemName, rootDir, customBaseDir: customRootDir?.parent);
|
||||
final l2sDir = await _ensureL2sDir(systemName, rootDir, customBaseDir: rootDir.parent);
|
||||
|
||||
// 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据)
|
||||
final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: customRootDir?.parent);
|
||||
final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: rootDir.parent);
|
||||
|
||||
String tmpPath = '/tmp';
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
|
||||
/// 设备 Root 权限探测与授权管理服务
|
||||
class RootService {
|
||||
static final RootService instance = RootService._();
|
||||
RootService._();
|
||||
|
||||
/// 测试桩:用于单测中模拟设备是否具备 Root 能力
|
||||
@visibleForTesting
|
||||
bool? mockRootCapable;
|
||||
|
||||
/// 测试桩:用于单测中模拟 Root 授权状态
|
||||
@visibleForTesting
|
||||
bool? mockRootGranted;
|
||||
|
||||
/// 常见 Linux/Android su 二进制搜索路径
|
||||
static const List<String> _commonSuPaths = [
|
||||
'/system/bin/su',
|
||||
'/system/xbin/su',
|
||||
'/sbin/su',
|
||||
'/system/xbin/daemonsu',
|
||||
'/su/bin/su',
|
||||
'/system/sd/xbin/su',
|
||||
'/data/local/xbin/su',
|
||||
'/data/local/bin/su',
|
||||
];
|
||||
|
||||
/// 静态检测当前设备是否具备 Root 能力(文件系统存在 su 二进制)
|
||||
///
|
||||
/// 该方法纯粹检查静态文件路径,绝不调用任何命令,因此绝对不会触发 Magisk / KernelSU / APatch 授权弹窗。
|
||||
bool isDeviceRootCapable() {
|
||||
if (mockRootCapable != null) {
|
||||
return mockRootCapable!;
|
||||
}
|
||||
|
||||
if (!kIsWeb && Platform.isAndroid) {
|
||||
for (final path in _commonSuPaths) {
|
||||
try {
|
||||
if (File(path).existsSync()) {
|
||||
return true;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 全局入口单次防打扰 Root 授权申请
|
||||
///
|
||||
/// 规则:
|
||||
/// 1. 如果设备本身没有 Root 能力,完全不申请权限;
|
||||
/// 2. 如果具备 Root 能力,仅在首次启动时主动执行一次 `su` 触发系统授权弹窗;
|
||||
/// 3. 记录标记 `hasPromptedRootRequest = true`,无论用户同意还是拒绝,之后永不再主动弹出。
|
||||
Future<bool> requestRootPermissionOnce(SettingsProvider settings) async {
|
||||
if (settings.hasPromptedRootRequest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isDeviceRootCapable()) {
|
||||
await settings.setHasPromptedRootRequest(true);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 标记为已主动申请过,防止后续反复打扰
|
||||
await settings.setHasPromptedRootRequest(true);
|
||||
|
||||
// 触发单次授权探测
|
||||
return await isRootAvailablePassive();
|
||||
}
|
||||
|
||||
/// 被动检测当前是否已获得真实 Root 权限 (uid=0)
|
||||
///
|
||||
/// 仅在用户主动触发 Chroot 操作、或 Auto 模式下准备启动容器时被动调用。
|
||||
Future<bool> isRootAvailablePassive({Duration timeout = const Duration(seconds: 4)}) async {
|
||||
if (mockRootGranted != null) {
|
||||
return mockRootGranted!;
|
||||
}
|
||||
|
||||
if (!isDeviceRootCapable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
final result = await Process.run(
|
||||
'su',
|
||||
['-c', 'id -u'],
|
||||
).timeout(timeout);
|
||||
|
||||
if (result.exitCode == 0) {
|
||||
final out = result.stdout.toString().trim();
|
||||
return out == '0';
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[RootService] 被动 Root 检查失败: $e');
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 显式尝试申请 Root 权限(执行一次 `su` 唤起系统的授权 dialog)
|
||||
Future<bool> promptRequestRootExplicit({Duration timeout = const Duration(seconds: 8)}) async {
|
||||
return await isRootAvailablePassive(timeout: timeout);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import 'package:code_editor/services/file_service.dart';
|
||||
import 'package:code_editor/services/internal_engine_service.dart';
|
||||
import 'package:code_editor/services/lsp/lsp_manager.dart';
|
||||
import 'package:code_editor/services/lsp_config_service.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@@ -73,6 +74,11 @@ class _MainViewState extends State<MainView> {
|
||||
if (mounted) {
|
||||
InternalEngineService.instance.ensureEngineReady(context);
|
||||
LspConfigService.instance.loadConfigs();
|
||||
DistroManager().detectAndApplyRuntime(
|
||||
context: context,
|
||||
settings: context.read<SettingsProvider>(),
|
||||
showToast: true,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import 'package:code_editor/models/virtual_keyboard_config.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../services/distro_manager.dart';
|
||||
import '../services/internal_engine_service.dart';
|
||||
import '../services/root_service.dart';
|
||||
import '../widgets/color_palette_dialog.dart';
|
||||
import 'code_completion_management_view.dart';
|
||||
import 'virtual_keyboard_config_view.dart';
|
||||
@@ -87,6 +89,7 @@ class SettingsView extends StatelessWidget {
|
||||
// 5. 容器分组 (Container)
|
||||
// ==============================
|
||||
_buildSectionHeader(context, l10n.containerSection),
|
||||
_buildContainerRuntimeModeTile(context, provider, l10n),
|
||||
_buildRebuildContainerTile(context, l10n),
|
||||
|
||||
const Divider(height: 32, indent: 16, endIndent: 16),
|
||||
@@ -1140,6 +1143,127 @@ class SettingsView extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// 容器:运行模式选择条目 (Auto / PRoot / Chroot)
|
||||
Widget _buildContainerRuntimeModeTile(
|
||||
BuildContext context,
|
||||
SettingsProvider provider,
|
||||
AppLocalizations l10n,
|
||||
) {
|
||||
final theme = Theme.of(context);
|
||||
final currentMode = provider.containerRuntimeMode;
|
||||
final modeTitle = switch (currentMode) {
|
||||
ContainerRuntimeMode.auto => l10n.containerRuntimeModeAuto,
|
||||
ContainerRuntimeMode.proot => l10n.containerRuntimeModeProot,
|
||||
ContainerRuntimeMode.chroot => l10n.containerRuntimeModeChroot,
|
||||
};
|
||||
|
||||
return ListTile(
|
||||
leading: Icon(Icons.rocket_launch_outlined, color: theme.colorScheme.primary),
|
||||
title: Text(l10n.containerRuntimeMode),
|
||||
subtitle: Text(modeTitle),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
_showContainerRuntimeModeSelector(context, provider, l10n);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showContainerRuntimeModeSelector(
|
||||
BuildContext context,
|
||||
SettingsProvider provider,
|
||||
AppLocalizations l10n,
|
||||
) async {
|
||||
final currentMode = provider.containerRuntimeMode;
|
||||
final theme = Theme.of(context);
|
||||
final isRootGranted = await RootService.instance.isRootAvailablePassive();
|
||||
|
||||
if (!context.mounted) return;
|
||||
|
||||
final options = [
|
||||
(
|
||||
mode: ContainerRuntimeMode.auto,
|
||||
title: l10n.containerRuntimeModeAuto,
|
||||
icon: Icons.auto_mode_rounded,
|
||||
enabled: true,
|
||||
),
|
||||
(
|
||||
mode: ContainerRuntimeMode.proot,
|
||||
title: l10n.containerRuntimeModeProot,
|
||||
icon: Icons.shield_outlined,
|
||||
enabled: true,
|
||||
),
|
||||
(
|
||||
mode: ContainerRuntimeMode.chroot,
|
||||
title: l10n.containerRuntimeModeChroot,
|
||||
icon: Icons.bolt_rounded,
|
||||
enabled: isRootGranted,
|
||||
),
|
||||
];
|
||||
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (sheetContext) {
|
||||
return SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
l10n.selectContainerRuntimeMode,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
for (final opt in options) ...[
|
||||
ListTile(
|
||||
enabled: opt.enabled,
|
||||
leading: Icon(
|
||||
opt.icon,
|
||||
color: opt.enabled
|
||||
? (opt.mode == currentMode ? theme.colorScheme.primary : null)
|
||||
: theme.disabledColor,
|
||||
),
|
||||
title: Text(
|
||||
opt.title,
|
||||
style: TextStyle(
|
||||
fontWeight: opt.mode == currentMode ? FontWeight.bold : FontWeight.normal,
|
||||
color: opt.enabled
|
||||
? (opt.mode == currentMode ? theme.colorScheme.primary : null)
|
||||
: theme.disabledColor,
|
||||
),
|
||||
),
|
||||
trailing: opt.mode == currentMode
|
||||
? Icon(Icons.check, color: opt.enabled ? theme.colorScheme.primary : theme.disabledColor)
|
||||
: (!opt.enabled ? Icon(Icons.lock_outline, size: 18, color: theme.disabledColor) : null),
|
||||
onTap: opt.enabled
|
||||
? () async {
|
||||
Navigator.of(sheetContext).pop();
|
||||
if (provider.containerRuntimeMode != opt.mode) {
|
||||
await provider.setContainerRuntimeMode(opt.mode);
|
||||
}
|
||||
if (context.mounted) {
|
||||
await DistroManager().detectAndApplyRuntime(
|
||||
context: context,
|
||||
settings: provider,
|
||||
showToast: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
: null,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 容器:销毁并重建容器条目
|
||||
Widget _buildRebuildContainerTile(
|
||||
BuildContext context,
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:code_editor/services/chroot_mount_manager.dart';
|
||||
import 'package:code_editor/services/distro_manager.dart';
|
||||
import 'package:code_editor/services/root_service.dart';
|
||||
import 'package:code_editor/views/settings_view.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
RootService.instance.mockRootCapable = null;
|
||||
RootService.instance.mockRootGranted = null;
|
||||
ChrootMountManager.instance.mockPrepareSuccess = null;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
RootService.instance.mockRootCapable = null;
|
||||
RootService.instance.mockRootGranted = null;
|
||||
ChrootMountManager.instance.mockPrepareSuccess = null;
|
||||
});
|
||||
|
||||
group('RootService Tests', () {
|
||||
test('isDeviceRootCapable defaults to false on non-rooted/desktop test environment', () {
|
||||
expect(RootService.instance.isDeviceRootCapable(), isFalse);
|
||||
});
|
||||
|
||||
test('isDeviceRootCapable honors mockRootCapable', () {
|
||||
RootService.instance.mockRootCapable = true;
|
||||
expect(RootService.instance.isDeviceRootCapable(), isTrue);
|
||||
|
||||
RootService.instance.mockRootCapable = false;
|
||||
expect(RootService.instance.isDeviceRootCapable(), isFalse);
|
||||
});
|
||||
|
||||
test('requestRootPermissionOnce does not prompt if device is not root capable', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
expect(settings.hasPromptedRootRequest, isFalse);
|
||||
|
||||
RootService.instance.mockRootCapable = false;
|
||||
final result = await RootService.instance.requestRootPermissionOnce(settings);
|
||||
|
||||
expect(result, isFalse);
|
||||
expect(settings.hasPromptedRootRequest, isTrue);
|
||||
});
|
||||
|
||||
test('requestRootPermissionOnce prompts once on root capable device, never prompts again', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
|
||||
RootService.instance.mockRootCapable = true;
|
||||
RootService.instance.mockRootGranted = true;
|
||||
|
||||
// First call prompts and grants
|
||||
final firstResult = await RootService.instance.requestRootPermissionOnce(settings);
|
||||
expect(firstResult, isTrue);
|
||||
expect(settings.hasPromptedRootRequest, isTrue);
|
||||
|
||||
// Second call does nothing (never prompts again)
|
||||
RootService.instance.mockRootGranted = false;
|
||||
final secondResult = await RootService.instance.requestRootPermissionOnce(settings);
|
||||
expect(secondResult, isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('SettingsProvider ContainerRuntimeMode Tests', () {
|
||||
test('containerRuntimeMode defaults to auto and persists changes', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
|
||||
expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.auto));
|
||||
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.chroot);
|
||||
expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.chroot));
|
||||
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.proot);
|
||||
expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.proot));
|
||||
|
||||
// Re-init from SharedPreferences
|
||||
final newSettings = SettingsProvider();
|
||||
await newSettings.init();
|
||||
expect(newSettings.containerRuntimeMode, equals(ContainerRuntimeMode.proot));
|
||||
});
|
||||
});
|
||||
|
||||
group('ChrootMountManager Tests', () {
|
||||
test('resolveTargetShell resolves zsh > bash > sh', () {
|
||||
final tempDir = Directory.systemTemp.createTempSync('chroot_test_');
|
||||
try {
|
||||
final binDir = Directory('${tempDir.path}/bin')..createSync(recursive: true);
|
||||
|
||||
// Neither exists -> /bin/sh
|
||||
expect(ChrootMountManager.instance.resolveTargetShell(tempDir), equals('/bin/sh'));
|
||||
|
||||
// bash exists -> /bin/bash
|
||||
final bashFile = File('${binDir.path}/bash')..writeAsStringSync('');
|
||||
expect(ChrootMountManager.instance.resolveTargetShell(tempDir), equals('/bin/bash'));
|
||||
|
||||
// zsh exists -> /bin/zsh (preferred over bash)
|
||||
final zshFile = File('${binDir.path}/zsh')..writeAsStringSync('');
|
||||
expect(ChrootMountManager.instance.resolveTargetShell(tempDir), equals('/bin/zsh'));
|
||||
|
||||
zshFile.deleteSync();
|
||||
bashFile.deleteSync();
|
||||
} finally {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('DistroManager Double-Track Dispatch & Fallback Tests', () {
|
||||
late Directory mockRootDir;
|
||||
|
||||
setUp(() {
|
||||
mockRootDir = Directory.systemTemp.createTempSync('distro_dispatch_test_');
|
||||
Directory('${mockRootDir.path}/etc').createSync(recursive: true);
|
||||
Directory('${mockRootDir.path}/bin').createSync(recursive: true);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
try {
|
||||
mockRootDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
test('buildLaunchConfig returns PRoot when mode is proot', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.proot);
|
||||
|
||||
final config = await DistroManager().buildLaunchConfig(
|
||||
systemName: 'test_system',
|
||||
customRootDir: mockRootDir,
|
||||
settingsProvider: settings,
|
||||
);
|
||||
|
||||
// PRoot configuration does not use su
|
||||
expect(config.executable, isNot(equals('su')));
|
||||
expect(config.arguments, contains('--kill-on-exit'));
|
||||
});
|
||||
|
||||
test('buildLaunchConfig returns Chroot when mode is chroot and prepare succeeds', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.chroot);
|
||||
|
||||
ChrootMountManager.instance.mockPrepareSuccess = true;
|
||||
|
||||
final config = await DistroManager().buildLaunchConfig(
|
||||
systemName: 'test_system',
|
||||
customRootDir: mockRootDir,
|
||||
settingsProvider: settings,
|
||||
customCommand: 'echo hello',
|
||||
);
|
||||
|
||||
// Chroot configuration uses su and passes chroot command
|
||||
expect(config.executable.endsWith('su'), isTrue);
|
||||
expect(config.arguments, contains('-c'));
|
||||
expect(config.arguments.last, contains('/system/bin/chroot'));
|
||||
expect(config.arguments.last, contains('echo hello'));
|
||||
});
|
||||
|
||||
test('buildLaunchConfig smoothly falls back to PRoot when chroot prepare fails', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.chroot);
|
||||
|
||||
// Chroot mount or check fails (e.g. root denied)
|
||||
ChrootMountManager.instance.mockPrepareSuccess = false;
|
||||
|
||||
final config = await DistroManager().buildLaunchConfig(
|
||||
systemName: 'test_system',
|
||||
customRootDir: mockRootDir,
|
||||
settingsProvider: settings,
|
||||
);
|
||||
|
||||
// Should automatically fall back to PRoot
|
||||
expect(config.arguments, contains('--kill-on-exit'));
|
||||
});
|
||||
|
||||
test('buildLaunchConfig in auto mode uses Chroot when Root available, falls back to PRoot when not', () async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.auto);
|
||||
|
||||
// 1. Root not available -> PRoot
|
||||
RootService.instance.mockRootGranted = false;
|
||||
final prootConfig = await DistroManager().buildLaunchConfig(
|
||||
systemName: 'test_system',
|
||||
customRootDir: mockRootDir,
|
||||
settingsProvider: settings,
|
||||
);
|
||||
expect(prootConfig.arguments, contains('--kill-on-exit'));
|
||||
|
||||
// 2. Root available & Chroot prepare success -> Chroot
|
||||
RootService.instance.mockRootGranted = true;
|
||||
ChrootMountManager.instance.mockPrepareSuccess = true;
|
||||
final chrootConfig = await DistroManager().buildLaunchConfig(
|
||||
systemName: 'test_system',
|
||||
customRootDir: mockRootDir,
|
||||
settingsProvider: settings,
|
||||
);
|
||||
expect(chrootConfig.executable.endsWith('su'), isTrue);
|
||||
expect(chrootConfig.arguments.last, contains('/system/bin/chroot'));
|
||||
});
|
||||
|
||||
testWidgets('detectAndApplyRuntime auto mode: falls back to proot and shows toast if root denied', (tester) async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.auto);
|
||||
|
||||
RootService.instance.mockRootCapable = true;
|
||||
RootService.instance.mockRootGranted = false;
|
||||
|
||||
late BuildContext testContext;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final result = await DistroManager().detectAndApplyRuntime(
|
||||
context: testContext,
|
||||
settings: settings,
|
||||
showToast: true,
|
||||
);
|
||||
|
||||
expect(result, equals(ContainerRuntimeType.proot));
|
||||
await tester.pump();
|
||||
expect(find.text('当前容器运行环境:PRoot'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('detectAndApplyRuntime auto mode: selects chroot and shows toast if root granted and mount ok', (tester) async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.auto);
|
||||
|
||||
RootService.instance.mockRootCapable = true;
|
||||
RootService.instance.mockRootGranted = true;
|
||||
ChrootMountManager.instance.mockPrepareSuccess = true;
|
||||
|
||||
late BuildContext testContext;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final result = await DistroManager().detectAndApplyRuntime(
|
||||
context: testContext,
|
||||
settings: settings,
|
||||
showToast: true,
|
||||
);
|
||||
|
||||
expect(result, equals(ContainerRuntimeType.chroot));
|
||||
await tester.pump();
|
||||
expect(find.text('当前容器运行环境:Chroot'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('detectAndApplyRuntime chroot mode: prompts explicit and falls back to proot if mount fails', (tester) async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
await settings.setContainerRuntimeMode(ContainerRuntimeMode.chroot);
|
||||
|
||||
RootService.instance.mockRootCapable = true;
|
||||
RootService.instance.mockRootGranted = true;
|
||||
ChrootMountManager.instance.mockPrepareSuccess = false; // Mount fails
|
||||
|
||||
late BuildContext testContext;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final result = await DistroManager().detectAndApplyRuntime(
|
||||
context: testContext,
|
||||
settings: settings,
|
||||
showToast: true,
|
||||
);
|
||||
|
||||
// Should smoothly fall back to proot
|
||||
expect(result, equals(ContainerRuntimeType.proot));
|
||||
await tester.pump();
|
||||
expect(find.text('当前容器运行环境:PRoot'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
group('SettingsView Container Runtime UI Tests', () {
|
||||
testWidgets('SettingsView disables Chroot when root is not granted', (tester) async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
RootService.instance.mockRootGranted = false;
|
||||
|
||||
await tester.pumpWidget(
|
||||
ChangeNotifierProvider<SettingsProvider>.value(
|
||||
value: settings,
|
||||
child: const MaterialApp(
|
||||
locale: Locale('zh'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SettingsView(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final runtimeTileFinder = find.text('容器运行模式');
|
||||
await tester.scrollUntilVisible(runtimeTileFinder, 300.0);
|
||||
expect(runtimeTileFinder, findsOneWidget);
|
||||
expect(find.text('自动'), findsOneWidget);
|
||||
|
||||
await tester.tap(runtimeTileFinder);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('选择容器运行模式'), findsOneWidget);
|
||||
expect(find.text('PRoot'), findsOneWidget);
|
||||
expect(find.text('Chroot'), findsOneWidget);
|
||||
|
||||
// Chroot should be disabled (has lock outline icon)
|
||||
final chrootTile = tester.widget<ListTile>(
|
||||
find.ancestor(of: find.text('Chroot'), matching: find.byType(ListTile)),
|
||||
);
|
||||
expect(chrootTile.enabled, isFalse);
|
||||
|
||||
// Tapping disabled Chroot does not change mode
|
||||
await tester.tap(find.text('Chroot'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.auto));
|
||||
});
|
||||
|
||||
testWidgets('SettingsView allows Chroot selection when root is granted and shows toast', (tester) async {
|
||||
final settings = SettingsProvider();
|
||||
await settings.init();
|
||||
RootService.instance.mockRootGranted = true;
|
||||
ChrootMountManager.instance.mockPrepareSuccess = true;
|
||||
|
||||
await tester.pumpWidget(
|
||||
ChangeNotifierProvider<SettingsProvider>.value(
|
||||
value: settings,
|
||||
child: const MaterialApp(
|
||||
locale: Locale('zh'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SettingsView(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final runtimeTileFinder = find.text('容器运行模式');
|
||||
await tester.scrollUntilVisible(runtimeTileFinder, 300.0);
|
||||
await tester.tap(runtimeTileFinder);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final chrootTile = tester.widget<ListTile>(
|
||||
find.ancestor(of: find.text('Chroot'), matching: find.byType(ListTile)),
|
||||
);
|
||||
expect(chrootTile.enabled, isTrue);
|
||||
|
||||
await tester.tap(find.text('Chroot'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.chroot));
|
||||
expect(find.text('当前容器运行环境:Chroot'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user