1
This commit is contained in:
1 parent
54c3083c24
commit
87e03ce0d8
44 files changed
+3965
-307
No files matched your search
@@ -0,0 +1,133 @@
|
||||
import 'dart:io';
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// 安装进度回调
|
||||
/// [progress] 0.0 ~ 1.0
|
||||
/// [message] 当前阶段说明
|
||||
typedef InstallProgressCallback = void Function(double progress, String message);
|
||||
|
||||
/// Linux 发行版 Rootfs 安装与解压服务
|
||||
class DistroInstaller {
|
||||
/// 解压并安装 tar.gz 格式的 Rootfs 到目标目录
|
||||
///
|
||||
/// [tarGzBytes] .tar.gz 压缩包字节流
|
||||
/// [targetDir] 目标解压目录 (即容器的 rootfs 路径)
|
||||
/// [onProgress] 进度回调
|
||||
static Future<void> installFromBytes({
|
||||
required Uint8List tarGzBytes,
|
||||
required Directory targetDir,
|
||||
InstallProgressCallback? onProgress,
|
||||
}) async {
|
||||
onProgress?.call(0.05, '正在校验与解析系统镜像...');
|
||||
|
||||
if (!targetDir.existsSync()) {
|
||||
targetDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
// 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿)
|
||||
onProgress?.call(0.15, '正在解压内核与文件系统结构...');
|
||||
final archive = await compute(_decodeTarGz, tarGzBytes);
|
||||
|
||||
// 2. 写入文件与目录
|
||||
final total = archive.length;
|
||||
int processed = 0;
|
||||
|
||||
for (final file in archive) {
|
||||
processed++;
|
||||
final filename = file.name;
|
||||
// 避免路径穿越漏洞 (Directory Traversal)
|
||||
if (filename.contains('..')) continue;
|
||||
|
||||
final outPath = p.join(targetDir.path, filename);
|
||||
|
||||
if (file.isFile) {
|
||||
final parentDir = Directory(p.dirname(outPath));
|
||||
if (!parentDir.existsSync()) {
|
||||
parentDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
// 处理符号链接与常规文件
|
||||
if (file.isSymbolicLink) {
|
||||
try {
|
||||
final link = Link(outPath);
|
||||
if (link.existsSync()) link.deleteSync();
|
||||
link.createSync(file.nameOfLinkedFile);
|
||||
} catch (_) {
|
||||
// Windows 或受限环境降级为写入目标路径文本或忽略
|
||||
}
|
||||
} else {
|
||||
final content = file.content as List<int>;
|
||||
File(outPath).writeAsBytesSync(content, flush: false);
|
||||
}
|
||||
} else {
|
||||
Directory(outPath).createSync(recursive: true);
|
||||
}
|
||||
|
||||
if (processed % 100 == 0 || processed == total) {
|
||||
final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90%
|
||||
onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...');
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 执行系统配置与网络补丁
|
||||
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
|
||||
await postInstallConfigure(targetDir);
|
||||
|
||||
onProgress?.call(1.0, '系统初始化就绪!');
|
||||
}
|
||||
|
||||
/// 后台 Isolate 解压 tar.gz
|
||||
static Archive _decodeTarGz(Uint8List bytes) {
|
||||
final tarData = GZipDecoder().decodeBytes(bytes);
|
||||
return TarDecoder().decodeBytes(tarData);
|
||||
}
|
||||
|
||||
/// 自动化环境补丁与配置
|
||||
/// 1. 注入 DNS (resolv.conf) 防止容器内 apk/apt 无法联网
|
||||
/// 2. 注入 hosts
|
||||
/// 3. 创建挂载点 /workspace 和 /tmp
|
||||
static Future<void> postInstallConfigure(Directory rootfsDir) async {
|
||||
final etcDir = Directory(p.join(rootfsDir.path, 'etc'));
|
||||
if (!etcDir.existsSync()) {
|
||||
etcDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
// 1. 配置 DNS 解析器
|
||||
final resolvFile = File(p.join(etcDir.path, 'resolv.conf'));
|
||||
try {
|
||||
resolvFile.writeAsStringSync(
|
||||
'# Generated by CodeEditor DistroManager\n'
|
||||
'nameserver 1.1.1.1\n'
|
||||
'nameserver 8.8.8.8\n'
|
||||
'nameserver 114.114.114.114\n',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 resolv.conf 失败: $e');
|
||||
}
|
||||
|
||||
// 2. 配置 hosts
|
||||
final hostsFile = File(p.join(etcDir.path, 'hosts'));
|
||||
try {
|
||||
hostsFile.writeAsStringSync(
|
||||
'127.0.0.1 localhost\n'
|
||||
'::1 localhost ip6-localhost ip6-loopback\n',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 hosts 失败: $e');
|
||||
}
|
||||
|
||||
// 3. 确保 /workspace 挂载点目录存在
|
||||
final workspaceDir = Directory(p.join(rootfsDir.path, 'workspace'));
|
||||
if (!workspaceDir.existsSync()) {
|
||||
workspaceDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
// 4. 确保 /tmp 目录存在
|
||||
final tmpDir = Directory(p.join(rootfsDir.path, 'tmp'));
|
||||
if (!tmpDir.existsSync()) {
|
||||
tmpDir.createSync(recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../models/distro_info.dart';
|
||||
import 'distro_installer.dart';
|
||||
|
||||
/// 容器启动配置数据
|
||||
class ProotLaunchConfig {
|
||||
/// 可执行程序(proot 二进制路径或 host shell)
|
||||
final String executable;
|
||||
|
||||
/// 启动参数
|
||||
final List<String> arguments;
|
||||
|
||||
/// 环境变量
|
||||
final Map<String, String> environment;
|
||||
|
||||
/// 初始工作目录
|
||||
final String workingDirectory;
|
||||
|
||||
const ProotLaunchConfig({
|
||||
required this.executable,
|
||||
required this.arguments,
|
||||
required this.environment,
|
||||
required this.workingDirectory,
|
||||
});
|
||||
|
||||
/// 格式化为命令行预览字符串
|
||||
String toCommandLine() {
|
||||
final argsStr = arguments.map((a) => a.contains(' ') ? '"$a"' : a).join(' ');
|
||||
return '$executable $argsStr';
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux 发行版管理器服务(单例模式,易扩展)
|
||||
class DistroManager {
|
||||
static final DistroManager _instance = DistroManager._internal();
|
||||
factory DistroManager() => _instance;
|
||||
DistroManager._internal() {
|
||||
// 注册内置默认发行版
|
||||
for (final d in DistroInfo.defaults) {
|
||||
_distros[d.id] = d;
|
||||
}
|
||||
}
|
||||
|
||||
/// 自定义覆盖根目录(主要用于测试)
|
||||
@visibleForTesting
|
||||
Directory? customBaseDir;
|
||||
|
||||
/// 发行版注册表 `Map<id, DistroInfo>`
|
||||
final Map<String, DistroInfo> _distros = {};
|
||||
|
||||
/// 获取所有已注册的发行版
|
||||
List<DistroInfo> listDistros() => _distros.values.toList();
|
||||
|
||||
/// 获取指定发行版元数据
|
||||
DistroInfo? getDistro(String id) => _distros[id];
|
||||
|
||||
/// 动态注册新的发行版(支持未来插件化或用户自定义导入)
|
||||
void registerDistro(DistroInfo distro) {
|
||||
_distros[distro.id] = distro;
|
||||
}
|
||||
|
||||
/// 注销指定发行版
|
||||
void unregisterDistro(String id) {
|
||||
_distros.remove(id);
|
||||
}
|
||||
|
||||
/// 获取发行版存储基础目录: `<app_dir>/distros`
|
||||
Future<Directory> getBaseDistrosDir() async {
|
||||
if (customBaseDir != null) {
|
||||
return customBaseDir!;
|
||||
}
|
||||
final appDir = await getApplicationSupportDirectory();
|
||||
final distrosDir = Directory(p.join(appDir.path, 'distros'));
|
||||
if (!distrosDir.existsSync()) {
|
||||
distrosDir.createSync(recursive: true);
|
||||
}
|
||||
return distrosDir;
|
||||
}
|
||||
|
||||
/// 获取指定发行版的 Rootfs 解压目录: `<app_dir>/distros/<distroId>/rootfs`
|
||||
Future<Directory> getDistroRootDir(String distroId) async {
|
||||
final baseDir = await getBaseDistrosDir();
|
||||
return Directory(p.join(baseDir.path, distroId, 'rootfs'));
|
||||
}
|
||||
|
||||
/// 检测指定发行版是否已安装就绪
|
||||
Future<bool> isInstalled(String distroId) async {
|
||||
// host 为宿主系统,无需安装
|
||||
if (distroId == 'host') return true;
|
||||
|
||||
final rootDir = await getDistroRootDir(distroId);
|
||||
if (!rootDir.existsSync()) return false;
|
||||
|
||||
// 检查关键目录和常用 shell 是否存在
|
||||
final hasEtc = Directory(p.join(rootDir.path, 'etc')).existsSync();
|
||||
final hasBin = Directory(p.join(rootDir.path, 'bin')).existsSync();
|
||||
return hasEtc && hasBin;
|
||||
}
|
||||
|
||||
/// 安装发行版(优先从内置 asset 离线安装,支持进度回调)
|
||||
Future<void> installDistro(
|
||||
String distroId, {
|
||||
InstallProgressCallback? onProgress,
|
||||
}) async {
|
||||
final distro = getDistro(distroId);
|
||||
if (distro == null) {
|
||||
throw ArgumentError('未知的发行版 ID: $distroId');
|
||||
}
|
||||
|
||||
if (distroId == 'host') {
|
||||
onProgress?.call(1.0, '本地 Shell 无需安装');
|
||||
return;
|
||||
}
|
||||
|
||||
final targetDir = await getDistroRootDir(distroId);
|
||||
|
||||
// 优先从内置 Asset 安装
|
||||
if (distro.assetPath != null) {
|
||||
onProgress?.call(0.02, '正在读取内置系统资源包...');
|
||||
final byteData = await rootBundle.load(distro.assetPath!);
|
||||
final bytes = byteData.buffer.asUint8List();
|
||||
|
||||
await DistroInstaller.installFromBytes(
|
||||
tarGzBytes: bytes,
|
||||
targetDir: targetDir,
|
||||
onProgress: onProgress,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 远程下载模式扩展点
|
||||
if (distro.downloadUrl != null) {
|
||||
throw UnsupportedError('远程下载安装功能后续支持,请先使用内置版本');
|
||||
}
|
||||
|
||||
throw StateError('该发行版既无内置 asset 也无下载链接: $distroId');
|
||||
}
|
||||
|
||||
/// 从用户本地指定的 .tar.gz 文件安装自定义系统
|
||||
Future<void> installFromCustomTarGz(
|
||||
String distroId,
|
||||
File tarGzFile, {
|
||||
InstallProgressCallback? onProgress,
|
||||
}) async {
|
||||
final targetDir = await getDistroRootDir(distroId);
|
||||
final bytes = await tarGzFile.readAsBytes();
|
||||
|
||||
await DistroInstaller.installFromBytes(
|
||||
tarGzBytes: bytes,
|
||||
targetDir: targetDir,
|
||||
onProgress: onProgress,
|
||||
);
|
||||
}
|
||||
|
||||
/// 卸载并清除指定发行版的 rootfs 目录
|
||||
Future<void> uninstallDistro(String distroId) async {
|
||||
if (distroId == 'host') return;
|
||||
|
||||
final baseDir = await getBaseDistrosDir();
|
||||
final distroDir = Directory(p.join(baseDir.path, distroId));
|
||||
if (distroDir.existsSync()) {
|
||||
distroDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// 构建 PRoot 容器启动命令与环境参数
|
||||
///
|
||||
/// [distroId] 发行版标识符
|
||||
/// [workspacePath] 挂载的代码工程路径(挂载到容器内部的 /workspace)
|
||||
/// [prootPath] proot 二进制路径(默认可传入 'proot' 或设备内部特定路径)
|
||||
/// [customCommand] 自定义初始执行命令(默认进入交互式 login shell)
|
||||
Future<ProotLaunchConfig> buildLaunchConfig({
|
||||
required String distroId,
|
||||
String? workspacePath,
|
||||
String prootPath = 'proot',
|
||||
String? customCommand,
|
||||
}) async {
|
||||
final distro = getDistro(distroId) ?? DistroInfo.alpine;
|
||||
|
||||
// 1. 本地 Shell 特殊处理:无需 PRoot
|
||||
if (distroId == 'host') {
|
||||
final initialDir = (workspacePath != null && Directory(workspacePath).existsSync())
|
||||
? workspacePath
|
||||
: Directory.current.path;
|
||||
|
||||
final args = customCommand != null ? ['-c', customCommand] : <String>[];
|
||||
return ProotLaunchConfig(
|
||||
executable: distro.defaultShell,
|
||||
arguments: args,
|
||||
environment: {
|
||||
'TERM': 'xterm-256color',
|
||||
},
|
||||
workingDirectory: initialDir,
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Linux 容器 (PRoot 隔离环境)
|
||||
final rootDir = await getDistroRootDir(distroId);
|
||||
final targetShell = distro.defaultShell;
|
||||
|
||||
final args = <String>[
|
||||
'-0', // 模拟 root 权限 (uid 0)
|
||||
'-r', rootDir.path, // 根文件系统路径
|
||||
'-b', '/dev', // 挂载标准设备节点
|
||||
'-b', '/proc', // 挂载进程信息
|
||||
'-b', '/sys', // 挂载系统信息
|
||||
];
|
||||
|
||||
// 挂载工作区
|
||||
String containerWorkDir = '/root';
|
||||
if (workspacePath != null && Directory(workspacePath).existsSync()) {
|
||||
args.addAll(['-b', '$workspacePath:/workspace']);
|
||||
containerWorkDir = '/workspace';
|
||||
}
|
||||
|
||||
// 设置容器内工作目录
|
||||
args.addAll(['-w', containerWorkDir]);
|
||||
|
||||
// 登录 Shell 或自定义命令
|
||||
if (customCommand != null && customCommand.isNotEmpty) {
|
||||
args.addAll([targetShell, '-c', customCommand]);
|
||||
} else {
|
||||
args.addAll([targetShell, '-l']);
|
||||
}
|
||||
|
||||
final env = <String, String>{
|
||||
'HOME': '/root',
|
||||
'USER': 'root',
|
||||
'TERM': 'xterm-256color',
|
||||
'LANG': 'C.UTF-8',
|
||||
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||
'TMPDIR': '/tmp',
|
||||
};
|
||||
|
||||
return ProotLaunchConfig(
|
||||
executable: prootPath,
|
||||
arguments: args,
|
||||
environment: env,
|
||||
workingDirectory: containerWorkDir,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
/// 文件存储权限管理服务
|
||||
class PermissionService {
|
||||
static final PermissionService instance = PermissionService._();
|
||||
PermissionService._();
|
||||
|
||||
/// 检查并确保拥有存储/工作区访问权限
|
||||
///
|
||||
/// 如果未授权且传入了 [context],会弹出友好说明对话框,引导用户前往系统设置开启“所有文件访问权限”。
|
||||
/// 返回 true 表示已获授权或无需该权限(非 Android 平台),false 表示用户拒绝或未授权。
|
||||
Future<bool> ensureStoragePermission({BuildContext? context}) async {
|
||||
// 桌面端(Windows / macOS / Linux)与 Web 端不需要此类移动端运行时权限
|
||||
if (kIsWeb || !Platform.isAndroid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. 优先检查并请求 Android 11+ (API 30+) 的管理所有文件权限
|
||||
var manageStatus = await Permission.manageExternalStorage.status;
|
||||
if (manageStatus.isGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 如果尚未请求过,直接发起系统级请求
|
||||
if (!manageStatus.isPermanentlyDenied) {
|
||||
manageStatus = await Permission.manageExternalStorage.request();
|
||||
if (manageStatus.isGranted) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 兼容 Android 10 及以下:检查普通 storage 权限
|
||||
var storageStatus = await Permission.storage.status;
|
||||
if (storageStatus.isGranted) {
|
||||
return true;
|
||||
}
|
||||
if (!storageStatus.isPermanentlyDenied) {
|
||||
storageStatus = await Permission.storage.request();
|
||||
if (storageStatus.isGranted) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 用户拒绝或处于需要跳转设置的状态,如果有 context 则弹出引导弹窗
|
||||
if (context != null && context.mounted) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final title = l10n?.storagePermissionRequiredTitle ?? '需要存储访问权限';
|
||||
final message = l10n?.storagePermissionRequiredMessage ??
|
||||
'代码编辑器需要“管理所有文件”权限,以便在您的设备上读取、新建和保存项目文件。\n\n请在接下来的系统设置页面中开启该权限。';
|
||||
final confirmText = l10n?.goToSettings ?? '去设置';
|
||||
final cancelText = l10n?.cancel ?? '取消';
|
||||
|
||||
final shouldOpenSettings = await DialogUtils.showConfirmDialog(
|
||||
context,
|
||||
title: title,
|
||||
message: message,
|
||||
confirmText: confirmText,
|
||||
cancelText: cancelText,
|
||||
icon: const Icon(Icons.folder_special_outlined, size: 28),
|
||||
);
|
||||
|
||||
if (shouldOpenSettings) {
|
||||
await openAppSettings();
|
||||
}
|
||||
}
|
||||
|
||||
// 再次确认一次权限状态
|
||||
final recheck = await Permission.manageExternalStorage.status;
|
||||
return recheck.isGranted;
|
||||
} catch (e) {
|
||||
debugPrint('权限检测发生异常: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 快速同步检查是否已经拥有管理所有文件权限(不弹窗)
|
||||
Future<bool> hasStoragePermission() async {
|
||||
if (kIsWeb || !Platform.isAndroid) return true;
|
||||
try {
|
||||
if (await Permission.manageExternalStorage.isGranted) return true;
|
||||
if (await Permission.storage.isGranted) return true;
|
||||
return false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user