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