This commit is contained in:
LZX committed 2026-09-13 16:41:19 +08:00
1 parent 87e03ce0d8
commit e932c60dbd
47 files changed
+4417 -923

No files matched your search

+119 -1
View File
@@ -121,5 +121,123 @@
"keepLocal": "Keep Local Changes",
"storagePermissionRequiredTitle": "Storage Access Required",
"storagePermissionRequiredMessage": "Code Editor requires \"All files access\" permission to read, create, and save project files on your device.\n\nPlease enable it in the system settings page.",
"goToSettings": "Settings"
"goToSettings": "Settings",
"terminal": "Terminal",
"terminalWithSystem": "Terminal · {system}",
"@terminalWithSystem": {
"placeholders": {
"system": {
"type": "String"
}
}
},
"sessionDefaultName": "Session",
"systemManagement": "System Management",
"systemManagementTooltip": "System Management & Selection",
"sessionListTooltip": "Session List",
"noActiveSessions": "No active sessions",
"terminalInputHint": "Enter command...",
"sendCommandTooltip": "Send Command",
"importNewSystem": "Import New System",
"importBuiltinAlpine": "Import from App (Alpine)",
"importExternalTarGz": "Import from External (.tar.gz)",
"selectSystemDefaultPrompt": "Select a system as default; new terminals will start in this system:",
"noSystemsPrompt": "No systems available. Tap \"+\" at top right to import",
"importBuiltinAlpineTitle": "Import Built-in Alpine System",
"systemNameHintWithDefault": "System name (e.g. {name})",
"@systemNameHintWithDefault": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"systemImportSuccess": "System \"{name}\" imported and ready",
"@systemImportSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"importExternalSystemTitle": "Import External System",
"systemNameHint": "System Name",
"externalSystemImportSuccess": "External system \"{name}\" imported and ready",
"@externalSystemImportSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSystemConfirmTitle": "High-Risk Operation: Delete System",
"deleteSystemConfirmMessage": "Are you sure you want to permanently delete system \"{name}\"?\n\n⚠️ This will physically erase all internal data and installed packages. This cannot be undone!\n\nAll associated terminal sessions will also be closed.",
"@deleteSystemConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"permanentDelete": "Permanently Delete",
"deleteSystemSuccess": "System \"{name}\" and associated sessions deleted",
"@deleteSystemSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSystemTooltip": "Permanently delete this system (High risk)",
"preparingInitialization": "Preparing initialization...",
"cancellingAndCleaning": "Cancelling and cleaning leftover directory...",
"cancelledImportSystem": "Cancelled importing system \"{name}\"",
"@cancelledImportSystem": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"importFailed": "Import failed: {error}",
"@importFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"importingSystemTitle": "Importing: {name}",
"@importingSystemTitle": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"cancelImport": "Cancel Import",
"interrupting": "Interrupting...",
"sessionDrawerTitle": "Sessions",
"addTerminalTooltip": "Add Terminal",
"noSystemSelectedWarning": "No system selected. Please import or select a system first.",
"noSessionsInDrawerPrompt": "No sessions. Tap top right to add",
"confirmDeleteTerminalSession": "Are you sure you want to delete terminal \"({index}) {name}\"?",
"@confirmDeleteTerminalSession": {
"placeholders": {
"index": {
"type": "int"
},
"name": {
"type": "String"
}
}
},
"deleteSystemFailed": "Failed to delete system: {error}",
"@deleteSystemFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
}
}
+228
View File
@@ -781,6 +781,234 @@ abstract class AppLocalizations {
/// In zh, this message translates to:
/// **'去设置'**
String get goToSettings;
/// No description provided for @terminal.
///
/// In zh, this message translates to:
/// **'终端'**
String get terminal;
/// No description provided for @terminalWithSystem.
///
/// In zh, this message translates to:
/// **'终端 · {system}'**
String terminalWithSystem(String system);
/// No description provided for @sessionDefaultName.
///
/// In zh, this message translates to:
/// **'会话'**
String get sessionDefaultName;
/// No description provided for @systemManagement.
///
/// In zh, this message translates to:
/// **'系统管理'**
String get systemManagement;
/// No description provided for @systemManagementTooltip.
///
/// In zh, this message translates to:
/// **'系统管理与选择'**
String get systemManagementTooltip;
/// No description provided for @sessionListTooltip.
///
/// In zh, this message translates to:
/// **'会话列表'**
String get sessionListTooltip;
/// No description provided for @noActiveSessions.
///
/// In zh, this message translates to:
/// **'暂无活跃会话'**
String get noActiveSessions;
/// No description provided for @terminalInputHint.
///
/// In zh, this message translates to:
/// **'输入命令...'**
String get terminalInputHint;
/// No description provided for @sendCommandTooltip.
///
/// In zh, this message translates to:
/// **'发送命令'**
String get sendCommandTooltip;
/// No description provided for @importNewSystem.
///
/// In zh, this message translates to:
/// **'导入新系统'**
String get importNewSystem;
/// No description provided for @importBuiltinAlpine.
///
/// In zh, this message translates to:
/// **'从软件中导入 (Alpine)'**
String get importBuiltinAlpine;
/// No description provided for @importExternalTarGz.
///
/// In zh, this message translates to:
/// **'从外部导入 (.tar.gz)'**
String get importExternalTarGz;
/// No description provided for @selectSystemDefaultPrompt.
///
/// In zh, this message translates to:
/// **'选择系统将设为默认系统,新建终端时从该系统中启动:'**
String get selectSystemDefaultPrompt;
/// No description provided for @noSystemsPrompt.
///
/// In zh, this message translates to:
/// **'暂无系统,请点击右上角 \"+\" 导入'**
String get noSystemsPrompt;
/// No description provided for @importBuiltinAlpineTitle.
///
/// In zh, this message translates to:
/// **'从软件导入 Alpine 系统'**
String get importBuiltinAlpineTitle;
/// No description provided for @systemNameHintWithDefault.
///
/// In zh, this message translates to:
/// **'系统名称(如 {name})'**
String systemNameHintWithDefault(String name);
/// No description provided for @systemImportSuccess.
///
/// In zh, this message translates to:
/// **'系统 \"{name}\" 导入并就绪'**
String systemImportSuccess(String name);
/// No description provided for @importExternalSystemTitle.
///
/// In zh, this message translates to:
/// **'导入外部系统'**
String get importExternalSystemTitle;
/// No description provided for @systemNameHint.
///
/// In zh, this message translates to:
/// **'系统名称'**
String get systemNameHint;
/// No description provided for @externalSystemImportSuccess.
///
/// In zh, this message translates to:
/// **'外部系统 \"{name}\" 导入并就绪'**
String externalSystemImportSuccess(String name);
/// No description provided for @deleteSystemConfirmTitle.
///
/// In zh, this message translates to:
/// **'高危操作:确认删除系统'**
String get deleteSystemConfirmTitle;
/// No description provided for @deleteSystemConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要彻底删除系统 \"{name}\" 吗?\n\n⚠️ 该操作将物理级清除该系统及其所有内部数据与已安装软件包,此操作不可逆!\n\n该系统关联的所有终端会话也将被同步关闭。'**
String deleteSystemConfirmMessage(String name);
/// No description provided for @permanentDelete.
///
/// In zh, this message translates to:
/// **'彻底删除'**
String get permanentDelete;
/// No description provided for @deleteSystemSuccess.
///
/// In zh, this message translates to:
/// **'已彻底删除系统 \"{name}\" 及关联会话'**
String deleteSystemSuccess(String name);
/// No description provided for @deleteSystemTooltip.
///
/// In zh, this message translates to:
/// **'彻底删除该系统 (高危)'**
String get deleteSystemTooltip;
/// No description provided for @preparingInitialization.
///
/// In zh, this message translates to:
/// **'准备初始化...'**
String get preparingInitialization;
/// No description provided for @cancellingAndCleaning.
///
/// In zh, this message translates to:
/// **'正在取消并清理残余目录...'**
String get cancellingAndCleaning;
/// No description provided for @cancelledImportSystem.
///
/// In zh, this message translates to:
/// **'已取消导入系统 \"{name}\"'**
String cancelledImportSystem(String name);
/// No description provided for @importFailed.
///
/// In zh, this message translates to:
/// **'导入失败: {error}'**
String importFailed(String error);
/// No description provided for @importingSystemTitle.
///
/// In zh, this message translates to:
/// **'正在导入: {name}'**
String importingSystemTitle(String name);
/// No description provided for @cancelImport.
///
/// In zh, this message translates to:
/// **'取消导入'**
String get cancelImport;
/// No description provided for @interrupting.
///
/// In zh, this message translates to:
/// **'正在中断...'**
String get interrupting;
/// No description provided for @sessionDrawerTitle.
///
/// In zh, this message translates to:
/// **'会话'**
String get sessionDrawerTitle;
/// No description provided for @addTerminalTooltip.
///
/// In zh, this message translates to:
/// **'添加终端'**
String get addTerminalTooltip;
/// No description provided for @noSystemSelectedWarning.
///
/// In zh, this message translates to:
/// **'当前未选择任何系统,请先导入或选择系统'**
String get noSystemSelectedWarning;
/// No description provided for @noSessionsInDrawerPrompt.
///
/// In zh, this message translates to:
/// **'暂无会话,请点击右上角添加'**
String get noSessionsInDrawerPrompt;
/// No description provided for @confirmDeleteTerminalSession.
///
/// In zh, this message translates to:
/// **'确定要删除终端 \"({index}) {name}\" 吗?'**
String confirmDeleteTerminalSession(int index, String name);
/// No description provided for @deleteSystemFailed.
///
/// In zh, this message translates to:
/// **'删除系统失败: {error}'**
String deleteSystemFailed(String error);
}
class _AppLocalizationsDelegate
+141
View File
@@ -381,4 +381,145 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get goToSettings => 'Settings';
@override
String get terminal => 'Terminal';
@override
String terminalWithSystem(String system) {
return 'Terminal · $system';
}
@override
String get sessionDefaultName => 'Session';
@override
String get systemManagement => 'System Management';
@override
String get systemManagementTooltip => 'System Management & Selection';
@override
String get sessionListTooltip => 'Session List';
@override
String get noActiveSessions => 'No active sessions';
@override
String get terminalInputHint => 'Enter command...';
@override
String get sendCommandTooltip => 'Send Command';
@override
String get importNewSystem => 'Import New System';
@override
String get importBuiltinAlpine => 'Import from App (Alpine)';
@override
String get importExternalTarGz => 'Import from External (.tar.gz)';
@override
String get selectSystemDefaultPrompt =>
'Select a system as default; new terminals will start in this system:';
@override
String get noSystemsPrompt =>
'No systems available. Tap \"+\" at top right to import';
@override
String get importBuiltinAlpineTitle => 'Import Built-in Alpine System';
@override
String systemNameHintWithDefault(String name) {
return 'System name (e.g. $name)';
}
@override
String systemImportSuccess(String name) {
return 'System \"$name\" imported and ready';
}
@override
String get importExternalSystemTitle => 'Import External System';
@override
String get systemNameHint => 'System Name';
@override
String externalSystemImportSuccess(String name) {
return 'External system \"$name\" imported and ready';
}
@override
String get deleteSystemConfirmTitle => 'High-Risk Operation: Delete System';
@override
String deleteSystemConfirmMessage(String name) {
return 'Are you sure you want to permanently delete system \"$name\"?\n\n⚠️ This will physically erase all internal data and installed packages. This cannot be undone!\n\nAll associated terminal sessions will also be closed.';
}
@override
String get permanentDelete => 'Permanently Delete';
@override
String deleteSystemSuccess(String name) {
return 'System \"$name\" and associated sessions deleted';
}
@override
String get deleteSystemTooltip =>
'Permanently delete this system (High risk)';
@override
String get preparingInitialization => 'Preparing initialization...';
@override
String get cancellingAndCleaning =>
'Cancelling and cleaning leftover directory...';
@override
String cancelledImportSystem(String name) {
return 'Cancelled importing system \"$name\"';
}
@override
String importFailed(String error) {
return 'Import failed: $error';
}
@override
String importingSystemTitle(String name) {
return 'Importing: $name';
}
@override
String get cancelImport => 'Cancel Import';
@override
String get interrupting => 'Interrupting...';
@override
String get sessionDrawerTitle => 'Sessions';
@override
String get addTerminalTooltip => 'Add Terminal';
@override
String get noSystemSelectedWarning =>
'No system selected. Please import or select a system first.';
@override
String get noSessionsInDrawerPrompt => 'No sessions. Tap top right to add';
@override
String confirmDeleteTerminalSession(int index, String name) {
return 'Are you sure you want to delete terminal \"($index) $name\"?';
}
@override
String deleteSystemFailed(String error) {
return 'Failed to delete system: $error';
}
}
+136
View File
@@ -374,4 +374,140 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get goToSettings => '去设置';
@override
String get terminal => '终端';
@override
String terminalWithSystem(String system) {
return '终端 · $system';
}
@override
String get sessionDefaultName => '会话';
@override
String get systemManagement => '系统管理';
@override
String get systemManagementTooltip => '系统管理与选择';
@override
String get sessionListTooltip => '会话列表';
@override
String get noActiveSessions => '暂无活跃会话';
@override
String get terminalInputHint => '输入命令...';
@override
String get sendCommandTooltip => '发送命令';
@override
String get importNewSystem => '导入新系统';
@override
String get importBuiltinAlpine => '从软件中导入 (Alpine)';
@override
String get importExternalTarGz => '从外部导入 (.tar.gz)';
@override
String get selectSystemDefaultPrompt => '选择系统将设为默认系统,新建终端时从该系统中启动:';
@override
String get noSystemsPrompt => '暂无系统,请点击右上角 \"+\" 导入';
@override
String get importBuiltinAlpineTitle => '从软件导入 Alpine 系统';
@override
String systemNameHintWithDefault(String name) {
return '系统名称(如 $name)';
}
@override
String systemImportSuccess(String name) {
return '系统 \"$name\" 导入并就绪';
}
@override
String get importExternalSystemTitle => '导入外部系统';
@override
String get systemNameHint => '系统名称';
@override
String externalSystemImportSuccess(String name) {
return '外部系统 \"$name\" 导入并就绪';
}
@override
String get deleteSystemConfirmTitle => '高危操作:确认删除系统';
@override
String deleteSystemConfirmMessage(String name) {
return '确定要彻底删除系统 \"$name\" 吗?\n\n⚠️ 该操作将物理级清除该系统及其所有内部数据与已安装软件包,此操作不可逆!\n\n该系统关联的所有终端会话也将被同步关闭。';
}
@override
String get permanentDelete => '彻底删除';
@override
String deleteSystemSuccess(String name) {
return '已彻底删除系统 \"$name\" 及关联会话';
}
@override
String get deleteSystemTooltip => '彻底删除该系统 (高危)';
@override
String get preparingInitialization => '准备初始化...';
@override
String get cancellingAndCleaning => '正在取消并清理残余目录...';
@override
String cancelledImportSystem(String name) {
return '已取消导入系统 \"$name\"';
}
@override
String importFailed(String error) {
return '导入失败: $error';
}
@override
String importingSystemTitle(String name) {
return '正在导入: $name';
}
@override
String get cancelImport => '取消导入';
@override
String get interrupting => '正在中断...';
@override
String get sessionDrawerTitle => '会话';
@override
String get addTerminalTooltip => '添加终端';
@override
String get noSystemSelectedWarning => '当前未选择任何系统,请先导入或选择系统';
@override
String get noSessionsInDrawerPrompt => '暂无会话,请点击右上角添加';
@override
String confirmDeleteTerminalSession(int index, String name) {
return '确定要删除终端 \"($index) $name\" 吗?';
}
@override
String deleteSystemFailed(String error) {
return '删除系统失败: $error';
}
}
+119 -1
View File
@@ -121,5 +121,123 @@
"keepLocal": "保留本地修改",
"storagePermissionRequiredTitle": "需要存储访问权限",
"storagePermissionRequiredMessage": "代码编辑器需要“管理所有文件”权限,以便在您的设备上读取、新建和保存项目文件。\n\n请在接下来的系统设置页面中开启该权限。",
"goToSettings": "去设置"
"goToSettings": "去设置",
"terminal": "终端",
"terminalWithSystem": "终端 · {system}",
"@terminalWithSystem": {
"placeholders": {
"system": {
"type": "String"
}
}
},
"sessionDefaultName": "会话",
"systemManagement": "系统管理",
"systemManagementTooltip": "系统管理与选择",
"sessionListTooltip": "会话列表",
"noActiveSessions": "暂无活跃会话",
"terminalInputHint": "输入命令...",
"sendCommandTooltip": "发送命令",
"importNewSystem": "导入新系统",
"importBuiltinAlpine": "从软件中导入 (Alpine)",
"importExternalTarGz": "从外部导入 (.tar.gz)",
"selectSystemDefaultPrompt": "选择系统将设为默认系统,新建终端时从该系统中启动:",
"noSystemsPrompt": "暂无系统,请点击右上角 \"+\" 导入",
"importBuiltinAlpineTitle": "从软件导入 Alpine 系统",
"systemNameHintWithDefault": "系统名称(如 {name})",
"@systemNameHintWithDefault": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"systemImportSuccess": "系统 \"{name}\" 导入并就绪",
"@systemImportSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"importExternalSystemTitle": "导入外部系统",
"systemNameHint": "系统名称",
"externalSystemImportSuccess": "外部系统 \"{name}\" 导入并就绪",
"@externalSystemImportSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSystemConfirmTitle": "高危操作:确认删除系统",
"deleteSystemConfirmMessage": "确定要彻底删除系统 \"{name}\" 吗?\n\n⚠️ 该操作将物理级清除该系统及其所有内部数据与已安装软件包,此操作不可逆!\n\n该系统关联的所有终端会话也将被同步关闭。",
"@deleteSystemConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"permanentDelete": "彻底删除",
"deleteSystemSuccess": "已彻底删除系统 \"{name}\" 及关联会话",
"@deleteSystemSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSystemTooltip": "彻底删除该系统 (高危)",
"preparingInitialization": "准备初始化...",
"cancellingAndCleaning": "正在取消并清理残余目录...",
"cancelledImportSystem": "已取消导入系统 \"{name}\"",
"@cancelledImportSystem": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"importFailed": "导入失败: {error}",
"@importFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"importingSystemTitle": "正在导入: {name}",
"@importingSystemTitle": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"cancelImport": "取消导入",
"interrupting": "正在中断...",
"sessionDrawerTitle": "会话",
"addTerminalTooltip": "添加终端",
"noSystemSelectedWarning": "当前未选择任何系统,请先导入或选择系统",
"noSessionsInDrawerPrompt": "暂无会话,请点击右上角添加",
"confirmDeleteTerminalSession": "确定要删除终端 \"({index}) {name}\" 吗?",
"@confirmDeleteTerminalSession": {
"placeholders": {
"index": {
"type": "int"
},
"name": {
"type": "String"
}
}
},
"deleteSystemFailed": "删除系统失败: {error}",
"@deleteSystemFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
}
}
+13 -1
View File
@@ -27,7 +27,19 @@ class MyApp extends StatelessWidget {
(tab ?? (TabProvider()..init()))..bindProjectProvider(project),
),
ChangeNotifierProvider(create: (_) => TerminalProvider()),
ChangeNotifierProvider(create: (_) => DistroProvider()..checkAllStatuses()),
ChangeNotifierProxyProvider<TerminalProvider, DistroProvider>(
create: (_) => DistroProvider()..init(),
update: (_, terminal, distro) {
final dp = distro ?? (DistroProvider()..init());
dp.onSystemDeleted = (deletedSystem) {
terminal.removeSessionsForDistro(deletedSystem);
if (!dp.hasAnySystem) {
terminal.clearAllSessions();
}
};
return dp;
},
),
],
child: Consumer<SettingsProvider>(
builder: (context, settings, child) {
+13 -185
View File
@@ -1,190 +1,18 @@
/// Linux 发行版安装状态
enum DistroStatus {
/// 未安装
notInstalled,
import 'dart:ffi';
/// 正在安装/解压中
installing,
/// 已安装就绪
installed,
/// 安装或运行异常
error,
}
/// Linux 发行版元数据模型,具备高扩展性
/// 内置 Linux 发行版资源信息常量
class DistroInfo {
/// 唯一标识符,例如 'alpine', 'debian', 'ubuntu', 'host'
final String id;
/// 显示名称,例如 'Alpine Linux'
final String name;
/// 版本号,例如 '3.20.3'
final String version;
/// 描述信息
final String description;
/// 默认登录 Shell,例如 '/bin/sh', '/bin/bash'
final String defaultShell;
/// 包管理器名称,例如 'apk', 'apt'
final String packageManager;
/// 支持的硬件架构,例如 ['aarch64', 'arm64-v8a']
final List<String> supportedArchs;
/// 内置应用资源路径(如有,可离线解压)
final String? assetPath;
/// 远程下载地址(支持网络按需下载扩展)
final String? downloadUrl;
/// 是否为官方内置预设
final bool isBuiltin;
/// 图标名称标识
final String iconName;
const DistroInfo({
required this.id,
required this.name,
required this.version,
required this.description,
this.defaultShell = '/bin/sh',
this.packageManager = 'apk',
this.supportedArchs = const ['aarch64', 'arm64-v8a', 'all'],
this.assetPath,
this.downloadUrl,
this.isBuiltin = true,
this.iconName = 'terminal',
});
/// 预设:Alpine Linux (轻量极速,内置 asset)
static const DistroInfo alpine = DistroInfo(
id: 'alpine',
name: 'Alpine Linux',
version: '3.20.3',
description: '轻量快速的 Linux 发行版,体积仅约 4MB,内置 apk 包管理器',
defaultShell: '/bin/sh',
packageManager: 'apk',
supportedArchs: ['aarch64', 'arm64-v8a'],
assetPath: 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz',
isBuiltin: true,
iconName: 'alpine',
);
/// 预设扩展:Debian GNU/Linux
static const DistroInfo debian = DistroInfo(
id: 'debian',
name: 'Debian GNU/Linux',
version: '12 (Bookworm)',
description: '全能稳定的 Linux 发行版,标准 glibc 兼容,内置 apt 包管理器',
defaultShell: '/bin/bash',
packageManager: 'apt',
supportedArchs: ['aarch64', 'x86_64'],
downloadUrl: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/',
isBuiltin: false,
iconName: 'debian',
);
/// 预设扩展:Ubuntu
static const DistroInfo ubuntu = DistroInfo(
id: 'ubuntu',
name: 'Ubuntu',
version: '24.04 LTS',
description: '应用与开发生态丰富的流行 Linux 发行版,内置 apt 包管理器',
defaultShell: '/bin/bash',
packageManager: 'apt',
supportedArchs: ['aarch64', 'x86_64'],
downloadUrl: 'https://mirrors.tuna.tsinghua.edu.cn/ubuntu-cdimage/ubuntu-base/releases/24.04/release/',
isBuiltin: false,
iconName: 'ubuntu',
);
/// 预设:Android 本地 Shell
static const DistroInfo host = DistroInfo(
id: 'host',
name: '本地 Shell',
version: 'Android',
description: '直接调用安卓系统内置的基础 Shell,无需虚拟环境',
defaultShell: '/system/bin/sh',
packageManager: 'none',
supportedArchs: ['all'],
isBuiltin: true,
iconName: 'host',
);
/// 默认官方预设列表
static const List<DistroInfo> defaults = [
alpine,
debian,
ubuntu,
host,
];
DistroInfo copyWith({
String? id,
String? name,
String? version,
String? description,
String? defaultShell,
String? packageManager,
List<String>? supportedArchs,
String? assetPath,
String? downloadUrl,
bool? isBuiltin,
String? iconName,
}) {
return DistroInfo(
id: id ?? this.id,
name: name ?? this.name,
version: version ?? this.version,
description: description ?? this.description,
defaultShell: defaultShell ?? this.defaultShell,
packageManager: packageManager ?? this.packageManager,
supportedArchs: supportedArchs ?? this.supportedArchs,
assetPath: assetPath ?? this.assetPath,
downloadUrl: downloadUrl ?? this.downloadUrl,
isBuiltin: isBuiltin ?? this.isBuiltin,
iconName: iconName ?? this.iconName,
);
/// 根据当前运行环境的 CPU 架构自动选取匹配的内置 Alpine Minirootfs
static String get builtinAlpineAssetPath {
final currentAbi = Abi.current();
if (currentAbi == Abi.androidX64 ||
currentAbi == Abi.linuxX64 ||
currentAbi == Abi.windowsX64) {
return 'assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz';
}
return 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz';
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'version': version,
'description': description,
'defaultShell': defaultShell,
'packageManager': packageManager,
'supportedArchs': supportedArchs,
'assetPath': assetPath,
'downloadUrl': downloadUrl,
'isBuiltin': isBuiltin,
'iconName': iconName,
};
}
factory DistroInfo.fromJson(Map<String, dynamic> json) {
return DistroInfo(
id: json['id'] as String,
name: json['name'] as String,
version: json['version'] as String,
description: json['description'] as String,
defaultShell: (json['defaultShell'] as String?) ?? '/bin/sh',
packageManager: (json['packageManager'] as String?) ?? 'apk',
supportedArchs: (json['supportedArchs'] as List<dynamic>?)
?.map((e) => e.toString())
.toList() ??
const ['aarch64'],
assetPath: json['assetPath'] as String?,
downloadUrl: json['downloadUrl'] as String?,
isBuiltin: (json['isBuiltin'] as bool?) ?? false,
iconName: (json['iconName'] as String?) ?? 'terminal',
);
}
/// 默认系统实例名称
static const String defaultSystemName = 'alpine';
}
+142 -29
View File
@@ -1,56 +1,169 @@
import 'dart:async';
import 'dart:convert';
import 'package:code_editor/services/distro_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pty/flutter_pty.dart';
import 'package:xterm/xterm.dart';
/// 单个终端会话的数据与状态模型
/// 单个真实交互式终端会话的数据与状态模型(基于 原生 Unix PTY 伪终端)
class TerminalSession {
final String id;
String name;
final String distroId;
final DateTime createdAt;
final List<String> outputLines;
final TextEditingController inputController;
final ScrollController scrollController;
final Terminal terminal;
final FocusNode focusNode;
Pty? _pty;
StreamSubscription? _ptyOutputSub;
bool _isProcessRunning = false;
String _inputBuffer = '';
TerminalSession({
required this.id,
this.name = '会话',
this.distroId = 'alpine',
DateTime? createdAt,
List<String>? initialOutput,
int maxLines = 10000,
bool autoStartProcess = false,
}) : createdAt = createdAt ?? DateTime.now(),
outputLines = initialOutput ?? <String>[],
inputController = TextEditingController(),
scrollController = ScrollController(),
focusNode = FocusNode();
/// 向终端输出追加内容
void appendOutput(String line) {
outputLines.add(line);
_autoScrollToBottom();
terminal = Terminal(maxLines: maxLines),
focusNode = FocusNode() {
_initTerminalEvents();
if (autoStartProcess) {
unawaited(startProcess());
}
}
/// 自动滚动到终端最底部
void _autoScrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (scrollController.hasClients) {
scrollController.animateTo(
scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 100),
curve: Curves.easeOut,
);
bool get isProcessRunning => _isProcessRunning;
/// 获取终端缓冲区当前全部可见文本(常用于测试与日志断言)
String get bufferText => terminal.buffer.getText();
void _initTerminalEvents() {
// 监听输入直接送往 PTY
terminal.onOutput = (data) {
if (_pty != null && _isProcessRunning) {
try {
_pty!.write(utf8.encode(data));
} catch (_) {}
} else {
_handleLocalEcho(data);
}
});
};
// 监听终端视口尺寸变化并同步给底层 PTY
terminal.onResize = (width, height, pixelWidth, pixelHeight) {
if (_pty != null && _isProcessRunning) {
try {
_pty!.resize(height, width);
} catch (_) {}
}
};
}
/// 清屏
/// 当无底层进程挂接时的本地简易交互回显支持(保证脱机/本地开发时的基础交互与光标跳动)
void _handleLocalEcho(String data) {
for (int i = 0; i < data.length; i++) {
final char = data[i];
if (char == '\r' || char == '\n') {
terminal.write('\r\n');
_executeLocalCommand(_inputBuffer.trim());
_inputBuffer = '';
} else if (char == '\x7f' || char == '\b') {
// 退格键
if (_inputBuffer.isNotEmpty) {
_inputBuffer = _inputBuffer.substring(0, _inputBuffer.length - 1);
terminal.write('\b \b');
}
} else if (char.codeUnitAt(0) >= 32) {
_inputBuffer += char;
terminal.write(char);
}
}
}
void _executeLocalCommand(String cmd) {
if (cmd.isEmpty) {
terminal.write('\$ ');
return;
}
if (cmd == 'clear') {
clear();
terminal.write('\$ ');
return;
}
terminal.write('\x1b[33m[Host fallback]: executed "$cmd"\x1b[0m\r\n');
terminal.write('\$ ');
}
/// 启动底层真实 PTY 进程(连接 PRoot 容器或 Host Shell)
Future<void> startProcess({DistroManager? distroManager, String? workspacePath}) async {
final manager = distroManager ?? DistroManager();
try {
final config = await manager.buildLaunchConfig(
systemName: distroId,
workspacePath: workspacePath,
);
final initialRows = terminal.viewHeight > 0 ? terminal.viewHeight : 24;
final initialCols = terminal.viewWidth > 0 ? terminal.viewWidth : 80;
// 使用真实 Unix 伪终端 (PTY) 启动子进程
_pty = Pty.start(
config.executable,
arguments: config.arguments,
environment: config.environment,
workingDirectory: config.workingDirectory,
rows: initialRows,
columns: initialCols,
);
_isProcessRunning = true;
// PTY 输出数据流实时解码并写入终端
_ptyOutputSub = _pty!.output.listen(
(bytes) {
terminal.write(utf8.decode(bytes, allowMalformed: true));
},
onError: (err) {
terminal.write('\r\n\x1b[31m[PTY Output error: $err]\x1b[0m\r\n');
},
onDone: () {
_isProcessRunning = false;
},
);
_pty!.exitCode.then((code) {
_isProcessRunning = false;
terminal.write('\r\n\x1b[33m[Process exited with code $code]\x1b[0m\r\n');
});
} catch (e) {
_isProcessRunning = false;
terminal.write('\x1b[1;36mWelcome to Terminal [$distroId]\x1b[0m\r\n');
terminal.write('\x1b[90m(PTY launch failed: $e. Running in local fallback mode.)\x1b[0m\r\n\r\n');
terminal.write('\$ ');
}
}
/// 向终端写入文本(支持 VT100 / ANSI 转义序列)
void write(String text) {
terminal.write(text);
}
/// 发送标准 ANSI 清屏并复位光标
void clear() {
outputLines.clear();
terminal.write('\x1b[2J\x1b[H');
}
/// 释放资源
/// 释放 PTY 进程与焦点资源
void dispose() {
inputController.dispose();
scrollController.dispose();
_ptyOutputSub?.cancel();
if (_pty != null) {
try {
_pty!.kill();
} catch (_) {}
_pty = null;
}
focusNode.dispose();
}
}
+88 -66
View File
@@ -1,93 +1,115 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import '../models/distro_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/distro_installer.dart';
import '../services/distro_manager.dart';
/// Linux 发行版状态提供者(供 UI 监听与绑定)
/// 终端多系统状态与默认系统持久化管理器
class DistroProvider with ChangeNotifier {
static const String _prefKeyDefaultSystem = 'terminal_default_system';
final DistroManager _manager = DistroManager();
/// 各发行版状态缓存
final Map<String, DistroStatus> _statuses = {};
/// 当前已安装的系统名称列表
List<String> _installedSystems = [];
/// 安装进度 (0.0 ~ 1.0)
final Map<String, double> _progress = {};
/// 当前选中的默认系统(若无系统则为 null)
String? _selectedSystem;
/// 状态描述文字(如 "正在解压... 45%")
final Map<String, String> _statusMessages = {};
/// 是否已完成初始状态加载
bool _isInitialized = false;
/// 默认创建会话使用的发行版 ID
String _defaultDistroId = 'alpine';
/// 系统被物理删除时的回调监听(如联动终端清理其下全部关联会话)
void Function(String deletedSystem)? onSystemDeleted;
String get defaultDistroId => _defaultDistroId;
bool get isInitialized => _isInitialized;
List<DistroInfo> get distros => _manager.listDistros();
List<String> get installedSystems => List.unmodifiable(_installedSystems);
DistroStatus getStatus(String id) => _statuses[id] ?? DistroStatus.notInstalled;
String? get selectedSystem => _selectedSystem;
double getProgress(String id) => _progress[id] ?? 0.0;
bool get hasAnySystem => _installedSystems.isNotEmpty;
String getStatusMessage(String id) => _statusMessages[id] ?? '';
/// 初始化检查所有发行版状态
Future<void> checkAllStatuses() async {
for (final distro in _manager.listDistros()) {
try {
final isInst = await _manager.isInstalled(distro.id);
_statuses[distro.id] = isInst ? DistroStatus.installed : DistroStatus.notInstalled;
} catch (_) {
_statuses[distro.id] = DistroStatus.error;
}
}
/// 初始化:扫描系统列表并读取持久化的默认系统
Future<void> init() async {
await refreshSystems();
_isInitialized = true;
notifyListeners();
}
/// 设置默认发行版
void setDefaultDistro(String id) {
if (_defaultDistroId != id) {
_defaultDistroId = id;
notifyListeners();
/// 重新扫描已安装的系统并校准当前默认选中项
Future<void> refreshSystems() async {
final systems = await _manager.listInstalledSystems();
_installedSystems = systems;
final prefs = await SharedPreferences.getInstance();
final savedSystem = prefs.getString(_prefKeyDefaultSystem);
if (savedSystem != null && _installedSystems.contains(savedSystem)) {
_selectedSystem = savedSystem;
} else if (_installedSystems.isNotEmpty) {
_selectedSystem = _installedSystems.first;
await prefs.setString(_prefKeyDefaultSystem, _selectedSystem!);
} else {
_selectedSystem = null;
await prefs.remove(_prefKeyDefaultSystem);
}
}
/// 安装发行版
Future<bool> installDistro(String distroId) async {
_statuses[distroId] = DistroStatus.installing;
_progress[distroId] = 0.0;
_statusMessages[distroId] = '准备开始安装...';
notifyListeners();
}
try {
await _manager.installDistro(
distroId,
onProgress: (prog, msg) {
_progress[distroId] = prog;
_statusMessages[distroId] = msg;
notifyListeners();
},
);
_statuses[distroId] = DistroStatus.installed;
_statusMessages[distroId] = '已就绪';
/// 选择指定系统为当前活跃系统并持久化为默认系统
Future<void> selectSystem(String systemName) async {
if (!_installedSystems.contains(systemName)) return;
if (_selectedSystem != systemName) {
_selectedSystem = systemName;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_prefKeyDefaultSystem, systemName);
notifyListeners();
return true;
} catch (e) {
_statuses[distroId] = DistroStatus.error;
_statusMessages[distroId] = '安装失败: $e';
notifyListeners();
return false;
}
}
/// 卸载发行版
Future<void> uninstallDistro(String distroId) async {
try {
await _manager.uninstallDistro(distroId);
_statuses[distroId] = DistroStatus.notInstalled;
_progress.remove(distroId);
_statusMessages.remove(distroId);
notifyListeners();
} catch (e) {
_statusMessages[distroId] = '卸载失败: $e';
notifyListeners();
}
/// 从应用内置资源导入 Alpine 系统实例
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await _manager.importBuiltinAlpine(
systemName: systemName,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 导入成功后刷新列表并自动选为当前系统
await refreshSystems();
await selectSystem(systemName);
}
/// 从外部 .tar.gz 压缩包导入自定义系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await _manager.importFromCustomTarGz(
systemName: systemName,
tarGzFile: tarGzFile,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 导入成功后刷新列表并自动选为当前系统
await refreshSystems();
await selectSystem(systemName);
}
/// 高危操作:删除指定系统实例
Future<void> deleteSystem(String systemName) async {
await _manager.deleteSystem(systemName);
onSystemDeleted?.call(systemName);
await refreshSystems();
}
}
+43 -59
View File
@@ -23,9 +23,12 @@ class TerminalProvider extends ChangeNotifier {
}
/// 懒加载:进入终端页面时调用,如果尚未创建会话,则自动创建并激活首个会话
void ensureInitialized() {
void ensureInitialized({
String defaultName = '会话',
String defaultDistroId = 'alpine',
}) {
if (_sessions.isEmpty) {
createSession(name: '会话', activate: true);
createSession(name: defaultName, distroId: defaultDistroId, activate: true);
}
}
@@ -33,20 +36,18 @@ class TerminalProvider extends ChangeNotifier {
/// [distroId]: 发行版标识符(如 'alpine', 'host')
/// [activate]: 是否自动跳转切换到该会话。抽屉右上角加号点击时为 false(直接添加但不跳转)。
TerminalSession createSession({
String name = '会话',
String? name,
String distroId = 'alpine',
bool activate = false,
bool autoStartProcess = true,
}) {
final nextIndex = _sessions.length + 1;
final sessionName = (name != null && name.trim().isNotEmpty) ? name.trim() : '会话';
final session = TerminalSession(
id: 'session_${DateTime.now().microsecondsSinceEpoch}_$nextIndex',
name: name,
name: sessionName,
distroId: distroId,
initialOutput: [
'Welcome to Terminal ($nextIndex) [$distroId]',
'Type "help" for a list of built-in commands or "clear" to clear.',
'',
],
autoStartProcess: autoStartProcess,
);
_sessions.add(session);
@@ -100,6 +101,36 @@ class TerminalProvider extends ChangeNotifier {
notifyListeners();
}
/// 移除指定系统的所有会话(当系统被物理删除时调用)
void removeSessionsForDistro(String distroId) {
final toRemove = _sessions.where((s) => s.distroId == distroId).toList();
if (toRemove.isEmpty) return;
for (final session in toRemove) {
session.dispose();
_sessions.remove(session);
}
if (_sessions.isEmpty) {
_activeIndex = 0;
} else if (_activeIndex >= _sessions.length) {
_activeIndex = _sessions.length - 1;
}
notifyListeners();
}
/// 清空全部会话并释放资源
void clearAllSessions() {
if (_sessions.isEmpty) return;
for (final session in _sessions) {
session.dispose();
}
_sessions.clear();
_activeIndex = 0;
notifyListeners();
}
/// 拖拽重新排序终端会话(接收 onReorderItem 传入的已修正目标索引)
void reorderSessions(int oldIndex, int newIndex) {
if (oldIndex < 0 || oldIndex >= _sessions.length) return;
@@ -121,56 +152,9 @@ class TerminalProvider extends ChangeNotifier {
notifyListeners();
}
/// 向指定终端会话追加输出并通知更新
void appendOutput(TerminalSession session, String line) {
session.appendOutput(line);
notifyListeners();
}
/// 执行简单交互命令(支持 help, clear, echo, date 等,后续可无缝接入 PTY / Shell)
void executeCommand(TerminalSession session, String rawInput) {
final input = rawInput.trim();
session.appendOutput('\$ $rawInput');
if (input.isEmpty) {
notifyListeners();
return;
}
final parts = input.split(RegExp(r'\s+'));
final cmd = parts.first.toLowerCase();
switch (cmd) {
case 'clear':
session.clear();
break;
case 'help':
session.appendOutput('Built-in terminal commands:');
session.appendOutput(' clear Clear the terminal screen');
session.appendOutput(' date Show current date and time');
session.appendOutput(' echo <msg> Echo text back');
session.appendOutput(' help Show this help information');
session.appendOutput(' sessions List active sessions');
break;
case 'date':
session.appendOutput(DateTime.now().toString());
break;
case 'echo':
session.appendOutput(parts.skip(1).join(' '));
break;
case 'sessions':
session.appendOutput('Total sessions: ${_sessions.length}');
for (int i = 0; i < _sessions.length; i++) {
final s = _sessions[i];
final marker = (i == _activeIndex) ? '*' : ' ';
session.appendOutput(' $marker (${i + 1}) ${s.name} [${s.id}]');
}
break;
default:
session.appendOutput('command not found: $cmd');
break;
}
/// 向指定终端会话写入文本并通知更新
void appendOutput(TerminalSession session, String text) {
session.write(text);
notifyListeners();
}
+190 -49
View File
@@ -1,6 +1,8 @@
import 'dart:ffi';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
/// 安装进度回调
@@ -8,6 +10,15 @@ import 'package:path/path.dart' as p;
/// [message] 当前阶段说明
typedef InstallProgressCallback = void Function(double progress, String message);
/// 取消安装异常
class DistroInstallCancelledException implements Exception {
final String message;
DistroInstallCancelledException([this.message = '用户已取消系统导入']);
@override
String toString() => message;
}
/// Linux 发行版 Rootfs 安装与解压服务
class DistroInstaller {
/// 解压并安装 tar.gz 格式的 Rootfs 到目标目录
@@ -15,67 +26,112 @@ class DistroInstaller {
/// [tarGzBytes] .tar.gz 压缩包字节流
/// [targetDir] 目标解压目录 (即容器的 rootfs 路径)
/// [onProgress] 进度回调
/// [isCancelled] 外部取消检查函数
static Future<void> installFromBytes({
required Uint8List tarGzBytes,
required Directory targetDir,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
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);
try {
// 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿)
onProgress?.call(0.15, '正在解压内核与文件系统结构...');
final archive = await compute(_decodeTarGz, tarGzBytes);
// 2. 写入文件与目录
final total = archive.length;
int processed = 0;
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
for (final file in archive) {
processed++;
final filename = file.name;
// 避免路径穿越漏洞 (Directory Traversal)
if (filename.contains('..')) continue;
// 2. 写入文件与目录
//
// 权限位必须逐条按 tar 头恢复:dart:io 没有 chmod,而解压本身不会保留
// 可执行位,所以恢复方式是按 mode 分组批量调用 chmod(避免逐文件 fork)。
// 之前这里用 `chmod -R 755` 一把梭,会把 /etc 下的配置文件也变成可执行。
final total = archive.length;
int processed = 0;
final Map<int, List<String>> byMode = <int, List<String>>{};
final outPath = p.join(targetDir.path, filename);
if (file.isFile) {
final parentDir = Directory(p.dirname(outPath));
if (!parentDir.existsSync()) {
parentDir.createSync(recursive: true);
for (final file in archive) {
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
// 处理符号链接与常规文件
if (file.isSymbolicLink) {
try {
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(file.nameOfLinkedFile);
} catch (_) {
// Windows 或受限环境降级为写入目标路径文本或忽略
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 {
final content = file.content as List<int>;
File(outPath).writeAsBytesSync(content, flush: false);
Directory(outPath).createSync(recursive: true);
}
// 记录 tar 头里的权限位(仅低 12 位有效位)。
// 符号链接必须跳过:chmod 会跟随链接,把目标文件的权限改坏
// (tar 里 symlink 条目的 mode 固定为 0777)。
final mode = file.mode & 0xFFF;
if (mode != 0 && !file.isSymbolicLink) {
byMode.putIfAbsent(mode, () => <String>[]).add(outPath);
}
if (processed % 50 == 0 || processed == total) {
final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90%
onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...');
}
} 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)...');
if (!Platform.isWindows) {
await _restoreModes(byMode);
}
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
// 3. 执行系统配置与网络补丁
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
await postInstallConfigure(targetDir);
onProgress?.call(1.0, '系统初始化就绪!');
} catch (e) {
// 若中途失败或取消,清理不完整的根目录
try {
if (targetDir.existsSync()) {
targetDir.deleteSync(recursive: true);
}
} catch (_) {}
rethrow;
}
// 3. 执行系统配置与网络补丁
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
await postInstallConfigure(targetDir);
onProgress?.call(1.0, '系统初始化就绪!');
}
/// 后台 Isolate 解压 tar.gz
@@ -84,10 +140,37 @@ class DistroInstaller {
return TarDecoder().decodeBytes(tarData);
}
/// 按 tar 头恢复权限位(dart:io 无 chmod,按 mode 分组批量调用,避免逐文件 fork)
static Future<void> _restoreModes(Map<int, List<String>> byMode) async {
for (final entry in byMode.entries) {
final octal = entry.key.toRadixString(8).padLeft(4, '0');
final paths = entry.value;
// 单次 chmod 的参数长度有限,分批执行
const batch = 100;
for (var i = 0; i < paths.length; i += batch) {
final end = (i + batch < paths.length) ? i + batch : paths.length;
final slice = paths.sublist(i, end);
try {
await Process.run('chmod', [octal, ...slice]);
} catch (e) {
debugPrint('[DistroInstaller] 恢复权限失败 ($octal): $e');
}
}
}
}
/// 容器可用的 DNS 解析器(按"可达优先"排序:国内公共 DNS 在前)
static const String guestResolvConf = '# Generated by CodeEditor\n'
'nameserver 223.5.5.5\n'
'nameserver 119.29.29.29\n'
'nameserver 114.114.114.114\n';
/// 自动化环境补丁与配置
/// 1. 注入 DNS (resolv.conf) 防止容器内 apk/apt 无法联网
/// 2. 注入 hosts
/// 3. 创建挂载点 /workspace 和 /tmp
///
/// 只做"发行版自身不会做、但容器化必需"的事:DNS、hosts、镜像源、
/// 挂载点目录、shim 部署。**不再改写 guest 的 /etc/profile** —— 那会破坏
/// 非 Alpine 发行版自带的登录环境(Alpine 原版 profile 与本项目此前写入的
/// 模板逐行相同,所以删掉它对 Alpine 没有任何影响)。
static Future<void> postInstallConfigure(Directory rootfsDir) async {
final etcDir = Directory(p.join(rootfsDir.path, 'etc'));
if (!etcDir.existsSync()) {
@@ -97,12 +180,7 @@ class DistroInstaller {
// 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',
);
resolvFile.writeAsStringSync(guestResolvConf);
} catch (e) {
debugPrint('[DistroInstaller] 写入 resolv.conf 失败: $e');
}
@@ -118,16 +196,79 @@ class DistroInstaller {
debugPrint('[DistroInstaller] 写入 hosts 失败: $e');
}
// 3. 确保 /workspace 挂载点目录存在
// 3. 配置 Alpine apk 软件源镜像(使用阿里云高速稳定镜像)
final apkDir = Directory(p.join(etcDir.path, 'apk'));
if (apkDir.existsSync()) {
final repoFile = File(p.join(apkDir.path, 'repositories'));
try {
repoFile.writeAsStringSync(
'https://mirrors.aliyun.com/alpine/v3.20/main\n'
'https://mirrors.aliyun.com/alpine/v3.20/community\n',
);
} catch (e) {
debugPrint('[DistroInstaller] 写入 repositories 失败: $e');
}
}
// 4. 确保 /workspace 挂载点目录存在
final workspaceDir = Directory(p.join(rootfsDir.path, 'workspace'));
if (!workspaceDir.existsSync()) {
workspaceDir.createSync(recursive: true);
}
// 4. 确保 /tmp 目录存在
// 5. 确保 /tmp 目录存在
final tmpDir = Directory(p.join(rootfsDir.path, 'tmp'));
if (!tmpDir.existsSync()) {
tmpDir.createSync(recursive: true);
}
// 6. 部署容器修复 Shim(libfix_seccomp.so)
await ensureSeccompShim(rootfsDir);
}
/// 部署容器修复 Shim(libfix_seccomp.so)
///
/// 它只做两件在 Android app 进程里必需的事:
/// 1. `utimensat()`(两个架构):Android 不允许应用数据区创建硬链接,PRoot
/// 的 `--link2symlink` 用 symlink + 隐藏记账文件模拟硬链接,导致 apk
/// 保 mtime 时跟随解析失败(`Failed to preserve modification time`)。
/// 2. `poll/select/pipe/dup2`(仅 x86_64):Android 的 app seccomp 策略把这些
/// 传统 syscall 返回 ENOSYS,而 musl 在有这些调用的架构上优先用它们。
static Future<void> ensureSeccompShim(Directory rootfsDir) async {
final libDir = Directory(p.join(rootfsDir.path, 'lib'));
if (!libDir.existsSync()) {
libDir.createSync(recursive: true);
}
final targetShim = File(p.join(libDir.path, 'libfix_seccomp.so'));
String? archFolder;
if (Platform.isAndroid || Platform.isLinux) {
final currentAbi = Abi.current();
if (currentAbi == Abi.androidX64 || currentAbi == Abi.linuxX64) {
archFolder = 'x86_64';
} else if (currentAbi == Abi.androidArm64 || currentAbi == Abi.linuxArm64) {
archFolder = 'arm64-v8a';
}
}
if (archFolder == null) return;
try {
final assetPath = 'assets/shims/$archFolder/libfix_seccomp.so';
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);
// 如果目标文件已存在且大小一致,则跳过写入
if (targetShim.existsSync() && targetShim.lengthSync() == bytes.length) {
return;
}
await targetShim.writeAsBytes(bytes, flush: true);
if (!Platform.isWindows) {
await Process.run('chmod', ['755', targetShim.path]);
}
debugPrint('[DistroInstaller] 成功部署 SECCOMP Shim: ${targetShim.path}');
} catch (e) {
debugPrint('[DistroInstaller] 部署 SECCOMP Shim 失败: $e');
}
}
}
+317 -96
View File
@@ -35,40 +35,16 @@ class ProotLaunchConfig {
}
}
/// Linux 发行版管理器服务(单例模式,易扩展)
/// Linux 发行版与多系统实例管理器服务(单例模式,易扩展)
class DistroManager {
static final DistroManager _instance = DistroManager._internal();
factory DistroManager() => _instance;
DistroManager._internal() {
// 注册内置默认发行版
for (final d in DistroInfo.defaults) {
_distros[d.id] = d;
}
}
DistroManager._internal();
/// 自定义覆盖根目录(主要用于测试)
@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) {
@@ -82,115 +58,212 @@ class DistroManager {
return distrosDir;
}
/// 获取指定发行版的 Rootfs 解压目录: `<app_dir>/distros/<distroId>/rootfs`
Future<Directory> getDistroRootDir(String distroId) async {
/// 获取指定系统实例的 Rootfs 解压目录: `<app_dir>/distros/<systemName>/rootfs`
Future<Directory> getSystemRootDir(String systemName) async {
final baseDir = await getBaseDistrosDir();
return Directory(p.join(baseDir.path, distroId, 'rootfs'));
return Directory(p.join(baseDir.path, systemName, 'rootfs'));
}
/// 检测指定发行版是否已安装就绪
Future<bool> isInstalled(String distroId) async {
// host 为宿主系统,无需安装
if (distroId == 'host') return true;
/// 获取当前已创建并解压成功的系统实例列表(文件夹名称即系统名称)
Future<List<String>> listInstalledSystems() async {
final baseDir = await getBaseDistrosDir();
if (!baseDir.existsSync()) return [];
final rootDir = await getDistroRootDir(distroId);
final List<String> systems = [];
final entities = baseDir.listSync(followLinks: false);
for (final entity in entities) {
if (entity is Directory) {
final name = p.basename(entity.path);
// 若子目录存在 rootfs/ 且包含基础目录结构,则视为有效系统实例
final rootDir = Directory(p.join(entity.path, 'rootfs'));
if (rootDir.existsSync()) {
systems.add(name);
}
}
}
// 按名称字母排序
systems.sort((a, b) => a.compareTo(b));
return systems;
}
/// 是否存在任何已安装的系统
Future<bool> hasAnySystem() async {
final systems = await listInstalledSystems();
return systems.isNotEmpty;
}
/// 检测指定系统实例是否已安装就绪
Future<bool> isSystemInstalled(String systemName) async {
if (systemName == 'host') return true;
final rootDir = await getSystemRootDir(systemName);
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');
/// 校验系统名称是否合法且未被占用
Future<void> validateSystemName(String systemName) async {
final trimmed = systemName.trim();
if (trimmed.isEmpty) {
throw ArgumentError('系统名称不能为空');
}
// 限制字符集:字母、数字、下划线、短横线、中文字符
final validRegex = RegExp(r'^[\w\u4e00-\u9fa5\-_]+$');
if (!validRegex.hasMatch(trimmed)) {
throw ArgumentError('系统名称只能包含字母、数字、中文、下划线或短横线');
}
if (distroId == 'host') {
onProgress?.call(1.0, '本地 Shell 无需安装');
return;
final systems = await listInstalledSystems();
if (systems.any((s) => s.toLowerCase() == trimmed.toLowerCase())) {
throw ArgumentError('已存在同名系统 "$trimmed",请使用其他名称');
}
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, {
/// 从应用内置资源导入 Alpine Linux 系统实例
///
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final targetDir = await getDistroRootDir(distroId);
final bytes = await tarGzFile.readAsBytes();
await validateSystemName(systemName);
final assetPath = DistroInfo.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 卸载并清除指定发行版的 rootfs 目录
Future<void> uninstallDistro(String distroId) async {
if (distroId == 'host') return;
/// 从用户本地指定的 .tar.gz 压缩包导入外部系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
if (!tarGzFile.existsSync()) {
throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}');
}
onProgress?.call(0.02, '正在读取外部系统压缩包...');
final bytes = await tarGzFile.readAsBytes();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 高危操作:彻底删除指定系统实例及其所有存储数据
Future<void> deleteSystem(String systemName) async {
if (systemName == 'host') return;
final baseDir = await getBaseDistrosDir();
final distroDir = Directory(p.join(baseDir.path, distroId));
if (distroDir.existsSync()) {
distroDir.deleteSync(recursive: true);
final systemDir = Directory(p.join(baseDir.path, systemName));
if (!systemDir.existsSync()) return;
for (int attempt = 0; attempt < 3; attempt++) {
try {
if (!systemDir.existsSync()) break;
await systemDir.delete(recursive: true);
break;
} catch (e) {
if (Platform.isLinux || Platform.isAndroid) {
try {
await Process.run('chmod', ['-R', '777', systemDir.path]);
} catch (_) {}
}
await Future<void>.delayed(const Duration(milliseconds: 60));
if (attempt == 2) {
try {
if (systemDir.existsSync()) {
systemDir.deleteSync(recursive: true);
}
} catch (_) {}
}
}
}
}
static const MethodChannel _nativeChannel = MethodChannel('com.example.code_editor/native');
String? _cachedProotPath;
String? _cachedNativeDir;
/// 获取 App 原生动态库目录路径(用于定位 libproot.so 与 libtalloc.so)
Future<String?> getNativeLibraryDir() async {
if (_cachedNativeDir != null) return _cachedNativeDir;
if (Platform.isAndroid) {
try {
final dir = await _nativeChannel.invokeMethod<String>('getNativeLibraryDir');
if (dir != null && dir.isNotEmpty) {
_cachedNativeDir = dir;
return dir;
}
} catch (e) {
debugPrint('获取原生动态库目录失败: $e');
}
}
return null;
}
/// 获取 proot 可执行程序的物理路径(优先检测 nativeLibraryDir/libproot.so)
Future<String> getProotExecutablePath() async {
if (_cachedProotPath != null && File(_cachedProotPath!).existsSync()) {
return _cachedProotPath!;
}
final nativeDir = await getNativeLibraryDir();
if (nativeDir != null) {
final soPath = p.join(nativeDir, 'libproot.so');
if (File(soPath).existsSync()) {
_cachedProotPath = soPath;
return soPath;
}
}
return 'proot';
}
/// 构建 PRoot 容器启动命令与环境参数
///
/// [distroId] 发行版标识符
/// [systemName] 当前选择的系统名称
/// [workspacePath] 挂载的代码工程路径(挂载到容器内部的 /workspace)
/// [prootPath] proot 二进制路径(默认可传入 'proot' 或设备内部特定路径)
/// [customCommand] 自定义初始执行命令(默认进入交互式 login shell)
/// [prootPath] proot 二进制路径
/// [customCommand] 自定义执行命令
Future<ProotLaunchConfig> buildLaunchConfig({
required String distroId,
required String systemName,
String? workspacePath,
String prootPath = 'proot',
String? customCommand,
}) async {
final distro = getDistro(distroId) ?? DistroInfo.alpine;
// 1. 本地 Shell 特殊处理:无需 PRoot
if (distroId == 'host') {
// 1. 本地 Shell 特殊处理
if (systemName == 'host') {
final initialDir = (workspacePath != null && Directory(workspacePath).existsSync())
? workspacePath
: Directory.current.path;
final args = customCommand != null ? ['-c', customCommand] : <String>[];
return ProotLaunchConfig(
executable: distro.defaultShell,
executable: '/system/bin/sh',
arguments: args,
environment: {
'TERM': 'xterm-256color',
@@ -200,17 +273,53 @@ class DistroManager {
}
// 2. Linux 容器 (PRoot 隔离环境)
final rootDir = await getDistroRootDir(distroId);
final targetShell = distro.defaultShell;
final rootDir = await getSystemRootDir(systemName);
final nativeDir = await getNativeLibraryDir();
final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath;
const targetShell = '/bin/sh';
// 确保容器内 DNS 配置存在(对标 proot-distro,保证网络连通与 apk/curl 正常解析)
await _ensureGuestDns(rootDir);
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
final shmDir = await _ensureShmDir(systemName);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范)
final l2sDir = await _ensureL2sDir(systemName);
// 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据)
final sysdataDir = await _ensureSysdataDir(systemName);
String tmpPath = '/tmp';
try {
tmpPath = (await getTemporaryDirectory()).path;
} catch (_) {
tmpPath = '/tmp';
}
final args = <String>[
'--kill-on-exit',
'--link2symlink',
'-0', // 模拟 root 权限 (uid 0)
'-k', '5.4.0-proot', // 伪装内核版本(解决 musl libc 调用 clone3/ppoll 时的 Function not implemented)
'-L', // 修复 lstat 符号链接大小属性
'-r', rootDir.path, // 根文件系统路径
'-b', '/dev', // 挂载标准设备节点
'-b', '/dev', // 挂载标准设备节点(宿主已有 /dev/stdin, stdout, stderr 等软链接)
'-b', '/dev/urandom:/dev/random', // 补充随机数设备节点
if (shmDir != null) ...['-b', '${shmDir.path}:/dev/shm'], // 挂载独立 POSIX 共享内存
'-b', '/proc', // 挂载进程信息
'-b', '/sys', // 挂载系统信息
if (sysdataDir != null) ...[
'-b', '${p.join(sysdataDir.path, 'sys_empty')}:/sys/fs/selinux',
'-b', '${p.join(sysdataDir.path, 'sysctl_entry_cap_last_cap')}:/proc/sys/kernel/cap_last_cap',
'-b', '${p.join(sysdataDir.path, 'sysctl_inotify_max_user_watches')}:/proc/sys/fs/inotify/max_user_watches',
],
];
if (Directory(tmpPath).existsSync()) {
args.addAll(['-b', '$tmpPath:/tmp']);
}
// 挂载工作区
String containerWorkDir = '/root';
if (workspacePath != null && Directory(workspacePath).existsSync()) {
@@ -221,6 +330,26 @@ class DistroManager {
// 设置容器内工作目录
args.addAll(['-w', containerWorkDir]);
// 用 /usr/bin/env -i 彻底隔离宿主(Android app 进程)继承的环境变量,
// 只注入标准纯净的容器环境变量;若修复 Shim 已部署则注入 LD_PRELOAD。
// Shim 的两项职责见 DistroInstaller.ensureSeccompShim 的注释。
await DistroInstaller.ensureSeccompShim(rootDir);
final shimFile = File(p.join(rootDir.path, 'lib', 'libfix_seccomp.so'));
final hasShim = shimFile.existsSync();
final guestEnvArgs = <String>[
'/usr/bin/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',
if (hasShim) 'LD_PRELOAD=/lib/libfix_seccomp.so',
];
args.addAll(guestEnvArgs);
// 登录 Shell 或自定义命令
if (customCommand != null && customCommand.isNotEmpty) {
args.addAll([targetShell, '-c', customCommand]);
@@ -234,14 +363,106 @@ class DistroManager {
'TERM': 'xterm-256color',
'LANG': 'C.UTF-8',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
'TMPDIR': '/tmp',
'TMPDIR': tmpPath,
'PROOT_TMP_DIR': tmpPath,
if (l2sDir != null) 'PROOT_L2S_DIR': l2sDir.path,
if (nativeDir != null) 'LD_LIBRARY_PATH': nativeDir,
};
// Process.start 的宿主工作目录必须在 Android 宿主真实存在
final hostWorkDir = rootDir.path;
return ProotLaunchConfig(
executable: prootPath,
executable: effectiveProot,
arguments: args,
environment: env,
workingDirectory: containerWorkDir,
workingDirectory: hostWorkDir,
);
}
/// 确保容器内具备标准 DNS 解析文件 `/etc/resolv.conf`(对标 proot-distro)
Future<void> _ensureGuestDns(Directory rootDir) async {
try {
final etcDir = Directory(p.join(rootDir.path, 'etc'));
if (!etcDir.existsSync()) {
etcDir.createSync(recursive: true);
}
final resolvConf = File(p.join(etcDir.path, 'resolv.conf'));
if (!resolvConf.existsSync() || (await resolvConf.length()) == 0) {
// "可达优先"排序:国内公共 DNS 在前(8.8.8.8/1.1.1.1 在国内常被丢包,
// 排在首位会让 musl/glibc 解析器先等一次超时)。与 DistroInstaller
// 的 guestResolvConf 保持一致。
await resolvConf.writeAsString(
DistroInstaller.guestResolvConf,
flush: true,
);
}
} catch (e) {
debugPrint('配置容器 DNS 失败 (非阻塞): $e');
}
}
/// 确保容器实例拥有独立的 POSIX 共享内存目录(对标 proot-distro shm.py)
Future<Directory?> _ensureShmDir(String systemName) async {
try {
final baseDir = await getBaseDistrosDir();
final shmDir = Directory(p.join(baseDir.path, systemName, 'shm'));
if (!shmDir.existsSync()) {
shmDir.createSync(recursive: true);
}
return shmDir;
} catch (e) {
debugPrint('创建容器 shm 目录失败 (非阻塞): $e');
return null;
}
}
/// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro login/__init__.py)
Future<Directory?> _ensureL2sDir(String systemName) async {
try {
final baseDir = await getBaseDistrosDir();
final l2sDir = Directory(p.join(baseDir.path, systemName, '.l2s'));
if (!l2sDir.existsSync()) {
l2sDir.createSync(recursive: true);
}
return l2sDir;
} catch (e) {
debugPrint('创建容器 .l2s 目录失败 (非阻塞): $e');
return null;
}
}
/// 确保容器实例拥有独立的 sysdata 桩目录与 SELinux 覆盖节点(对标 proot-distro sysdata.py)
Future<Directory?> _ensureSysdataDir(String systemName) async {
try {
final baseDir = await getBaseDistrosDir();
final sysdataDir = Directory(p.join(baseDir.path, systemName, 'sysdata'));
if (!sysdataDir.existsSync()) {
sysdataDir.createSync(recursive: true);
}
// 1. 空目录用于覆盖 /sys/fs/selinux(禁用 selinux 检测)
final emptyDir = Directory(p.join(sysdataDir.path, 'sys_empty'));
if (!emptyDir.existsSync()) {
emptyDir.createSync(recursive: true);
}
// 2. /proc/sys/kernel/cap_last_cap 桩
final capFile = File(p.join(sysdataDir.path, 'sysctl_entry_cap_last_cap'));
if (!capFile.existsSync()) {
capFile.writeAsStringSync('40\n');
}
// 3. /proc/sys/fs/inotify/max_user_watches 桩
final inotifyFile = File(p.join(sysdataDir.path, 'sysctl_inotify_max_user_watches'));
if (!inotifyFile.existsSync()) {
inotifyFile.writeAsStringSync('4096\n');
}
return sysdataDir;
} catch (e) {
debugPrint('创建容器 sysdata 目录失败 (非阻塞): $e');
return null;
}
}
}
+89 -226
View File
@@ -1,14 +1,17 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/distro_info.dart';
import 'package:code_editor/models/terminal_session.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/widgets/distro_extract_dialog.dart';
import 'package:code_editor/widgets/distro_selector_dialog.dart';
import 'package:code_editor/widgets/terminal_drawer.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xterm/xterm.dart' as xterm;
/// 终端视图(支持全屏会话保持、右侧抽屉多会话管理与交互)
/// 终端视图(支持多系统实例切换、全屏会话保持、右侧抽屉多会话管理与交互)
class TerminalView extends StatefulWidget {
const TerminalView({super.key});
@@ -22,10 +25,56 @@ class _TerminalViewState extends State<TerminalView> {
@override
void initState() {
super.initState();
// 懒加载:进入终端 view 时,若无会话则自动创建首个会话
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
context.read<TerminalProvider>().ensureInitialized();
// 首次或进入终端时:检测已安装系统。如果不存在任何系统,自动从软件内置导入 alpine
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) return;
final distroProvider = context.read<DistroProvider?>();
final l10n = AppLocalizations.of(context)!;
final defaultSessionName = l10n.sessionDefaultName;
if (distroProvider == null) {
context.read<TerminalProvider>().ensureInitialized(defaultName: defaultSessionName);
return;
}
await distroProvider.init();
if (!mounted) return;
if (!distroProvider.hasAnySystem) {
// 自动从软件内置资源导入 alpine,名称即为 alpine
final success = await DistroExtractDialog.show(
context: context,
systemName: 'alpine',
task: (onProgress, isCancelled) {
return distroProvider.importBuiltinAlpine(
systemName: 'alpine',
onProgress: onProgress,
isCancelled: isCancelled,
);
},
);
if (success && mounted) {
final termProvider = context.read<TerminalProvider>();
if (termProvider.isEmpty) {
termProvider.createSession(
name: defaultSessionName,
distroId: 'alpine',
activate: true,
);
}
}
} else {
// 已有系统,确保初始化首个会话
final termProvider = context.read<TerminalProvider>();
if (termProvider.isEmpty) {
final system = distroProvider.selectedSystem ?? 'alpine';
termProvider.createSession(
name: defaultSessionName,
distroId: system,
activate: true,
);
}
}
});
}
@@ -33,13 +82,17 @@ class _TerminalViewState extends State<TerminalView> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final provider = context.watch<TerminalProvider>();
final distroProvider = context.watch<DistroProvider?>();
final activeSession = provider.activeSession;
final sessions = provider.sessions;
final activeIndex = provider.activeIndex;
final titleText = activeSession?.name ?? '会话';
const subtitleText = '终端';
final titleText = activeSession?.name ?? l10n.sessionDefaultName;
final currentSystem = activeSession?.distroId ?? distroProvider?.selectedSystem;
final subtitleText = currentSystem != null ? l10n.terminalWithSystem(currentSystem) : l10n.terminal;
return Scaffold(
key: _scaffoldKey,
@@ -48,7 +101,7 @@ class _TerminalViewState extends State<TerminalView> {
foregroundColor: theme.colorScheme.onSurface,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: '返回',
tooltip: l10n.back,
onPressed: () => Navigator.of(context).pop(),
),
title: Column(
@@ -74,9 +127,17 @@ class _TerminalViewState extends State<TerminalView> {
],
),
actions: [
// 系统选择与管理按钮(位于会话列表左侧)
IconButton(
icon: const Icon(Icons.dns_outlined),
tooltip: l10n.systemManagementTooltip,
onPressed: () {
DistroSelectorDialog.show(context);
},
),
IconButton(
icon: const Icon(Icons.format_list_bulleted),
tooltip: '会话列表',
tooltip: l10n.sessionListTooltip,
onPressed: () {
_scaffoldKey.currentState?.openEndDrawer();
},
@@ -85,10 +146,10 @@ class _TerminalViewState extends State<TerminalView> {
),
endDrawer: const TerminalDrawer(),
body: sessions.isEmpty
? const Center(
? Center(
child: Text(
'暂无活跃会话',
style: TextStyle(color: Colors.grey),
l10n.noActiveSessions,
style: const TextStyle(color: Colors.grey),
),
)
: IndexedStack(
@@ -105,7 +166,7 @@ class _TerminalViewState extends State<TerminalView> {
}
}
/// 单个终端会话的终端渲染与交互容器
/// 单个真实交互式终端会话的终端渲染与交互容器
class _TerminalSessionBody extends StatefulWidget {
final TerminalSession session;
@@ -125,224 +186,26 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> {
final settings = context.watch<SettingsProvider?>();
final terminalFont = settings?.terminalFont ?? AppFonts.terminalMonospace;
final terminalStyle = xterm.TerminalStyle(
fontSize: 13.0,
fontFamily: terminalFont.fontFamily ?? 'monospace',
fontFamilyFallback: terminalFont.fallback,
);
return Container(
color: const Color(0xFF181818),
child: SafeArea(
top: false,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
// 点击终端空白区域自动聚焦输入框
session.focusNode.requestFocus();
},
child: Column(
children: [
if (_buildDistroStatusBar(context, session) != null)
_buildDistroStatusBar(context, session)!,
// 终端输出流滚动区域
Expanded(
child: ListView.builder(
controller: session.scrollController,
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
itemCount: session.outputLines.length,
itemBuilder: (context, index) {
final line = session.outputLines[index];
final isPrompt = line.startsWith('\$');
return SelectableText(
line.isEmpty ? ' ' : line,
style: TextStyle(
fontFamily: terminalFont.fontFamily,
fontFamilyFallback: terminalFont.fallback,
fontSize: 13.0,
color: isPrompt ? const Color(0xFF64B5F6) : const Color(0xFFD4D4D4),
height: 1.35,
),
);
},
),
),
const Divider(height: 1, color: Color(0xFF2A2A2A)),
// 终端命令行交互输入框
Container(
color: const Color(0xFF1E1E1E),
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0),
child: Row(
children: [
Text(
'\$ ',
style: TextStyle(
color: const Color(0xFF4CAF50),
fontWeight: FontWeight.bold,
fontFamily: terminalFont.fontFamily,
fontFamilyFallback: terminalFont.fallback,
fontSize: 14.0,
),
),
Expanded(
child: TextField(
controller: session.inputController,
focusNode: session.focusNode,
style: TextStyle(
color: Colors.white,
fontFamily: terminalFont.fontFamily,
fontFamilyFallback: terminalFont.fallback,
fontSize: 13.0,
),
cursorColor: const Color(0xFF4CAF50),
decoration: const InputDecoration(
hintText: '输入命令...',
hintStyle: TextStyle(color: Colors.white38, fontSize: 13.0),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.symmetric(vertical: 8.0),
),
onSubmitted: (text) {
if (text.isNotEmpty) {
context.read<TerminalProvider>().executeCommand(session, text);
session.inputController.clear();
session.focusNode.requestFocus();
}
},
),
),
IconButton(
icon: const Icon(Icons.send, size: 18, color: Colors.white70),
tooltip: '发送命令',
visualDensity: VisualDensity.compact,
onPressed: () {
final text = session.inputController.text;
if (text.isNotEmpty) {
context.read<TerminalProvider>().executeCommand(session, text);
session.inputController.clear();
session.focusNode.requestFocus();
}
},
),
],
),
),
],
),
child: xterm.TerminalView(
session.terminal,
focusNode: session.focusNode,
autofocus: true,
theme: xterm.TerminalThemes.defaultTheme,
textStyle: terminalStyle,
cursorType: xterm.TerminalCursorType.block,
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
),
),
);
}
Widget? _buildDistroStatusBar(BuildContext context, TerminalSession session) {
if (session.distroId != 'alpine') return null;
final distroProvider = context.watch<DistroProvider?>();
if (distroProvider == null) return null;
final status = distroProvider.getStatus('alpine');
if (status == DistroStatus.installed) return null;
if (status == DistroStatus.installing) {
final progress = distroProvider.getProgress('alpine');
final msg = distroProvider.getStatusMessage('alpine');
return Container(
color: const Color(0xFF252526),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.blueAccent),
),
const SizedBox(width: 8),
Expanded(
child: Text(
msg.isNotEmpty ? msg : '正在初始化 Alpine 环境...',
style: const TextStyle(color: Colors.white, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
'${(progress * 100).toInt()}%',
style: const TextStyle(color: Colors.white70, fontSize: 12),
),
],
),
const SizedBox(height: 6),
LinearProgressIndicator(
value: progress > 0 ? progress : null,
backgroundColor: Colors.white12,
valueColor: const AlwaysStoppedAnimation<Color>(Colors.blueAccent),
minHeight: 3,
),
],
),
);
}
if (status == DistroStatus.error) {
return Container(
color: Colors.red.shade900.withValues(alpha: 0.8),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0),
child: Row(
children: [
const Icon(Icons.error_outline, size: 16, color: Colors.white),
const SizedBox(width: 8),
Expanded(
child: Text(
distroProvider.getStatusMessage('alpine').isNotEmpty
? distroProvider.getStatusMessage('alpine')
: 'Alpine 初始化失败',
style: const TextStyle(color: Colors.white, fontSize: 12),
),
),
TextButton(
onPressed: () => distroProvider.installDistro('alpine'),
child: const Text('重试', style: TextStyle(color: Colors.yellowAccent)),
),
],
),
);
}
// notInstalled
return Container(
color: const Color(0xFF1E293B),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Row(
children: [
const Icon(Icons.layers_outlined, size: 18, color: Colors.lightBlueAccent),
const SizedBox(width: 10),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Alpine Linux 尚未就绪',
style: TextStyle(color: Colors.white, fontSize: 12.5, fontWeight: FontWeight.bold),
),
Text(
'内置极速解压包 (~3.9MB),点击立即初始化即可运行',
style: TextStyle(color: Colors.white70, fontSize: 11),
),
],
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueAccent,
foregroundColor: Colors.white,
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
textStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
),
onPressed: () {
distroProvider.installDistro('alpine');
},
child: const Text('一键初始化'),
),
],
),
);
}
}
+163
View File
@@ -0,0 +1,163 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/services/distro_installer.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:flutter/material.dart';
/// 同步前台解压进度弹窗(模态不可遮罩忽略,关闭或取消直接导致导入失败并回滚)
class DistroExtractDialog extends StatefulWidget {
final String systemName;
final Future<void> Function(InstallProgressCallback onProgress, bool Function() isCancelled) task;
const DistroExtractDialog({
super.key,
required this.systemName,
required this.task,
});
/// 快速拉起解压进程模态弹窗
/// 返回 true 表示导入成功,false 表示取消或失败
static Future<bool> show({
required BuildContext context,
required String systemName,
required Future<void> Function(InstallProgressCallback onProgress, bool Function() isCancelled) task,
}) async {
final result = await showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (ctx) => DistroExtractDialog(
systemName: systemName,
task: task,
),
);
return result ?? false;
}
@override
State<DistroExtractDialog> createState() => _DistroExtractDialogState();
}
class _DistroExtractDialogState extends State<DistroExtractDialog> {
double _progress = 0.0;
String? _message;
bool _isCancelled = false;
bool _isFinished = false;
@override
void initState() {
super.initState();
_startTask();
}
Future<void> _startTask() async {
try {
await widget.task(
(prog, msg) {
if (mounted && !_isCancelled) {
setState(() {
_progress = prog;
_message = msg;
});
}
},
() => _isCancelled,
);
if (mounted && !_isCancelled) {
_isFinished = true;
Navigator.of(context).pop(true);
}
} catch (e) {
if (mounted) {
final l10n = AppLocalizations.of(context)!;
if (e is DistroInstallCancelledException || _isCancelled) {
DialogUtils.showToast(context, l10n.cancelledImportSystem(widget.systemName));
} else {
DialogUtils.showErrorToast(context, l10n.importFailed(e.toString()));
}
Navigator.of(context).pop(false);
}
}
}
void _handleCancel() {
if (_isFinished) return;
final l10n = AppLocalizations.of(context)!;
setState(() {
_isCancelled = true;
_message = l10n.cancellingAndCleaning;
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final percentInt = (_progress * 100).clamp(0, 100).toInt();
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
_handleCancel();
},
child: AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
title: Row(
children: [
const Icon(Icons.archive_outlined, size: 22, color: Colors.blueAccent),
const SizedBox(width: 10),
Expanded(
child: Text(
l10n.importingSystemTitle(widget.systemName),
style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis,
),
),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_message ?? l10n.preparingInitialization,
style: TextStyle(
fontSize: 13.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 14),
LinearProgressIndicator(
value: _progress > 0 ? _progress : null,
minHeight: 6,
borderRadius: BorderRadius.circular(3),
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: Text(
'$percentInt%',
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
),
),
),
],
),
actions: [
TextButton(
onPressed: _isCancelled ? null : _handleCancel,
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.error,
),
child: Text(_isCancelled ? l10n.interrupting : l10n.cancelImport),
),
],
),
);
}
}
+314
View File
@@ -0,0 +1,314 @@
import 'dart:io';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/widgets/distro_extract_dialog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
/// 独立的 Linux 系统选择与管理对话框
class DistroSelectorDialog extends StatelessWidget {
const DistroSelectorDialog({super.key});
/// 打开系统选择与管理对话框
static Future<void> show(BuildContext context) {
return showDialog<void>(
context: context,
builder: (ctx) => const DistroSelectorDialog(),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final distroProvider = context.watch<DistroProvider>();
final systems = distroProvider.installedSystems;
final selectedSystem = distroProvider.selectedSystem;
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
titlePadding: const EdgeInsets.fromLTRB(20.0, 16.0, 12.0, 8.0),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
title: Row(
children: [
const Icon(Icons.dns_outlined, size: 22, color: Colors.blueAccent),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.systemManagement,
style: const TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold),
),
),
// 导入按钮与下拉选项
PopupMenuButton<String>(
icon: const Icon(Icons.add_circle_outline, color: Colors.blueAccent),
tooltip: l10n.importNewSystem,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
onSelected: (action) => _handleImportAction(context, action),
itemBuilder: (context) => [
PopupMenuItem(
value: 'builtin',
child: Row(
children: [
const Icon(Icons.layers_outlined, size: 18),
const SizedBox(width: 8),
Text(l10n.importBuiltinAlpine),
],
),
),
PopupMenuItem(
value: 'external',
child: Row(
children: [
const Icon(Icons.folder_open_outlined, size: 18),
const SizedBox(width: 8),
Text(l10n.importExternalTarGz),
],
),
),
],
),
],
),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
l10n.selectSystemDefaultPrompt,
style: TextStyle(
fontSize: 12.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
),
const Divider(height: 1),
Flexible(
child: systems.isEmpty
? Container(
padding: const EdgeInsets.symmetric(vertical: 32.0),
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.layers_clear_outlined,
size: 40,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
),
const SizedBox(height: 8),
Text(
l10n.noSystemsPrompt,
style: TextStyle(
fontSize: 13.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
)
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 4.0),
itemCount: systems.length,
itemBuilder: (context, index) {
final system = systems[index];
final isSelected = system == selectedSystem;
return Container(
margin: const EdgeInsets.symmetric(vertical: 3.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8.0),
border: Border.all(
color: isSelected
? theme.colorScheme.primary.withValues(alpha: 0.5)
: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
width: 1.0,
),
),
child: Material(
color: isSelected
? theme.colorScheme.primaryContainer.withValues(alpha: 0.4)
: Colors.transparent,
borderRadius: BorderRadius.circular(8.0),
child: ListTile(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 2.0),
title: Text(
system,
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected ? theme.colorScheme.primary : null,
fontSize: 14.0,
),
),
trailing: IconButton(
icon: Icon(
Icons.delete_outline,
color: theme.colorScheme.error,
size: 20,
),
tooltip: l10n.deleteSystemTooltip,
onPressed: () => _handleDeleteSystem(context, system),
),
onTap: () {
distroProvider.selectSystem(system);
},
),
),
);
},
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.done),
),
],
);
}
/// 处理导入菜单操作
Future<void> _handleImportAction(BuildContext context, String action) async {
final distroProvider = context.read<DistroProvider>();
final l10n = AppLocalizations.of(context)!;
if (action == 'builtin') {
// 1. 从内置 Alpine 导入
final defaultName = _generateUniqueSystemName('alpine', distroProvider.installedSystems);
final systemName = await DialogUtils.showInputDialog(
context,
title: l10n.importBuiltinAlpineTitle,
hintText: l10n.systemNameHintWithDefault(defaultName),
initialValue: defaultName,
);
if (systemName == null || systemName.trim().isEmpty || !context.mounted) return;
final cleanName = systemName.trim();
// 模态同步解压
final success = await DistroExtractDialog.show(
context: context,
systemName: cleanName,
task: (onProgress, isCancelled) {
return distroProvider.importBuiltinAlpine(
systemName: cleanName,
onProgress: onProgress,
isCancelled: isCancelled,
);
},
);
if (success && context.mounted) {
DialogUtils.showSuccessToast(context, l10n.systemImportSuccess(cleanName));
}
} else if (action == 'external') {
// 2. 从外部选择 .tar.gz 压缩包导入
final result = await FilePicker.platform.pickFiles(
type: FileType.any,
);
if (result == null || result.files.single.path == null || !context.mounted) return;
final filePath = result.files.single.path!;
final file = File(filePath);
// 提取默认名称(去掉 .tar.gz, .tgz 等后缀)
String baseName = p.basename(filePath);
if (baseName.endsWith('.tar.gz')) {
baseName = baseName.substring(0, baseName.length - 7);
} else if (baseName.endsWith('.tgz')) {
baseName = baseName.substring(0, baseName.length - 4);
} else {
baseName = p.basenameWithoutExtension(filePath);
}
baseName = baseName.replaceAll(RegExp(r'[^a-zA-Z0-9_\-]'), '_');
if (baseName.isEmpty) baseName = 'custom_linux';
final defaultName = _generateUniqueSystemName(baseName, distroProvider.installedSystems);
final systemName = await DialogUtils.showInputDialog(
context,
title: l10n.importExternalSystemTitle,
hintText: l10n.systemNameHint,
initialValue: defaultName,
);
if (systemName == null || systemName.trim().isEmpty || !context.mounted) return;
final cleanName = systemName.trim();
// 模态同步解压
final success = await DistroExtractDialog.show(
context: context,
systemName: cleanName,
task: (onProgress, isCancelled) {
return distroProvider.importFromCustomTarGz(
systemName: cleanName,
tarGzFile: file,
onProgress: onProgress,
isCancelled: isCancelled,
);
},
);
if (success && context.mounted) {
DialogUtils.showSuccessToast(context, l10n.externalSystemImportSuccess(cleanName));
}
}
}
/// 高危操作:二次确认删除系统
Future<void> _handleDeleteSystem(BuildContext context, String systemName) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
context,
title: l10n.deleteSystemConfirmTitle,
message: l10n.deleteSystemConfirmMessage(systemName),
confirmText: l10n.permanentDelete,
);
if (confirmed && context.mounted) {
final distroProvider = context.read<DistroProvider>();
final terminalProvider = context.read<TerminalProvider?>();
try {
await distroProvider.deleteSystem(systemName);
terminalProvider?.removeSessionsForDistro(systemName);
if (!distroProvider.hasAnySystem) {
terminalProvider?.clearAllSessions();
}
if (context.mounted) {
DialogUtils.showToast(context, l10n.deleteSystemSuccess(systemName));
}
} catch (e) {
if (context.mounted) {
DialogUtils.showErrorToast(context, l10n.deleteSystemFailed(e.toString()));
}
}
}
}
/// 自动生成不重复的系统实例名
String _generateUniqueSystemName(String prefix, List<String> existingSystems) {
if (!existingSystems.contains(prefix)) return prefix;
int index = 1;
while (existingSystems.contains('${prefix}_$index')) {
index++;
}
return '${prefix}_$index';
}
}
+19 -5
View File
@@ -1,4 +1,7 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/widgets/terminal_session_item_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
@@ -10,6 +13,7 @@ class TerminalDrawer extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final provider = context.watch<TerminalProvider>();
final sessions = provider.sessions;
final activeIndex = provider.activeIndex;
@@ -30,7 +34,7 @@ class TerminalDrawer extends StatelessWidget {
child: Row(
children: [
Text(
'会话',
l10n.sessionDrawerTitle,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
@@ -39,10 +43,20 @@ class TerminalDrawer extends StatelessWidget {
const Spacer(),
IconButton(
icon: const Icon(Icons.add),
tooltip: '添加终端',
tooltip: l10n.addTerminalTooltip,
onPressed: () {
// 直接添加终端,但不跳转
provider.createSession(name: '会话', distroId: 'alpine', activate: false);
final distroProvider = context.read<DistroProvider?>();
final currentSystem = distroProvider?.selectedSystem;
if (currentSystem == null) {
DialogUtils.showToast(context, l10n.noSystemSelectedWarning);
return;
}
// 基于当前选择的系统创建新终端
provider.createSession(
name: l10n.sessionDefaultName,
distroId: currentSystem,
activate: false,
);
},
),
],
@@ -56,7 +70,7 @@ class TerminalDrawer extends StatelessWidget {
child: sessions.isEmpty
? Center(
child: Text(
'暂无会话,请点击右上角添加',
l10n.noSessionsInDrawerPrompt,
style: TextStyle(
color: theme.colorScheme.onSurfaceVariant,
fontSize: 13.0,
+10 -7
View File
@@ -1,3 +1,4 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/terminal_session.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/utils/dialog_utils.dart';
@@ -22,8 +23,8 @@ class TerminalSessionItemWidget extends StatelessWidget {
final theme = Theme.of(context);
final displayIndex = index + 1; // 索引从 1 开始
final titleText = '($displayIndex) ${session.name}';
final badgeLabel = session.distroId;
final isHost = session.distroId == 'host';
final badgeLabel = isHost ? 'Host' : 'Alpine';
final textStyle = theme.textTheme.bodyMedium?.copyWith(
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
@@ -122,6 +123,7 @@ class TerminalSessionItemWidget extends StatelessWidget {
);
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final onSurfaceColor = theme.colorScheme.onSurface;
final selectedAction = await showMenu<String>(
@@ -141,14 +143,14 @@ class TerminalSessionItemWidget extends StatelessWidget {
_buildMenuItem(
value: 'rename',
icon: Icons.edit_outlined,
title: '重命名',
title: l10n.rename,
color: onSurfaceColor,
),
const PopupMenuDivider(),
_buildMenuItem(
value: 'delete',
icon: Icons.delete_outline,
title: '删除',
title: l10n.delete,
color: theme.colorScheme.error,
isDestructive: true,
),
@@ -184,13 +186,14 @@ class TerminalSessionItemWidget extends StatelessWidget {
void _handleMenuAction(BuildContext context, String action, int displayIndex) async {
final provider = context.read<TerminalProvider>();
final l10n = AppLocalizations.of(context)!;
switch (action) {
case 'rename':
final newName = await DialogUtils.showInputDialog(
context,
title: '重命名',
hintText: '新名称',
title: l10n.rename,
hintText: l10n.newName,
initialValue: session.name,
);
if (newName != null && newName.trim().isNotEmpty && newName.trim() != session.name) {
@@ -201,8 +204,8 @@ class TerminalSessionItemWidget extends StatelessWidget {
case 'delete':
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
context,
title: '确认删除',
message: '确定要删除终端 "($displayIndex) ${session.name}" 吗?',
title: l10n.confirmDelete,
message: l10n.confirmDeleteTerminalSession(displayIndex, session.name),
);
if (confirmed && context.mounted) {
provider.removeSession(session.id);