diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6db5a63..de7caf2 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,8 +1,16 @@ + + + + + + + + android:icon="@mipmap/ic_launcher" + android:requestLegacyExternalStorage="true"> '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'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 989d57a..7f24745 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -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 => '去设置'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 9bcf7cb..3eeae4a 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -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": "去设置" } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index d73f865..0c6021d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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( 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(), ); diff --git a/lib/models/app_font.dart b/lib/models/app_font.dart new file mode 100644 index 0000000..fe6f793 --- /dev/null +++ b/lib/models/app_font.dart @@ -0,0 +1,250 @@ +/// 字体定义与预设常量 +class AppFontItem { + final String id; + final String name; + final String? fontFamily; + final List 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 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 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 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, + ); + } +} diff --git a/lib/models/distro_info.dart b/lib/models/distro_info.dart new file mode 100644 index 0000000..a1a3e26 --- /dev/null +++ b/lib/models/distro_info.dart @@ -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 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 defaults = [ + alpine, + debian, + ubuntu, + host, + ]; + + DistroInfo copyWith({ + String? id, + String? name, + String? version, + String? description, + String? defaultShell, + String? packageManager, + List? 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 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 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?) + ?.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', + ); + } +} diff --git a/lib/models/terminal_session.dart b/lib/models/terminal_session.dart new file mode 100644 index 0000000..5ac551d --- /dev/null +++ b/lib/models/terminal_session.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +/// 单个终端会话的数据与状态模型 +class TerminalSession { + final String id; + String name; + final String distroId; + final DateTime createdAt; + final List outputLines; + final TextEditingController inputController; + final ScrollController scrollController; + final FocusNode focusNode; + + TerminalSession({ + required this.id, + this.name = '会话', + this.distroId = 'alpine', + DateTime? createdAt, + List? initialOutput, + }) : createdAt = createdAt ?? DateTime.now(), + outputLines = initialOutput ?? [], + 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(); + } +} diff --git a/lib/providers/distro_provider.dart b/lib/providers/distro_provider.dart new file mode 100644 index 0000000..b2c2b52 --- /dev/null +++ b/lib/providers/distro_provider.dart @@ -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 _statuses = {}; + + /// 安装进度 (0.0 ~ 1.0) + final Map _progress = {}; + + /// 状态描述文字(如 "正在解压... 45%") + final Map _statusMessages = {}; + + /// 默认创建会话使用的发行版 ID + String _defaultDistroId = 'alpine'; + + String get defaultDistroId => _defaultDistroId; + + List 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 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 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 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(); + } + } +} diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart index fd5e84f..bf72682 100644 --- a/lib/providers/settings_provider.dart +++ b/lib/providers/settings_provider.dart @@ -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 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 setWordWrap(bool wrap) async { if(_wordWrap == wrap) return; _wordWrap = wrap; @@ -190,4 +243,34 @@ class SettingsProvider extends ChangeNotifier { } }catch (_) {} } + + Future setUiFontId(String fontId) async { + if (_uiFontId == fontId) return; + _uiFontId = fontId; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyUiFont, fontId); + } catch (_) {} + } + + Future setEditorFontId(String fontId) async { + if (_editorFontId == fontId) return; + _editorFontId = fontId; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyEditorFont, fontId); + } catch (_) {} + } + + Future setTerminalFontId(String fontId) async { + if (_terminalFontId == fontId) return; + _terminalFontId = fontId; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyTerminalFont, fontId); + } catch (_) {} + } } diff --git a/lib/providers/terminal_provider.dart b/lib/providers/terminal_provider.dart new file mode 100644 index 0000000..0ba394e --- /dev/null +++ b/lib/providers/terminal_provider.dart @@ -0,0 +1,185 @@ +import 'package:code_editor/models/terminal_session.dart'; +import 'package:flutter/material.dart'; + +/// 全局终端会话管理 Provider +class TerminalProvider extends ChangeNotifier { + final List _sessions = []; + int _activeIndex = 0; + + List 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 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(); + } +} diff --git a/lib/services/distro_installer.dart b/lib/services/distro_installer.dart new file mode 100644 index 0000000..32b7339 --- /dev/null +++ b/lib/services/distro_installer.dart @@ -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 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; + 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 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); + } + } +} diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart new file mode 100644 index 0000000..f9b9f41 --- /dev/null +++ b/lib/services/distro_manager.dart @@ -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 arguments; + + /// 环境变量 + final Map 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` + final Map _distros = {}; + + /// 获取所有已注册的发行版 + List 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); + } + + /// 获取发行版存储基础目录: `/distros` + Future 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 解压目录: `/distros//rootfs` + Future getDistroRootDir(String distroId) async { + final baseDir = await getBaseDistrosDir(); + return Directory(p.join(baseDir.path, distroId, 'rootfs')); + } + + /// 检测指定发行版是否已安装就绪 + Future 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 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 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 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 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] : []; + 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 = [ + '-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 = { + '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, + ); + } +} diff --git a/lib/services/permission_service.dart b/lib/services/permission_service.dart new file mode 100644 index 0000000..28cb76c --- /dev/null +++ b/lib/services/permission_service.dart @@ -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 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 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; + } + } +} diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index 2f38ced..30e0482 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -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 _fadeAnim; + late final Animation _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(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, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} + diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index 38fa652..82e0d22 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -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 fonts, + required String currentId, + required ValueChanged onSelected, + required String previewSample, + }) { + showModalBottomSheet( + 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( + 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; diff --git a/lib/views/terminal_view.dart b/lib/views/terminal_view.dart new file mode 100644 index 0000000..066a3be --- /dev/null +++ b/lib/views/terminal_view.dart @@ -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 createState() => _TerminalViewState(); +} + +class _TerminalViewState extends State { + final GlobalKey _scaffoldKey = GlobalKey(); + + @override + void initState() { + super.initState(); + // 懒加载:进入终端 view 时,若无会话则自动创建首个会话 + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + context.read().ensureInitialized(); + } + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final provider = context.watch(); + 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(); + 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().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().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(); + 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(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('一键初始化'), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart index 1997680..27d28b7 100644 --- a/lib/widgets/code_editor_app_bar.dart +++ b/lib/widgets/code_editor_app_bar.dart @@ -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( + 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 _fadeAnimation; + late final Animation _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(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( - 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( - 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( - 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( - value: 'close_project', - child: Row( - children: [ - const Icon(Icons.folder_off_outlined, size: 20), - const SizedBox(width: 10), - Text(l10n.closeProject), - ], - ), - ), - PopupMenuItem( - 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, + ), ); } } diff --git a/lib/widgets/code_editor_drawer.dart b/lib/widgets/code_editor_drawer.dart index 165faaa..a93932d 100644 --- a/lib/widgets/code_editor_drawer.dart +++ b/lib/widgets/code_editor_drawer.dart @@ -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() : context.read(); + static ProjectProvider _getProjectProvider( + BuildContext context, { + bool listen = false, + }) { + return listen + ? context.watch() + : context.read(); } - static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) { + static TabProvider _getTabProvider( + BuildContext context, { + bool listen = false, + }) { return listen ? context.watch() : context.read(); } Future _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 _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())), + ], ), ); } diff --git a/lib/widgets/code_editor_menu.dart b/lib/widgets/code_editor_menu.dart index 3b89935..dfabe56 100644 --- a/lib/widgets/code_editor_menu.dart +++ b/lib/widgets/code_editor_menu.dart @@ -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 implements PreferredSizeWidget { _EditorContextMenuItem({ required String text, @@ -26,13 +26,126 @@ class _EditorContextMenuItem extends PopupMenuItem 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 _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 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 _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(); + } } } diff --git a/lib/widgets/code_editor_tab_bar.dart b/lib/widgets/code_editor_tab_bar.dart index a81610a..1e362c3 100644 --- a/lib/widgets/code_editor_tab_bar.dart +++ b/lib/widgets/code_editor_tab_bar.dart @@ -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( diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index 116adf1..6ca662d 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -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 { 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 { @override void initState() { super.initState(); + _toolbarController = CodeEditorToolbarController(focusNode: _focusNode); _loadFileContent(); } @@ -151,6 +156,7 @@ class _CodeEditorWidgetState extends State { 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 { _scrollController?.dispose(); _controller?.removeListener(_onTextChanged); _controller?.dispose(); + _focusNode.dispose(); super.dispose(); } @@ -341,6 +348,7 @@ class _CodeEditorWidgetState extends State { 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 { 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 { 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 { 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 { 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 { if (enableVirtualKeyboard && keyboardConfig != null) VirtualKeyboardWidget( controller: controller, + focusNode: _focusNode, config: keyboardConfig, ), ], @@ -449,7 +468,15 @@ class _CodeEditorWidgetState extends State { ? 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 { 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 { 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) { diff --git a/lib/widgets/file_item_widget.dart b/lib/widgets/file_item_widget.dart index 02ec6f9..dc8d261 100644 --- a/lib/widgets/file_item_widget.dart +++ b/lib/widgets/file_item_widget.dart @@ -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 { 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( diff --git a/lib/widgets/terminal_drawer.dart b/lib/widgets/terminal_drawer.dart new file mode 100644 index 0000000..c5e7557 --- /dev/null +++ b/lib/widgets/terminal_drawer.dart @@ -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(); + 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, + ); + }, + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/terminal_session_item_widget.dart b/lib/widgets/terminal_session_item_widget.dart new file mode 100644 index 0000000..4c8a91c --- /dev/null +++ b/lib/widgets/terminal_session_item_widget.dart @@ -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(); + 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( + 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 _buildMenuItem({ + required String value, + required IconData icon, + required String title, + required Color color, + bool isDestructive = false, + }) { + return PopupMenuItem( + 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(); + + 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; + } + } +} diff --git a/lib/widgets/virtual_keyboard_widget.dart b/lib/widgets/virtual_keyboard_widget.dart index fa7feb3..c5b3e2f 100644 --- a/lib/widgets/virtual_keyboard_widget.dart +++ b/lib/widgets/virtual_keyboard_widget.dart @@ -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 { // 轻微触觉反馈提升敲击手感 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 { 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 { 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), + ], + ), ), ), ); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 2e1de87..be1ee3e 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/pubspec.lock b/pubspec.lock index 0d6895f..b7fa831 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1,6 +1,22 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + archive: + dependency: "direct main" + description: + name: archive + sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d + url: "https://pub.dev" + source: hosted + version: "3.6.1" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" async: dependency: transitive description: @@ -33,6 +49,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: cfd4f5f575a49c5f10ca856e9846073f1e6c3ee94912377eea5f6cefc5272941 + url: "https://pub.dev" + source: hosted + version: "2.0.0" collection: dependency: transitive description: @@ -49,6 +73,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.3.5+5" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" cupertino_icons: dependency: "direct main" description: @@ -125,6 +157,14 @@ packages: description: flutter source: sdk version: "0.0.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f + url: "https://pub.dev" + source: hosted + version: "2.2.0" intl: dependency: "direct main" description: @@ -149,6 +189,30 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.5+1" + jni: + dependency: transitive + description: + name: jni + sha256: f038e58b4dc2c9037f50e233175086337e0b305e356d28211bf55f21c504cbd3 + url: "https://pub.dev" + source: hosted + version: "1.0.3" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: b2310cdd4c18c65c081ab141a41efa94aa26c65431803703ece51996f174f351 + url: "https://pub.dev" + source: hosted + version: "1.0.3" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" leak_tracker: dependency: transitive description: @@ -181,6 +245,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" matcher: dependency: transitive description: @@ -213,6 +285,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: ad56fd53a78ff6b1472fa59ff2a4e8b8ccabafc586fc263a1dfad0b99b5553e3 + url: "https://pub.dev" + source: hosted + version: "9.6.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" path: dependency: "direct main" description: @@ -221,6 +309,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" path_provider_linux: dependency: transitive description: @@ -245,6 +357,54 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.0" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: e6bcecadfe40df6b888141f23cbaf6ba6c3da49fb33f6ff887d060dd48544fbd + url: "https://pub.dev" + source: hosted + version: "13.0.2" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: b1ce660f4d0dcaffdf2605a19544c129fb5adda4e6fd039992ae356c4e437039 + url: "https://pub.dev" + source: hosted + version: "14.1.0" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: f49cb15a064ea9d974fc7fbb302099353b7b170d07284e86e264561579e5bcf8 + url: "https://pub.dev" + source: hosted + version: "9.6.1" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "6ea98b3f17f60d3b527f2647ed2ab4dc0f6bfe25b22cb1c363f5d8f62252f6ac" + url: "https://pub.dev" + source: hosted + version: "0.1.4+1" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: ed86a61c190258fdd65de395ea0632822e3415c1faec38eae0c31b479c28a531 + url: "https://pub.dev" + source: hosted + version: "4.4.1" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: caeae01858a0a7d2df67a445ac98e1ad95e55a0e77c73044f4e9b1c8c2289cbd + url: "https://pub.dev" + source: hosted + version: "0.2.2" platform: dependency: transitive description: @@ -269,6 +429,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.5+1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" re_editor: dependency: "direct main" description: @@ -285,6 +453,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.0.3" + record_use: + dependency: transitive + description: + name: record_use + sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2" + url: "https://pub.dev" + source: hosted + version: "1.1.1" shared_preferences: dependency: "direct main" description: @@ -394,6 +570,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.12" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" vector_math: dependency: transitive description: @@ -434,6 +618,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" sdks: dart: ">=3.12.0 <4.0.0" flutter: ">=3.44.0" diff --git a/pubspec.yaml b/pubspec.yaml index f32c8ff..d06c144 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -23,6 +23,9 @@ dependencies: provider: ^6.1.2 re_editor: ^0.10.0 re_highlight: ^0.0.3 + permission_handler: ^13.0.2 + path_provider: ^2.1.5 + archive: ^3.6.1 dev_dependencies: flutter_test: @@ -34,4 +37,27 @@ flutter: generate: true - uses-material-design: true \ No newline at end of file + uses-material-design: true + + assets: + - assets/distros/ + + fonts: + - family: JetBrains Mono + fonts: + - asset: assets/fonts/JetBrainsMonoNerdFontMono-Regular.ttf + - asset: assets/fonts/JetBrainsMonoNerdFontMono-Italic.ttf + style: italic + - asset: assets/fonts/JetBrainsMonoNerdFontMono-Bold.ttf + weight: 700 + - asset: assets/fonts/JetBrainsMonoNerdFontMono-BoldItalic.ttf + weight: 700 + style: italic + + - family: Fira Code + fonts: + - asset: assets/fonts/FiraCodeNerdFontMono-Regular.ttf + - asset: assets/fonts/FiraCodeNerdFontMono-Medium.ttf + weight: 500 + - asset: assets/fonts/FiraCodeNerdFontMono-Bold.ttf + weight: 700 \ No newline at end of file diff --git a/test/distro_manager_test.dart b/test/distro_manager_test.dart new file mode 100644 index 0000000..47ade18 --- /dev/null +++ b/test/distro_manager_test.dart @@ -0,0 +1,182 @@ +import 'dart:io'; +import 'dart:typed_data'; +import 'package:archive/archive.dart'; +import 'package:code_editor/models/distro_info.dart'; +import 'package:code_editor/providers/distro_provider.dart'; +import 'package:code_editor/services/distro_installer.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempDir; + late DistroManager manager; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('distro_test_'); + manager = DistroManager(); + manager.customBaseDir = tempDir; + }); + + tearDown(() { + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + group('DistroManager & DistroInfo Tests', () { + test('内置预设包含 Alpine, Debian, Ubuntu, Host', () { + final distros = manager.listDistros(); + expect(distros.any((d) => d.id == 'alpine'), isTrue); + expect(distros.any((d) => d.id == 'debian'), isTrue); + expect(distros.any((d) => d.id == 'ubuntu'), isTrue); + expect(distros.any((d) => d.id == 'host'), isTrue); + + final alpine = manager.getDistro('alpine'); + expect(alpine, isNotNull); + expect(alpine!.packageManager, 'apk'); + expect(alpine.defaultShell, '/bin/sh'); + expect(alpine.assetPath, contains('alpine-minirootfs')); + }); + + test('支持动态扩展注册与注销自定义发行版', () { + const customDistro = DistroInfo( + id: 'archlinux', + name: 'Arch Linux', + version: 'Rolling', + description: '滚动更新的极客发行版', + packageManager: 'pacman', + defaultShell: '/bin/bash', + isBuiltin: false, + ); + + manager.registerDistro(customDistro); + expect(manager.getDistro('archlinux'), isNotNull); + expect(manager.getDistro('archlinux')!.name, 'Arch Linux'); + + manager.unregisterDistro('archlinux'); + expect(manager.getDistro('archlinux'), isNull); + }); + + test('Host 本地环境默认视为已就绪', () async { + final isInstalled = await manager.isInstalled('host'); + expect(isInstalled, isTrue); + }); + + test('未初始化的 Linux 容器返回 false', () async { + final isInstalled = await manager.isInstalled('alpine'); + expect(isInstalled, isFalse); + }); + }); + + group('DistroInstaller 解压与网络配置测试', () { + test('创建测试 tar.gz 并使用 DistroInstaller 解压与配置', () async { + // 构造小型测试 tar.gz 镜像 + final archive = Archive(); + archive.addFile(ArchiveFile('bin/sh', 11, 'echo "sh"'.codeUnits)); + archive.addFile(ArchiveFile('etc/os-release', 18, 'NAME="Alpine Linux"'.codeUnits)); + + final tarData = TarEncoder().encode(archive); + final gzData = GZipEncoder().encode(tarData); + + final targetDir = Directory(p.join(tempDir.path, 'alpine', 'rootfs')); + + double lastProgress = 0.0; + String lastMessage = ''; + + await DistroInstaller.installFromBytes( + tarGzBytes: Uint8List.fromList(gzData!), + targetDir: targetDir, + onProgress: (prog, msg) { + lastProgress = prog; + lastMessage = msg; + }, + ); + + expect(lastProgress, 1.0); + expect(lastMessage, '系统初始化就绪!'); + + // 验证文件解压成功 + expect(File(p.join(targetDir.path, 'bin', 'sh')).existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'etc', 'os-release')).existsSync(), isTrue); + + // 验证自动配置的 resolv.conf (DNS) 与 hosts + final resolvFile = File(p.join(targetDir.path, 'etc', 'resolv.conf')); + expect(resolvFile.existsSync(), isTrue); + final resolvContent = resolvFile.readAsStringSync(); + expect(resolvContent, contains('nameserver 1.1.1.1')); + expect(resolvContent, contains('nameserver 8.8.8.8')); + + final hostsFile = File(p.join(targetDir.path, 'etc', 'hosts')); + expect(hostsFile.existsSync(), isTrue); + expect(hostsFile.readAsStringSync(), contains('127.0.0.1 localhost')); + + // 验证 /workspace 挂载点目录被创建 + expect(Directory(p.join(targetDir.path, 'workspace')).existsSync(), isTrue); + + // 此时检测安装状态应为 true + final isInstalled = await manager.isInstalled('alpine'); + expect(isInstalled, isTrue); + }); + }); + + group('ProotCommandBuilder 启动配置构建测试', () { + test('构建 Host 本地启动配置', () async { + final config = await manager.buildLaunchConfig( + distroId: 'host', + workspacePath: tempDir.path, + customCommand: 'ls -la', + ); + + expect(config.executable, '/system/bin/sh'); + expect(config.arguments, ['-c', 'ls -la']); + expect(config.workingDirectory, tempDir.path); + expect(config.environment['TERM'], 'xterm-256color'); + }); + + test('构建 Alpine PRoot 容器隔离启动配置与挂载参数', () async { + final config = await manager.buildLaunchConfig( + distroId: 'alpine', + workspacePath: tempDir.path, + prootPath: '/data/data/com.example/files/proot', + ); + + expect(config.executable, '/data/data/com.example/files/proot'); + expect(config.arguments, contains('-0')); + expect(config.arguments, contains('-r')); + expect(config.arguments, contains('-b')); + expect(config.arguments, contains('/dev')); + expect(config.arguments, contains('/proc')); + expect(config.arguments, contains('/sys')); + expect(config.arguments, contains('${tempDir.path}:/workspace')); + expect(config.arguments, contains('-w')); + expect(config.arguments, contains('/workspace')); + expect(config.arguments, contains('/bin/sh')); + expect(config.arguments, contains('-l')); + + expect(config.environment['HOME'], '/root'); + expect(config.environment['USER'], 'root'); + expect(config.environment['TERM'], 'xterm-256color'); + expect(config.environment['PATH'], isNotEmpty); + + final cmdLine = config.toCommandLine(); + expect(cmdLine, contains('/data/data/com.example/files/proot')); + expect(cmdLine, contains('-0')); + }); + }); + + group('DistroProvider 状态测试', () { + test('初始状态与切换默认发行版', () async { + final provider = DistroProvider(); + expect(provider.defaultDistroId, 'alpine'); + + provider.setDefaultDistro('host'); + expect(provider.defaultDistroId, 'host'); + + await provider.checkAllStatuses(); + expect(provider.getStatus('host'), DistroStatus.installed); + }); + }); +} diff --git a/test/terminal_test.dart b/test/terminal_test.dart new file mode 100644 index 0000000..6fc0418 --- /dev/null +++ b/test/terminal_test.dart @@ -0,0 +1,287 @@ +import 'package:code_editor/l10n/app_localizations.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/views/terminal_view.dart'; +import 'package:code_editor/widgets/terminal_session_item_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Widget createTestTerminalApp({required TerminalProvider terminalProvider}) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: terminalProvider), + ChangeNotifierProvider(create: (_) => DistroProvider()), + ], + child: MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const TerminalView(), + ), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + group('Terminal Subsystem Tests', () { + testWidgets('Lazy loading creates first session upon first entry', (tester) async { + final provider = TerminalProvider(); + expect(provider.sessions.isEmpty, isTrue); + + await tester.pumpWidget(createTestTerminalApp(terminalProvider: provider)); + await tester.pumpAndSettle(); + + expect(provider.sessions.length, equals(1)); + expect(provider.activeIndex, equals(0)); + expect(provider.activeSession?.name, equals('会话')); + + // Check AppBar title and subtitle + expect(find.text('会话'), findsWidgets); + expect(find.text('终端'), findsOneWidget); + }); + + testWidgets('Right drawer can be opened and shows title "会话" with add button', (tester) async { + final provider = TerminalProvider(); + await tester.pumpWidget(createTestTerminalApp(terminalProvider: provider)); + await tester.pumpAndSettle(); + + // Click list button in AppBar to open endDrawer + final listBtn = find.byIcon(Icons.format_list_bulleted); + expect(listBtn, findsOneWidget); + await tester.tap(listBtn); + await tester.pumpAndSettle(); + + // Drawer is open + expect(find.byType(Drawer), findsOneWidget); + expect(find.byIcon(Icons.add), findsOneWidget); + + // Verify item text format: (1) 会话 + expect(find.text('(1) 会话'), findsOneWidget); + + // Tap Add button in drawer: creates session but does NOT switch + await tester.tap(find.byIcon(Icons.add)); + await tester.pumpAndSettle(); + + expect(provider.sessions.length, equals(2)); + expect(provider.activeIndex, equals(0)); // Did not switch! + expect(find.text('(2) 会话'), findsOneWidget); + }); + + testWidgets('Tapping session item switches active session and closes drawer', (tester) async { + final provider = TerminalProvider(); + await tester.pumpWidget(createTestTerminalApp(terminalProvider: provider)); + await tester.pumpAndSettle(); + + // Open drawer + await tester.tap(find.byIcon(Icons.format_list_bulleted)); + await tester.pumpAndSettle(); + + // Add session 2 + await tester.tap(find.byIcon(Icons.add)); + await tester.pumpAndSettle(); + expect(provider.activeIndex, equals(0)); + + // Tap session 2 item + await tester.tap(find.text('(2) 会话')); + await tester.pumpAndSettle(); + + // Drawer should be closed and activeIndex is now 1 + expect(find.byType(Drawer), findsNothing); + expect(provider.activeIndex, equals(1)); + }); + + testWidgets('Long press on session item opens context menu with rename and delete', (tester) async { + final provider = TerminalProvider(); + await tester.pumpWidget(createTestTerminalApp(terminalProvider: provider)); + await tester.pumpAndSettle(); + + // Open drawer + await tester.tap(find.byIcon(Icons.format_list_bulleted)); + await tester.pumpAndSettle(); + + // Long press on session item + final sessionItem = find.byType(TerminalSessionItemWidget); + expect(sessionItem, findsOneWidget); + await tester.longPress(sessionItem); + await tester.pumpAndSettle(); + + // Context menu options + expect(find.text('重命名'), findsOneWidget); + expect(find.text('删除'), findsOneWidget); + + // Tap 重命名 + await tester.tap(find.text('重命名')); + await tester.pumpAndSettle(); + + // Dialog opens + expect(find.byType(AlertDialog), findsOneWidget); + final dialogTextField = find.descendant( + of: find.byType(AlertDialog), + matching: find.byType(TextField), + ); + await tester.enterText(dialogTextField, '调试终端'); + await tester.tap(find.text('确定')); + await tester.pumpAndSettle(); + + expect(provider.activeSession?.name, equals('调试终端')); + }); + + testWidgets('Session persistence: returning to editor and re-entering preserves sessions and buffers', (tester) async { + final provider = TerminalProvider(); + + // Simulate root app with Navigator + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: provider), + ], + child: MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: ElevatedButton( + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const TerminalView(), + ), + ); + }, + child: const Text('进入终端'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Enter terminal + await tester.tap(find.text('进入终端')); + await tester.pumpAndSettle(); + + expect(find.byType(TerminalView), findsOneWidget); + expect(provider.sessions.length, equals(1)); + + // Append custom text to session buffer via provider + provider.appendOutput(provider.activeSession!, 'CUSTOM_SESSION_OUTPUT_LINE'); + await tester.pumpAndSettle(); + expect(find.text('CUSTOM_SESSION_OUTPUT_LINE'), findsOneWidget); + + // Pop back to editor + await tester.tap(find.byIcon(Icons.arrow_back)); + await tester.pumpAndSettle(); + + expect(find.byType(TerminalView), findsNothing); + expect(find.text('进入终端'), findsOneWidget); + + // Provider still holds the session and buffer + expect(provider.sessions.length, equals(1)); + expect(provider.sessions.first.outputLines.contains('CUSTOM_SESSION_OUTPUT_LINE'), isTrue); + + // Re-enter terminal + await tester.tap(find.text('进入终端')); + await tester.pumpAndSettle(); + + // Verify the session output is still right there + expect(find.byType(TerminalView), findsOneWidget); + expect(find.text('CUSTOM_SESSION_OUTPUT_LINE'), findsOneWidget); + }); + + testWidgets('Deleting a session from context menu removes it and updates activeIndex', (tester) async { + final provider = TerminalProvider(); + await tester.pumpWidget(createTestTerminalApp(terminalProvider: provider)); + await tester.pumpAndSettle(); + + // Open drawer + await tester.tap(find.byIcon(Icons.format_list_bulleted)); + await tester.pumpAndSettle(); + + // Add second session + await tester.tap(find.byIcon(Icons.add)); + await tester.pumpAndSettle(); + expect(provider.sessions.length, equals(2)); + + // Long press second session + final items = find.byType(TerminalSessionItemWidget); + expect(items, findsNWidgets(2)); + await tester.longPress(items.at(1)); + await tester.pumpAndSettle(); + + // Tap 删除 + await tester.tap(find.text('删除')); + await tester.pumpAndSettle(); + + // Confirm dialog opens + expect(find.byType(AlertDialog), findsOneWidget); + await tester.tap(find.text('删除').last); + await tester.pumpAndSettle(); + + // Session 2 is deleted + expect(provider.sessions.length, equals(1)); + expect(find.text('(2) 会话'), findsNothing); + }); + + testWidgets('Dragging to reorder sessions updates session list order and labels', (tester) async { + final provider = TerminalProvider(); + await tester.pumpWidget(createTestTerminalApp(terminalProvider: provider)); + await tester.pumpAndSettle(); + + // Open drawer + await tester.tap(find.byIcon(Icons.format_list_bulleted)); + await tester.pumpAndSettle(); + + // Add second session + await tester.tap(find.byIcon(Icons.add)); + await tester.pumpAndSettle(); + + provider.renameSession(provider.sessions[0].id, '第一项'); + provider.renameSession(provider.sessions[1].id, '第二项'); + await tester.pumpAndSettle(); + + expect(find.text('(1) 第一项'), findsOneWidget); + expect(find.text('(2) 第二项'), findsOneWidget); + + // Drag first item's drag handle downwards past the second item + final firstDragHandle = find.byIcon(Icons.drag_handle).first; + await tester.drag(firstDragHandle, const Offset(0, 120)); + await tester.pumpAndSettle(); + + expect(provider.sessions[0].name, equals('第二项')); + expect(provider.sessions[1].name, equals('第一项')); + expect(find.text('(1) 第二项'), findsOneWidget); + expect(find.text('(2) 第一项'), findsOneWidget); + }); + + test('SettingsProvider manages UI, Editor, and Terminal font choices correctly', () async { + final settings = SettingsProvider(); + expect(settings.uiFont.id, equals('system_default')); + expect(settings.editorFont.id, equals('monospace')); + expect(settings.terminalFont.id, equals('monospace')); + + await settings.setUiFontId('sans_serif'); + expect(settings.uiFont.id, equals('sans_serif')); + expect(settings.uiFont.fontFamily, equals('sans-serif')); + + await settings.setEditorFontId('jetbrains_mono'); + expect(settings.editorFont.id, equals('jetbrains_mono')); + expect(settings.editorFont.fontFamily, equals('JetBrains Mono')); + + await settings.setTerminalFontId('consolas'); + expect(settings.terminalFont.id, equals('consolas')); + expect(settings.terminalFont.fontFamily, equals('Consolas')); + }); + }); +} + diff --git a/test/widget_test.dart b/test/widget_test.dart index 8fc46b2..8b6a318 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,3 +1,4 @@ +import 'dart:io'; import 'package:re_editor/re_editor.dart'; import 'package:code_editor/models/editor_tab_item.dart'; import 'package:code_editor/models/file_item.dart'; @@ -23,6 +24,7 @@ import 'package:code_editor/views/settings_view.dart'; import 'package:code_editor/views/main_view.dart'; import 'package:code_editor/widgets/code_editor_app_bar.dart'; import 'package:code_editor/widgets/code_editor_drawer.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/services/file_watcher_service.dart'; import 'package:code_editor/utils/syntax_highlight_helper.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -252,14 +254,12 @@ void main() { final appBar = tester.widget(appBarFinder); expect(appBar.foregroundColor, isNotNull); - // Verify PopupMenuButton has position under - final popupBtnFinder = find.byType(PopupMenuButton); - expect(popupBtnFinder, findsOneWidget); - final popupBtn = tester.widget>(popupBtnFinder); - expect(popupBtn.position, equals(PopupMenuPosition.under)); + // Verify more menu button exists + final moreBtnFinder = find.byIcon(Icons.more_vert); + expect(moreBtnFinder, findsOneWidget); // Tap menu button - await tester.tap(popupBtnFinder); + await tester.tap(moreBtnFinder); await tester.pumpAndSettle(); expect(find.text('设置'), findsOneWidget); @@ -284,6 +284,9 @@ void main() { ); await tester.pumpAndSettle(); + // Scroll until word wrap switch is visible + await tester.scrollUntilVisible(find.text('自动换行'), 200); + // Verify word wrap switch tile exists expect(find.text('自动换行'), findsOneWidget); final wordWrapTile = find.ancestor( @@ -303,6 +306,23 @@ void main() { await tester.pumpAndSettle(); expect(provider.wordWrap, isFalse); + // Verify indent size tile + expect(find.text('缩进大小'), findsOneWidget); + expect(find.text('2 个空格'), findsOneWidget); + + // Tap indent size tile to open modal + await tester.tap(find.text('缩进大小')); + await tester.pumpAndSettle(); + + expect(find.text('选择缩进空格数'), findsOneWidget); + expect(find.text('4 个空格'), findsOneWidget); + + // Select 4 spaces + await tester.tap(find.text('4 个空格')); + await tester.pumpAndSettle(); + + expect(provider.indentSize, equals(4)); + // Verify language section final langTile = find.text('应用语言'); await tester.scrollUntilVisible(langTile, 300); @@ -548,7 +568,7 @@ void main() { expect(find.text('/lib/views'), findsOneWidget); // Open popup menu - await tester.tap(find.byType(PopupMenuButton)); + await tester.tap(find.byIcon(Icons.more_vert)); await tester.pumpAndSettle(); expect(find.text('保存所有'), findsOneWidget); @@ -563,6 +583,48 @@ void main() { expect(saveAllTriggered, isTrue); }); + testWidgets('DialogUtils.showToast adapts position above soft keyboard when viewInsets.bottom > 0', (WidgetTester tester) async { + addTearDown(tester.view.resetViewInsets); + late BuildContext targetContext; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (ctx) { + targetContext = ctx; + return const Text('Target'); + }, + ), + ), + ), + ); + + // 1. 无软键盘时显示 Toast + DialogUtils.showSuccessToast(targetContext, '保存成功'); + await tester.pump(const Duration(milliseconds: 50)); + + expect(find.text('保存成功'), findsOneWidget); + final initialCenter = tester.getCenter(find.text('保存成功')); + + // 等待第一个 Toast 自动卸载 + await tester.pump(const Duration(seconds: 3)); + expect(find.text('保存成功'), findsNothing); + + // 2. 模拟系统软键盘弹出时 (viewInsets.bottom: 260 逻辑像素) + tester.view.viewInsets = FakeViewPadding(bottom: 260 * tester.view.devicePixelRatio); + DialogUtils.showSuccessToast(targetContext, '有键盘'); + await tester.pump(const Duration(milliseconds: 50)); + + final keyboardCenter = tester.getCenter(find.text('有键盘')); + // 键盘弹出后,Toast 中心点必须往上移(dy 变小)至少 200 像素以上,远离键盘遮挡区 + expect(keyboardCenter.dy, lessThan(initialCenter.dy - 200)); + + // 等待 Toast 动画与定时器自动卸载 + await tester.pump(const Duration(seconds: 3)); + expect(find.text('有键盘'), findsNothing); + }); + testWidgets('CodeEditorTabBar renders tabs and handles dirty close dialog', (WidgetTester tester) async { final provider = TabProvider(); final tab1 = EditorTabItem(path: '/test/file1.dart', isModified: false); @@ -616,12 +678,16 @@ void main() { test('SettingsProvider manages settings correctly', () async { final settings = SettingsProvider(); expect(settings.fontSize, equals(14.0)); + expect(settings.indentSize, equals(2)); expect(settings.wordWrap, isTrue); expect(settings.appThemeMode, equals(ThemeMode.system)); await settings.setFontSize(18.0); expect(settings.fontSize, equals(18.0)); + await settings.setIndentSize(4); + expect(settings.indentSize, equals(4)); + await settings.setWordWrap(false); expect(settings.wordWrap, isFalse); @@ -969,12 +1035,18 @@ void main() { }); testWidgets('Opening another file from file list when active file is modified does not prompt save dialog', (WidgetTester tester) async { + final tempDir = Directory.systemTemp.createTempSync('widget_test_tab_'); + addTearDown(() { + if (tempDir.existsSync()) tempDir.deleteSync(recursive: true); + }); + final tabProvider = TabProvider(); final projectProvider = ProjectProvider(); final settingsProvider = SettingsProvider(); - final file1 = FileItem(path: p.normalize('/ws/file1.dart'), name: 'file1.dart', isDirectory: false); - final file2 = FileItem(path: p.normalize('/ws/file2.dart'), name: 'file2.dart', isDirectory: false); + final file1 = FileItem(path: p.join(tempDir.path, 'file1.dart'), name: 'file1.dart', isDirectory: false); + final file2 = FileItem(path: p.join(tempDir.path, 'file2.dart'), name: 'file2.dart', isDirectory: false); + File(file2.path).writeAsStringSync('int b = 2;'); // Initial state: open file1 and modify it await tabProvider.openFile(file1.path, content: 'int a = 1;'); @@ -996,7 +1068,8 @@ void main() { ), ), ); - await tester.pumpAndSettle(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); // Verify main view is rendered with modified file1 expect(find.text('file1.dart'), findsWidgets); @@ -1004,27 +1077,32 @@ void main() { // Open file2 via selectFile (simulating user clicking file2 in file tree/drawer) await tabProvider.selectFile(file2); - await tester.pumpAndSettle(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); // NO save prompt dialog should appear expect(find.text('保存更改'), findsNothing); expect(find.text('保存所有更改?'), findsNothing); // Now file2 is active, file1 is still open and preserved in memory - expect(tabProvider.activeTab?.path, equals(p.normalize('/ws/file2.dart'))); + expect(tabProvider.activeTab?.path, equals(p.normalize(file2.path))); expect(tabProvider.openTabs.length, equals(2)); expect(tabProvider.openTabs[0].isModified, isTrue); expect(tabProvider.openTabs[0].content, equals('int a = 2;')); // Switch back to file1 via openFile (simulating clicking tab1) await tabProvider.openFile(file1.path); - await tester.pumpAndSettle(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); // NO save prompt dialog should appear on tab switch either expect(find.text('保存更改'), findsNothing); expect(find.text('保存所有更改?'), findsNothing); - expect(tabProvider.activeTab?.path, equals(p.normalize('/ws/file1.dart'))); + expect(tabProvider.activeTab?.path, equals(p.normalize(file1.path))); expect(tabProvider.activeTab?.isModified, isTrue); + + // Unmount MainView so cursor blinking timer cancels cleanly + await tester.pumpWidget(const SizedBox()); }); testWidgets('Close all tabs from PopupMenu prompts for dirty tabs and closes tabs', (WidgetTester tester) async { @@ -1050,28 +1128,34 @@ void main() { ), ), ); - await tester.pumpAndSettle(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); expect(tabProvider.openTabs.length, equals(1)); // Tap more menu - await tester.tap(find.byType(PopupMenuButton)); - await tester.pumpAndSettle(); + await tester.tap(find.byIcon(Icons.more_vert)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); // Tap '关闭所有标签' await tester.tap(find.text('关闭所有标签')); - await tester.pumpAndSettle(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); // Dirty prompt dialog should appear expect(find.text('保存所有更改?'), findsOneWidget); // Choose discard (不保存) await tester.tap(find.text('不保存')); - await tester.pumpAndSettle(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); // All tabs should be closed expect(tabProvider.openTabs, isEmpty); expect(tabProvider.activeTab, isNull); + + await tester.pumpWidget(const SizedBox()); }); testWidgets('Deleting current project in ProjectHistoryWidget closes project first before confirming delete', (WidgetTester tester) async { @@ -1386,7 +1470,7 @@ void main() { // Scroll to virtual keyboard tiles final configTile = find.text('编辑键盘配置'); - await tester.drag(find.byType(ListView), const Offset(0, -200)); + await tester.scrollUntilVisible(configTile, 200); await tester.pumpAndSettle(); expect(configTile, findsOneWidget); @@ -1407,11 +1491,11 @@ void main() { // Edit controller with invalid json on line 3 editorController.text = '{\n "pages": [\n error_here\n ]\n}'; - await tester.pumpAndSettle(); + await tester.pump(const Duration(milliseconds: 100)); // Tap '保存' await tester.tap(find.text('保存')); - await tester.pumpAndSettle(); + await tester.pump(const Duration(milliseconds: 100)); // Dialog should still be open and display error message with line number expect(find.text('小键盘配置 (JSON)'), findsOneWidget); @@ -1420,7 +1504,7 @@ void main() { // Tap '恢复默认' await tester.tap(find.text('恢复默认')); - await tester.pumpAndSettle(); + await tester.pump(const Duration(milliseconds: 100)); // Error message should clear expect(find.byIcon(Icons.error_outline), findsNothing); @@ -1428,7 +1512,7 @@ void main() { // Tap '保存' with valid config -> dialog closes await tester.tap(find.text('保存')); - await tester.pumpAndSettle(); + await tester.pump(const Duration(milliseconds: 500)); expect(find.text('小键盘配置 (JSON)'), findsNothing); diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 8b6d468..48de52b 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + PermissionHandlerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index b93c4c3..d6ee74d 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,9 +3,11 @@ # list(APPEND FLUTTER_PLUGIN_LIST + permission_handler_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni ) set(PLUGIN_BUNDLED_LIBRARIES)