From b03ece33a22d91f53c7b3df04528b299a5f82e41 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Fri, 11 Sep 2026 16:03:47 +0800 Subject: [PATCH] 1 --- devtools_options.yaml | 3 + lib/l10n/app_en.arb | 99 +++ lib/l10n/app_localizations.dart | 538 ++++++++++- lib/l10n/app_localizations_en.dart | 324 +++++++ lib/l10n/app_localizations_zh.dart | 286 ++++++ lib/l10n/app_zh.arb | 90 +- lib/main.dart | 67 +- lib/models/editor_tab_item.dart | 59 ++ lib/models/editor_theme.dart | 177 ++++ lib/models/file_directory_history.dart | 17 +- lib/providers/editor_provider.dart | 332 ++----- lib/providers/project_provider.dart | 334 +++++++ lib/providers/settings_provider.dart | 117 +++ lib/providers/tab_provider.dart | 470 ++++++++++ .../file_directory_history_service.dart | 4 + lib/services/file_watcher_service.dart | 122 +++ lib/utils/dialog_utils.dart | 568 ++++++++++++ lib/utils/syntax_highlight_helper.dart | 178 ++++ lib/views/main_view.dart | 106 ++- lib/views/settings_view.dart | 507 +++++++++++ lib/widgets/code_editor_app_bar.dart | 120 ++- lib/widgets/code_editor_drawer.dart | 41 +- lib/widgets/code_editor_menu.dart | 114 +++ lib/widgets/code_editor_tab_bar.dart | 241 +++++ lib/widgets/code_editor_widget.dart | 465 +++++++++- .../file_directory_history_widget.dart | 35 +- lib/widgets/file_item_widget.dart | 503 ++++------- lib/widgets/file_tree_widget.dart | 15 +- linux/flutter/generated_plugin_registrant.cc | 4 - linux/flutter/generated_plugins.cmake | 1 - macos/Flutter/GeneratedPluginRegistrant.swift | 2 - pubspec.lock | 210 +---- pubspec.yaml | 5 +- test/dialog_utils_test.dart | 299 +++++++ test/widget_test.dart | 839 ++++++++++++++++++ .../flutter/generated_plugin_registrant.cc | 3 - windows/flutter/generated_plugins.cmake | 1 - 37 files changed, 6388 insertions(+), 908 deletions(-) create mode 100644 devtools_options.yaml create mode 100644 lib/l10n/app_en.arb create mode 100644 lib/l10n/app_localizations_en.dart create mode 100644 lib/models/editor_tab_item.dart create mode 100644 lib/models/editor_theme.dart create mode 100644 lib/providers/project_provider.dart create mode 100644 lib/providers/settings_provider.dart create mode 100644 lib/providers/tab_provider.dart create mode 100644 lib/services/file_watcher_service.dart create mode 100644 lib/utils/dialog_utils.dart create mode 100644 lib/utils/syntax_highlight_helper.dart create mode 100644 lib/views/settings_view.dart create mode 100644 lib/widgets/code_editor_menu.dart create mode 100644 lib/widgets/code_editor_tab_bar.dart create mode 100644 test/dialog_utils_test.dart diff --git a/devtools_options.yaml b/devtools_options.yaml new file mode 100644 index 0000000..fa0b357 --- /dev/null +++ b/devtools_options.yaml @@ -0,0 +1,3 @@ +description: This file stores settings for Dart & Flutter DevTools. +documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states +extensions: diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb new file mode 100644 index 0000000..e19a95b --- /dev/null +++ b/lib/l10n/app_en.arb @@ -0,0 +1,99 @@ +{ + "@@locale": "en", + "appTitle": "Code Editor", + "run": "Run", + "settings": "Settings", + "fileDirectory": "File Directory", + "undo": "Undo", + "redo": "Redo", + "save": "Save", + "openFileDirectory": "Open File Directory", + "viewFileDirectoryHistory": "View Directory History", + "more": "More", + "noOpenDirectory": "No directory opened", + "noOpenFile": "No file opened", + "unnamed": "Untitled", + "unknownDirectory": "Unknown Directory", + "historyFileDirectories": "Directory History", + "noHistory": "No history records", + "deleteThisHistory": "Delete this record", + "deleteHistoryTitle": "Delete History", + "deleteHistoryMessage": "Are you sure you want to remove this project from history?", + "remove": "Remove", + "historyRemoved": "History record removed", + "confirm": "Confirm", + "cancel": "Cancel", + "delete": "Delete", + "close": "Close", + "gotIt": "Got it", + "done": "Done", + "newFile": "New File", + "newFolder": "New Folder", + "fileNameHint": "File name (e.g. main.dart)", + "folderNameHint": "Folder name", + "rename": "Rename", + "newName": "New name", + "cut": "Cut", + "copy": "Copy", + "paste": "Paste", + "selectAll": "Select All", + "copyPath": "Copy Path", + "copyRelativePath": "Copy Relative Path", + "copiedPathToClipboard": "Full path copied to clipboard", + "copiedRelativePathToClipboard": "Relative path copied to clipboard", + "cutItem": "Cut: {name}", + "copiedItem": "Copied: {name}", + "operationSuccess": "Operation successful", + "operationFailed": "Operation failed: {error}", + "createFileFailed": "Failed to create file: {error}", + "createFolderFailed": "Failed to create folder: {error}", + "renameFailed": "Failed to rename: {error}", + "deleteFailed": "Failed to delete: {error}", + "confirmDelete": "Confirm Delete", + "confirmDeleteMessage": "Are you sure you want to delete \"{name}\"? This cannot be undone.", + "nameCannotBeEmpty": "Name cannot be empty", + "nameInvalidChars": "Name cannot contain invalid characters (\\/:*?\"<>|)", + "appearanceSection": "Appearance", + "appThemeMode": "App Theme Mode", + "followSystem": "Follow System", + "followSystemSubtitle": "Match system appearance automatically", + "lightMode": "Light Mode", + "lightModeSubtitle": "Always stay light", + "darkMode": "Dark Mode", + "darkModeSubtitle": "Always stay dark", + "selectAppTheme": "Select App Theme", + "editorSection": "Editor", + "codeHighlightTheme": "Code Highlight Theme", + "selectCodeHighlightTheme": "Select Code Highlight Theme", + "darkThemeCategory": "Dark Theme", + "lightThemeCategory": "Light Theme", + "codeFontSize": "Font Size", + "decreaseFontSize": "Decrease font size", + "increaseFontSize": "Increase font size", + "fontSizeDialogTitle": "Editor Font Size", + "wordWrap": "Word Wrap", + "wordWrapSubtitle": "Wrap long lines to fit the editor width", + "languageSection": "Language", + "appLanguage": "App Language", + "selectLanguage": "Select App Language", + "languageFollowSystem": "Follow System", + "languageChinese": "简体中文", + "languageEnglish": "English", + "refreshDirectory": "Refresh Directory", + "back": "Back", + "darkLabel": "Dark", + "lightLabel": "Light", + "saveSuccess": "Saved successfully", + "saveFailed": "Failed to save: {error}", + "saveChangesTitle": "Save Changes", + "saveChangesMessage": "File \"{name}\" has been modified, save changes?", + "dontSave": "Don't Save", + "saveAll": "Save All", + "saveAllSuccess": "All files saved", + "saveAllPromptTitle": "Save All Changes?", + "saveAllPromptMessage": "There are unsaved changes in the project. Do you want to save all files?", + "fileConflictTitle": "File Changed Externally", + "fileConflictMessage": "File \"{name}\" has been changed on disk. How would you like to proceed?", + "reloadFromDisk": "Reload from Disk", + "keepLocal": "Keep Local Changes" +} \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 55e099f..d73be8b 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -5,6 +5,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:intl/intl.dart' as intl; +import 'app_localizations_en.dart'; import 'app_localizations_zh.dart'; // ignore_for_file: type=lint @@ -92,7 +93,16 @@ abstract class AppLocalizations { ]; /// A list of this localizations delegate's supported locales. - static const List supportedLocales = [Locale('zh')]; + static const List supportedLocales = [ + Locale('en'), + Locale('zh'), + ]; + + /// No description provided for @appTitle. + /// + /// In zh, this message translates to: + /// **'代码编辑器'** + String get appTitle; /// No description provided for @run. /// @@ -141,6 +151,528 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'查看文件目录历史'** String get viewFileDirectoryHistory; + + /// No description provided for @more. + /// + /// In zh, this message translates to: + /// **'更多'** + String get more; + + /// No description provided for @noOpenDirectory. + /// + /// In zh, this message translates to: + /// **'当前未打开文件目录'** + String get noOpenDirectory; + + /// No description provided for @noOpenFile. + /// + /// In zh, this message translates to: + /// **'当前未打开文件'** + String get noOpenFile; + + /// No description provided for @unnamed. + /// + /// In zh, this message translates to: + /// **'未命名'** + String get unnamed; + + /// No description provided for @unknownDirectory. + /// + /// In zh, this message translates to: + /// **'未知目录'** + String get unknownDirectory; + + /// No description provided for @historyFileDirectories. + /// + /// In zh, this message translates to: + /// **'历史文件目录'** + String get historyFileDirectories; + + /// No description provided for @noHistory. + /// + /// In zh, this message translates to: + /// **'暂无历史记录'** + String get noHistory; + + /// No description provided for @deleteThisHistory. + /// + /// In zh, this message translates to: + /// **'删除此记录'** + String get deleteThisHistory; + + /// No description provided for @deleteHistoryTitle. + /// + /// In zh, this message translates to: + /// **'删除历史记录'** + String get deleteHistoryTitle; + + /// No description provided for @deleteHistoryMessage. + /// + /// In zh, this message translates to: + /// **'确定要从历史记录中移除该项目吗?'** + String get deleteHistoryMessage; + + /// No description provided for @remove. + /// + /// In zh, this message translates to: + /// **'移除'** + String get remove; + + /// No description provided for @historyRemoved. + /// + /// In zh, this message translates to: + /// **'已移除历史记录'** + String get historyRemoved; + + /// No description provided for @confirm. + /// + /// In zh, this message translates to: + /// **'确定'** + String get confirm; + + /// No description provided for @cancel. + /// + /// In zh, this message translates to: + /// **'取消'** + String get cancel; + + /// No description provided for @delete. + /// + /// In zh, this message translates to: + /// **'删除'** + String get delete; + + /// No description provided for @close. + /// + /// In zh, this message translates to: + /// **'关闭'** + String get close; + + /// No description provided for @gotIt. + /// + /// In zh, this message translates to: + /// **'知道了'** + String get gotIt; + + /// No description provided for @done. + /// + /// In zh, this message translates to: + /// **'完成'** + String get done; + + /// No description provided for @newFile. + /// + /// In zh, this message translates to: + /// **'新建文件'** + String get newFile; + + /// No description provided for @newFolder. + /// + /// In zh, this message translates to: + /// **'新建文件夹'** + String get newFolder; + + /// No description provided for @fileNameHint. + /// + /// In zh, this message translates to: + /// **'文件名 (例如: main.dart)'** + String get fileNameHint; + + /// No description provided for @folderNameHint. + /// + /// In zh, this message translates to: + /// **'文件夹名'** + String get folderNameHint; + + /// No description provided for @rename. + /// + /// In zh, this message translates to: + /// **'重命名'** + String get rename; + + /// No description provided for @newName. + /// + /// In zh, this message translates to: + /// **'新名称'** + String get newName; + + /// No description provided for @cut. + /// + /// In zh, this message translates to: + /// **'剪切'** + String get cut; + + /// No description provided for @copy. + /// + /// In zh, this message translates to: + /// **'复制'** + String get copy; + + /// No description provided for @paste. + /// + /// In zh, this message translates to: + /// **'粘贴'** + String get paste; + + /// No description provided for @selectAll. + /// + /// In zh, this message translates to: + /// **'全选'** + String get selectAll; + + /// No description provided for @copyPath. + /// + /// In zh, this message translates to: + /// **'复制路径'** + String get copyPath; + + /// No description provided for @copyRelativePath. + /// + /// In zh, this message translates to: + /// **'复制相对路径'** + String get copyRelativePath; + + /// No description provided for @copiedPathToClipboard. + /// + /// In zh, this message translates to: + /// **'已复制完整路径到剪贴板'** + String get copiedPathToClipboard; + + /// No description provided for @copiedRelativePathToClipboard. + /// + /// In zh, this message translates to: + /// **'已复制相对路径到剪贴板'** + String get copiedRelativePathToClipboard; + + /// No description provided for @cutItem. + /// + /// In zh, this message translates to: + /// **'已剪切: {name}'** + String cutItem(Object name); + + /// No description provided for @copiedItem. + /// + /// In zh, this message translates to: + /// **'已复制: {name}'** + String copiedItem(Object name); + + /// No description provided for @operationSuccess. + /// + /// In zh, this message translates to: + /// **'操作成功'** + String get operationSuccess; + + /// No description provided for @operationFailed. + /// + /// In zh, this message translates to: + /// **'操作失败: {error}'** + String operationFailed(Object error); + + /// No description provided for @createFileFailed. + /// + /// In zh, this message translates to: + /// **'创建文件失败: {error}'** + String createFileFailed(Object error); + + /// No description provided for @createFolderFailed. + /// + /// In zh, this message translates to: + /// **'创建文件夹失败: {error}'** + String createFolderFailed(Object error); + + /// No description provided for @renameFailed. + /// + /// In zh, this message translates to: + /// **'重命名失败: {error}'** + String renameFailed(Object error); + + /// No description provided for @deleteFailed. + /// + /// In zh, this message translates to: + /// **'删除失败: {error}'** + String deleteFailed(Object error); + + /// No description provided for @confirmDelete. + /// + /// In zh, this message translates to: + /// **'确认删除'** + String get confirmDelete; + + /// No description provided for @confirmDeleteMessage. + /// + /// In zh, this message translates to: + /// **'确定要删除 \"{name}\" 吗?此操作不可恢复。'** + String confirmDeleteMessage(Object name); + + /// No description provided for @nameCannotBeEmpty. + /// + /// In zh, this message translates to: + /// **'名称不能为空'** + String get nameCannotBeEmpty; + + /// No description provided for @nameInvalidChars. + /// + /// In zh, this message translates to: + /// **'名称不能包含非法字符 (\\/:*?\"<>|)'** + String get nameInvalidChars; + + /// No description provided for @appearanceSection. + /// + /// In zh, this message translates to: + /// **'外观'** + String get appearanceSection; + + /// No description provided for @appThemeMode. + /// + /// In zh, this message translates to: + /// **'应用主题模式'** + String get appThemeMode; + + /// No description provided for @followSystem. + /// + /// In zh, this message translates to: + /// **'跟随系统'** + String get followSystem; + + /// No description provided for @followSystemSubtitle. + /// + /// In zh, this message translates to: + /// **'自动与系统深浅色外观保持一致'** + String get followSystemSubtitle; + + /// No description provided for @lightMode. + /// + /// In zh, this message translates to: + /// **'浅色模式'** + String get lightMode; + + /// No description provided for @lightModeSubtitle. + /// + /// In zh, this message translates to: + /// **'始终保持明亮外观'** + String get lightModeSubtitle; + + /// No description provided for @darkMode. + /// + /// In zh, this message translates to: + /// **'深色模式'** + String get darkMode; + + /// No description provided for @darkModeSubtitle. + /// + /// In zh, this message translates to: + /// **'始终保持暗黑外观'** + String get darkModeSubtitle; + + /// No description provided for @selectAppTheme. + /// + /// In zh, this message translates to: + /// **'选择应用主题'** + String get selectAppTheme; + + /// No description provided for @editorSection. + /// + /// In zh, this message translates to: + /// **'编辑区'** + String get editorSection; + + /// No description provided for @codeHighlightTheme. + /// + /// In zh, this message translates to: + /// **'代码高亮主题'** + String get codeHighlightTheme; + + /// No description provided for @selectCodeHighlightTheme. + /// + /// In zh, this message translates to: + /// **'选择代码高亮主题'** + String get selectCodeHighlightTheme; + + /// No description provided for @darkThemeCategory. + /// + /// In zh, this message translates to: + /// **'暗色系'** + String get darkThemeCategory; + + /// No description provided for @lightThemeCategory. + /// + /// In zh, this message translates to: + /// **'浅色系'** + String get lightThemeCategory; + + /// No description provided for @codeFontSize. + /// + /// In zh, this message translates to: + /// **'代码字号缩放'** + String get codeFontSize; + + /// No description provided for @decreaseFontSize. + /// + /// In zh, this message translates to: + /// **'减小字号'** + String get decreaseFontSize; + + /// No description provided for @increaseFontSize. + /// + /// In zh, this message translates to: + /// **'增大字号'** + String get increaseFontSize; + + /// No description provided for @fontSizeDialogTitle. + /// + /// In zh, this message translates to: + /// **'代码字号'** + String get fontSizeDialogTitle; + + /// No description provided for @wordWrap. + /// + /// In zh, this message translates to: + /// **'自动换行'** + String get wordWrap; + + /// No description provided for @wordWrapSubtitle. + /// + /// In zh, this message translates to: + /// **'长代码行超出边界时自动折行'** + String get wordWrapSubtitle; + + /// No description provided for @languageSection. + /// + /// In zh, this message translates to: + /// **'语言'** + String get languageSection; + + /// No description provided for @appLanguage. + /// + /// In zh, this message translates to: + /// **'应用语言'** + String get appLanguage; + + /// No description provided for @selectLanguage. + /// + /// In zh, this message translates to: + /// **'选择应用语言'** + String get selectLanguage; + + /// No description provided for @languageFollowSystem. + /// + /// In zh, this message translates to: + /// **'跟随系统'** + String get languageFollowSystem; + + /// No description provided for @languageChinese. + /// + /// In zh, this message translates to: + /// **'简体中文'** + String get languageChinese; + + /// No description provided for @languageEnglish. + /// + /// In zh, this message translates to: + /// **'English'** + String get languageEnglish; + + /// No description provided for @refreshDirectory. + /// + /// In zh, this message translates to: + /// **'刷新目录'** + String get refreshDirectory; + + /// No description provided for @back. + /// + /// In zh, this message translates to: + /// **'返回'** + String get back; + + /// No description provided for @darkLabel. + /// + /// In zh, this message translates to: + /// **'暗色'** + String get darkLabel; + + /// No description provided for @lightLabel. + /// + /// In zh, this message translates to: + /// **'浅色'** + String get lightLabel; + + /// No description provided for @saveSuccess. + /// + /// In zh, this message translates to: + /// **'保存成功'** + String get saveSuccess; + + /// No description provided for @saveFailed. + /// + /// In zh, this message translates to: + /// **'保存失败: {error}'** + String saveFailed(Object error); + + /// No description provided for @saveChangesTitle. + /// + /// In zh, this message translates to: + /// **'保存更改'** + String get saveChangesTitle; + + /// No description provided for @saveChangesMessage. + /// + /// In zh, this message translates to: + /// **'文件 \"{name}\" 已被修改,是否保存更改?'** + String saveChangesMessage(Object name); + + /// No description provided for @dontSave. + /// + /// In zh, this message translates to: + /// **'不保存'** + String get dontSave; + + /// No description provided for @saveAll. + /// + /// In zh, this message translates to: + /// **'保存所有'** + String get saveAll; + + /// No description provided for @saveAllSuccess. + /// + /// In zh, this message translates to: + /// **'所有文件已保存'** + String get saveAllSuccess; + + /// No description provided for @saveAllPromptTitle. + /// + /// In zh, this message translates to: + /// **'保存所有更改?'** + String get saveAllPromptTitle; + + /// No description provided for @saveAllPromptMessage. + /// + /// In zh, this message translates to: + /// **'当前项目中有未保存的修改,是否保存所有文件?'** + String get saveAllPromptMessage; + + /// No description provided for @fileConflictTitle. + /// + /// In zh, this message translates to: + /// **'外部文件已被更改'** + String get fileConflictTitle; + + /// No description provided for @fileConflictMessage. + /// + /// In zh, this message translates to: + /// **'文件 \"{name}\" 已在外部被更改。您希望如何处理?'** + String fileConflictMessage(Object name); + + /// No description provided for @reloadFromDisk. + /// + /// In zh, this message translates to: + /// **'用磁盘内容覆盖'** + String get reloadFromDisk; + + /// No description provided for @keepLocal. + /// + /// In zh, this message translates to: + /// **'保留本地修改'** + String get keepLocal; } class _AppLocalizationsDelegate @@ -154,7 +686,7 @@ class _AppLocalizationsDelegate @override bool isSupported(Locale locale) => - ['zh'].contains(locale.languageCode); + ['en', 'zh'].contains(locale.languageCode); @override bool shouldReload(_AppLocalizationsDelegate old) => false; @@ -163,6 +695,8 @@ class _AppLocalizationsDelegate AppLocalizations lookupAppLocalizations(Locale locale) { // Lookup logic when only language code is specified. switch (locale.languageCode) { + case 'en': + return AppLocalizationsEn(); case 'zh': return AppLocalizationsZh(); } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart new file mode 100644 index 0000000..35b59b1 --- /dev/null +++ b/lib/l10n/app_localizations_en.dart @@ -0,0 +1,324 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for English (`en`). +class AppLocalizationsEn extends AppLocalizations { + AppLocalizationsEn([String locale = 'en']) : super(locale); + + @override + String get appTitle => 'Code Editor'; + + @override + String get run => 'Run'; + + @override + String get settings => 'Settings'; + + @override + String get fileDirectory => 'File Directory'; + + @override + String get undo => 'Undo'; + + @override + String get redo => 'Redo'; + + @override + String get save => 'Save'; + + @override + String get openFileDirectory => 'Open File Directory'; + + @override + String get viewFileDirectoryHistory => 'View Directory History'; + + @override + String get more => 'More'; + + @override + String get noOpenDirectory => 'No directory opened'; + + @override + String get noOpenFile => 'No file opened'; + + @override + String get unnamed => 'Untitled'; + + @override + String get unknownDirectory => 'Unknown Directory'; + + @override + String get historyFileDirectories => 'Directory History'; + + @override + String get noHistory => 'No history records'; + + @override + String get deleteThisHistory => 'Delete this record'; + + @override + String get deleteHistoryTitle => 'Delete History'; + + @override + String get deleteHistoryMessage => + 'Are you sure you want to remove this project from history?'; + + @override + String get remove => 'Remove'; + + @override + String get historyRemoved => 'History record removed'; + + @override + String get confirm => 'Confirm'; + + @override + String get cancel => 'Cancel'; + + @override + String get delete => 'Delete'; + + @override + String get close => 'Close'; + + @override + String get gotIt => 'Got it'; + + @override + String get done => 'Done'; + + @override + String get newFile => 'New File'; + + @override + String get newFolder => 'New Folder'; + + @override + String get fileNameHint => 'File name (e.g. main.dart)'; + + @override + String get folderNameHint => 'Folder name'; + + @override + String get rename => 'Rename'; + + @override + String get newName => 'New name'; + + @override + String get cut => 'Cut'; + + @override + String get copy => 'Copy'; + + @override + String get paste => 'Paste'; + + @override + String get selectAll => 'Select All'; + + @override + String get copyPath => 'Copy Path'; + + @override + String get copyRelativePath => 'Copy Relative Path'; + + @override + String get copiedPathToClipboard => 'Full path copied to clipboard'; + + @override + String get copiedRelativePathToClipboard => + 'Relative path copied to clipboard'; + + @override + String cutItem(Object name) { + return 'Cut: $name'; + } + + @override + String copiedItem(Object name) { + return 'Copied: $name'; + } + + @override + String get operationSuccess => 'Operation successful'; + + @override + String operationFailed(Object error) { + return 'Operation failed: $error'; + } + + @override + String createFileFailed(Object error) { + return 'Failed to create file: $error'; + } + + @override + String createFolderFailed(Object error) { + return 'Failed to create folder: $error'; + } + + @override + String renameFailed(Object error) { + return 'Failed to rename: $error'; + } + + @override + String deleteFailed(Object error) { + return 'Failed to delete: $error'; + } + + @override + String get confirmDelete => 'Confirm Delete'; + + @override + String confirmDeleteMessage(Object name) { + return 'Are you sure you want to delete \"$name\"? This cannot be undone.'; + } + + @override + String get nameCannotBeEmpty => 'Name cannot be empty'; + + @override + String get nameInvalidChars => + 'Name cannot contain invalid characters (\\/:*?\"<>|)'; + + @override + String get appearanceSection => 'Appearance'; + + @override + String get appThemeMode => 'App Theme Mode'; + + @override + String get followSystem => 'Follow System'; + + @override + String get followSystemSubtitle => 'Match system appearance automatically'; + + @override + String get lightMode => 'Light Mode'; + + @override + String get lightModeSubtitle => 'Always stay light'; + + @override + String get darkMode => 'Dark Mode'; + + @override + String get darkModeSubtitle => 'Always stay dark'; + + @override + String get selectAppTheme => 'Select App Theme'; + + @override + String get editorSection => 'Editor'; + + @override + String get codeHighlightTheme => 'Code Highlight Theme'; + + @override + String get selectCodeHighlightTheme => 'Select Code Highlight Theme'; + + @override + String get darkThemeCategory => 'Dark Theme'; + + @override + String get lightThemeCategory => 'Light Theme'; + + @override + String get codeFontSize => 'Font Size'; + + @override + String get decreaseFontSize => 'Decrease font size'; + + @override + String get increaseFontSize => 'Increase font size'; + + @override + String get fontSizeDialogTitle => 'Editor Font Size'; + + @override + String get wordWrap => 'Word Wrap'; + + @override + String get wordWrapSubtitle => 'Wrap long lines to fit the editor width'; + + @override + String get languageSection => 'Language'; + + @override + String get appLanguage => 'App Language'; + + @override + String get selectLanguage => 'Select App Language'; + + @override + String get languageFollowSystem => 'Follow System'; + + @override + String get languageChinese => '简体中文'; + + @override + String get languageEnglish => 'English'; + + @override + String get refreshDirectory => 'Refresh Directory'; + + @override + String get back => 'Back'; + + @override + String get darkLabel => 'Dark'; + + @override + String get lightLabel => 'Light'; + + @override + String get saveSuccess => 'Saved successfully'; + + @override + String saveFailed(Object error) { + return 'Failed to save: $error'; + } + + @override + String get saveChangesTitle => 'Save Changes'; + + @override + String saveChangesMessage(Object name) { + return 'File \"$name\" has been modified, save changes?'; + } + + @override + String get dontSave => 'Don\'t Save'; + + @override + String get saveAll => 'Save All'; + + @override + String get saveAllSuccess => 'All files saved'; + + @override + String get saveAllPromptTitle => 'Save All Changes?'; + + @override + String get saveAllPromptMessage => + 'There are unsaved changes in the project. Do you want to save all files?'; + + @override + String get fileConflictTitle => 'File Changed Externally'; + + @override + String fileConflictMessage(Object name) { + return 'File \"$name\" has been changed on disk. How would you like to proceed?'; + } + + @override + String get reloadFromDisk => 'Reload from Disk'; + + @override + String get keepLocal => 'Keep Local Changes'; +} diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a5576c0..3eb5041 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -8,6 +8,9 @@ import 'app_localizations.dart'; class AppLocalizationsZh extends AppLocalizations { AppLocalizationsZh([String locale = 'zh']) : super(locale); + @override + String get appTitle => '代码编辑器'; + @override String get run => '运行'; @@ -31,4 +34,287 @@ class AppLocalizationsZh extends AppLocalizations { @override String get viewFileDirectoryHistory => '查看文件目录历史'; + + @override + String get more => '更多'; + + @override + String get noOpenDirectory => '当前未打开文件目录'; + + @override + String get noOpenFile => '当前未打开文件'; + + @override + String get unnamed => '未命名'; + + @override + String get unknownDirectory => '未知目录'; + + @override + String get historyFileDirectories => '历史文件目录'; + + @override + String get noHistory => '暂无历史记录'; + + @override + String get deleteThisHistory => '删除此记录'; + + @override + String get deleteHistoryTitle => '删除历史记录'; + + @override + String get deleteHistoryMessage => '确定要从历史记录中移除该项目吗?'; + + @override + String get remove => '移除'; + + @override + String get historyRemoved => '已移除历史记录'; + + @override + String get confirm => '确定'; + + @override + String get cancel => '取消'; + + @override + String get delete => '删除'; + + @override + String get close => '关闭'; + + @override + String get gotIt => '知道了'; + + @override + String get done => '完成'; + + @override + String get newFile => '新建文件'; + + @override + String get newFolder => '新建文件夹'; + + @override + String get fileNameHint => '文件名 (例如: main.dart)'; + + @override + String get folderNameHint => '文件夹名'; + + @override + String get rename => '重命名'; + + @override + String get newName => '新名称'; + + @override + String get cut => '剪切'; + + @override + String get copy => '复制'; + + @override + String get paste => '粘贴'; + + @override + String get selectAll => '全选'; + + @override + String get copyPath => '复制路径'; + + @override + String get copyRelativePath => '复制相对路径'; + + @override + String get copiedPathToClipboard => '已复制完整路径到剪贴板'; + + @override + String get copiedRelativePathToClipboard => '已复制相对路径到剪贴板'; + + @override + String cutItem(Object name) { + return '已剪切: $name'; + } + + @override + String copiedItem(Object name) { + return '已复制: $name'; + } + + @override + String get operationSuccess => '操作成功'; + + @override + String operationFailed(Object error) { + return '操作失败: $error'; + } + + @override + String createFileFailed(Object error) { + return '创建文件失败: $error'; + } + + @override + String createFolderFailed(Object error) { + return '创建文件夹失败: $error'; + } + + @override + String renameFailed(Object error) { + return '重命名失败: $error'; + } + + @override + String deleteFailed(Object error) { + return '删除失败: $error'; + } + + @override + String get confirmDelete => '确认删除'; + + @override + String confirmDeleteMessage(Object name) { + return '确定要删除 \"$name\" 吗?此操作不可恢复。'; + } + + @override + String get nameCannotBeEmpty => '名称不能为空'; + + @override + String get nameInvalidChars => '名称不能包含非法字符 (\\/:*?\"<>|)'; + + @override + String get appearanceSection => '外观'; + + @override + String get appThemeMode => '应用主题模式'; + + @override + String get followSystem => '跟随系统'; + + @override + String get followSystemSubtitle => '自动与系统深浅色外观保持一致'; + + @override + String get lightMode => '浅色模式'; + + @override + String get lightModeSubtitle => '始终保持明亮外观'; + + @override + String get darkMode => '深色模式'; + + @override + String get darkModeSubtitle => '始终保持暗黑外观'; + + @override + String get selectAppTheme => '选择应用主题'; + + @override + String get editorSection => '编辑区'; + + @override + String get codeHighlightTheme => '代码高亮主题'; + + @override + String get selectCodeHighlightTheme => '选择代码高亮主题'; + + @override + String get darkThemeCategory => '暗色系'; + + @override + String get lightThemeCategory => '浅色系'; + + @override + String get codeFontSize => '代码字号缩放'; + + @override + String get decreaseFontSize => '减小字号'; + + @override + String get increaseFontSize => '增大字号'; + + @override + String get fontSizeDialogTitle => '代码字号'; + + @override + String get wordWrap => '自动换行'; + + @override + String get wordWrapSubtitle => '长代码行超出边界时自动折行'; + + @override + String get languageSection => '语言'; + + @override + String get appLanguage => '应用语言'; + + @override + String get selectLanguage => '选择应用语言'; + + @override + String get languageFollowSystem => '跟随系统'; + + @override + String get languageChinese => '简体中文'; + + @override + String get languageEnglish => 'English'; + + @override + String get refreshDirectory => '刷新目录'; + + @override + String get back => '返回'; + + @override + String get darkLabel => '暗色'; + + @override + String get lightLabel => '浅色'; + + @override + String get saveSuccess => '保存成功'; + + @override + String saveFailed(Object error) { + return '保存失败: $error'; + } + + @override + String get saveChangesTitle => '保存更改'; + + @override + String saveChangesMessage(Object name) { + return '文件 \"$name\" 已被修改,是否保存更改?'; + } + + @override + String get dontSave => '不保存'; + + @override + String get saveAll => '保存所有'; + + @override + String get saveAllSuccess => '所有文件已保存'; + + @override + String get saveAllPromptTitle => '保存所有更改?'; + + @override + String get saveAllPromptMessage => '当前项目中有未保存的修改,是否保存所有文件?'; + + @override + String get fileConflictTitle => '外部文件已被更改'; + + @override + String fileConflictMessage(Object name) { + return '文件 \"$name\" 已在外部被更改。您希望如何处理?'; + } + + @override + String get reloadFromDisk => '用磁盘内容覆盖'; + + @override + String get keepLocal => '保留本地修改'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 57a1f28..f60bc9d 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1,5 +1,6 @@ { "@@locale": "zh", + "appTitle": "代码编辑器", "run": "运行", "settings": "设置", "fileDirectory": "文件目录", @@ -7,5 +8,92 @@ "redo": "重做", "save": "保存", "openFileDirectory": "打开文件目录", - "viewFileDirectoryHistory": "查看文件目录历史" + "viewFileDirectoryHistory": "查看文件目录历史", + "more": "更多", + "noOpenDirectory": "当前未打开文件目录", + "noOpenFile": "当前未打开文件", + "unnamed": "未命名", + "unknownDirectory": "未知目录", + "historyFileDirectories": "历史文件目录", + "noHistory": "暂无历史记录", + "deleteThisHistory": "删除此记录", + "deleteHistoryTitle": "删除历史记录", + "deleteHistoryMessage": "确定要从历史记录中移除该项目吗?", + "remove": "移除", + "historyRemoved": "已移除历史记录", + "confirm": "确定", + "cancel": "取消", + "delete": "删除", + "close": "关闭", + "gotIt": "知道了", + "done": "完成", + "newFile": "新建文件", + "newFolder": "新建文件夹", + "fileNameHint": "文件名 (例如: main.dart)", + "folderNameHint": "文件夹名", + "rename": "重命名", + "newName": "新名称", + "cut": "剪切", + "copy": "复制", + "paste": "粘贴", + "selectAll": "全选", + "copyPath": "复制路径", + "copyRelativePath": "复制相对路径", + "copiedPathToClipboard": "已复制完整路径到剪贴板", + "copiedRelativePathToClipboard": "已复制相对路径到剪贴板", + "cutItem": "已剪切: {name}", + "copiedItem": "已复制: {name}", + "operationSuccess": "操作成功", + "operationFailed": "操作失败: {error}", + "createFileFailed": "创建文件失败: {error}", + "createFolderFailed": "创建文件夹失败: {error}", + "renameFailed": "重命名失败: {error}", + "deleteFailed": "删除失败: {error}", + "confirmDelete": "确认删除", + "confirmDeleteMessage": "确定要删除 \"{name}\" 吗?此操作不可恢复。", + "nameCannotBeEmpty": "名称不能为空", + "nameInvalidChars": "名称不能包含非法字符 (\\/:*?\"<>|)", + "appearanceSection": "外观", + "appThemeMode": "应用主题模式", + "followSystem": "跟随系统", + "followSystemSubtitle": "自动与系统深浅色外观保持一致", + "lightMode": "浅色模式", + "lightModeSubtitle": "始终保持明亮外观", + "darkMode": "深色模式", + "darkModeSubtitle": "始终保持暗黑外观", + "selectAppTheme": "选择应用主题", + "editorSection": "编辑区", + "codeHighlightTheme": "代码高亮主题", + "selectCodeHighlightTheme": "选择代码高亮主题", + "darkThemeCategory": "暗色系", + "lightThemeCategory": "浅色系", + "codeFontSize": "代码字号缩放", + "decreaseFontSize": "减小字号", + "increaseFontSize": "增大字号", + "fontSizeDialogTitle": "代码字号", + "wordWrap": "自动换行", + "wordWrapSubtitle": "长代码行超出边界时自动折行", + "languageSection": "语言", + "appLanguage": "应用语言", + "selectLanguage": "选择应用语言", + "languageFollowSystem": "跟随系统", + "languageChinese": "简体中文", + "languageEnglish": "English", + "refreshDirectory": "刷新目录", + "back": "返回", + "darkLabel": "暗色", + "lightLabel": "浅色", + "saveSuccess": "保存成功", + "saveFailed": "保存失败: {error}", + "saveChangesTitle": "保存更改", + "saveChangesMessage": "文件 \"{name}\" 已被修改,是否保存更改?", + "dontSave": "不保存", + "saveAll": "保存所有", + "saveAllSuccess": "所有文件已保存", + "saveAllPromptTitle": "保存所有更改?", + "saveAllPromptMessage": "当前项目中有未保存的修改,是否保存所有文件?", + "fileConflictTitle": "外部文件已被更改", + "fileConflictMessage": "文件 \"{name}\" 已在外部被更改。您希望如何处理?", + "reloadFromDisk": "用磁盘内容覆盖", + "keepLocal": "保留本地修改" } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 97ba93c..c356844 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,8 @@ 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'; import 'package:code_editor/views/main_view.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -13,26 +16,60 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return ChangeNotifierProvider( - create: (_) => EditorProvider()..init(), - child: MaterialApp( - debugShowCheckedModeBanner: false, - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - title: 'Flutter Demo', - theme: ThemeData( - useMaterial3: true, - colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), - fontFamilyFallback: const [ + return MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()..init()), + ChangeNotifierProvider(create: (_) => ProjectProvider()..init()), + ChangeNotifierProxyProvider( + create: (_) => TabProvider()..init(), + 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) { + const fontFallbacks = [ 'PingFang SC', // iOS / macOS 'Noto Sans SC', // Android 'Microsoft YaHei', // Windows 'WenQuanYi Micro Hei', // Linux 'sans-serif', // Web & generic fallback - ], - ), - home: const MainView(), + ]; + + return MaterialApp( + debugShowCheckedModeBanner: false, + locale: settings.locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle, + themeMode: settings.appThemeMode, + theme: ThemeData( + useMaterial3: true, + brightness: Brightness.light, + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: Brightness.light, + ), + fontFamilyFallback: fontFallbacks, + ), + darkTheme: ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: Brightness.dark, + ), + fontFamilyFallback: fontFallbacks, + ), + home: const MainView(), + ); + }, ), ); } -} \ No newline at end of file +} diff --git a/lib/models/editor_tab_item.dart b/lib/models/editor_tab_item.dart new file mode 100644 index 0000000..0977f8e --- /dev/null +++ b/lib/models/editor_tab_item.dart @@ -0,0 +1,59 @@ +import 'package:path/path.dart' as p; + +class EditorTabItem { + final String path; + String content; + String originalContent; + bool isModified; + bool isLoaded; + double verticalScrollOffset; + double horizontalScrollOffset; + bool hasExternalConflict; + bool isDeletedOnDisk; + + EditorTabItem({ + required this.path, + this.content = '', + this.originalContent = '', + this.isModified = false, + this.isLoaded = false, + this.verticalScrollOffset = 0.0, + this.horizontalScrollOffset = 0.0, + this.hasExternalConflict = false, + this.isDeletedOnDisk = false, + }); + + String get name => p.basename(path); + + /// 计算标签展示名称: + /// 当存在同名文件标签时显示相对项目路径,否则优先显示简短文件名 + String getDisplayName(List allTabs, String? rootPath) { + final hasDuplicateName = allTabs.where((tab) => tab.name == name).length > 1; + if (hasDuplicateName) { + if (rootPath != null && rootPath.isNotEmpty) { + try { + if (p.isWithin(rootPath, path)) { + final rel = p.relative(path, from: rootPath); + return rel; + } + } catch (_) {} + } + return path; + } + return name; + } + + /// 包含脏标记的前缀名称 + String getFormattedTitle(List allTabs, String? rootPath) { + final displayName = getDisplayName(allTabs, rootPath); + return isModified ? '* $displayName' : displayName; + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is EditorTabItem && runtimeType == other.runtimeType && path == other.path; + + @override + int get hashCode => path.hashCode; +} diff --git a/lib/models/editor_theme.dart b/lib/models/editor_theme.dart new file mode 100644 index 0000000..f82b91f --- /dev/null +++ b/lib/models/editor_theme.dart @@ -0,0 +1,177 @@ +import 'package:flutter/material.dart'; +import 'package:re_highlight/styles/atom-one-dark.dart'; +import 'package:re_highlight/styles/atom-one-light.dart'; +import 'package:re_highlight/styles/github-dark.dart'; +import 'package:re_highlight/styles/github.dart'; +import 'package:re_highlight/styles/monokai-sublime.dart'; +import 'package:re_highlight/styles/vs2015.dart'; + +/// 代码编辑器专用独立主题模型 +/// +/// 代码编辑器主题完全独立于 App 全局的 Light/Dark 主题, +/// 明确定义自身的所有背景色、前景色、高亮色、行号色与选区颜色。 +class EditorTheme { + /// 主题唯一标识 + final String id; + + /// 主题展示名称 + final String name; + + /// 是否为暗色系 + final bool isDark; + + /// 编辑区背景色 + final Color backgroundColor; + + /// 编辑区普通文本颜色(未被高亮命中的字符、普通变量名、标点等) + final Color textColor; + + /// 行号与折叠三角等指示器文字颜色 + final Color gutterTextColor; + + /// 当前光标所在行的行号高亮颜色 + final Color focusedGutterTextColor; + + /// 行号区背景色(若为 null 则与编辑区背景色一致) + final Color? gutterBackgroundColor; + + /// 光标颜色 + final Color cursorColor; + + /// 当前行背景高亮颜色 + final Color? cursorLineColor; + + /// 文本选区背景高亮颜色 + final Color selectionColor; + + /// 语法高亮映射表 (re_highlight 样式映射) + final Map highlightTheme; + + const EditorTheme({ + required this.id, + required this.name, + required this.isDark, + required this.backgroundColor, + required this.textColor, + required this.gutterTextColor, + required this.focusedGutterTextColor, + this.gutterBackgroundColor, + required this.cursorColor, + this.cursorLineColor, + required this.selectionColor, + required this.highlightTheme, + }); + + // ========================================== + // 内置预设主题 (Presets) + // ========================================== + + /// Atom One Dark (经典暗色,默认主题) + static const EditorTheme atomOneDark = EditorTheme( + id: 'atom-one-dark', + name: 'Atom One Dark', + isDark: true, + backgroundColor: Color(0xFF282C34), + textColor: Color(0xFFABB2BF), + gutterTextColor: Color(0xFF5C6370), + focusedGutterTextColor: Color(0xFFABB2BF), + cursorColor: Color(0xFF528BFF), + cursorLineColor: Color(0x1FFFFFFF), + selectionColor: Color(0x40528BFF), + highlightTheme: atomOneDarkTheme, + ); + + /// Atom One Light (经典明亮浅色) + static const EditorTheme atomOneLight = EditorTheme( + id: 'atom-one-light', + name: 'Atom One Light', + isDark: false, + backgroundColor: Color(0xFFFAFAFA), + textColor: Color(0xFF383A42), + gutterTextColor: Color(0xFFA0A1A7), + focusedGutterTextColor: Color(0xFF383A42), + cursorColor: Color(0xFF526FFF), + cursorLineColor: Color(0x0F000000), + selectionColor: Color(0x30526FFF), + highlightTheme: atomOneLightTheme, + ); + + /// GitHub Dark (GitHub 暗色) + static const EditorTheme githubDark = EditorTheme( + id: 'github-dark', + name: 'GitHub Dark', + isDark: true, + backgroundColor: Color(0xFF0D1117), + textColor: Color(0xFFC9D1D9), + gutterTextColor: Color(0xFF8B949E), + focusedGutterTextColor: Color(0xFFC9D1D9), + cursorColor: Color(0xFF58A6FF), + cursorLineColor: Color(0x16FFFFFF), + selectionColor: Color(0x3D58A6FF), + highlightTheme: githubDarkTheme, + ); + + /// GitHub Light (GitHub 浅色) + static const EditorTheme githubLight = EditorTheme( + id: 'github-light', + name: 'GitHub Light', + isDark: false, + backgroundColor: Color(0xFFFFFFFF), + textColor: Color(0xFF24292E), + gutterTextColor: Color(0xFF959DA5), + focusedGutterTextColor: Color(0xFF24292E), + cursorColor: Color(0xFF0366D6), + cursorLineColor: Color(0x0A000000), + selectionColor: Color(0x330366D6), + highlightTheme: githubTheme, + ); + + /// Monokai Sublime (高对比度深色) + static const EditorTheme monokaiSublime = EditorTheme( + id: 'monokai-sublime', + name: 'Monokai Sublime', + isDark: true, + backgroundColor: Color(0xFF23241F), + textColor: Color(0xFFF8F8F2), + gutterTextColor: Color(0xFF75715E), + focusedGutterTextColor: Color(0xFFF8F8F2), + cursorColor: Color(0xFFF8F8F0), + cursorLineColor: Color(0x1FFFFFFF), + selectionColor: Color(0x4049483E), + highlightTheme: monokaiSublimeTheme, + ); + + /// VS 2015 / Visual Studio Dark + static const EditorTheme vs2015 = EditorTheme( + id: 'vs2015', + name: 'Visual Studio Dark', + isDark: true, + backgroundColor: Color(0xFF1E1E1E), + textColor: Color(0xFFDCDCDC), + gutterTextColor: Color(0xFF858585), + focusedGutterTextColor: Color(0xFFDCDCDC), + cursorColor: Color(0xFFA6A6A6), + cursorLineColor: Color(0x15FFFFFF), + selectionColor: Color(0x40264F78), + highlightTheme: vs2015Theme, + ); + + /// 所有支持的预设主题列表 + static const List presets = [ + atomOneDark, + atomOneLight, + githubDark, + githubLight, + monokaiSublime, + vs2015, + ]; + + /// 根据 ID 查找主题,若不存在则回退至默认主题 + static EditorTheme fromId(String? id) { + if (id == null || id.isEmpty) return atomOneDark; + return presets.firstWhere( + (theme) => theme.id == id, + orElse: () => atomOneDark, + ); + } +} diff --git a/lib/models/file_directory_history.dart b/lib/models/file_directory_history.dart index a302f12..8466ac5 100644 --- a/lib/models/file_directory_history.dart +++ b/lib/models/file_directory_history.dart @@ -4,27 +4,42 @@ class FileDirectoryHistory { final String? rootPath; final String? lastOpenedFilePath; final List openDirectoryPaths; + final List openFilePaths; const FileDirectoryHistory({ required this.rootPath, required this.lastOpenedFilePath, this.openDirectoryPaths = const [], + this.openFilePaths = const [], }); Map toMap() => { 'rootPath': rootPath, 'lastOpenedFilePath': lastOpenedFilePath, 'openDirectoryPaths': openDirectoryPaths, + 'openFilePaths': openFilePaths, }; factory FileDirectoryHistory.fromMap(Map map) { + final rawOpenFilePaths = map['openFilePaths'] as List?; + final lastFile = map['lastOpenedFilePath'] as String?; + List openFiles; + if (rawOpenFilePaths != null) { + openFiles = rawOpenFilePaths.map((e) => e.toString()).toList(); + } else if (lastFile != null && lastFile.isNotEmpty) { + openFiles = [lastFile]; + } else { + openFiles = const []; + } + return FileDirectoryHistory( rootPath: map['rootPath'] as String?, - lastOpenedFilePath: map['lastOpenedFilePath'] as String?, + lastOpenedFilePath: lastFile, openDirectoryPaths: (map['openDirectoryPaths'] as List?) ?.map((e) => e.toString()) .toList() ?? const [], + openFilePaths: openFiles, ); } diff --git a/lib/providers/editor_provider.dart b/lib/providers/editor_provider.dart index 0be077c..9e0863d 100644 --- a/lib/providers/editor_provider.dart +++ b/lib/providers/editor_provider.dart @@ -1,265 +1,111 @@ +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/services/file_directory_history_service.dart'; -import 'package:code_editor/services/file_service.dart'; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/foundation.dart'; -import 'package:path/path.dart' as p; +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 { - FileDirectoryHistory _history = const FileDirectoryHistory( - rootPath: null, - lastOpenedFilePath: "未命名", - ); - List _items = []; - bool _isLoading = false; - FileItem? _cutItem; - FileItem? _copiedItem; + final SettingsProvider settingsProvider; + final ProjectProvider projectProvider; + final TabProvider tabProvider; - FileDirectoryHistory get history => _history; - String? get rootPath => _history.rootPath; - String? get currentFilePath => _history.lastOpenedFilePath; - List get openDirectoryPaths => _history.openDirectoryPaths; - List get items => _items; - bool get isLoading => _isLoading; - FileItem? get cutItem => _cutItem; - FileItem? get copiedItem => _copiedItem; - bool get canPaste => _cutItem != null || _copiedItem != null; - - bool isFileSelected(String path) { - if (currentFilePath == null) return false; - return currentFilePath == path || currentFilePath!.trim() == path.trim(); + 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); } - bool isItemCut(String path) { - if (_cutItem == null) return false; - return _cutItem!.path == path || _cutItem!.path.trim() == path.trim(); + @override + void dispose() { + settingsProvider.removeListener(notifyListeners); + projectProvider.removeListener(notifyListeners); + tabProvider.removeListener(notifyListeners); + super.dispose(); } Future init() async { - await _loadProjectFromHistory(); + await settingsProvider.init(); + await projectProvider.init(); + await tabProvider.init(); } - Future _loadProjectFromHistory() async { - _isLoading = true; - notifyListeners(); + // =================== 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; - try { - final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory(); - if (lastHistory == null) { - _isLoading = false; - notifyListeners(); - return; - } + 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); - final path = lastHistory.rootPath; - final cleanPath = (path != null && path.trim().isNotEmpty) ? p.normalize(path.trim()) : null; - final validOpenPaths = cleanPath == null - ? [] - : lastHistory.openDirectoryPaths - .map((e) => p.normalize(e.trim())) - .where((e) => e != cleanPath && p.isWithin(cleanPath, e)) - .toList(); + // =================== 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; - List items = cleanPath != null - ? await FileService.instance.buildTree( - cleanPath, - openDirectoryPaths: validOpenPaths, - ) - : []; + 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); - _items = items; - _history = FileDirectoryHistory( - rootPath: cleanPath, - lastOpenedFilePath: lastHistory.lastOpenedFilePath, - openDirectoryPaths: validOpenPaths, - ); - } catch (e) { - debugPrint('加载项目历史失败: $e'); - } finally { - _isLoading = false; - notifyListeners(); - } + @visibleForTesting + void setHistoryForTesting(FileDirectoryHistory history) { + // ignore: invalid_use_of_visible_for_testing_member + projectProvider.setHistoryForTesting(history); } - Future openDirectory() async { - try { - final String? selectedPath = await FilePicker.platform.getDirectoryPath(); - if (selectedPath == null || selectedPath.trim().isEmpty) { - return; - } + // =================== Tab Provider Getters & Methods =================== + List get openTabs => tabProvider.openTabs; + EditorTabItem? get activeTab => tabProvider.activeTab; + String? get currentFilePath => tabProvider.currentFilePath; + bool get isModified => tabProvider.isModified; - final cleanPath = p.normalize(selectedPath.trim()); - final currentRoot = _history.rootPath != null ? p.normalize(_history.rootPath!) : null; - final isSameRoot = currentRoot != null && cleanPath == currentRoot; + 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); - await FileDirectoryHistoryService.instance.recordHistory( - rootPath: cleanPath, - lastOpenedFilePath: isSameRoot ? _history.lastOpenedFilePath : null, - openDirectoryPaths: isSameRoot ? _history.openDirectoryPaths : const [], - ); - - _cutItem = null; - _copiedItem = null; - - await _loadProjectFromHistory(); - } catch (e) { - debugPrint('打开文件夹失败: $e'); - } - } - - Future switchProject(FileDirectoryHistory selectedHistory) async { - final selectedRoot = selectedHistory.rootPath; - if (selectedRoot == null || selectedRoot.trim().isEmpty) return; - - await FileDirectoryHistoryService.instance.recordHistory( - rootPath: selectedRoot, - lastOpenedFilePath: selectedHistory.lastOpenedFilePath, - openDirectoryPaths: selectedHistory.openDirectoryPaths, - ); - - _cutItem = null; - _copiedItem = null; - - await _loadProjectFromHistory(); - } - - Future selectFile(FileItem item) async { - if (item.isDirectory) return; - final cleanPath = _history.rootPath; - if (cleanPath != null) { - await FileDirectoryHistoryService.instance.recordHistory( - rootPath: cleanPath, - lastOpenedFilePath: item.path, - openDirectoryPaths: _history.openDirectoryPaths, - ); - _history = FileDirectoryHistory( - rootPath: cleanPath, - lastOpenedFilePath: item.path, - openDirectoryPaths: _history.openDirectoryPaths, - ); - notifyListeners(); - } - } - - Future toggleDirectory(FileItem item, bool expanded) async { - final cleanPath = _history.rootPath; - if (cleanPath == null) return; - - final updatedOpenPaths = List.from(_history.openDirectoryPaths); - if (expanded) { - if (!updatedOpenPaths.contains(item.path)) { - updatedOpenPaths.add(item.path); - } - if (item.children.isEmpty) { - final children = await FileService.instance.buildTree( - item.path, - depth: item.depth + 1, - openDirectoryPaths: updatedOpenPaths, - ); - item.children.clear(); - item.children.addAll(children); - } - } else { - updatedOpenPaths.remove(item.path); - } - - await FileDirectoryHistoryService.instance.recordHistory( - rootPath: cleanPath, - lastOpenedFilePath: _history.lastOpenedFilePath, - openDirectoryPaths: updatedOpenPaths, - ); - _history = FileDirectoryHistory( - rootPath: cleanPath, - lastOpenedFilePath: _history.lastOpenedFilePath, - openDirectoryPaths: updatedOpenPaths, - ); - notifyListeners(); - } - - Future refreshTree() async { - final currentRoot = _history.rootPath; - if (currentRoot == null || currentRoot.trim().isEmpty) return; - - try { - final items = await FileService.instance.buildTree( - currentRoot, - openDirectoryPaths: _history.openDirectoryPaths, - ); - - String? currentFile = _history.lastOpenedFilePath; - if (currentFile != null) { - final exists = await FileService.instance.entityExists(currentFile); - if (!exists) { - currentFile = null; - await FileDirectoryHistoryService.instance.recordHistory( - rootPath: currentRoot, - lastOpenedFilePath: null, - openDirectoryPaths: _history.openDirectoryPaths, - ); - } - } - - _items = items; - if (currentFile != _history.lastOpenedFilePath) { - _history = FileDirectoryHistory( - rootPath: currentRoot, - lastOpenedFilePath: currentFile, - openDirectoryPaths: _history.openDirectoryPaths, - ); - } - notifyListeners(); - } catch (e) { - debugPrint('刷新目录树失败: $e'); - } - } - - void cut(FileItem item) { - _cutItem = item; - _copiedItem = null; - notifyListeners(); - } - - void copy(FileItem item) { - _copiedItem = item; - _cutItem = null; - notifyListeners(); - } - - Future paste(FileItem targetDir) async { - if (!targetDir.isDirectory) return; - - if (_cutItem != null) { - final source = _cutItem!; - await FileService.instance.moveEntity(source.path, targetDir.path); - _cutItem = null; - await refreshTree(); - } else if (_copiedItem != null) { - final source = _copiedItem!; - await FileService.instance.copyEntity(source.path, targetDir.path); - await refreshTree(); - } - } - - Future createFile(String parentDir, String name) async { - final targetPath = p.join(parentDir, name.trim()); - await FileService.instance.createFile(targetPath); - await refreshTree(); - } - - Future createDirectory(String parentDir, String name) async { - final targetPath = p.join(parentDir, name.trim()); - await FileService.instance.createDirectory(targetPath); - await refreshTree(); - } - - Future rename(FileItem item, String newName) async { - await FileService.instance.renameEntity(item.path, newName.trim()); - await refreshTree(); - } - - Future delete(FileItem item) async { - await FileService.instance.deleteEntity(item.path); - await refreshTree(); + @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 new file mode 100644 index 0000000..76c2e96 --- /dev/null +++ b/lib/providers/project_provider.dart @@ -0,0 +1,334 @@ +import 'dart:io'; +import 'package:code_editor/models/file_directory_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/file_service.dart'; +import 'package:code_editor/services/file_watcher_service.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +class ProjectProvider extends ChangeNotifier { + FileDirectoryHistory _history = const FileDirectoryHistory( + rootPath: null, + lastOpenedFilePath: null, + ); + List _items = []; + bool _isLoading = false; + FileItem? _cutItem; + FileItem? _copiedItem; + + // 跨 Provider 协同回调 + void Function(String oldPath, String newPath)? onEntityRenamed; + void Function(String deletedPath)? onEntityDeleted; + void Function(String? rootPath, List openFilePaths, String? lastOpenedFilePath)? onProjectChanged; + void Function(String modifiedPath)? onExternalFileModified; + void Function(String deletedPath)? onExternalFileDeleted; + + FileDirectoryHistory get history => _history; + String? get rootPath => _history.rootPath; + List get openDirectoryPaths => _history.openDirectoryPaths; + List get items => _items; + bool get isLoading => _isLoading; + FileItem? get cutItem => _cutItem; + FileItem? get copiedItem => _copiedItem; + bool get canPaste => _cutItem != null || _copiedItem != null; + + bool isItemCut(String path) { + if (_cutItem == null) return false; + return _cutItem!.path == path || _cutItem!.path.trim() == path.trim(); + } + + Future init() async { + await _loadProjectFromHistory(); + } + + @visibleForTesting + void setHistoryForTesting(FileDirectoryHistory history) { + _history = history; + notifyListeners(); + } + + @visibleForTesting + void setItemsForTesting(List items) { + _items = items; + notifyListeners(); + } + + Future _loadProjectFromHistory() async { + _isLoading = true; + notifyListeners(); + + try { + final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory(); + if (lastHistory == null) { + _isLoading = false; + notifyListeners(); + return; + } + + final path = lastHistory.rootPath; + final cleanPath = (path != null && path.trim().isNotEmpty) ? p.normalize(path.trim()) : null; + final validOpenPaths = cleanPath == null + ? [] + : lastHistory.openDirectoryPaths + .map((e) => p.normalize(e.trim())) + .where((e) => e != cleanPath && p.isWithin(cleanPath, e)) + .toList(); + + List items = cleanPath != null + ? await FileService.instance.buildTree( + cleanPath, + openDirectoryPaths: validOpenPaths, + ) + : []; + + _items = items; + _history = FileDirectoryHistory( + rootPath: cleanPath, + lastOpenedFilePath: lastHistory.lastOpenedFilePath, + openDirectoryPaths: validOpenPaths, + openFilePaths: lastHistory.openFilePaths, + ); + + // 启动外部文件变动监听服务 + _startWatcher(cleanPath); + + // 通知外部(例如 TabProvider)同步标签页历史 + onProjectChanged?.call(cleanPath, lastHistory.openFilePaths, lastHistory.lastOpenedFilePath); + } catch (e) { + debugPrint('加载项目历史失败: $e'); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + Future openDirectory() async { + try { + final String? selectedPath = await FilePicker.platform.getDirectoryPath(); + if (selectedPath == null || selectedPath.trim().isEmpty) { + return; + } + + final cleanPath = p.normalize(selectedPath.trim()); + final currentRoot = _history.rootPath != null ? p.normalize(_history.rootPath!) : null; + final isSameRoot = currentRoot != null && cleanPath == currentRoot; + + await FileDirectoryHistoryService.instance.recordHistory( + rootPath: cleanPath, + lastOpenedFilePath: isSameRoot ? _history.lastOpenedFilePath : null, + openDirectoryPaths: isSameRoot ? _history.openDirectoryPaths : const [], + openFilePaths: isSameRoot ? _history.openFilePaths : const [], + ); + + _cutItem = null; + _copiedItem = null; + + await _loadProjectFromHistory(); + } catch (e) { + debugPrint('打开文件夹失败: $e'); + } + } + + Future switchProject(FileDirectoryHistory selectedHistory) async { + final selectedRoot = selectedHistory.rootPath; + if (selectedRoot == null || selectedRoot.trim().isEmpty) return; + + await FileDirectoryHistoryService.instance.recordHistory( + rootPath: selectedRoot, + lastOpenedFilePath: selectedHistory.lastOpenedFilePath, + openDirectoryPaths: selectedHistory.openDirectoryPaths, + openFilePaths: selectedHistory.openFilePaths, + ); + + _cutItem = null; + _copiedItem = null; + + await _loadProjectFromHistory(); + } + + Future toggleDirectory(FileItem item, bool expanded) async { + final cleanPath = _history.rootPath; + if (cleanPath == null) return; + + final updatedOpenPaths = List.from(_history.openDirectoryPaths); + if (expanded) { + if (!updatedOpenPaths.contains(item.path)) { + updatedOpenPaths.add(item.path); + } + if (item.children.isEmpty) { + final children = await FileService.instance.buildTree( + item.path, + depth: item.depth + 1, + openDirectoryPaths: updatedOpenPaths, + ); + item.children.clear(); + item.children.addAll(children); + } + } else { + updatedOpenPaths.remove(item.path); + } + + await FileDirectoryHistoryService.instance.recordHistory( + rootPath: cleanPath, + lastOpenedFilePath: _history.lastOpenedFilePath, + openDirectoryPaths: updatedOpenPaths, + openFilePaths: _history.openFilePaths, + ); + _history = FileDirectoryHistory( + rootPath: cleanPath, + lastOpenedFilePath: _history.lastOpenedFilePath, + openDirectoryPaths: updatedOpenPaths, + openFilePaths: _history.openFilePaths, + ); + notifyListeners(); + } + + Future refreshTree() async { + final currentRoot = _history.rootPath; + if (currentRoot == null || currentRoot.trim().isEmpty) return; + + try { + final items = await FileService.instance.buildTree( + currentRoot, + openDirectoryPaths: _history.openDirectoryPaths, + ); + + String? currentFile = _history.lastOpenedFilePath; + if (currentFile != null) { + final exists = await FileService.instance.entityExists(currentFile); + if (!exists) { + currentFile = null; + await FileDirectoryHistoryService.instance.recordHistory( + rootPath: currentRoot, + lastOpenedFilePath: null, + openDirectoryPaths: _history.openDirectoryPaths, + openFilePaths: _history.openFilePaths, + ); + } + } + + _items = items; + if (currentFile != _history.lastOpenedFilePath) { + _history = FileDirectoryHistory( + rootPath: currentRoot, + lastOpenedFilePath: currentFile, + openDirectoryPaths: _history.openDirectoryPaths, + openFilePaths: _history.openFilePaths, + ); + } + notifyListeners(); + } catch (e) { + debugPrint('刷新目录树失败: $e'); + } + } + + void cut(FileItem item) { + _cutItem = item; + _copiedItem = null; + notifyListeners(); + } + + void copy(FileItem item) { + _copiedItem = item; + _cutItem = null; + notifyListeners(); + } + + Future paste(FileItem targetDir) async { + if (!targetDir.isDirectory) return; + + if (_cutItem != null) { + final source = _cutItem!; + await FileService.instance.moveEntity(source.path, targetDir.path); + _cutItem = null; + await refreshTree(); + } else if (_copiedItem != null) { + final source = _copiedItem!; + await FileService.instance.copyEntity(source.path, targetDir.path); + await refreshTree(); + } + } + + Future createFile(String parentDir, String name) async { + final targetPath = p.join(parentDir, name.trim()); + await FileService.instance.createFile(targetPath); + await refreshTree(); + } + + Future createDirectory(String parentDir, String name) async { + final targetPath = p.join(parentDir, name.trim()); + await FileService.instance.createDirectory(targetPath); + await refreshTree(); + } + + Future rename(FileItem item, String newName) async { + final targetPath = p.normalize(p.join(p.dirname(item.path), newName.trim())); + await FileService.instance.renameEntity(item.path, newName.trim()); + final oldNormalized = p.normalize(item.path); + + onEntityRenamed?.call(oldNormalized, targetPath); + + await refreshTree(); + } + + Future delete(FileItem item) async { + await FileService.instance.deleteEntity(item.path); + final oldNormalized = p.normalize(item.path); + + onEntityDeleted?.call(oldNormalized); + + await refreshTree(); + } + + void _startWatcher(String? rootPath) { + if (rootPath == null || rootPath.isEmpty) { + FileWatcherService.instance.stopWatching(); + return; + } + FileWatcherService.instance.startWatching( + rootPath, + onEvents: _onFileSystemEvents, + ); + } + + void _onFileSystemEvents(List events) { + bool needRefreshTree = false; + + for (final event in events) { + final normalizedPath = p.normalize(event.path); + + if (event is FileSystemCreateEvent) { + needRefreshTree = true; + } else if (event is FileSystemDeleteEvent) { + needRefreshTree = true; + onExternalFileDeleted?.call(normalizedPath); + } else if (event is FileSystemMoveEvent) { + needRefreshTree = true; + final dest = event.destination; + if (dest != null) { + onEntityRenamed?.call(normalizedPath, p.normalize(dest)); + } else { + onExternalFileDeleted?.call(normalizedPath); + } + } else if (event is FileSystemModifyEvent) { + if (event.isDirectory) { + needRefreshTree = true; + } else { + onExternalFileModified?.call(normalizedPath); + } + } + } + + if (needRefreshTree) { + refreshTree(); + } + } + + @override + void dispose() { + FileWatcherService.instance.stopWatching(); + super.dispose(); + } +} diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart new file mode 100644 index 0000000..5327953 --- /dev/null +++ b/lib/providers/settings_provider.dart @@ -0,0 +1,117 @@ +import 'package:code_editor/models/editor_theme.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 _keyAppLocale = 'app_locale'; + + EditorTheme _editorTheme = EditorTheme.atomOneDark; + ThemeMode _appThemeMode = ThemeMode.system; + double _fontSize = 14.0; + bool _wordWrap = true; + Locale? _locale; + + EditorTheme get editorTheme => _editorTheme; + ThemeMode get appThemeMode => _appThemeMode; + double get fontSize => _fontSize; + bool get wordWrap => _wordWrap; + Locale? get locale => _locale; + + Future init() async { + await _loadSettings(); + } + + 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) { + _appThemeMode = ThemeMode.values.firstWhere( + (e) => e.name == themeModeName, + orElse: () => ThemeMode.system, + ); + } + + final savedFontSize = prefs.getDouble(_keyEditorFontSize); + if (savedFontSize != null && savedFontSize >= 10 && savedFontSize <= 32) { + _fontSize = savedFontSize; + } + + final savedWordWrap = prefs.getBool(_keyWordWrap); + if (savedWordWrap != null) { + _wordWrap = savedWordWrap; + } + + final savedLocale = prefs.getString(_keyAppLocale); + if (savedLocale != null && savedLocale.isNotEmpty) { + _locale = Locale(savedLocale); + } else { + _locale = null; // 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 (_) {} + } + + Future setAppThemeMode(ThemeMode mode) async { + if (_appThemeMode == mode) return; + _appThemeMode = mode; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyAppThemeMode, mode.name); + } catch (_) {} + } + + Future setFontSize(double size) async { + final clamped = size.clamp(10.0, 30.0); + if (_fontSize == clamped) return; + _fontSize = clamped; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setDouble(_keyEditorFontSize, clamped); + } catch (_) {} + } + + Future setWordWrap(bool wrap) async { + if (_wordWrap == wrap) return; + _wordWrap = wrap; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyWordWrap, wrap); + } catch (_) {} + } + + Future setLocale(Locale? newLocale) async { + if (_locale == newLocale) return; + _locale = newLocale; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + if (newLocale == null) { + await prefs.remove(_keyAppLocale); + } else { + await prefs.setString(_keyAppLocale, newLocale.languageCode); + } + } catch (_) {} + } +} diff --git a/lib/providers/tab_provider.dart b/lib/providers/tab_provider.dart new file mode 100644 index 0000000..0780122 --- /dev/null +++ b/lib/providers/tab_provider.dart @@ -0,0 +1,470 @@ +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/file_service.dart'; +import 'package:code_editor/services/file_watcher_service.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +class TabProvider extends ChangeNotifier { + List _openTabs = []; + String? _activeFilePath; + bool _isModified = false; + Future Function()? _saveHandler; + + ProjectProvider? _projectProvider; + + List get openTabs => _openTabs; + EditorTabItem? get activeTab { + if (_activeFilePath == null) return null; + final index = _openTabs.indexWhere((tab) => p.equals(tab.path, _activeFilePath!)); + return index != -1 ? _openTabs[index] : null; + } + + String? get currentFilePath => _activeFilePath; + bool get isModified => activeTab?.isModified ?? _isModified; + + void bindProjectProvider(ProjectProvider projectProvider) { + if (_projectProvider == projectProvider) return; + _projectProvider = projectProvider; + projectProvider.onEntityRenamed = handleEntityRenamed; + projectProvider.onEntityDeleted = handleEntityDeleted; + projectProvider.onProjectChanged = handleProjectChanged; + projectProvider.onExternalFileModified = handleExternalFileModified; + projectProvider.onExternalFileDeleted = handleExternalFileDeleted; + } + + bool isFileSelected(String path) { + if (_activeFilePath == null) return false; + return p.equals(_activeFilePath!, path); + } + + Future init() async { + await _loadTabsFromHistory(); + } + + Future _loadTabsFromHistory() async { + try { + final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory(); + if (lastHistory == null) return; + await handleProjectChanged( + lastHistory.rootPath, + lastHistory.openFilePaths, + lastHistory.lastOpenedFilePath, + ); + } catch (e) { + debugPrint('加载标签页历史失败: $e'); + } + } + + Future handleProjectChanged( + String? rootPath, + List openFilePaths, + String? lastOpenedFilePath, + ) async { + final List loadedTabs = []; + + for (final filePath in openFilePaths) { + final cleanFilePath = p.normalize(filePath.trim()); + if (await FileService.instance.entityExists(cleanFilePath)) { + loadedTabs.add(EditorTabItem( + path: cleanFilePath, + isModified: false, + )); + } + } + + if (loadedTabs.isEmpty && lastOpenedFilePath != null && lastOpenedFilePath.trim().isNotEmpty) { + final cleanLast = p.normalize(lastOpenedFilePath.trim()); + if (await FileService.instance.entityExists(cleanLast)) { + loadedTabs.add(EditorTabItem( + path: cleanLast, + isModified: false, + )); + } + } + + _openTabs = loadedTabs; + + if (lastOpenedFilePath != null && _openTabs.any((t) => p.equals(t.path, lastOpenedFilePath.trim()))) { + _activeFilePath = _openTabs.firstWhere((t) => p.equals(t.path, lastOpenedFilePath.trim())).path; + } else if (_openTabs.isNotEmpty) { + _activeFilePath = _openTabs.first.path; + } else { + _activeFilePath = null; + } + + _isModified = false; + notifyListeners(); + } + + void handleEntityRenamed(String oldNormalized, String targetPath) { + for (int i = 0; i < _openTabs.length; i++) { + final tabPath = _openTabs[i].path; + if (p.equals(tabPath, oldNormalized)) { + _openTabs[i] = EditorTabItem( + path: targetPath, + content: _openTabs[i].content, + originalContent: _openTabs[i].originalContent, + isModified: _openTabs[i].isModified, + isLoaded: _openTabs[i].isLoaded, + verticalScrollOffset: _openTabs[i].verticalScrollOffset, + horizontalScrollOffset: _openTabs[i].horizontalScrollOffset, + ); + } else if (p.isWithin(oldNormalized, tabPath)) { + final rel = p.relative(tabPath, from: oldNormalized); + final newChildPath = p.normalize(p.join(targetPath, rel)); + _openTabs[i] = EditorTabItem( + path: newChildPath, + content: _openTabs[i].content, + originalContent: _openTabs[i].originalContent, + isModified: _openTabs[i].isModified, + isLoaded: _openTabs[i].isLoaded, + verticalScrollOffset: _openTabs[i].verticalScrollOffset, + horizontalScrollOffset: _openTabs[i].horizontalScrollOffset, + ); + } + } + + if (_activeFilePath != null) { + if (p.equals(_activeFilePath!, oldNormalized)) { + _activeFilePath = targetPath; + } else if (p.isWithin(oldNormalized, _activeFilePath!)) { + final rel = p.relative(_activeFilePath!, from: oldNormalized); + _activeFilePath = p.normalize(p.join(targetPath, rel)); + } + } + + _persistTabsHistory(); + notifyListeners(); + } + + void handleEntityDeleted(String oldNormalized) { + _openTabs.removeWhere((tab) => p.equals(tab.path, oldNormalized) || p.isWithin(oldNormalized, tab.path)); + if (_activeFilePath != null && (p.equals(_activeFilePath!, oldNormalized) || p.isWithin(oldNormalized, _activeFilePath!))) { + _activeFilePath = _openTabs.isNotEmpty ? _openTabs.first.path : null; + _isModified = activeTab?.isModified ?? false; + } + _persistTabsHistory(); + notifyListeners(); + } + + /// 处理外部文件内容被修改事件 + Future handleExternalFileModified(String modifiedPath) async { + final cleanPath = p.normalize(modifiedPath); + final tabIndex = _openTabs.indexWhere((t) => p.equals(t.path, cleanPath)); + if (tabIndex == -1) return; + final tab = _openTabs[tabIndex]; + + try { + if (!await FileService.instance.entityExists(cleanPath)) return; + final raw = await FileService.instance.readFileContent(cleanPath); + final diskContent = raw.replaceAll('\r\n', '\n'); + + // 内容无实质改变则跳过 + if (tab.content == diskContent) { + return; + } + + if (!tab.isModified) { + // 未修改文件:静默无感热重载 + tab.content = diskContent; + tab.originalContent = diskContent; + tab.isLoaded = true; + tab.hasExternalConflict = false; + notifyListeners(); + } else { + // 已修改文件:发生外部冲突,标记冲突以通知 UI 弹出提示,严禁直接覆盖 + tab.hasExternalConflict = true; + notifyListeners(); + } + } catch (e) { + debugPrint('处理外部文件变动失败: $e'); + } + } + + /// 解决外部文件冲突 + Future resolveConflict(EditorTabItem tab, {required bool reloadFromDisk}) async { + tab.hasExternalConflict = false; + if (reloadFromDisk) { + try { + final raw = await FileService.instance.readFileContent(tab.path); + final diskContent = raw.replaceAll('\r\n', '\n'); + tab.content = diskContent; + tab.originalContent = diskContent; + tab.isModified = false; + if (_activeFilePath == tab.path) { + _isModified = false; + } + } catch (e) { + debugPrint('重载外部文件失败: $e'); + } + } + notifyListeners(); + } + + /// 处理外部文件被删除事件 + void handleExternalFileDeleted(String deletedPath) { + final cleanPath = p.normalize(deletedPath); + final affectedTabs = _openTabs + .where((t) { + final tClean = p.normalize(t.path); + return tClean == cleanPath || p.isWithin(cleanPath, tClean); + }) + .toList(); + + for (final tab in affectedTabs) { + if (!tab.isModified) { + // 未修改的文件安全自动关闭 + _openTabs.remove(tab); + if (_activeFilePath == tab.path) { + _activeFilePath = _openTabs.isNotEmpty ? _openTabs.first.path : null; + _isModified = activeTab?.isModified ?? false; + } + } else { + // 已修改的文件保留在标签栏防止丢代码,仅标记磁盘已被删除 + tab.isDeletedOnDisk = true; + } + } + _persistTabsHistory(); + notifyListeners(); + } + + Future _persistTabsHistory() async { + final root = _projectProvider?.rootPath; + if (root != null) { + final openPaths = _openTabs.map((t) => t.path).toList(); + await FileDirectoryHistoryService.instance.recordHistory( + rootPath: root, + lastOpenedFilePath: _activeFilePath, + openDirectoryPaths: _projectProvider?.openDirectoryPaths ?? const [], + openFilePaths: openPaths, + ); + } + } + + @visibleForTesting + void setOpenTabsForTesting(List tabs, {String? activePath}) { + _openTabs = List.from(tabs); + _activeFilePath = activePath ?? (_openTabs.isNotEmpty ? _openTabs.first.path : null); + _isModified = activeTab?.isModified ?? false; + notifyListeners(); + } + + @visibleForTesting + void setModifiedForTesting(bool modified) { + _isModified = modified; + if (activeTab != null) { + activeTab!.isModified = modified; + } + notifyListeners(); + } + + void setModified(bool modified) { + if (isModified == modified) return; + if (activeTab != null) { + activeTab!.isModified = modified; + } + _isModified = modified; + notifyListeners(); + } + + void updateActiveTabContent(String content, {bool? isModified}) { + final tab = activeTab; + if (tab != null) { + final normalized = content.replaceAll('\r\n', '\n'); + tab.content = normalized; + if (isModified != null) { + tab.isModified = isModified; + } else { + tab.isModified = normalized != tab.originalContent.replaceAll('\r\n', '\n'); + } + _isModified = tab.isModified; + notifyListeners(); + } + } + + void registerSaveHandler(Future Function()? handler) { + _saveHandler = handler; + } + + Future selectFile(FileItem item) async { + if (item.isDirectory) return; + await openFile(item.path); + } + + Future openFile(String path, {String? content}) async { + final cleanPath = p.normalize(path.trim()); + final existingIndex = _openTabs.indexWhere((tab) => p.equals(tab.path, cleanPath)); + if (existingIndex != -1) { + _activeFilePath = _openTabs[existingIndex].path; + _isModified = _openTabs[existingIndex].isModified; + } else { + String initialContent = content ?? ''; + bool loaded = false; + if (content != null) { + initialContent = initialContent.replaceAll('\r\n', '\n'); + loaded = true; + } else { + try { + if (await FileService.instance.entityExists(cleanPath)) { + final raw = await FileService.instance.readFileContent(cleanPath); + initialContent = raw.replaceAll('\r\n', '\n'); + loaded = true; + } + } catch (_) {} + } + final tab = EditorTabItem( + path: cleanPath, + content: initialContent, + originalContent: initialContent, + isModified: false, + isLoaded: loaded, + ); + _openTabs.add(tab); + _activeFilePath = cleanPath; + _isModified = false; + } + + await _persistTabsHistory(); + notifyListeners(); + } + + Future closeTab(BuildContext context, int index) async { + if (index < 0 || index >= _openTabs.length) return false; + final tab = _openTabs[index]; + + if (tab.isModified) { + final result = await DialogUtils.showSavePromptDialog( + context, + fileName: tab.name, + ); + switch (result) { + case SavePromptResult.save: + final saved = await saveTab(tab); + if (!saved) return false; + break; + case SavePromptResult.discard: + tab.isModified = false; + break; + case SavePromptResult.cancel: + return false; + } + } + + final wasActive = _activeFilePath != null && p.equals(tab.path, _activeFilePath!); + _openTabs.removeAt(index); + + if (wasActive) { + if (_openTabs.isEmpty) { + _activeFilePath = null; + _isModified = false; + } else { + final newIndex = index.clamp(0, _openTabs.length - 1); + _activeFilePath = _openTabs[newIndex].path; + _isModified = _openTabs[newIndex].isModified; + } + } + + 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; + final item = _openTabs.removeAt(oldIndex); + _openTabs.insert(newIndex, item); + await _persistTabsHistory(); + notifyListeners(); + } + + Future saveTab(EditorTabItem tab) async { + try { + FileWatcherService.instance.markRecentlySaved(tab.path); + if (_activeFilePath != null && p.equals(tab.path, _activeFilePath!) && _saveHandler != null) { + final ok = await _saveHandler!(); + if (ok) { + tab.originalContent = tab.content; + tab.isModified = false; + _isModified = false; + notifyListeners(); + } + return ok; + } + + await FileService.instance.saveFile(tab.path, tab.content); + tab.originalContent = tab.content; + tab.isModified = false; + if (_activeFilePath != null && p.equals(tab.path, _activeFilePath!)) { + _isModified = false; + } + notifyListeners(); + return true; + } catch (e) { + debugPrint('保存文件失败: $e'); + return false; + } + } + + Future saveCurrentFile() async { + final tab = activeTab; + if (tab != null) { + return await saveTab(tab); + } + if (_saveHandler != null) { + return await _saveHandler!(); + } + return false; + } + + Future saveAllFiles() async { + if (_openTabs.isEmpty) { + return await saveCurrentFile(); + } + bool allSuccess = true; + for (final tab in _openTabs) { + if (tab.isModified) { + FileWatcherService.instance.markRecentlySaved(tab.path); + final ok = await saveTab(tab); + if (!ok) allSuccess = false; + } + } + notifyListeners(); + return allSuccess; + } + + /// 检查是否有未保存的更改;若有脏文件则弹出确认弹窗 + Future checkUnsavedChanges(BuildContext context) async { + final dirtyTabs = _openTabs.where((t) => t.isModified).toList(); + if (dirtyTabs.isEmpty && !_isModified) { + return true; + } + + final result = await DialogUtils.showSaveAllPromptDialog(context); + switch (result) { + case SavePromptResult.save: + final saved = await saveAllFiles(); + if (saved && context.mounted) { + final l10n = AppLocalizations.of(context); + DialogUtils.showSuccessToast(context, l10n?.saveAllSuccess ?? '所有文件已保存'); + } + return saved; + + case SavePromptResult.discard: + for (final tab in _openTabs) { + tab.isModified = false; + } + _isModified = false; + notifyListeners(); + return true; + + case SavePromptResult.cancel: + return false; + } + } +} diff --git a/lib/services/file_directory_history_service.dart b/lib/services/file_directory_history_service.dart index 4079443..e1a1b4d 100644 --- a/lib/services/file_directory_history_service.dart +++ b/lib/services/file_directory_history_service.dart @@ -13,6 +13,7 @@ class FileDirectoryHistoryService { required String rootPath, String? lastOpenedFilePath, List? openDirectoryPaths, + List? openFilePaths, }) async { final cleanPath = rootPath.trim(); if(cleanPath.isEmpty) return; @@ -22,10 +23,12 @@ class FileDirectoryHistoryService { final existingIndex = history.indexWhere((item) => item.rootPath == cleanPath); String? resolvedFile = lastOpenedFilePath; List? resolvedOpenDirs = openDirectoryPaths; + List? resolvedOpenFiles = openFilePaths; if(existingIndex != -1) { resolvedFile ??= history[existingIndex].lastOpenedFilePath; resolvedOpenDirs ??= history[existingIndex].openDirectoryPaths; + resolvedOpenFiles ??= history[existingIndex].openFilePaths; history.removeAt(existingIndex); } @@ -35,6 +38,7 @@ class FileDirectoryHistoryService { rootPath: cleanPath, lastOpenedFilePath: resolvedFile, openDirectoryPaths: resolvedOpenDirs ?? const [], + openFilePaths: resolvedOpenFiles ?? const [], ), ); diff --git a/lib/services/file_watcher_service.dart b/lib/services/file_watcher_service.dart new file mode 100644 index 0000000..6590e22 --- /dev/null +++ b/lib/services/file_watcher_service.dart @@ -0,0 +1,122 @@ +import 'dart:async'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; + +/// 外部文件系统变动监听服务: +/// 1. 递归监听项目根目录下的文件与目录变动 +/// 2. 300ms 防抖机制合并高频写入与构建事件 +/// 3. 自身写盘保护(Self-Trigger Filter),避免自身保存陷入死循环 +/// 4. 自动过滤 .git、.dart_tool、build 等高频临时目录 +class FileWatcherService { + static final FileWatcherService instance = FileWatcherService._(); + FileWatcherService._(); + + StreamSubscription? _subscription; + Timer? _debounceTimer; + final List _pendingEvents = []; + final Map _recentlySavedFiles = {}; + + String? _watchedRootPath; + + /// 当前是否正在监听 + bool get isWatching => _subscription != null; + + /// 当前监听的根路径 + String? get watchedRootPath => _watchedRootPath; + + /// 登记应用自身刚才写盘保存的文件,在 600ms 内忽略该文件抛出的外部修改事件 + void markRecentlySaved(String filePath) { + final clean = p.normalize(filePath); + _recentlySavedFiles[clean] = DateTime.now(); + } + + /// 检查是否为应用自身刚刚保存的文件 + bool isRecentlySaved(String filePath) { + final clean = p.normalize(filePath); + final savedTime = _recentlySavedFiles[clean]; + if (savedTime == null) return false; + final elapsed = DateTime.now().difference(savedTime); + if (elapsed.inMilliseconds < 600) { + return true; + } + _recentlySavedFiles.remove(clean); + return false; + } + + /// 判断路径是否属于应该忽略的隐藏或构建目录 + static bool shouldIgnore(String path) { + final segments = p.split(path); + for (final seg in segments) { + if (seg == '.git' || + seg == '.dart_tool' || + seg == '.idea' || + seg == '.vscode' || + seg == 'build' || + seg == '.gradle') { + return true; + } + } + return false; + } + + /// 开始监听指定项目根目录 + void startWatching( + String rootPath, { + required void Function(List events) onEvents, + Duration debounceDuration = const Duration(milliseconds: 300), + }) { + stopWatching(); + + final cleanRoot = p.normalize(rootPath); + final dir = Directory(cleanRoot); + if (!dir.existsSync()) return; + + _watchedRootPath = cleanRoot; + + try { + _subscription = dir.watch(recursive: true).listen( + (event) { + if (shouldIgnore(event.path)) { + return; + } + + // 自身保存的文件在保护窗口内忽略内容修改事件 + if (event is FileSystemModifyEvent && isRecentlySaved(event.path)) { + return; + } + + _pendingEvents.add(event); + + _debounceTimer?.cancel(); + _debounceTimer = Timer(debounceDuration, () { + if (_pendingEvents.isEmpty) return; + final batch = List.from(_pendingEvents); + _pendingEvents.clear(); + onEvents(batch); + }); + }, + onError: (e) { + debugPrint('FileWatcherService 监听异常: $e'); + }, + ); + } catch (e) { + debugPrint('FileWatcherService 启动监听失败: $e'); + } + } + + /// 停止并释放监听 + void stopWatching() { + _debounceTimer?.cancel(); + _debounceTimer = null; + _pendingEvents.clear(); + _subscription?.cancel(); + _subscription = null; + _watchedRootPath = null; + } + + @visibleForTesting + void clearRecentlySavedForTesting() { + _recentlySavedFiles.clear(); + } +} diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart new file mode 100644 index 0000000..2f38ced --- /dev/null +++ b/lib/utils/dialog_utils.dart @@ -0,0 +1,568 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:flutter/material.dart'; + +/// Toast 类型 +enum ToastType { + info, + success, + warning, + error, +} + +/// 保存未保存更改提示结果 +enum SavePromptResult { + save, + discard, + cancel, +} + +/// 外部文件冲突提示结果 +enum FileConflictResult { + reloadFromDisk, + keepLocal, +} + +/// 集中封装 Dialog 与 Toast 的工具类 +class DialogUtils { + DialogUtils._(); + + // ========================================== + // 1. Toast 轻提示 + // ========================================== + + /// 显示浮动 Toast + static void showToast( + BuildContext context, + String message, { + ToastType type = ToastType.info, + Duration duration = const Duration(seconds: 2), + }) { + final overlay = Overlay.maybeOf(context, rootOverlay: true); + if (overlay == null) return; + + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + // 根据类型配置图标与色彩 + final (iconData, bgColor, textColor, borderColor) = switch (type) { + ToastType.success => ( + Icons.check_circle_outline, + Colors.green.shade800, + Colors.white, + Colors.green.shade600, + ), + ToastType.error => ( + Icons.error_outline, + colorScheme.errorContainer, + colorScheme.onErrorContainer, + colorScheme.error, + ), + ToastType.warning => ( + Icons.warning_amber_rounded, + Colors.amber.shade900, + Colors.white, + Colors.amber.shade700, + ), + ToastType.info => ( + Icons.info_outline, + colorScheme.inverseSurface, + colorScheme.onInverseSurface, + colorScheme.outlineVariant, + ), + }; + + late OverlayEntry entry; + entry = OverlayEntry( + builder: (ctx) => Positioned( + bottom: 48, + left: 0, + right: 0, + child: Center( + child: Material( + color: Colors.transparent, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 24), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: borderColor, width: 1), + boxShadow: const [ + BoxShadow( + color: Colors.black26, + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(iconData, size: 18, color: textColor), + const SizedBox(width: 8), + Flexible( + child: Text( + message, + style: theme.textTheme.bodyMedium?.copyWith( + color: textColor, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + + overlay.insert(entry); + Future.delayed(duration, () { + if (entry.mounted) { + entry.remove(); + } + }); + } + + static void showSuccessToast(BuildContext context, String message) { + showToast(context, message, type: ToastType.success); + } + + static void showErrorToast(BuildContext context, String message) { + showToast(context, message, type: ToastType.error); + } + + static void showWarningToast(BuildContext context, String message) { + showToast(context, message, type: ToastType.warning); + } + + static void showInfoToast(BuildContext context, String message) { + showToast(context, message, type: ToastType.info); + } + + // ========================================== + // 2. 消息提示 Dialog (Info, Warning, Error) + // ========================================== + + /// 信息提示弹窗 (Info) + static Future showInfoDialog( + BuildContext context, { + required String title, + required String message, + String? confirmText, + }) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + return _showMessageDialog( + context, + title: title, + message: message, + confirmText: confirmText ?? l10n?.confirm ?? '确定', + icon: Icon(Icons.info_outline, color: theme.colorScheme.primary, size: 28), + ); + } + + /// 警告提示弹窗 (Warning) + static Future showWarningDialog( + BuildContext context, { + required String title, + required String message, + String? confirmText, + }) { + final l10n = AppLocalizations.of(context); + return _showMessageDialog( + context, + title: title, + message: message, + confirmText: confirmText ?? l10n?.gotIt ?? '知道了', + icon: const Icon(Icons.warning_amber_rounded, color: Colors.amber, size: 28), + ); + } + + /// 错误提示弹窗 (Error) + static Future showErrorDialog( + BuildContext context, { + required String title, + required String message, + String? confirmText, + }) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + return _showMessageDialog( + context, + title: title, + message: message, + confirmText: confirmText ?? l10n?.close ?? '关闭', + icon: Icon(Icons.error_outline, color: theme.colorScheme.error, size: 28), + ); + } + + static Future _showMessageDialog( + BuildContext context, { + required String title, + required String message, + required String confirmText, + required Widget icon, + }) { + final theme = Theme.of(context); + return showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 1.0, + ), + ), + icon: icon, + title: Text(title), + content: Text(message), + actions: [ + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: Text(confirmText), + ), + ], + ); + }, + ); + } + + // ========================================== + // 3. 确认弹窗 (普通确认 vs 特殊/高危确认) + // ========================================== + + /// 普通确认弹窗 (如:保存提示、重新载入等常规操作) + static Future showConfirmDialog( + BuildContext context, { + required String title, + required String message, + String? confirmText, + String? cancelText, + Widget? icon, + }) async { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final effConfirmText = confirmText ?? l10n?.confirm ?? '确定'; + final effCancelText = cancelText ?? l10n?.cancel ?? '取消'; + final result = await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 1.0, + ), + ), + icon: icon, + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(effCancelText), + ), + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text(effConfirmText), + ), + ], + ); + }, + ); + return result ?? false; + } + + /// 特殊/高危确认弹窗 (如:删除文件、清空历史等不可逆操作) + static Future showDestructiveConfirmDialog( + BuildContext context, { + required String title, + required String message, + String? confirmText, + String? cancelText, + IconData icon = Icons.delete_outline, + }) async { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final effConfirmText = confirmText ?? l10n?.delete ?? '删除'; + final effCancelText = cancelText ?? l10n?.cancel ?? '取消'; + final result = await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.error.withValues(alpha: 0.5), + width: 1.0, + ), + ), + icon: Icon(icon, color: theme.colorScheme.error, size: 28), + title: Text( + title, + style: TextStyle(color: theme.colorScheme.error), + ), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(effCancelText), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: theme.colorScheme.error, + foregroundColor: theme.colorScheme.onError, + ), + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text(effConfirmText), + ), + ], + ); + }, + ); + return result ?? false; + } + + /// 未保存更改提示弹窗 (保存、不保存、取消) + static Future showSavePromptDialog( + BuildContext context, { + required String fileName, + }) async { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final title = l10n?.saveChangesTitle ?? '保存更改'; + final message = l10n?.saveChangesMessage(fileName) ?? '文件 "$fileName" 已被修改,是否保存更改?'; + final saveText = l10n?.save ?? '保存'; + final dontSaveText = l10n?.dontSave ?? '不保存'; + final cancelText = l10n?.cancel ?? '取消'; + + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 1.0, + ), + ), + icon: Icon( + Icons.help_outline, + color: theme.colorScheme.primary, + size: 28, + ), + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(SavePromptResult.cancel), + child: Text(cancelText), + ), + TextButton( + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.error, + ), + onPressed: () => Navigator.of(dialogContext).pop(SavePromptResult.discard), + child: Text(dontSaveText), + ), + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(SavePromptResult.save), + child: Text(saveText), + ), + ], + ); + }, + ); + + return result ?? SavePromptResult.cancel; + } + + /// 未保存所有更改提示弹窗 (保存所有、不保存、取消) + static Future showSaveAllPromptDialog( + BuildContext context, + ) async { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final title = l10n?.saveAllPromptTitle ?? '保存所有更改?'; + final message = l10n?.saveAllPromptMessage ?? '当前项目中有未保存的修改,是否保存所有文件?'; + final saveText = l10n?.saveAll ?? '保存所有'; + final dontSaveText = l10n?.dontSave ?? '不保存'; + final cancelText = l10n?.cancel ?? '取消'; + + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 1.0, + ), + ), + icon: Icon( + Icons.help_outline, + color: theme.colorScheme.primary, + size: 28, + ), + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(SavePromptResult.cancel), + child: Text(cancelText), + ), + TextButton( + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.error, + ), + onPressed: () => Navigator.of(dialogContext).pop(SavePromptResult.discard), + child: Text(dontSaveText), + ), + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(SavePromptResult.save), + child: Text(saveText), + ), + ], + ); + }, + ); + + return result ?? SavePromptResult.cancel; + } + + /// 外部文件冲突提示弹窗 (用磁盘内容覆盖、保留本地修改) + static Future showFileConflictDialog( + BuildContext context, { + required String fileName, + }) async { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final title = l10n?.fileConflictTitle ?? '外部文件已被更改'; + final message = l10n?.fileConflictMessage(fileName) ?? '文件 "$fileName" 已在外部被更改。您希望如何处理?'; + final reloadText = l10n?.reloadFromDisk ?? '用磁盘内容覆盖'; + final keepText = l10n?.keepLocal ?? '保留本地修改'; + + final result = await showDialog( + context: context, + barrierDismissible: false, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 1.0, + ), + ), + icon: Icon( + Icons.warning_amber_rounded, + color: Colors.amber.shade800, + size: 28, + ), + title: Text(title), + content: Text(message), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(FileConflictResult.keepLocal), + child: Text(keepText), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: theme.colorScheme.error, + foregroundColor: theme.colorScheme.onError, + ), + onPressed: () => Navigator.of(dialogContext).pop(FileConflictResult.reloadFromDisk), + child: Text(reloadText), + ), + ], + ); + }, + ); + + return result ?? FileConflictResult.keepLocal; + } + + // ========================================== + // 4. 输入弹窗 (Input Dialog) + // ========================================== + + /// 通用文本输入弹窗,返回用户输入的内容;若取消或关闭则返回 null + static Future showInputDialog( + BuildContext context, { + required String title, + String? hintText, + String? initialValue, + String? confirmText, + String? cancelText, + String? Function(String?)? validator, + }) { + final controller = TextEditingController(text: initialValue); + final formKey = GlobalKey(); + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final effConfirmText = confirmText ?? l10n?.confirm ?? '确定'; + final effCancelText = cancelText ?? l10n?.cancel ?? '取消'; + + // 默认校验:不可为空且不能包含常见系统非法字符 + String? defaultValidator(String? val) { + if (val == null || val.trim().isEmpty) { + return l10n?.nameCannotBeEmpty ?? '名称不能为空'; + } + if (val.contains(RegExp(r'[\\/:*?"<>|]'))) { + return l10n?.nameInvalidChars ?? '名称不能包含非法字符 (\\/:*?"<>|)'; + } + return null; + } + + return showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 1.0, + ), + ), + title: Text(title), + content: Form( + key: formKey, + child: TextFormField( + controller: controller, + autofocus: true, + decoration: InputDecoration( + hintText: hintText, + border: const OutlineInputBorder(), + ), + validator: validator ?? defaultValidator, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(null), + child: Text(effCancelText), + ), + FilledButton( + onPressed: () { + if (formKey.currentState?.validate() ?? false) { + Navigator.of(dialogContext).pop(controller.text); + } + }, + child: Text(effConfirmText), + ), + ], + ); + }, + ); + } +} diff --git a/lib/utils/syntax_highlight_helper.dart b/lib/utils/syntax_highlight_helper.dart new file mode 100644 index 0000000..1afafd2 --- /dev/null +++ b/lib/utils/syntax_highlight_helper.dart @@ -0,0 +1,178 @@ +import 'package:path/path.dart' as p; +import 'package:re_editor/re_editor.dart'; +import 'package:re_highlight/languages/all.dart'; + +/// 语法高亮辅助类: +/// 1. 基于文件后缀与特殊文件名的 O(1) 语法匹配,彻底避免全量遍历 +/// 2. 语法模式单例缓存,避免每帧重复创建 CodeHighlightThemeMode +class SyntaxHighlightHelper { + SyntaxHighlightHelper._(); + + static final Map _modeCache = {}; + + /// 特殊文件名映射(忽略大小写比较) + static const Map _fileNameMap = { + 'dockerfile': 'dockerfile', + 'makefile': 'makefile', + 'gnumakefile': 'makefile', + 'cmakelists.txt': 'cmake', + 'gemfile': 'ruby', + 'rakefile': 'ruby', + 'podfile': 'ruby', + 'vagrantfile': 'ruby', + 'package.json': 'json', + 'composer.json': 'json', + 'pubspec.yaml': 'yaml', + 'pubspec.lock': 'yaml', + '.bashrc': 'bash', + '.bash_profile': 'bash', + '.zshrc': 'bash', + '.profile': 'bash', + '.gitignore': 'ini', + '.gitattributes': 'ini', + '.gitmodules': 'ini', + '.editorconfig': 'ini', + '.env': 'ini', + }; + + /// 常见扩展名到 re_highlight 语言标识符的 O(1) 映射 + static const Map _extensionMap = { + // Dart & Flutter + '.dart': 'dart', + + // Web & JS / TS + '.js': 'javascript', + '.mjs': 'javascript', + '.cjs': 'javascript', + '.jsx': 'javascript', + '.ts': 'typescript', + '.mts': 'typescript', + '.cts': 'typescript', + '.tsx': 'typescript', + '.json': 'json', + '.jsonc': 'json', + '.arb': 'json', + '.html': 'xml', + '.htm': 'xml', + '.xhtml': 'xml', + '.vue': 'xml', + '.css': 'css', + '.scss': 'scss', + '.less': 'less', + + // 配置与数据标记 + '.yaml': 'yaml', + '.yml': 'yaml', + '.xml': 'xml', + '.iml': 'xml', + '.svg': 'xml', + '.plist': 'xml', + '.xaml': 'xml', + '.properties': 'properties', + '.ini': 'ini', + '.cfg': 'ini', + '.conf': 'ini', + '.config': 'ini', + '.toml': 'ini', + '.proto': 'protobuf', + + // 文档 + '.md': 'markdown', + '.markdown': 'markdown', + '.tex': 'latex', + + // 常用后端与系统语言 + '.py': 'python', + '.pyw': 'python', + '.java': 'java', + '.kt': 'kotlin', + '.kts': 'kotlin', + '.c': 'c', + '.h': 'c', + '.cpp': 'cpp', + '.cxx': 'cpp', + '.cc': 'cpp', + '.hpp': 'cpp', + '.hxx': 'cpp', + '.hh': 'cpp', + '.cs': 'csharp', + '.go': 'go', + '.rs': 'rust', + '.swift': 'swift', + '.php': 'php', + '.rb': 'ruby', + '.lua': 'lua', + '.r': 'r', + '.sql': 'sql', + + // 脚本与自动化 + '.sh': 'bash', + '.bash': 'bash', + '.zsh': 'bash', + '.ps1': 'powershell', + '.psm1': 'powershell', + '.bat': 'dos', + '.cmd': 'dos', + + // 构建与版本控制 + '.cmake': 'cmake', + '.gradle': 'gradle', + '.groovy': 'groovy', + '.diff': 'diff', + '.patch': 'diff', + '.dockerfile': 'dockerfile', + '.graphql': 'graphql', + '.gql': 'graphql', + }; + + /// 根据文件路径获取对应的 re_highlight 语言 ID,未匹配则返回 null + static String? getLanguageId(String? filePath) { + if (filePath == null || filePath.trim().isEmpty) { + return null; + } + final fileName = p.basename(filePath).toLowerCase(); + + // 1. 优先根据完整文件名精准匹配 (例如 Dockerfile, Makefile, pubspec.yaml) + final exactMatch = _fileNameMap[fileName]; + if (exactMatch != null) { + return exactMatch; + } + + // 2. 根据文件扩展名 O(1) 匹配 + final ext = p.extension(filePath).toLowerCase(); + if (ext.isNotEmpty) { + return _extensionMap[ext]; + } + + return null; + } + + /// 获取指定语言的 CodeHighlightThemeMode 实例(带缓存单例) + static CodeHighlightThemeMode? getMode(String langId) { + final cached = _modeCache[langId]; + if (cached != null) { + return cached; + } + final definition = builtinAllLanguages[langId]; + if (definition != null) { + final mode = CodeHighlightThemeMode(mode: definition); + _modeCache[langId] = mode; + return mode; + } + return null; + } + + /// 为指定文件获取仅包含所需语法的精简映射表。 + /// 若为纯文本或未知格式则返回空 Map,不会注入无用的 194 种模式。 + static Map getLanguagesForFile(String? filePath) { + final langId = getLanguageId(filePath); + if (langId == null) { + return const {}; + } + final mode = getMode(langId); + if (mode == null) { + return const {}; + } + return {langId: mode}; + } +} diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index ca03e10..352ce00 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -1,6 +1,12 @@ +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'; +import 'package:code_editor/views/settings_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/widgets/code_editor_tab_bar.dart'; import 'package:code_editor/widgets/code_editor_widget.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -8,29 +14,95 @@ import 'package:provider/provider.dart'; 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; + } + } + + 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; + } + } + + void _handleSave(BuildContext context) async { + final tabProvider = _getTabProvider(context); + if (tabProvider.currentFilePath == null || tabProvider.currentFilePath!.isEmpty) { + return; + } + final saved = await tabProvider.saveCurrentFile(); + if (saved && context.mounted) { + final l10n = AppLocalizations.of(context); + DialogUtils.showSuccessToast(context, l10n?.saveSuccess ?? '保存成功'); + } + } + + void _handleSaveAll(BuildContext context) async { + final tabProvider = _getTabProvider(context); + final saved = await tabProvider.saveAllFiles(); + if (saved && context.mounted) { + final l10n = AppLocalizations.of(context); + DialogUtils.showSuccessToast(context, l10n?.saveAllSuccess ?? '所有文件已保存'); + } + } + @override Widget build(BuildContext context) { - final isLoading = context.select((p) => p.isLoading); - if (isLoading) { + final projectProvider = _getProjectProvider(context, listen: true); + final tabProvider = _getTabProvider(context, listen: true); + + if (projectProvider.isLoading) { return const Center(child: CircularProgressIndicator()); } - final currentFile = context.select((p) => p.currentFilePath); - final rootPath = context.select((p) => p.rootPath); + final currentFile = tabProvider.currentFilePath; + final rootPath = projectProvider.rootPath; + final isModified = tabProvider.isModified; - return Scaffold( - appBar: CodeEditorAppBar( - filePath: currentFile, - onUndo: () {}, - onRedo: () {}, - onSave: () {}, - onRun: () {}, - onSettings: () {}, - ), - drawer: const CodeEditorDrawer(), - body: CodeEditorWidget( - filePath: currentFile, - rootPath: rootPath, + return PopScope( + canPop: !isModified, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + final canProceed = await _getTabProvider(context).checkUnsavedChanges(context); + if (canProceed && context.mounted) { + Navigator.of(context).pop(); + } + }, + child: Scaffold( + appBar: CodeEditorAppBar( + filePath: currentFile, + rootPath: rootPath, + isModified: isModified, + onSave: () => _handleSave(context), + onSaveAll: () => _handleSaveAll(context), + onRun: () {}, + onSettings: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => const SettingsView(), + ), + ); + }, + ), + drawer: const CodeEditorDrawer(), + body: Column( + children: [ + const CodeEditorTabBar(), + Expanded( + child: CodeEditorWidget( + filePath: currentFile, + rootPath: rootPath, + ), + ), + ], + ), ), ); } diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart new file mode 100644 index 0000000..01dc77d --- /dev/null +++ b/lib/views/settings_view.dart @@ -0,0 +1,507 @@ +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/providers/settings_provider.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +/// 设置页面 +class SettingsView extends StatelessWidget { + const SettingsView({super.key}); + + static SettingsProvider _getProvider(BuildContext context) { + try { + return context.watch(); + } catch (_) { + return context.watch().settingsProvider; + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final provider = _getProvider(context); + + return Scaffold( + appBar: AppBar( + leading: IconButton( + icon: const Icon(Icons.arrow_back), + tooltip: l10n.back, + onPressed: () => Navigator.of(context).pop(), + ), + title: Text(l10n.settings), + centerTitle: false, + ), + body: ListView( + padding: const EdgeInsets.symmetric(vertical: 12), + children: [ + // ============================== + // 1. 外观分组 (Appearance) + // ============================== + _buildSectionHeader(context, l10n.appearanceSection), + _buildThemeModeTile(context, provider, l10n), + + const Divider(height: 32, indent: 16, endIndent: 16), + + // ============================== + // 2. 编辑区分组 (Editor) + // ============================== + _buildSectionHeader(context, l10n.editorSection), + _buildEditorThemeTile(context, provider, l10n), + _buildFontSizeTile(context, provider, l10n), + _buildWordWrapTile(context, provider, l10n), + + const Divider(height: 32, indent: 16, endIndent: 16), + + // ============================== + // 3. 语言分组 (Language) + // ============================== + _buildSectionHeader(context, l10n.languageSection), + _buildLanguageTile(context, provider, l10n), + ], + ), + ); + } + + /// 一行设置区介绍标题 + Widget _buildSectionHeader(BuildContext context, String title) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 6), + child: Text( + title, + style: theme.textTheme.labelLarge?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + letterSpacing: 0.5, + ), + ), + ); + } + + /// 外观:系统/明亮/暗黑主题切换条目 + Widget _buildThemeModeTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + final currentMode = provider.appThemeMode; + + final (icon, modeTitle) = switch (currentMode) { + ThemeMode.system => (Icons.brightness_auto, l10n.followSystem), + ThemeMode.light => (Icons.light_mode, l10n.lightMode), + ThemeMode.dark => (Icons.dark_mode, l10n.darkMode), + }; + + return ListTile( + leading: Icon(icon, color: theme.colorScheme.primary), + title: Text(l10n.appThemeMode), + subtitle: Text(modeTitle), + trailing: const Icon(Icons.chevron_right), + onTap: () { + _showThemeModeSelector(context, provider, l10n); + }, + ); + } + + void _showThemeModeSelector( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + showModalBottomSheet( + context: context, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (sheetContext) { + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + l10n.selectAppTheme, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + ), + RadioGroup( + groupValue: provider.appThemeMode, + onChanged: (mode) { + if (mode != null) { + provider.setAppThemeMode(mode); + Navigator.of(sheetContext).pop(); + } + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + RadioListTile( + title: Text(l10n.followSystem), + subtitle: Text(l10n.followSystemSubtitle), + value: ThemeMode.system, + ), + RadioListTile( + title: Text(l10n.lightMode), + subtitle: Text(l10n.lightModeSubtitle), + value: ThemeMode.light, + ), + RadioListTile( + title: Text(l10n.darkMode), + subtitle: Text(l10n.darkModeSubtitle), + value: ThemeMode.dark, + ), + ], + ), + ), + const SizedBox(height: 12), + ], + ), + ); + }, + ); + } + + /// 编辑区:代码主题切换条目 + Widget _buildEditorThemeTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + final currentTheme = provider.editorTheme; + final themeCategory = currentTheme.isDark ? l10n.darkLabel : l10n.lightLabel; + + return ListTile( + leading: Icon(Icons.palette_outlined, color: theme.colorScheme.primary), + title: Text(l10n.codeHighlightTheme), + subtitle: Text( + '${currentTheme.name} ($themeCategory)', + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 24, + height: 24, + decoration: BoxDecoration( + color: currentTheme.backgroundColor, + shape: BoxShape.circle, + border: Border.all( + color: theme.colorScheme.outlineVariant, + width: 1.5, + ), + ), + ), + const SizedBox(width: 8), + const Icon(Icons.chevron_right), + ], + ), + onTap: () { + _showEditorThemeSelector(context, provider, l10n); + }, + ); + } + + void _showEditorThemeSelector( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (sheetContext) { + final theme = Theme.of(context); + return SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(sheetContext).size.height * 0.65, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + l10n.selectCodeHighlightTheme, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + ), + Expanded( + child: ListView.builder( + itemCount: EditorTheme.presets.length, + itemBuilder: (context, index) { + final item = EditorTheme.presets[index]; + final isSelected = item.id == provider.editorTheme.id; + + return ListTile( + leading: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: item.backgroundColor, + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: theme.colorScheme.outlineVariant, + width: 1, + ), + ), + alignment: Alignment.center, + child: Text( + 'Aa', + style: TextStyle( + color: item.textColor, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + title: Text(item.name), + subtitle: Text( + item.isDark ? l10n.darkThemeCategory : l10n.lightThemeCategory, + ), + trailing: isSelected + ? Icon(Icons.check, color: theme.colorScheme.primary) + : null, + selected: isSelected, + onTap: () { + provider.setEditorTheme(item); + Navigator.of(sheetContext).pop(); + }, + ); + }, + ), + ), + ], + ), + ), + ); + }, + ); + } + + /// 编辑区:字号与缩放调节条目 + Widget _buildFontSizeTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + + return ListTile( + leading: Icon(Icons.format_size, color: theme.colorScheme.primary), + title: Text(l10n.codeFontSize), + subtitle: Text('${provider.fontSize.toInt()} pt'), + trailing: SizedBox( + width: 150, + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + IconButton( + icon: const Icon(Icons.remove, size: 18), + visualDensity: VisualDensity.compact, + tooltip: l10n.decreaseFontSize, + onPressed: provider.fontSize > 10.0 + ? () => provider.setFontSize(provider.fontSize - 1) + : null, + ), + Text( + '${provider.fontSize.toInt()}', + style: const TextStyle(fontWeight: FontWeight.bold), + ), + IconButton( + icon: const Icon(Icons.add, size: 18), + visualDensity: VisualDensity.compact, + tooltip: l10n.increaseFontSize, + onPressed: provider.fontSize < 30.0 + ? () => provider.setFontSize(provider.fontSize + 1) + : null, + ), + ], + ), + ), + onTap: () { + _showFontSizeDialog(context, provider, l10n); + }, + ); + } + + void _showFontSizeDialog( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + double tempSize = provider.fontSize; + + showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setDialogState) { + return AlertDialog( + title: Text(l10n.fontSizeDialogTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${tempSize.toInt()} pt', + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + Slider( + value: tempSize.clamp(10.0, 30.0), + min: 10.0, + max: 30.0, + divisions: 20, + label: '${tempSize.toInt()}', + onChanged: (val) { + setDialogState(() { + tempSize = val; + }); + provider.setFontSize(val); + }, + ), + const SizedBox(height: 8), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: provider.editorTheme.backgroundColor, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + 'const hello = "World";', + style: TextStyle( + color: provider.editorTheme.textColor, + fontSize: tempSize, + fontFamily: 'Consolas, Monaco, monospace', + ), + ), + ), + ], + ), + actions: [ + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: Text(l10n.done), + ), + ], + ); + }, + ); + }, + ); + } + + /// 编辑区:自动换行切换条目 + Widget _buildWordWrapTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + + return SwitchListTile( + secondary: Icon(Icons.wrap_text, color: theme.colorScheme.primary), + title: Text(l10n.wordWrap), + subtitle: Text(l10n.wordWrapSubtitle), + value: provider.wordWrap, + onChanged: (val) => provider.setWordWrap(val), + ); + } + + /// 语言:应用语言选择条目 + Widget _buildLanguageTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + final currentLocale = provider.locale; + + final langTitle = switch (currentLocale?.languageCode) { + 'zh' => l10n.languageChinese, + 'en' => l10n.languageEnglish, + _ => l10n.languageFollowSystem, + }; + + return ListTile( + leading: Icon(Icons.language, color: theme.colorScheme.primary), + title: Text(l10n.appLanguage), + subtitle: Text(langTitle), + trailing: const Icon(Icons.chevron_right), + onTap: () { + _showLanguageSelector(context, provider, l10n); + }, + ); + } + + void _showLanguageSelector( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final currentValue = provider.locale?.languageCode ?? 'system'; + + showModalBottomSheet( + context: context, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (sheetContext) { + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + l10n.selectLanguage, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + ), + RadioGroup( + groupValue: currentValue, + onChanged: (val) { + if (val != null) { + if (val == 'system') { + provider.setLocale(null); + } else { + provider.setLocale(Locale(val)); + } + Navigator.of(sheetContext).pop(); + } + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + RadioListTile( + title: Text(l10n.languageFollowSystem), + subtitle: Text(l10n.followSystemSubtitle), + value: 'system', + ), + RadioListTile( + title: Text(l10n.languageChinese), + value: 'zh', + ), + RadioListTile( + title: Text(l10n.languageEnglish), + value: 'en', + ), + ], + ), + ), + const SizedBox(height: 12), + ], + ), + ); + }, + ); + } +} diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart index 604fd67..e717004 100644 --- a/lib/widgets/code_editor_app_bar.dart +++ b/lib/widgets/code_editor_app_bar.dart @@ -4,18 +4,20 @@ import 'package:path/path.dart' as p; class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { final String? filePath; - final VoidCallback? onUndo; - final VoidCallback? onRedo; + final String? rootPath; + final bool isModified; final VoidCallback? onSave; + final VoidCallback? onSaveAll; final VoidCallback? onRun; final VoidCallback? onSettings; const CodeEditorAppBar({ super.key, required this.filePath, - this.onUndo, - this.onRedo, + this.rootPath, + this.isModified = false, this.onSave, + this.onSaveAll, this.onRun, this.onSettings, }); @@ -29,29 +31,59 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { final l10n = AppLocalizations.of(context)!; final path = filePath; + final String titleText; + final String? subtitleText; + if (path != null && path.isNotEmpty) { + final base = p.basename(path); + titleText = isModified ? '* $base' : base; + + if (rootPath != null && rootPath!.trim().isNotEmpty) { + final cleanRoot = p.normalize(rootPath!.trim()); + final cleanFile = p.normalize(path.trim()); + final dirPath = p.dirname(cleanFile); + + if (dirPath == cleanRoot || !p.isWithin(cleanRoot, cleanFile)) { + subtitleText = '/'; + } else { + final rel = p.relative(dirPath, from: cleanRoot); + final formattedRel = rel.replaceAll(r'\', '/'); + subtitleText = formattedRel.startsWith('/') ? formattedRel : '/$formattedRel'; + } + } else { + subtitleText = '/'; + } + } else { + titleText = ''; + subtitleText = null; + } + return AppBar( backgroundColor: theme.colorScheme.primaryContainer, - foregroundColor: theme.colorScheme.onPrimaryContainer, - title: Text(path != null && path.isNotEmpty ? p.basename(path) : ''), + foregroundColor: theme.colorScheme.onSurface, + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + titleText, + style: const TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.bold, + ), + overflow: TextOverflow.ellipsis, + ), + if (subtitleText != null) + Text( + subtitleText, + style: TextStyle( + fontSize: 11.0, + color: theme.colorScheme.onSurfaceVariant, + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), actions: [ - IconButton( - visualDensity: VisualDensity.compact, - icon: const Icon(Icons.undo), - tooltip: l10n.undo, - onPressed: onUndo ?? () {}, - ), - IconButton( - visualDensity: VisualDensity.compact, - icon: const Icon(Icons.redo), - tooltip: l10n.redo, - onPressed: onRedo ?? () {}, - ), - IconButton( - visualDensity: VisualDensity.compact, - icon: const Icon(Icons.save_outlined), - tooltip: l10n.save, - onPressed: onSave ?? () {}, - ), IconButton( visualDensity: VisualDensity.compact, icon: const Icon(Icons.play_arrow), @@ -60,9 +92,43 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { ), IconButton( visualDensity: VisualDensity.compact, - icon: const Icon(Icons.settings), - tooltip: l10n.settings, - onPressed: onSettings ?? () {}, + icon: const Icon(Icons.save_outlined), + tooltip: l10n.save, + onPressed: onSave ?? () {}, + ), + PopupMenuButton( + icon: const Icon(Icons.more_vert), + tooltip: l10n.more, + position: PopupMenuPosition.under, + onSelected: (value) { + if (value == 'save_all') { + onSaveAll?.call(); + } else if (value == 'settings') { + onSettings?.call(); + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'save_all', + child: Row( + children: [ + const Icon(Icons.save_as_outlined, size: 20), + const SizedBox(width: 10), + Text(l10n.saveAll), + ], + ), + ), + PopupMenuItem( + value: 'settings', + child: Row( + children: [ + const Icon(Icons.settings, size: 20), + const SizedBox(width: 10), + Text(l10n.settings), + ], + ), + ), + ], ), ], ); diff --git a/lib/widgets/code_editor_drawer.dart b/lib/widgets/code_editor_drawer.dart index fc47227..3b45fbb 100644 --- a/lib/widgets/code_editor_drawer.dart +++ b/lib/widgets/code_editor_drawer.dart @@ -1,5 +1,7 @@ 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/widgets/file_tree_widget.dart'; import 'package:flutter/material.dart'; @@ -8,11 +10,30 @@ 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; + } + } + + 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; + } + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = AppLocalizations.of(context)!; - final rootPath = context.select((p) => p.rootPath); + final projectProvider = _getProjectProvider(context, listen: true); + final rootPath = projectProvider.rootPath; return Drawer( child: SafeArea( @@ -38,13 +59,17 @@ class CodeEditorDrawer extends StatelessWidget { const Spacer(), IconButton( icon: const Icon(Icons.refresh), - tooltip: '刷新目录', - onPressed: () => context.read().refreshTree(), + tooltip: l10n.refreshDirectory, + onPressed: () => _getProjectProvider(context).refreshTree(), ), IconButton( icon: const Icon(Icons.folder_open), tooltip: l10n.openFileDirectory, - onPressed: () => context.read().openDirectory(), + onPressed: () async { + final canProceed = await _getTabProvider(context).checkUnsavedChanges(context); + if (!canProceed || !context.mounted) return; + _getProjectProvider(context).openDirectory(); + }, ), IconButton( icon: const Icon(Icons.history), @@ -52,8 +77,10 @@ class CodeEditorDrawer extends StatelessWidget { onPressed: () { FileDirectoryHistoryWidget.show( context, - onSelectHistory: (selectedHistory) { - context.read().switchProject(selectedHistory); + onSelectHistory: (selectedHistory) async { + final canProceed = await _getTabProvider(context).checkUnsavedChanges(context); + if (!canProceed || !context.mounted) return; + _getProjectProvider(context).switchProject(selectedHistory); }, ); }, @@ -63,7 +90,7 @@ class CodeEditorDrawer extends StatelessWidget { Text( rootPath ?? '', style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onPrimaryContainer.withValues(alpha: 0.8), + color: theme.colorScheme.onSurfaceVariant, ), overflow: TextOverflow.ellipsis, maxLines: 1, diff --git a/lib/widgets/code_editor_menu.dart b/lib/widgets/code_editor_menu.dart new file mode 100644 index 0000000..3b89935 --- /dev/null +++ b/lib/widgets/code_editor_menu.dart @@ -0,0 +1,114 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:re_editor/re_editor.dart'; + +/// 桌面端与移动端代码编辑器的浮动/右键菜单项组件 +class _EditorContextMenuItem extends PopupMenuItem implements PreferredSizeWidget { + _EditorContextMenuItem({ + required String text, + required IconData icon, + required VoidCallback onTap, + super.enabled = true, + }) : super( + onTap: onTap, + height: 36, + child: Row( + children: [ + Icon(icon, size: 16), + const SizedBox(width: 8), + Text(text, style: const TextStyle(fontSize: 13)), + ], + ), + ); + + @override + Size get preferredSize => const Size(140, 36); +} + +/// 自定义代码编辑器选区与右键菜单控制器 +class CodeEditorToolbarController implements SelectionToolbarController { + const CodeEditorToolbarController(); + + @override + void hide(BuildContext context) { + // 菜单由 showMenu / 遮罩自动关闭,不需要额外动作 + } + + @override + void show({ + required BuildContext context, + required CodeLineEditingController controller, + required TextSelectionToolbarAnchors anchors, + Rect? renderRect, + required LayerLink layerLink, + required ValueNotifier visibility, + }) async { + final hasSelection = controller.selection.baseOffset != -1 && + controller.selection.extentOffset != -1 && + !controller.selection.isCollapsed; + + // 检查剪贴板是否有内容以决定是否启用粘贴 + final clipboardData = await Clipboard.getData(Clipboard.kTextPlain); + final hasClipboard = clipboardData != null && (clipboardData.text?.isNotEmpty ?? false); + + if (!context.mounted) return; + + final l10n = AppLocalizations.of(context); + final mediaQuery = MediaQuery.of(context); + final anchor = anchors.primaryAnchor.dx > 0 && anchors.primaryAnchor.dy > 0 + ? anchors.primaryAnchor + : (anchors.secondaryAnchor ?? Offset.zero); + + await showMenu( + context: context, + elevation: 6, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide( + color: Theme.of(context).colorScheme.outlineVariant, + width: 0.8, + ), + ), + position: RelativeRect.fromRect( + anchor & const Size(140, 40), + Offset.zero & mediaQuery.size, + ), + items: [ + _EditorContextMenuItem( + text: l10n?.cut ?? '剪切', + icon: Icons.content_cut, + enabled: hasSelection, + onTap: () { + controller.cut(); + }, + ), + _EditorContextMenuItem( + text: l10n?.copy ?? '复制', + icon: Icons.copy, + enabled: hasSelection, + onTap: () { + controller.copy(); + }, + ), + _EditorContextMenuItem( + text: l10n?.paste ?? '粘贴', + icon: Icons.paste, + enabled: hasClipboard, + onTap: () { + controller.paste(); + }, + ), + const PopupMenuDivider(height: 1), + _EditorContextMenuItem( + text: l10n?.selectAll ?? '全选', + icon: Icons.select_all, + enabled: !controller.isEmpty, + onTap: () { + controller.selectAll(); + }, + ), + ], + ); + } +} diff --git a/lib/widgets/code_editor_tab_bar.dart b/lib/widgets/code_editor_tab_bar.dart new file mode 100644 index 0000000..bd2cd15 --- /dev/null +++ b/lib/widgets/code_editor_tab_bar.dart @@ -0,0 +1,241 @@ +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'; +import 'package:provider/provider.dart'; + +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; + } + } + + 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; + } + } + } + + double _calculateTabNaturalWidth( + BuildContext context, { + required String displayName, + required bool isModified, + }) { + final textScaler = MediaQuery.maybeTextScalerOf(context) ?? TextScaler.noScaling; + final theme = Theme.of(context); + final textPainter = TextPainter( + text: TextSpan( + text: displayName, + style: TextStyle( + fontSize: 12.0, + fontWeight: FontWeight.bold, + fontFamilyFallback: theme.textTheme.bodyMedium?.fontFamilyFallback, + ), + ), + textScaler: textScaler, + maxLines: 1, + textDirection: TextDirection.ltr, + )..layout(); + + // 实际所需完整宽度(向上取整避免浮点精度缺失): + // 文本宽度 + 脏标记 (12.0) + 内外间距与关闭按钮 (33.0) + 安全呼吸缓冲空间 (16.0) + final textWidth = textPainter.width.ceilToDouble(); + final dirtyWidth = isModified ? 12.0 : 0.0; + const fixedElementsWidth = 33.0; // 容器内边距(8) + 关闭按钮(24) + 边框(1) + const safetyBuffer = 16.0; // 安全呼吸空间,杜绝亚像素及字体微偏差导致的省略号 + + return textWidth + dirtyWidth + fixedElementsWidth + safetyBuffer; + } + + @override + Widget build(BuildContext context) { + final tabProvider = _getTabProvider(context); + final projectProvider = _getProjectProvider(context); + final tabs = tabProvider.openTabs; + if (tabs.isEmpty) { + return const SizedBox.shrink(); + } + + final theme = Theme.of(context); + final activePath = tabProvider.currentFilePath; + final rootPath = projectProvider?.rootPath; + + return Container( + height: 36.0, + width: double.infinity, + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.2), + border: Border( + bottom: BorderSide( + color: theme.colorScheme.outlineVariant, + width: 0.8, + ), + ), + ), + child: LayoutBuilder( + builder: (context, constraints) { + final totalWidth = constraints.maxWidth; + final tabCount = tabs.length; + final equalShare = math.max(28.0, totalWidth / tabCount); + + return Theme( + data: theme.copyWith( + canvasColor: Colors.transparent, + shadowColor: Colors.transparent, + ), + child: ReorderableListView.builder( + scrollDirection: Axis.horizontal, + buildDefaultDragHandles: false, + itemCount: tabs.length, + onReorderItem: (oldIndex, newIndex) { + tabProvider.reorderTabs(oldIndex, newIndex); + }, + itemBuilder: (context, index) { + final tab = tabs[index]; + final isSelected = activePath != null && tab.path == activePath; + final displayName = tab.getDisplayName(tabs, rootPath); + final naturalWidth = _calculateTabNaturalWidth( + context, + displayName: displayName, + isModified: tab.isModified, + ); + // 单个 tab 最大宽度为内容宽度(名称宽度+默认间距+按钮宽度),不足时等比例压缩划分 + final itemWidth = math.min(naturalWidth, equalShare); + + return _buildTabItem( + context, + tabProvider: tabProvider, + tab: tab, + index: index, + isSelected: isSelected, + displayName: displayName, + width: itemWidth, + ); + }, + ), + ); + }, + ), + ); + } + + Widget _buildTabItem( + BuildContext context, { + required TabProvider tabProvider, + required EditorTabItem tab, + required int index, + required bool isSelected, + required String displayName, + required double width, + }) { + final theme = Theme.of(context); + + return ReorderableDelayedDragStartListener( + key: ValueKey(tab.path), + index: index, + child: Container( + width: width, + height: 36.0, + decoration: BoxDecoration( + color: isSelected + ? theme.colorScheme.surface + : theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.35), + border: Border( + right: BorderSide( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 1.0, + ), + bottom: isSelected + ? BorderSide( + color: theme.colorScheme.primary, + width: 2.0, + ) + : BorderSide.none, + ), + ), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + tabProvider.openFile(tab.path); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4.0), + child: Row( + children: [ + Expanded( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (tab.isModified) + Padding( + padding: const EdgeInsets.only(right: 2.0), + child: Text( + '*', + style: TextStyle( + color: theme.colorScheme.error, + fontWeight: FontWeight.bold, + fontSize: 13.0, + ), + ), + ), + Flexible( + child: Text( + displayName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.0, + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, + color: isSelected + ? theme.colorScheme.onSurface + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ), + InkResponse( + radius: 12, + borderRadius: BorderRadius.circular(4.0), + hoverColor: theme.colorScheme.onSurface.withValues(alpha: 0.12), + highlightColor: theme.colorScheme.onSurface.withValues(alpha: 0.18), + onTap: () { + tabProvider.closeTab(context, index); + }, + child: Padding( + padding: const EdgeInsets.all(3.0), + child: Icon( + Icons.close, + size: 14.0, + color: isSelected + ? theme.colorScheme.onSurface + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); +} +} diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index ee9a872..86228fa 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -1,11 +1,19 @@ -import 'dart:convert'; - +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/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.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'; +import 'package:code_editor/utils/syntax_highlight_helper.dart'; +import 'package:code_editor/widgets/code_editor_menu.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_code_editor/flutter_code_editor.dart'; -import 'package:flutter_highlight/themes/atom-one-dark.dart'; -import 'package:highlight/languages/dart.dart'; +import 'package:flutter/scheduler.dart'; import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:re_editor/re_editor.dart'; class CodeEditorWidget extends StatefulWidget { final String? rootPath; @@ -14,7 +22,7 @@ class CodeEditorWidget extends StatefulWidget { const CodeEditorWidget({ super.key, required this.rootPath, - required this.filePath + required this.filePath, }); @override @@ -22,10 +30,102 @@ class CodeEditorWidget extends StatefulWidget { } class _CodeEditorWidgetState extends State { - final CodeController _controller = CodeController(); + 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; + } + } + + 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; + } + } + + CodeLineEditingController? _controller; + CodeScrollController? _scrollController; bool _isLoading = false; int _currentLoadVersion = 0; String? _errorMessage; + String? _currentLoadedPath; + bool _isShowingConflictDialog = false; + + EditorTabItem? _getCurrentTab() { + final filePath = widget.filePath; + if (filePath == null || filePath.isEmpty) return null; + try { + final provider = _getTabProvider(context); + final rootPath = widget.rootPath; + final fullFilePath = (rootPath == null || rootPath.isEmpty || p.isAbsolute(filePath)) + ? filePath + : p.join(rootPath, filePath); + final cleanPath = p.normalize(fullFilePath); + return provider.openTabs.where((t) => p.equals(t.path, cleanPath)).firstOrNull; + } catch (_) { + return null; + } + } + + void _saveCurrentTabScrollState(EditorTabItem? tab) { + if (tab == null || _scrollController == null) return; + if (_scrollController!.verticalScroller.hasClients) { + tab.verticalScrollOffset = _scrollController!.verticalScroller.offset; + } + if (_scrollController!.horizontalScroller.hasClients) { + tab.horizontalScrollOffset = _scrollController!.horizontalScroller.offset; + } + } + + void _restoreTabScrollState(EditorTabItem tab) { + final oldScroll = _scrollController; + + final vScroller = ScrollController(initialScrollOffset: tab.verticalScrollOffset); + final hScroller = ScrollController(initialScrollOffset: tab.horizontalScrollOffset); + + vScroller.addListener(() { + if (vScroller.hasClients) { + tab.verticalScrollOffset = vScroller.offset; + } + }); + hScroller.addListener(() { + if (hScroller.hasClients) { + tab.horizontalScrollOffset = hScroller.offset; + } + }); + + _scrollController = CodeScrollController( + verticalScroller: vScroller, + horizontalScroller: hScroller, + ); + + oldScroll?.verticalScroller.dispose(); + oldScroll?.horizontalScroller.dispose(); + oldScroll?.dispose(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || _scrollController == null) return; + if (vScroller.hasClients) { + final maxV = vScroller.position.maxScrollExtent; + final targetV = tab.verticalScrollOffset.clamp(0.0, maxV); + if ((vScroller.offset - targetV).abs() > 0.5) { + vScroller.jumpTo(targetV); + } + } + if (hScroller.hasClients) { + final maxH = hScroller.position.maxScrollExtent; + final targetH = tab.horizontalScrollOffset.clamp(0.0, maxH); + if ((hScroller.offset - targetH).abs() > 0.5) { + hScroller.jumpTo(targetH); + } + } + }); + } @override void initState() { @@ -37,25 +137,173 @@ class _CodeEditorWidgetState extends State { void didUpdateWidget(covariant CodeEditorWidget oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.filePath != widget.filePath || oldWidget.rootPath != widget.rootPath) { + if (_controller != null && oldWidget.filePath != null) { + try { + final provider = _getTabProvider(context); + final oldPath = p.normalize(oldWidget.filePath!); + final oldTab = provider.openTabs.where((t) => p.equals(t.path, oldPath)).firstOrNull; + if (oldTab != null && oldTab.isLoaded) { + final current = _controller!.text.replaceAll('\r\n', '\n'); + final normalizedOriginal = oldTab.originalContent.replaceAll('\r\n', '\n'); + oldTab.content = current; + oldTab.isModified = current != normalizedOriginal; + _saveCurrentTabScrollState(oldTab); + } + } catch (_) {} + } _loadFileContent(); } } @override void dispose() { - _controller.dispose(); + try { + _getTabProvider(context).registerSaveHandler(null); + } catch (_) {} + final currentTab = _getCurrentTab(); + _saveCurrentTabScrollState(currentTab); + _scrollController?.verticalScroller.dispose(); + _scrollController?.horizontalScroller.dispose(); + _scrollController?.dispose(); + _controller?.removeListener(_onTextChanged); + _controller?.dispose(); super.dispose(); } + void _onTextChanged() { + if (!mounted || _controller == null) return; + final currentTab = _getCurrentTab(); + if (currentTab == null || !currentTab.isLoaded) return; + // 确保当前活跃 tab 与当前加载的控制器路径严格一致,杜绝切换过程中误写其他 tab + if (!p.equals(currentTab.path, _currentLoadedPath ?? '')) return; + + final current = _controller!.text.replaceAll('\r\n', '\n'); + final normalizedOriginal = currentTab.originalContent.replaceAll('\r\n', '\n'); + final isModified = current != normalizedOriginal; + + // 若文本内容与脏状态均未变化(例如光标移动、选区变动、代理绑定),直接跳过 + if (currentTab.content == current && currentTab.isModified == isModified) { + return; + } + + currentTab.content = current; + currentTab.isModified = isModified; + + void notifyProvider() { + if (!mounted) return; + try { + final provider = _getTabProvider(context); + provider.updateActiveTabContent(current, isModified: isModified); + } catch (_) {} + } + + if (WidgetsBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { + WidgetsBinding.instance.addPostFrameCallback((_) => notifyProvider()); + } else { + notifyProvider(); + } + } + + Future _saveFile({bool showToast = false}) async { + final currentPath = widget.filePath; + if (currentPath == null || currentPath.isEmpty || _controller == null) { + return false; + } + final rootPath = widget.rootPath; + final String fullFilePath = (rootPath == null || rootPath.isEmpty || p.isAbsolute(currentPath)) + ? currentPath + : p.join(rootPath, currentPath); + + try { + FileWatcherService.instance.markRecentlySaved(fullFilePath); + final content = _controller!.text.replaceAll('\r\n', '\n'); + await FileService.instance.saveFile(fullFilePath, content); + if (mounted) { + try { + final provider = _getTabProvider(context); + final tab = provider.activeTab; + if (tab != null) { + tab.content = content; + tab.originalContent = content; + tab.isModified = false; + } + provider.setModified(false); + } catch (_) {} + if (showToast) { + final l10n = AppLocalizations.of(context); + DialogUtils.showSuccessToast(context, l10n?.saveSuccess ?? '保存成功'); + } + } + return true; + } catch (e) { + if (mounted) { + final l10n = AppLocalizations.of(context); + DialogUtils.showErrorToast( + context, + l10n?.saveFailed(e.toString()) ?? '保存失败: $e', + ); + } + return false; + } + } + + void _syncExternalContentIfChanged(TabProvider provider) { + final activeTab = provider.activeTab; + if (activeTab == null || _controller == null || _currentLoadedPath == null) return; + if (!activeTab.isLoaded) return; + // 仅在当前编辑器已经加载了当前激活 tab 的内容时,才响应外部变动。杜绝标签切换过程中的状态混淆! + if (!p.equals(activeTab.path, _currentLoadedPath!)) return; + + // 1. 外部修改冲突处理(本地已修改,外部也发生修改) + if (activeTab.hasExternalConflict && !_isShowingConflictDialog) { + _isShowingConflictDialog = true; + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + final result = await DialogUtils.showFileConflictDialog( + context, + fileName: activeTab.name, + ); + if (!mounted) return; + _isShowingConflictDialog = false; + final reload = result == FileConflictResult.reloadFromDisk; + await provider.resolveConflict(activeTab, reloadFromDisk: reload); + if (reload && mounted && p.equals(activeTab.path, _currentLoadedPath!)) { + _controller?.removeListener(_onTextChanged); + _controller?.text = activeTab.content; + _controller?.addListener(_onTextChanged); + setState(() {}); + } + }); + return; + } + + // 2. 未修改文件外部静默热更新 + if (!activeTab.isModified && activeTab.content != _controller!.text) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || _controller == null || !p.equals(activeTab.path, _currentLoadedPath!)) return; + _controller?.removeListener(_onTextChanged); + _controller?.text = activeTab.content; + _controller?.addListener(_onTextChanged); + setState(() {}); + }); + } + } + @override Widget build(BuildContext context) { + try { + final tabProvider = _getTabProvider(context, listen: true); + _syncExternalContentIfChanged(tabProvider); + } catch (_) {} + + final l10n = AppLocalizations.of(context); final hasNoProject = widget.rootPath == null || widget.rootPath!.trim().isEmpty; final hasNoFile = widget.filePath == null || widget.filePath!.trim().isEmpty; if (hasNoProject && hasNoFile) { return Center( child: Text( - "当前未打开文件目录", + l10n?.noOpenDirectory ?? "当前未打开文件目录", style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ), @@ -83,7 +331,7 @@ class _CodeEditorWidgetState extends State { if (hasNoFile) { return Center( child: Text( - "当前未打开文件", + l10n?.noOpenFile ?? "当前未打开文件", style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ), @@ -91,24 +339,74 @@ class _CodeEditorWidgetState extends State { ); } - // atomOneDark 默认背景色为 0xFF282C34 - const editorBgColor = Color(0xFF282C34); + final controller = _controller; + if (controller == null) { + return const SizedBox.shrink(); + } + + // 获取独立的代码编辑器主题与字号(若处于无 Provider 测试环境则安全降级) + EditorTheme activeTheme = EditorTheme.atomOneDark; + double activeFontSize = 14.0; + bool activeWordWrap = true; + try { + final settings = _getSettingsProvider(context, listen: true); + activeTheme = settings.editorTheme; + activeFontSize = settings.fontSize; + activeWordWrap = settings.wordWrap; + } catch (_) {} return Container( - color: editorBgColor, + color: activeTheme.backgroundColor, width: double.infinity, height: double.infinity, - child: CodeTheme( - data: CodeThemeData(styles: atomOneDarkTheme), - child: SingleChildScrollView( - child: CodeField( - controller: _controller, - gutterStyle: const GutterStyle( - showLineNumbers: true, - showFoldingHandles: true, - ), + 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, + ), + ), + ], + ); + }, ), ); } @@ -120,8 +418,19 @@ class _CodeEditorWidgetState extends State { final hasNoFile = filePath == null || filePath.trim().isEmpty; if (hasNoFile) { - _controller.text = ''; + _currentLoadedPath = null; + _controller?.removeListener(_onTextChanged); + _controller?.dispose(); + _controller = null; if (mounted) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + try { + final provider = _getTabProvider(context); + provider.setModified(false); + provider.registerSaveHandler(null); + } catch (_) {} + }); setState(() { _isLoading = false; _errorMessage = null; @@ -134,36 +443,104 @@ class _CodeEditorWidgetState extends State { ? filePath : p.join(rootPath, filePath); + if (_currentLoadedPath != null && p.equals(_currentLoadedPath!, fullFilePath) && _controller != null) { + return; + } + + final provider = _getTabProvider(context); + final cleanPath = p.normalize(fullFilePath); + final tab = provider.openTabs.where((t) => p.equals(t.path, cleanPath)).firstOrNull; + + // 内存复用极速通道:若标签页已经在内存中,直接同步切换控制器,0毫秒响应,彻底免去 isLoading 转圈与销毁重建 + if (tab != null && tab.isLoaded) { + final oldController = _controller; + oldController?.removeListener(_onTextChanged); + + final normalizedContent = tab.content.replaceAll('\r\n', '\n'); + final normalizedOriginal = tab.originalContent.replaceAll('\r\n', '\n'); + tab.content = normalizedContent; + tab.originalContent = normalizedOriginal; + + final newController = CodeLineEditingController.fromText(normalizedContent); + + _controller = newController; + _currentLoadedPath = fullFilePath; + _errorMessage = null; + _isLoading = false; + + // 必须在 _controller 和 tab 状态准备就绪后再挂载文本监听,避免初始化阶段被误判为脏 + newController.addListener(_onTextChanged); + + oldController?.dispose(); + + _restoreTabScrollState(tab); + + try { + provider.setModified(tab.isModified); + provider.registerSaveHandler(() => _saveFile()); + } catch (_) {} + + if (mounted) { + setState(() {}); + } + return; + } + + // 首次冷加载文件(未在内存中): final int requestVersion = ++_currentLoadVersion; - setState(() { - _isLoading = true; - _errorMessage = null; - }); + // 仅在当前未展示任何代码时才显示 loading,已有代码切换时保持编辑器容器,避免白屏闪烁 + if (_controller == null) { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + } try { - final content = await FileService.instance.readFileContent(fullFilePath); - if(!mounted || requestVersion != _currentLoadVersion) { + final rawDiskContent = await FileService.instance.readFileContent(fullFilePath); + final diskContent = rawDiskContent.replaceAll('\r\n', '\n'); + + if (!mounted || requestVersion != _currentLoadVersion) { return; } - _controller.language = _resolveLanguage(fullFilePath); - _controller.text = content; - }catch(e) { - if(!mounted || requestVersion != _currentLoadVersion) return; - setState(() { - _errorMessage = '$e'; - }); - }finally { - if(mounted && requestVersion == _currentLoadVersion) { + final oldController = _controller; + oldController?.removeListener(_onTextChanged); + + final newController = CodeLineEditingController.fromText(diskContent); + + _controller = newController; + _currentLoadedPath = fullFilePath; + _errorMessage = null; + + if (tab != null) { + tab.content = diskContent; + tab.originalContent = diskContent; + tab.isLoaded = true; + tab.isModified = false; + } + + newController.addListener(_onTextChanged); + oldController?.dispose(); + + if (tab != null) { + _restoreTabScrollState(tab); + } + + if (mounted) { + try { + provider.setModified(tab?.isModified ?? false); + provider.registerSaveHandler(() => _saveFile()); + } catch (_) {} + } + } catch (e) { + if (!mounted || requestVersion != _currentLoadVersion) return; + _errorMessage = '$e'; + } finally { + if (mounted && requestVersion == _currentLoadVersion) { setState(() => _isLoading = false); } } } - - dynamic _resolveLanguage(String path) { - if(path.endsWith('.dart')) return dart; - if(path.endsWith('.json')) return json; - return null; - } } \ No newline at end of file diff --git a/lib/widgets/file_directory_history_widget.dart b/lib/widgets/file_directory_history_widget.dart index ac628de..15d1a28 100644 --- a/lib/widgets/file_directory_history_widget.dart +++ b/lib/widgets/file_directory_history_widget.dart @@ -1,5 +1,7 @@ +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/utils/dialog_utils.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; @@ -56,14 +58,27 @@ class _FileDirectoryHistoryWidgetState Future _deleteHistory(FileDirectoryHistory item) async { final root = item.rootPath; if (root != null && root.isNotEmpty) { - await FileDirectoryHistoryService.instance.removeHistory(root); - await _loadHistory(); + 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); + } + } } } @override Widget build(BuildContext context) { final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; return Dialog( clipBehavior: Clip.antiAlias, @@ -92,19 +107,19 @@ class _FileDirectoryHistoryWidgetState children: [ Expanded( child: Text( - '历史文件目录', + l10n.historyFileDirectories, style: theme.textTheme.titleMedium?.copyWith( fontWeight: FontWeight.bold, - color: theme.colorScheme.onPrimaryContainer, + color: theme.colorScheme.onSurface, ), ), ), IconButton( icon: Icon( Icons.close, - color: theme.colorScheme.onPrimaryContainer, + color: theme.colorScheme.onSurface, ), - tooltip: '关闭', + tooltip: l10n.close, visualDensity: VisualDensity.compact, onPressed: () => Navigator.of(context).pop(), ), @@ -126,7 +141,7 @@ class _FileDirectoryHistoryWidgetState child: Padding( padding: const EdgeInsets.all(32.0), child: Text( - '暂无历史记录', + l10n.noHistory, style: TextStyle( color: theme.colorScheme.onSurfaceVariant, fontSize: 14, @@ -149,8 +164,8 @@ class _FileDirectoryHistoryWidgetState final fileName = (lastFile != null && lastFile.trim().isNotEmpty) ? p.basename(lastFile) - : '未打开文件'; - final rootDir = item.rootPath ?? '未知目录'; + : l10n.noOpenFile; + final rootDir = item.rootPath ?? l10n.unknownDirectory; return InkWell( onTap: () { @@ -210,7 +225,7 @@ class _FileDirectoryHistoryWidgetState size: 20, color: theme.colorScheme.error, ), - tooltip: '删除此记录', + tooltip: l10n.deleteThisHistory, visualDensity: VisualDensity.compact, onPressed: () => _deleteHistory(item), ), diff --git a/lib/widgets/file_item_widget.dart b/lib/widgets/file_item_widget.dart index 1456bf2..750b36f 100644 --- a/lib/widgets/file_item_widget.dart +++ b/lib/widgets/file_item_widget.dart @@ -1,5 +1,9 @@ +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'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; @@ -17,6 +21,24 @@ 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; + } + } + + 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; + } + } + @override Widget build(BuildContext context) { return _buildFileItem(context, widget.fileItem); @@ -24,14 +46,15 @@ class _FileItemWidgetState extends State { Widget _buildFileItem(BuildContext context, FileItem item) { final theme = Theme.of(context); - final provider = context.watch(); + final projectProvider = _getProjectProvider(context, listen: true); + final tabProvider = _getTabProvider(context, listen: true); final indent = EdgeInsets.only(left: item.depth * 16.0 + 8.0, right: 8.0); // 判断该文件是否处于被剪切状态 - final isCut = provider.isItemCut(item.path); + final isCut = projectProvider.isItemCut(item.path); // 判断该文件是否为当前正在编辑/修改的文件 - final isSelected = !item.isDirectory && provider.isFileSelected(item.path); + final isSelected = !item.isDirectory && tabProvider.isFileSelected(item.path); // 文字样式:剪切时变灰,选中时高亮,其余正常 final itemTextStyle = theme.textTheme.bodyMedium?.copyWith( @@ -72,7 +95,7 @@ class _FileItemWidgetState extends State { setState(() { item.isOpen = expanded; }); - context.read().toggleDirectory(item, expanded); + _getProjectProvider(context).toggleDirectory(item, expanded); }, children: item.children .map((child) => FileItemWidget(fileItem: child)) @@ -86,33 +109,36 @@ class _FileItemWidgetState extends State { }, child: Container( margin: const EdgeInsets.symmetric(vertical: 1.0), - decoration: BoxDecoration( - color: isSelected - ? theme.colorScheme.primaryContainer.withValues(alpha: 0.5) - : Colors.transparent, - borderRadius: BorderRadius.circular(8.0), - ), - child: ListTile( - contentPadding: indent, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8.0), + child: Material( + color: Colors.transparent, + child: ListTile( + contentPadding: indent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8.0), + ), + selected: isSelected, + selectedTileColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.5), + leading: Icon( + _getFileIcon(item), + size: 20, + color: iconColor, + ), + title: Text( + item.name, + style: itemTextStyle, + ), + dense: true, + onTap: () { + final scaffold = Scaffold.maybeOf(context); + if (scaffold != null && scaffold.isDrawerOpen) { + scaffold.closeDrawer(); + } + if (tabProvider.isFileSelected(item.path)) { + return; + } + _getTabProvider(context).selectFile(item); + }, ), - selected: isSelected, - selectedTileColor: Colors.transparent, - leading: Icon( - _getFileIcon(item), - size: 20, - color: iconColor, - ), - title: Text( - item.name, - style: itemTextStyle, - ), - dense: true, - onTap: () { - Navigator.of(context).maybePop(); // 关闭 Drawer - context.read().selectFile(item); - }, ), ), ); @@ -125,107 +151,31 @@ class _FileItemWidgetState extends State { return Icons.commit_outlined; } - switch (item.extension) { - case '.dart': - return Icons.flutter_dash; - case '.html': - case '.htm': - return Icons.html; - case '.css': - case '.scss': - case '.sass': - case '.less': - return Icons.css; - case '.js': - case '.mjs': - case '.cjs': - return Icons.javascript; - case '.ts': - case '.tsx': - case '.jsx': - case '.vue': - case '.svelte': - return Icons.code; - case '.json': - return Icons.data_object; - case '.yaml': - case '.yml': - case '.toml': - case '.ini': - case '.env': - case '.conf': - case '.config': - case '.properties': - return Icons.settings_suggest_outlined; - case '.xml': - return Icons.code; - case '.md': - case '.markdown': - return Icons.article_outlined; - case '.pdf': - return Icons.picture_as_pdf_outlined; - case '.py': - case '.pyw': - case '.java': - case '.kt': - case '.kts': - case '.c': - case '.cpp': - case '.cc': - case '.h': - case '.hpp': - case '.cs': - case '.go': - case '.rs': - case '.swift': - case '.rb': - case '.php': - return Icons.code; - case '.sh': - case '.bash': - case '.zsh': - case '.bat': - case '.cmd': - case '.ps1': - return Icons.terminal; - case '.sql': - case '.db': - case '.sqlite': - return Icons.storage_outlined; - case '.png': - case '.jpg': - case '.jpeg': - case '.gif': - case '.webp': - case '.svg': - case '.ico': - case '.bmp': - return Icons.image_outlined; - case '.mp3': - case '.wav': - case '.ogg': - case '.flac': - case '.aac': - return Icons.audio_file_outlined; - case '.mp4': - case '.avi': - case '.mov': - case '.mkv': - case '.flv': - case '.webm': - return Icons.video_file_outlined; - case '.zip': - case '.rar': - case '.7z': - case '.tar': - case '.gz': - return Icons.folder_zip_outlined; - case '.lock': - return Icons.lock_outline; - case '.txt': - default: - return Icons.description_outlined; - } + return switch (item.extension) { + '.dart' => Icons.flutter_dash, + '.html' || '.htm' => Icons.html, + '.css' || '.scss' || '.sass' || '.less' => Icons.css, + '.js' || '.mjs' || '.cjs' => Icons.javascript, + '.ts' || '.tsx' || '.jsx' || '.vue' || '.svelte' => Icons.code, + '.json' => Icons.data_object, + '.yaml' || '.yml' || '.toml' || '.ini' || '.env' || '.conf' || '.config' || '.properties' => + Icons.settings_suggest_outlined, + '.xml' => Icons.code, + '.md' || '.markdown' => Icons.article_outlined, + '.pdf' => Icons.picture_as_pdf_outlined, + '.py' || '.pyw' || '.java' || '.kt' || '.kts' || '.c' || '.cpp' || '.cc' || + '.h' || '.hpp' || '.cs' || '.go' || '.rs' || '.swift' || '.rb' || '.php' => + Icons.code, + '.sh' || '.bash' || '.zsh' || '.bat' || '.cmd' || '.ps1' => Icons.terminal, + '.sql' || '.db' || '.sqlite' => Icons.storage_outlined, + '.png' || '.jpg' || '.jpeg' || '.gif' || '.webp' || '.svg' || '.ico' || '.bmp' => + Icons.image_outlined, + '.mp3' || '.wav' || '.ogg' || '.flac' || '.aac' => Icons.audio_file_outlined, + '.mp4' || '.avi' || '.mov' || '.mkv' || '.flv' || '.webm' => Icons.video_file_outlined, + '.zip' || '.rar' || '.7z' || '.tar' || '.gz' => Icons.folder_zip_outlined, + '.lock' => Icons.lock_outline, + _ => Icons.description_outlined, + }; } void _showContextMenu(FileItem item, Offset tapPosition) async { @@ -236,17 +186,28 @@ class _FileItemWidgetState extends State { ); final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); final onSurfaceColor = theme.colorScheme.onSurface; - final canPaste = context.read().canPaste; + final canPaste = _getProjectProvider(context).canPaste; final menuItems = >[]; + final strNewFile = l10n?.newFile ?? '新建文件'; + final strNewFolder = l10n?.newFolder ?? '新建文件夹'; + final strCut = l10n?.cut ?? '剪切'; + final strCopy = l10n?.copy ?? '复制'; + final strPaste = l10n?.paste ?? '粘贴'; + final strCopyPath = l10n?.copyPath ?? '复制路径'; + final strCopyRelativePath = l10n?.copyRelativePath ?? '复制相对路径'; + final strRename = l10n?.rename ?? '重命名'; + final strDelete = l10n?.delete ?? '删除'; + if (item.isDirectory) { menuItems.addAll([ - _buildMenuItem('new_file', Icons.note_add_outlined, '新建文件', onSurfaceColor), - _buildMenuItem('new_folder', Icons.create_new_folder_outlined, '新建文件夹', onSurfaceColor), + _buildMenuItem('new_file', Icons.note_add_outlined, strNewFile, onSurfaceColor), + _buildMenuItem('new_folder', Icons.create_new_folder_outlined, strNewFolder, onSurfaceColor), const PopupMenuDivider(), - _buildMenuItem('cut', Icons.content_cut, '剪切', onSurfaceColor), - _buildMenuItem('copy', Icons.copy, '复制', onSurfaceColor), + _buildMenuItem('cut', Icons.content_cut, strCut, onSurfaceColor), + _buildMenuItem('copy', Icons.copy, strCopy, onSurfaceColor), PopupMenuItem( value: 'paste', enabled: canPaste, @@ -261,7 +222,7 @@ class _FileItemWidgetState extends State { ), const SizedBox(width: 8), Text( - '粘贴', + strPaste, style: TextStyle( color: canPaste ? onSurfaceColor @@ -272,31 +233,31 @@ class _FileItemWidgetState extends State { ), ), const PopupMenuDivider(), - _buildMenuItem('copy_path', Icons.link, '复制路径', onSurfaceColor), - _buildMenuItem('copy_relative_path', Icons.short_text, '复制相对路径', onSurfaceColor), + _buildMenuItem('copy_path', Icons.link, strCopyPath, onSurfaceColor), + _buildMenuItem('copy_relative_path', Icons.short_text, strCopyRelativePath, onSurfaceColor), const PopupMenuDivider(), - _buildMenuItem('rename', Icons.edit_outlined, '重命名', onSurfaceColor), + _buildMenuItem('rename', Icons.edit_outlined, strRename, onSurfaceColor), _buildMenuItem( 'delete', Icons.delete_outline, - '删除', + strDelete, theme.colorScheme.error, isDestructive: true, ), ]); } else { menuItems.addAll([ - _buildMenuItem('cut', Icons.content_cut, '剪切', onSurfaceColor), - _buildMenuItem('copy', Icons.copy, '复制', onSurfaceColor), + _buildMenuItem('cut', Icons.content_cut, strCut, onSurfaceColor), + _buildMenuItem('copy', Icons.copy, strCopy, onSurfaceColor), const PopupMenuDivider(), - _buildMenuItem('copy_path', Icons.link, '复制路径', onSurfaceColor), - _buildMenuItem('copy_relative_path', Icons.short_text, '复制相对路径', onSurfaceColor), + _buildMenuItem('copy_path', Icons.link, strCopyPath, onSurfaceColor), + _buildMenuItem('copy_relative_path', Icons.short_text, strCopyRelativePath, onSurfaceColor), const PopupMenuDivider(), - _buildMenuItem('rename', Icons.edit_outlined, '重命名', onSurfaceColor), + _buildMenuItem('rename', Icons.edit_outlined, strRename, onSurfaceColor), _buildMenuItem( 'delete', Icons.delete_outline, - '删除', + strDelete, theme.colorScheme.error, isDestructive: true, ), @@ -350,247 +311,103 @@ class _FileItemWidgetState extends State { } void _handleMenuAction(FileItem item, String action) async { - final provider = context.read(); + final provider = _getProjectProvider(context); + final l10n = AppLocalizations.of(context); + switch (action) { case 'new_file': - await _showCreateInputDialog( - title: '新建文件', - hintText: '文件名 (例如: main.dart)', - onConfirm: (name) async { - await provider.createFile(item.path, name); - }, + final name = await DialogUtils.showInputDialog( + context, + title: l10n?.newFile ?? '新建文件', + hintText: l10n?.fileNameHint ?? '文件名 (例如: main.dart)', ); + if (name != null && name.trim().isNotEmpty) { + try { + await provider.createFile(item.path, name.trim()); + } catch (e) { + if (mounted) DialogUtils.showErrorToast(context, l10n?.createFileFailed(e.toString()) ?? '创建文件失败: $e'); + } + } break; case 'new_folder': - await _showCreateInputDialog( - title: '新建文件夹', - hintText: '文件夹名', - onConfirm: (name) async { - await provider.createDirectory(item.path, name); - }, + final name = await DialogUtils.showInputDialog( + context, + title: l10n?.newFolder ?? '新建文件夹', + hintText: l10n?.folderNameHint ?? '文件夹名', ); + if (name != null && name.trim().isNotEmpty) { + try { + await provider.createDirectory(item.path, name.trim()); + } catch (e) { + if (mounted) DialogUtils.showErrorToast(context, l10n?.createFolderFailed(e.toString()) ?? '创建文件夹失败: $e'); + } + } break; case 'cut': provider.cut(item); - if (mounted) _showToast(context, '已剪切: ${item.name}'); + if (mounted) DialogUtils.showInfoToast(context, l10n?.cutItem(item.name) ?? '已剪切: ${item.name}'); break; case 'copy': provider.copy(item); - if (mounted) _showToast(context, '已复制: ${item.name}'); + if (mounted) DialogUtils.showInfoToast(context, l10n?.copiedItem(item.name) ?? '已复制: ${item.name}'); break; case 'paste': try { await provider.paste(item); - if (mounted) _showToast(context, '操作成功'); + if (mounted) DialogUtils.showSuccessToast(context, l10n?.operationSuccess ?? '操作成功'); } catch (e) { - if (mounted) _showToast(context, '操作失败: $e', isError: true); + if (mounted) DialogUtils.showErrorToast(context, l10n?.operationFailed(e.toString()) ?? '操作失败: $e'); } break; case 'copy_path': await Clipboard.setData(ClipboardData(text: item.fullPath)); if (mounted) { - _showToast(context, '已复制完整路径到剪贴板'); + DialogUtils.showSuccessToast(context, l10n?.copiedPathToClipboard ?? '已复制完整路径到剪贴板'); } break; case 'copy_relative_path': await Clipboard.setData(ClipboardData(text: item.getRelativePath(provider.rootPath))); if (mounted) { - _showToast(context, '已复制相对路径到剪贴板'); + DialogUtils.showSuccessToast(context, l10n?.copiedRelativePathToClipboard ?? '已复制相对路径到剪贴板'); } break; case 'rename': - await _showCreateInputDialog( - title: '重命名', - hintText: '新名称', + final newName = await DialogUtils.showInputDialog( + context, + title: l10n?.rename ?? '重命名', + hintText: l10n?.newName ?? '新名称', initialValue: item.name, - onConfirm: (newName) async { - if (newName.trim() == item.name) return; - await provider.rename(item, newName.trim()); - }, ); + if (newName != null && newName.trim().isNotEmpty && newName.trim() != item.name) { + try { + await provider.rename(item, newName.trim()); + } catch (e) { + if (mounted) DialogUtils.showErrorToast(context, l10n?.renameFailed(e.toString()) ?? '重命名失败: $e'); + } + } break; case 'delete': - final confirmed = await _showConfirmDialog( - title: '确认删除', - content: '确定要删除 "${item.name}" 吗?此操作不可恢复。', + final confirmed = await DialogUtils.showDestructiveConfirmDialog( + context, + title: l10n?.confirmDelete ?? '确认删除', + message: l10n?.confirmDeleteMessage(item.name) ?? '确定要删除 "${item.name}" 吗?此操作不可恢复。', ); - if (confirmed == true && mounted) { - await provider.delete(item); + if (confirmed && mounted) { + try { + await provider.delete(item); + } catch (e) { + if (mounted) DialogUtils.showErrorToast(context, l10n?.deleteFailed(e.toString()) ?? '删除失败: $e'); + } } break; } } - - void _showToast(BuildContext context, String message, {bool isError = false}) { - final overlay = Overlay.of(context, rootOverlay: true); - final theme = Theme.of(context); - - late OverlayEntry entry; - entry = OverlayEntry( - builder: (ctx) => Positioned( - bottom: 48, - left: 0, - right: 0, - child: Center( - child: Material( - color: Colors.transparent, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), - decoration: BoxDecoration( - color: isError - ? theme.colorScheme.errorContainer - : theme.colorScheme.inverseSurface, - borderRadius: BorderRadius.circular(12), - border: Border.all( - color: isError - ? theme.colorScheme.error - : theme.colorScheme.outlineVariant, - width: 1, - ), - boxShadow: const [ - BoxShadow( - color: Colors.black26, - blurRadius: 10, - offset: Offset(0, 4), - ), - ], - ), - child: Text( - message, - style: theme.textTheme.bodyMedium?.copyWith( - color: isError - ? theme.colorScheme.onErrorContainer - : theme.colorScheme.onInverseSurface, - fontWeight: FontWeight.w500, - ), - ), - ), - ), - ), - ), - ); - - overlay.insert(entry); - Future.delayed(const Duration(seconds: 2), () { - if (entry.mounted) { - entry.remove(); - } - }); - } - - Future _showCreateInputDialog({ - required String title, - required String hintText, - String? initialValue, - required Future Function(String value) onConfirm, - }) async { - final controller = TextEditingController(text: initialValue); - final formKey = GlobalKey(); - - final theme = Theme.of(context); - - await showDialog( - context: context, - builder: (dialogContext) { - return AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16.0), - side: BorderSide( - color: theme.colorScheme.outlineVariant, - width: 1.0, - ), - ), - title: Text(title), - content: Form( - key: formKey, - child: TextFormField( - controller: controller, - autofocus: true, - decoration: InputDecoration( - hintText: hintText, - border: const OutlineInputBorder(), - ), - validator: (val) { - if (val == null || val.trim().isEmpty) { - return '名称不能为空'; - } - if (val.contains(RegExp(r'[\\/:*?"<>|]'))) { - return '名称不能包含非法字符 (\\/:*?"<>|)'; - } - return null; - }, - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.of(dialogContext).pop(), - child: const Text('取消'), - ), - FilledButton( - onPressed: () async { - if (formKey.currentState?.validate() ?? false) { - final inputVal = controller.text; - Navigator.of(dialogContext).pop(); - try { - await onConfirm(inputVal); - } catch (e) { - if (mounted) { - _showToast(context, '操作失败: $e', isError: true); - } - } - } - }, - child: const Text('确定'), - ), - ], - ); - }, - ); - } - - Future _showConfirmDialog({ - required String title, - required String content, - }) { - final theme = Theme.of(context); - return showDialog( - context: context, - builder: (dialogContext) { - return AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16.0), - side: BorderSide( - color: theme.colorScheme.outlineVariant, - width: 1.0, - ), - ), - title: Text(title), - content: Text(content), - actions: [ - TextButton( - onPressed: () => Navigator.of(dialogContext).pop(false), - child: const Text('取消'), - ), - FilledButton( - style: FilledButton.styleFrom( - backgroundColor: theme.colorScheme.error, - foregroundColor: theme.colorScheme.onError, - ), - onPressed: () => Navigator.of(dialogContext).pop(true), - child: const Text('删除'), - ), - ], - ); - }, - ); - } } - diff --git a/lib/widgets/file_tree_widget.dart b/lib/widgets/file_tree_widget.dart index efc85f3..3d5d7b2 100644 --- a/lib/widgets/file_tree_widget.dart +++ b/lib/widgets/file_tree_widget.dart @@ -1,5 +1,5 @@ -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/widgets/file_item_widget.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -7,11 +7,20 @@ import 'package:provider/provider.dart'; class FileTreeWidget extends StatelessWidget { const FileTreeWidget({super.key}); + static ProjectProvider _getProjectProvider(BuildContext context) { + try { + return context.watch(); + } catch (_) { + return context.watch().projectProvider; + } + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); - final rootPath = context.select((p) => p.rootPath); - final items = context.select>((p) => p.items); + final projectProvider = _getProjectProvider(context); + final rootPath = projectProvider.rootPath; + final items = projectProvider.items; // 1. 如果用户还没有打开/选择任何根目录 if (rootPath == null || rootPath.trim().isEmpty) { diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index f6f23bf..e71a16d 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,10 +6,6 @@ #include "generated_plugin_registrant.h" -#include void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); - url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index f16b4c3..2e1de87 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,7 +3,6 @@ # list(APPEND FLUTTER_PLUGIN_LIST - url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index ef89af8..438e7e5 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -7,10 +7,8 @@ import Foundation import file_picker import shared_preferences_foundation -import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) - UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) } diff --git a/pubspec.lock b/pubspec.lock index 7eb8940..0d6895f 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -9,14 +9,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.0" - autotrie: - dependency: transitive - description: - name: autotrie - sha256: "55da6faefb53cfcb0abb2f2ca8636123fb40e35286bb57440d2cf467568188f8" - url: "https://pub.dev" - source: hosted - version: "2.0.0" boolean_selector: dependency: transitive description: @@ -33,14 +25,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" - charcode: - dependency: transitive - description: - name: charcode - sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a - url: "https://pub.dev" - source: hosted - version: "1.4.0" clock: dependency: transitive description: @@ -65,14 +49,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.3.5+5" - crypto: - dependency: transitive - description: - name: crypto - sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf - url: "https://pub.dev" - source: hosted - version: "3.0.7" cupertino_icons: dependency: "direct main" description: @@ -81,14 +57,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" - equatable: - dependency: transitive - description: - name: equatable - sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" - url: "https://pub.dev" - source: hosted - version: "2.1.0" fake_async: dependency: transitive description: @@ -126,22 +94,6 @@ packages: description: flutter source: sdk version: "0.0.0" - flutter_code_editor: - dependency: "direct main" - description: - name: flutter_code_editor - sha256: "9af48ba8e3558b6ea4bb98b84c5eb1649702acf53e61a84d88383eeb79b239b0" - url: "https://pub.dev" - source: hosted - version: "0.3.5" - flutter_highlight: - dependency: "direct main" - description: - name: flutter_highlight - sha256: "7b96333867aa07e122e245c033b8ad622e4e3a42a1a2372cbb098a2541d8782c" - url: "https://pub.dev" - source: hosted - version: "0.7.0" flutter_lints: dependency: "direct dev" description: @@ -173,38 +125,6 @@ packages: description: flutter source: sdk version: "0.0.0" - highlight: - dependency: "direct main" - description: - name: highlight - sha256: "5353a83ffe3e3eca7df0abfb72dcf3fa66cc56b953728e7113ad4ad88497cf21" - url: "https://pub.dev" - source: hosted - version: "0.7.0" - hive: - dependency: transitive - description: - name: hive - sha256: "8dcf6db979d7933da8217edcec84e9df1bdb4e4edc7fc77dbd5aa74356d6d941" - url: "https://pub.dev" - source: hosted - version: "2.2.3" - http: - dependency: transitive - description: - name: http - sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" - url: "https://pub.dev" - source: hosted - version: "1.6.0" - http_parser: - dependency: transitive - description: - name: http_parser - sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" - url: "https://pub.dev" - source: hosted - version: "4.1.2" intl: dependency: "direct main" description: @@ -213,6 +133,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.20.3" + isolate_contactor: + dependency: transitive + description: + name: isolate_contactor + sha256: "6ba8434ceb58238a1389d6365111a3efe7baa1c68a66f4db6d63d351cf6c3a0f" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + isolate_manager: + dependency: transitive + description: + name: isolate_manager + sha256: "22ed0c25f80ec3b5f21e3a55d060f4650afff33f27c2dff34c0f9409d5759ae5" + url: "https://pub.dev" + source: hosted + version: "4.1.5+1" leak_tracker: dependency: transitive description: @@ -237,14 +173,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.2" - linked_scroll_controller: - dependency: transitive - description: - name: linked_scroll_controller - sha256: e6020062bcf4ffc907ee7fd090fa971e65d8dfaac3c62baf601a3ced0b37986a - url: "https://pub.dev" - source: hosted - version: "0.2.0" lints: dependency: transitive description: @@ -277,14 +205,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.0" - mocktail: - dependency: transitive - description: - name: mocktail - sha256: "5e1bf53cc7baa8062a33b84424deb61513858ea05c601b8509e683815b5914aa" - url: "https://pub.dev" - source: hosted - version: "1.0.5" nested: dependency: transitive description: @@ -349,14 +269,22 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.5+1" - scrollable_positioned_list: - dependency: transitive + re_editor: + dependency: "direct main" description: - name: scrollable_positioned_list - sha256: "1b54d5f1329a1e263269abc9e2543d90806131aa14fe7c6062a8054d57249287" + name: re_editor + sha256: "66671c4774a6b4c5254c9a53ab35a083e7e7da9ae371c519bcf491c70a2a4e56" url: "https://pub.dev" source: hosted - version: "0.3.8" + version: "0.10.0" + re_highlight: + dependency: "direct main" + description: + name: re_highlight + sha256: "6c4ac3f76f939fb7ca9df013df98526634e17d8f7460e028bd23a035870024f2" + url: "https://pub.dev" + source: hosted + version: "0.0.3" shared_preferences: dependency: "direct main" description: @@ -466,86 +394,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.12" - tuple: - dependency: transitive - description: - name: tuple - sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151 - url: "https://pub.dev" - source: hosted - version: "2.0.2" - typed_data: - dependency: transitive - description: - name: typed_data - sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 - url: "https://pub.dev" - source: hosted - version: "1.4.0" - url_launcher: - dependency: transitive - description: - name: url_launcher - sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 - url: "https://pub.dev" - source: hosted - version: "6.3.2" - url_launcher_android: - dependency: transitive - description: - name: url_launcher_android - sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" - url: "https://pub.dev" - source: hosted - version: "6.3.33" - url_launcher_ios: - dependency: transitive - description: - name: url_launcher_ios - sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" - url: "https://pub.dev" - source: hosted - version: "6.4.2" - url_launcher_linux: - dependency: transitive - description: - name: url_launcher_linux - sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" - url: "https://pub.dev" - source: hosted - version: "3.2.3" - url_launcher_macos: - dependency: transitive - description: - name: url_launcher_macos - sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" - url: "https://pub.dev" - source: hosted - version: "3.2.6" - url_launcher_platform_interface: - dependency: transitive - description: - name: url_launcher_platform_interface - sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" - url: "https://pub.dev" - source: hosted - version: "2.3.2" - url_launcher_web: - dependency: transitive - description: - name: url_launcher_web - sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" - url: "https://pub.dev" - source: hosted - version: "2.4.3" - url_launcher_windows: - dependency: transitive - description: - name: url_launcher_windows - sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" - url: "https://pub.dev" - source: hosted - version: "3.1.6" vector_math: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 99724dc..f32c8ff 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -17,13 +17,12 @@ dependencies: intl: any cupertino_icons: ^1.0.8 - flutter_code_editor: ^0.3.1 - flutter_highlight: ^0.7.0 - highlight: ^0.7.0 shared_preferences: ^2.3.0 path: ^1.9.0 file_picker: ^8.1.7 provider: ^6.1.2 + re_editor: ^0.10.0 + re_highlight: ^0.0.3 dev_dependencies: flutter_test: diff --git a/test/dialog_utils_test.dart b/test/dialog_utils_test.dart new file mode 100644 index 0000000..e359b9a --- /dev/null +++ b/test/dialog_utils_test.dart @@ -0,0 +1,299 @@ +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('DialogUtils Tests', () { + testWidgets('shows toast on overlay without errors', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () { + DialogUtils.showToast(context, 'Test Toast'); + DialogUtils.showSuccessToast(context, 'Success Toast'); + DialogUtils.showErrorToast(context, 'Error Toast'); + DialogUtils.showWarningToast(context, 'Warning Toast'); + DialogUtils.showInfoToast(context, 'Info Toast'); + }, + child: const Text('Trigger Toast'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('Trigger Toast')); + await tester.pump(); + + expect(find.text('Test Toast'), findsOneWidget); + expect(find.text('Success Toast'), findsOneWidget); + expect(find.text('Error Toast'), findsOneWidget); + expect(find.text('Warning Toast'), findsOneWidget); + expect(find.text('Info Toast'), findsOneWidget); + + // 等待 toast 定时器执行完毕并移除 + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('shows info dialog and closes on button click', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () { + DialogUtils.showInfoDialog( + context, + title: '信息提示', + message: '这是信息内容', + ); + }, + child: const Text('Open Info Dialog'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('Open Info Dialog')); + await tester.pumpAndSettle(); + + expect(find.text('信息提示'), findsOneWidget); + expect(find.text('这是信息内容'), findsOneWidget); + expect(find.text('确定'), findsOneWidget); + + await tester.tap(find.text('确定')); + await tester.pumpAndSettle(); + + expect(find.text('信息提示'), findsNothing); + }); + + testWidgets('shows warning dialog and error dialog', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () { + DialogUtils.showWarningDialog( + context, + title: '警告提示', + message: '这是警告内容', + ); + }, + child: const Text('Open Warning Dialog'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('Open Warning Dialog')); + await tester.pumpAndSettle(); + + expect(find.text('警告提示'), findsOneWidget); + expect(find.text('这是警告内容'), findsOneWidget); + expect(find.text('知道了'), findsOneWidget); + + await tester.tap(find.text('知道了')); + await tester.pumpAndSettle(); + + expect(find.text('警告提示'), findsNothing); + }); + + testWidgets('shows normal confirm dialog returning true on confirm and false on cancel', + (WidgetTester tester) async { + bool? confirmResult; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return Column( + children: [ + ElevatedButton( + onPressed: () async { + confirmResult = await DialogUtils.showConfirmDialog( + context, + title: '普通确认', + message: '确认要执行此操作吗?', + ); + }, + child: const Text('Open Confirm'), + ), + ], + ); + }, + ), + ), + ), + ); + + // 1. 测试点击取消 + await tester.tap(find.text('Open Confirm')); + await tester.pumpAndSettle(); + + expect(find.text('普通确认'), findsOneWidget); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + + expect(confirmResult, false); + + // 2. 测试点击确定 + await tester.tap(find.text('Open Confirm')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('确定')); + await tester.pumpAndSettle(); + + expect(confirmResult, true); + }); + + testWidgets('shows destructive confirm dialog with error styling and delete action', + (WidgetTester tester) async { + bool? confirmResult; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () async { + confirmResult = await DialogUtils.showDestructiveConfirmDialog( + context, + title: '确认删除', + message: '删除后无法恢复!', + confirmText: '永久删除', + ); + }, + child: const Text('Open Delete Dialog'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('Open Delete Dialog')); + await tester.pumpAndSettle(); + + expect(find.text('确认删除'), findsOneWidget); + expect(find.text('永久删除'), findsOneWidget); + + await tester.tap(find.text('永久删除')); + await tester.pumpAndSettle(); + + expect(confirmResult, true); + }); + + testWidgets('shows input dialog with validation and returns value', + (WidgetTester tester) async { + String? enteredValue; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () async { + enteredValue = await DialogUtils.showInputDialog( + context, + title: '新建文件', + hintText: '请输入文件名', + initialValue: 'init.dart', + ); + }, + child: const Text('Open Input Dialog'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('Open Input Dialog')); + await tester.pumpAndSettle(); + + expect(find.text('新建文件'), findsOneWidget); + expect(find.text('init.dart'), findsOneWidget); + + // 1. 输入非法字符并校验 + await tester.enterText(find.byType(TextFormField), 'bad/name'); + await tester.tap(find.text('确定')); + await tester.pumpAndSettle(); + + expect(find.text('名称不能包含非法字符 (\\/:*?"<>|)'), findsOneWidget); + + // 2. 输入合法字符并确定 + await tester.enterText(find.byType(TextFormField), 'good_name.dart'); + await tester.tap(find.text('确定')); + await tester.pumpAndSettle(); + + expect(enteredValue, 'good_name.dart'); + }); + + testWidgets('shows save prompt dialog and handles save, discard, cancel', + (WidgetTester tester) async { + SavePromptResult? promptResult; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () async { + promptResult = await DialogUtils.showSavePromptDialog( + context, + fileName: 'main.dart', + ); + }, + child: const Text('Open Save Prompt'), + ); + }, + ), + ), + ), + ); + + // 1. Test Cancel + await tester.tap(find.text('Open Save Prompt')); + await tester.pumpAndSettle(); + + expect(find.text('保存更改'), findsOneWidget); + expect(find.text('文件 "main.dart" 已被修改,是否保存更改?'), findsOneWidget); + expect(find.text('保存'), findsOneWidget); + expect(find.text('不保存'), findsOneWidget); + expect(find.text('取消'), findsOneWidget); + + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(promptResult, equals(SavePromptResult.cancel)); + + // 2. Test Discard + await tester.tap(find.text('Open Save Prompt')); + await tester.pumpAndSettle(); + await tester.tap(find.text('不保存')); + await tester.pumpAndSettle(); + expect(promptResult, equals(SavePromptResult.discard)); + + // 3. Test Save + await tester.tap(find.text('Open Save Prompt')); + await tester.pumpAndSettle(); + await tester.tap(find.text('保存')); + await tester.pumpAndSettle(); + expect(promptResult, equals(SavePromptResult.save)); + }); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart index dd95d61..f36b1b1 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,5 +1,12 @@ +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/providers/project_provider.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.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'; import 'package:flutter/material.dart'; @@ -7,9 +14,55 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; +import 'package:code_editor/l10n/app_localizations.dart'; 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/services/file_watcher_service.dart'; +import 'package:code_editor/utils/syntax_highlight_helper.dart'; +import 'package:shared_preferences/shared_preferences.dart'; void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + test('SyntaxHighlightHelper maps file extensions and names to correct language IDs', () { + expect(SyntaxHighlightHelper.getLanguageId('main.dart'), 'dart'); + expect(SyntaxHighlightHelper.getLanguageId('app.json'), 'json'); + expect(SyntaxHighlightHelper.getLanguageId('intl_zh.arb'), 'json'); + expect(SyntaxHighlightHelper.getLanguageId('script.js'), 'javascript'); + expect(SyntaxHighlightHelper.getLanguageId('app.ts'), 'typescript'); + expect(SyntaxHighlightHelper.getLanguageId('index.html'), 'xml'); + expect(SyntaxHighlightHelper.getLanguageId('style.css'), 'css'); + expect(SyntaxHighlightHelper.getLanguageId('pubspec.yaml'), 'yaml'); + expect(SyntaxHighlightHelper.getLanguageId('README.md'), 'markdown'); + expect(SyntaxHighlightHelper.getLanguageId('main.py'), 'python'); + expect(SyntaxHighlightHelper.getLanguageId('Dockerfile'), 'dockerfile'); + expect(SyntaxHighlightHelper.getLanguageId('Makefile'), 'makefile'); + expect(SyntaxHighlightHelper.getLanguageId('code_editor.iml'), 'xml'); + expect(SyntaxHighlightHelper.getLanguageId('unknown.xyz'), isNull); + expect(SyntaxHighlightHelper.getLanguageId(null), isNull); + + // Verify all resolved languages exist in builtinAllLanguages + final dartLanguages = SyntaxHighlightHelper.getLanguagesForFile('main.dart'); + expect(dartLanguages.keys, ['dart']); + expect(dartLanguages['dart'], isNotNull); + + final imlLanguages = SyntaxHighlightHelper.getLanguagesForFile('code_editor.iml'); + expect(imlLanguages.keys, ['xml']); + expect(imlLanguages['xml'], isNotNull); + + // Cache verification + final dartLanguages2 = SyntaxHighlightHelper.getLanguagesForFile('test.dart'); + expect(identical(dartLanguages['dart'], dartLanguages2['dart']), isTrue); + + // Plain text returns empty map without loading 194 languages + expect(SyntaxHighlightHelper.getLanguagesForFile('notes.txt'), isEmpty); + }); + + testWidgets('App loads smoke test', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); await tester.pump(const Duration(milliseconds: 100)); @@ -160,8 +213,794 @@ void main() { expect(dirItem.extension, equals('')); expect(dirItem.nameWithoutExtension, equals('lib')); }); + + testWidgets('CodeEditorAppBar uses onSurface foregroundColor and position under', (WidgetTester tester) async { + bool settingsOpened = false; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), + ), + home: Scaffold( + appBar: CodeEditorAppBar( + filePath: '/workspace/main.dart', + onSettings: () => settingsOpened = true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final appBarFinder = find.byType(AppBar); + expect(appBarFinder, findsOneWidget); + final appBar = tester.widget(appBarFinder); + expect(appBar.foregroundColor, isNotNull); + + // Verify PopupMenuButton has position under + final popupBtnFinder = find.byType(PopupMenuButton); + expect(popupBtnFinder, findsOneWidget); + final popupBtn = tester.widget>(popupBtnFinder); + expect(popupBtn.position, equals(PopupMenuPosition.under)); + + // Tap menu button + await tester.tap(popupBtnFinder); + await tester.pumpAndSettle(); + + expect(find.text('设置'), findsOneWidget); + await tester.tap(find.text('设置')); + await tester.pumpAndSettle(); + expect(settingsOpened, isTrue); + }); + + testWidgets('SettingsView renders word wrap switch and language options', (WidgetTester tester) async { + final provider = EditorProvider(); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: provider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const SettingsView(), + ), + ), + ); + await tester.pumpAndSettle(); + + // Verify word wrap switch tile exists + expect(find.text('自动换行'), findsOneWidget); + final switchFinder = find.byType(Switch); + expect(switchFinder, findsOneWidget); + expect(provider.wordWrap, isTrue); + + // Toggle word wrap + await tester.tap(switchFinder); + await tester.pumpAndSettle(); + expect(provider.wordWrap, isFalse); + + // Verify language section + expect(find.text('应用语言'), findsOneWidget); + expect(find.text('跟随系统'), findsWidgets); + + // Tap language tile to open modal + await tester.tap(find.text('应用语言')); + await tester.pumpAndSettle(); + + expect(find.text('选择应用语言'), findsOneWidget); + expect(find.text('English'), findsOneWidget); + + // Select English + await tester.tap(find.text('English')); + await tester.pumpAndSettle(); + + expect(provider.locale, equals(const Locale('en'))); + }); + + testWidgets('EditorProvider wordWrap and locale can be updated', (WidgetTester tester) async { + final provider = EditorProvider(); + + expect(provider.wordWrap, isTrue); + await provider.setWordWrap(false); + expect(provider.wordWrap, isFalse); + + expect(provider.locale, isNull); + await provider.setLocale(const Locale('en')); + expect(provider.locale, equals(const Locale('en'))); + await provider.setLocale(null); + expect(provider.locale, isNull); + }); + + testWidgets('SettingsView font size dialog allows maximum 30 without assertion error', (WidgetTester tester) async { + final provider = EditorProvider(); + await provider.setFontSize(30.0); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: provider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const SettingsView(), + ), + ), + ); + await tester.pumpAndSettle(); + + // Tap font size tile to open dialog with initial value 30.0 + expect(find.text('30'), findsWidgets); + await tester.tap(find.text('代码字号缩放')); + await tester.pumpAndSettle(); + + // Dialog should be open without throwing Slider assertion error + expect(find.byType(Slider), findsOneWidget); + final slider = tester.widget(find.byType(Slider)); + expect(slider.max, equals(30.0)); + expect(slider.value, equals(30.0)); + + // Tap done button + await tester.tap(find.text('完成')); + await tester.pumpAndSettle(); + }); + + testWidgets('CodeEditorAppBar displays asterisk when isModified is true', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const Scaffold( + appBar: CodeEditorAppBar( + filePath: '/workspace/main.dart', + isModified: false, + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('main.dart'), findsOneWidget); + expect(find.text('* main.dart'), findsNothing); + + // Rebuild with isModified = true + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const Scaffold( + appBar: CodeEditorAppBar( + filePath: '/workspace/main.dart', + isModified: true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + 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); + expect(provider.isModified, isTrue); + + bool saveCalled = false; + provider.registerSaveHandler(() async { + saveCalled = true; + return true; + }); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () async { + final proceed = await provider.checkUnsavedChanges(context); + expect(proceed, isTrue); + }, + child: const Text('Check'), + ); + }, + ), + ), + ); + + // Tap button to trigger checkUnsavedChanges + await tester.tap(find.text('Check')); + await tester.pumpAndSettle(); + + // Dialog should be displayed for saving all files in project + expect(find.text('保存所有更改?'), findsOneWidget); + expect(find.text('当前项目中有未保存的修改,是否保存所有文件?'), findsOneWidget); + + // Tap Save All + await tester.tap(find.text('保存所有')); + await tester.pumpAndSettle(); + + expect(saveCalled, isTrue); + + // Advance timer to let toast disappear + await tester.pump(const Duration(seconds: 3)); + }); + + 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); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: provider, + child: MaterialApp( + home: Scaffold( + body: FileItemWidget(fileItem: fileItem), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('main.dart'), findsOneWidget); + expect(find.text('* main.dart'), findsNothing); + }); + + test('EditorTabItem disambiguates duplicate file names with relative path', () { + final tab1 = EditorTabItem(path: p.normalize('/workspace/lib/widgets/app_bar.dart')); + final tab2 = EditorTabItem(path: p.normalize('/workspace/lib/views/app_bar.dart')); + final tab3 = EditorTabItem(path: p.normalize('/workspace/lib/main.dart')); + final tabs = [tab1, tab2, tab3]; + + final root = p.normalize('/workspace'); + + // Duplicate names display relative path + expect(tab1.getDisplayName(tabs, root), equals(p.normalize('lib/widgets/app_bar.dart'))); + expect(tab2.getDisplayName(tabs, root), equals(p.normalize('lib/views/app_bar.dart'))); + + // Unique name displays plain filename + expect(tab3.getDisplayName(tabs, root), equals('main.dart')); + + // Formatted title with dirty marker + tab3.isModified = true; + expect(tab3.getFormattedTitle(tabs, root), equals('* main.dart')); + }); + + testWidgets('CodeEditorAppBar displays primary title, subtitle, and save all action', (WidgetTester tester) async { + bool saveAllTriggered = false; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + appBar: CodeEditorAppBar( + filePath: p.normalize('/workspace/main.dart'), + rootPath: p.normalize('/workspace'), + isModified: false, + onSaveAll: () => saveAllTriggered = true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Primary title: main.dart, Subtitle: / + expect(find.text('main.dart'), findsOneWidget); + expect(find.text('/'), findsOneWidget); + + // Rebuild with subfolder file + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + appBar: CodeEditorAppBar( + filePath: p.normalize('/workspace/lib/views/home.dart'), + rootPath: p.normalize('/workspace'), + isModified: true, + onSaveAll: () => saveAllTriggered = true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('* home.dart'), findsOneWidget); + expect(find.text('/lib/views'), findsOneWidget); + + // Open popup menu + await tester.tap(find.byType(PopupMenuButton)); + await tester.pumpAndSettle(); + + expect(find.text('保存所有'), findsOneWidget); + expect(find.text('设置'), findsOneWidget); + + // Tap 保存所有 + await tester.tap(find.text('保存所有')); + await tester.pumpAndSettle(); + + expect(saveAllTriggered, isTrue); + }); + + testWidgets('CodeEditorTabBar renders tabs and handles dirty close dialog', (WidgetTester tester) async { + final provider = EditorProvider(); + 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( + value: provider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const Scaffold( + body: Column( + children: [ + CodeEditorTabBar(), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Verify tabs rendered + expect(find.text('file1.dart'), findsOneWidget); + expect(find.text('file2.dart'), findsOneWidget); + // Tab2 is dirty, so asterisk * is displayed + expect(find.text('*'), findsOneWidget); + + // Click close on tab2 (dirty) + final closeIcons = find.byIcon(Icons.close); + expect(closeIcons, findsNWidgets(2)); + await tester.tap(closeIcons.at(1)); + await tester.pumpAndSettle(); + + // Save prompt dialog should appear + expect(find.text('保存更改'), findsOneWidget); + expect(find.text('文件 "file2.dart" 已被修改,是否保存更改?'), findsOneWidget); + + // Tap Discard (不保存) + await tester.tap(find.text('不保存')); + await tester.pumpAndSettle(); + + // Now tab2 should be closed, only tab1 left + expect(provider.openTabs.length, equals(1)); + expect(provider.openTabs.first.path, equals('/test/file1.dart')); + }); + + test('SettingsProvider manages settings correctly', () async { + final settings = SettingsProvider(); + expect(settings.fontSize, equals(14.0)); + expect(settings.wordWrap, isTrue); + expect(settings.appThemeMode, equals(ThemeMode.system)); + + await settings.setFontSize(18.0); + expect(settings.fontSize, equals(18.0)); + + await settings.setWordWrap(false); + expect(settings.wordWrap, isFalse); + + await settings.setAppThemeMode(ThemeMode.dark); + expect(settings.appThemeMode, equals(ThemeMode.dark)); + + await settings.setLocale(const Locale('en')); + expect(settings.locale, equals(const Locale('en'))); + }); + + test('ProjectProvider manages cut/copy/paste and tree state', () { + final project = ProjectProvider(); + final itemA = FileItem(name: 'a.dart', path: '/test/a.dart', isDirectory: false); + final itemB = FileItem(name: 'b.dart', path: '/test/b.dart', isDirectory: false); + + expect(project.canPaste, isFalse); + project.cut(itemA); + expect(project.canPaste, isTrue); + expect(project.isItemCut(itemA.path), isTrue); + expect(project.isItemCut(itemB.path), isFalse); + + project.copy(itemB); + expect(project.canPaste, isTrue); + expect(project.isItemCut(itemA.path), isFalse); + expect(project.copiedItem, equals(itemB)); + }); + + test('TabProvider manages openTabs, activeTab, and dirty state', () { + final tabProvider = TabProvider(); + final tab1 = EditorTabItem(path: '/ws/main.dart', content: 'void main() {}'); + tabProvider.setOpenTabsForTesting([tab1]); + + expect(tabProvider.openTabs.length, equals(1)); + expect(tabProvider.activeTab?.path, equals('/ws/main.dart')); + expect(tabProvider.isModified, isFalse); + + tabProvider.updateActiveTabContent('void main() { print(1); }', isModified: true); + expect(tabProvider.isModified, isTrue); + expect(tabProvider.activeTab?.content, equals('void main() { print(1); }')); + + tabProvider.setModified(false); + expect(tabProvider.isModified, isFalse); + }); + + test('EditorTabItem tracks isLoaded state and scroll offsets for in-memory caching', () { + final tab = EditorTabItem( + path: '/ws/test.dart', + content: 'hello', + isLoaded: true, + verticalScrollOffset: 120.0, + horizontalScrollOffset: 45.0, + ); + expect(tab.isLoaded, isTrue); + expect(tab.content, 'hello'); + expect(tab.verticalScrollOffset, 120.0); + expect(tab.horizontalScrollOffset, 45.0); + + final tabUnloaded = EditorTabItem(path: '/ws/cold.dart'); + expect(tabUnloaded.isLoaded, isFalse); + expect(tabUnloaded.verticalScrollOffset, 0.0); + expect(tabUnloaded.horizontalScrollOffset, 0.0); + }); + + testWidgets('CodeEditorWidget tab switching does not falsely mark tabs as dirty', (WidgetTester tester) async { + final tabProvider = TabProvider(); + final tabA = EditorTabItem( + path: '/test/a.dart', + content: 'void main() {\r\n print("a");\r\n}', + originalContent: 'void main() {\r\n print("a");\r\n}', + isLoaded: true, + isModified: false, + ); + final tabB = EditorTabItem( + path: '/test/b.dart', + content: 'void main() {\r\n print("b");\r\n}', + originalContent: 'void main() {\r\n print("b");\r\n}', + isLoaded: true, + isModified: false, + ); + tabProvider.setOpenTabsForTesting([tabA, tabB], activePath: tabA.path); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: const MaterialApp( + home: Scaffold( + body: CodeEditorWidget(rootPath: '/test', filePath: '/test/a.dart'), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + // Tab A should not be dirty + expect(tabA.isModified, isFalse); + expect(tabProvider.isModified, isFalse); + + // Switch to Tab B + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: const MaterialApp( + home: Scaffold( + body: CodeEditorWidget(rootPath: '/test', filePath: '/test/b.dart'), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + // Neither Tab A nor Tab B should be dirty! + expect(tabA.isModified, isFalse); + expect(tabB.isModified, isFalse); + expect(tabProvider.isModified, isFalse); + }); + + test('CodeLineEditingController text exact match with disk strings', () { + final samples = [ + 'void main() {\n print("hello");\n}\n', + 'void main() {\r\n print("hello");\r\n}\r\n', + 'class A {\n int x = 1;\n}', + 'class A {\r\n int x = 1;\r\n}', + '', + 'single line', + 'single line\n', + 'single line\r\n', + ' \n\t\t\n \n', + '\r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n', + ]; + + for (final raw in samples) { + final normalized = raw.replaceAll('\r\n', '\n'); + final controller = CodeLineEditingController.fromText(normalized); + final text = controller.text; + final current = text.replaceAll('\r\n', '\n'); + final normalizedOriginal = normalized.replaceAll('\r\n', '\n'); + expect(current == normalizedOriginal, isTrue, reason: 'Failed on raw: $raw, current: $current, orig: $normalizedOriginal'); + } + }); + + testWidgets('CodeEditorTabBar tab width does not stretch across entire row for single tab', (WidgetTester tester) async { + final tabProvider = TabProvider(); + final tab = EditorTabItem(path: '/test/main.dart', isModified: false); + tabProvider.setOpenTabsForTesting([tab]); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: tabProvider, + child: const MaterialApp( + home: Scaffold( + body: SizedBox( + width: 500.0, + child: CodeEditorTabBar(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Find the Container corresponding to the tab + final tabFinder = find.byKey(ValueKey(tab.path)); + expect(tabFinder, findsOneWidget); + + final RenderBox renderBox = tester.renderObject(tabFinder); + // On a 500px width container, a single tab with name 'main.dart' + // should NOT stretch to 500px, but be around ~80-140px. + expect(renderBox.size.width, lessThan(200.0)); + expect(renderBox.size.width, greaterThan(36.0)); + }); + + test('FileWatcherService filters ignored directories and handles self-save tracking', () { + expect(FileWatcherService.shouldIgnore('/ws/.git/config'), isTrue); + expect(FileWatcherService.shouldIgnore('/ws/.dart_tool/package_config.json'), isTrue); + expect(FileWatcherService.shouldIgnore('/ws/build/app.apk'), isTrue); + expect(FileWatcherService.shouldIgnore('/ws/lib/main.dart'), isFalse); + + final watcher = FileWatcherService.instance; + watcher.clearRecentlySavedForTesting(); + + expect(watcher.isRecentlySaved('/ws/lib/main.dart'), isFalse); + watcher.markRecentlySaved('/ws/lib/main.dart'); + expect(watcher.isRecentlySaved('/ws/lib/main.dart'), isTrue); + }); + + test('TabProvider handles external file modified: clean tab reloads silently, dirty tab triggers conflict', () async { + final tabProvider = TabProvider(); + final cleanTab = EditorTabItem( + path: '/ws/clean.dart', + content: 'old clean content', + originalContent: 'old clean content', + isModified: false, + ); + final dirtyTab = EditorTabItem( + path: '/ws/dirty.dart', + content: 'user edited content', + originalContent: 'baseline content', + isModified: true, + ); + tabProvider.setOpenTabsForTesting([cleanTab, dirtyTab]); + + // External file delete handling + tabProvider.handleExternalFileDeleted('/ws/clean.dart'); + expect(tabProvider.openTabs.any((t) => t.path == '/ws/clean.dart'), isFalse); + // Dirty tab should NOT be deleted automatically to protect code + tabProvider.handleExternalFileDeleted('/ws/dirty.dart'); + expect(tabProvider.openTabs.any((t) => t.path == '/ws/dirty.dart'), isTrue); + expect(dirtyTab.isDeletedOnDisk, isTrue); + + // Conflict resolution + dirtyTab.hasExternalConflict = true; + tabProvider.resolveConflict(dirtyTab, reloadFromDisk: false); + expect(dirtyTab.hasExternalConflict, isFalse); + expect(dirtyTab.content, equals('user edited content')); + }); + + testWidgets('Switching between .iml and .dart tabs preserves syntax highlight mapping and maintains clean dirty state', (WidgetTester tester) async { + final tabProvider = TabProvider(); + final tabIml = EditorTabItem( + path: p.normalize('/ws/code_editor.iml'), + content: '\r\n\r\n', + originalContent: '\r\n\r\n', + isLoaded: true, + isModified: false, + ); + final tabDart1 = EditorTabItem( + path: p.normalize('/ws/lib/main.dart'), + content: 'void main() {\r\n print("main");\r\n}\r\n', + originalContent: 'void main() {\r\n print("main");\r\n}\r\n', + isLoaded: true, + isModified: false, + ); + final tabDart2 = EditorTabItem( + path: p.normalize('/ws/lib/test.dart'), + content: 'void testFunc() {\r\n print("test");\r\n}\r\n', + originalContent: 'void testFunc() {\r\n print("test");\r\n}\r\n', + isLoaded: true, + isModified: false, + ); + tabProvider.setOpenTabsForTesting([tabIml, tabDart1, tabDart2], activePath: tabIml.path); + + // 1. Initial build with .iml + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + home: Scaffold( + body: CodeEditorWidget(rootPath: p.normalize('/ws'), filePath: tabIml.path), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + // .iml must have XML syntax mode + final imlModes = SyntaxHighlightHelper.getLanguagesForFile(tabIml.path); + expect(imlModes.keys, ['xml']); + expect(tabIml.isModified, isFalse); + expect(tabDart1.isModified, isFalse); + expect(tabDart2.isModified, isFalse); + + // 2. Switch to main.dart + await tabProvider.openFile(tabDart1.path); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + home: Scaffold( + body: CodeEditorWidget(rootPath: p.normalize('/ws'), filePath: tabDart1.path), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + // main.dart must have Dart syntax mode + final dart1Modes = SyntaxHighlightHelper.getLanguagesForFile(tabDart1.path); + expect(dart1Modes.keys, ['dart']); + expect(tabIml.isModified, isFalse, reason: 'Switching from .iml to .dart must not mark .iml dirty!'); + expect(tabDart1.isModified, isFalse, reason: 'Opening .dart tab must not mark it dirty!'); + + // 3. Switch to test.dart + await tabProvider.openFile(tabDart2.path); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + home: Scaffold( + body: CodeEditorWidget(rootPath: p.normalize('/ws'), filePath: tabDart2.path), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + expect(tabIml.isModified, isFalse); + expect(tabDart1.isModified, isFalse); + expect(tabDart2.isModified, isFalse); + + // 4. Switch back to main.dart + await tabProvider.openFile(tabDart1.path); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + home: Scaffold( + body: CodeEditorWidget(rootPath: p.normalize('/ws'), filePath: tabDart1.path), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + expect(tabIml.isModified, isFalse); + expect(tabDart1.isModified, isFalse); + expect(tabDart2.isModified, isFalse); + + // 5. Simulate editing: update content to modified -> dirty + tabProvider.updateActiveTabContent('void main() {\r\n print("modified");\r\n}\r\n'); + expect(tabDart1.isModified, isTrue); + expect(tabProvider.isModified, isTrue); + + // 6. Undo back to original content -> automatically clean! + tabProvider.updateActiveTabContent(tabDart1.originalContent); + expect(tabDart1.isModified, isFalse); + expect(tabProvider.isModified, isFalse); + }); + + testWidgets('Opening another file from file list when active file is modified does not prompt save dialog', (WidgetTester tester) async { + final tabProvider = TabProvider(); + final projectProvider = ProjectProvider(); + final settingsProvider = SettingsProvider(); + + final file1 = FileItem(path: p.normalize('/ws/file1.dart'), name: 'file1.dart', isDirectory: false); + final file2 = FileItem(path: p.normalize('/ws/file2.dart'), name: 'file2.dart', isDirectory: false); + + // Initial state: open file1 and modify it + await tabProvider.openFile(file1.path, content: 'int a = 1;'); + tabProvider.updateActiveTabContent('int a = 2;', isModified: true); + expect(tabProvider.isModified, isTrue); + + 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(); + + // Verify main view is rendered with modified file1 + expect(find.text('file1.dart'), findsWidgets); + expect(tabProvider.isModified, isTrue); + + // Open file2 via selectFile (simulating user clicking file2 in file tree/drawer) + await tabProvider.selectFile(file2); + await tester.pumpAndSettle(); + + // NO save prompt dialog should appear + expect(find.text('保存更改'), findsNothing); + expect(find.text('保存所有更改?'), findsNothing); + + // Now file2 is active, file1 is still open and preserved in memory + expect(tabProvider.activeTab?.path, equals(p.normalize('/ws/file2.dart'))); + expect(tabProvider.openTabs.length, equals(2)); + expect(tabProvider.openTabs[0].isModified, isTrue); + expect(tabProvider.openTabs[0].content, equals('int a = 2;')); + + // Switch back to file1 via openFile (simulating clicking tab1) + await tabProvider.openFile(file1.path); + await tester.pumpAndSettle(); + + // NO save prompt dialog should appear on tab switch either + expect(find.text('保存更改'), findsNothing); + expect(find.text('保存所有更改?'), findsNothing); + expect(tabProvider.activeTab?.path, equals(p.normalize('/ws/file1.dart'))); + expect(tabProvider.activeTab?.isModified, isTrue); + }); } + diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 4f78848..8b6d468 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,9 +6,6 @@ #include "generated_plugin_registrant.h" -#include void RegisterPlugins(flutter::PluginRegistry* registry) { - UrlLauncherWindowsRegisterWithRegistrar( - registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index 88b22e5..b93c4c3 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,7 +3,6 @@ # list(APPEND FLUTTER_PLUGIN_LIST - url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST