diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e19a95b..c0e4813 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3,18 +3,19 @@ "appTitle": "Code Editor", "run": "Run", "settings": "Settings", - "fileDirectory": "File Directory", + "fileDirectory": "Project", "undo": "Undo", "redo": "Redo", "save": "Save", - "openFileDirectory": "Open File Directory", - "viewFileDirectoryHistory": "View Directory History", + "openFileDirectory": "Open Project", + "openProjectPrompt": "Please tap the button above to open a project", + "viewProjectHistory": "View Project History", "more": "More", - "noOpenDirectory": "No directory opened", + "noOpenDirectory": "No project opened", "noOpenFile": "No file opened", "unnamed": "Untitled", "unknownDirectory": "Unknown Directory", - "historyFileDirectories": "Directory History", + "projectHistory": "Project History", "noHistory": "No history records", "deleteThisHistory": "Delete this record", "deleteHistoryTitle": "Delete History", @@ -25,6 +26,8 @@ "cancel": "Cancel", "delete": "Delete", "close": "Close", + "closeAllTabs": "Close All Tabs", + "closeProject": "Close Project", "gotIt": "Got it", "done": "Done", "newFile": "New File", @@ -73,13 +76,22 @@ "fontSizeDialogTitle": "Editor Font Size", "wordWrap": "Word Wrap", "wordWrapSubtitle": "Wrap long lines to fit the editor width", + "virtualKeyboard": "Accessory Keyboard", + "virtualKeyboardSubtitle": "Show accessory symbols and shortcuts below the code editor", + "editVirtualKeyboardConfig": "Edit Keyboard Config", + "editVirtualKeyboardConfigSubtitle": "Customize keyboard layout and shortcuts (JSON)", + "virtualKeyboardDialogTitle": "Keyboard Config (JSON)", + "resetDefault": "Reset to Default", + "configFormatError": "Configuration format error", + "configSavedSuccess": "Keyboard configuration saved", + "formatJson": "Format", "languageSection": "Language", "appLanguage": "App Language", "selectLanguage": "Select App Language", "languageFollowSystem": "Follow System", "languageChinese": "简体中文", "languageEnglish": "English", - "refreshDirectory": "Refresh Directory", + "refreshDirectory": "Refresh Project", "back": "Back", "darkLabel": "Dark", "lightLabel": "Light", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index d73be8b..2a7fedb 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -119,7 +119,7 @@ abstract class AppLocalizations { /// No description provided for @fileDirectory. /// /// In zh, this message translates to: - /// **'文件目录'** + /// **'项目'** String get fileDirectory; /// No description provided for @undo. @@ -143,14 +143,20 @@ abstract class AppLocalizations { /// No description provided for @openFileDirectory. /// /// In zh, this message translates to: - /// **'打开文件目录'** + /// **'打开项目'** String get openFileDirectory; - /// No description provided for @viewFileDirectoryHistory. + /// No description provided for @openProjectPrompt. /// /// In zh, this message translates to: - /// **'查看文件目录历史'** - String get viewFileDirectoryHistory; + /// **'请点击上方按钮打开项目'** + String get openProjectPrompt; + + /// No description provided for @viewProjectHistory. + /// + /// In zh, this message translates to: + /// **'查看项目历史'** + String get viewProjectHistory; /// No description provided for @more. /// @@ -161,7 +167,7 @@ abstract class AppLocalizations { /// No description provided for @noOpenDirectory. /// /// In zh, this message translates to: - /// **'当前未打开文件目录'** + /// **'当前未打开项目'** String get noOpenDirectory; /// No description provided for @noOpenFile. @@ -182,11 +188,11 @@ abstract class AppLocalizations { /// **'未知目录'** String get unknownDirectory; - /// No description provided for @historyFileDirectories. + /// No description provided for @projectHistory. /// /// In zh, this message translates to: - /// **'历史文件目录'** - String get historyFileDirectories; + /// **'历史项目'** + String get projectHistory; /// No description provided for @noHistory. /// @@ -248,6 +254,18 @@ abstract class AppLocalizations { /// **'关闭'** String get close; + /// No description provided for @closeAllTabs. + /// + /// In zh, this message translates to: + /// **'关闭所有标签'** + String get closeAllTabs; + + /// No description provided for @closeProject. + /// + /// In zh, this message translates to: + /// **'关闭当前项目'** + String get closeProject; + /// No description provided for @gotIt. /// /// In zh, this message translates to: @@ -536,6 +554,60 @@ abstract class AppLocalizations { /// **'长代码行超出边界时自动折行'** String get wordWrapSubtitle; + /// No description provided for @virtualKeyboard. + /// + /// In zh, this message translates to: + /// **'辅助小键盘'** + String get virtualKeyboard; + + /// No description provided for @virtualKeyboardSubtitle. + /// + /// In zh, this message translates to: + /// **'在代码编辑区底部显示辅助符号与快捷键'** + String get virtualKeyboardSubtitle; + + /// No description provided for @editVirtualKeyboardConfig. + /// + /// In zh, this message translates to: + /// **'编辑键盘配置'** + String get editVirtualKeyboardConfig; + + /// No description provided for @editVirtualKeyboardConfigSubtitle. + /// + /// In zh, this message translates to: + /// **'自定义小键盘按键布局与快捷键 (JSON)'** + String get editVirtualKeyboardConfigSubtitle; + + /// No description provided for @virtualKeyboardDialogTitle. + /// + /// In zh, this message translates to: + /// **'小键盘配置 (JSON)'** + String get virtualKeyboardDialogTitle; + + /// No description provided for @resetDefault. + /// + /// In zh, this message translates to: + /// **'恢复默认'** + String get resetDefault; + + /// No description provided for @configFormatError. + /// + /// In zh, this message translates to: + /// **'配置格式错误'** + String get configFormatError; + + /// No description provided for @configSavedSuccess. + /// + /// In zh, this message translates to: + /// **'小键盘配置已保存'** + String get configSavedSuccess; + + /// No description provided for @formatJson. + /// + /// In zh, this message translates to: + /// **'格式化'** + String get formatJson; + /// No description provided for @languageSection. /// /// In zh, this message translates to: @@ -575,7 +647,7 @@ abstract class AppLocalizations { /// No description provided for @refreshDirectory. /// /// In zh, this message translates to: - /// **'刷新目录'** + /// **'刷新项目'** String get refreshDirectory; /// No description provided for @back. diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 35b59b1..ee31915 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -18,7 +18,7 @@ class AppLocalizationsEn extends AppLocalizations { String get settings => 'Settings'; @override - String get fileDirectory => 'File Directory'; + String get fileDirectory => 'Project'; @override String get undo => 'Undo'; @@ -30,16 +30,20 @@ class AppLocalizationsEn extends AppLocalizations { String get save => 'Save'; @override - String get openFileDirectory => 'Open File Directory'; + String get openFileDirectory => 'Open Project'; @override - String get viewFileDirectoryHistory => 'View Directory History'; + String get openProjectPrompt => + 'Please tap the button above to open a project'; + + @override + String get viewProjectHistory => 'View Project History'; @override String get more => 'More'; @override - String get noOpenDirectory => 'No directory opened'; + String get noOpenDirectory => 'No project opened'; @override String get noOpenFile => 'No file opened'; @@ -51,7 +55,7 @@ class AppLocalizationsEn extends AppLocalizations { String get unknownDirectory => 'Unknown Directory'; @override - String get historyFileDirectories => 'Directory History'; + String get projectHistory => 'Project History'; @override String get noHistory => 'No history records'; @@ -84,6 +88,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get close => 'Close'; + @override + String get closeAllTabs => 'Close All Tabs'; + + @override + String get closeProject => 'Close Project'; + @override String get gotIt => 'Got it'; @@ -246,6 +256,35 @@ class AppLocalizationsEn extends AppLocalizations { @override String get wordWrapSubtitle => 'Wrap long lines to fit the editor width'; + @override + String get virtualKeyboard => 'Accessory Keyboard'; + + @override + String get virtualKeyboardSubtitle => + 'Show accessory symbols and shortcuts below the code editor'; + + @override + String get editVirtualKeyboardConfig => 'Edit Keyboard Config'; + + @override + String get editVirtualKeyboardConfigSubtitle => + 'Customize keyboard layout and shortcuts (JSON)'; + + @override + String get virtualKeyboardDialogTitle => 'Keyboard Config (JSON)'; + + @override + String get resetDefault => 'Reset to Default'; + + @override + String get configFormatError => 'Configuration format error'; + + @override + String get configSavedSuccess => 'Keyboard configuration saved'; + + @override + String get formatJson => 'Format'; + @override String get languageSection => 'Language'; @@ -265,7 +304,7 @@ class AppLocalizationsEn extends AppLocalizations { String get languageEnglish => 'English'; @override - String get refreshDirectory => 'Refresh Directory'; + String get refreshDirectory => 'Refresh Project'; @override String get back => 'Back'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 3eb5041..989d57a 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -18,7 +18,7 @@ class AppLocalizationsZh extends AppLocalizations { String get settings => '设置'; @override - String get fileDirectory => '文件目录'; + String get fileDirectory => '项目'; @override String get undo => '撤销'; @@ -30,16 +30,19 @@ class AppLocalizationsZh extends AppLocalizations { String get save => '保存'; @override - String get openFileDirectory => '打开文件目录'; + String get openFileDirectory => '打开项目'; @override - String get viewFileDirectoryHistory => '查看文件目录历史'; + String get openProjectPrompt => '请点击上方按钮打开项目'; + + @override + String get viewProjectHistory => '查看项目历史'; @override String get more => '更多'; @override - String get noOpenDirectory => '当前未打开文件目录'; + String get noOpenDirectory => '当前未打开项目'; @override String get noOpenFile => '当前未打开文件'; @@ -51,7 +54,7 @@ class AppLocalizationsZh extends AppLocalizations { String get unknownDirectory => '未知目录'; @override - String get historyFileDirectories => '历史文件目录'; + String get projectHistory => '历史项目'; @override String get noHistory => '暂无历史记录'; @@ -83,6 +86,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get close => '关闭'; + @override + String get closeAllTabs => '关闭所有标签'; + + @override + String get closeProject => '关闭当前项目'; + @override String get gotIt => '知道了'; @@ -243,6 +252,33 @@ class AppLocalizationsZh extends AppLocalizations { @override String get wordWrapSubtitle => '长代码行超出边界时自动折行'; + @override + String get virtualKeyboard => '辅助小键盘'; + + @override + String get virtualKeyboardSubtitle => '在代码编辑区底部显示辅助符号与快捷键'; + + @override + String get editVirtualKeyboardConfig => '编辑键盘配置'; + + @override + String get editVirtualKeyboardConfigSubtitle => '自定义小键盘按键布局与快捷键 (JSON)'; + + @override + String get virtualKeyboardDialogTitle => '小键盘配置 (JSON)'; + + @override + String get resetDefault => '恢复默认'; + + @override + String get configFormatError => '配置格式错误'; + + @override + String get configSavedSuccess => '小键盘配置已保存'; + + @override + String get formatJson => '格式化'; + @override String get languageSection => '语言'; @@ -262,7 +298,7 @@ class AppLocalizationsZh extends AppLocalizations { String get languageEnglish => 'English'; @override - String get refreshDirectory => '刷新目录'; + String get refreshDirectory => '刷新项目'; @override String get back => '返回'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index f60bc9d..9bcf7cb 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3,18 +3,19 @@ "appTitle": "代码编辑器", "run": "运行", "settings": "设置", - "fileDirectory": "文件目录", + "fileDirectory": "项目", "undo": "撤销", "redo": "重做", "save": "保存", - "openFileDirectory": "打开文件目录", - "viewFileDirectoryHistory": "查看文件目录历史", + "openFileDirectory": "打开项目", + "openProjectPrompt": "请点击上方按钮打开项目", + "viewProjectHistory": "查看项目历史", "more": "更多", - "noOpenDirectory": "当前未打开文件目录", + "noOpenDirectory": "当前未打开项目", "noOpenFile": "当前未打开文件", "unnamed": "未命名", "unknownDirectory": "未知目录", - "historyFileDirectories": "历史文件目录", + "projectHistory": "历史项目", "noHistory": "暂无历史记录", "deleteThisHistory": "删除此记录", "deleteHistoryTitle": "删除历史记录", @@ -25,6 +26,8 @@ "cancel": "取消", "delete": "删除", "close": "关闭", + "closeAllTabs": "关闭所有标签", + "closeProject": "关闭当前项目", "gotIt": "知道了", "done": "完成", "newFile": "新建文件", @@ -73,13 +76,22 @@ "fontSizeDialogTitle": "代码字号", "wordWrap": "自动换行", "wordWrapSubtitle": "长代码行超出边界时自动折行", + "virtualKeyboard": "辅助小键盘", + "virtualKeyboardSubtitle": "在代码编辑区底部显示辅助符号与快捷键", + "editVirtualKeyboardConfig": "编辑键盘配置", + "editVirtualKeyboardConfigSubtitle": "自定义小键盘按键布局与快捷键 (JSON)", + "virtualKeyboardDialogTitle": "小键盘配置 (JSON)", + "resetDefault": "恢复默认", + "configFormatError": "配置格式错误", + "configSavedSuccess": "小键盘配置已保存", + "formatJson": "格式化", "languageSection": "语言", "appLanguage": "应用语言", "selectLanguage": "选择应用语言", "languageFollowSystem": "跟随系统", "languageChinese": "简体中文", "languageEnglish": "English", - "refreshDirectory": "刷新目录", + "refreshDirectory": "刷新项目", "back": "返回", "darkLabel": "暗色", "lightLabel": "浅色", diff --git a/lib/main.dart b/lib/main.dart index c356844..d73f865 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,4 @@ import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/providers/editor_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'; @@ -25,11 +24,6 @@ class MyApp extends StatelessWidget { update: (_, project, tab) => (tab ?? (TabProvider()..init()))..bindProjectProvider(project), ), - ChangeNotifierProxyProvider3( - create: (ctx) => EditorProvider(), - update: (_, settings, project, tab, editor) => - EditorProvider(settings: settings, project: project, tab: tab), - ), ], child: Consumer( builder: (context, settings, child) { diff --git a/lib/models/editor_tab_item.dart b/lib/models/editor_tab_item.dart index 0977f8e..d56be9f 100644 --- a/lib/models/editor_tab_item.dart +++ b/lib/models/editor_tab_item.dart @@ -29,14 +29,14 @@ class EditorTabItem { /// 当存在同名文件标签时显示相对项目路径,否则优先显示简短文件名 String getDisplayName(List allTabs, String? rootPath) { final hasDuplicateName = allTabs.where((tab) => tab.name == name).length > 1; - if (hasDuplicateName) { - if (rootPath != null && rootPath.isNotEmpty) { + if(hasDuplicateName) { + if(rootPath != null && rootPath.isNotEmpty) { try { - if (p.isWithin(rootPath, path)) { + if(p.isWithin(rootPath, path)) { final rel = p.relative(path, from: rootPath); return rel; } - } catch (_) {} + }catch (_) {} } return path; } diff --git a/lib/models/editor_theme.dart b/lib/models/editor_theme.dart index f82b91f..528c6c7 100644 --- a/lib/models/editor_theme.dart +++ b/lib/models/editor_theme.dart @@ -168,7 +168,7 @@ class EditorTheme { /// 根据 ID 查找主题,若不存在则回退至默认主题 static EditorTheme fromId(String? id) { - if (id == null || id.isEmpty) return atomOneDark; + if(id == null || id.isEmpty) return atomOneDark; return presets.firstWhere( (theme) => theme.id == id, orElse: () => atomOneDark, diff --git a/lib/models/file_item.dart b/lib/models/file_item.dart index 88fc6bc..41ee9ea 100644 --- a/lib/models/file_item.dart +++ b/lib/models/file_item.dart @@ -1,50 +1,50 @@ -import 'package:path/path.dart' as p; - -class FileItem { - final String fullPath; - final String name; - final String? relativePath; - final bool isDirectory; - List children; - final int depth; - bool isOpen; - - FileItem({ - required String path, - String? name, - this.relativePath, - this.isDirectory = false, - List? children, - this.depth = 0, - this.isOpen = false, - }) : fullPath = p.normalize(path), - name = name ?? p.basename(path), - children = children ?? []; - - /// 完整物理绝对路径别名(完全兼容旧代码) - String get path => fullPath; - - /// 文件扩展名(含前导点,如 '.dart'、'.json';文件夹或无扩展名返回 '') - String get extension => isDirectory ? '' : p.extension(fullPath).toLowerCase(); - - /// 不带扩展名的文件名(如 'main') - String get nameWithoutExtension => - isDirectory ? name : p.basenameWithoutExtension(fullPath); - - /// 优先展示相对路径;若无相对路径则展示纯文件名 - String get displayPath => relativePath ?? name; - - /// 获取相对于指定 rootPath 的相对路径(优先使用已有相对路径,跨盘或无项目安全回退) - String getRelativePath([String? fromRoot]) { - if (relativePath != null && (fromRoot == null || fromRoot.isEmpty)) { - return relativePath!; - } - final root = fromRoot; - if (root == null || root.trim().isEmpty) return name; - try { - return p.relative(fullPath, from: root); - } catch (_) { - return fullPath; - } - } -} \ No newline at end of file +import 'package:path/path.dart' as p; + +class FileItem { + final String fullPath; + final String name; + final String? relativePath; + final bool isDirectory; + List children; + final int depth; + bool isOpen; + + FileItem({ + required String path, + String? name, + this.relativePath, + this.isDirectory = false, + List? children, + this.depth = 0, + this.isOpen = false, + }) : fullPath = p.normalize(path), + name = name ?? p.basename(path), + children = children ?? []; + + /// 完整物理绝对路径别名(完全兼容旧代码) + String get path => fullPath; + + /// 文件扩展名(含前导点,如 '.dart'、'.json';文件夹或无扩展名返回 '') + String get extension => isDirectory ? '' : p.extension(fullPath).toLowerCase(); + + /// 不带扩展名的文件名(如 'main') + String get nameWithoutExtension => + isDirectory ? name : p.basenameWithoutExtension(fullPath); + + /// 优先展示相对路径;若无相对路径则展示纯文件名 + String get displayPath => relativePath ?? name; + + /// 获取相对于指定 rootPath 的相对路径(优先使用已有相对路径,跨盘或无项目安全回退) + String getRelativePath([String? fromRoot]) { + if(relativePath != null && (fromRoot == null || fromRoot.isEmpty)) { + return relativePath!; + } + final root = fromRoot; + if(root == null || root.trim().isEmpty) return name; + try { + return p.relative(fullPath, from: root); + }catch (_) { + return fullPath; + } + } +} diff --git a/lib/models/file_directory_history.dart b/lib/models/project_history.dart similarity index 65% rename from lib/models/file_directory_history.dart rename to lib/models/project_history.dart index 8466ac5..29bc3d1 100644 --- a/lib/models/file_directory_history.dart +++ b/lib/models/project_history.dart @@ -1,12 +1,12 @@ import 'dart:convert'; -class FileDirectoryHistory { - final String? rootPath; - final String? lastOpenedFilePath; - final List openDirectoryPaths; - final List openFilePaths; +class ProjectHistory { + final String? rootPath; //项目根绝对路径 + final String? lastOpenedFilePath; //上一次打开的文件绝对路径 + final List openDirectoryPaths; //在文件树中打开的所有文件夹的绝对路径 + final List openFilePaths; //存在于编辑区的所有文件的绝对路径 - const FileDirectoryHistory({ + const ProjectHistory({ required this.rootPath, required this.lastOpenedFilePath, this.openDirectoryPaths = const [], @@ -20,7 +20,7 @@ class FileDirectoryHistory { 'openFilePaths': openFilePaths, }; - factory FileDirectoryHistory.fromMap(Map map) { + factory ProjectHistory.fromMap(Map map) { final rawOpenFilePaths = map['openFilePaths'] as List?; final lastFile = map['lastOpenedFilePath'] as String?; List openFiles; @@ -32,7 +32,7 @@ class FileDirectoryHistory { openFiles = const []; } - return FileDirectoryHistory( + return ProjectHistory( rootPath: map['rootPath'] as String?, lastOpenedFilePath: lastFile, openDirectoryPaths: (map['openDirectoryPaths'] as List?) @@ -44,13 +44,13 @@ class FileDirectoryHistory { } String toJson() => jsonEncode(toMap()); - factory FileDirectoryHistory.fromJson(String source) { + factory ProjectHistory.fromJson(String source) { try { final decoded = jsonDecode(source); if (decoded is Map) { - return FileDirectoryHistory.fromMap(Map.from(decoded)); + return ProjectHistory.fromMap(Map.from(decoded)); } } catch (_) {} - return const FileDirectoryHistory(rootPath: null, lastOpenedFilePath: null); + return const ProjectHistory(rootPath: null, lastOpenedFilePath: null); } } \ No newline at end of file diff --git a/lib/models/virtual_keyboard_config.dart b/lib/models/virtual_keyboard_config.dart new file mode 100644 index 0000000..5907a22 --- /dev/null +++ b/lib/models/virtual_keyboard_config.dart @@ -0,0 +1,341 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; + +/// 内置常量图标映射辅助类 +class KeyboardIconHelper { + static const Map _icons = { + 'undo': Icons.undo, + 'redo': Icons.redo, + 'tab': Icons.keyboard_tab, + 'arrow_left': Icons.arrow_back, + 'arrow_right': Icons.arrow_forward, + 'arrow_up': Icons.arrow_upward, + 'arrow_down': Icons.arrow_downward, + 'home': Icons.vertical_align_top, + 'end': Icons.vertical_align_bottom, + 'backspace': Icons.backspace_outlined, + 'delete': Icons.delete_outline, + 'copy': Icons.copy, + 'cut': Icons.content_cut, + 'paste': Icons.content_paste, + 'save': Icons.save_outlined, + 'search': Icons.search, + 'keyboard_hide': Icons.keyboard_hide_outlined, + }; + + /// 根据 icon 字符串获取对应的 IconData,不存在或为空时返回 null + static IconData? getIcon(String? iconKey) { + if (iconKey == null || iconKey.trim().isEmpty) return null; + return _icons[iconKey.trim().toLowerCase()]; + } + + /// 所有支持的图标名称列表(方便用户配置或提示) + static List get supportedIconKeys => _icons.keys.toList(); +} + +/// 小键盘单个按键数据模型 +class KeyboardKeyItem { + /// 显示文本(当 icon 为空或不存在时渲染) + final String label; + + /// 内置图标常量名称,非空且在内置库存在时优先渲染图标 + final String? icon; + + /// 动作类型: + /// - 'input': 普通文本输入(默认) + /// - 'pair': 括号/引号等成对符号,支持选区包裹与光标偏移 + /// - 'command': 编辑器动作命令,例如 'cursor_left', 'tab', 'undo' 等 + final String action; + + /// 动作附带值(输入的文本或命令名称) + final String value; + + /// 光标插入后的相对偏移(如 pair \"()\" 插入后光标向左移动 1 位,则为 -1) + final int cursorOffset; + + const KeyboardKeyItem({ + required this.label, + this.icon, + this.action = 'input', + required this.value, + this.cursorOffset = 0, + }); + + /// 从 JSON 数据中解析按键: + /// - 若为 String:严格转换为 input 动作,label 和 value 为该字符串,绝对不做额外猜测! + /// - 若为 Map:读取相应字段。 + factory KeyboardKeyItem.fromJson(dynamic json) { + if (json is String) { + return KeyboardKeyItem( + label: json, + value: json, + action: 'input', + cursorOffset: 0, + ); + } + if (json is Map) { + final label = json['label']?.toString() ?? json['value']?.toString() ?? ''; + final value = json['value']?.toString() ?? label; + final action = json['action']?.toString() ?? 'input'; + final icon = json['icon']?.toString(); + final cursorOffset = (json['cursorOffset'] as num?)?.toInt() ?? 0; + return KeyboardKeyItem( + label: label, + icon: icon, + action: action, + value: value, + cursorOffset: cursorOffset, + ); + } + return const KeyboardKeyItem(label: '', value: ''); + } + + Map toJson() { + final map = { + 'label': label, + 'value': value, + 'action': action, + }; + if (icon != null && icon!.isNotEmpty) { + map['icon'] = icon; + } + if (cursorOffset != 0) { + map['cursorOffset'] = cursorOffset; + } + return map; + } +} + +/// 小键盘单页数据模型 +class KeyboardPageItem { + /// 每行格子数(页面宽度等分为 count 份) + final int count; + + /// 该页的所有行按键,每行是一个按键列表 + final List> keys; + + const KeyboardPageItem({ + required this.count, + required this.keys, + }); + + factory KeyboardPageItem.fromJson(Map json) { + final count = (json['count'] as num?)?.toInt() ?? 6; + final rawKeys = json['keys'] as List? ?? []; + final List> parsedKeys = []; + + for (final row in rawKeys) { + if (row is List) { + parsedKeys.add(row.map((k) => KeyboardKeyItem.fromJson(k)).toList()); + } + } + + return KeyboardPageItem( + count: count > 0 ? count : 6, + keys: parsedKeys, + ); + } + + Map toJson() { + return { + 'count': count, + 'keys': keys.map((row) => row.map((k) => k.toJson()).toList()).toList(), + }; + } +} + +/// 完整虚拟键盘配置模型 +class VirtualKeyboardConfig { + final List pages; + + const VirtualKeyboardConfig({ + required this.pages, + }); + + factory VirtualKeyboardConfig.fromJson(Map json) { + final rawPages = json['pages'] as List? ?? []; + final List parsedPages = []; + + for (final p in rawPages) { + if (p is Map) { + parsedPages.add(KeyboardPageItem.fromJson(p)); + } + } + + return VirtualKeyboardConfig( + pages: parsedPages.isNotEmpty ? parsedPages : _defaultConfig().pages, + ); + } + + Map toJson() { + return { + 'pages': pages.map((p) => p.toJson()).toList(), + }; + } + + /// 校验 JSON 文本合法性,若合法返回 null,若非法返回具体错误描述 + static String? validateJson(String jsonStr) { + final trimmed = jsonStr.trim(); + if (trimmed.isEmpty) { + return '配置内容不能为空'; + } + + dynamic decoded; + try { + decoded = jsonDecode(jsonStr); + } on FormatException catch (e) { + String locationStr = ''; + if (e.offset != null && e.offset! >= 0 && e.offset! <= jsonStr.length) { + int line = 1; + int column = 1; + for (int i = 0; i < e.offset!; i++) { + if (jsonStr[i] == '\n') { + line++; + column = 1; + } else { + column++; + } + } + locationStr = ' (第 $line 行, 第 $column 列)'; + } + return 'JSON 语法错误: ${e.message}$locationStr'; + } catch (e) { + return 'JSON 解析失败: $e'; + } + + if (decoded is! Map) { + return '配置根节点必须是 JSON 对象 (以 {} 包裹)'; + } + + if (!decoded.containsKey('pages')) { + return '根节点缺少必需的 "pages" 列表字段'; + } + + final pages = decoded['pages']; + if (pages is! List) { + return '"pages" 字段必须是一个数组 (List)'; + } + + if (pages.isEmpty) { + return '"pages" 至少需要包含 1 个页面配置'; + } + + for (int pIdx = 0; pIdx < pages.length; pIdx++) { + final page = pages[pIdx]; + final pageNum = pIdx + 1; + if (page is! Map) { + return '第 $pageNum 页必须是一个 JSON 对象'; + } + + if (!page.containsKey('count')) { + return '第 $pageNum 页缺少必需的 "count" 字段'; + } + + final count = page['count']; + if (count is! int || count <= 0) { + return '第 $pageNum 页的 "count" 必须为大于 0 的正整数'; + } + + if (!page.containsKey('keys')) { + return '第 $pageNum 页缺少必需的 "keys" 字段'; + } + + final keys = page['keys']; + if (keys is! List) { + return '第 $pageNum 页的 "keys" 必须是一个数组'; + } + + for (int rIdx = 0; rIdx < keys.length; rIdx++) { + final row = keys[rIdx]; + final rowNum = rIdx + 1; + if (row is! List) { + return '第 $pageNum 页第 $rowNum 行必须是一个按键数组'; + } + + for (int kIdx = 0; kIdx < row.length; kIdx++) { + final key = row[kIdx]; + final keyNum = kIdx + 1; + if (key is String) { + // 纯文本是完全合法的 + continue; + } else if (key is Map) { + // 对象形式必须至少有 label 或 value + final hasLabel = key.containsKey('label') && key['label'] != null; + final hasValue = key.containsKey('value') && key['value'] != null; + final hasIcon = key.containsKey('icon') && key['icon'] != null; + if (!hasLabel && !hasValue && !hasIcon) { + return '第 $pageNum 页第 $rowNum 行第 $keyNum 个按键缺少 label、value 或 icon 属性'; + } + if (key.containsKey('cursorOffset') && key['cursorOffset'] is! int) { + return '第 $pageNum 页第 $rowNum 行第 $keyNum 个按键的 "cursorOffset" 必须为整数'; + } + } else { + return '第 $pageNum 页第 $rowNum 行第 $keyNum 个按键类型错误,只能是文本字符串或对象'; + } + } + } + } + + return null; + } + + /// 默认配置预设 + static VirtualKeyboardConfig defaultConfiguration() => _defaultConfig(); + + static VirtualKeyboardConfig _defaultConfig() { + return const VirtualKeyboardConfig( + pages: [ + // Page 1: 常用标点与成对符号 (每行 6 格) + KeyboardPageItem( + count: 6, + keys: [ + [ + KeyboardKeyItem(label: 'Tab', icon: 'tab', action: 'command', value: 'tab'), + KeyboardKeyItem(label: '(', action: 'pair', value: '()', cursorOffset: -1), + KeyboardKeyItem(label: ')', action: 'input', value: ')'), + KeyboardKeyItem(label: '{', action: 'pair', value: '{}', cursorOffset: -1), + KeyboardKeyItem(label: '}', action: 'input', value: '}'), + KeyboardKeyItem(label: ';', action: 'input', value: ';'), + ], + [ + KeyboardKeyItem(label: '<-', icon: 'arrow_left', action: 'command', value: 'cursor_left'), + KeyboardKeyItem(label: '->', icon: 'arrow_right', action: 'command', value: 'cursor_right'), + KeyboardKeyItem(label: '[', action: 'pair', value: '[]', cursorOffset: -1), + KeyboardKeyItem(label: ']', action: 'input', value: ']'), + KeyboardKeyItem(label: '"', action: 'pair', value: '""', cursorOffset: -1), + KeyboardKeyItem(label: "'", action: 'pair', value: "''", cursorOffset: -1), + ], + ], + ), + // Page 2: 常用操作与运算符 (每行 6 格) + KeyboardPageItem( + count: 6, + keys: [ + [ + KeyboardKeyItem(label: '撤销', icon: 'undo', action: 'command', value: 'undo'), + KeyboardKeyItem(label: '重做', icon: 'redo', action: 'command', value: 'redo'), + KeyboardKeyItem(label: '=', action: 'input', value: '='), + KeyboardKeyItem(label: '+', action: 'input', value: '+'), + KeyboardKeyItem(label: '-', action: 'input', value: '-'), + KeyboardKeyItem(label: '*', action: 'input', value: '*'), + ], + [ + KeyboardKeyItem(label: '/', action: 'input', value: '/'), + KeyboardKeyItem(label: ':', action: 'input', value: ':'), + KeyboardKeyItem(label: ',', action: 'input', value: ','), + KeyboardKeyItem(label: '.', action: 'input', value: '.'), + KeyboardKeyItem(label: '!', action: 'input', value: '!'), + KeyboardKeyItem(label: '?', action: 'input', value: '?'), + ], + ], + ), + ], + ); + } + + /// 转换为格式化好的默认 JSON 字符串 + static String defaultJsonPretty() { + const encoder = JsonEncoder.withIndent(' '); + return encoder.convert(_defaultConfig().toJson()); + } +} diff --git a/lib/providers/editor_provider.dart b/lib/providers/editor_provider.dart deleted file mode 100644 index 9e0863d..0000000 --- a/lib/providers/editor_provider.dart +++ /dev/null @@ -1,111 +0,0 @@ -import 'package:code_editor/models/editor_tab_item.dart'; -import 'package:code_editor/models/editor_theme.dart'; -import 'package:code_editor/models/file_directory_history.dart'; -import 'package:code_editor/models/file_item.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:flutter/material.dart'; - -/// 组合门面 Provider,委托给 SettingsProvider, ProjectProvider, TabProvider, -/// 保持向下兼容性与测试透明度。 -class EditorProvider extends ChangeNotifier { - final SettingsProvider settingsProvider; - final ProjectProvider projectProvider; - final TabProvider tabProvider; - - EditorProvider({ - SettingsProvider? settings, - ProjectProvider? project, - TabProvider? tab, - }) : settingsProvider = settings ?? SettingsProvider(), - projectProvider = project ?? ProjectProvider(), - tabProvider = tab ?? TabProvider() { - tabProvider.bindProjectProvider(projectProvider); - settingsProvider.addListener(notifyListeners); - projectProvider.addListener(notifyListeners); - tabProvider.addListener(notifyListeners); - } - - @override - void dispose() { - settingsProvider.removeListener(notifyListeners); - projectProvider.removeListener(notifyListeners); - tabProvider.removeListener(notifyListeners); - super.dispose(); - } - - Future init() async { - await settingsProvider.init(); - await projectProvider.init(); - await tabProvider.init(); - } - - // =================== Settings Provider Getters & Methods =================== - EditorTheme get editorTheme => settingsProvider.editorTheme; - ThemeMode get appThemeMode => settingsProvider.appThemeMode; - double get fontSize => settingsProvider.fontSize; - bool get wordWrap => settingsProvider.wordWrap; - Locale? get locale => settingsProvider.locale; - - Future setEditorTheme(EditorTheme theme) => settingsProvider.setEditorTheme(theme); - Future setAppThemeMode(ThemeMode mode) => settingsProvider.setAppThemeMode(mode); - Future setFontSize(double size) => settingsProvider.setFontSize(size); - Future setWordWrap(bool wrap) => settingsProvider.setWordWrap(wrap); - Future setLocale(Locale? newLocale) => settingsProvider.setLocale(newLocale); - - // =================== Project Provider Getters & Methods =================== - FileDirectoryHistory get history => projectProvider.history; - String? get rootPath => projectProvider.rootPath; - List get openDirectoryPaths => projectProvider.openDirectoryPaths; - List get items => projectProvider.items; - bool get isLoading => projectProvider.isLoading; - FileItem? get cutItem => projectProvider.cutItem; - FileItem? get copiedItem => projectProvider.copiedItem; - bool get canPaste => projectProvider.canPaste; - - bool isItemCut(String path) => projectProvider.isItemCut(path); - Future openDirectory() => projectProvider.openDirectory(); - Future switchProject(FileDirectoryHistory selectedHistory) => projectProvider.switchProject(selectedHistory); - Future toggleDirectory(FileItem item, bool expanded) => projectProvider.toggleDirectory(item, expanded); - Future refreshTree() => projectProvider.refreshTree(); - void cut(FileItem item) => projectProvider.cut(item); - void copy(FileItem item) => projectProvider.copy(item); - Future paste(FileItem targetDir) => projectProvider.paste(targetDir); - Future createFile(String parentDir, String name) => projectProvider.createFile(parentDir, name); - Future createDirectory(String parentDir, String name) => projectProvider.createDirectory(parentDir, name); - Future rename(FileItem item, String newName) => projectProvider.rename(item, newName); - Future delete(FileItem item) => projectProvider.delete(item); - - @visibleForTesting - void setHistoryForTesting(FileDirectoryHistory history) { - // ignore: invalid_use_of_visible_for_testing_member - projectProvider.setHistoryForTesting(history); - } - - // =================== Tab Provider Getters & Methods =================== - List get openTabs => tabProvider.openTabs; - EditorTabItem? get activeTab => tabProvider.activeTab; - String? get currentFilePath => tabProvider.currentFilePath; - bool get isModified => tabProvider.isModified; - - bool isFileSelected(String path) => tabProvider.isFileSelected(path); - Future selectFile(FileItem item) => tabProvider.selectFile(item); - Future openFile(String path, {String? content}) => tabProvider.openFile(path, content: content); - Future closeTab(BuildContext context, int index) => tabProvider.closeTab(context, index); - Future reorderTabs(int oldIndex, int newIndex) => tabProvider.reorderTabs(oldIndex, newIndex); - Future saveTab(EditorTabItem tab) => tabProvider.saveTab(tab); - Future saveCurrentFile() => tabProvider.saveCurrentFile(); - Future saveAllFiles() => tabProvider.saveAllFiles(); - Future checkUnsavedChanges(BuildContext context) => tabProvider.checkUnsavedChanges(context); - void registerSaveHandler(Future Function()? handler) => tabProvider.registerSaveHandler(handler); - void setModified(bool modified) => tabProvider.setModified(modified); - void updateActiveTabContent(String content, {bool? isModified}) => - tabProvider.updateActiveTabContent(content, isModified: isModified); - - @visibleForTesting - void setOpenTabsForTesting(List tabs, {String? activePath}) { - // ignore: invalid_use_of_visible_for_testing_member - tabProvider.setOpenTabsForTesting(tabs, activePath: activePath); - } -} diff --git a/lib/providers/project_provider.dart b/lib/providers/project_provider.dart index 76c2e96..9234d8e 100644 --- a/lib/providers/project_provider.dart +++ b/lib/providers/project_provider.dart @@ -1,7 +1,7 @@ import 'dart:io'; -import 'package:code_editor/models/file_directory_history.dart'; +import 'package:code_editor/models/project_history.dart'; import 'package:code_editor/models/file_item.dart'; -import 'package:code_editor/services/file_directory_history_service.dart'; +import 'package:code_editor/services/project_history_service.dart'; import 'package:code_editor/services/file_service.dart'; import 'package:code_editor/services/file_watcher_service.dart'; import 'package:file_picker/file_picker.dart'; @@ -9,15 +9,22 @@ import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; class ProjectProvider extends ChangeNotifier { - FileDirectoryHistory _history = const FileDirectoryHistory( + //项目历史 + ProjectHistory _history = const ProjectHistory( rootPath: null, lastOpenedFilePath: null, ); + + //根目录的一级子文件目录 List _items = []; - bool _isLoading = false; + + //当前剪切复制的文件 FileItem? _cutItem; FileItem? _copiedItem; + //是否正在加载项目 + bool _isLoading = false; + // 跨 Provider 协同回调 void Function(String oldPath, String newPath)? onEntityRenamed; void Function(String deletedPath)? onEntityDeleted; @@ -25,7 +32,7 @@ class ProjectProvider extends ChangeNotifier { void Function(String modifiedPath)? onExternalFileModified; void Function(String deletedPath)? onExternalFileDeleted; - FileDirectoryHistory get history => _history; + ProjectHistory get history => _history; String? get rootPath => _history.rootPath; List get openDirectoryPaths => _history.openDirectoryPaths; List get items => _items; @@ -44,7 +51,7 @@ class ProjectProvider extends ChangeNotifier { } @visibleForTesting - void setHistoryForTesting(FileDirectoryHistory history) { + void setHistoryForTesting(ProjectHistory history) { _history = history; notifyListeners(); } @@ -55,13 +62,14 @@ class ProjectProvider extends ChangeNotifier { notifyListeners(); } + //从历史加载项目 Future _loadProjectFromHistory() async { _isLoading = true; notifyListeners(); try { - final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory(); - if (lastHistory == null) { + final lastHistory = await ProjectHistoryService.instance.getLastHistory(); + if(lastHistory == null) { _isLoading = false; notifyListeners(); return; @@ -84,7 +92,7 @@ class ProjectProvider extends ChangeNotifier { : []; _items = items; - _history = FileDirectoryHistory( + _history = ProjectHistory( rootPath: cleanPath, lastOpenedFilePath: lastHistory.lastOpenedFilePath, openDirectoryPaths: validOpenPaths, @@ -96,18 +104,19 @@ class ProjectProvider extends ChangeNotifier { // 通知外部(例如 TabProvider)同步标签页历史 onProjectChanged?.call(cleanPath, lastHistory.openFilePaths, lastHistory.lastOpenedFilePath); - } catch (e) { + }catch(e) { debugPrint('加载项目历史失败: $e'); - } finally { + }finally { _isLoading = false; notifyListeners(); } } + //打开新的项目 Future openDirectory() async { try { final String? selectedPath = await FilePicker.platform.getDirectoryPath(); - if (selectedPath == null || selectedPath.trim().isEmpty) { + if(selectedPath == null || selectedPath.trim().isEmpty) { return; } @@ -115,7 +124,7 @@ class ProjectProvider extends ChangeNotifier { final currentRoot = _history.rootPath != null ? p.normalize(_history.rootPath!) : null; final isSameRoot = currentRoot != null && cleanPath == currentRoot; - await FileDirectoryHistoryService.instance.recordHistory( + await ProjectHistoryService.instance.recordHistory( rootPath: cleanPath, lastOpenedFilePath: isSameRoot ? _history.lastOpenedFilePath : null, openDirectoryPaths: isSameRoot ? _history.openDirectoryPaths : const [], @@ -126,16 +135,17 @@ class ProjectProvider extends ChangeNotifier { _copiedItem = null; await _loadProjectFromHistory(); - } catch (e) { + }catch (e) { debugPrint('打开文件夹失败: $e'); } } - Future switchProject(FileDirectoryHistory selectedHistory) async { + //选择项目历史 + Future switchProject(ProjectHistory selectedHistory) async { final selectedRoot = selectedHistory.rootPath; - if (selectedRoot == null || selectedRoot.trim().isEmpty) return; + if(selectedRoot == null || selectedRoot.trim().isEmpty) return; - await FileDirectoryHistoryService.instance.recordHistory( + await ProjectHistoryService.instance.recordHistory( rootPath: selectedRoot, lastOpenedFilePath: selectedHistory.lastOpenedFilePath, openDirectoryPaths: selectedHistory.openDirectoryPaths, @@ -148,16 +158,31 @@ class ProjectProvider extends ChangeNotifier { await _loadProjectFromHistory(); } + /// 关闭当前项目 + Future closeProject() async { + _startWatcher(null); + _cutItem = null; + _copiedItem = null; + _items = []; + _history = const ProjectHistory( + rootPath: null, + lastOpenedFilePath: null, + ); + onProjectChanged?.call(null, const [], null); + notifyListeners(); + } + + //展开文件夹 Future toggleDirectory(FileItem item, bool expanded) async { final cleanPath = _history.rootPath; - if (cleanPath == null) return; + if(cleanPath == null) return; final updatedOpenPaths = List.from(_history.openDirectoryPaths); - if (expanded) { - if (!updatedOpenPaths.contains(item.path)) { + if(expanded) { + if(!updatedOpenPaths.contains(item.path)) { updatedOpenPaths.add(item.path); } - if (item.children.isEmpty) { + if(item.children.isEmpty) { final children = await FileService.instance.buildTree( item.path, depth: item.depth + 1, @@ -166,17 +191,17 @@ class ProjectProvider extends ChangeNotifier { item.children.clear(); item.children.addAll(children); } - } else { + }else { updatedOpenPaths.remove(item.path); } - await FileDirectoryHistoryService.instance.recordHistory( + await ProjectHistoryService.instance.recordHistory( rootPath: cleanPath, lastOpenedFilePath: _history.lastOpenedFilePath, openDirectoryPaths: updatedOpenPaths, openFilePaths: _history.openFilePaths, ); - _history = FileDirectoryHistory( + _history = ProjectHistory( rootPath: cleanPath, lastOpenedFilePath: _history.lastOpenedFilePath, openDirectoryPaths: updatedOpenPaths, @@ -187,7 +212,7 @@ class ProjectProvider extends ChangeNotifier { Future refreshTree() async { final currentRoot = _history.rootPath; - if (currentRoot == null || currentRoot.trim().isEmpty) return; + if(currentRoot == null || currentRoot.trim().isEmpty) return; try { final items = await FileService.instance.buildTree( @@ -196,11 +221,11 @@ class ProjectProvider extends ChangeNotifier { ); String? currentFile = _history.lastOpenedFilePath; - if (currentFile != null) { + if(currentFile != null) { final exists = await FileService.instance.entityExists(currentFile); - if (!exists) { + if(!exists) { currentFile = null; - await FileDirectoryHistoryService.instance.recordHistory( + await ProjectHistoryService.instance.recordHistory( rootPath: currentRoot, lastOpenedFilePath: null, openDirectoryPaths: _history.openDirectoryPaths, @@ -210,8 +235,8 @@ class ProjectProvider extends ChangeNotifier { } _items = items; - if (currentFile != _history.lastOpenedFilePath) { - _history = FileDirectoryHistory( + if(currentFile != _history.lastOpenedFilePath) { + _history = ProjectHistory( rootPath: currentRoot, lastOpenedFilePath: currentFile, openDirectoryPaths: _history.openDirectoryPaths, @@ -219,7 +244,7 @@ class ProjectProvider extends ChangeNotifier { ); } notifyListeners(); - } catch (e) { + }catch (e) { debugPrint('刷新目录树失败: $e'); } } @@ -237,14 +262,14 @@ class ProjectProvider extends ChangeNotifier { } Future paste(FileItem targetDir) async { - if (!targetDir.isDirectory) return; + if(!targetDir.isDirectory) return; - if (_cutItem != null) { + if(_cutItem != null) { final source = _cutItem!; await FileService.instance.moveEntity(source.path, targetDir.path); _cutItem = null; await refreshTree(); - } else if (_copiedItem != null) { + }else if (_copiedItem != null) { final source = _copiedItem!; await FileService.instance.copyEntity(source.path, targetDir.path); await refreshTree(); @@ -283,7 +308,7 @@ class ProjectProvider extends ChangeNotifier { } void _startWatcher(String? rootPath) { - if (rootPath == null || rootPath.isEmpty) { + if(rootPath == null || rootPath.isEmpty) { FileWatcherService.instance.stopWatching(); return; } @@ -296,15 +321,15 @@ class ProjectProvider extends ChangeNotifier { void _onFileSystemEvents(List events) { bool needRefreshTree = false; - for (final event in events) { + for(final event in events) { final normalizedPath = p.normalize(event.path); - if (event is FileSystemCreateEvent) { + if(event is FileSystemCreateEvent) { needRefreshTree = true; - } else if (event is FileSystemDeleteEvent) { + }else if (event is FileSystemDeleteEvent) { needRefreshTree = true; onExternalFileDeleted?.call(normalizedPath); - } else if (event is FileSystemMoveEvent) { + }else if (event is FileSystemMoveEvent) { needRefreshTree = true; final dest = event.destination; if (dest != null) { @@ -312,7 +337,7 @@ class ProjectProvider extends ChangeNotifier { } else { onExternalFileDeleted?.call(normalizedPath); } - } else if (event is FileSystemModifyEvent) { + }else if (event is FileSystemModifyEvent) { if (event.isDirectory) { needRefreshTree = true; } else { @@ -321,7 +346,7 @@ class ProjectProvider extends ChangeNotifier { } } - if (needRefreshTree) { + if(needRefreshTree) { refreshTree(); } } diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart index 5327953..fd5e84f 100644 --- a/lib/providers/settings_provider.dart +++ b/lib/providers/settings_provider.dart @@ -1,24 +1,40 @@ +import 'dart:convert'; import 'package:code_editor/models/editor_theme.dart'; +import 'package:code_editor/models/virtual_keyboard_config.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SettingsProvider extends ChangeNotifier { - static const String _keyEditorTheme = 'editor_theme_id'; - static const String _keyAppThemeMode = 'app_theme_mode'; - static const String _keyEditorFontSize = 'editor_font_size'; - static const String _keyWordWrap = 'editor_word_wrap'; + //外观 + static const String _keyAppThemeMode = 'app_theme_mode'; //应用主题 + + //编辑区 + static const String _keyEditorTheme = 'editor_theme_id'; //代码主题 + static const String _keyEditorFontSize = 'editor_font_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 _keyAppLocale = 'app_locale'; - EditorTheme _editorTheme = EditorTheme.atomOneDark; ThemeMode _appThemeMode = ThemeMode.system; + EditorTheme _editorTheme = EditorTheme.atomOneDark; double _fontSize = 14.0; bool _wordWrap = true; + bool _enableVirtualKeyboard = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS; + String _virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty(); + VirtualKeyboardConfig _virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration(); Locale? _locale; - EditorTheme get editorTheme => _editorTheme; ThemeMode get appThemeMode => _appThemeMode; + EditorTheme get editorTheme => _editorTheme; double get fontSize => _fontSize; bool get wordWrap => _wordWrap; + bool get enableVirtualKeyboard => _enableVirtualKeyboard; + String get virtualKeyboardConfigJson => _virtualKeyboardConfigJson; + VirtualKeyboardConfig get virtualKeyboardConfig => _virtualKeyboardConfig; Locale? get locale => _locale; Future init() async { @@ -28,90 +44,150 @@ class SettingsProvider extends ChangeNotifier { Future _loadSettings() async { try { final prefs = await SharedPreferences.getInstance(); - final themeId = prefs.getString(_keyEditorTheme); - _editorTheme = EditorTheme.fromId(themeId); + //设置外观 final themeModeName = prefs.getString(_keyAppThemeMode); - if (themeModeName != null) { + if(themeModeName != null) { _appThemeMode = ThemeMode.values.firstWhere( (e) => e.name == themeModeName, orElse: () => ThemeMode.system, ); } + //设置编辑区 + final themeId = prefs.getString(_keyEditorTheme); + _editorTheme = EditorTheme.fromId(themeId); + + final savedFontSize = prefs.getDouble(_keyEditorFontSize); - if (savedFontSize != null && savedFontSize >= 10 && savedFontSize <= 32) { + if(savedFontSize != null && savedFontSize >= 10 && savedFontSize <= 32) { _fontSize = savedFontSize; } final savedWordWrap = prefs.getBool(_keyWordWrap); - if (savedWordWrap != null) { + if(savedWordWrap != null) { _wordWrap = savedWordWrap; } + final savedEnableVirtualKeyboard = prefs.getBool(_keyEnableVirtualKeyboard); + if (savedEnableVirtualKeyboard != null) { + _enableVirtualKeyboard = savedEnableVirtualKeyboard; + } + + final savedKeyboardConfig = prefs.getString(_keyVirtualKeyboardConfig); + if (savedKeyboardConfig != null && savedKeyboardConfig.trim().isNotEmpty) { + final err = VirtualKeyboardConfig.validateJson(savedKeyboardConfig); + if (err == null) { + try { + final decoded = jsonDecode(savedKeyboardConfig) as Map; + _virtualKeyboardConfig = VirtualKeyboardConfig.fromJson(decoded); + _virtualKeyboardConfigJson = savedKeyboardConfig; + } catch (_) {} + } + } + + //设置语言 final savedLocale = prefs.getString(_keyAppLocale); - if (savedLocale != null && savedLocale.isNotEmpty) { + if(savedLocale != null && savedLocale.isNotEmpty) { _locale = Locale(savedLocale); } else { - _locale = null; // null 表示跟随系统 + _locale = null; } notifyListeners(); - } catch (_) {} - } - - Future setEditorTheme(EditorTheme theme) async { - if (_editorTheme.id == theme.id) return; - _editorTheme = theme; - notifyListeners(); - try { - final prefs = await SharedPreferences.getInstance(); - await prefs.setString(_keyEditorTheme, theme.id); - } catch (_) {} + }catch (_) {} } Future setAppThemeMode(ThemeMode mode) async { - if (_appThemeMode == mode) return; + if(_appThemeMode == mode) return; _appThemeMode = mode; notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_keyAppThemeMode, mode.name); - } catch (_) {} + }catch (_) {} } + Future setEditorTheme(EditorTheme theme) async { + if(_editorTheme.id == theme.id) return; + _editorTheme = theme; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyEditorTheme, theme.id); + }catch(_) {} + } + Future setFontSize(double size) async { final clamped = size.clamp(10.0, 30.0); - if (_fontSize == clamped) return; + if(_fontSize == clamped) return; _fontSize = clamped; notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.setDouble(_keyEditorFontSize, clamped); - } catch (_) {} + }catch (_) {} } Future setWordWrap(bool wrap) async { - if (_wordWrap == wrap) return; + if(_wordWrap == wrap) return; _wordWrap = wrap; notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_keyWordWrap, wrap); + }catch (_) {} + } + + Future setEnableVirtualKeyboard(bool enable) async { + if (_enableVirtualKeyboard == enable) return; + _enableVirtualKeyboard = enable; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyEnableVirtualKeyboard, enable); + } catch (_) {} + } + + Future setVirtualKeyboardConfig(String jsonStr) async { + final err = VirtualKeyboardConfig.validateJson(jsonStr); + if (err != null) { + return false; + } + try { + final decoded = jsonDecode(jsonStr) as Map; + _virtualKeyboardConfig = VirtualKeyboardConfig.fromJson(decoded); + _virtualKeyboardConfigJson = jsonStr; + notifyListeners(); + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyVirtualKeyboardConfig, jsonStr); + return true; + } catch (_) { + return false; + } + } + + Future resetVirtualKeyboardConfig() async { + _virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration(); + _virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty(); + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_keyVirtualKeyboardConfig); } catch (_) {} } Future setLocale(Locale? newLocale) async { - if (_locale == newLocale) return; + if(_locale == newLocale) return; _locale = newLocale; notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); - if (newLocale == null) { + if(newLocale == null) { await prefs.remove(_keyAppLocale); } else { await prefs.setString(_keyAppLocale, newLocale.languageCode); } - } catch (_) {} + }catch (_) {} } } diff --git a/lib/providers/tab_provider.dart b/lib/providers/tab_provider.dart index 0780122..341d13b 100644 --- a/lib/providers/tab_provider.dart +++ b/lib/providers/tab_provider.dart @@ -2,7 +2,7 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/editor_tab_item.dart'; import 'package:code_editor/models/file_item.dart'; import 'package:code_editor/providers/project_provider.dart'; -import 'package:code_editor/services/file_directory_history_service.dart'; +import 'package:code_editor/services/project_history_service.dart'; import 'package:code_editor/services/file_service.dart'; import 'package:code_editor/services/file_watcher_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; @@ -48,7 +48,7 @@ class TabProvider extends ChangeNotifier { Future _loadTabsFromHistory() async { try { - final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory(); + final lastHistory = await ProjectHistoryService.instance.getLastHistory(); if (lastHistory == null) return; await handleProjectChanged( lastHistory.rootPath, @@ -237,7 +237,7 @@ class TabProvider extends ChangeNotifier { final root = _projectProvider?.rootPath; if (root != null) { final openPaths = _openTabs.map((t) => t.path).toList(); - await FileDirectoryHistoryService.instance.recordHistory( + await ProjectHistoryService.instance.recordHistory( rootPath: root, lastOpenedFilePath: _activeFilePath, openDirectoryPaths: _projectProvider?.openDirectoryPaths ?? const [], @@ -348,7 +348,6 @@ class TabProvider extends ChangeNotifier { if (!saved) return false; break; case SavePromptResult.discard: - tab.isModified = false; break; case SavePromptResult.cancel: return false; @@ -374,6 +373,20 @@ class TabProvider extends ChangeNotifier { return true; } + /// 关闭所有打开的标签页 + Future closeAllTabs(BuildContext context) async { + if (_openTabs.isEmpty) return true; + final canProceed = await checkUnsavedChanges(context); + if (!canProceed) return false; + + _openTabs.clear(); + _activeFilePath = null; + _isModified = false; + await _persistTabsHistory(); + notifyListeners(); + return true; + } + Future reorderTabs(int oldIndex, int newIndex) async { if (oldIndex < 0 || oldIndex >= _openTabs.length) return; if (newIndex < 0 || newIndex >= _openTabs.length) return; @@ -456,11 +469,6 @@ class TabProvider extends ChangeNotifier { return saved; case SavePromptResult.discard: - for (final tab in _openTabs) { - tab.isModified = false; - } - _isModified = false; - notifyListeners(); return true; case SavePromptResult.cancel: diff --git a/lib/services/file_service.dart b/lib/services/file_service.dart index c3b58bd..7d724d2 100644 --- a/lib/services/file_service.dart +++ b/lib/services/file_service.dart @@ -15,7 +15,7 @@ class FileService { List openDirectoryPaths = const [], int maxDepth = 10, }) async { - if (depth > maxDepth) { + if(depth > maxDepth) { return []; } @@ -23,10 +23,10 @@ class FileService { final rootDir = Directory(dirPath); try { - if (!await rootDir.exists()) { + if(!await rootDir.exists()) { return []; } - } catch (_) { + }catch (_) { return []; } @@ -42,7 +42,7 @@ class FileService { final normalizedOpenPaths = openDirectoryPaths.map((e) => p.normalize(e)).toSet(); - for (var entity in entities) { + for(var entity in entities) { try { final fileName = p.basename(entity.path); if (fileName.startsWith('.')) continue; @@ -51,13 +51,13 @@ class FileService { String? relativePath; try { relativePath = p.relative(entityPath, from: effectiveRoot); - } catch (_) {} + }catch (_) {} - if (entity is Directory) { + if(entity is Directory) { final isDirOpen = normalizedOpenPaths.contains(entityPath); List children = []; // 只有当该子目录确实被用户展开时,才递归加载其子项,避免无限制深度扫描 - if (isDirOpen) { + if(isDirOpen) { children = await buildTree( entityPath, rootPath: effectiveRoot, @@ -75,7 +75,7 @@ class FileService { depth: depth, isOpen: isDirOpen, )); - } else if (entity is File) { + }else if (entity is File) { items.add(FileItem( name: fileName, path: entityPath, @@ -84,7 +84,7 @@ class FileService { depth: depth, )); } - } catch (_) { + }catch (_) { // 单个文件/目录异常跳过,防止整体崩溃 continue; } @@ -95,14 +95,14 @@ class FileService { if (!a.isDirectory && b.isDirectory) return 1; return a.name.toLowerCase().compareTo(b.name.toLowerCase()); }); - } catch (_) { + }catch (_) { // 扫描顶层目录出错,安全返回已扫描项 } return items; } - // 常见的二进制文件扩展名(不适合在代码文本编辑器中打开) + //二进制文件扩展名 static const Set _binaryExtensions = { '.exe', '.dll', '.bin', '.so', '.dylib', '.class', '.pyc', '.zip', '.tar', '.gz', '.7z', '.rar', '.iso', '.apk', '.aab', @@ -119,17 +119,17 @@ class FileService { Future readFileContent(String path) async { final file = File(path); - if (!await file.exists()) { + if(!await file.exists()) { throw FileSystemException('文件不存在或已被移除', path); } final ext = p.extension(path).toLowerCase(); - if (_binaryExtensions.contains(ext)) { + if(_binaryExtensions.contains(ext)) { throw const FileSystemException('此文件是二进制可执行文件或多媒体文件,不支持作为文本编辑'); } final length = await file.length(); - if (length > maxTextFileSize) { + if(length > maxTextFileSize) { final sizeMb = (length / (1024 * 1024)).toStringAsFixed(1); throw FileSystemException('文件过大 (${sizeMb}MB),超过了编辑器限制 (2MB),暂不支持直接打开'); } @@ -140,19 +140,19 @@ class FileService { try { final buffer = List.filled(4096, 0); final bytesRead = await raf.readInto(buffer, 0, 4096); - for (int i = 0; i < bytesRead; i++) { - if (buffer[i] == 0) { + for(int i = 0; i < bytesRead; i++) { + if(buffer[i] == 0) { throw const FileSystemException('检测到该文件为二进制格式,不支持作为文本展示与编辑'); } } - } finally { + }finally { await raf.close(); } return await file.readAsString( encoding: const Utf8Codec(allowMalformed: true), ); - } catch (e) { + }catch (e) { if (e is FileSystemException) rethrow; throw FileSystemException('读取文件失败: $e', path); } @@ -167,7 +167,7 @@ class FileService { // 新建文件 Future createFile(String targetPath) async { final file = File(targetPath); - if (await file.exists()) { + if(await file.exists()) { throw FileSystemException('文件已存在', targetPath); } await file.create(recursive: true); @@ -176,7 +176,7 @@ class FileService { // 新建文件夹 Future createDirectory(String targetPath) async { final dir = Directory(targetPath); - if (await dir.exists()) { + if(await dir.exists()) { throw FileSystemException('文件夹已存在', targetPath); } await dir.create(recursive: true); @@ -185,15 +185,15 @@ class FileService { // 重命名 Future renameEntity(String oldPath, String newName) async { final entityType = await FileSystemEntity.type(oldPath); - if (entityType == FileSystemEntityType.notFound) { + if(entityType == FileSystemEntityType.notFound) { throw FileSystemException('项目不存在', oldPath); } final parentDir = p.dirname(oldPath); final newPath = p.join(parentDir, newName); - if (entityType == FileSystemEntityType.directory) { + if(entityType == FileSystemEntityType.directory) { await Directory(oldPath).rename(newPath); - } else { + }else { await File(oldPath).rename(newPath); } } @@ -201,9 +201,9 @@ class FileService { // 删除 Future deleteEntity(String targetPath) async { final entityType = await FileSystemEntity.type(targetPath); - if (entityType == FileSystemEntityType.directory) { + if(entityType == FileSystemEntityType.directory) { await Directory(targetPath).delete(recursive: true); - } else if (entityType == FileSystemEntityType.file) { + }else if (entityType == FileSystemEntityType.file) { await File(targetPath).delete(); } } @@ -217,9 +217,9 @@ class FileService { // 如果同名,自动生成副本名称(如 file(1).dart) targetPath = await _getUniqueTargetPath(targetPath, entityType == FileSystemEntityType.directory); - if (entityType == FileSystemEntityType.directory) { + if(entityType == FileSystemEntityType.directory) { await _copyDirectory(Directory(sourcePath), Directory(targetPath)); - } else if (entityType == FileSystemEntityType.file) { + }else if (entityType == FileSystemEntityType.file) { await File(sourcePath).copy(targetPath); } } @@ -230,45 +230,47 @@ class FileService { final baseName = p.basename(sourcePath); String targetPath = p.join(destinationDir, baseName); - if (p.equals(p.dirname(sourcePath), destinationDir)) { + if(p.equals(p.dirname(sourcePath), destinationDir)) { // 在同一目录下粘贴剪切的项目,无需操作 return; } targetPath = await _getUniqueTargetPath(targetPath, entityType == FileSystemEntityType.directory); - if (entityType == FileSystemEntityType.directory) { + if(entityType == FileSystemEntityType.directory) { try { await Directory(sourcePath).rename(targetPath); - } catch (_) { + }catch (_) { // 跨盘符或无法直接 rename 时退化为 copy + delete await _copyDirectory(Directory(sourcePath), Directory(targetPath)); await Directory(sourcePath).delete(recursive: true); } - } else if (entityType == FileSystemEntityType.file) { + }else if (entityType == FileSystemEntityType.file) { try { await File(sourcePath).rename(targetPath); - } catch (_) { + }catch (_) { await File(sourcePath).copy(targetPath); await File(sourcePath).delete(); } } } + //递归复制文件 Future _copyDirectory(Directory source, Directory destination) async { await destination.create(recursive: true); await for (final entity in source.list(recursive: false, followLinks: false)) { final newPath = p.join(destination.path, p.basename(entity.path)); - if (entity is Directory) { + if(entity is Directory) { await _copyDirectory(entity, Directory(newPath)); - } else if (entity is File) { + }else if (entity is File) { await entity.copy(newPath); } } } + //处理同名 Future _getUniqueTargetPath(String originalPath, bool isDirectory) async { - if (!await FileSystemEntity.isDirectory(originalPath) && + if(!await FileSystemEntity.isDirectory(originalPath) && !await FileSystemEntity.isFile(originalPath)) { return originalPath; } @@ -280,10 +282,10 @@ class FileService { : p.basenameWithoutExtension(originalPath); int counter = 1; - while (true) { + while(true) { final candidateName = '$nameWithoutExt($counter)$ext'; final candidatePath = p.join(parent, candidateName); - if (!await FileSystemEntity.isDirectory(candidatePath) && + if(!await FileSystemEntity.isDirectory(candidatePath) && !await FileSystemEntity.isFile(candidatePath)) { return candidatePath; } @@ -291,6 +293,7 @@ class FileService { } } + //存在 Future entityExists(String path) async { final type = await FileSystemEntity.type(path); return type != FileSystemEntityType.notFound; diff --git a/lib/services/file_watcher_service.dart b/lib/services/file_watcher_service.dart index 6590e22..5d56973 100644 --- a/lib/services/file_watcher_service.dart +++ b/lib/services/file_watcher_service.dart @@ -47,7 +47,7 @@ class FileWatcherService { /// 判断路径是否属于应该忽略的隐藏或构建目录 static bool shouldIgnore(String path) { final segments = p.split(path); - for (final seg in segments) { + for(final seg in segments) { if (seg == '.git' || seg == '.dart_tool' || seg == '.idea' || @@ -70,19 +70,19 @@ class FileWatcherService { final cleanRoot = p.normalize(rootPath); final dir = Directory(cleanRoot); - if (!dir.existsSync()) return; + if(!dir.existsSync()) return; _watchedRootPath = cleanRoot; try { _subscription = dir.watch(recursive: true).listen( (event) { - if (shouldIgnore(event.path)) { + if(shouldIgnore(event.path)) { return; } // 自身保存的文件在保护窗口内忽略内容修改事件 - if (event is FileSystemModifyEvent && isRecentlySaved(event.path)) { + if(event is FileSystemModifyEvent && isRecentlySaved(event.path)) { return; } @@ -100,7 +100,7 @@ class FileWatcherService { debugPrint('FileWatcherService 监听异常: $e'); }, ); - } catch (e) { + }catch (e) { debugPrint('FileWatcherService 启动监听失败: $e'); } } diff --git a/lib/services/file_directory_history_service.dart b/lib/services/project_history_service.dart similarity index 74% rename from lib/services/file_directory_history_service.dart rename to lib/services/project_history_service.dart index e1a1b4d..b8c583a 100644 --- a/lib/services/file_directory_history_service.dart +++ b/lib/services/project_history_service.dart @@ -1,11 +1,11 @@ -import 'package:code_editor/models/file_directory_history.dart'; +import 'package:code_editor/models/project_history.dart'; import 'package:shared_preferences/shared_preferences.dart'; -class FileDirectoryHistoryService { - static final FileDirectoryHistoryService instance = FileDirectoryHistoryService._(); - FileDirectoryHistoryService._(); +class ProjectHistoryService { + static final ProjectHistoryService instance = ProjectHistoryService._(); + ProjectHistoryService._(); - static const String _keyHistory = 'file_directory_history'; + static const String _keyHistory = 'project_history'; static const int _maxHistoryCount = 15; //记录 @@ -18,7 +18,7 @@ class FileDirectoryHistoryService { final cleanPath = rootPath.trim(); if(cleanPath.isEmpty) return; - List history = await getFullHistory(); + List history = await getFullHistory(); final existingIndex = history.indexWhere((item) => item.rootPath == cleanPath); String? resolvedFile = lastOpenedFilePath; @@ -34,7 +34,7 @@ class FileDirectoryHistoryService { history.insert( 0, - FileDirectoryHistory( + ProjectHistory( rootPath: cleanPath, lastOpenedFilePath: resolvedFile, openDirectoryPaths: resolvedOpenDirs ?? const [], @@ -50,21 +50,21 @@ class FileDirectoryHistoryService { } //获取完整历史 - Future> getFullHistory() async { + Future> getFullHistory() async { final prefs = await SharedPreferences.getInstance(); final rawList = prefs.getStringList(_keyHistory) ?? []; - return rawList.map((jsonStr) => FileDirectoryHistory.fromJson(jsonStr)).toList(); + return rawList.map((jsonStr) => ProjectHistory.fromJson(jsonStr)).toList(); } //获取最近历史 - Future getLastHistory() async { + Future getLastHistory() async { final history = await getFullHistory(); return history.isNotEmpty ? history.first : null; } //删除指定的历史 Future removeHistory(String path) async { - List history = await getFullHistory(); + List history = await getFullHistory(); history.removeWhere((item) => item.rootPath == path); await _saveHistoryList(history); } @@ -75,7 +75,7 @@ class FileDirectoryHistoryService { await prefs.remove(_keyHistory); } - Future _saveHistoryList(List list) async { + Future _saveHistoryList(List list) async { final prefs = await SharedPreferences.getInstance(); final jsonList = list.map((item) => item.toJson()).toList(); await prefs.setStringList(_keyHistory, jsonList); diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index 352ce00..bca5de3 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -1,5 +1,4 @@ import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/providers/editor_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/utils/dialog_utils.dart'; @@ -15,21 +14,11 @@ class MainView extends StatelessWidget { const MainView({super.key}); static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.projectProvider; - } + return listen ? context.watch() : context.read(); } static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.tabProvider; - } + return listen ? context.watch() : context.read(); } void _handleSave(BuildContext context) async { @@ -53,6 +42,19 @@ class MainView extends StatelessWidget { } } + void _handleCloseAllTabs(BuildContext context) async { + await _getTabProvider(context).closeAllTabs(context); + } + + void _handleCloseProject(BuildContext context) async { + final tabProvider = _getTabProvider(context); + final projectProvider = _getProjectProvider(context); + final canProceed = await tabProvider.checkUnsavedChanges(context); + if (canProceed && context.mounted) { + await projectProvider.closeProject(); + } + } + @override Widget build(BuildContext context) { final projectProvider = _getProjectProvider(context, listen: true); @@ -82,6 +84,8 @@ class MainView extends StatelessWidget { isModified: isModified, onSave: () => _handleSave(context), onSaveAll: () => _handleSaveAll(context), + onCloseAllTabs: () => _handleCloseAllTabs(context), + onCloseProject: () => _handleCloseProject(context), onRun: () {}, onSettings: () { Navigator.of(context).push( diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index 01dc77d..38fa652 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -1,20 +1,20 @@ +import 'dart:convert'; import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/editor_theme.dart'; -import 'package:code_editor/providers/editor_provider.dart'; +import 'package:code_editor/models/virtual_keyboard_config.dart'; import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:code_editor/utils/syntax_highlight_helper.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:re_editor/re_editor.dart'; /// 设置页面 class SettingsView extends StatelessWidget { const SettingsView({super.key}); static SettingsProvider _getProvider(BuildContext context) { - try { - return context.watch(); - } catch (_) { - return context.watch().settingsProvider; - } + return context.watch(); } @override @@ -50,6 +50,8 @@ class SettingsView extends StatelessWidget { _buildEditorThemeTile(context, provider, l10n), _buildFontSizeTile(context, provider, l10n), _buildWordWrapTile(context, provider, l10n), + _buildVirtualKeyboardTile(context, provider, l10n), + _buildVirtualKeyboardConfigTile(context, provider, l10n), const Divider(height: 32, indent: 16, endIndent: 16), @@ -416,6 +418,229 @@ class SettingsView extends StatelessWidget { ); } + /// 编辑区:虚拟小键盘开关条目 + Widget _buildVirtualKeyboardTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + + return SwitchListTile( + secondary: Icon(Icons.keyboard_outlined, color: theme.colorScheme.primary), + title: Text(l10n.virtualKeyboard), + subtitle: Text(l10n.virtualKeyboardSubtitle), + value: provider.enableVirtualKeyboard, + onChanged: (val) => provider.setEnableVirtualKeyboard(val), + ); + } + + /// 编辑区:小键盘配置编辑条目 + Widget _buildVirtualKeyboardConfigTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + + return ListTile( + enabled: provider.enableVirtualKeyboard, + leading: Icon(Icons.tune, color: provider.enableVirtualKeyboard ? theme.colorScheme.primary : theme.disabledColor), + title: Text(l10n.editVirtualKeyboardConfig), + subtitle: Text(l10n.editVirtualKeyboardConfigSubtitle), + trailing: const Icon(Icons.chevron_right), + onTap: () { + _showKeyboardConfigDialog(context, provider, l10n); + }, + ); + } + + void _showKeyboardConfigDialog( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final codeController = CodeLineEditingController.fromText(provider.virtualKeyboardConfigJson); + String? validationError; + + showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setDialogState) { + final theme = Theme.of(context); + final activeTheme = provider.editorTheme; + + return AlertDialog( + title: Text(l10n.virtualKeyboardDialogTitle), + content: SizedBox( + width: 680, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (validationError != null) + Container( + width: double.infinity, + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: theme.colorScheme.errorContainer, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: theme.colorScheme.error, width: 0.8), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.error_outline, size: 18, color: theme.colorScheme.error), + const SizedBox(width: 8), + Expanded( + child: Text( + validationError!, + style: TextStyle( + color: theme.colorScheme.onErrorContainer, + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ), + ), + Flexible( + child: Container( + height: 360, + decoration: BoxDecoration( + color: activeTheme.backgroundColor, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: validationError != null + ? theme.colorScheme.error + : theme.colorScheme.outlineVariant, + ), + ), + clipBehavior: Clip.antiAlias, + child: CodeEditor( + controller: codeController, + wordWrap: false, + style: CodeEditorStyle( + fontSize: 13, + textColor: activeTheme.textColor, + backgroundColor: activeTheme.backgroundColor, + cursorColor: activeTheme.cursorColor, + cursorLineColor: activeTheme.cursorLineColor, + selectionColor: activeTheme.selectionColor, + fontFamily: 'Consolas, Monaco, "Courier New", monospace', + codeTheme: CodeHighlightTheme( + languages: SyntaxHighlightHelper.getLanguagesForFile('config.json'), + theme: activeTheme.highlightTheme, + ), + ), + indicatorBuilder: (context, editingController, chunkController, notifier) { + return Row( + children: [ + DefaultCodeLineNumber( + controller: editingController, + notifier: notifier, + textStyle: TextStyle( + color: activeTheme.gutterTextColor, + fontSize: 12, + fontFamily: 'Consolas, Monaco, "Courier New", monospace', + ), + focusedTextStyle: TextStyle( + color: activeTheme.focusedGutterTextColor, + fontSize: 12, + fontWeight: FontWeight.bold, + fontFamily: 'Consolas, Monaco, "Courier New", monospace', + ), + ), + DefaultCodeChunkIndicator( + width: 16, + controller: chunkController, + notifier: notifier, + painter: DefaultCodeChunkIndicatorPainter( + color: activeTheme.gutterTextColor, + ), + ), + ], + ); + }, + ), + ), + ), + const SizedBox(height: 8), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + TextButton.icon( + icon: const Icon(Icons.restore, size: 16), + label: Text(l10n.resetDefault), + onPressed: () { + setDialogState(() { + codeController.text = VirtualKeyboardConfig.defaultJsonPretty(); + validationError = null; + }); + }, + ), + TextButton.icon( + icon: const Icon(Icons.format_align_left, size: 16), + label: Text(l10n.formatJson), + onPressed: () { + final err = VirtualKeyboardConfig.validateJson(codeController.text); + if (err != null) { + setDialogState(() { + validationError = err; + }); + } else { + try { + final decoded = jsonDecode(codeController.text); + const encoder = JsonEncoder.withIndent(' '); + setDialogState(() { + codeController.text = encoder.convert(decoded); + validationError = null; + }); + } catch (_) {} + } + }, + ), + ], + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () async { + final jsonText = codeController.text; + final err = VirtualKeyboardConfig.validateJson(jsonText); + if (err != null) { + setDialogState(() { + validationError = err; + }); + return; + } + + final success = await provider.setVirtualKeyboardConfig(jsonText); + if (success && dialogContext.mounted) { + Navigator.of(dialogContext).pop(); + DialogUtils.showSuccessToast(context, l10n.configSavedSuccess); + } + }, + child: Text(l10n.save), + ), + ], + ); + }, + ); + }, + ); + } + /// 语言:应用语言选择条目 Widget _buildLanguageTile( BuildContext context, diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart index e717004..1997680 100644 --- a/lib/widgets/code_editor_app_bar.dart +++ b/lib/widgets/code_editor_app_bar.dart @@ -9,6 +9,8 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { final VoidCallback? onSave; final VoidCallback? onSaveAll; final VoidCallback? onRun; + final VoidCallback? onCloseAllTabs; + final VoidCallback? onCloseProject; final VoidCallback? onSettings; const CodeEditorAppBar({ @@ -19,6 +21,8 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { this.onSave, this.onSaveAll, this.onRun, + this.onCloseAllTabs, + this.onCloseProject, this.onSettings, }); @@ -103,6 +107,10 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { 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(); } @@ -118,6 +126,26 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { ], ), ), + PopupMenuItem( + value: 'close_all_tabs', + child: Row( + children: [ + const Icon(Icons.close_fullscreen_outlined, size: 20), + const SizedBox(width: 10), + Text(l10n.closeAllTabs), + ], + ), + ), + 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( diff --git a/lib/widgets/code_editor_drawer.dart b/lib/widgets/code_editor_drawer.dart index 3b45fbb..165faaa 100644 --- a/lib/widgets/code_editor_drawer.dart +++ b/lib/widgets/code_editor_drawer.dart @@ -1,30 +1,61 @@ import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/providers/editor_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; -import 'package:code_editor/widgets/file_directory_history_widget.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'; import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; class CodeEditorDrawer extends StatelessWidget { const CodeEditorDrawer({super.key}); static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.projectProvider; - } + return listen ? context.watch() : context.read(); } static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.tabProvider; + return listen ? context.watch() : context.read(); + } + + Future _handleNewFile(BuildContext context, String rootPath) async { + final l10n = AppLocalizations.of(context); + final name = await DialogUtils.showInputDialog( + context, + title: l10n?.newFile ?? '新建文件', + hintText: l10n?.fileNameHint ?? '文件名 (例如: main.dart)', + ); + if (name != null && name.trim().isNotEmpty && context.mounted) { + try { + await _getProjectProvider(context).createFile(rootPath, name.trim()); + if (context.mounted) { + final newFilePath = p.join(rootPath, name.trim()); + await _getTabProvider(context).openFile(newFilePath); + } + } catch (e) { + if (context.mounted) { + DialogUtils.showErrorToast(context, l10n?.createFileFailed(e.toString()) ?? '创建文件失败: $e'); + } + } + } + } + + Future _handleNewFolder(BuildContext context, String rootPath) async { + final l10n = AppLocalizations.of(context); + final name = await DialogUtils.showInputDialog( + context, + title: l10n?.newFolder ?? '新建文件夹', + hintText: l10n?.folderNameHint ?? '文件夹名', + ); + if (name != null && name.trim().isNotEmpty && context.mounted) { + try { + await _getProjectProvider(context).createDirectory(rootPath, name.trim()); + } catch (e) { + if (context.mounted) { + DialogUtils.showErrorToast(context, l10n?.createFolderFailed(e.toString()) ?? '创建文件夹失败: $e'); + } + } } } @@ -34,6 +65,7 @@ class CodeEditorDrawer extends StatelessWidget { final l10n = AppLocalizations.of(context)!; final projectProvider = _getProjectProvider(context, listen: true); final rootPath = projectProvider.rootPath; + final hasProject = rootPath != null && rootPath.trim().isNotEmpty; return Drawer( child: SafeArea( @@ -73,9 +105,9 @@ class CodeEditorDrawer extends StatelessWidget { ), IconButton( icon: const Icon(Icons.history), - tooltip: l10n.viewFileDirectoryHistory, + tooltip: l10n.viewProjectHistory, onPressed: () { - FileDirectoryHistoryWidget.show( + ProjectHistoryWidget.show( context, onSelectHistory: (selectedHistory) async { final canProceed = await _getTabProvider(context).checkUnsavedChanges(context); @@ -87,13 +119,41 @@ class CodeEditorDrawer extends StatelessWidget { ), ], ), - Text( - rootPath ?? '', - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, + 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), + ), + ], + ], ), ], ), diff --git a/lib/widgets/code_editor_tab_bar.dart b/lib/widgets/code_editor_tab_bar.dart index bd2cd15..a81610a 100644 --- a/lib/widgets/code_editor_tab_bar.dart +++ b/lib/widgets/code_editor_tab_bar.dart @@ -1,6 +1,5 @@ import 'dart:math' as math; import 'package:code_editor/models/editor_tab_item.dart'; -import 'package:code_editor/providers/editor_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:flutter/material.dart'; @@ -10,24 +9,14 @@ class CodeEditorTabBar extends StatelessWidget { const CodeEditorTabBar({super.key}); static TabProvider _getTabProvider(BuildContext context, {bool listen = true}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.tabProvider; - } + return listen ? context.watch() : context.read(); } static ProjectProvider? _getProjectProvider(BuildContext context, {bool listen = true}) { try { return listen ? context.watch() : context.read(); } catch (_) { - try { - final editor = listen ? context.watch() : context.read(); - return editor.projectProvider; - } catch (_) { - return null; - } + return null; } } diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index 86228fa..116adf1 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -1,7 +1,7 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/editor_tab_item.dart'; import 'package:code_editor/models/editor_theme.dart'; -import 'package:code_editor/providers/editor_provider.dart'; +import 'package:code_editor/models/virtual_keyboard_config.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/services/file_service.dart'; @@ -9,6 +9,7 @@ import 'package:code_editor/services/file_watcher_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/utils/syntax_highlight_helper.dart'; import 'package:code_editor/widgets/code_editor_menu.dart'; +import 'package:code_editor/widgets/virtual_keyboard_widget.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:path/path.dart' as p; @@ -31,21 +32,11 @@ class CodeEditorWidget extends StatefulWidget { class _CodeEditorWidgetState extends State { static SettingsProvider _getSettingsProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.settingsProvider; - } + return listen ? context.watch() : context.read(); } static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.tabProvider; - } + return listen ? context.watch() : context.read(); } CodeLineEditingController? _controller; @@ -303,7 +294,7 @@ class _CodeEditorWidgetState extends State { if (hasNoProject && hasNoFile) { return Center( child: Text( - l10n?.noOpenDirectory ?? "当前未打开文件目录", + l10n?.noOpenDirectory ?? "当前未打开项目", style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ), @@ -348,65 +339,80 @@ class _CodeEditorWidgetState extends State { EditorTheme activeTheme = EditorTheme.atomOneDark; double activeFontSize = 14.0; bool activeWordWrap = true; + bool enableVirtualKeyboard = false; + VirtualKeyboardConfig? keyboardConfig; try { final settings = _getSettingsProvider(context, listen: true); activeTheme = settings.editorTheme; activeFontSize = settings.fontSize; activeWordWrap = settings.wordWrap; + enableVirtualKeyboard = settings.enableVirtualKeyboard; + keyboardConfig = settings.virtualKeyboardConfig; } catch (_) {} return Container( color: activeTheme.backgroundColor, width: double.infinity, height: double.infinity, - child: CodeEditor( - key: ValueKey(_currentLoadedPath), - controller: controller, - scrollController: _scrollController, - wordWrap: activeWordWrap, - toolbarController: const CodeEditorToolbarController(), - style: CodeEditorStyle( - fontSize: activeFontSize, - textColor: activeTheme.textColor, - backgroundColor: activeTheme.backgroundColor, - cursorColor: activeTheme.cursorColor, - cursorLineColor: activeTheme.cursorLineColor, - selectionColor: activeTheme.selectionColor, - fontFamily: 'Consolas, Monaco, "Courier New", monospace', - codeTheme: CodeHighlightTheme( - languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath), - theme: activeTheme.highlightTheme, + child: Column( + children: [ + Expanded( + child: CodeEditor( + key: ValueKey(_currentLoadedPath), + controller: controller, + scrollController: _scrollController, + wordWrap: activeWordWrap, + toolbarController: const CodeEditorToolbarController(), + style: CodeEditorStyle( + fontSize: activeFontSize, + textColor: activeTheme.textColor, + backgroundColor: activeTheme.backgroundColor, + cursorColor: activeTheme.cursorColor, + cursorLineColor: activeTheme.cursorLineColor, + selectionColor: activeTheme.selectionColor, + fontFamily: 'Consolas, Monaco, "Courier New", monospace', + codeTheme: CodeHighlightTheme( + languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath), + theme: activeTheme.highlightTheme, + ), + ), + indicatorBuilder: (context, editingController, chunkController, notifier) { + return Row( + children: [ + DefaultCodeLineNumber( + controller: editingController, + notifier: notifier, + textStyle: TextStyle( + color: activeTheme.gutterTextColor, + fontSize: (activeFontSize - 1).clamp(9.0, 30.0), + fontFamily: 'Consolas, Monaco, "Courier New", monospace', + ), + focusedTextStyle: TextStyle( + color: activeTheme.focusedGutterTextColor, + fontSize: (activeFontSize - 1).clamp(9.0, 30.0), + fontWeight: FontWeight.bold, + fontFamily: 'Consolas, Monaco, "Courier New", monospace', + ), + ), + DefaultCodeChunkIndicator( + width: 20, + controller: chunkController, + notifier: notifier, + painter: DefaultCodeChunkIndicatorPainter( + color: activeTheme.gutterTextColor, + ), + ), + ], + ); + }, + ), ), - ), - indicatorBuilder: (context, editingController, chunkController, notifier) { - return Row( - children: [ - DefaultCodeLineNumber( - controller: editingController, - notifier: notifier, - textStyle: TextStyle( - color: activeTheme.gutterTextColor, - fontSize: (activeFontSize - 1).clamp(9.0, 30.0), - fontFamily: 'Consolas, Monaco, "Courier New", monospace', - ), - focusedTextStyle: TextStyle( - color: activeTheme.focusedGutterTextColor, - fontSize: (activeFontSize - 1).clamp(9.0, 30.0), - fontWeight: FontWeight.bold, - fontFamily: 'Consolas, Monaco, "Courier New", monospace', - ), - ), - DefaultCodeChunkIndicator( - width: 20, - controller: chunkController, - notifier: notifier, - painter: DefaultCodeChunkIndicatorPainter( - color: activeTheme.gutterTextColor, - ), - ), - ], - ); - }, + if (enableVirtualKeyboard && keyboardConfig != null) + VirtualKeyboardWidget( + controller: controller, + config: keyboardConfig, + ), + ], ), ); } diff --git a/lib/widgets/file_item_widget.dart b/lib/widgets/file_item_widget.dart index 750b36f..02ec6f9 100644 --- a/lib/widgets/file_item_widget.dart +++ b/lib/widgets/file_item_widget.dart @@ -1,6 +1,5 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/file_item.dart'; -import 'package:code_editor/providers/editor_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/utils/dialog_utils.dart'; @@ -22,21 +21,11 @@ class FileItemWidget extends StatefulWidget { class _FileItemWidgetState extends State { static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.projectProvider; - } + return listen ? context.watch() : context.read(); } static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) { - try { - return listen ? context.watch() : context.read(); - } catch (_) { - final editor = listen ? context.watch() : context.read(); - return editor.tabProvider; - } + return listen ? context.watch() : context.read(); } @override diff --git a/lib/widgets/file_tree_widget.dart b/lib/widgets/file_tree_widget.dart index 3d5d7b2..38af097 100644 --- a/lib/widgets/file_tree_widget.dart +++ b/lib/widgets/file_tree_widget.dart @@ -1,4 +1,4 @@ -import 'package:code_editor/providers/editor_provider.dart'; +import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/widgets/file_item_widget.dart'; import 'package:flutter/material.dart'; @@ -8,16 +8,13 @@ class FileTreeWidget extends StatelessWidget { const FileTreeWidget({super.key}); static ProjectProvider _getProjectProvider(BuildContext context) { - try { - return context.watch(); - } catch (_) { - return context.watch().projectProvider; - } + return context.watch(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); final projectProvider = _getProjectProvider(context); final rootPath = projectProvider.rootPath; final items = projectProvider.items; @@ -28,7 +25,7 @@ class FileTreeWidget extends StatelessWidget { padding: const EdgeInsets.all(24.0), child: Center( child: Text( - "请点击上方按钮打开文件目录", + l10n?.openProjectPrompt ?? "请点击上方按钮打开项目", textAlign: TextAlign.center, style: theme.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.bold, diff --git a/lib/widgets/file_directory_history_widget.dart b/lib/widgets/project_history_widget.dart similarity index 77% rename from lib/widgets/file_directory_history_widget.dart rename to lib/widgets/project_history_widget.dart index 15d1a28..6f92470 100644 --- a/lib/widgets/file_directory_history_widget.dart +++ b/lib/widgets/project_history_widget.dart @@ -1,14 +1,17 @@ import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/models/file_directory_history.dart'; -import 'package:code_editor/services/file_directory_history_service.dart'; +import 'package:code_editor/models/project_history.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/project_history_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; -class FileDirectoryHistoryWidget extends StatefulWidget { - final ValueChanged? onSelectHistory; +class ProjectHistoryWidget extends StatefulWidget { + final ValueChanged? onSelectHistory; - const FileDirectoryHistoryWidget({ + const ProjectHistoryWidget({ super.key, this.onSelectHistory, }); @@ -16,13 +19,13 @@ class FileDirectoryHistoryWidget extends StatefulWidget { /// 打开历史弹窗(不关闭后方的 Drawer) static Future show( BuildContext context, { - ValueChanged? onSelectHistory, + ValueChanged? onSelectHistory, }) { return showDialog( context: context, barrierDismissible: true, builder: (BuildContext dialogContext) { - return FileDirectoryHistoryWidget( + return ProjectHistoryWidget( onSelectHistory: onSelectHistory, ); }, @@ -30,13 +33,13 @@ class FileDirectoryHistoryWidget extends StatefulWidget { } @override - State createState() => - _FileDirectoryHistoryWidgetState(); + State createState() => + _ProjectHistoryWidgetState(); } -class _FileDirectoryHistoryWidgetState - extends State { - List _historyList = []; +class _ProjectHistoryWidgetState + extends State { + List _historyList = []; bool _isLoading = true; @override @@ -46,7 +49,7 @@ class _FileDirectoryHistoryWidgetState } Future _loadHistory() async { - final list = await FileDirectoryHistoryService.instance.getFullHistory(); + final list = await ProjectHistoryService.instance.getFullHistory(); if (mounted) { setState(() { _historyList = list; @@ -55,22 +58,50 @@ class _FileDirectoryHistoryWidgetState } } - Future _deleteHistory(FileDirectoryHistory item) async { + Future _deleteHistory(ProjectHistory item) async { final root = item.rootPath; - if (root != null && root.isNotEmpty) { - final l10n = AppLocalizations.of(context)!; - final confirmed = await DialogUtils.showDestructiveConfirmDialog( - context, - title: l10n.deleteHistoryTitle, - message: l10n.deleteHistoryMessage, - confirmText: l10n.remove, - ); - if (confirmed && mounted) { - await FileDirectoryHistoryService.instance.removeHistory(root); - await _loadHistory(); - if (mounted) { - DialogUtils.showSuccessToast(context, l10n.historyRemoved); - } + if (root == null || root.isEmpty) return; + + // 1. 判断是否是当前正在打开的项目 + ProjectProvider? projectProvider; + TabProvider? tabProvider; + try { + projectProvider = context.read(); + tabProvider = context.read(); + } catch (_) {} + + final currentRoot = projectProvider?.rootPath; + final isCurrentProject = currentRoot != null && p.equals(p.normalize(currentRoot), p.normalize(root)); + + // 2. 如果删除的是当前项目,先进行保存确认检查 + if (isCurrentProject && tabProvider != null) { + final canProceed = await tabProvider.checkUnsavedChanges(context); + if (!canProceed || !mounted) { + // 用户取消或未通过保存流程,中止后续操作 + return; + } + } + + // 3. 弹出是否移除历史记录确认弹窗 + final l10n = AppLocalizations.of(context)!; + final confirmed = await DialogUtils.showDestructiveConfirmDialog( + context, + title: l10n.deleteHistoryTitle, + message: l10n.deleteHistoryMessage, + confirmText: l10n.remove, + ); + + // 4. 只有两者均为 true(保存检查通过 且 确认移除历史记录),才真正去关闭当前项目并删除历史 + if (confirmed && mounted) { + if (isCurrentProject && projectProvider != null) { + await projectProvider.closeProject(); + if (!mounted) return; + } + + await ProjectHistoryService.instance.removeHistory(root); + await _loadHistory(); + if (mounted) { + DialogUtils.showSuccessToast(context, l10n.historyRemoved); } } } @@ -107,7 +138,7 @@ class _FileDirectoryHistoryWidgetState children: [ Expanded( child: Text( - l10n.historyFileDirectories, + l10n.projectHistory, style: theme.textTheme.titleMedium?.copyWith( fontWeight: FontWeight.bold, color: theme.colorScheme.onSurface, diff --git a/lib/widgets/virtual_keyboard_widget.dart b/lib/widgets/virtual_keyboard_widget.dart new file mode 100644 index 0000000..fa7feb3 --- /dev/null +++ b/lib/widgets/virtual_keyboard_widget.dart @@ -0,0 +1,327 @@ +import 'package:code_editor/models/virtual_keyboard_config.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:re_editor/re_editor.dart'; + +/// 编辑器下方的虚拟辅助小键盘组件 +class VirtualKeyboardWidget extends StatefulWidget { + final CodeLineEditingController? controller; + final VirtualKeyboardConfig config; + final Color? backgroundColor; + + const VirtualKeyboardWidget({ + super.key, + required this.controller, + required this.config, + this.backgroundColor, + }); + + @override + State createState() => _VirtualKeyboardWidgetState(); +} + +class _VirtualKeyboardWidgetState extends State { + late PageController _pageController; + int _currentPage = 0; + + @override + void initState() { + super.initState(); + _pageController = PageController(initialPage: 0); + } + + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + + void _handleKeyTap(KeyboardKeyItem keyItem) { + final controller = widget.controller; + if (controller == null) return; + + // 轻微触觉反馈提升敲击手感 + HapticFeedback.lightImpact(); + + switch (keyItem.action) { + case 'command': + _handleCommand(controller, keyItem.value); + break; + case 'pair': + _handlePair(controller, keyItem.value, keyItem.cursorOffset); + break; + case 'input': + default: + _handleInput(controller, keyItem.value.isNotEmpty ? keyItem.value : keyItem.label); + break; + } + } + + void _handleInput(CodeLineEditingController controller, String text) { + if (text.isEmpty) return; + controller.replaceSelection(text); + } + + void _handlePair(CodeLineEditingController controller, String pairText, int offset) { + final hasSelection = !controller.selection.isCollapsed && + controller.selection.baseOffset != -1 && + controller.selection.extentOffset != -1; + + if (hasSelection) { + final selected = controller.selectedText; + if (pairText.length >= 2) { + final left = pairText.substring(0, pairText.length ~/ 2); + final right = pairText.substring(pairText.length ~/ 2); + final wrapped = left + selected + right; + controller.replaceSelection(wrapped); + } else { + controller.replaceSelection(pairText + selected + pairText); + } + } else { + controller.replaceSelection(pairText); + if (offset != 0) { + final curSel = controller.selection; + final targetOffset = (curSel.extentOffset + offset).clamp(0, controller.extentLine.length); + controller.selection = CodeLineSelection.collapsed( + index: curSel.extentIndex, + offset: targetOffset, + ); + } + } + } + + void _handleCommand(CodeLineEditingController controller, String command) { + final cmd = command.toLowerCase().trim(); + switch (cmd) { + case 'tab': + controller.applyIndent(); + break; + case 'untab': + case 'outdent': + controller.applyOutdent(); + break; + case 'cursor_left': + case 'left': + controller.moveCursor(AxisDirection.left); + break; + case 'cursor_right': + case 'right': + controller.moveCursor(AxisDirection.right); + break; + case 'cursor_up': + case 'up': + controller.moveCursor(AxisDirection.up); + break; + case 'cursor_down': + case 'down': + controller.moveCursor(AxisDirection.down); + break; + case 'line_start': + case 'home': + controller.moveCursorToLineStart(); + break; + case 'line_end': + case 'end': + controller.moveCursorToLineEnd(); + break; + case 'page_start': + controller.moveCursorToPageStart(); + break; + case 'page_end': + controller.moveCursorToPageEnd(); + break; + case 'undo': + if (controller.canUndo) { + controller.undo(); + } + break; + case 'redo': + if (controller.canRedo) { + controller.redo(); + } + break; + case 'copy': + controller.copy(); + break; + case 'cut': + controller.cut(); + break; + case 'paste': + controller.paste(); + break; + case 'backspace': + case 'delete_backward': + controller.deleteBackward(); + break; + case 'delete': + case 'delete_forward': + controller.deleteForward(); + break; + case 'select_all': + controller.selectAll(); + break; + default: + // 未知命令安全降级为直接输入其命令名称或原文本 + controller.replaceSelection(command); + break; + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + final bgColor = widget.backgroundColor ?? + (isDark ? const Color(0xFF1E1E1E) : const Color(0xFFF2F3F5)); + final borderColor = isDark ? const Color(0xFF333333) : const Color(0xFFDCDFE6); + + final pages = widget.config.pages; + if (pages.isEmpty) { + return const SizedBox.shrink(); + } + + return 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); + }, + ), + ), + if (pages.length > 1) _buildPageIndicator(pages.length, theme), + ], + ), + ), + ); + } + + Widget _buildPageIndicator(int pageCount, ThemeData theme) { + return Padding( + padding: const EdgeInsets.only(bottom: 3), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(pageCount, (index) { + final isSelected = index == _currentPage; + return Container( + margin: const EdgeInsets.symmetric(horizontal: 2.5), + width: isSelected ? 12 : 4, + height: 4, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(2), + color: isSelected + ? theme.colorScheme.primary + : theme.colorScheme.onSurface.withValues(alpha: 0.25), + ), + ); + }), + ), + ); + } + + Widget _buildPage(KeyboardPageItem page, bool isDark) { + return LayoutBuilder( + builder: (context, constraints) { + final count = page.count > 0 ? page.count : 6; + final cellWidth = constraints.maxWidth / count; + final rows = page.keys; + + return Column( + children: rows.take(2).map((row) { + return SizedBox( + height: 42, + child: Row( + children: List.generate(count, (colIndex) { + if (colIndex < row.length) { + final keyItem = row[colIndex]; + return SizedBox( + width: cellWidth, + height: 42, + child: _buildKeyButton(keyItem, isDark), + ); + } else { + // 多余未配置的格子,正常渲染背景占位 + return SizedBox( + width: cellWidth, + height: 42, + ); + } + }), + ), + ); + }).toList(), + ); + }, + ); + } + + Widget _buildKeyButton(KeyboardKeyItem keyItem, bool isDark) { + final iconData = KeyboardIconHelper.getIcon(keyItem.icon); + + final btnBgColor = isDark ? const Color(0xFF2C2C2C) : const Color(0xFFFFFFFF); + final btnTextColor = isDark ? const Color(0xFFE0E0E0) : const Color(0xFF303133); + final borderColor = isDark ? const Color(0xFF383838) : const Color(0xFFE4E7ED); + + Widget content; + if (iconData != null) { + content = Icon( + iconData, + size: 18, + color: btnTextColor, + ); + } else { + content = Text( + keyItem.label, + style: TextStyle( + fontSize: keyItem.label.length > 3 ? 12 : 15, + fontWeight: FontWeight.w500, + color: btnTextColor, + fontFamily: 'Consolas, Monaco, monospace', + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + } + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 2.5, vertical: 3), + child: Material( + color: btnBgColor, + borderRadius: BorderRadius.circular(6), + elevation: 0.5, + shadowColor: Colors.black26, + child: InkWell( + borderRadius: BorderRadius.circular(6), + onTap: () => _handleKeyTap(keyItem), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6), + border: Border.all(color: borderColor, width: 0.8), + ), + alignment: Alignment.center, + child: content, + ), + ), + ), + ); + } +} diff --git a/test/widget_test.dart b/test/widget_test.dart index f36b1b1..8fc46b2 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,11 +1,14 @@ import 'package:re_editor/re_editor.dart'; import 'package:code_editor/models/editor_tab_item.dart'; -import 'package:code_editor/models/file_directory_history.dart'; import 'package:code_editor/models/file_item.dart'; -import 'package:code_editor/providers/editor_provider.dart'; +import 'package:code_editor/models/project_history.dart'; +import 'package:code_editor/services/project_history_service.dart'; +import 'package:code_editor/widgets/project_history_widget.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/models/virtual_keyboard_config.dart'; +import 'package:code_editor/widgets/virtual_keyboard_widget.dart'; import 'package:code_editor/widgets/code_editor_tab_bar.dart'; import 'package:code_editor/widgets/code_editor_widget.dart'; import 'package:code_editor/widgets/file_item_widget.dart'; @@ -19,6 +22,7 @@ import 'package:code_editor/main.dart'; 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/services/file_watcher_service.dart'; import 'package:code_editor/utils/syntax_highlight_helper.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -80,7 +84,7 @@ void main() { ); await tester.pumpAndSettle(); - expect(find.text("当前未打开文件目录"), findsOneWidget); + expect(find.text("当前未打开项目"), findsOneWidget); await tester.pumpWidget( const MaterialApp( @@ -91,7 +95,7 @@ void main() { ); await tester.pumpAndSettle(); - expect(find.text("当前未打开文件目录"), findsOneWidget); + expect(find.text("当前未打开项目"), findsOneWidget); await tester.pumpWidget( const MaterialApp( @@ -112,8 +116,11 @@ void main() { final dirItem = FileItem(name: 'src', path: '/test/src', isDirectory: true); await tester.pumpWidget( - ChangeNotifierProvider( - create: (_) => EditorProvider(), + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => ProjectProvider()), + ChangeNotifierProvider(create: (_) => TabProvider()), + ], child: MaterialApp( home: Scaffold( body: Column( @@ -139,12 +146,16 @@ void main() { testWidgets('FileItemWidget enables paste when copiedItem is present', (WidgetTester tester) async { final dirItem = FileItem(name: 'src', path: '/test/src', isDirectory: true); final copiedFile = FileItem(name: 'main.dart', path: '/test/main.dart', isDirectory: false); - final provider = EditorProvider(); - provider.copy(copiedFile); + final projectProvider = ProjectProvider(); + final tabProvider = TabProvider(); + projectProvider.copy(copiedFile); await tester.pumpWidget( - ChangeNotifierProvider.value( - value: provider, + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], child: MaterialApp( home: Scaffold( body: FileItemWidget( @@ -168,8 +179,8 @@ void main() { expect(popupItem.enabled, isTrue); }); - test('EditorProvider manages cut, copy, and paste states correctly', () { - final provider = EditorProvider(); + test('ProjectProvider manages cut, copy, and paste states correctly', () { + final provider = ProjectProvider(); final file1 = FileItem(name: 'a.dart', path: '/test/a.dart', isDirectory: false); final file2 = FileItem(name: 'b.dart', path: '/test/b.dart', isDirectory: false); @@ -258,10 +269,10 @@ void main() { }); testWidgets('SettingsView renders word wrap switch and language options', (WidgetTester tester) async { - final provider = EditorProvider(); + final provider = SettingsProvider(); await tester.pumpWidget( - ChangeNotifierProvider.value( + ChangeNotifierProvider.value( value: provider, child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -275,7 +286,15 @@ void main() { // Verify word wrap switch tile exists expect(find.text('自动换行'), findsOneWidget); - final switchFinder = find.byType(Switch); + final wordWrapTile = find.ancestor( + of: find.text('自动换行'), + matching: find.byType(SwitchListTile), + ); + expect(wordWrapTile, findsOneWidget); + final switchFinder = find.descendant( + of: wordWrapTile, + matching: find.byType(Switch), + ); expect(switchFinder, findsOneWidget); expect(provider.wordWrap, isTrue); @@ -285,11 +304,16 @@ void main() { expect(provider.wordWrap, isFalse); // Verify language section - expect(find.text('应用语言'), findsOneWidget); + final langTile = find.text('应用语言'); + await tester.scrollUntilVisible(langTile, 300); + // Drag slightly up to ensure it is nicely inside viewport + await tester.drag(find.byType(ListView), const Offset(0, -100)); + await tester.pumpAndSettle(); + expect(langTile, findsOneWidget); expect(find.text('跟随系统'), findsWidgets); // Tap language tile to open modal - await tester.tap(find.text('应用语言')); + await tester.tap(langTile); await tester.pumpAndSettle(); expect(find.text('选择应用语言'), findsOneWidget); @@ -302,8 +326,8 @@ void main() { expect(provider.locale, equals(const Locale('en'))); }); - testWidgets('EditorProvider wordWrap and locale can be updated', (WidgetTester tester) async { - final provider = EditorProvider(); + testWidgets('SettingsProvider wordWrap and locale can be updated', (WidgetTester tester) async { + final provider = SettingsProvider(); expect(provider.wordWrap, isTrue); await provider.setWordWrap(false); @@ -317,11 +341,11 @@ void main() { }); testWidgets('SettingsView font size dialog allows maximum 30 without assertion error', (WidgetTester tester) async { - final provider = EditorProvider(); + final provider = SettingsProvider(); await provider.setFontSize(30.0); await tester.pumpWidget( - ChangeNotifierProvider.value( + ChangeNotifierProvider.value( value: provider, child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -385,10 +409,9 @@ void main() { expect(find.text('* main.dart'), findsOneWidget); }); - testWidgets('EditorProvider checkUnsavedChanges saves or discards correctly', (WidgetTester tester) async { - final provider = EditorProvider(); - provider.setHistoryForTesting(const FileDirectoryHistory(rootPath: '/test', lastOpenedFilePath: '/test/demo.txt')); - provider.setModified(true); + testWidgets('TabProvider checkUnsavedChanges saves or discards correctly', (WidgetTester tester) async { + final provider = TabProvider(); + provider.setModifiedForTesting(true); expect(provider.isModified, isTrue); bool saveCalled = false; @@ -436,13 +459,16 @@ void main() { testWidgets('FileItemWidget does not display asterisk even when isModified is true', (WidgetTester tester) async { final fileItem = FileItem(name: 'main.dart', path: '/test/main.dart', isDirectory: false); - final provider = EditorProvider(); - provider.setHistoryForTesting(const FileDirectoryHistory(rootPath: '/test', lastOpenedFilePath: '/test/main.dart')); - provider.setModified(true); + final projectProvider = ProjectProvider(); + final tabProvider = TabProvider(); + tabProvider.setModifiedForTesting(true); await tester.pumpWidget( - ChangeNotifierProvider.value( - value: provider, + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], child: MaterialApp( home: Scaffold( body: FileItemWidget(fileItem: fileItem), @@ -526,6 +552,8 @@ void main() { await tester.pumpAndSettle(); expect(find.text('保存所有'), findsOneWidget); + expect(find.text('关闭所有标签'), findsOneWidget); + expect(find.text('关闭当前项目'), findsOneWidget); expect(find.text('设置'), findsOneWidget); // Tap 保存所有 @@ -536,13 +564,13 @@ void main() { }); testWidgets('CodeEditorTabBar renders tabs and handles dirty close dialog', (WidgetTester tester) async { - final provider = EditorProvider(); + final provider = TabProvider(); final tab1 = EditorTabItem(path: '/test/file1.dart', isModified: false); final tab2 = EditorTabItem(path: '/test/file2.dart', isModified: true); provider.setOpenTabsForTesting([tab1, tab2], activePath: '/test/file1.dart'); await tester.pumpWidget( - ChangeNotifierProvider.value( + ChangeNotifierProvider.value( value: provider, child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -998,6 +1026,416 @@ void main() { expect(tabProvider.activeTab?.path, equals(p.normalize('/ws/file1.dart'))); expect(tabProvider.activeTab?.isModified, isTrue); }); + + testWidgets('Close all tabs from PopupMenu prompts for dirty tabs and closes tabs', (WidgetTester tester) async { + final tabProvider = TabProvider(); + final projectProvider = ProjectProvider(); + final settingsProvider = SettingsProvider(); + + await tabProvider.openFile(p.normalize('/ws/file1.dart'), content: 'code'); + tabProvider.updateActiveTabContent('modified code', isModified: true); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const MainView(), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(tabProvider.openTabs.length, equals(1)); + + // Tap more menu + await tester.tap(find.byType(PopupMenuButton)); + await tester.pumpAndSettle(); + + // Tap '关闭所有标签' + await tester.tap(find.text('关闭所有标签')); + await tester.pumpAndSettle(); + + // Dirty prompt dialog should appear + expect(find.text('保存所有更改?'), findsOneWidget); + + // Choose discard (不保存) + await tester.tap(find.text('不保存')); + await tester.pumpAndSettle(); + + // All tabs should be closed + expect(tabProvider.openTabs, isEmpty); + expect(tabProvider.activeTab, isNull); + }); + + testWidgets('Deleting current project in ProjectHistoryWidget closes project first before confirming delete', (WidgetTester tester) async { + final projectPath = p.normalize('/ws/current_proj'); + final otherPath = p.normalize('/ws/other_proj'); + + final tabProvider = TabProvider(); + final projectProvider = ProjectProvider(); + final settingsProvider = SettingsProvider(); + + // Set current project in ProjectProvider + projectProvider.setHistoryForTesting(ProjectHistory( + rootPath: projectPath, + lastOpenedFilePath: p.normalize('$projectPath/main.dart'), + )); + + await tabProvider.openFile(p.normalize('$projectPath/main.dart'), content: 'initial'); + tabProvider.updateActiveTabContent('dirty content', isModified: true); + expect(tabProvider.isModified, isTrue); + + // Save history: record otherPath first, then projectPath so projectPath is at index 0 + await ProjectHistoryService.instance.recordHistory( + rootPath: otherPath, + lastOpenedFilePath: null, + ); + await ProjectHistoryService.instance.recordHistory( + rootPath: projectPath, + lastOpenedFilePath: p.normalize('$projectPath/main.dart'), + ); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const Scaffold( + body: ProjectHistoryWidget(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Find delete buttons in the history list (there should be 2 projects) + final deleteButtons = find.byIcon(Icons.delete_outline); + expect(deleteButtons, findsNWidgets(2)); + + // Tap delete on current project + await tester.tap(deleteButtons.first); + await tester.pumpAndSettle(); + + // 1. Should first prompt to save dirty changes of current project! + expect(find.text('保存所有更改?'), findsOneWidget); + + // Discard changes + await tester.tap(find.text('不保存')); + await tester.pumpAndSettle(); + + // 2. The second dialog (delete history) should appear! + expect(find.text('删除历史记录'), findsOneWidget); + expect(find.text('确定要从历史记录中移除该项目吗?'), findsOneWidget); + + // Case A: User taps cancel in remove dialog -> project should NOT be closed! + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(projectProvider.rootPath, equals(projectPath)); + + // Case B: User taps delete again, proceeds, and taps remove -> now project is closed! + await tester.tap(deleteButtons.first); + await tester.pumpAndSettle(); + + if (find.text('保存所有更改?').evaluate().isNotEmpty) { + await tester.tap(find.text('不保存')); + await tester.pumpAndSettle(); + } + + expect(find.text('删除历史记录'), findsOneWidget); + + // Tap remove + await tester.tap(find.text('移除')); + await tester.pumpAndSettle(); + + // Both true -> Project is now closed and removed from history + expect(projectProvider.rootPath, isNull); + + // Let toast timer finish + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('CodeEditorDrawer header renders new file and new folder buttons when project is open', (WidgetTester tester) async { + final projectProvider = ProjectProvider(); + final tabProvider = TabProvider(); + projectProvider.setHistoryForTesting(const ProjectHistory( + rootPath: '/workspace/demo_app', + lastOpenedFilePath: null, + )); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const Scaffold( + drawer: CodeEditorDrawer(), + body: Center(child: Text('Home')), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Open Drawer + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Verify root path text is displayed + expect(find.text('/workspace/demo_app'), findsOneWidget); + + // Verify new file and new folder icon buttons exist + final newFileBtn = find.byIcon(Icons.note_add_outlined); + final newFolderBtn = find.byIcon(Icons.create_new_folder_outlined); + expect(newFileBtn, findsOneWidget); + expect(newFolderBtn, findsOneWidget); + + // Tap new file button -> should show input dialog + await tester.tap(newFileBtn); + await tester.pumpAndSettle(); + expect(find.text('新建文件'), findsOneWidget); + expect(find.text('取消'), findsOneWidget); + + // Cancel input dialog + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(find.text('新建文件'), findsNothing); + + // Tap new folder button -> should show input dialog + await tester.tap(newFolderBtn); + await tester.pumpAndSettle(); + expect(find.text('新建文件夹'), findsOneWidget); + + // Cancel + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + }); + + group('Virtual Keyboard (Accessory Keyboard) Tests', () { + test('Pure string in JSON keys is strictly parsed as input without guessing', () { + final key1 = KeyboardKeyItem.fromJson(';'); + expect(key1.label, ';'); + expect(key1.value, ';'); + expect(key1.action, 'input'); + expect(key1.icon, isNull); + + // Verify strings with command names like Tab or () are NOT magically guessed + final key2 = KeyboardKeyItem.fromJson('Tab'); + expect(key2.label, 'Tab'); + expect(key2.value, 'Tab'); + expect(key2.action, 'input'); + + final key3 = KeyboardKeyItem.fromJson('{}'); + expect(key3.label, '{}'); + expect(key3.value, '{}'); + expect(key3.action, 'input'); + expect(key3.cursorOffset, 0); + + // Verify object format is parsed correctly + final keyObj = KeyboardKeyItem.fromJson({ + 'label': 'Tab', + 'icon': 'tab', + 'action': 'command', + 'value': 'tab', + }); + expect(keyObj.label, 'Tab'); + expect(keyObj.icon, 'tab'); + expect(keyObj.action, 'command'); + expect(keyObj.value, 'tab'); + }); + + test('KeyboardIconHelper maps known icons and returns null for unknown/empty', () { + expect(KeyboardIconHelper.getIcon('tab'), isNotNull); + expect(KeyboardIconHelper.getIcon('undo'), isNotNull); + expect(KeyboardIconHelper.getIcon('arrow_left'), isNotNull); + expect(KeyboardIconHelper.getIcon(null), isNull); + expect(KeyboardIconHelper.getIcon(''), isNull); + expect(KeyboardIconHelper.getIcon('non_existent_xyz'), isNull); + }); + + test('VirtualKeyboardConfig validateJson strictly identifies syntax and schema errors', () { + // Empty check + expect(VirtualKeyboardConfig.validateJson(''), '配置内容不能为空'); + expect(VirtualKeyboardConfig.validateJson(' '), '配置内容不能为空'); + + // Syntax check with line and column reporting + final syntaxErr = VirtualKeyboardConfig.validateJson('{\n "pages": [\n invalid\n ]\n}'); + expect(syntaxErr, contains('JSON 语法错误')); + expect(syntaxErr, contains('第 3 行')); + + // Root map check + expect(VirtualKeyboardConfig.validateJson('[]'), contains('根节点必须是 JSON 对象')); + + // Pages array check + expect(VirtualKeyboardConfig.validateJson('{}'), contains('缺少必需的 "pages"')); + expect(VirtualKeyboardConfig.validateJson('{"pages": "invalid"}'), contains('"pages" 字段必须是一个数组')); + expect(VirtualKeyboardConfig.validateJson('{"pages": []}'), contains('至少需要包含 1 个页面配置')); + + // Page item check + expect(VirtualKeyboardConfig.validateJson('{"pages": ["not-a-map"]}'), contains('第 1 页必须是一个 JSON 对象')); + expect(VirtualKeyboardConfig.validateJson('{"pages": [{}]}'), contains('缺少必需的 "count" 字段')); + expect(VirtualKeyboardConfig.validateJson('{"pages": [{"count": 0, "keys": []}]}'), contains('"count" 必须为大于 0 的正整数')); + expect(VirtualKeyboardConfig.validateJson('{"pages": [{"count": 6}]}'), contains('缺少必需的 "keys" 字段')); + + // Row check + expect(VirtualKeyboardConfig.validateJson('{"pages": [{"count": 6, "keys": ["not-a-list"]}]}'), contains('第 1 页第 1 行必须是一个按键数组')); + + // Key check + expect(VirtualKeyboardConfig.validateJson('{"pages": [{"count": 6, "keys": [[123]]}]}'), contains('只能是文本字符串或对象')); + expect(VirtualKeyboardConfig.validateJson('{"pages": [{"count": 6, "keys": [[{}]]}]}'), contains('缺少 label、value 或 icon 属性')); + + // Valid check (default config) + final validJson = VirtualKeyboardConfig.defaultJsonPretty(); + expect(VirtualKeyboardConfig.validateJson(validJson), isNull); + + // Valid check with shorthand pure strings + const shorthandJson = ''' + { + "pages": [ + { + "count": 6, + "keys": [ + [";", "=", "+", "-", "*", "/"], + ["(", ")", "[", "]", "{", "}"] + ] + } + ] + } + '''; + expect(VirtualKeyboardConfig.validateJson(shorthandJson), isNull); + }); + + testWidgets('VirtualKeyboardWidget renders keys according to count and handles input/commands', (tester) async { + final controller = CodeLineEditingController.fromText('hello'); + controller.selection = const CodeLineSelection.collapsed(index: 0, offset: 5); + + final config = VirtualKeyboardConfig.defaultConfiguration(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: VirtualKeyboardWidget( + controller: controller, + config: config, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // PageView should be present + expect(find.byType(PageView), findsOneWidget); + + // Tab icon exists + expect(find.byIcon(Icons.keyboard_tab), findsOneWidget); + + // Tap ';' key + final semicolonKey = find.text(';'); + expect(semicolonKey, findsOneWidget); + await tester.tap(semicolonKey); + await tester.pumpAndSettle(); + + // Controller should have received ';' + expect(controller.text, 'hello;'); + + // Tap '(' pair key -> should insert () and place cursor inside + final parenKey = find.text('('); + expect(parenKey, findsOneWidget); + await tester.tap(parenKey); + await tester.pumpAndSettle(); + + expect(controller.text, 'hello;()'); + expect(controller.selection.extentOffset, 7); // between '(' and ')' + }); + + testWidgets('SettingsView displays virtual keyboard toggle and config dialog with embedded CodeEditor and line-level error report', (tester) async { + final settingsProvider = SettingsProvider(); + await settingsProvider.init(); + await settingsProvider.setEnableVirtualKeyboard(true); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: settingsProvider, + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('zh'), + home: SettingsView(), + ), + ), + ); + await tester.pumpAndSettle(); + + // Scroll to virtual keyboard tiles + final configTile = find.text('编辑键盘配置'); + await tester.drag(find.byType(ListView), const Offset(0, -200)); + await tester.pumpAndSettle(); + expect(configTile, findsOneWidget); + + // Tap config tile to open dialog + await tester.tap(configTile); + await tester.pumpAndSettle(); + + expect(find.text('小键盘配置 (JSON)'), findsOneWidget); + expect(find.text('格式化'), findsOneWidget); + expect(find.text('恢复默认'), findsOneWidget); + + // Verify embedded CodeEditor is present with line number gutter + expect(find.byType(CodeEditor), findsOneWidget); + expect(find.byType(DefaultCodeLineNumber), findsOneWidget); + + final codeEditor = tester.widget(find.byType(CodeEditor)); + final editorController = codeEditor.controller!; + + // Edit controller with invalid json on line 3 + editorController.text = '{\n "pages": [\n error_here\n ]\n}'; + await tester.pumpAndSettle(); + + // Tap '保存' + await tester.tap(find.text('保存')); + await tester.pumpAndSettle(); + + // Dialog should still be open and display error message with line number + expect(find.text('小键盘配置 (JSON)'), findsOneWidget); + expect(find.byIcon(Icons.error_outline), findsOneWidget); + expect(find.textContaining('第 3 行'), findsOneWidget); + + // Tap '恢复默认' + await tester.tap(find.text('恢复默认')); + await tester.pumpAndSettle(); + + // Error message should clear + expect(find.byIcon(Icons.error_outline), findsNothing); + expect(editorController.text, contains('"pages"')); + + // Tap '保存' with valid config -> dialog closes + await tester.tap(find.text('保存')); + await tester.pumpAndSettle(); + + expect(find.text('小键盘配置 (JSON)'), findsNothing); + + // Let success toast timer complete + await tester.pump(const Duration(seconds: 3)); + }); + }); }