1
This commit is contained in:
1 parent
54c3083c24
commit
87e03ce0d8
44 files changed
+3965
-307
No files matched your search
+15
-1
@@ -74,6 +74,17 @@
|
||||
"decreaseFontSize": "Decrease font size",
|
||||
"increaseFontSize": "Increase font size",
|
||||
"fontSizeDialogTitle": "Editor Font Size",
|
||||
"indentSize": "Indent Size",
|
||||
"selectIndentSize": "Select Indent Size",
|
||||
"spacesCount": "{count} Spaces",
|
||||
"@spacesCount": {
|
||||
"description": "Indent spaces count",
|
||||
"placeholders": {
|
||||
"count": {
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
},
|
||||
"wordWrap": "Word Wrap",
|
||||
"wordWrapSubtitle": "Wrap long lines to fit the editor width",
|
||||
"virtualKeyboard": "Accessory Keyboard",
|
||||
@@ -107,5 +118,8 @@
|
||||
"fileConflictTitle": "File Changed Externally",
|
||||
"fileConflictMessage": "File \"{name}\" has been changed on disk. How would you like to proceed?",
|
||||
"reloadFromDisk": "Reload from Disk",
|
||||
"keepLocal": "Keep Local Changes"
|
||||
"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"
|
||||
}
|
||||
@@ -542,6 +542,24 @@ abstract class AppLocalizations {
|
||||
/// **'代码字号'**
|
||||
String get fontSizeDialogTitle;
|
||||
|
||||
/// No description provided for @indentSize.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'缩进大小'**
|
||||
String get indentSize;
|
||||
|
||||
/// No description provided for @selectIndentSize.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'选择缩进空格数'**
|
||||
String get selectIndentSize;
|
||||
|
||||
/// 缩进空格数量展示
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'{count} 个空格'**
|
||||
String spacesCount(int count);
|
||||
|
||||
/// No description provided for @wordWrap.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
@@ -745,6 +763,24 @@ abstract class AppLocalizations {
|
||||
/// In zh, this message translates to:
|
||||
/// **'保留本地修改'**
|
||||
String get keepLocal;
|
||||
|
||||
/// No description provided for @storagePermissionRequiredTitle.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'需要存储访问权限'**
|
||||
String get storagePermissionRequiredTitle;
|
||||
|
||||
/// No description provided for @storagePermissionRequiredMessage.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'代码编辑器需要“管理所有文件”权限,以便在您的设备上读取、新建和保存项目文件。\n\n请在接下来的系统设置页面中开启该权限。'**
|
||||
String get storagePermissionRequiredMessage;
|
||||
|
||||
/// No description provided for @goToSettings.
|
||||
///
|
||||
/// In zh, this message translates to:
|
||||
/// **'去设置'**
|
||||
String get goToSettings;
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate
|
||||
|
||||
@@ -250,6 +250,17 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get fontSizeDialogTitle => 'Editor Font Size';
|
||||
|
||||
@override
|
||||
String get indentSize => 'Indent Size';
|
||||
|
||||
@override
|
||||
String get selectIndentSize => 'Select Indent Size';
|
||||
|
||||
@override
|
||||
String spacesCount(int count) {
|
||||
return '$count Spaces';
|
||||
}
|
||||
|
||||
@override
|
||||
String get wordWrap => 'Word Wrap';
|
||||
|
||||
@@ -360,4 +371,14 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
|
||||
@override
|
||||
String get keepLocal => 'Keep Local Changes';
|
||||
|
||||
@override
|
||||
String get storagePermissionRequiredTitle => 'Storage Access Required';
|
||||
|
||||
@override
|
||||
String get 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.';
|
||||
|
||||
@override
|
||||
String get goToSettings => 'Settings';
|
||||
}
|
||||
@@ -246,6 +246,17 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get fontSizeDialogTitle => '代码字号';
|
||||
|
||||
@override
|
||||
String get indentSize => '缩进大小';
|
||||
|
||||
@override
|
||||
String get selectIndentSize => '选择缩进空格数';
|
||||
|
||||
@override
|
||||
String spacesCount(int count) {
|
||||
return '$count 个空格';
|
||||
}
|
||||
|
||||
@override
|
||||
String get wordWrap => '自动换行';
|
||||
|
||||
@@ -353,4 +364,14 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
|
||||
@override
|
||||
String get keepLocal => '保留本地修改';
|
||||
|
||||
@override
|
||||
String get storagePermissionRequiredTitle => '需要存储访问权限';
|
||||
|
||||
@override
|
||||
String get storagePermissionRequiredMessage =>
|
||||
'代码编辑器需要“管理所有文件”权限,以便在您的设备上读取、新建和保存项目文件。\n\n请在接下来的系统设置页面中开启该权限。';
|
||||
|
||||
@override
|
||||
String get goToSettings => '去设置';
|
||||
}
|
||||
+15
-1
@@ -74,6 +74,17 @@
|
||||
"decreaseFontSize": "减小字号",
|
||||
"increaseFontSize": "增大字号",
|
||||
"fontSizeDialogTitle": "代码字号",
|
||||
"indentSize": "缩进大小",
|
||||
"selectIndentSize": "选择缩进空格数",
|
||||
"spacesCount": "{count} 个空格",
|
||||
"@spacesCount": {
|
||||
"description": "缩进空格数量展示",
|
||||
"placeholders": {
|
||||
"count": {
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
},
|
||||
"wordWrap": "自动换行",
|
||||
"wordWrapSubtitle": "长代码行超出边界时自动折行",
|
||||
"virtualKeyboard": "辅助小键盘",
|
||||
@@ -107,5 +118,8 @@
|
||||
"fileConflictTitle": "外部文件已被更改",
|
||||
"fileConflictMessage": "文件 \"{name}\" 已在外部被更改。您希望如何处理?",
|
||||
"reloadFromDisk": "用磁盘内容覆盖",
|
||||
"keepLocal": "保留本地修改"
|
||||
"keepLocal": "保留本地修改",
|
||||
"storagePermissionRequiredTitle": "需要存储访问权限",
|
||||
"storagePermissionRequiredMessage": "代码编辑器需要“管理所有文件”权限,以便在您的设备上读取、新建和保存项目文件。\n\n请在接下来的系统设置页面中开启该权限。",
|
||||
"goToSettings": "去设置"
|
||||
}
|
||||
+8
-10
@@ -1,7 +1,9 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/providers/distro_provider.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:code_editor/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/views/main_view.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -24,17 +26,11 @@ class MyApp extends StatelessWidget {
|
||||
update: (_, project, tab) =>
|
||||
(tab ?? (TabProvider()..init()))..bindProjectProvider(project),
|
||||
),
|
||||
ChangeNotifierProvider(create: (_) => TerminalProvider()),
|
||||
ChangeNotifierProvider(create: (_) => DistroProvider()..checkAllStatuses()),
|
||||
],
|
||||
child: Consumer<SettingsProvider>(
|
||||
builder: (context, settings, child) {
|
||||
const fontFallbacks = [
|
||||
'PingFang SC', // iOS / macOS
|
||||
'Noto Sans SC', // Android
|
||||
'Microsoft YaHei', // Windows
|
||||
'WenQuanYi Micro Hei', // Linux
|
||||
'sans-serif', // Web & generic fallback
|
||||
];
|
||||
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: settings.locale,
|
||||
@@ -49,7 +45,8 @@ class MyApp extends StatelessWidget {
|
||||
seedColor: Colors.blue,
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
fontFamilyFallback: fontFallbacks,
|
||||
fontFamily: settings.uiFont.fontFamily,
|
||||
fontFamilyFallback: settings.uiFont.fallback,
|
||||
),
|
||||
darkTheme: ThemeData(
|
||||
useMaterial3: true,
|
||||
@@ -58,7 +55,8 @@ class MyApp extends StatelessWidget {
|
||||
seedColor: Colors.blue,
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
fontFamilyFallback: fontFallbacks,
|
||||
fontFamily: settings.uiFont.fontFamily,
|
||||
fontFamilyFallback: settings.uiFont.fallback,
|
||||
),
|
||||
home: const MainView(),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
/// 字体定义与预设常量
|
||||
class AppFontItem {
|
||||
final String id;
|
||||
final String name;
|
||||
final String? fontFamily;
|
||||
final List<String> fallback;
|
||||
final bool isMonospace;
|
||||
|
||||
const AppFontItem({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.fontFamily,
|
||||
this.fallback = const [],
|
||||
this.isMonospace = false,
|
||||
});
|
||||
}
|
||||
|
||||
/// 集中管理的字体常量表(方便随时追加网络/本地下载的字体)
|
||||
class AppFonts {
|
||||
// ==========================================
|
||||
// 1. 外观 UI 字体选项
|
||||
// ==========================================
|
||||
static const AppFontItem uiDefault = AppFontItem(
|
||||
id: 'system_default',
|
||||
name: '系统默认 (System Default)',
|
||||
fontFamily: null,
|
||||
fallback: [
|
||||
'PingFang SC',
|
||||
'Noto Sans SC',
|
||||
'Microsoft YaHei',
|
||||
'WenQuanYi Micro Hei',
|
||||
'sans-serif',
|
||||
],
|
||||
);
|
||||
|
||||
static const AppFontItem uiSansSerif = AppFontItem(
|
||||
id: 'sans_serif',
|
||||
name: '无衬线体 (Sans-Serif)',
|
||||
fontFamily: 'sans-serif',
|
||||
fallback: [
|
||||
'PingFang SC',
|
||||
'Noto Sans SC',
|
||||
'Microsoft YaHei',
|
||||
'sans-serif',
|
||||
],
|
||||
);
|
||||
|
||||
static const AppFontItem uiSerif = AppFontItem(
|
||||
id: 'serif',
|
||||
name: '衬线体 (Serif / 宋体)',
|
||||
fontFamily: 'serif',
|
||||
fallback: [
|
||||
'Songti SC',
|
||||
'SimSun',
|
||||
'serif',
|
||||
],
|
||||
);
|
||||
|
||||
static const AppFontItem uiJetBrainsMono = AppFontItem(
|
||||
id: 'jetbrains_mono',
|
||||
name: 'JetBrains Mono',
|
||||
fontFamily: 'JetBrains Mono',
|
||||
fallback: [
|
||||
'PingFang SC',
|
||||
'Noto Sans SC',
|
||||
'Microsoft YaHei',
|
||||
'sans-serif',
|
||||
],
|
||||
);
|
||||
|
||||
static const AppFontItem uiFiraCode = AppFontItem(
|
||||
id: 'fira_code',
|
||||
name: 'Fira Code',
|
||||
fontFamily: 'Fira Code',
|
||||
fallback: [
|
||||
'PingFang SC',
|
||||
'Noto Sans SC',
|
||||
'Microsoft YaHei',
|
||||
'sans-serif',
|
||||
],
|
||||
);
|
||||
|
||||
/// 外观 UI 可选字体列表
|
||||
static const List<AppFontItem> uiFonts = [
|
||||
uiDefault,
|
||||
uiSansSerif,
|
||||
uiSerif,
|
||||
uiJetBrainsMono,
|
||||
uiFiraCode,
|
||||
];
|
||||
|
||||
// ==========================================
|
||||
// 2. 代码编辑区字体选项
|
||||
// ==========================================
|
||||
static const AppFontItem editorMonospace = AppFontItem(
|
||||
id: 'monospace',
|
||||
name: '系统等宽 (System Monospace)',
|
||||
fontFamily: 'monospace',
|
||||
fallback: [
|
||||
'Consolas',
|
||||
'Menlo',
|
||||
'Monaco',
|
||||
'Courier New',
|
||||
'monospace',
|
||||
],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem editorConsolas = AppFontItem(
|
||||
id: 'consolas',
|
||||
name: 'Consolas',
|
||||
fontFamily: 'Consolas',
|
||||
fallback: ['monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem editorCourierNew = AppFontItem(
|
||||
id: 'courier_new',
|
||||
name: 'Courier New',
|
||||
fontFamily: 'Courier New',
|
||||
fallback: ['Courier', 'monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem editorMenlo = AppFontItem(
|
||||
id: 'menlo',
|
||||
name: 'Menlo / Monaco',
|
||||
fontFamily: 'Menlo',
|
||||
fallback: ['Monaco', 'monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
/// 预设的开源编程字体配置(用户后续下载字体包放入 assets/fonts/ 并配置 pubspec 后即可即开即用)
|
||||
static const AppFontItem editorJetBrainsMono = AppFontItem(
|
||||
id: 'jetbrains_mono',
|
||||
name: 'JetBrains Mono (推荐)',
|
||||
fontFamily: 'JetBrains Mono',
|
||||
fallback: ['monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem editorFiraCode = AppFontItem(
|
||||
id: 'fira_code',
|
||||
name: 'Fira Code',
|
||||
fontFamily: 'Fira Code',
|
||||
fallback: ['monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
/// 代码编辑区可选字体列表
|
||||
static const List<AppFontItem> editorFonts = [
|
||||
editorMonospace,
|
||||
editorConsolas,
|
||||
editorCourierNew,
|
||||
editorMenlo,
|
||||
editorJetBrainsMono,
|
||||
editorFiraCode,
|
||||
];
|
||||
|
||||
// ==========================================
|
||||
// 3. 终端字体选项
|
||||
// ==========================================
|
||||
static const AppFontItem terminalMonospace = AppFontItem(
|
||||
id: 'monospace',
|
||||
name: '系统等宽 (System Monospace)',
|
||||
fontFamily: 'monospace',
|
||||
fallback: [
|
||||
'Consolas',
|
||||
'Menlo',
|
||||
'Monaco',
|
||||
'Courier New',
|
||||
'monospace',
|
||||
],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem terminalConsolas = AppFontItem(
|
||||
id: 'consolas',
|
||||
name: 'Consolas',
|
||||
fontFamily: 'Consolas',
|
||||
fallback: ['monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem terminalCourierNew = AppFontItem(
|
||||
id: 'courier_new',
|
||||
name: 'Courier New',
|
||||
fontFamily: 'Courier New',
|
||||
fallback: ['Courier', 'monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem terminalMenlo = AppFontItem(
|
||||
id: 'menlo',
|
||||
name: 'Menlo / Monaco',
|
||||
fontFamily: 'Menlo',
|
||||
fallback: ['Monaco', 'monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem terminalJetBrainsMono = AppFontItem(
|
||||
id: 'jetbrains_mono',
|
||||
name: 'JetBrains Mono (推荐)',
|
||||
fontFamily: 'JetBrains Mono',
|
||||
fallback: ['monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
static const AppFontItem terminalFiraCode = AppFontItem(
|
||||
id: 'fira_code',
|
||||
name: 'Fira Code',
|
||||
fontFamily: 'Fira Code',
|
||||
fallback: ['monospace'],
|
||||
isMonospace: true,
|
||||
);
|
||||
|
||||
/// 终端可选字体列表
|
||||
static const List<AppFontItem> terminalFonts = [
|
||||
terminalMonospace,
|
||||
terminalConsolas,
|
||||
terminalCourierNew,
|
||||
terminalMenlo,
|
||||
terminalJetBrainsMono,
|
||||
terminalFiraCode,
|
||||
];
|
||||
|
||||
// ==========================================
|
||||
// 4. 查询辅助方法
|
||||
// ==========================================
|
||||
static AppFontItem getUiFont(String? id) {
|
||||
return uiFonts.firstWhere(
|
||||
(f) => f.id == id,
|
||||
orElse: () => uiDefault,
|
||||
);
|
||||
}
|
||||
|
||||
static AppFontItem getEditorFont(String? id) {
|
||||
return editorFonts.firstWhere(
|
||||
(f) => f.id == id,
|
||||
orElse: () => editorMonospace,
|
||||
);
|
||||
}
|
||||
|
||||
static AppFontItem getTerminalFont(String? id) {
|
||||
return terminalFonts.firstWhere(
|
||||
(f) => f.id == id,
|
||||
orElse: () => terminalMonospace,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/// Linux 发行版安装状态
|
||||
enum DistroStatus {
|
||||
/// 未安装
|
||||
notInstalled,
|
||||
|
||||
/// 正在安装/解压中
|
||||
installing,
|
||||
|
||||
/// 已安装就绪
|
||||
installed,
|
||||
|
||||
/// 安装或运行异常
|
||||
error,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
);
|
||||
}
|
||||
|
||||
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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 单个终端会话的数据与状态模型
|
||||
class TerminalSession {
|
||||
final String id;
|
||||
String name;
|
||||
final String distroId;
|
||||
final DateTime createdAt;
|
||||
final List<String> outputLines;
|
||||
final TextEditingController inputController;
|
||||
final ScrollController scrollController;
|
||||
final FocusNode focusNode;
|
||||
|
||||
TerminalSession({
|
||||
required this.id,
|
||||
this.name = '会话',
|
||||
this.distroId = 'alpine',
|
||||
DateTime? createdAt,
|
||||
List<String>? initialOutput,
|
||||
}) : createdAt = createdAt ?? DateTime.now(),
|
||||
outputLines = initialOutput ?? <String>[],
|
||||
inputController = TextEditingController(),
|
||||
scrollController = ScrollController(),
|
||||
focusNode = FocusNode();
|
||||
|
||||
/// 向终端输出追加内容
|
||||
void appendOutput(String line) {
|
||||
outputLines.add(line);
|
||||
_autoScrollToBottom();
|
||||
}
|
||||
|
||||
/// 自动滚动到终端最底部
|
||||
void _autoScrollToBottom() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (scrollController.hasClients) {
|
||||
scrollController.animateTo(
|
||||
scrollController.position.maxScrollExtent,
|
||||
duration: const Duration(milliseconds: 100),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 清屏
|
||||
void clear() {
|
||||
outputLines.clear();
|
||||
}
|
||||
|
||||
/// 释放资源
|
||||
void dispose() {
|
||||
inputController.dispose();
|
||||
scrollController.dispose();
|
||||
focusNode.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/distro_info.dart';
|
||||
import '../services/distro_manager.dart';
|
||||
|
||||
/// Linux 发行版状态提供者(供 UI 监听与绑定)
|
||||
class DistroProvider with ChangeNotifier {
|
||||
final DistroManager _manager = DistroManager();
|
||||
|
||||
/// 各发行版状态缓存
|
||||
final Map<String, DistroStatus> _statuses = {};
|
||||
|
||||
/// 安装进度 (0.0 ~ 1.0)
|
||||
final Map<String, double> _progress = {};
|
||||
|
||||
/// 状态描述文字(如 "正在解压... 45%")
|
||||
final Map<String, String> _statusMessages = {};
|
||||
|
||||
/// 默认创建会话使用的发行版 ID
|
||||
String _defaultDistroId = 'alpine';
|
||||
|
||||
String get defaultDistroId => _defaultDistroId;
|
||||
|
||||
List<DistroInfo> get distros => _manager.listDistros();
|
||||
|
||||
DistroStatus getStatus(String id) => _statuses[id] ?? DistroStatus.notInstalled;
|
||||
|
||||
double getProgress(String id) => _progress[id] ?? 0.0;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 设置默认发行版
|
||||
void setDefaultDistro(String id) {
|
||||
if (_defaultDistroId != id) {
|
||||
_defaultDistroId = id;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 安装发行版
|
||||
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] = '已就绪';
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'dart:convert';
|
||||
import 'package:code_editor/models/app_font.dart';
|
||||
import 'package:code_editor/models/editor_theme.dart';
|
||||
import 'package:code_editor/models/virtual_keyboard_config.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -8,20 +9,30 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
//外观
|
||||
static const String _keyAppThemeMode = 'app_theme_mode'; //应用主题
|
||||
static const String _keyUiFont = 'app_ui_font'; //界面字体
|
||||
|
||||
//编辑区
|
||||
static const String _keyEditorTheme = 'editor_theme_id'; //代码主题
|
||||
static const String _keyEditorFontSize = 'editor_font_size'; //代码字体大小
|
||||
static const String _keyEditorIndentSize = 'editor_indent_size'; //缩进大小
|
||||
static const String _keyWordWrap = 'editor_word_wrap'; //自动换行
|
||||
static const String _keyEnableVirtualKeyboard = 'enable_virtual_keyboard'; //小键盘启用
|
||||
static const String _keyVirtualKeyboardConfig = 'virtual_keyboard_config'; //小键盘配置JSON
|
||||
static const String _keyEditorFont = 'editor_font_family'; //代码字体
|
||||
|
||||
//终端
|
||||
static const String _keyTerminalFont = 'terminal_font_family'; //终端字体
|
||||
|
||||
//语言
|
||||
static const String _keyAppLocale = 'app_locale';
|
||||
|
||||
ThemeMode _appThemeMode = ThemeMode.system;
|
||||
String _uiFontId = 'system_default';
|
||||
EditorTheme _editorTheme = EditorTheme.atomOneDark;
|
||||
String _editorFontId = 'monospace';
|
||||
String _terminalFontId = 'monospace';
|
||||
double _fontSize = 14.0;
|
||||
int _indentSize = 2;
|
||||
bool _wordWrap = true;
|
||||
bool _enableVirtualKeyboard = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS;
|
||||
String _virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty();
|
||||
@@ -29,8 +40,18 @@ class SettingsProvider extends ChangeNotifier {
|
||||
Locale? _locale;
|
||||
|
||||
ThemeMode get appThemeMode => _appThemeMode;
|
||||
String get uiFontId => _uiFontId;
|
||||
AppFontItem get uiFont => AppFonts.getUiFont(_uiFontId);
|
||||
|
||||
EditorTheme get editorTheme => _editorTheme;
|
||||
String get editorFontId => _editorFontId;
|
||||
AppFontItem get editorFont => AppFonts.getEditorFont(_editorFontId);
|
||||
|
||||
String get terminalFontId => _terminalFontId;
|
||||
AppFontItem get terminalFont => AppFonts.getTerminalFont(_terminalFontId);
|
||||
|
||||
double get fontSize => _fontSize;
|
||||
int get indentSize => _indentSize;
|
||||
bool get wordWrap => _wordWrap;
|
||||
bool get enableVirtualKeyboard => _enableVirtualKeyboard;
|
||||
String get virtualKeyboardConfigJson => _virtualKeyboardConfigJson;
|
||||
@@ -64,6 +85,11 @@ class SettingsProvider extends ChangeNotifier {
|
||||
_fontSize = savedFontSize;
|
||||
}
|
||||
|
||||
final savedIndentSize = prefs.getInt(_keyEditorIndentSize);
|
||||
if (savedIndentSize != null && (savedIndentSize == 2 || savedIndentSize == 4 || savedIndentSize == 8)) {
|
||||
_indentSize = savedIndentSize;
|
||||
}
|
||||
|
||||
final savedWordWrap = prefs.getBool(_keyWordWrap);
|
||||
if(savedWordWrap != null) {
|
||||
_wordWrap = savedWordWrap;
|
||||
@@ -86,6 +112,22 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
//设置字体
|
||||
final savedUiFont = prefs.getString(_keyUiFont);
|
||||
if (savedUiFont != null && savedUiFont.isNotEmpty) {
|
||||
_uiFontId = savedUiFont;
|
||||
}
|
||||
|
||||
final savedEditorFont = prefs.getString(_keyEditorFont);
|
||||
if (savedEditorFont != null && savedEditorFont.isNotEmpty) {
|
||||
_editorFontId = savedEditorFont;
|
||||
}
|
||||
|
||||
final savedTerminalFont = prefs.getString(_keyTerminalFont);
|
||||
if (savedTerminalFont != null && savedTerminalFont.isNotEmpty) {
|
||||
_terminalFontId = savedTerminalFont;
|
||||
}
|
||||
|
||||
//设置语言
|
||||
final savedLocale = prefs.getString(_keyAppLocale);
|
||||
if(savedLocale != null && savedLocale.isNotEmpty) {
|
||||
@@ -129,6 +171,17 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setIndentSize(int size) async {
|
||||
if (size != 2 && size != 4 && size != 8) return;
|
||||
if (_indentSize == size) return;
|
||||
_indentSize = size;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt(_keyEditorIndentSize, size);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setWordWrap(bool wrap) async {
|
||||
if(_wordWrap == wrap) return;
|
||||
_wordWrap = wrap;
|
||||
@@ -190,4 +243,34 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setUiFontId(String fontId) async {
|
||||
if (_uiFontId == fontId) return;
|
||||
_uiFontId = fontId;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyUiFont, fontId);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setEditorFontId(String fontId) async {
|
||||
if (_editorFontId == fontId) return;
|
||||
_editorFontId = fontId;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyEditorFont, fontId);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setTerminalFontId(String fontId) async {
|
||||
if (_terminalFontId == fontId) return;
|
||||
_terminalFontId = fontId;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyTerminalFont, fontId);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import 'package:code_editor/models/terminal_session.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 全局终端会话管理 Provider
|
||||
class TerminalProvider extends ChangeNotifier {
|
||||
final List<TerminalSession> _sessions = [];
|
||||
int _activeIndex = 0;
|
||||
|
||||
List<TerminalSession> get sessions => List.unmodifiable(_sessions);
|
||||
|
||||
int get activeIndex => _activeIndex;
|
||||
|
||||
bool get isEmpty => _sessions.isEmpty;
|
||||
|
||||
bool get isNotEmpty => _sessions.isNotEmpty;
|
||||
|
||||
TerminalSession? get activeSession {
|
||||
if (_sessions.isEmpty) return null;
|
||||
if (_activeIndex >= 0 && _activeIndex < _sessions.length) {
|
||||
return _sessions[_activeIndex];
|
||||
}
|
||||
return _sessions.first;
|
||||
}
|
||||
|
||||
/// 懒加载:进入终端页面时调用,如果尚未创建会话,则自动创建并激活首个会话
|
||||
void ensureInitialized() {
|
||||
if (_sessions.isEmpty) {
|
||||
createSession(name: '会话', activate: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// 创建新会话
|
||||
/// [distroId]: 发行版标识符(如 'alpine', 'host')
|
||||
/// [activate]: 是否自动跳转切换到该会话。抽屉右上角加号点击时为 false(直接添加但不跳转)。
|
||||
TerminalSession createSession({
|
||||
String name = '会话',
|
||||
String distroId = 'alpine',
|
||||
bool activate = false,
|
||||
}) {
|
||||
final nextIndex = _sessions.length + 1;
|
||||
final session = TerminalSession(
|
||||
id: 'session_${DateTime.now().microsecondsSinceEpoch}_$nextIndex',
|
||||
name: name,
|
||||
distroId: distroId,
|
||||
initialOutput: [
|
||||
'Welcome to Terminal ($nextIndex) [$distroId]',
|
||||
'Type "help" for a list of built-in commands or "clear" to clear.',
|
||||
'',
|
||||
],
|
||||
);
|
||||
|
||||
_sessions.add(session);
|
||||
|
||||
if (activate || _sessions.length == 1) {
|
||||
_activeIndex = _sessions.length - 1;
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
return session;
|
||||
}
|
||||
|
||||
/// 切换当前激活的会话
|
||||
void selectSession(int index) {
|
||||
if (index >= 0 && index < _sessions.length) {
|
||||
if (_activeIndex != index) {
|
||||
_activeIndex = index;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 重命名指定终端会话
|
||||
void renameSession(String id, String newName) {
|
||||
final trimmed = newName.trim();
|
||||
if (trimmed.isEmpty) return;
|
||||
|
||||
final index = _sessions.indexWhere((s) => s.id == id);
|
||||
if (index != -1) {
|
||||
_sessions[index].name = trimmed;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 删除指定终端会话
|
||||
void removeSession(String id) {
|
||||
final index = _sessions.indexWhere((s) => s.id == id);
|
||||
if (index == -1) return;
|
||||
|
||||
final removedSession = _sessions.removeAt(index);
|
||||
removedSession.dispose();
|
||||
|
||||
if (_sessions.isEmpty) {
|
||||
_activeIndex = 0;
|
||||
} else if (_activeIndex >= _sessions.length) {
|
||||
_activeIndex = _sessions.length - 1;
|
||||
} else if (_activeIndex > index) {
|
||||
_activeIndex--;
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 拖拽重新排序终端会话(接收 onReorderItem 传入的已修正目标索引)
|
||||
void reorderSessions(int oldIndex, int newIndex) {
|
||||
if (oldIndex < 0 || oldIndex >= _sessions.length) return;
|
||||
if (newIndex < 0 || newIndex >= _sessions.length) return;
|
||||
if (oldIndex == newIndex) return;
|
||||
|
||||
final activeSessionId = activeSession?.id;
|
||||
|
||||
final session = _sessions.removeAt(oldIndex);
|
||||
_sessions.insert(newIndex, session);
|
||||
|
||||
if (activeSessionId != null) {
|
||||
final foundIndex = _sessions.indexWhere((s) => s.id == activeSessionId);
|
||||
if (foundIndex != -1) {
|
||||
_activeIndex = foundIndex;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final session in _sessions) {
|
||||
session.dispose();
|
||||
}
|
||||
_sessions.clear();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
-50
@@ -26,17 +26,20 @@ enum FileConflictResult {
|
||||
class DialogUtils {
|
||||
DialogUtils._();
|
||||
|
||||
// ==========================================
|
||||
// 1. Toast 轻提示
|
||||
// ==========================================
|
||||
static OverlayEntry? _currentToastEntry;
|
||||
|
||||
/// 显示浮动 Toast
|
||||
/// 显示浮动 Toast(自动避开软键盘及底部安全区)
|
||||
static void showToast(
|
||||
BuildContext context,
|
||||
String message, {
|
||||
ToastType type = ToastType.info,
|
||||
Duration duration = const Duration(seconds: 2),
|
||||
}) {
|
||||
if (_currentToastEntry != null && _currentToastEntry!.mounted) {
|
||||
_currentToastEntry!.remove();
|
||||
_currentToastEntry = null;
|
||||
}
|
||||
|
||||
final overlay = Overlay.maybeOf(context, rootOverlay: true);
|
||||
if (overlay == null) return;
|
||||
|
||||
@@ -73,56 +76,26 @@ class DialogUtils {
|
||||
|
||||
late OverlayEntry entry;
|
||||
entry = OverlayEntry(
|
||||
builder: (ctx) => Positioned(
|
||||
bottom: 48,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Center(
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 24),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: borderColor, width: 1),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black26,
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(iconData, size: 18, color: textColor),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
message,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: textColor,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
builder: (ctx) => _ToastWidget(
|
||||
message: message,
|
||||
iconData: iconData,
|
||||
bgColor: bgColor,
|
||||
textColor: textColor,
|
||||
borderColor: borderColor,
|
||||
duration: duration,
|
||||
onDismissed: () {
|
||||
if (entry.mounted) {
|
||||
entry.remove();
|
||||
}
|
||||
if (_currentToastEntry == entry) {
|
||||
_currentToastEntry = null;
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
_currentToastEntry = entry;
|
||||
overlay.insert(entry);
|
||||
Future.delayed(duration, () {
|
||||
if (entry.mounted) {
|
||||
entry.remove();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static void showSuccessToast(BuildContext context, String message) {
|
||||
@@ -566,3 +539,134 @@ class DialogUtils {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 视口感知与软键盘避让的动画 Toast 悬浮组件
|
||||
class _ToastWidget extends StatefulWidget {
|
||||
final String message;
|
||||
final IconData iconData;
|
||||
final Color bgColor;
|
||||
final Color textColor;
|
||||
final Color borderColor;
|
||||
final VoidCallback onDismissed;
|
||||
final Duration duration;
|
||||
|
||||
const _ToastWidget({
|
||||
required this.message,
|
||||
required this.iconData,
|
||||
required this.bgColor,
|
||||
required this.textColor,
|
||||
required this.borderColor,
|
||||
required this.onDismissed,
|
||||
required this.duration,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_ToastWidget> createState() => _ToastWidgetState();
|
||||
}
|
||||
|
||||
class _ToastWidgetState extends State<_ToastWidget> with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller;
|
||||
late final Animation<double> _fadeAnim;
|
||||
late final Animation<double> _scaleAnim;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
reverseDuration: const Duration(milliseconds: 200),
|
||||
);
|
||||
_fadeAnim = CurvedAnimation(parent: _controller, curve: Curves.easeOut);
|
||||
_scaleAnim = Tween<double>(begin: 0.88, end: 1.0).animate(
|
||||
CurvedAnimation(parent: _controller, curve: Curves.easeOutBack),
|
||||
);
|
||||
|
||||
_controller.forward();
|
||||
|
||||
Future.delayed(widget.duration, () {
|
||||
if (mounted) {
|
||||
_controller.reverse().then((_) {
|
||||
if (mounted) {
|
||||
widget.onDismissed();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
final viewInsetsBottom = mediaQuery.viewInsets.bottom;
|
||||
final paddingBottom = mediaQuery.padding.bottom;
|
||||
|
||||
// 动态适配视口:
|
||||
// 若系统键盘唤起(viewInsets.bottom > 0),则浮动于键盘与辅助小键盘上方(viewInsets.bottom + 72)
|
||||
// 若无键盘,则浮动于屏幕安全区上方(paddingBottom + 48)
|
||||
final bottomOffset = viewInsetsBottom > 0
|
||||
? viewInsetsBottom + 72.0
|
||||
: paddingBottom + 48.0;
|
||||
|
||||
return AnimatedPositioned(
|
||||
duration: const Duration(milliseconds: 250),
|
||||
curve: Curves.easeOutCubic,
|
||||
bottom: bottomOffset,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: IgnorePointer(
|
||||
child: FadeTransition(
|
||||
opacity: _fadeAnim,
|
||||
child: ScaleTransition(
|
||||
scale: _scaleAnim,
|
||||
child: Center(
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 24),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: widget.bgColor,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: widget.borderColor, width: 1),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black26,
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(widget.iconData, size: 18, color: widget.textColor),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
widget.message,
|
||||
style: TextStyle(
|
||||
color: widget.textColor,
|
||||
fontSize: 14.0,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:convert';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/app_font.dart';
|
||||
import 'package:code_editor/models/editor_theme.dart';
|
||||
import 'package:code_editor/models/virtual_keyboard_config.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
@@ -40,6 +41,7 @@ class SettingsView extends StatelessWidget {
|
||||
// ==============================
|
||||
_buildSectionHeader(context, l10n.appearanceSection),
|
||||
_buildThemeModeTile(context, provider, l10n),
|
||||
_buildUiFontTile(context, provider),
|
||||
|
||||
const Divider(height: 32, indent: 16, endIndent: 16),
|
||||
|
||||
@@ -49,6 +51,8 @@ class SettingsView extends StatelessWidget {
|
||||
_buildSectionHeader(context, l10n.editorSection),
|
||||
_buildEditorThemeTile(context, provider, l10n),
|
||||
_buildFontSizeTile(context, provider, l10n),
|
||||
_buildEditorFontTile(context, provider),
|
||||
_buildIndentSizeTile(context, provider, l10n),
|
||||
_buildWordWrapTile(context, provider, l10n),
|
||||
_buildVirtualKeyboardTile(context, provider, l10n),
|
||||
_buildVirtualKeyboardConfigTile(context, provider, l10n),
|
||||
@@ -56,7 +60,15 @@ class SettingsView extends StatelessWidget {
|
||||
const Divider(height: 32, indent: 16, endIndent: 16),
|
||||
|
||||
// ==============================
|
||||
// 3. 语言分组 (Language)
|
||||
// 3. 终端分组 (Terminal)
|
||||
// ==============================
|
||||
_buildSectionHeader(context, '终端'),
|
||||
_buildTerminalFontTile(context, provider),
|
||||
|
||||
const Divider(height: 32, indent: 16, endIndent: 16),
|
||||
|
||||
// ==============================
|
||||
// 4. 语言分组 (Language)
|
||||
// ==============================
|
||||
_buildSectionHeader(context, l10n.languageSection),
|
||||
_buildLanguageTile(context, provider, l10n),
|
||||
@@ -166,6 +178,151 @@ class SettingsView extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// 外观:UI 界面字体条目
|
||||
Widget _buildUiFontTile(BuildContext context, SettingsProvider provider) {
|
||||
final theme = Theme.of(context);
|
||||
final currentFont = provider.uiFont;
|
||||
return ListTile(
|
||||
leading: Icon(Icons.font_download_outlined, color: theme.colorScheme.primary),
|
||||
title: const Text('界面字体'),
|
||||
subtitle: Text(currentFont.name),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
_showFontSelector(
|
||||
context,
|
||||
title: '选择界面字体',
|
||||
fonts: AppFonts.uiFonts,
|
||||
currentId: provider.uiFontId,
|
||||
previewSample: '代码编辑器界面字体预览 Code Editor 123',
|
||||
onSelected: (id) => provider.setUiFontId(id),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 编辑区:代码字体条目
|
||||
Widget _buildEditorFontTile(BuildContext context, SettingsProvider provider) {
|
||||
final theme = Theme.of(context);
|
||||
final currentFont = provider.editorFont;
|
||||
return ListTile(
|
||||
leading: Icon(Icons.text_fields, color: theme.colorScheme.primary),
|
||||
title: const Text('代码字体'),
|
||||
subtitle: Text(currentFont.name),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
_showFontSelector(
|
||||
context,
|
||||
title: '选择代码字体',
|
||||
fonts: AppFonts.editorFonts,
|
||||
currentId: provider.editorFontId,
|
||||
previewSample: 'void main() { int a = 123; } // 代码预览',
|
||||
onSelected: (id) => provider.setEditorFontId(id),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 终端:终端字体条目
|
||||
Widget _buildTerminalFontTile(BuildContext context, SettingsProvider provider) {
|
||||
final theme = Theme.of(context);
|
||||
final currentFont = provider.terminalFont;
|
||||
return ListTile(
|
||||
leading: Icon(Icons.terminal, color: theme.colorScheme.primary),
|
||||
title: const Text('终端字体'),
|
||||
subtitle: Text(currentFont.name),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
_showFontSelector(
|
||||
context,
|
||||
title: '选择终端字体',
|
||||
fonts: AppFonts.terminalFonts,
|
||||
currentId: provider.terminalFontId,
|
||||
previewSample: '\$ git status -s # 终端字体预览',
|
||||
onSelected: (id) => provider.setTerminalFontId(id),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 字体选择底部弹窗
|
||||
void _showFontSelector(
|
||||
BuildContext context, {
|
||||
required String title,
|
||||
required List<AppFontItem> fonts,
|
||||
required String currentId,
|
||||
required ValueChanged<String> onSelected,
|
||||
required String previewSample,
|
||||
}) {
|
||||
showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (sheetContext) {
|
||||
final theme = Theme.of(context);
|
||||
return SafeArea(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(sheetContext).size.height * 0.65,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
title,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: fonts.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = fonts[index];
|
||||
final isSelected = item.id == currentId;
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
item.isMonospace ? Icons.code : Icons.font_download_outlined,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
),
|
||||
title: Text(
|
||||
item.name,
|
||||
style: TextStyle(
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
previewSample,
|
||||
style: TextStyle(
|
||||
fontFamily: item.fontFamily,
|
||||
fontFamilyFallback: item.fallback,
|
||||
fontSize: 12.0,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
trailing: isSelected
|
||||
? Icon(Icons.check, color: theme.colorScheme.primary)
|
||||
: null,
|
||||
onTap: () {
|
||||
onSelected(item.id);
|
||||
Navigator.of(sheetContext).pop();
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 编辑区:代码主题切换条目
|
||||
Widget _buildEditorThemeTile(
|
||||
BuildContext context,
|
||||
@@ -334,6 +491,70 @@ class SettingsView extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
/// 编辑区:缩进大小配置条目
|
||||
Widget _buildIndentSizeTile(
|
||||
BuildContext context,
|
||||
SettingsProvider provider,
|
||||
AppLocalizations l10n,
|
||||
) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return ListTile(
|
||||
leading: Icon(Icons.format_indent_increase, color: theme.colorScheme.primary),
|
||||
title: Text(l10n.indentSize),
|
||||
subtitle: Text(l10n.spacesCount(provider.indentSize)),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
_showIndentSizeSelector(context, provider, l10n);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showIndentSizeSelector(
|
||||
BuildContext context,
|
||||
SettingsProvider provider,
|
||||
AppLocalizations l10n,
|
||||
) {
|
||||
showModalBottomSheet<void>(
|
||||
context: context,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (sheetContext) {
|
||||
const options = [2, 4, 8];
|
||||
return SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
l10n.selectIndentSize,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
...options.map((count) {
|
||||
final isSelected = provider.indentSize == count;
|
||||
return ListTile(
|
||||
title: Text(l10n.spacesCount(count)),
|
||||
trailing: isSelected
|
||||
? Icon(Icons.check, color: Theme.of(context).colorScheme.primary)
|
||||
: null,
|
||||
selected: isSelected,
|
||||
onTap: () {
|
||||
provider.setIndentSize(count);
|
||||
Navigator.of(sheetContext).pop();
|
||||
},
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showFontSizeDialog(
|
||||
BuildContext context,
|
||||
SettingsProvider provider,
|
||||
@@ -595,7 +816,7 @@ class SettingsView extends StatelessWidget {
|
||||
} else {
|
||||
try {
|
||||
final decoded = jsonDecode(codeController.text);
|
||||
const encoder = JsonEncoder.withIndent(' ');
|
||||
final encoder = JsonEncoder.withIndent(' ' * provider.indentSize);
|
||||
setDialogState(() {
|
||||
codeController.text = encoder.convert(decoded);
|
||||
validationError = null;
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
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/terminal_drawer.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
/// 终端视图(支持全屏会话保持、右侧抽屉多会话管理与交互)
|
||||
class TerminalView extends StatefulWidget {
|
||||
const TerminalView({super.key});
|
||||
|
||||
@override
|
||||
State<TerminalView> createState() => _TerminalViewState();
|
||||
}
|
||||
|
||||
class _TerminalViewState extends State<TerminalView> {
|
||||
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 懒加载:进入终端 view 时,若无会话则自动创建首个会话
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) {
|
||||
context.read<TerminalProvider>().ensureInitialized();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final provider = context.watch<TerminalProvider>();
|
||||
final activeSession = provider.activeSession;
|
||||
final sessions = provider.sessions;
|
||||
final activeIndex = provider.activeIndex;
|
||||
|
||||
final titleText = activeSession?.name ?? '会话';
|
||||
const subtitleText = '终端';
|
||||
|
||||
return Scaffold(
|
||||
key: _scaffoldKey,
|
||||
appBar: AppBar(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
tooltip: '返回',
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
titleText,
|
||||
style: const TextStyle(
|
||||
fontSize: 16.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Text(
|
||||
subtitleText,
|
||||
style: TextStyle(
|
||||
fontSize: 11.0,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.format_list_bulleted),
|
||||
tooltip: '会话列表',
|
||||
onPressed: () {
|
||||
_scaffoldKey.currentState?.openEndDrawer();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
endDrawer: const TerminalDrawer(),
|
||||
body: sessions.isEmpty
|
||||
? const Center(
|
||||
child: Text(
|
||||
'暂无活跃会话',
|
||||
style: TextStyle(color: Colors.grey),
|
||||
),
|
||||
)
|
||||
: IndexedStack(
|
||||
index: (activeIndex >= 0 && activeIndex < sessions.length) ? activeIndex : 0,
|
||||
children: [
|
||||
for (final session in sessions)
|
||||
_TerminalSessionBody(
|
||||
key: ValueKey(session.id),
|
||||
session: session,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个终端会话的终端渲染与交互容器
|
||||
class _TerminalSessionBody extends StatefulWidget {
|
||||
final TerminalSession session;
|
||||
|
||||
const _TerminalSessionBody({
|
||||
super.key,
|
||||
required this.session,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_TerminalSessionBody> createState() => _TerminalSessionBodyState();
|
||||
}
|
||||
|
||||
class _TerminalSessionBodyState extends State<_TerminalSessionBody> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final session = widget.session;
|
||||
final settings = context.watch<SettingsProvider?>();
|
||||
final terminalFont = settings?.terminalFont ?? AppFonts.terminalMonospace;
|
||||
|
||||
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();
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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('一键初始化'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/views/terminal_view.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
final String? filePath;
|
||||
@@ -9,6 +11,7 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
final VoidCallback? onSave;
|
||||
final VoidCallback? onSaveAll;
|
||||
final VoidCallback? onRun;
|
||||
final VoidCallback? onTerminal;
|
||||
final VoidCallback? onCloseAllTabs;
|
||||
final VoidCallback? onCloseProject;
|
||||
final VoidCallback? onSettings;
|
||||
@@ -21,6 +24,7 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
this.onSave,
|
||||
this.onSaveAll,
|
||||
this.onRun,
|
||||
this.onTerminal,
|
||||
this.onCloseAllTabs,
|
||||
this.onCloseProject,
|
||||
this.onSettings,
|
||||
@@ -61,104 +65,322 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
subtitleText = null;
|
||||
}
|
||||
|
||||
return AppBar(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
titleText,
|
||||
style: const TextStyle(
|
||||
fontSize: 16.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (subtitleText != null)
|
||||
return CodeEditorTapRegion(
|
||||
child: AppBar(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
subtitleText,
|
||||
style: TextStyle(
|
||||
fontSize: 11.0,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
titleText,
|
||||
style: const TextStyle(
|
||||
fontSize: 16.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (subtitleText != null)
|
||||
Text(
|
||||
subtitleText,
|
||||
style: TextStyle(
|
||||
fontSize: 11.0,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
child: IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
tooltip: l10n.run,
|
||||
onPressed: onRun ?? () {},
|
||||
),
|
||||
),
|
||||
Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
child: IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.save_outlined),
|
||||
tooltip: l10n.save,
|
||||
onPressed: onSave ?? () {},
|
||||
),
|
||||
),
|
||||
Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
child: IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.terminal),
|
||||
tooltip: '终端',
|
||||
onPressed: onTerminal ??
|
||||
() {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (context) => const TerminalView(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
_MoreMenuButton(
|
||||
onSaveAll: onSaveAll,
|
||||
onCloseAllTabs: onCloseAllTabs,
|
||||
onCloseProject: onCloseProject,
|
||||
onSettings: onSettings,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
tooltip: l10n.run,
|
||||
onPressed: onRun ?? () {},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 基于 OverlayEntry 的右上角更多菜单组件(带对齐右上角缩放淡入淡出动画,非模态不关闭键盘)
|
||||
class _MoreMenuButton extends StatefulWidget {
|
||||
final VoidCallback? onSaveAll;
|
||||
final VoidCallback? onCloseAllTabs;
|
||||
final VoidCallback? onCloseProject;
|
||||
final VoidCallback? onSettings;
|
||||
|
||||
const _MoreMenuButton({
|
||||
this.onSaveAll,
|
||||
this.onCloseAllTabs,
|
||||
this.onCloseProject,
|
||||
this.onSettings,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_MoreMenuButton> createState() => _MoreMenuButtonState();
|
||||
}
|
||||
|
||||
class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _animController;
|
||||
late final Animation<double> _fadeAnimation;
|
||||
late final Animation<double> _scaleAnimation;
|
||||
OverlayEntry? _barrierEntry;
|
||||
OverlayEntry? _menuEntry;
|
||||
final GlobalKey _buttonKey = GlobalKey();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_animController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 150),
|
||||
reverseDuration: const Duration(milliseconds: 100),
|
||||
);
|
||||
_fadeAnimation = CurvedAnimation(
|
||||
parent: _animController,
|
||||
curve: Curves.easeOutCubic,
|
||||
reverseCurve: Curves.easeInCubic,
|
||||
);
|
||||
_scaleAnimation = Tween<double>(begin: 0.85, end: 1.0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _animController,
|
||||
curve: Curves.easeOutCubic,
|
||||
reverseCurve: Curves.easeInCubic,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_animController.dispose();
|
||||
_forceRemoveEntries();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _forceRemoveEntries() {
|
||||
if (_barrierEntry != null && _barrierEntry!.mounted) {
|
||||
_barrierEntry!.remove();
|
||||
}
|
||||
_barrierEntry = null;
|
||||
|
||||
if (_menuEntry != null && _menuEntry!.mounted) {
|
||||
_menuEntry!.remove();
|
||||
}
|
||||
_menuEntry = null;
|
||||
}
|
||||
|
||||
void _closeMenu({VoidCallback? onClosed}) async {
|
||||
if (_menuEntry == null) {
|
||||
onClosed?.call();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await _animController.reverse();
|
||||
} catch (_) {}
|
||||
if (mounted) {
|
||||
_forceRemoveEntries();
|
||||
onClosed?.call();
|
||||
}
|
||||
}
|
||||
|
||||
void _showMenu() {
|
||||
_forceRemoveEntries();
|
||||
|
||||
final overlay = Overlay.maybeOf(context, rootOverlay: true);
|
||||
if (overlay == null) return;
|
||||
|
||||
final renderBox = _buttonKey.currentContext?.findRenderObject() as RenderBox?;
|
||||
if (renderBox == null) return;
|
||||
|
||||
final size = renderBox.size;
|
||||
final offset = renderBox.localToGlobal(Offset.zero);
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final onSurfaceColor = theme.colorScheme.onSurface;
|
||||
|
||||
_barrierEntry = OverlayEntry(
|
||||
builder: (ctx) => Positioned.fill(
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.translucent,
|
||||
onTap: () => _closeMenu(),
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.save_outlined),
|
||||
tooltip: l10n.save,
|
||||
onPressed: onSave ?? () {},
|
||||
),
|
||||
PopupMenuButton<String>(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
tooltip: l10n.more,
|
||||
position: PopupMenuPosition.under,
|
||||
onSelected: (value) {
|
||||
if (value == 'save_all') {
|
||||
onSaveAll?.call();
|
||||
} else if (value == 'close_all_tabs') {
|
||||
onCloseAllTabs?.call();
|
||||
} else if (value == 'close_project') {
|
||||
onCloseProject?.call();
|
||||
} else if (value == 'settings') {
|
||||
onSettings?.call();
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem<String>(
|
||||
value: 'save_all',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.save_as_outlined, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(l10n.saveAll),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
_menuEntry = OverlayEntry(
|
||||
builder: (ctx) {
|
||||
return Positioned(
|
||||
top: offset.dy + size.height + 4,
|
||||
right: 8,
|
||||
child: FadeTransition(
|
||||
opacity: _fadeAnimation,
|
||||
child: ScaleTransition(
|
||||
scale: _scaleAnimation,
|
||||
alignment: Alignment.topRight,
|
||||
child: Material(
|
||||
color: theme.colorScheme.surface,
|
||||
surfaceTintColor: theme.colorScheme.surfaceTint,
|
||||
elevation: 6,
|
||||
shadowColor: Colors.black26,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: 1.0,
|
||||
),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Container(
|
||||
width: 170,
|
||||
padding: const EdgeInsets.symmetric(vertical: 4.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_buildMenuItem(
|
||||
icon: Icons.save_as_outlined,
|
||||
title: l10n.saveAll,
|
||||
iconColor: onSurfaceColor,
|
||||
onTap: () {
|
||||
_closeMenu(onClosed: widget.onSaveAll);
|
||||
},
|
||||
),
|
||||
_buildMenuItem(
|
||||
icon: Icons.close_fullscreen_outlined,
|
||||
title: l10n.closeAllTabs,
|
||||
iconColor: onSurfaceColor,
|
||||
onTap: () {
|
||||
_closeMenu(onClosed: widget.onCloseAllTabs);
|
||||
},
|
||||
),
|
||||
Divider(
|
||||
height: 9,
|
||||
thickness: 0.8,
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
),
|
||||
_buildMenuItem(
|
||||
icon: Icons.folder_off_outlined,
|
||||
title: l10n.closeProject,
|
||||
iconColor: onSurfaceColor,
|
||||
onTap: () {
|
||||
_closeMenu(onClosed: widget.onCloseProject);
|
||||
},
|
||||
),
|
||||
Divider(
|
||||
height: 9,
|
||||
thickness: 0.8,
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
),
|
||||
_buildMenuItem(
|
||||
icon: Icons.settings,
|
||||
title: l10n.settings,
|
||||
iconColor: onSurfaceColor,
|
||||
onTap: () {
|
||||
_closeMenu(onClosed: widget.onSettings);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
PopupMenuItem<String>(
|
||||
value: 'close_all_tabs',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.close_fullscreen_outlined, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(l10n.closeAllTabs),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
overlay.insertAll([_barrierEntry!, _menuEntry!]);
|
||||
_animController.forward(from: 0.0);
|
||||
}
|
||||
|
||||
Widget _buildMenuItem({
|
||||
required IconData icon,
|
||||
required String title,
|
||||
required Color iconColor,
|
||||
required VoidCallback onTap,
|
||||
bool isDestructive = false,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: 18,
|
||||
color: isDestructive ? theme.colorScheme.error : iconColor,
|
||||
),
|
||||
PopupMenuItem<String>(
|
||||
value: 'close_project',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.folder_off_outlined, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(l10n.closeProject),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem<String>(
|
||||
value: 'settings',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.settings, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(l10n.settings),
|
||||
],
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontSize: 14.0,
|
||||
color: isDestructive ? theme.colorScheme.error : theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
child: IconButton(
|
||||
key: _buttonKey,
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.more_vert),
|
||||
tooltip: l10n.more,
|
||||
onPressed: _showMenu,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:code_editor/services/permission_service.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:code_editor/widgets/project_history_widget.dart';
|
||||
import 'package:code_editor/widgets/file_tree_widget.dart';
|
||||
@@ -11,15 +12,27 @@ import 'package:provider/provider.dart';
|
||||
class CodeEditorDrawer extends StatelessWidget {
|
||||
const CodeEditorDrawer({super.key});
|
||||
|
||||
static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) {
|
||||
return listen ? context.watch<ProjectProvider>() : context.read<ProjectProvider>();
|
||||
static ProjectProvider _getProjectProvider(
|
||||
BuildContext context, {
|
||||
bool listen = false,
|
||||
}) {
|
||||
return listen
|
||||
? context.watch<ProjectProvider>()
|
||||
: context.read<ProjectProvider>();
|
||||
}
|
||||
|
||||
static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) {
|
||||
static TabProvider _getTabProvider(
|
||||
BuildContext context, {
|
||||
bool listen = false,
|
||||
}) {
|
||||
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
|
||||
}
|
||||
|
||||
Future<void> _handleNewFile(BuildContext context, String rootPath) async {
|
||||
final hasPermission = await PermissionService.instance
|
||||
.ensureStoragePermission(context: context);
|
||||
if (!hasPermission || !context.mounted) return;
|
||||
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final name = await DialogUtils.showInputDialog(
|
||||
context,
|
||||
@@ -35,13 +48,20 @@ class CodeEditorDrawer extends StatelessWidget {
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
DialogUtils.showErrorToast(context, l10n?.createFileFailed(e.toString()) ?? '创建文件失败: $e');
|
||||
DialogUtils.showErrorToast(
|
||||
context,
|
||||
l10n?.createFileFailed(e.toString()) ?? '创建文件失败: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handleNewFolder(BuildContext context, String rootPath) async {
|
||||
final hasPermission = await PermissionService.instance
|
||||
.ensureStoragePermission(context: context);
|
||||
if (!hasPermission || !context.mounted) return;
|
||||
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final name = await DialogUtils.showInputDialog(
|
||||
context,
|
||||
@@ -50,10 +70,15 @@ class CodeEditorDrawer extends StatelessWidget {
|
||||
);
|
||||
if (name != null && name.trim().isNotEmpty && context.mounted) {
|
||||
try {
|
||||
await _getProjectProvider(context).createDirectory(rootPath, name.trim());
|
||||
await _getProjectProvider(
|
||||
context,
|
||||
).createDirectory(rootPath, name.trim());
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
DialogUtils.showErrorToast(context, l10n?.createFolderFailed(e.toString()) ?? '创建文件夹失败: $e');
|
||||
DialogUtils.showErrorToast(
|
||||
context,
|
||||
l10n?.createFolderFailed(e.toString()) ?? '创建文件夹失败: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,101 +93,120 @@ class CodeEditorDrawer extends StatelessWidget {
|
||||
final hasProject = rootPath != null && rootPath.trim().isNotEmpty;
|
||||
|
||||
return Drawer(
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
l10n.fileDirectory,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh),
|
||||
tooltip: l10n.refreshDirectory,
|
||||
onPressed: () => _getProjectProvider(context).refreshTree(),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.folder_open),
|
||||
tooltip: l10n.openFileDirectory,
|
||||
onPressed: () async {
|
||||
final canProceed = await _getTabProvider(context).checkUnsavedChanges(context);
|
||||
if (!canProceed || !context.mounted) return;
|
||||
_getProjectProvider(context).openDirectory();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: l10n.viewProjectHistory,
|
||||
onPressed: () {
|
||||
ProjectHistoryWidget.show(
|
||||
context,
|
||||
onSelectHistory: (selectedHistory) async {
|
||||
final canProceed = await _getTabProvider(context).checkUnsavedChanges(context);
|
||||
if (!canProceed || !context.mounted) return;
|
||||
_getProjectProvider(context).switchProject(selectedHistory);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
rootPath ?? '',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer,
|
||||
),
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
l10n.fileDirectory,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
if (hasProject) ...[
|
||||
const SizedBox(width: 8),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 18,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
|
||||
icon: const Icon(Icons.note_add_outlined),
|
||||
tooltip: l10n.newFile,
|
||||
onPressed: () => _handleNewFile(context, rootPath),
|
||||
icon: const Icon(Icons.refresh),
|
||||
tooltip: l10n.refreshDirectory,
|
||||
onPressed: () =>
|
||||
_getProjectProvider(context).refreshTree(),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 18,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
|
||||
icon: const Icon(Icons.create_new_folder_outlined),
|
||||
tooltip: l10n.newFolder,
|
||||
onPressed: () => _handleNewFolder(context, rootPath),
|
||||
icon: const Icon(Icons.folder_open),
|
||||
tooltip: l10n.openFileDirectory,
|
||||
onPressed: () async {
|
||||
final hasPermission = await PermissionService
|
||||
.instance
|
||||
.ensureStoragePermission(context: context);
|
||||
if (!hasPermission || !context.mounted) return;
|
||||
final canProceed = await _getTabProvider(
|
||||
context,
|
||||
).checkUnsavedChanges(context);
|
||||
if (!canProceed || !context.mounted) return;
|
||||
_getProjectProvider(context).openDirectory();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: l10n.viewProjectHistory,
|
||||
onPressed: () {
|
||||
ProjectHistoryWidget.show(
|
||||
context,
|
||||
onSelectHistory: (selectedHistory) async {
|
||||
final canProceed = await _getTabProvider(
|
||||
context,
|
||||
).checkUnsavedChanges(context);
|
||||
if (!canProceed || !context.mounted) return;
|
||||
_getProjectProvider(
|
||||
context,
|
||||
).switchProject(selectedHistory);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
rootPath ?? '',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
if (hasProject) ...[
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 18,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 28,
|
||||
minHeight: 28,
|
||||
),
|
||||
icon: const Icon(Icons.note_add_outlined),
|
||||
tooltip: l10n.newFile,
|
||||
onPressed: () => _handleNewFile(context, rootPath),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 18,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 28,
|
||||
minHeight: 28,
|
||||
),
|
||||
icon: const Icon(Icons.create_new_folder_outlined),
|
||||
tooltip: l10n.newFolder,
|
||||
onPressed: () =>
|
||||
_handleNewFolder(context, rootPath),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const Expanded(
|
||||
child: FileTreeWidget(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Expanded(child: SafeArea(top: false, child: FileTreeWidget())),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
/// 桌面端与移动端代码编辑器的浮动/右键菜单项组件
|
||||
/// 桌面端代码编辑器的右键菜单项组件
|
||||
class _EditorContextMenuItem extends PopupMenuItem<void> implements PreferredSizeWidget {
|
||||
_EditorContextMenuItem({
|
||||
required String text,
|
||||
@@ -26,13 +26,126 @@ class _EditorContextMenuItem extends PopupMenuItem<void> implements PreferredSiz
|
||||
Size get preferredSize => const Size(140, 36);
|
||||
}
|
||||
|
||||
/// 移动端选区悬浮工具栏(基于 OverlayEntry,绝不压入 Route,软键盘保持弹起)
|
||||
class _MobileSelectionToolbarWidget extends StatefulWidget {
|
||||
final TextSelectionToolbarAnchors anchors;
|
||||
final CodeLineEditingController controller;
|
||||
final VoidCallback onDismiss;
|
||||
final FocusNode? focusNode;
|
||||
|
||||
const _MobileSelectionToolbarWidget({
|
||||
required this.anchors,
|
||||
required this.controller,
|
||||
required this.onDismiss,
|
||||
this.focusNode,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_MobileSelectionToolbarWidget> createState() => _MobileSelectionToolbarWidgetState();
|
||||
}
|
||||
|
||||
class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWidget> {
|
||||
bool _canPaste = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_checkClipboard();
|
||||
}
|
||||
|
||||
Future<void> _checkClipboard() async {
|
||||
try {
|
||||
final hasStrings = await Clipboard.hasStrings();
|
||||
if (mounted && !hasStrings) {
|
||||
setState(() {
|
||||
_canPaste = false;
|
||||
});
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final hasSelection = widget.controller.selection.baseOffset != -1 &&
|
||||
widget.controller.selection.extentOffset != -1 &&
|
||||
!widget.controller.selection.isCollapsed;
|
||||
|
||||
return AdaptiveTextSelectionToolbar.buttonItems(
|
||||
anchors: widget.anchors,
|
||||
buttonItems: [
|
||||
if (hasSelection)
|
||||
ContextMenuButtonItem(
|
||||
label: l10n?.cut ?? '剪切',
|
||||
type: ContextMenuButtonType.cut,
|
||||
onPressed: () {
|
||||
widget.controller.cut();
|
||||
widget.onDismiss();
|
||||
widget.focusNode?.requestFocus();
|
||||
},
|
||||
),
|
||||
if (hasSelection)
|
||||
ContextMenuButtonItem(
|
||||
label: l10n?.copy ?? '复制',
|
||||
type: ContextMenuButtonType.copy,
|
||||
onPressed: () {
|
||||
widget.controller.copy();
|
||||
widget.onDismiss();
|
||||
widget.focusNode?.requestFocus();
|
||||
},
|
||||
),
|
||||
if (_canPaste)
|
||||
ContextMenuButtonItem(
|
||||
label: l10n?.paste ?? '粘贴',
|
||||
type: ContextMenuButtonType.paste,
|
||||
onPressed: () {
|
||||
widget.controller.paste();
|
||||
widget.onDismiss();
|
||||
widget.focusNode?.requestFocus();
|
||||
},
|
||||
),
|
||||
if (!widget.controller.isEmpty)
|
||||
ContextMenuButtonItem(
|
||||
label: l10n?.selectAll ?? '全选',
|
||||
type: ContextMenuButtonType.selectAll,
|
||||
onPressed: () {
|
||||
widget.controller.selectAll();
|
||||
widget.onDismiss();
|
||||
widget.focusNode?.requestFocus();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 自定义代码编辑器选区与右键菜单控制器
|
||||
class CodeEditorToolbarController implements SelectionToolbarController {
|
||||
const CodeEditorToolbarController();
|
||||
final FocusNode? focusNode;
|
||||
late final SelectionToolbarController _mobileController;
|
||||
|
||||
CodeEditorToolbarController({this.focusNode}) {
|
||||
_mobileController = MobileSelectionToolbarController(
|
||||
builder: ({
|
||||
required BuildContext context,
|
||||
required TextSelectionToolbarAnchors anchors,
|
||||
required CodeLineEditingController controller,
|
||||
required VoidCallback onDismiss,
|
||||
required VoidCallback onRefresh,
|
||||
}) {
|
||||
return _MobileSelectionToolbarWidget(
|
||||
anchors: anchors,
|
||||
controller: controller,
|
||||
onDismiss: onDismiss,
|
||||
focusNode: focusNode,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void hide(BuildContext context) {
|
||||
// 菜单由 showMenu / 遮罩自动关闭,不需要额外动作
|
||||
_mobileController.hide(context);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -43,6 +156,29 @@ class CodeEditorToolbarController implements SelectionToolbarController {
|
||||
Rect? renderRect,
|
||||
required LayerLink layerLink,
|
||||
required ValueNotifier<bool> visibility,
|
||||
}) {
|
||||
if (renderRect == null) {
|
||||
_showDesktopMenu(
|
||||
context: context,
|
||||
controller: controller,
|
||||
anchors: anchors,
|
||||
);
|
||||
} else {
|
||||
_mobileController.show(
|
||||
context: context,
|
||||
controller: controller,
|
||||
anchors: anchors,
|
||||
renderRect: renderRect,
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showDesktopMenu({
|
||||
required BuildContext context,
|
||||
required CodeLineEditingController controller,
|
||||
required TextSelectionToolbarAnchors anchors,
|
||||
}) async {
|
||||
final hasSelection = controller.selection.baseOffset != -1 &&
|
||||
controller.selection.extentOffset != -1 &&
|
||||
@@ -110,5 +246,9 @@ class CodeEditorToolbarController implements SelectionToolbarController {
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
if (focusNode != null && !focusNode!.hasFocus) {
|
||||
focusNode!.requestFocus();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
class CodeEditorTabBar extends StatelessWidget {
|
||||
const CodeEditorTabBar({super.key});
|
||||
@@ -64,9 +65,10 @@ class CodeEditorTabBar extends StatelessWidget {
|
||||
final activePath = tabProvider.currentFilePath;
|
||||
final rootPath = projectProvider?.rootPath;
|
||||
|
||||
return Container(
|
||||
height: 36.0,
|
||||
width: double.infinity,
|
||||
return CodeEditorTapRegion(
|
||||
child: Container(
|
||||
height: 36.0,
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.2),
|
||||
border: Border(
|
||||
@@ -120,7 +122,8 @@ class CodeEditorTabBar extends StatelessWidget {
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTabItem(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/app_font.dart';
|
||||
import 'package:code_editor/models/editor_tab_item.dart';
|
||||
import 'package:code_editor/models/editor_theme.dart';
|
||||
import 'package:code_editor/models/virtual_keyboard_config.dart';
|
||||
@@ -41,10 +42,13 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
|
||||
CodeLineEditingController? _controller;
|
||||
CodeScrollController? _scrollController;
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
late final CodeEditorToolbarController _toolbarController;
|
||||
bool _isLoading = false;
|
||||
int _currentLoadVersion = 0;
|
||||
String? _errorMessage;
|
||||
String? _currentLoadedPath;
|
||||
int? _currentIndentSize;
|
||||
bool _isShowingConflictDialog = false;
|
||||
|
||||
EditorTabItem? _getCurrentTab() {
|
||||
@@ -121,6 +125,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_toolbarController = CodeEditorToolbarController(focusNode: _focusNode);
|
||||
_loadFileContent();
|
||||
}
|
||||
|
||||
@@ -151,6 +156,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
try {
|
||||
_getTabProvider(context).registerSaveHandler(null);
|
||||
} catch (_) {}
|
||||
_toolbarController.hide(context);
|
||||
final currentTab = _getCurrentTab();
|
||||
_saveCurrentTabScrollState(currentTab);
|
||||
_scrollController?.verticalScroller.dispose();
|
||||
@@ -158,6 +164,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
_scrollController?.dispose();
|
||||
_controller?.removeListener(_onTextChanged);
|
||||
_controller?.dispose();
|
||||
_focusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -341,6 +348,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
bool activeWordWrap = true;
|
||||
bool enableVirtualKeyboard = false;
|
||||
VirtualKeyboardConfig? keyboardConfig;
|
||||
AppFontItem activeEditorFont = AppFonts.editorMonospace;
|
||||
try {
|
||||
final settings = _getSettingsProvider(context, listen: true);
|
||||
activeTheme = settings.editorTheme;
|
||||
@@ -348,6 +356,12 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
activeWordWrap = settings.wordWrap;
|
||||
enableVirtualKeyboard = settings.enableVirtualKeyboard;
|
||||
keyboardConfig = settings.virtualKeyboardConfig;
|
||||
activeEditorFont = settings.editorFont;
|
||||
if (_currentIndentSize != null && _currentIndentSize != settings.indentSize) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _loadFileContent();
|
||||
});
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
return Container(
|
||||
@@ -360,9 +374,10 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
child: CodeEditor(
|
||||
key: ValueKey(_currentLoadedPath),
|
||||
controller: controller,
|
||||
focusNode: _focusNode,
|
||||
scrollController: _scrollController,
|
||||
wordWrap: activeWordWrap,
|
||||
toolbarController: const CodeEditorToolbarController(),
|
||||
toolbarController: _toolbarController,
|
||||
style: CodeEditorStyle(
|
||||
fontSize: activeFontSize,
|
||||
textColor: activeTheme.textColor,
|
||||
@@ -370,7 +385,8 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
cursorColor: activeTheme.cursorColor,
|
||||
cursorLineColor: activeTheme.cursorLineColor,
|
||||
selectionColor: activeTheme.selectionColor,
|
||||
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
|
||||
fontFamily: activeEditorFont.fontFamily,
|
||||
fontFamilyFallback: activeEditorFont.fallback,
|
||||
codeTheme: CodeHighlightTheme(
|
||||
languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath),
|
||||
theme: activeTheme.highlightTheme,
|
||||
@@ -385,13 +401,15 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
textStyle: TextStyle(
|
||||
color: activeTheme.gutterTextColor,
|
||||
fontSize: (activeFontSize - 1).clamp(9.0, 30.0),
|
||||
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
|
||||
fontFamily: activeEditorFont.fontFamily,
|
||||
fontFamilyFallback: activeEditorFont.fallback,
|
||||
),
|
||||
focusedTextStyle: TextStyle(
|
||||
color: activeTheme.focusedGutterTextColor,
|
||||
fontSize: (activeFontSize - 1).clamp(9.0, 30.0),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
|
||||
fontFamily: activeEditorFont.fontFamily,
|
||||
fontFamilyFallback: activeEditorFont.fallback,
|
||||
),
|
||||
),
|
||||
DefaultCodeChunkIndicator(
|
||||
@@ -410,6 +428,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
if (enableVirtualKeyboard && keyboardConfig != null)
|
||||
VirtualKeyboardWidget(
|
||||
controller: controller,
|
||||
focusNode: _focusNode,
|
||||
config: keyboardConfig,
|
||||
),
|
||||
],
|
||||
@@ -449,7 +468,15 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
? filePath
|
||||
: p.join(rootPath, filePath);
|
||||
|
||||
if (_currentLoadedPath != null && p.equals(_currentLoadedPath!, fullFilePath) && _controller != null) {
|
||||
int activeIndentSize = 2;
|
||||
try {
|
||||
activeIndentSize = _getSettingsProvider(context).indentSize;
|
||||
} catch (_) {}
|
||||
|
||||
if (_currentLoadedPath != null &&
|
||||
p.equals(_currentLoadedPath!, fullFilePath) &&
|
||||
_controller != null &&
|
||||
_currentIndentSize == activeIndentSize) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -467,10 +494,14 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
tab.content = normalizedContent;
|
||||
tab.originalContent = normalizedOriginal;
|
||||
|
||||
final newController = CodeLineEditingController.fromText(normalizedContent);
|
||||
final newController = CodeLineEditingController.fromText(
|
||||
normalizedContent,
|
||||
CodeLineOptions(indentSize: activeIndentSize),
|
||||
);
|
||||
|
||||
_controller = newController;
|
||||
_currentLoadedPath = fullFilePath;
|
||||
_currentIndentSize = activeIndentSize;
|
||||
_errorMessage = null;
|
||||
_isLoading = false;
|
||||
|
||||
@@ -514,10 +545,14 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
final oldController = _controller;
|
||||
oldController?.removeListener(_onTextChanged);
|
||||
|
||||
final newController = CodeLineEditingController.fromText(diskContent);
|
||||
final newController = CodeLineEditingController.fromText(
|
||||
diskContent,
|
||||
CodeLineOptions(indentSize: activeIndentSize),
|
||||
);
|
||||
|
||||
_controller = newController;
|
||||
_currentLoadedPath = fullFilePath;
|
||||
_currentIndentSize = activeIndentSize;
|
||||
_errorMessage = null;
|
||||
|
||||
if (tab != null) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:code_editor/services/permission_service.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -303,6 +304,12 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
final provider = _getProjectProvider(context);
|
||||
final l10n = AppLocalizations.of(context);
|
||||
|
||||
// 对于文件变动类操作,先校验并确保已获取存储访问权限
|
||||
if (['new_file', 'new_folder', 'paste', 'rename', 'delete'].contains(action)) {
|
||||
final hasPermission = await PermissionService.instance.ensureStoragePermission(context: context);
|
||||
if (!hasPermission || !mounted) return;
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case 'new_file':
|
||||
final name = await DialogUtils.showInputDialog(
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'package:code_editor/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/widgets/terminal_session_item_widget.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
/// 终端右侧抽屉(会话列表与管理)
|
||||
class TerminalDrawer extends StatelessWidget {
|
||||
const TerminalDrawer({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final provider = context.watch<TerminalProvider>();
|
||||
final sessions = provider.sessions;
|
||||
final activeIndex = provider.activeIndex;
|
||||
|
||||
return Drawer(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// 抽屉头部:使用与文件树一致的 primaryContainer 背景色并沉浸延伸至顶部状态栏
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primaryContainer,
|
||||
),
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 16.0, right: 8.0, top: 4.0, bottom: 4.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'会话',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
tooltip: '添加终端',
|
||||
onPressed: () {
|
||||
// 直接添加终端,但不跳转
|
||||
provider.createSession(name: '会话', distroId: 'alpine', activate: false);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
// 终端项目列表
|
||||
Expanded(
|
||||
child: sessions.isEmpty
|
||||
? Center(
|
||||
child: Text(
|
||||
'暂无会话,请点击右上角添加',
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
fontSize: 13.0,
|
||||
),
|
||||
),
|
||||
)
|
||||
: ReorderableListView.builder(
|
||||
buildDefaultDragHandles: false,
|
||||
padding: const EdgeInsets.symmetric(vertical: 4.0),
|
||||
itemCount: sessions.length,
|
||||
onReorderItem: (oldIndex, newIndex) {
|
||||
provider.reorderSessions(oldIndex, newIndex);
|
||||
},
|
||||
itemBuilder: (context, index) {
|
||||
final session = sessions[index];
|
||||
return TerminalSessionItemWidget(
|
||||
key: ValueKey(session.id),
|
||||
session: session,
|
||||
index: index,
|
||||
isSelected: index == activeIndex,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import 'package:code_editor/models/terminal_session.dart';
|
||||
import 'package:code_editor/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
/// 独立的终端项目组件
|
||||
class TerminalSessionItemWidget extends StatelessWidget {
|
||||
final TerminalSession session;
|
||||
final int index;
|
||||
final bool isSelected;
|
||||
|
||||
const TerminalSessionItemWidget({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.index,
|
||||
required this.isSelected,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final displayIndex = index + 1; // 索引从 1 开始
|
||||
final titleText = '($displayIndex) ${session.name}';
|
||||
final isHost = session.distroId == 'host';
|
||||
final badgeLabel = isHost ? 'Host' : 'Alpine';
|
||||
|
||||
final textStyle = theme.textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
|
||||
color: isSelected ? theme.colorScheme.primary : null,
|
||||
);
|
||||
|
||||
final iconColor = isSelected ? theme.colorScheme.primary : null;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: GestureDetector(
|
||||
onLongPressStart: (details) {
|
||||
_showContextMenu(context, details.globalPosition, displayIndex);
|
||||
},
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 0.0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
selected: isSelected,
|
||||
selectedTileColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.5),
|
||||
leading: Icon(
|
||||
Icons.terminal,
|
||||
size: 20,
|
||||
color: iconColor,
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
titleText,
|
||||
style: textStyle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 1.5),
|
||||
decoration: BoxDecoration(
|
||||
color: isHost
|
||||
? theme.colorScheme.surfaceContainerHighest
|
||||
: theme.colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(4.0),
|
||||
),
|
||||
child: Text(
|
||||
badgeLabel,
|
||||
style: TextStyle(
|
||||
fontSize: 10.0,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isHost
|
||||
? theme.colorScheme.onSurfaceVariant
|
||||
: theme.colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
trailing: ReorderableDragStartListener(
|
||||
index: index,
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.grab,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 8.0),
|
||||
child: Icon(
|
||||
Icons.drag_handle,
|
||||
size: 20,
|
||||
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
dense: true,
|
||||
onTap: () {
|
||||
final provider = context.read<TerminalProvider>();
|
||||
provider.selectSession(index);
|
||||
final scaffold = Scaffold.maybeOf(context);
|
||||
if (scaffold != null && scaffold.isEndDrawerOpen) {
|
||||
scaffold.closeEndDrawer();
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 长按弹出菜单(样式与文件树长按菜单完全对齐)
|
||||
void _showContextMenu(BuildContext context, Offset tapPosition, int displayIndex) async {
|
||||
final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
|
||||
final position = RelativeRect.fromRect(
|
||||
Rect.fromLTWH(tapPosition.dx, tapPosition.dy, 0, 0),
|
||||
Offset.zero & overlay.size,
|
||||
);
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final onSurfaceColor = theme.colorScheme.onSurface;
|
||||
|
||||
final selectedAction = await showMenu<String>(
|
||||
context: context,
|
||||
position: position,
|
||||
color: theme.colorScheme.surface,
|
||||
surfaceTintColor: theme.colorScheme.surfaceTint,
|
||||
elevation: 6,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: 1.0,
|
||||
),
|
||||
),
|
||||
items: [
|
||||
_buildMenuItem(
|
||||
value: 'rename',
|
||||
icon: Icons.edit_outlined,
|
||||
title: '重命名',
|
||||
color: onSurfaceColor,
|
||||
),
|
||||
const PopupMenuDivider(),
|
||||
_buildMenuItem(
|
||||
value: 'delete',
|
||||
icon: Icons.delete_outline,
|
||||
title: '删除',
|
||||
color: theme.colorScheme.error,
|
||||
isDestructive: true,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
if (selectedAction != null && context.mounted) {
|
||||
_handleMenuAction(context, selectedAction, displayIndex);
|
||||
}
|
||||
}
|
||||
|
||||
PopupMenuItem<String> _buildMenuItem({
|
||||
required String value,
|
||||
required IconData icon,
|
||||
required String title,
|
||||
required Color color,
|
||||
bool isDestructive = false,
|
||||
}) {
|
||||
return PopupMenuItem<String>(
|
||||
value: value,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 18, color: color),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(color: color),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _handleMenuAction(BuildContext context, String action, int displayIndex) async {
|
||||
final provider = context.read<TerminalProvider>();
|
||||
|
||||
switch (action) {
|
||||
case 'rename':
|
||||
final newName = await DialogUtils.showInputDialog(
|
||||
context,
|
||||
title: '重命名',
|
||||
hintText: '新名称',
|
||||
initialValue: session.name,
|
||||
);
|
||||
if (newName != null && newName.trim().isNotEmpty && newName.trim() != session.name) {
|
||||
provider.renameSession(session.id, newName.trim());
|
||||
}
|
||||
break;
|
||||
|
||||
case 'delete':
|
||||
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
|
||||
context,
|
||||
title: '确认删除',
|
||||
message: '确定要删除终端 "($displayIndex) ${session.name}" 吗?',
|
||||
);
|
||||
if (confirmed && context.mounted) {
|
||||
provider.removeSession(session.id);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,14 @@ import 'package:re_editor/re_editor.dart';
|
||||
/// 编辑器下方的虚拟辅助小键盘组件
|
||||
class VirtualKeyboardWidget extends StatefulWidget {
|
||||
final CodeLineEditingController? controller;
|
||||
final FocusNode? focusNode;
|
||||
final VirtualKeyboardConfig config;
|
||||
final Color? backgroundColor;
|
||||
|
||||
const VirtualKeyboardWidget({
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.focusNode,
|
||||
required this.config,
|
||||
this.backgroundColor,
|
||||
});
|
||||
@@ -43,6 +45,11 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget> {
|
||||
// 轻微触觉反馈提升敲击手感
|
||||
HapticFeedback.lightImpact();
|
||||
|
||||
// 如果提供了 focusNode 且当前未聚焦,或者为了确保软键盘不掉,请求聚焦
|
||||
if (widget.focusNode != null && !widget.focusNode!.hasFocus) {
|
||||
widget.focusNode!.requestFocus();
|
||||
}
|
||||
|
||||
switch (keyItem.action) {
|
||||
case 'command':
|
||||
_handleCommand(controller, keyItem.value);
|
||||
@@ -160,6 +167,11 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget> {
|
||||
case 'select_all':
|
||||
controller.selectAll();
|
||||
break;
|
||||
case 'keyboard_hide':
|
||||
case 'hide_keyboard':
|
||||
widget.focusNode?.unfocus();
|
||||
SystemChannels.textInput.invokeMethod('TextInput.hide');
|
||||
break;
|
||||
default:
|
||||
// 未知命令安全降级为直接输入其命令名称或原文本
|
||||
controller.replaceSelection(command);
|
||||
@@ -181,35 +193,37 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget> {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
border: Border(
|
||||
top: BorderSide(color: borderColor, width: 0.8),
|
||||
return CodeEditorTapRegion(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
border: Border(
|
||||
top: BorderSide(color: borderColor, width: 0.8),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 84, // 两行按键的高度
|
||||
child: PageView.builder(
|
||||
controller: _pageController,
|
||||
itemCount: pages.length,
|
||||
onPageChanged: (idx) {
|
||||
setState(() {
|
||||
_currentPage = idx;
|
||||
});
|
||||
},
|
||||
itemBuilder: (context, pageIndex) {
|
||||
return _buildPage(pages[pageIndex], isDark);
|
||||
},
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 84, // 两行按键的高度
|
||||
child: PageView.builder(
|
||||
controller: _pageController,
|
||||
itemCount: pages.length,
|
||||
onPageChanged: (idx) {
|
||||
setState(() {
|
||||
_currentPage = idx;
|
||||
});
|
||||
},
|
||||
itemBuilder: (context, pageIndex) {
|
||||
return _buildPage(pages[pageIndex], isDark);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
if (pages.length > 1) _buildPageIndicator(pages.length, theme),
|
||||
],
|
||||
if (pages.length > 1) _buildPageIndicator(pages.length, theme),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user