From 9fbb414ee6019970454aa249280a8994b6a13a8f Mon Sep 17 00:00:00 2001
From: LZX <1820455493@qq.com>
Date: Sun, 13 Sep 2026 20:22:34 +0800
Subject: [PATCH] 1
---
.../app/src/main/res/values-night/styles.xml | 1 +
android/app/src/main/res/values/styles.xml | 1 +
lib/l10n/app_en.arb | 138 +++-
lib/l10n/app_localizations.dart | 350 +++++++++-
lib/l10n/app_localizations_en.dart | 205 +++++-
lib/l10n/app_localizations_zh.dart | 196 +++++-
lib/l10n/app_zh.arb | 138 +++-
lib/main.dart | 22 +
lib/models/app_font.dart | 4 +-
lib/models/virtual_keyboard_config.dart | 216 +++++-
lib/providers/settings_provider.dart | 8 +-
lib/providers/tab_provider.dart | 11 +-
lib/services/distro_installer.dart | 1 +
lib/services/file_service.dart | 2 +-
lib/services/project_history_service.dart | 8 +-
lib/views/settings_view.dart | 199 +-----
lib/views/virtual_keyboard_config_view.dart | 616 ++++++++++++++++++
lib/widgets/code_editor_app_bar.dart | 8 +
lib/widgets/code_editor_tab_bar.dart | 43 +-
lib/widgets/code_editor_widget.dart | 225 +++++--
lib/widgets/terminal_drawer.dart | 27 +-
.../virtual_keyboard_key_edit_dialog.dart | 390 +++++++++++
lib/widgets/virtual_keyboard_key_tile.dart | 89 +++
.../virtual_keyboard_page_config_section.dart | 88 +++
lib/widgets/virtual_keyboard_page_drawer.dart | 184 ++++++
lib/widgets/virtual_keyboard_row_tile.dart | 126 ++++
lib/widgets/virtual_keyboard_widget.dart | 266 +++++---
test/terminal_test.dart | 10 +-
test/widget_test.dart | 368 +++++++++--
29 files changed, 3480 insertions(+), 460 deletions(-)
create mode 100644 lib/views/virtual_keyboard_config_view.dart
create mode 100644 lib/widgets/virtual_keyboard_key_edit_dialog.dart
create mode 100644 lib/widgets/virtual_keyboard_key_tile.dart
create mode 100644 lib/widgets/virtual_keyboard_page_config_section.dart
create mode 100644 lib/widgets/virtual_keyboard_page_drawer.dart
create mode 100644 lib/widgets/virtual_keyboard_row_tile.dart
diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml
index 06952be..1a808fa 100644
--- a/android/app/src/main/res/values-night/styles.xml
+++ b/android/app/src/main/res/values-night/styles.xml
@@ -14,5 +14,6 @@
This Theme is only used starting with V2 of Flutter's Android embedding. -->
diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml
index cb1ef88..f257849 100644
--- a/android/app/src/main/res/values/styles.xml
+++ b/android/app/src/main/res/values/styles.xml
@@ -14,5 +14,6 @@
This Theme is only used starting with V2 of Flutter's Android embedding. -->
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index e28f23b..216d034 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -90,7 +90,7 @@
"virtualKeyboard": "Accessory Keyboard",
"virtualKeyboardSubtitle": "Show accessory symbols and shortcuts below the code editor",
"editVirtualKeyboardConfig": "Edit Keyboard Config",
- "editVirtualKeyboardConfigSubtitle": "Customize keyboard layout and shortcuts (JSON)",
+ "editVirtualKeyboardConfigSubtitle": "Customize keyboard layout and shortcuts",
"virtualKeyboardDialogTitle": "Keyboard Config (JSON)",
"resetDefault": "Reset to Default",
"configFormatError": "Configuration format error",
@@ -239,5 +239,139 @@
"type": "String"
}
}
- }
+ },
+ "cancel": "Cancel",
+ "confirm": "Confirm",
+ "delete": "Delete",
+ "addSession": "New Session",
+ "editorScope": "Editor",
+ "terminalScope": "Terminal",
+ "virtualKeyboardConfigTitle": "Accessory Keyboard Config",
+ "virtualKeyboardPageSubtitle": "{scope}:(Page {page})",
+ "@virtualKeyboardPageSubtitle": {
+ "placeholders": {
+ "scope": {
+ "type": "String"
+ },
+ "page": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardRestoreDefaultTooltip": "Reset to default presets",
+ "keyboardPageManagementTooltip": "Page Management",
+ "keyboardDrawerTitle": "Pages",
+ "keyboardNewPage": "New Page",
+ "keyboardPageItemTitle": "Page {page}",
+ "@keyboardPageItemTitle": {
+ "placeholders": {
+ "page": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardPageItemSubtitle": "{count} rows",
+ "@keyboardPageItemSubtitle": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDeletePageTooltip": "Delete page",
+ "keyboardPageConfigSectionTitle": "Page Configuration",
+ "keyboardRowButtons": "Buttons per row",
+ "keyboardRowGridDescription": "Page width divided into {count} columns",
+ "@keyboardRowGridDescription": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDecreaseRowButtonsTooltip": "Decrease buttons per row",
+ "keyboardIncreaseRowButtonsTooltip": "Increase buttons per row",
+ "keyboardPageKeysSectionTitle": "Page Keys",
+ "keyboardAddNewRow": "Add Row",
+ "keyboardEmptyPageKeysHint": "No key rows in current page",
+ "keyboardEmptyRowKeysHint": "No keys in this row, tap '+' above to add",
+ "keyboardRowKeyCount": "{count} keys",
+ "@keyboardRowKeyCount": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardAddKeyTooltip": "Add key",
+ "keyboardDeleteRowTooltip": "Delete row",
+ "keyboardEditKeyTooltip": "Edit key",
+ "keyboardDeleteKeyTooltip": "Delete key",
+ "keyboardNoLabel": "(No label)",
+ "keyboardResetDefaultTitle": "Reset to Default",
+ "keyboardResetDefaultContent": "Are you sure you want to reset the keyboard to default presets? Your custom modifications will be overwritten.",
+ "keyboardResetDefaultSuccess": "Reset to default presets successfully",
+ "keyboardDeletePageTitle": "Delete Page",
+ "keyboardDeletePageContent": "Are you sure you want to delete \"Page {page}\"?",
+ "@keyboardDeletePageContent": {
+ "placeholders": {
+ "page": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDeleteRowTitle": "Delete Key Row",
+ "keyboardDeleteRowContent": "Are you sure you want to delete \"Row {row}\" and all its keys?",
+ "@keyboardDeleteRowContent": {
+ "placeholders": {
+ "row": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDeleteKeyTitle": "Delete Key",
+ "keyboardDeleteKeyContent": "Are you sure you want to delete key \"{key}\"?",
+ "@keyboardDeleteKeyContent": {
+ "placeholders": {
+ "key": {
+ "type": "String"
+ }
+ }
+ },
+ "keyboardKeepAtLeastOnePageWarning": "Must keep at least one page",
+ "keyboardRowMaxKeysWarning": "A row currently has {count} keys, row button count cannot be less than {count}",
+ "@keyboardRowMaxKeysWarning": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardRowReachedMaxWarning": "Key count in this row has reached maximum (max {count} keys)",
+ "@keyboardRowReachedMaxWarning": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardAddKeyTitle": "Add Key",
+ "keyboardEditKeyTitle": "Edit Key",
+ "keyboardLabelFormField": "Label",
+ "keyboardLabelFormFieldHint": "Text displayed on the key, e.g. Tab, (), A",
+ "keyboardLabelOrIconRequiredError": "Please enter display text or select an icon",
+ "keyboardIconFormField": "Icon (Optional)",
+ "keyboardNoIconOption": "No icon (Use text)",
+ "keyboardActionFormField": "Action",
+ "keyboardValueFormField": "Input Text (Value)",
+ "keyboardValueFormFieldHint": "Text inserted upon click, e.g. ;, =, ->",
+ "keyboardValueRequiredError": "Input text cannot be empty",
+ "keyboardPairPresetFormField": "Pair Symbols Preset (Value)",
+ "keyboardCommandPresetFormField": "Editor Command Preset (Value)",
+ "keyboardModifierPresetFormField": "Terminal Modifier (Value)",
+ "keyboardTerminalKeyPresetFormField": "Terminal Key (Value)",
+ "keyboardCursorOffsetFormField": "Cursor Relative Offset (cursorOffset)",
+ "keyboardCursorOffsetHelper": "e.g. For () cursor in center should move left by 1, enter -1",
+ "keyboardCursorOffsetRequiredError": "Please enter cursor offset (usually -1)",
+ "keyboardCursorOffsetIntegerError": "Offset must be an integer"
}
\ No newline at end of file
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 1f15413..95e118e 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -593,7 +593,7 @@ abstract class AppLocalizations {
/// No description provided for @editVirtualKeyboardConfigSubtitle.
///
/// In zh, this message translates to:
- /// **'自定义小键盘按键布局与快捷键 (JSON)'**
+ /// **'自定义小键盘按键布局与快捷键'**
String get editVirtualKeyboardConfigSubtitle;
/// No description provided for @virtualKeyboardDialogTitle.
@@ -1009,6 +1009,354 @@ abstract class AppLocalizations {
/// In zh, this message translates to:
/// **'删除系统失败: {error}'**
String deleteSystemFailed(String error);
+
+ /// No description provided for @addSession.
+ ///
+ /// In zh, this message translates to:
+ /// **'新增会话'**
+ String get addSession;
+
+ /// No description provided for @editorScope.
+ ///
+ /// In zh, this message translates to:
+ /// **'编辑区'**
+ String get editorScope;
+
+ /// No description provided for @terminalScope.
+ ///
+ /// In zh, this message translates to:
+ /// **'终端'**
+ String get terminalScope;
+
+ /// No description provided for @virtualKeyboardConfigTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'小键盘配置'**
+ String get virtualKeyboardConfigTitle;
+
+ /// No description provided for @virtualKeyboardPageSubtitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'{scope}:(第 {page} 页)'**
+ String virtualKeyboardPageSubtitle(String scope, int page);
+
+ /// No description provided for @keyboardRestoreDefaultTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'恢复默认预设'**
+ String get keyboardRestoreDefaultTooltip;
+
+ /// No description provided for @keyboardPageManagementTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'页面管理'**
+ String get keyboardPageManagementTooltip;
+
+ /// No description provided for @keyboardDrawerTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'页面'**
+ String get keyboardDrawerTitle;
+
+ /// No description provided for @keyboardNewPage.
+ ///
+ /// In zh, this message translates to:
+ /// **'新建页面'**
+ String get keyboardNewPage;
+
+ /// No description provided for @keyboardPageItemTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'第 {page} 页'**
+ String keyboardPageItemTitle(int page);
+
+ /// No description provided for @keyboardPageItemSubtitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'{count} 行'**
+ String keyboardPageItemSubtitle(int count);
+
+ /// No description provided for @keyboardDeletePageTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'删除页面'**
+ String get keyboardDeletePageTooltip;
+
+ /// No description provided for @keyboardPageConfigSectionTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'页面配置'**
+ String get keyboardPageConfigSectionTitle;
+
+ /// No description provided for @keyboardRowButtons.
+ ///
+ /// In zh, this message translates to:
+ /// **'行按钮数'**
+ String get keyboardRowButtons;
+
+ /// No description provided for @keyboardRowGridDescription.
+ ///
+ /// In zh, this message translates to:
+ /// **'页面宽度等分为 {count} 格'**
+ String keyboardRowGridDescription(int count);
+
+ /// No description provided for @keyboardDecreaseRowButtonsTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'减少每行按键数'**
+ String get keyboardDecreaseRowButtonsTooltip;
+
+ /// No description provided for @keyboardIncreaseRowButtonsTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'增加每行按键数'**
+ String get keyboardIncreaseRowButtonsTooltip;
+
+ /// No description provided for @keyboardPageKeysSectionTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'页面按键'**
+ String get keyboardPageKeysSectionTitle;
+
+ /// No description provided for @keyboardAddNewRow.
+ ///
+ /// In zh, this message translates to:
+ /// **'添加新行'**
+ String get keyboardAddNewRow;
+
+ /// No description provided for @keyboardEmptyPageKeysHint.
+ ///
+ /// In zh, this message translates to:
+ /// **'当前页面暂无按键行'**
+ String get keyboardEmptyPageKeysHint;
+
+ /// No description provided for @keyboardEmptyRowKeysHint.
+ ///
+ /// In zh, this message translates to:
+ /// **'行内暂无按键,点击上方“+”添加'**
+ String get keyboardEmptyRowKeysHint;
+
+ /// No description provided for @keyboardRowKeyCount.
+ ///
+ /// In zh, this message translates to:
+ /// **'{count} 个按键'**
+ String keyboardRowKeyCount(int count);
+
+ /// No description provided for @keyboardAddKeyTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'添加按键'**
+ String get keyboardAddKeyTooltip;
+
+ /// No description provided for @keyboardDeleteRowTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'删除整行'**
+ String get keyboardDeleteRowTooltip;
+
+ /// No description provided for @keyboardEditKeyTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'编辑按键'**
+ String get keyboardEditKeyTooltip;
+
+ /// No description provided for @keyboardDeleteKeyTooltip.
+ ///
+ /// In zh, this message translates to:
+ /// **'删除按键'**
+ String get keyboardDeleteKeyTooltip;
+
+ /// No description provided for @keyboardNoLabel.
+ ///
+ /// In zh, this message translates to:
+ /// **'(无标签)'**
+ String get keyboardNoLabel;
+
+ /// No description provided for @keyboardResetDefaultTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'恢复默认配置'**
+ String get keyboardResetDefaultTitle;
+
+ /// No description provided for @keyboardResetDefaultContent.
+ ///
+ /// In zh, this message translates to:
+ /// **'确定要将小键盘恢复为初始默认预设吗?当前自定义修改将被覆盖。'**
+ String get keyboardResetDefaultContent;
+
+ /// No description provided for @keyboardResetDefaultSuccess.
+ ///
+ /// In zh, this message translates to:
+ /// **'已恢复默认预设'**
+ String get keyboardResetDefaultSuccess;
+
+ /// No description provided for @keyboardDeletePageTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'删除页面'**
+ String get keyboardDeletePageTitle;
+
+ /// No description provided for @keyboardDeletePageContent.
+ ///
+ /// In zh, this message translates to:
+ /// **'确定要删除“第 {page} 页”吗?'**
+ String keyboardDeletePageContent(int page);
+
+ /// No description provided for @keyboardDeleteRowTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'删除按键行'**
+ String get keyboardDeleteRowTitle;
+
+ /// No description provided for @keyboardDeleteRowContent.
+ ///
+ /// In zh, this message translates to:
+ /// **'确定要删除“第 {row} 行”及其包含的所有按键吗?'**
+ String keyboardDeleteRowContent(int row);
+
+ /// No description provided for @keyboardDeleteKeyTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'删除按键'**
+ String get keyboardDeleteKeyTitle;
+
+ /// No description provided for @keyboardDeleteKeyContent.
+ ///
+ /// In zh, this message translates to:
+ /// **'确定要删除按键“{key}”吗?'**
+ String keyboardDeleteKeyContent(String key);
+
+ /// No description provided for @keyboardKeepAtLeastOnePageWarning.
+ ///
+ /// In zh, this message translates to:
+ /// **'至少需要保留一个页面'**
+ String get keyboardKeepAtLeastOnePageWarning;
+
+ /// No description provided for @keyboardRowMaxKeysWarning.
+ ///
+ /// In zh, this message translates to:
+ /// **'当前存在包含 {count} 个按键的行,行按钮数不能小于 {count}'**
+ String keyboardRowMaxKeysWarning(int count);
+
+ /// No description provided for @keyboardRowReachedMaxWarning.
+ ///
+ /// In zh, this message translates to:
+ /// **'当前行按键数已达到上限(最多 {count} 个按键)'**
+ String keyboardRowReachedMaxWarning(int count);
+
+ /// No description provided for @keyboardAddKeyTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'添加按键'**
+ String get keyboardAddKeyTitle;
+
+ /// No description provided for @keyboardEditKeyTitle.
+ ///
+ /// In zh, this message translates to:
+ /// **'编辑按键'**
+ String get keyboardEditKeyTitle;
+
+ /// No description provided for @keyboardLabelFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'显示文本 (Label)'**
+ String get keyboardLabelFormField;
+
+ /// No description provided for @keyboardLabelFormFieldHint.
+ ///
+ /// In zh, this message translates to:
+ /// **'按键上显示的文本,如 Tab、()、A'**
+ String get keyboardLabelFormFieldHint;
+
+ /// No description provided for @keyboardLabelOrIconRequiredError.
+ ///
+ /// In zh, this message translates to:
+ /// **'请输入显示文本或选择图标'**
+ String get keyboardLabelOrIconRequiredError;
+
+ /// No description provided for @keyboardIconFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'图标 (Icon, 可选)'**
+ String get keyboardIconFormField;
+
+ /// No description provided for @keyboardNoIconOption.
+ ///
+ /// In zh, this message translates to:
+ /// **'无图标 (使用文本显示)'**
+ String get keyboardNoIconOption;
+
+ /// No description provided for @keyboardActionFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'动作类型 (Action)'**
+ String get keyboardActionFormField;
+
+ /// No description provided for @keyboardValueFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'输入文本内容 (Value)'**
+ String get keyboardValueFormField;
+
+ /// No description provided for @keyboardValueFormFieldHint.
+ ///
+ /// In zh, this message translates to:
+ /// **'点击后直接插入的文本,如 ;、=、->'**
+ String get keyboardValueFormFieldHint;
+
+ /// No description provided for @keyboardValueRequiredError.
+ ///
+ /// In zh, this message translates to:
+ /// **'输入文本不能为空'**
+ String get keyboardValueRequiredError;
+
+ /// No description provided for @keyboardPairPresetFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'成对符号预设 (Value)'**
+ String get keyboardPairPresetFormField;
+
+ /// No description provided for @keyboardCommandPresetFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'预设编辑器命令 (Value)'**
+ String get keyboardCommandPresetFormField;
+
+ /// No description provided for @keyboardModifierPresetFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'终端修饰键 (Value)'**
+ String get keyboardModifierPresetFormField;
+
+ /// No description provided for @keyboardTerminalKeyPresetFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'终端按键 (Value)'**
+ String get keyboardTerminalKeyPresetFormField;
+
+ /// No description provided for @keyboardCursorOffsetFormField.
+ ///
+ /// In zh, this message translates to:
+ /// **'光标相对偏移 (cursorOffset)'**
+ String get keyboardCursorOffsetFormField;
+
+ /// No description provided for @keyboardCursorOffsetHelper.
+ ///
+ /// In zh, this message translates to:
+ /// **'例如 () 插入后光标居中需向左偏移 1 位,填写 -1'**
+ String get keyboardCursorOffsetHelper;
+
+ /// No description provided for @keyboardCursorOffsetRequiredError.
+ ///
+ /// In zh, this message translates to:
+ /// **'请输入光标偏移(通常为 -1)'**
+ String get keyboardCursorOffsetRequiredError;
+
+ /// No description provided for @keyboardCursorOffsetIntegerError.
+ ///
+ /// In zh, this message translates to:
+ /// **'偏移量必须为整数'**
+ String get keyboardCursorOffsetIntegerError;
}
class _AppLocalizationsDelegate
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 050b738..960c009 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -279,7 +279,7 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get editVirtualKeyboardConfigSubtitle =>
- 'Customize keyboard layout and shortcuts (JSON)';
+ 'Customize keyboard layout and shortcuts';
@override
String get virtualKeyboardDialogTitle => 'Keyboard Config (JSON)';
@@ -522,4 +522,207 @@ class AppLocalizationsEn extends AppLocalizations {
String deleteSystemFailed(String error) {
return 'Failed to delete system: $error';
}
+
+ @override
+ String get addSession => 'New Session';
+
+ @override
+ String get editorScope => 'Editor';
+
+ @override
+ String get terminalScope => 'Terminal';
+
+ @override
+ String get virtualKeyboardConfigTitle => 'Accessory Keyboard Config';
+
+ @override
+ String virtualKeyboardPageSubtitle(String scope, int page) {
+ return '$scope:(Page $page)';
+ }
+
+ @override
+ String get keyboardRestoreDefaultTooltip => 'Reset to default presets';
+
+ @override
+ String get keyboardPageManagementTooltip => 'Page Management';
+
+ @override
+ String get keyboardDrawerTitle => 'Pages';
+
+ @override
+ String get keyboardNewPage => 'New Page';
+
+ @override
+ String keyboardPageItemTitle(int page) {
+ return 'Page $page';
+ }
+
+ @override
+ String keyboardPageItemSubtitle(int count) {
+ return '$count rows';
+ }
+
+ @override
+ String get keyboardDeletePageTooltip => 'Delete page';
+
+ @override
+ String get keyboardPageConfigSectionTitle => 'Page Configuration';
+
+ @override
+ String get keyboardRowButtons => 'Buttons per row';
+
+ @override
+ String keyboardRowGridDescription(int count) {
+ return 'Page width divided into $count columns';
+ }
+
+ @override
+ String get keyboardDecreaseRowButtonsTooltip => 'Decrease buttons per row';
+
+ @override
+ String get keyboardIncreaseRowButtonsTooltip => 'Increase buttons per row';
+
+ @override
+ String get keyboardPageKeysSectionTitle => 'Page Keys';
+
+ @override
+ String get keyboardAddNewRow => 'Add Row';
+
+ @override
+ String get keyboardEmptyPageKeysHint => 'No key rows in current page';
+
+ @override
+ String get keyboardEmptyRowKeysHint =>
+ 'No keys in this row, tap \'+\' above to add';
+
+ @override
+ String keyboardRowKeyCount(int count) {
+ return '$count keys';
+ }
+
+ @override
+ String get keyboardAddKeyTooltip => 'Add key';
+
+ @override
+ String get keyboardDeleteRowTooltip => 'Delete row';
+
+ @override
+ String get keyboardEditKeyTooltip => 'Edit key';
+
+ @override
+ String get keyboardDeleteKeyTooltip => 'Delete key';
+
+ @override
+ String get keyboardNoLabel => '(No label)';
+
+ @override
+ String get keyboardResetDefaultTitle => 'Reset to Default';
+
+ @override
+ String get keyboardResetDefaultContent =>
+ 'Are you sure you want to reset the keyboard to default presets? Your custom modifications will be overwritten.';
+
+ @override
+ String get keyboardResetDefaultSuccess =>
+ 'Reset to default presets successfully';
+
+ @override
+ String get keyboardDeletePageTitle => 'Delete Page';
+
+ @override
+ String keyboardDeletePageContent(int page) {
+ return 'Are you sure you want to delete \"Page $page\"?';
+ }
+
+ @override
+ String get keyboardDeleteRowTitle => 'Delete Key Row';
+
+ @override
+ String keyboardDeleteRowContent(int row) {
+ return 'Are you sure you want to delete \"Row $row\" and all its keys?';
+ }
+
+ @override
+ String get keyboardDeleteKeyTitle => 'Delete Key';
+
+ @override
+ String keyboardDeleteKeyContent(String key) {
+ return 'Are you sure you want to delete key \"$key\"?';
+ }
+
+ @override
+ String get keyboardKeepAtLeastOnePageWarning => 'Must keep at least one page';
+
+ @override
+ String keyboardRowMaxKeysWarning(int count) {
+ return 'A row currently has $count keys, row button count cannot be less than $count';
+ }
+
+ @override
+ String keyboardRowReachedMaxWarning(int count) {
+ return 'Key count in this row has reached maximum (max $count keys)';
+ }
+
+ @override
+ String get keyboardAddKeyTitle => 'Add Key';
+
+ @override
+ String get keyboardEditKeyTitle => 'Edit Key';
+
+ @override
+ String get keyboardLabelFormField => 'Label';
+
+ @override
+ String get keyboardLabelFormFieldHint =>
+ 'Text displayed on the key, e.g. Tab, (), A';
+
+ @override
+ String get keyboardLabelOrIconRequiredError =>
+ 'Please enter display text or select an icon';
+
+ @override
+ String get keyboardIconFormField => 'Icon (Optional)';
+
+ @override
+ String get keyboardNoIconOption => 'No icon (Use text)';
+
+ @override
+ String get keyboardActionFormField => 'Action';
+
+ @override
+ String get keyboardValueFormField => 'Input Text (Value)';
+
+ @override
+ String get keyboardValueFormFieldHint =>
+ 'Text inserted upon click, e.g. ;, =, ->';
+
+ @override
+ String get keyboardValueRequiredError => 'Input text cannot be empty';
+
+ @override
+ String get keyboardPairPresetFormField => 'Pair Symbols Preset (Value)';
+
+ @override
+ String get keyboardCommandPresetFormField => 'Editor Command Preset (Value)';
+
+ @override
+ String get keyboardModifierPresetFormField => 'Terminal Modifier (Value)';
+
+ @override
+ String get keyboardTerminalKeyPresetFormField => 'Terminal Key (Value)';
+
+ @override
+ String get keyboardCursorOffsetFormField =>
+ 'Cursor Relative Offset (cursorOffset)';
+
+ @override
+ String get keyboardCursorOffsetHelper =>
+ 'e.g. For () cursor in center should move left by 1, enter -1';
+
+ @override
+ String get keyboardCursorOffsetRequiredError =>
+ 'Please enter cursor offset (usually -1)';
+
+ @override
+ String get keyboardCursorOffsetIntegerError => 'Offset must be an integer';
}
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index f31077d..eedec89 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -273,7 +273,7 @@ class AppLocalizationsZh extends AppLocalizations {
String get editVirtualKeyboardConfig => '编辑键盘配置';
@override
- String get editVirtualKeyboardConfigSubtitle => '自定义小键盘按键布局与快捷键 (JSON)';
+ String get editVirtualKeyboardConfigSubtitle => '自定义小键盘按键布局与快捷键';
@override
String get virtualKeyboardDialogTitle => '小键盘配置 (JSON)';
@@ -510,4 +510,198 @@ class AppLocalizationsZh extends AppLocalizations {
String deleteSystemFailed(String error) {
return '删除系统失败: $error';
}
+
+ @override
+ String get addSession => '新增会话';
+
+ @override
+ String get editorScope => '编辑区';
+
+ @override
+ String get terminalScope => '终端';
+
+ @override
+ String get virtualKeyboardConfigTitle => '小键盘配置';
+
+ @override
+ String virtualKeyboardPageSubtitle(String scope, int page) {
+ return '$scope:(第 $page 页)';
+ }
+
+ @override
+ String get keyboardRestoreDefaultTooltip => '恢复默认预设';
+
+ @override
+ String get keyboardPageManagementTooltip => '页面管理';
+
+ @override
+ String get keyboardDrawerTitle => '页面';
+
+ @override
+ String get keyboardNewPage => '新建页面';
+
+ @override
+ String keyboardPageItemTitle(int page) {
+ return '第 $page 页';
+ }
+
+ @override
+ String keyboardPageItemSubtitle(int count) {
+ return '$count 行';
+ }
+
+ @override
+ String get keyboardDeletePageTooltip => '删除页面';
+
+ @override
+ String get keyboardPageConfigSectionTitle => '页面配置';
+
+ @override
+ String get keyboardRowButtons => '行按钮数';
+
+ @override
+ String keyboardRowGridDescription(int count) {
+ return '页面宽度等分为 $count 格';
+ }
+
+ @override
+ String get keyboardDecreaseRowButtonsTooltip => '减少每行按键数';
+
+ @override
+ String get keyboardIncreaseRowButtonsTooltip => '增加每行按键数';
+
+ @override
+ String get keyboardPageKeysSectionTitle => '页面按键';
+
+ @override
+ String get keyboardAddNewRow => '添加新行';
+
+ @override
+ String get keyboardEmptyPageKeysHint => '当前页面暂无按键行';
+
+ @override
+ String get keyboardEmptyRowKeysHint => '行内暂无按键,点击上方“+”添加';
+
+ @override
+ String keyboardRowKeyCount(int count) {
+ return '$count 个按键';
+ }
+
+ @override
+ String get keyboardAddKeyTooltip => '添加按键';
+
+ @override
+ String get keyboardDeleteRowTooltip => '删除整行';
+
+ @override
+ String get keyboardEditKeyTooltip => '编辑按键';
+
+ @override
+ String get keyboardDeleteKeyTooltip => '删除按键';
+
+ @override
+ String get keyboardNoLabel => '(无标签)';
+
+ @override
+ String get keyboardResetDefaultTitle => '恢复默认配置';
+
+ @override
+ String get keyboardResetDefaultContent => '确定要将小键盘恢复为初始默认预设吗?当前自定义修改将被覆盖。';
+
+ @override
+ String get keyboardResetDefaultSuccess => '已恢复默认预设';
+
+ @override
+ String get keyboardDeletePageTitle => '删除页面';
+
+ @override
+ String keyboardDeletePageContent(int page) {
+ return '确定要删除“第 $page 页”吗?';
+ }
+
+ @override
+ String get keyboardDeleteRowTitle => '删除按键行';
+
+ @override
+ String keyboardDeleteRowContent(int row) {
+ return '确定要删除“第 $row 行”及其包含的所有按键吗?';
+ }
+
+ @override
+ String get keyboardDeleteKeyTitle => '删除按键';
+
+ @override
+ String keyboardDeleteKeyContent(String key) {
+ return '确定要删除按键“$key”吗?';
+ }
+
+ @override
+ String get keyboardKeepAtLeastOnePageWarning => '至少需要保留一个页面';
+
+ @override
+ String keyboardRowMaxKeysWarning(int count) {
+ return '当前存在包含 $count 个按键的行,行按钮数不能小于 $count';
+ }
+
+ @override
+ String keyboardRowReachedMaxWarning(int count) {
+ return '当前行按键数已达到上限(最多 $count 个按键)';
+ }
+
+ @override
+ String get keyboardAddKeyTitle => '添加按键';
+
+ @override
+ String get keyboardEditKeyTitle => '编辑按键';
+
+ @override
+ String get keyboardLabelFormField => '显示文本 (Label)';
+
+ @override
+ String get keyboardLabelFormFieldHint => '按键上显示的文本,如 Tab、()、A';
+
+ @override
+ String get keyboardLabelOrIconRequiredError => '请输入显示文本或选择图标';
+
+ @override
+ String get keyboardIconFormField => '图标 (Icon, 可选)';
+
+ @override
+ String get keyboardNoIconOption => '无图标 (使用文本显示)';
+
+ @override
+ String get keyboardActionFormField => '动作类型 (Action)';
+
+ @override
+ String get keyboardValueFormField => '输入文本内容 (Value)';
+
+ @override
+ String get keyboardValueFormFieldHint => '点击后直接插入的文本,如 ;、=、->';
+
+ @override
+ String get keyboardValueRequiredError => '输入文本不能为空';
+
+ @override
+ String get keyboardPairPresetFormField => '成对符号预设 (Value)';
+
+ @override
+ String get keyboardCommandPresetFormField => '预设编辑器命令 (Value)';
+
+ @override
+ String get keyboardModifierPresetFormField => '终端修饰键 (Value)';
+
+ @override
+ String get keyboardTerminalKeyPresetFormField => '终端按键 (Value)';
+
+ @override
+ String get keyboardCursorOffsetFormField => '光标相对偏移 (cursorOffset)';
+
+ @override
+ String get keyboardCursorOffsetHelper => '例如 () 插入后光标居中需向左偏移 1 位,填写 -1';
+
+ @override
+ String get keyboardCursorOffsetRequiredError => '请输入光标偏移(通常为 -1)';
+
+ @override
+ String get keyboardCursorOffsetIntegerError => '偏移量必须为整数';
}
diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb
index 05e234f..4d47f7a 100644
--- a/lib/l10n/app_zh.arb
+++ b/lib/l10n/app_zh.arb
@@ -90,7 +90,7 @@
"virtualKeyboard": "辅助小键盘",
"virtualKeyboardSubtitle": "在代码编辑区底部显示辅助符号与快捷键",
"editVirtualKeyboardConfig": "编辑键盘配置",
- "editVirtualKeyboardConfigSubtitle": "自定义小键盘按键布局与快捷键 (JSON)",
+ "editVirtualKeyboardConfigSubtitle": "自定义小键盘按键布局与快捷键",
"virtualKeyboardDialogTitle": "小键盘配置 (JSON)",
"resetDefault": "恢复默认",
"configFormatError": "配置格式错误",
@@ -239,5 +239,139 @@
"type": "String"
}
}
- }
+ },
+ "cancel": "取消",
+ "confirm": "确定",
+ "delete": "删除",
+ "addSession": "新增会话",
+ "editorScope": "编辑区",
+ "terminalScope": "终端",
+ "virtualKeyboardConfigTitle": "小键盘配置",
+ "virtualKeyboardPageSubtitle": "{scope}:(第 {page} 页)",
+ "@virtualKeyboardPageSubtitle": {
+ "placeholders": {
+ "scope": {
+ "type": "String"
+ },
+ "page": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardRestoreDefaultTooltip": "恢复默认预设",
+ "keyboardPageManagementTooltip": "页面管理",
+ "keyboardDrawerTitle": "页面",
+ "keyboardNewPage": "新建页面",
+ "keyboardPageItemTitle": "第 {page} 页",
+ "@keyboardPageItemTitle": {
+ "placeholders": {
+ "page": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardPageItemSubtitle": "{count} 行",
+ "@keyboardPageItemSubtitle": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDeletePageTooltip": "删除页面",
+ "keyboardPageConfigSectionTitle": "页面配置",
+ "keyboardRowButtons": "行按钮数",
+ "keyboardRowGridDescription": "页面宽度等分为 {count} 格",
+ "@keyboardRowGridDescription": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDecreaseRowButtonsTooltip": "减少每行按键数",
+ "keyboardIncreaseRowButtonsTooltip": "增加每行按键数",
+ "keyboardPageKeysSectionTitle": "页面按键",
+ "keyboardAddNewRow": "添加新行",
+ "keyboardEmptyPageKeysHint": "当前页面暂无按键行",
+ "keyboardEmptyRowKeysHint": "行内暂无按键,点击上方“+”添加",
+ "keyboardRowKeyCount": "{count} 个按键",
+ "@keyboardRowKeyCount": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardAddKeyTooltip": "添加按键",
+ "keyboardDeleteRowTooltip": "删除整行",
+ "keyboardEditKeyTooltip": "编辑按键",
+ "keyboardDeleteKeyTooltip": "删除按键",
+ "keyboardNoLabel": "(无标签)",
+ "keyboardResetDefaultTitle": "恢复默认配置",
+ "keyboardResetDefaultContent": "确定要将小键盘恢复为初始默认预设吗?当前自定义修改将被覆盖。",
+ "keyboardResetDefaultSuccess": "已恢复默认预设",
+ "keyboardDeletePageTitle": "删除页面",
+ "keyboardDeletePageContent": "确定要删除“第 {page} 页”吗?",
+ "@keyboardDeletePageContent": {
+ "placeholders": {
+ "page": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDeleteRowTitle": "删除按键行",
+ "keyboardDeleteRowContent": "确定要删除“第 {row} 行”及其包含的所有按键吗?",
+ "@keyboardDeleteRowContent": {
+ "placeholders": {
+ "row": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardDeleteKeyTitle": "删除按键",
+ "keyboardDeleteKeyContent": "确定要删除按键“{key}”吗?",
+ "@keyboardDeleteKeyContent": {
+ "placeholders": {
+ "key": {
+ "type": "String"
+ }
+ }
+ },
+ "keyboardKeepAtLeastOnePageWarning": "至少需要保留一个页面",
+ "keyboardRowMaxKeysWarning": "当前存在包含 {count} 个按键的行,行按钮数不能小于 {count}",
+ "@keyboardRowMaxKeysWarning": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardRowReachedMaxWarning": "当前行按键数已达到上限(最多 {count} 个按键)",
+ "@keyboardRowReachedMaxWarning": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "keyboardAddKeyTitle": "添加按键",
+ "keyboardEditKeyTitle": "编辑按键",
+ "keyboardLabelFormField": "显示文本 (Label)",
+ "keyboardLabelFormFieldHint": "按键上显示的文本,如 Tab、()、A",
+ "keyboardLabelOrIconRequiredError": "请输入显示文本或选择图标",
+ "keyboardIconFormField": "图标 (Icon, 可选)",
+ "keyboardNoIconOption": "无图标 (使用文本显示)",
+ "keyboardActionFormField": "动作类型 (Action)",
+ "keyboardValueFormField": "输入文本内容 (Value)",
+ "keyboardValueFormFieldHint": "点击后直接插入的文本,如 ;、=、->",
+ "keyboardValueRequiredError": "输入文本不能为空",
+ "keyboardPairPresetFormField": "成对符号预设 (Value)",
+ "keyboardCommandPresetFormField": "预设编辑器命令 (Value)",
+ "keyboardModifierPresetFormField": "终端修饰键 (Value)",
+ "keyboardTerminalKeyPresetFormField": "终端按键 (Value)",
+ "keyboardCursorOffsetFormField": "光标相对偏移 (cursorOffset)",
+ "keyboardCursorOffsetHelper": "例如 () 插入后光标居中需向左偏移 1 位,填写 -1",
+ "keyboardCursorOffsetRequiredError": "请输入光标偏移(通常为 -1)",
+ "keyboardCursorOffsetIntegerError": "偏移量必须为整数"
}
\ No newline at end of file
diff --git a/lib/main.dart b/lib/main.dart
index 9c1206c..d387e73 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -8,7 +8,15 @@ import 'package:code_editor/views/main_view.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
+import 'package:flutter/services.dart';
+
void main() {
+ WidgetsFlutterBinding.ensureInitialized();
+ SystemChrome.setSystemUIOverlayStyle(
+ const SystemUiOverlayStyle(
+ statusBarColor: Colors.transparent,
+ ),
+ );
runApp(const MyApp());
}
@@ -57,6 +65,13 @@ class MyApp extends StatelessWidget {
seedColor: Colors.blue,
brightness: Brightness.light,
),
+ appBarTheme: const AppBarTheme(
+ systemOverlayStyle: SystemUiOverlayStyle(
+ statusBarColor: Colors.transparent,
+ statusBarIconBrightness: Brightness.dark,
+ statusBarBrightness: Brightness.light,
+ ),
+ ),
fontFamily: settings.uiFont.fontFamily,
fontFamilyFallback: settings.uiFont.fallback,
),
@@ -67,6 +82,13 @@ class MyApp extends StatelessWidget {
seedColor: Colors.blue,
brightness: Brightness.dark,
),
+ appBarTheme: const AppBarTheme(
+ systemOverlayStyle: SystemUiOverlayStyle(
+ statusBarColor: Colors.transparent,
+ statusBarIconBrightness: Brightness.light,
+ statusBarBrightness: Brightness.dark,
+ ),
+ ),
fontFamily: settings.uiFont.fontFamily,
fontFamilyFallback: settings.uiFont.fallback,
),
diff --git a/lib/models/app_font.dart b/lib/models/app_font.dart
index fe6f793..a8d215b 100644
--- a/lib/models/app_font.dart
+++ b/lib/models/app_font.dart
@@ -237,14 +237,14 @@ class AppFonts {
static AppFontItem getEditorFont(String? id) {
return editorFonts.firstWhere(
(f) => f.id == id,
- orElse: () => editorMonospace,
+ orElse: () => editorJetBrainsMono,
);
}
static AppFontItem getTerminalFont(String? id) {
return terminalFonts.firstWhere(
(f) => f.id == id,
- orElse: () => terminalMonospace,
+ orElse: () => terminalJetBrainsMono,
);
}
}
diff --git a/lib/models/virtual_keyboard_config.dart b/lib/models/virtual_keyboard_config.dart
index 5907a22..cd9de94 100644
--- a/lib/models/virtual_keyboard_config.dart
+++ b/lib/models/virtual_keyboard_config.dart
@@ -7,6 +7,8 @@ class KeyboardIconHelper {
'undo': Icons.undo,
'redo': Icons.redo,
'tab': Icons.keyboard_tab,
+ 'untab': Icons.format_indent_decrease,
+ 'outdent': Icons.format_indent_decrease,
'arrow_left': Icons.arrow_back,
'arrow_right': Icons.arrow_forward,
'arrow_up': Icons.arrow_upward,
@@ -33,6 +35,114 @@ class KeyboardIconHelper {
static List get supportedIconKeys => _icons.keys.toList();
}
+/// 虚拟小键盘作用域(编辑区或终端)
+enum KeyboardScope {
+ editor,
+ terminal;
+
+ String get displayName {
+ switch (this) {
+ case KeyboardScope.editor:
+ return '编辑区';
+ case KeyboardScope.terminal:
+ return '终端';
+ }
+ }
+}
+
+/// 按键动作定义项辅助
+class KeyboardActionOption {
+ final String action;
+ final String label;
+ final String description;
+
+ const KeyboardActionOption({
+ required this.action,
+ required this.label,
+ required this.description,
+ });
+}
+
+/// 预设值选项辅助
+class KeyboardValueOption {
+ final String value;
+ final String label;
+
+ const KeyboardValueOption({
+ required this.value,
+ required this.label,
+ });
+}
+
+/// 作用域对应的动作与预设值定义
+class KeyboardScopeHelper {
+ /// 编辑区支持的动作类型
+ static const List editorActions = [
+ KeyboardActionOption(action: 'input', label: '普通文本 (input)', description: '直接插入指定文本内容'),
+ KeyboardActionOption(action: 'pair', label: '成对符号 (pair)', description: '括号/引号等成对符号,支持选区包裹与光标偏移'),
+ KeyboardActionOption(action: 'command', label: '编辑器命令 (command)', description: '触发缩进、撤销、光标移动等编辑器功能'),
+ ];
+
+ /// 终端支持的动作类型
+ static const List terminalActions = [
+ KeyboardActionOption(action: 'input', label: '普通文本 (input)', description: '直接向终端发送指定文本'),
+ KeyboardActionOption(action: 'modifier', label: '修饰键 (modifier)', description: 'Ctrl / Alt 等组合修饰键状态切换'),
+ KeyboardActionOption(action: 'terminal_key', label: '终端按键 (terminal_key)', description: 'Esc、Tab、Ctrl+C、方向键等终端特殊键'),
+ ];
+
+ /// 编辑区预设命令列表
+ static const List editorCommands = [
+ KeyboardValueOption(value: 'tab', label: 'Tab (向右缩进)'),
+ KeyboardValueOption(value: 'untab', label: 'Untab (向左缩进)'),
+ KeyboardValueOption(value: 'undo', label: '撤销 (Undo)'),
+ KeyboardValueOption(value: 'redo', label: '重做 (Redo)'),
+ KeyboardValueOption(value: 'cursor_left', label: '光标左移'),
+ KeyboardValueOption(value: 'cursor_right', label: '光标右移'),
+ KeyboardValueOption(value: 'cursor_up', label: '光标上移'),
+ KeyboardValueOption(value: 'cursor_down', label: '光标下移'),
+ KeyboardValueOption(value: 'line_start', label: '移动至行首'),
+ KeyboardValueOption(value: 'line_end', label: '移动至行尾'),
+ KeyboardValueOption(value: 'page_start', label: '移动至文首'),
+ KeyboardValueOption(value: 'page_end', label: '移动至文末'),
+ KeyboardValueOption(value: 'copy', label: '复制 (Copy)'),
+ KeyboardValueOption(value: 'cut', label: '剪切 (Cut)'),
+ KeyboardValueOption(value: 'paste', label: '粘贴 (Paste)'),
+ KeyboardValueOption(value: 'delete', label: '删除 (Delete)'),
+ KeyboardValueOption(value: 'select_all', label: '全选 (Select All)'),
+ KeyboardValueOption(value: 'keyboard_hide', label: '收起小键盘'),
+ ];
+
+ /// 编辑区成对符号预设列表
+ static const List editorPairs = [
+ KeyboardValueOption(value: '()', label: '圆括号 ()'),
+ KeyboardValueOption(value: '[]', label: '方括号 []'),
+ KeyboardValueOption(value: '{}', label: '花括号 {}'),
+ KeyboardValueOption(value: '""', label: '双引号 ""'),
+ KeyboardValueOption(value: "''", label: "单引号 ''"),
+ KeyboardValueOption(value: '<>', label: '尖括号 <>'),
+ ];
+
+ /// 终端修饰键预设列表
+ static const List terminalModifiers = [
+ KeyboardValueOption(value: 'ctrl', label: 'Ctrl 键'),
+ KeyboardValueOption(value: 'alt', label: 'Alt 键'),
+ ];
+
+ /// 终端按键预设列表
+ static const List terminalKeys = [
+ KeyboardValueOption(value: 'esc', label: 'Esc (退出键)'),
+ KeyboardValueOption(value: 'terminal_tab', label: 'Tab (补全键)'),
+ KeyboardValueOption(value: 'ctrl_c', label: 'Ctrl + C (中断信号)'),
+ KeyboardValueOption(value: 'ctrl_d', label: 'Ctrl + D (EOF / 退出)'),
+ KeyboardValueOption(value: 'ctrl_z', label: 'Ctrl + Z (挂起挂起)'),
+ KeyboardValueOption(value: 'ctrl_l', label: 'Ctrl + L (清屏)'),
+ KeyboardValueOption(value: 'arrow_up', label: '方向上键 (历史上一条)'),
+ KeyboardValueOption(value: 'arrow_down', label: '方向下键 (历史下一条)'),
+ KeyboardValueOption(value: 'arrow_left', label: '方向左键'),
+ KeyboardValueOption(value: 'arrow_right', label: '方向右键'),
+ ];
+}
+
/// 小键盘单个按键数据模型
class KeyboardKeyItem {
/// 显示文本(当 icon 为空或不存在时渲染)
@@ -45,6 +155,8 @@ class KeyboardKeyItem {
/// - 'input': 普通文本输入(默认)
/// - 'pair': 括号/引号等成对符号,支持选区包裹与光标偏移
/// - 'command': 编辑器动作命令,例如 'cursor_left', 'tab', 'undo' 等
+ /// - 'modifier': 终端修饰键,如 'ctrl', 'alt'
+ /// - 'terminal_key': 终端按键,如 'esc', 'ctrl_c'
final String action;
/// 动作附带值(输入的文本或命令名称)
@@ -61,6 +173,23 @@ class KeyboardKeyItem {
this.cursorOffset = 0,
});
+ KeyboardKeyItem copyWith({
+ String? label,
+ String? icon,
+ bool clearIcon = false,
+ String? action,
+ String? value,
+ int? cursorOffset,
+ }) {
+ return KeyboardKeyItem(
+ label: label ?? this.label,
+ icon: clearIcon ? null : (icon ?? this.icon),
+ action: action ?? this.action,
+ value: value ?? this.value,
+ cursorOffset: cursorOffset ?? this.cursorOffset,
+ );
+ }
+
/// 从 JSON 数据中解析按键:
/// - 若为 String:严格转换为 input 动作,label 和 value 为该字符串,绝对不做额外猜测!
/// - 若为 Map:读取相应字段。
@@ -119,6 +248,16 @@ class KeyboardPageItem {
required this.keys,
});
+ KeyboardPageItem copyWith({
+ int? count,
+ List>? keys,
+ }) {
+ return KeyboardPageItem(
+ count: count ?? this.count,
+ keys: keys ?? this.keys,
+ );
+ }
+
factory KeyboardPageItem.fromJson(Map json) {
final count = (json['count'] as num?)?.toInt() ?? 6;
final rawKeys = json['keys'] as List? ?? [];
@@ -152,7 +291,18 @@ class VirtualKeyboardConfig {
required this.pages,
});
+ VirtualKeyboardConfig copyWith({
+ List? pages,
+ }) {
+ return VirtualKeyboardConfig(
+ pages: pages ?? this.pages,
+ );
+ }
+
factory VirtualKeyboardConfig.fromJson(Map json) {
+ if (!json.containsKey('pages')) {
+ return _defaultConfig();
+ }
final rawPages = json['pages'] as List? ?? [];
final List parsedPages = [];
@@ -163,10 +313,26 @@ class VirtualKeyboardConfig {
}
return VirtualKeyboardConfig(
- pages: parsedPages.isNotEmpty ? parsedPages : _defaultConfig().pages,
+ pages: parsedPages,
);
}
+ /// 判断当前配置是否包含至少一个有效按键
+ bool get hasKeys {
+ for (final page in pages) {
+ for (final row in page.keys) {
+ for (final key in row) {
+ if (key.label.trim().isNotEmpty ||
+ (key.icon != null && key.icon!.trim().isNotEmpty) ||
+ key.value.trim().isNotEmpty) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
Map toJson() {
return {
'pages': pages.map((p) => p.toJson()).toList(),
@@ -285,47 +451,51 @@ class VirtualKeyboardConfig {
static VirtualKeyboardConfig _defaultConfig() {
return const VirtualKeyboardConfig(
pages: [
- // Page 1: 常用标点与成对符号 (每行 6 格)
+ // Page 1: 常用控制、括号与高频符号 (每行 7 格)
KeyboardPageItem(
- count: 6,
+ count: 7,
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: 'Untab', icon: 'untab', action: 'command', value: 'untab'),
+ KeyboardKeyItem(label: '()', action: 'pair', value: '()', cursorOffset: -1),
+ KeyboardKeyItem(label: '[]', action: 'pair', value: '[]', cursorOffset: -1),
+ KeyboardKeyItem(label: '{}', action: 'pair', value: '{}', cursorOffset: -1),
+ KeyboardKeyItem(label: '撤销', icon: 'undo', action: 'command', value: 'undo'),
+ KeyboardKeyItem(label: '重做', icon: 'redo', action: 'command', value: 'redo'),
],
[
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),
+ KeyboardKeyItem(label: '""', action: 'pair', value: '""', cursorOffset: -1),
+ KeyboardKeyItem(label: "''", action: 'pair', value: "''", cursorOffset: -1),
+ KeyboardKeyItem(label: ';', action: 'input', value: ';'),
+ KeyboardKeyItem(label: '=', action: 'input', value: '='),
+ KeyboardKeyItem(label: ',', action: 'input', value: ','),
],
],
),
- // Page 2: 常用操作与运算符 (每行 6 格)
+ // Page 2: 常用代码符号与运算符 (每行 7 格)
KeyboardPageItem(
- count: 6,
+ count: 7,
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: r'\', action: 'input', value: r'\'),
+ 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: '?'),
+ KeyboardKeyItem(label: '&', action: 'input', value: '&'),
+ KeyboardKeyItem(label: '|', action: 'input', value: '|'),
],
],
),
diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart
index bf72682..1b1c98c 100644
--- a/lib/providers/settings_provider.dart
+++ b/lib/providers/settings_provider.dart
@@ -29,11 +29,11 @@ class SettingsProvider extends ChangeNotifier {
ThemeMode _appThemeMode = ThemeMode.system;
String _uiFontId = 'system_default';
EditorTheme _editorTheme = EditorTheme.atomOneDark;
- String _editorFontId = 'monospace';
- String _terminalFontId = 'monospace';
+ String _editorFontId = 'jetbrains_mono';
+ String _terminalFontId = 'jetbrains_mono';
double _fontSize = 14.0;
- int _indentSize = 2;
- bool _wordWrap = true;
+ int _indentSize = 4;
+ bool _wordWrap = false;
bool _enableVirtualKeyboard = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS;
String _virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty();
VirtualKeyboardConfig _virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration();
diff --git a/lib/providers/tab_provider.dart b/lib/providers/tab_provider.dart
index 341d13b..2383924 100644
--- a/lib/providers/tab_provider.dart
+++ b/lib/providers/tab_provider.dart
@@ -79,7 +79,8 @@ class TabProvider extends ChangeNotifier {
if (loadedTabs.isEmpty && lastOpenedFilePath != null && lastOpenedFilePath.trim().isNotEmpty) {
final cleanLast = p.normalize(lastOpenedFilePath.trim());
- if (await FileService.instance.entityExists(cleanLast)) {
+ final wasExplicitlyClosed = openFilePaths.isNotEmpty && !openFilePaths.any((pStr) => p.equals(p.normalize(pStr), cleanLast));
+ if (!wasExplicitlyClosed && await FileService.instance.entityExists(cleanLast)) {
loadedTabs.add(EditorTabItem(
path: cleanLast,
isModified: false,
@@ -373,6 +374,14 @@ class TabProvider extends ChangeNotifier {
return true;
}
+ /// 根据文件路径安全关闭指定标签页(避免由于并发动画或索引错位导致的越界异常)
+ Future closeTabByPath(BuildContext context, String path) async {
+ final cleanPath = p.normalize(path.trim());
+ final index = _openTabs.indexWhere((t) => p.equals(t.path, cleanPath));
+ if (index == -1) return false;
+ return closeTab(context, index);
+ }
+
/// 关闭所有打开的标签页
Future closeAllTabs(BuildContext context) async {
if (_openTabs.isEmpty) return true;
diff --git a/lib/services/distro_installer.dart b/lib/services/distro_installer.dart
index 34ed601..a22686b 100644
--- a/lib/services/distro_installer.dart
+++ b/lib/services/distro_installer.dart
@@ -163,6 +163,7 @@ class DistroInstaller {
static const String guestResolvConf = '# Generated by CodeEditor\n'
'nameserver 223.5.5.5\n'
'nameserver 119.29.29.29\n'
+ 'nameserver 1.1.1.1\n'
'nameserver 114.114.114.114\n';
/// 自动化环境补丁与配置
diff --git a/lib/services/file_service.dart b/lib/services/file_service.dart
index 7d724d2..c9c9fe8 100644
--- a/lib/services/file_service.dart
+++ b/lib/services/file_service.dart
@@ -125,7 +125,7 @@ class FileService {
final ext = p.extension(path).toLowerCase();
if(_binaryExtensions.contains(ext)) {
- throw const FileSystemException('此文件是二进制可执行文件或多媒体文件,不支持作为文本编辑');
+ throw FileSystemException('此文件是二进制可执行文件或多媒体文件,不支持作为文本编辑', path);
}
final length = await file.length();
diff --git a/lib/services/project_history_service.dart b/lib/services/project_history_service.dart
index b8c583a..d054388 100644
--- a/lib/services/project_history_service.dart
+++ b/lib/services/project_history_service.dart
@@ -26,9 +26,13 @@ class ProjectHistoryService {
List? resolvedOpenFiles = openFilePaths;
if(existingIndex != -1) {
- resolvedFile ??= history[existingIndex].lastOpenedFilePath;
+ if (openFilePaths == null) {
+ resolvedFile ??= history[existingIndex].lastOpenedFilePath;
+ resolvedOpenFiles ??= history[existingIndex].openFilePaths;
+ } else if (openFilePaths.isEmpty) {
+ resolvedFile = null;
+ }
resolvedOpenDirs ??= history[existingIndex].openDirectoryPaths;
- resolvedOpenFiles ??= history[existingIndex].openFilePaths;
history.removeAt(existingIndex);
}
diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart
index 82e0d22..cf4fe96 100644
--- a/lib/views/settings_view.dart
+++ b/lib/views/settings_view.dart
@@ -1,14 +1,11 @@
-import 'dart:convert';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/editor_theme.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:code_editor/providers/settings_provider.dart';
-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';
+import 'virtual_keyboard_config_view.dart';
/// 设置页面
class SettingsView extends StatelessWidget {
@@ -671,197 +668,19 @@ class SettingsView extends StatelessWidget {
subtitle: Text(l10n.editVirtualKeyboardConfigSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
- _showKeyboardConfigDialog(context, provider, l10n);
- },
- );
- }
-
- void _showKeyboardConfigDialog(
- BuildContext context,
- SettingsProvider provider,
- AppLocalizations l10n,
- ) {
- final codeController = CodeLineEditingController.fromText(provider.virtualKeyboardConfigJson);
- String? validationError;
-
- showDialog(
- context: context,
- barrierDismissible: false,
- builder: (dialogContext) {
- return StatefulBuilder(
- builder: (context, setDialogState) {
- final theme = Theme.of(context);
- final activeTheme = provider.editorTheme;
-
- return AlertDialog(
- title: Text(l10n.virtualKeyboardDialogTitle),
- content: SizedBox(
- width: 680,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (validationError != null)
- Container(
- width: double.infinity,
- margin: const EdgeInsets.only(bottom: 12),
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
- decoration: BoxDecoration(
- color: theme.colorScheme.errorContainer,
- borderRadius: BorderRadius.circular(8),
- border: Border.all(color: theme.colorScheme.error, width: 0.8),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Icon(Icons.error_outline, size: 18, color: theme.colorScheme.error),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- validationError!,
- style: TextStyle(
- color: theme.colorScheme.onErrorContainer,
- fontSize: 13,
- fontWeight: FontWeight.w500,
- ),
- ),
- ),
- ],
- ),
- ),
- Flexible(
- child: Container(
- height: 360,
- decoration: BoxDecoration(
- color: activeTheme.backgroundColor,
- borderRadius: BorderRadius.circular(8),
- border: Border.all(
- color: validationError != null
- ? theme.colorScheme.error
- : theme.colorScheme.outlineVariant,
- ),
- ),
- clipBehavior: Clip.antiAlias,
- child: CodeEditor(
- controller: codeController,
- wordWrap: false,
- style: CodeEditorStyle(
- fontSize: 13,
- textColor: activeTheme.textColor,
- backgroundColor: activeTheme.backgroundColor,
- cursorColor: activeTheme.cursorColor,
- cursorLineColor: activeTheme.cursorLineColor,
- selectionColor: activeTheme.selectionColor,
- fontFamily: 'Consolas, Monaco, "Courier New", monospace',
- codeTheme: CodeHighlightTheme(
- languages: SyntaxHighlightHelper.getLanguagesForFile('config.json'),
- theme: activeTheme.highlightTheme,
- ),
- ),
- indicatorBuilder: (context, editingController, chunkController, notifier) {
- return Row(
- children: [
- DefaultCodeLineNumber(
- controller: editingController,
- notifier: notifier,
- textStyle: TextStyle(
- color: activeTheme.gutterTextColor,
- fontSize: 12,
- fontFamily: 'Consolas, Monaco, "Courier New", monospace',
- ),
- focusedTextStyle: TextStyle(
- color: activeTheme.focusedGutterTextColor,
- fontSize: 12,
- fontWeight: FontWeight.bold,
- fontFamily: 'Consolas, Monaco, "Courier New", monospace',
- ),
- ),
- DefaultCodeChunkIndicator(
- width: 16,
- controller: chunkController,
- notifier: notifier,
- painter: DefaultCodeChunkIndicatorPainter(
- color: activeTheme.gutterTextColor,
- ),
- ),
- ],
- );
- },
- ),
- ),
- ),
- const SizedBox(height: 8),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- TextButton.icon(
- icon: const Icon(Icons.restore, size: 16),
- label: Text(l10n.resetDefault),
- onPressed: () {
- setDialogState(() {
- codeController.text = VirtualKeyboardConfig.defaultJsonPretty();
- validationError = null;
- });
- },
- ),
- TextButton.icon(
- icon: const Icon(Icons.format_align_left, size: 16),
- label: Text(l10n.formatJson),
- onPressed: () {
- final err = VirtualKeyboardConfig.validateJson(codeController.text);
- if (err != null) {
- setDialogState(() {
- validationError = err;
- });
- } else {
- try {
- final decoded = jsonDecode(codeController.text);
- final encoder = JsonEncoder.withIndent(' ' * provider.indentSize);
- 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),
- ),
- ],
- );
- },
+ Navigator.of(context).push(
+ MaterialPageRoute(
+ builder: (_) => const VirtualKeyboardConfigView(
+ scope: KeyboardScope.editor,
+ ),
+ ),
);
},
);
}
+
+
/// 语言:应用语言选择条目
Widget _buildLanguageTile(
BuildContext context,
diff --git a/lib/views/virtual_keyboard_config_view.dart b/lib/views/virtual_keyboard_config_view.dart
new file mode 100644
index 0000000..b4d6e83
--- /dev/null
+++ b/lib/views/virtual_keyboard_config_view.dart
@@ -0,0 +1,616 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'dart:convert';
+import '../l10n/app_localizations.dart';
+import '../models/virtual_keyboard_config.dart';
+import '../providers/settings_provider.dart';
+import '../utils/dialog_utils.dart';
+import '../widgets/virtual_keyboard_page_drawer.dart';
+import '../widgets/virtual_keyboard_page_config_section.dart';
+import '../widgets/virtual_keyboard_row_tile.dart';
+import '../widgets/virtual_keyboard_key_edit_dialog.dart';
+
+/// 虚拟小键盘图形化配置视图
+class VirtualKeyboardConfigView extends StatefulWidget {
+ final KeyboardScope scope;
+
+ const VirtualKeyboardConfigView({
+ super.key,
+ this.scope = KeyboardScope.editor,
+ });
+
+ @override
+ State createState() => _VirtualKeyboardConfigViewState();
+}
+
+class _VirtualKeyboardConfigViewState extends State {
+ final GlobalKey _scaffoldKey = GlobalKey();
+ final ScrollController _pageScrollController = ScrollController();
+
+ /// 当前工作区正在编辑的页面索引 (0-indexed)
+ int _currentPageIndex = 0;
+
+ /// 本地维护的工作副本,实时同步至 SettingsProvider
+ late VirtualKeyboardConfig _config;
+
+ /// 页面内部行展开状态缓存:`pageIndex` -> `Set`
+ final Map> _expandedRowsByPage = {};
+
+ /// 页面滚动偏移量缓存:pageIndex -> double
+ final Map _scrollOffsetByPage = {};
+
+ @override
+ void initState() {
+ super.initState();
+ final settingsProvider = context.read();
+ _config = settingsProvider.virtualKeyboardConfig;
+ if (_currentPageIndex >= _config.pages.length) {
+ _currentPageIndex = 0;
+ }
+ }
+
+ @override
+ void dispose() {
+ _pageScrollController.dispose();
+ super.dispose();
+ }
+
+ /// 切换当前页面并恢复该页面的滚动位置
+ void _selectPage(int index) {
+ if (_currentPageIndex == index) return;
+
+ if (_pageScrollController.hasClients) {
+ _scrollOffsetByPage[_currentPageIndex] = _pageScrollController.offset;
+ }
+
+ setState(() {
+ _currentPageIndex = index;
+ });
+
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (_pageScrollController.hasClients) {
+ final targetOffset = _scrollOffsetByPage[index] ?? 0.0;
+ final maxScroll = _pageScrollController.position.maxScrollExtent;
+ final clampedOffset = targetOffset.clamp(0.0, maxScroll);
+ _pageScrollController.jumpTo(clampedOffset);
+ }
+ });
+ }
+
+ /// 保存并同步到 SettingsProvider
+ Future _syncAndSaveConfig() async {
+ final settingsProvider = context.read();
+ const encoder = JsonEncoder.withIndent(' ');
+ final jsonStr = encoder.convert(_config.toJson());
+ await settingsProvider.setVirtualKeyboardConfig(jsonStr);
+ }
+
+ /// 恢复默认配置
+ Future _resetToDefault() async {
+ final l10n = AppLocalizations.of(context)!;
+ final confirmed = await showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l10n.keyboardResetDefaultTitle),
+ content: Text(l10n.keyboardResetDefaultContent),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(ctx).pop(false),
+ child: Text(l10n.cancel),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.of(ctx).pop(true),
+ child: Text(l10n.resetDefault),
+ ),
+ ],
+ ),
+ );
+
+ if (confirmed == true) {
+ if (!mounted) return;
+ final settingsProvider = context.read();
+ await settingsProvider.resetVirtualKeyboardConfig();
+ if (!mounted) return;
+ setState(() {
+ _config = settingsProvider.virtualKeyboardConfig;
+ _currentPageIndex = 0;
+ _expandedRowsByPage.clear();
+ _scrollOffsetByPage.clear();
+ });
+ if (_pageScrollController.hasClients) {
+ _pageScrollController.jumpTo(0.0);
+ }
+ DialogUtils.showToast(context, l10n.keyboardResetDefaultSuccess, type: ToastType.success);
+ }
+ }
+
+ /// 添加新页面
+ void _addNewPage() {
+ final newPageIndex = _config.pages.length;
+ if (_pageScrollController.hasClients) {
+ _scrollOffsetByPage[_currentPageIndex] = _pageScrollController.offset;
+ }
+
+ setState(() {
+ final newPage = KeyboardPageItem(
+ count: 7,
+ keys: [
+ [
+ const KeyboardKeyItem(label: 'New', value: 'New'),
+ ],
+ ],
+ );
+ final newPages = List.from(_config.pages)..add(newPage);
+ _config = _config.copyWith(pages: newPages);
+ _currentPageIndex = newPageIndex;
+ _expandedRowsByPage[newPageIndex] = {};
+ _scrollOffsetByPage[newPageIndex] = 0.0;
+ });
+
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (_pageScrollController.hasClients) {
+ _pageScrollController.jumpTo(0.0);
+ }
+ });
+
+ _syncAndSaveConfig();
+ }
+
+ /// 删除指定页面
+ void _deletePage(int pageIndex) {
+ final l10n = AppLocalizations.of(context)!;
+ if (_config.pages.length <= 1) {
+ DialogUtils.showToast(context, l10n.keyboardKeepAtLeastOnePageWarning, type: ToastType.warning);
+ return;
+ }
+
+ showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l10n.keyboardDeletePageTitle),
+ content: Text(l10n.keyboardDeletePageContent(pageIndex + 1)),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(ctx).pop(false),
+ child: Text(l10n.cancel),
+ ),
+ FilledButton(
+ style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
+ onPressed: () => Navigator.of(ctx).pop(true),
+ child: Text(l10n.delete),
+ ),
+ ],
+ ),
+ ).then((confirmed) {
+ if (confirmed == true) {
+ setState(() {
+ final newPages = List.from(_config.pages)..removeAt(pageIndex);
+ _config = _config.copyWith(pages: newPages);
+
+ _expandedRowsByPage.remove(pageIndex);
+ _scrollOffsetByPage.remove(pageIndex);
+
+ if (_currentPageIndex >= newPages.length) {
+ _currentPageIndex = newPages.length - 1;
+ }
+ });
+ _syncAndSaveConfig();
+ }
+ });
+ }
+
+ /// 页面拖拽重排序
+ void _reorderPages(int oldIndex, int newIndex) {
+ setState(() {
+ final newPages = List.from(_config.pages);
+ final item = newPages.removeAt(oldIndex);
+ newPages.insert(newIndex, item);
+
+ final oldExpanded = _expandedRowsByPage.remove(oldIndex);
+ final oldOffset = _scrollOffsetByPage.remove(oldIndex);
+
+ if (_currentPageIndex == oldIndex) {
+ _currentPageIndex = newIndex;
+ } else if (_currentPageIndex > oldIndex && _currentPageIndex <= newIndex) {
+ _currentPageIndex -= 1;
+ } else if (_currentPageIndex < oldIndex && _currentPageIndex >= newIndex) {
+ _currentPageIndex += 1;
+ }
+
+ if (oldExpanded != null) {
+ _expandedRowsByPage[newIndex] = oldExpanded;
+ }
+ if (oldOffset != null) {
+ _scrollOffsetByPage[newIndex] = oldOffset;
+ }
+
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+
+ /// 修改当前页的 count(减小时,最大行按键数不能大于目标按键数)
+ void _updateCurrentPageCount(int newCount) {
+ if (newCount < 1 || newCount > 12) return;
+ final page = _config.pages[_currentPageIndex];
+
+ if (newCount < page.count) {
+ int maxKeysInRows = 0;
+ for (final row in page.keys) {
+ if (row.length > maxKeysInRows) {
+ maxKeysInRows = row.length;
+ }
+ }
+ if (maxKeysInRows > newCount) {
+ final l10n = AppLocalizations.of(context)!;
+ DialogUtils.showToast(
+ context,
+ l10n.keyboardRowMaxKeysWarning(maxKeysInRows),
+ type: ToastType.warning,
+ );
+ return;
+ }
+ }
+
+ setState(() {
+ final updatedPage = page.copyWith(count: newCount);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+
+ /// 向当前页添加一行
+ void _addNewRow() {
+ setState(() {
+ final page = _config.pages[_currentPageIndex];
+ final newKeys = List>.from(page.keys);
+ newKeys.add([]);
+ final updatedPage = page.copyWith(keys: newKeys);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+
+ /// 删除当前页的指定行(带二次确认弹窗)
+ void _deleteRow(int rowIndex) {
+ final l10n = AppLocalizations.of(context)!;
+ showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l10n.keyboardDeleteRowTitle),
+ content: Text(l10n.keyboardDeleteRowContent(rowIndex + 1)),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(ctx).pop(false),
+ child: Text(l10n.cancel),
+ ),
+ FilledButton(
+ style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
+ onPressed: () => Navigator.of(ctx).pop(true),
+ child: Text(l10n.delete),
+ ),
+ ],
+ ),
+ ).then((confirmed) {
+ if (confirmed == true) {
+ setState(() {
+ final page = _config.pages[_currentPageIndex];
+ final newKeys = List>.from(page.keys)..removeAt(rowIndex);
+ final updatedPage = page.copyWith(keys: newKeys);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+
+ final expandedSet = _expandedRowsByPage[_currentPageIndex];
+ if (expandedSet != null) {
+ expandedSet.remove(rowIndex);
+ }
+ });
+ _syncAndSaveConfig();
+ }
+ });
+ }
+
+ /// 行拖动重排序
+ void _reorderRows(int oldIndex, int newIndex) {
+ setState(() {
+ final page = _config.pages[_currentPageIndex];
+ final newKeys = List>.from(page.keys);
+ final row = newKeys.removeAt(oldIndex);
+ newKeys.insert(newIndex, row);
+
+ final updatedPage = page.copyWith(keys: newKeys);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+
+ /// 添加或编辑按键
+ Future _openKeyEditDialog({
+ required int rowIndex,
+ int? keyIndex,
+ KeyboardKeyItem? initialKey,
+ }) async {
+ final page = _config.pages[_currentPageIndex];
+ if (keyIndex == null) {
+ final currentRowKeysCount = page.keys[rowIndex].length;
+ if (currentRowKeysCount >= page.count) {
+ final l10n = AppLocalizations.of(context)!;
+ DialogUtils.showToast(
+ context,
+ l10n.keyboardRowReachedMaxWarning(page.count),
+ type: ToastType.warning,
+ );
+ return;
+ }
+ }
+
+ final result = await showDialog(
+ context: context,
+ barrierDismissible: false,
+ builder: (ctx) => KeyEditDialog(
+ scope: widget.scope,
+ initialKey: initialKey,
+ ),
+ );
+
+ if (result != null) {
+ setState(() {
+ final currentPage = _config.pages[_currentPageIndex];
+ final newKeys = List>.from(
+ currentPage.keys.map((row) => List.from(row)),
+ );
+
+ if (keyIndex == null) {
+ newKeys[rowIndex].add(result);
+ } else {
+ newKeys[rowIndex][keyIndex] = result;
+ }
+
+ final updatedPage = currentPage.copyWith(keys: newKeys);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+ }
+
+ /// 删除按键(带二次确认弹窗)
+ void _deleteKey(int rowIndex, int keyIndex) {
+ final page = _config.pages[_currentPageIndex];
+ if (rowIndex >= page.keys.length || keyIndex >= page.keys[rowIndex].length) return;
+ final keyItem = page.keys[rowIndex][keyIndex];
+ final keyName = keyItem.label.isNotEmpty ? keyItem.label : keyItem.value;
+
+ final l10n = AppLocalizations.of(context)!;
+ showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l10n.keyboardDeleteKeyTitle),
+ content: Text(l10n.keyboardDeleteKeyContent(keyName)),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(ctx).pop(false),
+ child: Text(l10n.cancel),
+ ),
+ FilledButton(
+ style: FilledButton.styleFrom(backgroundColor: Theme.of(ctx).colorScheme.error),
+ onPressed: () => Navigator.of(ctx).pop(true),
+ child: Text(l10n.delete),
+ ),
+ ],
+ ),
+ ).then((confirmed) {
+ if (confirmed == true) {
+ setState(() {
+ final currentPage = _config.pages[_currentPageIndex];
+ final newKeys = List>.from(
+ currentPage.keys.map((row) => List.from(row)),
+ );
+ newKeys[rowIndex].removeAt(keyIndex);
+
+ final updatedPage = currentPage.copyWith(keys: newKeys);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+ });
+ }
+
+ /// 行内按键拖动重排序
+ void _reorderKeys(int rowIndex, int oldIndex, int newIndex) {
+ setState(() {
+ final page = _config.pages[_currentPageIndex];
+ final newKeys = List>.from(
+ page.keys.map((row) => List.from(row)),
+ );
+ final item = newKeys[rowIndex].removeAt(oldIndex);
+ newKeys[rowIndex].insert(newIndex, item);
+
+ final updatedPage = page.copyWith(keys: newKeys);
+ final newPages = List.from(_config.pages);
+ newPages[_currentPageIndex] = updatedPage;
+ _config = _config.copyWith(pages: newPages);
+ });
+ _syncAndSaveConfig();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final l10n = AppLocalizations.of(context)!;
+ final currentPage = (_currentPageIndex < _config.pages.length)
+ ? _config.pages[_currentPageIndex]
+ : _config.pages.first;
+
+ final scopeName = widget.scope == KeyboardScope.editor
+ ? l10n.editorScope
+ : l10n.terminalScope;
+ final subtitleText = l10n.virtualKeyboardPageSubtitle(scopeName, _currentPageIndex + 1);
+
+ return Scaffold(
+ key: _scaffoldKey,
+ appBar: AppBar(
+ leading: IconButton(
+ icon: const Icon(Icons.arrow_back),
+ tooltip: l10n.back,
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ title: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ l10n.virtualKeyboardConfigTitle,
+ style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
+ ),
+ Text(
+ subtitleText,
+ style: TextStyle(
+ fontSize: 12,
+ color: theme.colorScheme.onSurface.withValues(alpha: 0.65),
+ ),
+ ),
+ ],
+ ),
+ actions: [
+ IconButton(
+ icon: const Icon(Icons.restore),
+ tooltip: l10n.keyboardRestoreDefaultTooltip,
+ onPressed: _resetToDefault,
+ ),
+ IconButton(
+ icon: const Icon(Icons.layers_outlined),
+ tooltip: l10n.keyboardPageManagementTooltip,
+ onPressed: () {
+ _scaffoldKey.currentState?.openEndDrawer();
+ },
+ ),
+ ],
+ ),
+ endDrawer: VirtualKeyboardPageDrawer(
+ pages: _config.pages,
+ currentPageIndex: _currentPageIndex,
+ onAddNewPage: _addNewPage,
+ onSelectPage: _selectPage,
+ onDeletePage: _deletePage,
+ onReorderPages: _reorderPages,
+ ),
+ body: ListView(
+ controller: _pageScrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ children: [
+ // 板块一:当前页配置
+ VirtualKeyboardPageConfigSection(
+ count: currentPage.count,
+ onCountChanged: _updateCurrentPageCount,
+ ),
+ const SizedBox(height: 20),
+
+ // 板块二:页面按键行管理
+ _buildPageKeysSection(theme, l10n, currentPage),
+ ],
+ ),
+ );
+ }
+
+ /// 板块二:按键行管理
+ Widget _buildPageKeysSection(ThemeData theme, AppLocalizations l10n, KeyboardPageItem currentPage) {
+ final expandedRows = _expandedRowsByPage.putIfAbsent(_currentPageIndex, () => {});
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Row(
+ children: [
+ Icon(Icons.keyboard_alt_outlined, size: 20, color: theme.colorScheme.primary),
+ const SizedBox(width: 8),
+ Text(
+ l10n.keyboardPageKeysSectionTitle,
+ style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
+ ),
+ ],
+ ),
+ TextButton.icon(
+ icon: const Icon(Icons.add, size: 18),
+ label: Text(l10n.keyboardAddNewRow),
+ onPressed: _addNewRow,
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+
+ if (currentPage.keys.isEmpty)
+ Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(24),
+ decoration: BoxDecoration(
+ border: Border.all(color: theme.dividerColor.withValues(alpha: 0.3)),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Column(
+ children: [
+ Icon(Icons.keyboard_outlined, size: 48, color: theme.hintColor.withValues(alpha: 0.5)),
+ const SizedBox(height: 8),
+ Text(l10n.keyboardEmptyPageKeysHint, style: TextStyle(color: theme.hintColor)),
+ const SizedBox(height: 12),
+ FilledButton.tonalIcon(
+ icon: const Icon(Icons.add),
+ label: Text(l10n.keyboardAddNewRow),
+ onPressed: _addNewRow,
+ ),
+ ],
+ ),
+ )
+ else
+ ReorderableListView.builder(
+ shrinkWrap: true,
+ physics: const NeverScrollableScrollPhysics(),
+ buildDefaultDragHandles: false,
+ itemCount: currentPage.keys.length,
+ onReorderItem: _reorderRows,
+ itemBuilder: (context, rowIndex) {
+ final rowKeys = currentPage.keys[rowIndex];
+ final isExpanded = expandedRows.contains(rowIndex);
+
+ return VirtualKeyboardRowTile(
+ key: ValueKey('page_${_currentPageIndex}_row_$rowIndex'),
+ pageIndex: _currentPageIndex,
+ rowIndex: rowIndex,
+ rowKeys: rowKeys,
+ isExpanded: isExpanded,
+ onExpansionChanged: (expanded) {
+ if (expanded) {
+ expandedRows.add(rowIndex);
+ } else {
+ expandedRows.remove(rowIndex);
+ }
+ },
+ onAddKey: () => _openKeyEditDialog(rowIndex: rowIndex),
+ onDeleteRow: () => _deleteRow(rowIndex),
+ onReorderKeys: (oldIdx, newIdx) => _reorderKeys(rowIndex, oldIdx, newIdx),
+ onEditKey: (keyIdx, keyItem) => _openKeyEditDialog(
+ rowIndex: rowIndex,
+ keyIndex: keyIdx,
+ initialKey: keyItem,
+ ),
+ onDeleteKey: (keyIdx) => _deleteKey(rowIndex, keyIdx),
+ );
+ },
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart
index 27d28b7..5b1ba74 100644
--- a/lib/widgets/code_editor_app_bar.dart
+++ b/lib/widgets/code_editor_app_bar.dart
@@ -1,6 +1,7 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/views/terminal_view.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:re_editor/re_editor.dart';
@@ -65,8 +66,15 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
subtitleText = null;
}
+ final isDark = theme.brightness == Brightness.dark;
+
return CodeEditorTapRegion(
child: AppBar(
+ systemOverlayStyle: SystemUiOverlayStyle(
+ statusBarColor: Colors.transparent,
+ statusBarIconBrightness: isDark ? Brightness.light : Brightness.dark,
+ statusBarBrightness: isDark ? Brightness.dark : Brightness.light,
+ ),
backgroundColor: theme.colorScheme.primaryContainer,
foregroundColor: theme.colorScheme.onSurface,
title: Column(
diff --git a/lib/widgets/code_editor_tab_bar.dart b/lib/widgets/code_editor_tab_bar.dart
index 1e362c3..8f4d995 100644
--- a/lib/widgets/code_editor_tab_bar.dart
+++ b/lib/widgets/code_editor_tab_bar.dart
@@ -43,11 +43,11 @@ class CodeEditorTabBar extends StatelessWidget {
)..layout();
// 实际所需完整宽度(向上取整避免浮点精度缺失):
- // 文本宽度 + 脏标记 (12.0) + 内外间距与关闭按钮 (33.0) + 安全呼吸缓冲空间 (16.0)
+ // 文本宽度 + 脏标记 (10.0) + 内外间距与关闭按钮 (26.0) + 安全缓冲空间 (10.0)
final textWidth = textPainter.width.ceilToDouble();
- final dirtyWidth = isModified ? 12.0 : 0.0;
- const fixedElementsWidth = 33.0; // 容器内边距(8) + 关闭按钮(24) + 边框(1)
- const safetyBuffer = 16.0; // 安全呼吸空间,杜绝亚像素及字体微偏差导致的省略号
+ final dirtyWidth = isModified ? 10.0 : 0.0;
+ const fixedElementsWidth = 26.0; // 容器内边距(8) + 关闭按钮(18)
+ const safetyBuffer = 10.0; // 安全呼吸空间
return textWidth + dirtyWidth + fixedElementsWidth + safetyBuffer;
}
@@ -67,7 +67,7 @@ class CodeEditorTabBar extends StatelessWidget {
return CodeEditorTapRegion(
child: Container(
- height: 36.0,
+ height: 28.0,
width: double.infinity,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.2),
@@ -94,9 +94,16 @@ class CodeEditorTabBar extends StatelessWidget {
buildDefaultDragHandles: false,
itemCount: tabs.length,
onReorderItem: (oldIndex, newIndex) {
- tabProvider.reorderTabs(oldIndex, newIndex);
+ int targetIndex = newIndex;
+ if (oldIndex < newIndex) {
+ targetIndex -= 1;
+ }
+ tabProvider.reorderTabs(oldIndex, targetIndex);
},
itemBuilder: (context, index) {
+ if (index < 0 || index >= tabs.length) {
+ return const SizedBox.shrink(key: ValueKey('empty_tab_placeholder'));
+ }
final tab = tabs[index];
final isSelected = activePath != null && tab.path == activePath;
final displayName = tab.getDisplayName(tabs, rootPath);
@@ -142,7 +149,7 @@ class CodeEditorTabBar extends StatelessWidget {
index: index,
child: Container(
width: width,
- height: 36.0,
+ height: 28.0,
decoration: BoxDecoration(
color: isSelected
? theme.colorScheme.surface
@@ -153,11 +160,11 @@ class CodeEditorTabBar extends StatelessWidget {
width: 1.0,
),
bottom: isSelected
- ? BorderSide(
- color: theme.colorScheme.primary,
- width: 2.0,
- )
- : BorderSide.none,
+ ? BorderSide(
+ color: theme.colorScheme.primary,
+ width: 2.0,
+ )
+ : BorderSide.none,
),
),
child: Material(
@@ -167,7 +174,7 @@ class CodeEditorTabBar extends StatelessWidget {
tabProvider.openFile(tab.path);
},
child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4.0),
+ padding: const EdgeInsets.only(left: 6.0, right: 2.0),
child: Row(
children: [
Expanded(
@@ -182,7 +189,7 @@ class CodeEditorTabBar extends StatelessWidget {
style: TextStyle(
color: theme.colorScheme.error,
fontWeight: FontWeight.bold,
- fontSize: 13.0,
+ fontSize: 12.0,
),
),
),
@@ -204,18 +211,18 @@ class CodeEditorTabBar extends StatelessWidget {
),
),
InkResponse(
- radius: 12,
+ radius: 10,
borderRadius: BorderRadius.circular(4.0),
hoverColor: theme.colorScheme.onSurface.withValues(alpha: 0.12),
highlightColor: theme.colorScheme.onSurface.withValues(alpha: 0.18),
onTap: () {
- tabProvider.closeTab(context, index);
+ tabProvider.closeTabByPath(context, tab.path);
},
child: Padding(
- padding: const EdgeInsets.all(3.0),
+ padding: const EdgeInsets.all(2.0),
child: Icon(
Icons.close,
- size: 14.0,
+ size: 13.0,
color: isSelected
? theme.colorScheme.onSurface
: theme.colorScheme.onSurfaceVariant,
diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart
index 6ca662d..f22f1c6 100644
--- a/lib/widgets/code_editor_widget.dart
+++ b/lib/widgets/code_editor_widget.dart
@@ -51,6 +51,77 @@ class _CodeEditorWidgetState extends State {
int? _currentIndentSize;
bool _isShowingConflictDialog = false;
+ // 双指捏合缩放字号状态
+ final Map _pointerPositions = {};
+ double? _initialPinchDistance;
+ double? _initialPinchFontSize;
+ double? _activeZoomFontSize;
+ bool _isPinching = false;
+
+ void _handlePointerDown(PointerDownEvent event, double currentFontSize) {
+ _pointerPositions[event.pointer] = event.position;
+ if (_pointerPositions.length == 2) {
+ final points = _pointerPositions.values.toList();
+ _initialPinchDistance = (points[0] - points[1]).distance;
+ _initialPinchFontSize = _activeZoomFontSize ?? currentFontSize;
+ setState(() {
+ _isPinching = true;
+ });
+ }
+ }
+
+ void _handlePointerMove(PointerMoveEvent event) {
+ if (!_pointerPositions.containsKey(event.pointer)) return;
+ _pointerPositions[event.pointer] = event.position;
+
+ if (_pointerPositions.length >= 2 &&
+ _initialPinchDistance != null &&
+ _initialPinchDistance! > 10.0 &&
+ _initialPinchFontSize != null) {
+ final points = _pointerPositions.values.toList();
+ final currentDistance = (points[0] - points[1]).distance;
+ final scale = currentDistance / _initialPinchDistance!;
+ final rawFontSize = (_initialPinchFontSize! * scale).clamp(10.0, 30.0);
+ final newFontSize = (rawFontSize * 10).round() / 10.0;
+ if (_activeZoomFontSize != newFontSize) {
+ setState(() {
+ _activeZoomFontSize = newFontSize;
+ });
+ }
+ }
+ }
+
+ void _handlePointerUp(PointerUpEvent event) {
+ _pointerPositions.remove(event.pointer);
+ if (_pointerPositions.length < 2 && _isPinching) {
+ _finishPinchZoom();
+ }
+ }
+
+ void _handlePointerCancel(PointerCancelEvent event) {
+ _pointerPositions.remove(event.pointer);
+ if (_pointerPositions.length < 2 && _isPinching) {
+ _finishPinchZoom();
+ }
+ }
+
+ void _finishPinchZoom() {
+ final finalSize = _activeZoomFontSize;
+ setState(() {
+ _isPinching = false;
+ _initialPinchDistance = null;
+ _initialPinchFontSize = null;
+ _activeZoomFontSize = null;
+ });
+
+ if (finalSize != null) {
+ try {
+ final settings = _getSettingsProvider(context);
+ settings.setFontSize(finalSize.roundToDouble());
+ } catch (_) {}
+ }
+ }
+
EditorTabItem? _getCurrentTab() {
final filePath = widget.filePath;
if (filePath == null || filePath.isEmpty) return null;
@@ -348,7 +419,7 @@ class _CodeEditorWidgetState extends State {
bool activeWordWrap = true;
bool enableVirtualKeyboard = false;
VirtualKeyboardConfig? keyboardConfig;
- AppFontItem activeEditorFont = AppFonts.editorMonospace;
+ AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono;
try {
final settings = _getSettingsProvider(context, listen: true);
activeTheme = settings.editorTheme;
@@ -364,6 +435,8 @@ class _CodeEditorWidgetState extends State {
}
} catch (_) {}
+ final double displayFontSize = _activeZoomFontSize ?? activeFontSize;
+
return Container(
color: activeTheme.backgroundColor,
width: double.infinity,
@@ -371,61 +444,107 @@ class _CodeEditorWidgetState extends State {
child: Column(
children: [
Expanded(
- child: CodeEditor(
- key: ValueKey(_currentLoadedPath),
- controller: controller,
- focusNode: _focusNode,
- scrollController: _scrollController,
- wordWrap: activeWordWrap,
- toolbarController: _toolbarController,
- style: CodeEditorStyle(
- fontSize: activeFontSize,
- textColor: activeTheme.textColor,
- backgroundColor: activeTheme.backgroundColor,
- cursorColor: activeTheme.cursorColor,
- cursorLineColor: activeTheme.cursorLineColor,
- selectionColor: activeTheme.selectionColor,
- fontFamily: activeEditorFont.fontFamily,
- fontFamilyFallback: activeEditorFont.fallback,
- codeTheme: CodeHighlightTheme(
- languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath),
- theme: activeTheme.highlightTheme,
- ),
+ child: Listener(
+ behavior: HitTestBehavior.translucent,
+ onPointerDown: (event) => _handlePointerDown(event, activeFontSize),
+ onPointerMove: _handlePointerMove,
+ onPointerUp: _handlePointerUp,
+ onPointerCancel: _handlePointerCancel,
+ child: Stack(
+ children: [
+ CodeEditor(
+ key: ValueKey(_currentLoadedPath),
+ controller: controller,
+ focusNode: _focusNode,
+ scrollController: _scrollController,
+ wordWrap: activeWordWrap,
+ toolbarController: _toolbarController,
+ style: CodeEditorStyle(
+ fontSize: displayFontSize,
+ textColor: activeTheme.textColor,
+ backgroundColor: activeTheme.backgroundColor,
+ cursorColor: activeTheme.cursorColor,
+ cursorLineColor: activeTheme.cursorLineColor,
+ selectionColor: activeTheme.selectionColor,
+ fontFamily: activeEditorFont.fontFamily,
+ fontFamilyFallback: activeEditorFont.fallback,
+ codeTheme: CodeHighlightTheme(
+ languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath),
+ theme: activeTheme.highlightTheme,
+ ),
+ ),
+ indicatorBuilder: (context, editingController, chunkController, notifier) {
+ return Row(
+ children: [
+ DefaultCodeLineNumber(
+ controller: editingController,
+ notifier: notifier,
+ textStyle: TextStyle(
+ color: activeTheme.gutterTextColor,
+ fontSize: (displayFontSize - 1).clamp(9.0, 30.0),
+ fontFamily: activeEditorFont.fontFamily,
+ fontFamilyFallback: activeEditorFont.fallback,
+ ),
+ focusedTextStyle: TextStyle(
+ color: activeTheme.focusedGutterTextColor,
+ fontSize: (displayFontSize - 1).clamp(9.0, 30.0),
+ fontWeight: FontWeight.bold,
+ fontFamily: activeEditorFont.fontFamily,
+ fontFamilyFallback: activeEditorFont.fallback,
+ ),
+ ),
+ DefaultCodeChunkIndicator(
+ width: 20,
+ controller: chunkController,
+ notifier: notifier,
+ painter: DefaultCodeChunkIndicatorPainter(
+ color: activeTheme.gutterTextColor,
+ ),
+ ),
+ ],
+ );
+ },
+ ),
+ if (_isPinching && _activeZoomFontSize != null)
+ Center(
+ child: IgnorePointer(
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(alpha: 0.75),
+ borderRadius: BorderRadius.circular(24),
+ boxShadow: const [
+ BoxShadow(
+ color: Colors.black26,
+ blurRadius: 8,
+ offset: Offset(0, 2),
+ ),
+ ],
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(Icons.format_size, color: Colors.white, size: 18),
+ const SizedBox(width: 8),
+ Text(
+ '${_activeZoomFontSize!.round()} pt',
+ style: const TextStyle(
+ color: Colors.white,
+ fontSize: 15,
+ fontWeight: FontWeight.bold,
+ decoration: TextDecoration.none,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
),
- indicatorBuilder: (context, editingController, chunkController, notifier) {
- return Row(
- children: [
- DefaultCodeLineNumber(
- controller: editingController,
- notifier: notifier,
- textStyle: TextStyle(
- color: activeTheme.gutterTextColor,
- fontSize: (activeFontSize - 1).clamp(9.0, 30.0),
- fontFamily: activeEditorFont.fontFamily,
- fontFamilyFallback: activeEditorFont.fallback,
- ),
- focusedTextStyle: TextStyle(
- color: activeTheme.focusedGutterTextColor,
- fontSize: (activeFontSize - 1).clamp(9.0, 30.0),
- fontWeight: FontWeight.bold,
- fontFamily: activeEditorFont.fontFamily,
- fontFamilyFallback: activeEditorFont.fallback,
- ),
- ),
- DefaultCodeChunkIndicator(
- width: 20,
- controller: chunkController,
- notifier: notifier,
- painter: DefaultCodeChunkIndicatorPainter(
- color: activeTheme.gutterTextColor,
- ),
- ),
- ],
- );
- },
),
),
- if (enableVirtualKeyboard && keyboardConfig != null)
+ if (enableVirtualKeyboard && keyboardConfig != null && keyboardConfig.hasKeys)
VirtualKeyboardWidget(
controller: controller,
focusNode: _focusNode,
diff --git a/lib/widgets/terminal_drawer.dart b/lib/widgets/terminal_drawer.dart
index b639d08..9c16979 100644
--- a/lib/widgets/terminal_drawer.dart
+++ b/lib/widgets/terminal_drawer.dart
@@ -33,17 +33,26 @@ class TerminalDrawer extends StatelessWidget {
padding: const EdgeInsets.only(left: 16.0, right: 8.0, top: 4.0, bottom: 4.0),
child: Row(
children: [
- Text(
- l10n.sessionDrawerTitle,
- style: theme.textTheme.titleMedium?.copyWith(
- fontWeight: FontWeight.bold,
- color: theme.colorScheme.onSurface,
+ Expanded(
+ child: Text(
+ l10n.sessionDrawerTitle,
+ style: theme.textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.bold,
+ color: theme.colorScheme.onSurface,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
),
),
- const Spacer(),
- IconButton(
- icon: const Icon(Icons.add),
- tooltip: l10n.addTerminalTooltip,
+ const SizedBox(width: 8),
+ TextButton.icon(
+ icon: const Icon(Icons.add, size: 18),
+ label: Text(l10n.addSession),
+ style: TextButton.styleFrom(
+ visualDensity: VisualDensity.compact,
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ foregroundColor: theme.colorScheme.onSurface,
+ ),
onPressed: () {
final distroProvider = context.read();
final currentSystem = distroProvider?.selectedSystem;
diff --git a/lib/widgets/virtual_keyboard_key_edit_dialog.dart b/lib/widgets/virtual_keyboard_key_edit_dialog.dart
new file mode 100644
index 0000000..5b7ccc4
--- /dev/null
+++ b/lib/widgets/virtual_keyboard_key_edit_dialog.dart
@@ -0,0 +1,390 @@
+import 'package:flutter/material.dart';
+import '../l10n/app_localizations.dart';
+import '../models/virtual_keyboard_config.dart';
+
+/// 编辑或添加虚拟小键盘按键的独立弹窗
+class KeyEditDialog extends StatefulWidget {
+ final KeyboardScope scope;
+ final KeyboardKeyItem? initialKey;
+
+ const KeyEditDialog({
+ super.key,
+ required this.scope,
+ this.initialKey,
+ });
+
+ @override
+ State createState() => _KeyEditDialogState();
+}
+
+class _KeyEditDialogState extends State {
+ final _formKey = GlobalKey();
+
+ late TextEditingController _labelController;
+ late TextEditingController _valueInputController;
+ late TextEditingController _cursorOffsetController;
+
+ String? _selectedIcon;
+ late String _selectedAction;
+ String? _selectedPresetValue;
+
+ @override
+ void initState() {
+ super.initState();
+ final init = widget.initialKey;
+
+ _labelController = TextEditingController(text: init?.label ?? '');
+ _valueInputController = TextEditingController(text: init?.value ?? '');
+ _cursorOffsetController = TextEditingController(
+ text: (init?.cursorOffset ?? (init?.action == 'pair' ? -1 : 0)).toString(),
+ );
+
+ _selectedIcon = (init?.icon != null && KeyboardIconHelper.getIcon(init!.icon) != null)
+ ? init.icon
+ : null;
+
+ final availableActions = widget.scope == KeyboardScope.editor
+ ? KeyboardScopeHelper.editorActions
+ : KeyboardScopeHelper.terminalActions;
+
+ if (init != null && availableActions.any((a) => a.action == init.action)) {
+ _selectedAction = init.action;
+ } else {
+ _selectedAction = availableActions.first.action;
+ }
+
+ _syncPresetValueFromInitial();
+ }
+
+ void _syncPresetValueFromInitial() {
+ final currentVal = widget.initialKey?.value ?? '';
+ if (_selectedAction == 'command') {
+ if (KeyboardScopeHelper.editorCommands.any((c) => c.value == currentVal)) {
+ _selectedPresetValue = currentVal;
+ } else {
+ _selectedPresetValue = KeyboardScopeHelper.editorCommands.first.value;
+ }
+ } else if (_selectedAction == 'pair') {
+ if (KeyboardScopeHelper.editorPairs.any((p) => p.value == currentVal)) {
+ _selectedPresetValue = currentVal;
+ } else {
+ _selectedPresetValue = KeyboardScopeHelper.editorPairs.first.value;
+ }
+ } else if (_selectedAction == 'modifier') {
+ if (KeyboardScopeHelper.terminalModifiers.any((m) => m.value == currentVal)) {
+ _selectedPresetValue = currentVal;
+ } else {
+ _selectedPresetValue = KeyboardScopeHelper.terminalModifiers.first.value;
+ }
+ } else if (_selectedAction == 'terminal_key') {
+ if (KeyboardScopeHelper.terminalKeys.any((k) => k.value == currentVal)) {
+ _selectedPresetValue = currentVal;
+ } else {
+ _selectedPresetValue = KeyboardScopeHelper.terminalKeys.first.value;
+ }
+ } else {
+ _selectedPresetValue = null;
+ }
+ }
+
+ @override
+ void dispose() {
+ _labelController.dispose();
+ _valueInputController.dispose();
+ _cursorOffsetController.dispose();
+ super.dispose();
+ }
+
+ void _onActionChanged(String? newAction) {
+ if (newAction == null || newAction == _selectedAction) return;
+ setState(() {
+ _selectedAction = newAction;
+ if (_selectedAction == 'pair') {
+ _selectedPresetValue = KeyboardScopeHelper.editorPairs.first.value;
+ if (_cursorOffsetController.text.isEmpty || _cursorOffsetController.text == '0') {
+ _cursorOffsetController.text = '-1';
+ }
+ if (_labelController.text.isEmpty) {
+ _labelController.text = _selectedPresetValue!;
+ }
+ } else if (_selectedAction == 'command') {
+ _selectedPresetValue = KeyboardScopeHelper.editorCommands.first.value;
+ } else if (_selectedAction == 'modifier') {
+ _selectedPresetValue = KeyboardScopeHelper.terminalModifiers.first.value;
+ } else if (_selectedAction == 'terminal_key') {
+ _selectedPresetValue = KeyboardScopeHelper.terminalKeys.first.value;
+ } else {
+ _selectedPresetValue = null;
+ }
+ });
+ }
+
+ void _onSave() {
+ if (!_formKey.currentState!.validate()) return;
+
+ final String label = _labelController.text.trim();
+ String value;
+ int cursorOffset = 0;
+
+ if (_selectedAction == 'input') {
+ value = _valueInputController.text;
+ } else {
+ value = _selectedPresetValue ?? '';
+ }
+
+ if (_selectedAction == 'pair') {
+ cursorOffset = int.tryParse(_cursorOffsetController.text.trim()) ?? -1;
+ }
+
+ final keyItem = KeyboardKeyItem(
+ label: label.isNotEmpty ? label : value,
+ icon: (_selectedIcon != null && _selectedIcon!.isNotEmpty) ? _selectedIcon : null,
+ action: _selectedAction,
+ value: value,
+ cursorOffset: cursorOffset,
+ );
+
+ Navigator.of(context).pop(keyItem);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = AppLocalizations.of(context)!;
+ final availableActions = widget.scope == KeyboardScope.editor
+ ? KeyboardScopeHelper.editorActions
+ : KeyboardScopeHelper.terminalActions;
+
+ return AlertDialog(
+ title: Text(widget.initialKey == null ? l10n.keyboardAddKeyTitle : l10n.keyboardEditKeyTitle),
+ content: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 420),
+ child: SingleChildScrollView(
+ child: Form(
+ key: _formKey,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // 显示标签 Label
+ TextFormField(
+ controller: _labelController,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardLabelFormField,
+ hintText: l10n.keyboardLabelFormFieldHint,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ validator: (val) {
+ if ((val == null || val.trim().isEmpty) &&
+ (_selectedIcon == null || _selectedIcon!.isEmpty) &&
+ _selectedAction == 'input' &&
+ _valueInputController.text.trim().isEmpty) {
+ return l10n.keyboardLabelOrIconRequiredError;
+ }
+ return null;
+ },
+ ),
+ const SizedBox(height: 14),
+
+ // 内置图标选择 Icon
+ DropdownButtonFormField(
+ isExpanded: true,
+ initialValue: _selectedIcon,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardIconFormField,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ items: [
+ DropdownMenuItem(
+ value: null,
+ child: Text(l10n.keyboardNoIconOption, overflow: TextOverflow.ellipsis),
+ ),
+ ...KeyboardIconHelper.supportedIconKeys.map(
+ (iconKey) => DropdownMenuItem(
+ value: iconKey,
+ child: Row(
+ children: [
+ Icon(KeyboardIconHelper.getIcon(iconKey), size: 18),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(iconKey, overflow: TextOverflow.ellipsis),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ onChanged: (val) {
+ setState(() {
+ _selectedIcon = val;
+ });
+ },
+ ),
+ const SizedBox(height: 14),
+
+ // 动作类型 Action
+ DropdownButtonFormField(
+ isExpanded: true,
+ initialValue: _selectedAction,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardActionFormField,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ items: availableActions.map(
+ (actionOption) => DropdownMenuItem(
+ value: actionOption.action,
+ child: Text(actionOption.label, overflow: TextOverflow.ellipsis),
+ ),
+ ).toList(),
+ onChanged: _onActionChanged,
+ ),
+ const SizedBox(height: 14),
+
+ // 动作值 Value 控件联动
+ if (_selectedAction == 'input')
+ TextFormField(
+ controller: _valueInputController,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardValueFormField,
+ hintText: l10n.keyboardValueFormFieldHint,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ validator: (val) {
+ if (val == null || val.isEmpty) {
+ return l10n.keyboardValueRequiredError;
+ }
+ return null;
+ },
+ )
+ else if (_selectedAction == 'pair')
+ DropdownButtonFormField(
+ isExpanded: true,
+ initialValue: _selectedPresetValue,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardPairPresetFormField,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ items: KeyboardScopeHelper.editorPairs.map(
+ (pair) => DropdownMenuItem(
+ value: pair.value,
+ child: Text('${pair.label} (${pair.value})', overflow: TextOverflow.ellipsis),
+ ),
+ ).toList(),
+ onChanged: (val) {
+ setState(() {
+ _selectedPresetValue = val;
+ if (_labelController.text.isEmpty && val != null) {
+ _labelController.text = val;
+ }
+ });
+ },
+ )
+ else if (_selectedAction == 'command')
+ DropdownButtonFormField(
+ isExpanded: true,
+ initialValue: _selectedPresetValue,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardCommandPresetFormField,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ items: KeyboardScopeHelper.editorCommands.map(
+ (cmd) => DropdownMenuItem(
+ value: cmd.value,
+ child: Text('${cmd.label} [${cmd.value}]', overflow: TextOverflow.ellipsis),
+ ),
+ ).toList(),
+ onChanged: (val) {
+ setState(() {
+ _selectedPresetValue = val;
+ });
+ },
+ )
+ else if (_selectedAction == 'modifier')
+ DropdownButtonFormField(
+ isExpanded: true,
+ initialValue: _selectedPresetValue,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardModifierPresetFormField,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ items: KeyboardScopeHelper.terminalModifiers.map(
+ (m) => DropdownMenuItem(
+ value: m.value,
+ child: Text(m.label, overflow: TextOverflow.ellipsis),
+ ),
+ ).toList(),
+ onChanged: (val) {
+ setState(() {
+ _selectedPresetValue = val;
+ });
+ },
+ )
+ else if (_selectedAction == 'terminal_key')
+ DropdownButtonFormField(
+ isExpanded: true,
+ initialValue: _selectedPresetValue,
+ decoration: InputDecoration(
+ labelText: l10n.keyboardTerminalKeyPresetFormField,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ items: KeyboardScopeHelper.terminalKeys.map(
+ (k) => DropdownMenuItem(
+ value: k.value,
+ child: Text(k.label, overflow: TextOverflow.ellipsis),
+ ),
+ ).toList(),
+ onChanged: (val) {
+ setState(() {
+ _selectedPresetValue = val;
+ });
+ },
+ ),
+
+ // 仅当 action == pair 时显示 cursorOffset
+ if (_selectedAction == 'pair') ...[
+ const SizedBox(height: 14),
+ TextFormField(
+ controller: _cursorOffsetController,
+ keyboardType: const TextInputType.numberWithOptions(signed: true),
+ decoration: InputDecoration(
+ labelText: l10n.keyboardCursorOffsetFormField,
+ helperText: l10n.keyboardCursorOffsetHelper,
+ border: const OutlineInputBorder(),
+ isDense: true,
+ ),
+ validator: (val) {
+ if (val == null || val.trim().isEmpty) {
+ return l10n.keyboardCursorOffsetRequiredError;
+ }
+ if (int.tryParse(val.trim()) == null) {
+ return l10n.keyboardCursorOffsetIntegerError;
+ }
+ return null;
+ },
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: Text(l10n.cancel),
+ ),
+ FilledButton(
+ onPressed: _onSave,
+ child: Text(l10n.confirm),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/widgets/virtual_keyboard_key_tile.dart b/lib/widgets/virtual_keyboard_key_tile.dart
new file mode 100644
index 0000000..57b5b8e
--- /dev/null
+++ b/lib/widgets/virtual_keyboard_key_tile.dart
@@ -0,0 +1,89 @@
+import 'package:flutter/material.dart';
+import '../l10n/app_localizations.dart';
+import '../models/virtual_keyboard_config.dart';
+
+/// 虚拟小键盘单行内的单个按键卡片组件
+class VirtualKeyboardKeyTile extends StatelessWidget {
+ final int pageIndex;
+ final int rowIndex;
+ final int keyIndex;
+ final KeyboardKeyItem keyItem;
+ final VoidCallback onEdit;
+ final VoidCallback onDelete;
+
+ const VirtualKeyboardKeyTile({
+ super.key,
+ required this.pageIndex,
+ required this.rowIndex,
+ required this.keyIndex,
+ required this.keyItem,
+ required this.onEdit,
+ required this.onDelete,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final l10n = AppLocalizations.of(context)!;
+ final hasIcon = keyItem.icon != null && keyItem.icon!.isNotEmpty;
+ final iconData = hasIcon ? KeyboardIconHelper.getIcon(keyItem.icon) : null;
+
+ return Card(
+ key: ValueKey('page_${pageIndex}_row_${rowIndex}_key_$keyIndex'),
+ margin: const EdgeInsets.only(bottom: 6),
+ color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
+ elevation: 0,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(8),
+ side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.2)),
+ ),
+ child: ListTile(
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
+ leading: Container(
+ width: 38,
+ height: 38,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: theme.colorScheme.surface,
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(color: theme.dividerColor.withValues(alpha: 0.4)),
+ ),
+ child: iconData != null
+ ? Icon(iconData, size: 20, color: theme.colorScheme.primary)
+ : Text(
+ keyItem.label.isNotEmpty ? keyItem.label : '?',
+ style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ title: Text(
+ keyItem.label.isNotEmpty ? keyItem.label : l10n.keyboardNoLabel,
+ style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
+ ),
+ trailing: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ icon: const Icon(Icons.edit_outlined, size: 18),
+ tooltip: l10n.keyboardEditKeyTooltip,
+ onPressed: onEdit,
+ ),
+ IconButton(
+ icon: const Icon(Icons.delete_outline, size: 18),
+ tooltip: l10n.keyboardDeleteKeyTooltip,
+ onPressed: onDelete,
+ ),
+ ReorderableDragStartListener(
+ index: keyIndex,
+ child: const Padding(
+ padding: EdgeInsets.symmetric(horizontal: 6),
+ child: Icon(Icons.drag_handle, size: 18, color: Colors.grey),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/virtual_keyboard_page_config_section.dart b/lib/widgets/virtual_keyboard_page_config_section.dart
new file mode 100644
index 0000000..ca0440d
--- /dev/null
+++ b/lib/widgets/virtual_keyboard_page_config_section.dart
@@ -0,0 +1,88 @@
+import 'package:flutter/material.dart';
+import '../l10n/app_localizations.dart';
+
+/// 虚拟小键盘当前页的基础属性配置板块(行按钮数)
+class VirtualKeyboardPageConfigSection extends StatelessWidget {
+ final int count;
+ final ValueChanged onCountChanged;
+
+ const VirtualKeyboardPageConfigSection({
+ super.key,
+ required this.count,
+ required this.onCountChanged,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final l10n = AppLocalizations.of(context)!;
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Icon(Icons.tune, size: 20, color: theme.colorScheme.primary),
+ const SizedBox(width: 8),
+ Text(
+ l10n.keyboardPageConfigSectionTitle,
+ style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Card(
+ elevation: 0,
+ margin: EdgeInsets.zero,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.3)),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l10n.keyboardRowButtons, style: const TextStyle(fontWeight: FontWeight.w500)),
+ const SizedBox(height: 2),
+ Text(
+ l10n.keyboardRowGridDescription(count),
+ style: TextStyle(fontSize: 12, color: theme.hintColor),
+ ),
+ ],
+ ),
+ Row(
+ children: [
+ IconButton.filledTonal(
+ icon: const Icon(Icons.remove, size: 18),
+ tooltip: l10n.keyboardDecreaseRowButtonsTooltip,
+ visualDensity: VisualDensity.compact,
+ onPressed: count > 3 ? () => onCountChanged(count - 1) : null,
+ ),
+ Container(
+ constraints: const BoxConstraints(minWidth: 44),
+ alignment: Alignment.center,
+ child: Text(
+ '$count',
+ style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
+ ),
+ ),
+ IconButton.filledTonal(
+ icon: const Icon(Icons.add, size: 18),
+ tooltip: l10n.keyboardIncreaseRowButtonsTooltip,
+ visualDensity: VisualDensity.compact,
+ onPressed: count < 12 ? () => onCountChanged(count + 1) : null,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/widgets/virtual_keyboard_page_drawer.dart b/lib/widgets/virtual_keyboard_page_drawer.dart
new file mode 100644
index 0000000..a50ffbf
--- /dev/null
+++ b/lib/widgets/virtual_keyboard_page_drawer.dart
@@ -0,0 +1,184 @@
+import 'package:flutter/material.dart';
+import '../l10n/app_localizations.dart';
+import '../models/virtual_keyboard_config.dart';
+
+/// 虚拟小键盘页面管理抽屉
+class VirtualKeyboardPageDrawer extends StatelessWidget {
+ final List pages;
+ final int currentPageIndex;
+ final VoidCallback onAddNewPage;
+ final ValueChanged onSelectPage;
+ final ValueChanged onDeletePage;
+ final void Function(int oldIndex, int newIndex) onReorderPages;
+
+ const VirtualKeyboardPageDrawer({
+ super.key,
+ required this.pages,
+ required this.currentPageIndex,
+ required this.onAddNewPage,
+ required this.onSelectPage,
+ required this.onDeletePage,
+ required this.onReorderPages,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final l10n = AppLocalizations.of(context)!;
+
+ return Drawer(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // 抽屉头部
+ SafeArea(
+ bottom: false,
+ child: Padding(
+ padding: const EdgeInsets.only(left: 16.0, right: 8.0, top: 4.0, bottom: 4.0),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ l10n.keyboardDrawerTitle,
+ style: theme.textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.bold,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ const SizedBox(width: 8),
+ // 单独加号,后面文本为新建页面
+ TextButton.icon(
+ icon: const Icon(Icons.add, size: 18),
+ label: Text(l10n.keyboardNewPage),
+ style: TextButton.styleFrom(
+ visualDensity: VisualDensity.compact,
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ ),
+ onPressed: () {
+ onAddNewPage();
+ Navigator.of(context).pop(); // 关闭抽屉
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ const Divider(height: 1),
+
+ // 页面可拖动排序列表
+ Expanded(
+ child: ReorderableListView.builder(
+ buildDefaultDragHandles: false,
+ padding: const EdgeInsets.symmetric(vertical: 4.0),
+ itemCount: pages.length,
+ onReorderItem: onReorderPages,
+ itemBuilder: (context, index) {
+ final isSelected = index == currentPageIndex;
+ final pageItem = pages[index];
+
+ return VirtualKeyboardPageDrawerItem(
+ key: ValueKey('page_$index'),
+ index: index,
+ pageItem: pageItem,
+ isSelected: isSelected,
+ canDelete: pages.length > 1,
+ onSelect: () {
+ onSelectPage(index);
+ Navigator.of(context).pop();
+ },
+ onDelete: () => onDeletePage(index),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// 抽屉内的独立页面列表项组件
+class VirtualKeyboardPageDrawerItem extends StatelessWidget {
+ final int index;
+ final KeyboardPageItem pageItem;
+ final bool isSelected;
+ final bool canDelete;
+ final VoidCallback onSelect;
+ final VoidCallback onDelete;
+
+ const VirtualKeyboardPageDrawerItem({
+ super.key,
+ required this.index,
+ required this.pageItem,
+ required this.isSelected,
+ required this.canDelete,
+ required this.onSelect,
+ required this.onDelete,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final l10n = AppLocalizations.of(context)!;
+
+ return Container(
+ margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
+ child: Material(
+ color: Colors.transparent,
+ child: ListTile(
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 0.0),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(8.0),
+ ),
+ selected: isSelected,
+ selectedTileColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.5),
+ leading: Icon(
+ Icons.dashboard_outlined,
+ size: 20,
+ color: isSelected ? theme.colorScheme.primary : theme.colorScheme.onSurfaceVariant,
+ ),
+ title: Text(
+ l10n.keyboardPageItemTitle(index + 1),
+ style: TextStyle(
+ fontSize: 14.0,
+ fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
+ color: isSelected ? theme.colorScheme.primary : null,
+ ),
+ ),
+ subtitle: Text(
+ l10n.keyboardPageItemSubtitle(pageItem.keys.length),
+ style: TextStyle(
+ fontSize: 12.0,
+ color: theme.colorScheme.onSurfaceVariant,
+ ),
+ ),
+ dense: true,
+ onTap: onSelect,
+ trailing: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ icon: const Icon(Icons.delete_outline, size: 20),
+ tooltip: l10n.keyboardDeletePageTooltip,
+ onPressed: canDelete ? onDelete : null,
+ ),
+ ReorderableDragStartListener(
+ index: index,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 8.0),
+ child: Icon(
+ Icons.drag_handle,
+ size: 20,
+ color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/virtual_keyboard_row_tile.dart b/lib/widgets/virtual_keyboard_row_tile.dart
new file mode 100644
index 0000000..d30e00b
--- /dev/null
+++ b/lib/widgets/virtual_keyboard_row_tile.dart
@@ -0,0 +1,126 @@
+import 'package:flutter/material.dart';
+import '../l10n/app_localizations.dart';
+import '../models/virtual_keyboard_config.dart';
+import 'virtual_keyboard_key_tile.dart';
+
+/// 虚拟小键盘页面内的单个按键行(含 ExpansionTile 与行内按键列表)
+class VirtualKeyboardRowTile extends StatelessWidget {
+ final int pageIndex;
+ final int rowIndex;
+ final List rowKeys;
+ final bool isExpanded;
+ final ValueChanged onExpansionChanged;
+ final VoidCallback onAddKey;
+ final VoidCallback onDeleteRow;
+ final void Function(int oldIndex, int newIndex) onReorderKeys;
+ final void Function(int keyIndex, KeyboardKeyItem key) onEditKey;
+ final ValueChanged onDeleteKey;
+
+ const VirtualKeyboardRowTile({
+ super.key,
+ required this.pageIndex,
+ required this.rowIndex,
+ required this.rowKeys,
+ required this.isExpanded,
+ required this.onExpansionChanged,
+ required this.onAddKey,
+ required this.onDeleteRow,
+ required this.onReorderKeys,
+ required this.onEditKey,
+ required this.onDeleteKey,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final l10n = AppLocalizations.of(context)!;
+
+ return Card(
+ key: ValueKey('page_${pageIndex}_row_$rowIndex'),
+ margin: const EdgeInsets.only(bottom: 12),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.3)),
+ ),
+ child: Theme(
+ data: theme.copyWith(dividerColor: Colors.transparent),
+ child: ExpansionTile(
+ key: ValueKey('page_${pageIndex}_row_${rowIndex}_$isExpanded'),
+ initiallyExpanded: isExpanded,
+ onExpansionChanged: onExpansionChanged,
+ leading: CircleAvatar(
+ radius: 14,
+ backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.12),
+ child: Text(
+ '${rowIndex + 1}',
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.bold,
+ color: theme.colorScheme.primary,
+ ),
+ ),
+ ),
+ title: Text(l10n.keyboardRowKeyCount(rowKeys.length)),
+ trailing: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ icon: const Icon(Icons.add, size: 20),
+ tooltip: l10n.keyboardAddKeyTooltip,
+ color: theme.colorScheme.primary,
+ onPressed: onAddKey,
+ ),
+ IconButton(
+ icon: const Icon(Icons.delete_outline, size: 20),
+ tooltip: l10n.keyboardDeleteRowTooltip,
+ onPressed: onDeleteRow,
+ ),
+ ReorderableDragStartListener(
+ index: rowIndex,
+ child: const Padding(
+ padding: EdgeInsets.symmetric(horizontal: 8),
+ child: Icon(Icons.drag_handle, color: Colors.grey),
+ ),
+ ),
+ ],
+ ),
+ children: [
+ if (rowKeys.isEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 16),
+ child: Center(
+ child: Text(
+ l10n.keyboardEmptyRowKeysHint,
+ style: TextStyle(fontSize: 13, color: theme.hintColor),
+ ),
+ ),
+ )
+ else
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
+ child: ReorderableListView.builder(
+ shrinkWrap: true,
+ physics: const NeverScrollableScrollPhysics(),
+ buildDefaultDragHandles: false,
+ itemCount: rowKeys.length,
+ onReorderItem: onReorderKeys,
+ itemBuilder: (context, keyIndex) {
+ final keyItem = rowKeys[keyIndex];
+ return VirtualKeyboardKeyTile(
+ key: ValueKey('page_${pageIndex}_row_${rowIndex}_key_$keyIndex'),
+ pageIndex: pageIndex,
+ rowIndex: rowIndex,
+ keyIndex: keyIndex,
+ keyItem: keyItem,
+ onEdit: () => onEditKey(keyIndex, keyItem),
+ onDelete: () => onDeleteKey(keyIndex),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/virtual_keyboard_widget.dart b/lib/widgets/virtual_keyboard_widget.dart
index c5b3e2f..db2674f 100644
--- a/lib/widgets/virtual_keyboard_widget.dart
+++ b/lib/widgets/virtual_keyboard_widget.dart
@@ -22,19 +22,30 @@ class VirtualKeyboardWidget extends StatefulWidget {
State createState() => _VirtualKeyboardWidgetState();
}
-class _VirtualKeyboardWidgetState extends State {
+class _VirtualKeyboardWidgetState extends State
+ with SingleTickerProviderStateMixin {
late PageController _pageController;
+ late AnimationController _animationController;
int _currentPage = 0;
+ static const double _rowHeight = 30.0;
+ static const double _indicatorHeight = 12.0;
+
@override
void initState() {
super.initState();
_pageController = PageController(initialPage: 0);
+ _animationController = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 200),
+ value: 0.0, // 默认折叠(0.0 表示仅显示第一行,1.0 表示完全展开)
+ );
}
@override
void dispose() {
_pageController.dispose();
+ _animationController.dispose();
super.dispose();
}
@@ -181,6 +192,10 @@ class _VirtualKeyboardWidgetState extends State {
@override
Widget build(BuildContext context) {
+ if (!widget.config.hasKeys) {
+ return const SizedBox.shrink();
+ }
+
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
@@ -189,65 +204,143 @@ class _VirtualKeyboardWidgetState extends State {
final borderColor = isDark ? const Color(0xFF333333) : const Color(0xFFDCDFE6);
final pages = widget.config.pages;
- if (pages.isEmpty) {
- return const SizedBox.shrink();
+
+ int maxRows = 1;
+ for (final p in pages) {
+ if (p.keys.length > maxRows) {
+ maxRows = p.keys.length;
+ }
}
+ final hasMultiplePages = pages.length > 1;
+ final double indicatorTargetHeight = hasMultiplePages ? _indicatorHeight : 0.0;
+ // 多出的行高 + 多页指示器高度
+ final double totalExpandableHeight = (maxRows - 1) * _rowHeight + indicatorTargetHeight;
+
return CodeEditorTapRegion(
- child: Container(
- decoration: BoxDecoration(
- color: bgColor,
- border: Border(
- top: BorderSide(color: borderColor, width: 0.8),
- ),
- ),
- child: SafeArea(
- top: false,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- SizedBox(
- height: 84, // 两行按键的高度
- child: PageView.builder(
- controller: _pageController,
- itemCount: pages.length,
- onPageChanged: (idx) {
- setState(() {
- _currentPage = idx;
- });
- },
- itemBuilder: (context, pageIndex) {
- return _buildPage(pages[pageIndex], isDark);
- },
+ child: AnimatedBuilder(
+ animation: _animationController,
+ builder: (context, child) {
+ final progress = _animationController.value;
+ final currentIndicatorHeight = indicatorTargetHeight * progress;
+ final currentPageViewHeight = _rowHeight + ((maxRows - 1) * _rowHeight * progress);
+
+ return GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onVerticalDragStart: (details) {
+ _animationController.stop();
+ },
+ onVerticalDragUpdate: (details) {
+ if (totalExpandableHeight > 0) {
+ // 上拉 (delta.dy < 0) 增加展开进度,下拉 (delta.dy > 0) 减少展开进度
+ final deltaProgress = -details.delta.dy / totalExpandableHeight;
+ _animationController.value =
+ (_animationController.value + deltaProgress).clamp(0.0, 1.0);
+ }
+ },
+ onVerticalDragEnd: (details) {
+ final velocity = details.primaryVelocity ?? 0;
+ if (velocity < -250) {
+ _animationController.forward();
+ } else if (velocity > 250) {
+ _animationController.reverse();
+ } else if (_animationController.value > 0.5) {
+ _animationController.forward();
+ } else {
+ _animationController.reverse();
+ }
+ },
+ child: Container(
+ decoration: BoxDecoration(
+ color: bgColor,
+ border: Border(
+ top: BorderSide(color: borderColor, width: 0.8),
),
),
- if (pages.length > 1) _buildPageIndicator(pages.length, theme),
- ],
- ),
- ),
+ child: SafeArea(
+ top: false,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (hasMultiplePages)
+ _buildPageIndicator(
+ pages.length,
+ theme,
+ progress,
+ currentIndicatorHeight,
+ ),
+ SizedBox(
+ height: currentPageViewHeight,
+ child: PageView.builder(
+ controller: _pageController,
+ itemCount: pages.length,
+ onPageChanged: (idx) {
+ setState(() {
+ _currentPage = idx;
+ });
+ },
+ itemBuilder: (context, pageIndex) {
+ return _buildPage(pages[pageIndex], isDark);
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
),
);
}
- 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 _buildPageIndicator(
+ int pageCount,
+ ThemeData theme,
+ double progress,
+ double height,
+ ) {
+ if (pageCount <= 1 || progress <= 0.001 || height <= 0.5) {
+ return const SizedBox.shrink();
+ }
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ if (_animationController.value > 0.5) {
+ _animationController.reverse();
+ } else {
+ _animationController.forward();
+ }
+ },
+ child: SizedBox(
+ height: height,
+ child: Opacity(
+ opacity: progress.clamp(0.0, 1.0),
+ child: Center(
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ 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),
+ ),
+ );
+ }),
),
- );
- }),
+ ),
+ ),
),
);
}
@@ -259,30 +352,38 @@ class _VirtualKeyboardWidgetState extends State {
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(),
+ return ClipRect(
+ child: OverflowBox(
+ minHeight: 0,
+ maxHeight: double.infinity,
+ alignment: Alignment.topLeft,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: rows.map((row) {
+ return SizedBox(
+ height: _rowHeight,
+ child: Row(
+ children: List.generate(count, (colIndex) {
+ if (colIndex < row.length) {
+ final keyItem = row[colIndex];
+ return SizedBox(
+ width: cellWidth,
+ height: _rowHeight,
+ child: _buildKeyButton(keyItem, isDark),
+ );
+ } else {
+ return SizedBox(
+ width: cellWidth,
+ height: _rowHeight,
+ );
+ }
+ }),
+ ),
+ );
+ }).toList(),
+ ),
+ ),
);
},
);
@@ -299,14 +400,14 @@ class _VirtualKeyboardWidgetState extends State {
if (iconData != null) {
content = Icon(
iconData,
- size: 18,
+ size: 15,
color: btnTextColor,
);
} else {
content = Text(
keyItem.label,
style: TextStyle(
- fontSize: keyItem.label.length > 3 ? 12 : 15,
+ fontSize: keyItem.label.length > 3 ? 11 : 13,
fontWeight: FontWeight.w500,
color: btnTextColor,
fontFamily: 'Consolas, Monaco, monospace',
@@ -317,19 +418,18 @@ class _VirtualKeyboardWidgetState extends State {
}
return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 2.5, vertical: 3),
+ padding: const EdgeInsets.symmetric(horizontal: 0.75, vertical: 0.75),
child: Material(
color: btnBgColor,
- borderRadius: BorderRadius.circular(6),
- elevation: 0.5,
- shadowColor: Colors.black26,
+ borderRadius: BorderRadius.circular(4),
+ elevation: 0,
child: InkWell(
- borderRadius: BorderRadius.circular(6),
+ borderRadius: BorderRadius.circular(4),
onTap: () => _handleKeyTap(keyItem),
child: Container(
decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(6),
- border: Border.all(color: borderColor, width: 0.8),
+ borderRadius: BorderRadius.circular(4),
+ border: Border.all(color: borderColor, width: 0.6),
),
alignment: Alignment.center,
child: content,
diff --git a/test/terminal_test.dart b/test/terminal_test.dart
index 7ebbb3b..45e9c88 100644
--- a/test/terminal_test.dart
+++ b/test/terminal_test.dart
@@ -409,16 +409,16 @@ void main() {
test('SettingsProvider manages UI, Editor, and Terminal font choices correctly', () async {
final settings = SettingsProvider();
expect(settings.uiFont.id, equals('system_default'));
- expect(settings.editorFont.id, equals('monospace'));
- expect(settings.terminalFont.id, equals('monospace'));
+ expect(settings.editorFont.id, equals('jetbrains_mono'));
+ expect(settings.terminalFont.id, equals('jetbrains_mono'));
await settings.setUiFontId('sans_serif');
expect(settings.uiFont.id, equals('sans_serif'));
expect(settings.uiFont.fontFamily, equals('sans-serif'));
- await settings.setEditorFontId('jetbrains_mono');
- expect(settings.editorFont.id, equals('jetbrains_mono'));
- expect(settings.editorFont.fontFamily, equals('JetBrains Mono'));
+ await settings.setEditorFontId('monospace');
+ expect(settings.editorFont.id, equals('monospace'));
+ expect(settings.editorFont.fontFamily, equals('monospace'));
await settings.setTerminalFontId('consolas');
expect(settings.terminalFont.id, equals('consolas'));
diff --git a/test/widget_test.dart b/test/widget_test.dart
index 31f33cf..9b3bbaf 100644
--- a/test/widget_test.dart
+++ b/test/widget_test.dart
@@ -22,6 +22,8 @@ import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/main.dart';
import 'package:code_editor/views/settings_view.dart';
import 'package:code_editor/views/main_view.dart';
+import 'package:code_editor/views/virtual_keyboard_config_view.dart';
+import 'package:code_editor/widgets/virtual_keyboard_key_edit_dialog.dart';
import 'package:code_editor/widgets/code_editor_app_bar.dart';
import 'package:code_editor/widgets/code_editor_drawer.dart';
import 'package:code_editor/utils/dialog_utils.dart';
@@ -299,29 +301,29 @@ void main() {
matching: find.byType(Switch),
);
expect(switchFinder, findsOneWidget);
- expect(provider.wordWrap, isTrue);
+ expect(provider.wordWrap, isFalse);
// Toggle word wrap
await tester.tap(switchFinder);
await tester.pumpAndSettle();
- expect(provider.wordWrap, isFalse);
+ expect(provider.wordWrap, isTrue);
// Verify indent size tile
expect(find.text('缩进大小'), findsOneWidget);
- expect(find.text('2 个空格'), findsOneWidget);
+ expect(find.text('4 个空格'), findsOneWidget);
// Tap indent size tile to open modal
await tester.tap(find.text('缩进大小'));
await tester.pumpAndSettle();
expect(find.text('选择缩进空格数'), findsOneWidget);
- expect(find.text('4 个空格'), findsOneWidget);
+ expect(find.text('2 个空格'), findsOneWidget);
- // Select 4 spaces
- await tester.tap(find.text('4 个空格'));
+ // Select 2 spaces
+ await tester.tap(find.text('2 个空格'));
await tester.pumpAndSettle();
- expect(provider.indentSize, equals(4));
+ expect(provider.indentSize, equals(2));
// Verify language section
final langTile = find.text('应用语言');
@@ -349,9 +351,9 @@ void main() {
testWidgets('SettingsProvider wordWrap and locale can be updated', (WidgetTester tester) async {
final provider = SettingsProvider();
- expect(provider.wordWrap, isTrue);
- await provider.setWordWrap(false);
expect(provider.wordWrap, isFalse);
+ await provider.setWordWrap(true);
+ expect(provider.wordWrap, isTrue);
expect(provider.locale, isNull);
await provider.setLocale(const Locale('en'));
@@ -678,18 +680,18 @@ void main() {
test('SettingsProvider manages settings correctly', () async {
final settings = SettingsProvider();
expect(settings.fontSize, equals(14.0));
- expect(settings.indentSize, equals(2));
- expect(settings.wordWrap, isTrue);
+ expect(settings.indentSize, equals(4));
+ expect(settings.wordWrap, isFalse);
expect(settings.appThemeMode, equals(ThemeMode.system));
await settings.setFontSize(18.0);
expect(settings.fontSize, equals(18.0));
- await settings.setIndentSize(4);
- expect(settings.indentSize, equals(4));
+ await settings.setIndentSize(2);
+ expect(settings.indentSize, equals(2));
- await settings.setWordWrap(false);
- expect(settings.wordWrap, isFalse);
+ await settings.setWordWrap(true);
+ expect(settings.wordWrap, isTrue);
await settings.setAppThemeMode(ThemeMode.dark);
expect(settings.appThemeMode, equals(ThemeMode.dark));
@@ -1431,26 +1433,79 @@ void main() {
// 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();
+ // Untab button icon exists in row 1
+ expect(find.byIcon(Icons.format_indent_decrease), findsOneWidget);
- // Controller should have received ';'
- expect(controller.text, 'hello;');
-
- // Tap '(' pair key -> should insert () and place cursor inside
- final parenKey = find.text('(');
+ // 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 ')'
+ expect(controller.text, 'hello()');
+ expect(controller.selection.extentOffset, 6); // between '(' and ')'
});
- testWidgets('SettingsView displays virtual keyboard toggle and config dialog with embedded CodeEditor and line-level error report', (tester) async {
+ testWidgets('VirtualKeyboardWidget hides completely when no keys, hides dots in single row, and expands smoothly on drag', (tester) async {
+ final controller = CodeLineEditingController.fromText('');
+
+ // 1. 无按键配置下完全不显示 (SizedBox.shrink)
+ const emptyConfig = VirtualKeyboardConfig(pages: []);
+ expect(emptyConfig.hasKeys, isFalse);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: VirtualKeyboardWidget(
+ controller: controller,
+ config: emptyConfig,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.byType(PageView), findsNothing);
+
+ // 2. 正常多页多行配置
+ final config = VirtualKeyboardConfig.defaultConfiguration();
+ expect(config.hasKeys, isTrue);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: VirtualKeyboardWidget(
+ controller: controller,
+ config: config,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ // 默认只显示一行,初始高度为 30,且分页指示圆点不显示
+ final keyboardFinder = find.byType(VirtualKeyboardWidget);
+ expect(keyboardFinder, findsOneWidget);
+ final initialSize = tester.getSize(keyboardFinder);
+ expect(initialSize.height, closeTo(30.0, 1.0));
+
+ // 向上拖动上拉手势测试
+ await tester.drag(keyboardFinder, const Offset(0, -60));
+ await tester.pumpAndSettle();
+
+ // 展开后高度增加(多行 + 分页圆点)
+ final expandedSize = tester.getSize(keyboardFinder);
+ expect(expandedSize.height, greaterThan(65.0));
+
+ // 再次向下拉收起
+ await tester.drag(keyboardFinder, const Offset(0, 60));
+ await tester.pumpAndSettle();
+
+ final collapsedSize = tester.getSize(keyboardFinder);
+ expect(collapsedSize.height, closeTo(30.0, 1.0));
+ });
+
+ testWidgets('SettingsView navigates to VirtualKeyboardConfigView with full visual config controls', (tester) async {
final settingsProvider = SettingsProvider();
await settingsProvider.init();
await settingsProvider.setEnableVirtualKeyboard(true);
@@ -1474,50 +1529,239 @@ void main() {
await tester.pumpAndSettle();
expect(configTile, findsOneWidget);
- // Tap config tile to open dialog
+ // Tap config tile to navigate to VirtualKeyboardConfigView
await tester.tap(configTile);
await tester.pumpAndSettle();
- expect(find.text('小键盘配置 (JSON)'), findsOneWidget);
- expect(find.text('格式化'), findsOneWidget);
- expect(find.text('恢复默认'), findsOneWidget);
+ // Verify VirtualKeyboardConfigView is rendered
+ expect(find.byType(VirtualKeyboardConfigView), findsOneWidget);
+ expect(find.text('小键盘配置'), findsOneWidget);
+ expect(find.text('编辑区:(第 1 页)'), findsOneWidget);
+ expect(find.text('页面配置'), 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);
+ // Test increasing/decreasing count
+ final addCountButton = find.byTooltip('增加每行按键数');
+ expect(addCountButton, findsOneWidget);
+ await tester.tap(addCountButton);
+ await tester.pumpAndSettle();
+ expect(settingsProvider.virtualKeyboardConfig.pages[0].count, equals(8));
- final codeEditor = tester.widget(find.byType(CodeEditor));
- final editorController = codeEditor.controller!;
+ // Test decreasing count below maxKeysInRows constraint (Requirement 8)
+ // Page 0 default rows have 7 keys. Trying to decrease count down to 6 should be blocked and show Toast
+ final removeCountButton = find.byTooltip('减少每行按键数');
+ await tester.tap(removeCountButton); // 8 -> 7 (allowed, max keys is 7)
+ await tester.pumpAndSettle();
+ expect(settingsProvider.virtualKeyboardConfig.pages[0].count, equals(7));
- // Edit controller with invalid json on line 3
- editorController.text = '{\n "pages": [\n error_here\n ]\n}';
- await tester.pump(const Duration(milliseconds: 100));
+ await tester.tap(removeCountButton); // 7 -> 6 (blocked! row has 7 keys)
+ await tester.pumpAndSettle();
+ expect(settingsProvider.virtualKeyboardConfig.pages[0].count, equals(7)); // Still 7!
+ expect(find.textContaining('行按钮数不能小于 7'), findsOneWidget);
- // Tap '保存'
- await tester.tap(find.text('保存'));
- await tester.pump(const Duration(milliseconds: 100));
-
- // 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.pump(const Duration(milliseconds: 100));
-
- // 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('保存'));
+ // Test Drawer: Open EndDrawer
+ final drawerButton = find.byTooltip('页面管理');
+ expect(drawerButton, findsOneWidget);
+ await tester.tap(drawerButton);
await tester.pumpAndSettle();
- expect(find.text('小键盘配置 (JSON)'), findsNothing);
+ expect(find.text('页面'), findsOneWidget);
+ expect(find.text('第 1 页'), findsOneWidget);
+ expect(find.text('第 2 页'), findsOneWidget);
- // Let success toast timer complete
- await tester.pump(const Duration(seconds: 3));
+ // Add a page from drawer (Requirement 5: 新建页面 button)
+ final addPageButton = find.text('新建页面');
+ await tester.tap(addPageButton);
+ await tester.pumpAndSettle();
+
+ // Drawer closed, navigated to new page 3
+ expect(settingsProvider.virtualKeyboardConfig.pages.length, equals(3));
+ expect(find.text('编辑区:(第 3 页)'), findsOneWidget);
+ expect(find.text('页面配置'), findsOneWidget);
+
+ // Page 3 has 1 row with 1 key ("New"). Test adding keys up to count limit (Requirement 8)
+ // Add a key in row 1
+ final addKeyButton = find.byTooltip('添加按键').first;
+ await tester.tap(addKeyButton);
+ await tester.pumpAndSettle();
+
+ // KeyEditDialog is open
+ expect(find.byType(KeyEditDialog), findsOneWidget);
+ expect(find.text('添加按键'), findsOneWidget);
+
+ // Enter label & value
+ await tester.enterText(find.widgetWithText(TextFormField, '显示文本 (Label)'), 'TestKey');
+ await tester.enterText(find.widgetWithText(TextFormField, '输入文本内容 (Value)'), 'test_val');
+ await tester.pumpAndSettle();
+
+ // Tap '确定' to save key
+ await tester.tap(find.text('确定'));
+ await tester.pumpAndSettle();
+
+ // Dialog closed and key is added to page 3
+ expect(find.byType(KeyEditDialog), findsNothing);
+ expect(settingsProvider.virtualKeyboardConfig.pages[2].keys[0].any((k) => k.label == 'TestKey'), isTrue);
+
+ // Expand the row ExpansionTile and verify TestKey widget is rendered
+ await tester.tap(find.text('2 个按键'));
+ await tester.pumpAndSettle();
+ expect(find.text('TestKey'), findsWidgets);
+
+ // Tap back button to return to SettingsView
+ await tester.tap(find.byTooltip('返回'));
+ await tester.pumpAndSettle();
+
+ expect(find.byType(VirtualKeyboardConfigView), findsNothing);
+ expect(find.byType(SettingsView), findsOneWidget);
+ });
+
+ testWidgets('VirtualKeyboardConfigView enforces row key limits and preserves expansion across page navigation', (tester) async {
+ final settingsProvider = SettingsProvider();
+ await settingsProvider.init();
+
+ await tester.pumpWidget(
+ ChangeNotifierProvider.value(
+ value: settingsProvider,
+ child: const MaterialApp(
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ locale: Locale('zh'),
+ home: VirtualKeyboardConfigView(scope: KeyboardScope.editor),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ // Verify row 1 has 7 keys and count is 7
+ expect(settingsProvider.virtualKeyboardConfig.pages[0].count, equals(7));
+ expect(settingsProvider.virtualKeyboardConfig.pages[0].keys[0].length, equals(7));
+
+ // Attempt to add a key to row 1 (which already has 7 keys == count)
+ final addKeyButton = find.byTooltip('添加按键').first;
+ await tester.tap(addKeyButton);
+ await tester.pumpAndSettle();
+
+ // Toast shown, KeyEditDialog not opened
+ expect(find.byType(KeyEditDialog), findsNothing);
+ expect(find.textContaining('当前行按键数已达到上限'), findsOneWidget);
+
+ // Verify ExpansionTile starts collapsed
+ expect(find.text('7 个按键'), findsWidgets);
+
+ // Tap first row ExpansionTile to expand
+ await tester.tap(find.text('7 个按键').first);
+ await tester.pumpAndSettle();
+
+ // Open drawer, switch to page 2, verify expansion state isolation
+ await tester.tap(find.byTooltip('页面管理'));
+ await tester.pumpAndSettle();
+ expect(find.text('第 2 页'), findsOneWidget);
+
+ await tester.tap(find.text('第 2 页'));
+ await tester.pumpAndSettle();
+
+ // On page 2, verify subtitle updated
+ expect(find.text('编辑区:(第 2 页)'), findsOneWidget);
+
+ // Switch back to page 1 via drawer, verify row 1 state persisted
+ await tester.tap(find.byTooltip('页面管理'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('第 1 页'));
+ await tester.pumpAndSettle();
+ expect(find.text('编辑区:(第 1 页)'), findsOneWidget);
+
+ // Test row deletion confirmation dialog
+ final deleteRowButton = find.byTooltip('删除整行').first;
+ await tester.tap(deleteRowButton);
+ await tester.pumpAndSettle();
+
+ expect(find.text('删除按键行'), findsOneWidget);
+ expect(find.textContaining('确定要删除“第 1 行”'), findsOneWidget);
+ await tester.tap(find.text('取消'));
+ await tester.pumpAndSettle();
+ expect(find.text('删除按键行'), findsNothing);
+
+ // Test key deletion confirmation dialog
+ final deleteKeyButton = find.byTooltip('删除按键').first;
+ await tester.tap(deleteKeyButton);
+ await tester.pumpAndSettle();
+
+ expect(find.text('删除按键'), findsOneWidget);
+ expect(find.textContaining('确定要删除按键'), findsOneWidget);
+ await tester.tap(find.text('取消'));
+ await tester.pumpAndSettle();
+ expect(find.text('删除按键'), findsNothing);
+ });
+
+ testWidgets('CodeEditorWidget pinch-to-zoom adjusts font size dynamically and saves to settings', (tester) async {
+ final tempDir = Directory.systemTemp.createTempSync('editor_zoom_test');
+ final testFile = File('${tempDir.path}/test.dart')..writeAsStringSync('void main() {}');
+
+ final settingsProvider = SettingsProvider();
+ await settingsProvider.init();
+ await settingsProvider.setFontSize(14.0);
+
+ final tabProvider = TabProvider();
+ await tabProvider.init();
+ tabProvider.openTabs.add(
+ EditorTabItem(
+ path: testFile.path,
+ content: 'void main() {}',
+ originalContent: 'void main() {}',
+ isLoaded: true,
+ isModified: false,
+ ),
+ );
+
+ await tester.pumpWidget(
+ MultiProvider(
+ providers: [
+ ChangeNotifierProvider.value(value: settingsProvider),
+ ChangeNotifierProvider.value(value: tabProvider),
+ ],
+ child: MaterialApp(
+ home: Scaffold(
+ body: CodeEditorWidget(
+ rootPath: tempDir.path,
+ filePath: testFile.path,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.byType(CodeEditor), findsOneWidget);
+ expect(settingsProvider.fontSize, 14.0);
+
+ // Simulate 2-pointer pinch gesture
+ final gesture1 = await tester.createGesture();
+ final gesture2 = await tester.createGesture();
+
+ await gesture1.down(const Offset(200, 300));
+ await gesture2.down(const Offset(200, 350)); // Initial distance: 50.0
+ await tester.pump();
+
+ // Move fingers apart to distance 100.0 (2x scale) -> target font size: 14 * 2 = 28.0
+ await gesture2.moveTo(const Offset(200, 400));
+ await tester.pump();
+
+ // Verify pinch HUD is visible
+ expect(find.text('28 pt'), findsOneWidget);
+
+ // Release pointers
+ await gesture1.up();
+ await gesture2.up();
+ await tester.pumpAndSettle();
+
+ // Verify HUD is removed and settingsProvider font size is updated to 28
+ expect(find.text('28 pt'), findsNothing);
+ expect(settingsProvider.fontSize, 28.0);
+
+ try {
+ tempDir.deleteSync(recursive: true);
+ } catch (_) {}
});
});
}