This commit is contained in:
LZX committed 2026-09-14 00:06:49 +08:00
1 parent 9fbb414ee6
commit 4554f22c87
233 files changed
+147430 -605

No files matched your search

+155 -8
View File
@@ -71,6 +71,27 @@
"darkThemeCategory": "Dark Theme",
"lightThemeCategory": "Light Theme",
"codeFontSize": "Font Size",
"uiFont": "Interface Font",
"selectUiFont": "Select Interface Font",
"themeColor": "Theme Color",
"selectThemeColor": "Select Theme Color",
"terminalBackgroundColor": "Terminal Background",
"selectTerminalBackgroundColor": "Select Terminal Background",
"uiFontPreview": "Code Editor interface font preview 123",
"codeFont": "Code Font",
"selectCodeFont": "Select Code Font",
"codeFontPreview": "const app = \"Code Editor\"; // code preview",
"terminalFont": "Terminal Font",
"selectTerminalFont": "Select Terminal Font",
"terminalFontPreview": "$ git status -s # terminal font preview",
"fontName": "{font, select, system_default{System Default} sans_serif{Sans-Serif} serif{Serif (Songti)} monospace{System Monospace} consolas{Consolas} courier_new{Courier New} menlo{Menlo / Monaco} jetbrains_mono{JetBrains Mono} fira_code{Fira Code} other{{font}}}",
"@fontName": {
"placeholders": {
"font": {
"type": "String"
}
}
},
"decreaseFontSize": "Decrease font size",
"increaseFontSize": "Increase font size",
"fontSizeDialogTitle": "Editor Font Size",
@@ -91,6 +112,10 @@
"virtualKeyboardSubtitle": "Show accessory symbols and shortcuts below the code editor",
"editVirtualKeyboardConfig": "Edit Keyboard Config",
"editVirtualKeyboardConfigSubtitle": "Customize keyboard layout and shortcuts",
"terminalVirtualKeyboard": "Terminal Accessory Keyboard",
"terminalVirtualKeyboardSubtitle": "Show special keys and command shortcuts below the terminal",
"editTerminalVirtualKeyboardConfig": "Edit Terminal Keyboard Config",
"editTerminalVirtualKeyboardConfigSubtitle": "Customize Esc / Tab / Ctrl combos and other terminal keys",
"virtualKeyboardDialogTitle": "Keyboard Config (JSON)",
"resetDefault": "Reset to Default",
"configFormatError": "Configuration format error",
@@ -361,17 +386,139 @@
"keyboardLabelFormFieldHint": "Text displayed on the key, e.g. Tab, (), A",
"keyboardLabelOrIconRequiredError": "Please enter display text or select an icon",
"keyboardIconFormField": "Icon (Optional)",
"keyboardIconName": "{icon, select, undo{Undo} redo{Redo} tab{Indent} untab{Outdent} outdent{Decrease Indent} arrow_left{Left Arrow} arrow_right{Right Arrow} arrow_up{Up Arrow} arrow_down{Down Arrow} home{Line Start} end{Line End} first_page{Document Start} last_page{Document End} page_up{Page Up} page_down{Page Down} enter{Enter} space{Space} escape{Escape} insert{Insert} clear{Clear} keyboard{Keyboard} backspace{Backspace} delete{Delete} copy{Copy} cut{Cut} paste{Paste} save{Save} search{Search} select_all{Select All} keyboard_hide{Hide Keyboard} other{{icon}}}",
"@keyboardIconName": {
"placeholders": {
"icon": {
"type": "String"
}
}
},
"keyboardNoIconOption": "No icon (Use text)",
"keyboardActionFormField": "Action",
"keyboardValueFormField": "Input Text (Value)",
"keyboardActionName": "{action, select, input{Plain Text} pair{Pair Symbols} command{Editor Command} modifier{Modifier Key} key{Special Key} other{{action}}}",
"@keyboardActionName": {
"placeholders": {
"action": {
"type": "String"
}
}
},
"keyboardActionInputTerminal": "Command Shortcut",
"keyboardKeyFormField": "Special Key",
"keyboardKeyGroupNavigation": "Navigation",
"keyboardKeyGroupEditing": "Editing",
"keyboardKeyGroupFunctionKeys": "Function Keys",
"keyboardKeyGroupLetters": "Letters",
"keyboardAutoEnter": "Send Enter after",
"keyboardKeyName": "{key, select, escape{Escape} tab{Tab} backtab{Backtab} returnKey{Return} enter{Enter} numpadEnter{Keypad Enter} backspace{Backspace} delete{Delete} insert{Insert} space{Space} numpadClear{Clear} arrowUp{Up} arrowDown{Down} arrowLeft{Left} arrowRight{Right} home{Home} end{End} pageUp{Page Up} pageDown{Page Down} f1{F1} f2{F2} f3{F3} f4{F4} f5{F5} f6{F6} f7{F7} f8{F8} f9{F9} f10{F10} f11{F11} f12{F12} other{{key}}}",
"@keyboardKeyName": {
"placeholders": {
"key": {
"type": "String"
}
}
},
"keyboardKeyInvalidError": "This key produces no output in the terminal; please pick a listed special key",
"keyboardValueFormField": "Input Text",
"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",
"keyboardPairValueFormField": "Pair Symbols",
"keyboardPairValueFormFieldHint": "e.g. (), [], \"\", <>",
"keyboardPairValueRequiredError": "Please enter the pair symbols",
"keyboardPairValueInvalidError": "Enter at least 2 characters with different halves, e.g. (), []",
"keyboardCommandPresetFormField": "Editor Command",
"keyboardCommandName": "{command, select, tab{Indent} untab{Outdent} undo{Undo} redo{Redo} cursor_left{Cursor Left} cursor_right{Cursor Right} cursor_up{Cursor Up} cursor_down{Cursor Down} line_start{Move to Line Start} line_end{Move to Line End} page_start{Move to Document Start} page_end{Move to Document End} copy{Copy} cut{Cut} paste{Paste} delete{Delete} select_all{Select All} keyboard_hide{Hide Keyboard} other{{command}}}",
"@keyboardCommandName": {
"placeholders": {
"command": {
"type": "String"
}
}
},
"keyboardModifierPresetFormField": "Terminal Modifier",
"keyboardModifierName": "{modifier, select, ctrl{Ctrl Key} alt{Alt Key} shift{Shift Key} other{{modifier}}}",
"@keyboardModifierName": {
"placeholders": {
"modifier": {
"type": "String"
}
}
},
"keyboardCursorOffsetFormField": "Cursor Relative Offset",
"keyboardCursorOffsetRequiredError": "Please enter cursor offset (usually -1)",
"keyboardCursorOffsetIntegerError": "Offset must be an integer"
"keyboardCursorOffsetIntegerError": "Offset must be an integer",
"recommended": "Recommended",
"presetColors": "Preset Colors",
"hexColor": "Hex Color",
"currentColor": "Current",
"newColor": "Preview",
"runTasks": "Run Tasks",
"projectDetect": "Detect Project",
"projectDetecting": "Detecting project...",
"editRunTasks": "Edit Run Tasks",
"projectSection": "Project",
"showHiddenFiles": "Show Hidden Files",
"showHiddenFilesSubtitle": "Show hidden files and folders starting with dot (.) in file tree",
"searchTasksHint": "Search tasks...",
"noTasksAvailable": "No executable tasks available",
"noMatchingTasks": "No matching tasks found",
"userCustomTasks": "User Custom Tasks",
"systemDetectedTasks": "System Detected Tasks",
"editCustomTasksTooltip": "Edit Custom Tasks",
"runTasksConfig": "Run Tasks Configuration",
"editTask": "Edit Task",
"addTask": "Add Task",
"runTasksConfigSubtitle": "Configuration will be saved to .code_editor/run_tasks.json in project root",
"noCustomTasksInProject": "No custom tasks in current project",
"createNow": "Create Now",
"saveAndApply": "Save & Apply",
"taskNameRequired": "Task Name *",
"taskNameHint": "e.g. Build & Run Debug",
"taskNameEmptyError": "Please enter task name",
"shellCommandRequired": "Shell Command *",
"shellCommandHint": "e.g. cmake -B build && cmake --build build",
"shellCommandEmptyError": "Please enter command",
"taskDescOptional": "Description (Optional)",
"taskDescHint": "Briefly describe the task purpose",
"clearBeforeRun": "Clear Screen (clear)",
"clearBeforeRunSubtitle": "Clear terminal output before executing task",
"runTasksUpdated": "Run tasks configuration updated",
"detectCompletedMessage": "Detection completed, found {count} tasks",
"@detectCompletedMessage": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"pleaseOpenProjectFirst": "Please open a project first",
"deleteTaskConfirmMessage": "Are you sure you want to delete task \"{name}\"?",
"@deleteTaskConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSelectedTasksConfirmMessage": "Are you sure you want to delete the selected {count} tasks?",
"@deleteSelectedTasksConfirmMessage": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"deleteSelected": "Delete Selected",
"selectTasksToDelete": "Select Tasks to Delete",
"selectedCount": "{count} selected",
"@selectedCount": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"unsavedTaskChangesTitle": "Unsaved Task Changes",
"unsavedTaskChangesMessage": "The task has been modified. Do you want to discard unsaved changes and leave?"
}
+481 -19
View File
@@ -524,6 +524,90 @@ abstract class AppLocalizations {
/// **'代码字号缩放'**
String get codeFontSize;
/// No description provided for @uiFont.
///
/// In zh, this message translates to:
/// **'界面字体'**
String get uiFont;
/// No description provided for @selectUiFont.
///
/// In zh, this message translates to:
/// **'选择界面字体'**
String get selectUiFont;
/// No description provided for @themeColor.
///
/// In zh, this message translates to:
/// **'主题颜色'**
String get themeColor;
/// No description provided for @selectThemeColor.
///
/// In zh, this message translates to:
/// **'选择主题颜色'**
String get selectThemeColor;
/// No description provided for @terminalBackgroundColor.
///
/// In zh, this message translates to:
/// **'终端背景颜色'**
String get terminalBackgroundColor;
/// No description provided for @selectTerminalBackgroundColor.
///
/// In zh, this message translates to:
/// **'选择终端背景颜色'**
String get selectTerminalBackgroundColor;
/// No description provided for @uiFontPreview.
///
/// In zh, this message translates to:
/// **'代码编辑器界面字体预览 Code Editor 123'**
String get uiFontPreview;
/// No description provided for @codeFont.
///
/// In zh, this message translates to:
/// **'代码字体'**
String get codeFont;
/// No description provided for @selectCodeFont.
///
/// In zh, this message translates to:
/// **'选择代码字体'**
String get selectCodeFont;
/// No description provided for @codeFontPreview.
///
/// In zh, this message translates to:
/// **'const app = \"Code Editor\"; // 代码预览'**
String get codeFontPreview;
/// No description provided for @terminalFont.
///
/// In zh, this message translates to:
/// **'终端字体'**
String get terminalFont;
/// No description provided for @selectTerminalFont.
///
/// In zh, this message translates to:
/// **'选择终端字体'**
String get selectTerminalFont;
/// No description provided for @terminalFontPreview.
///
/// In zh, this message translates to:
/// **'\$ git status -s # 终端字体预览'**
String get terminalFontPreview;
/// No description provided for @fontName.
///
/// In zh, this message translates to:
/// **'{font, select, system_default{系统默认} sans_serif{无衬线体} serif{衬线体(宋体)} monospace{系统等宽} consolas{Consolas} courier_new{Courier New} menlo{Menlo / Monaco} jetbrains_mono{JetBrains Mono} fira_code{Fira Code} other{{font}}}'**
String fontName(String font);
/// No description provided for @decreaseFontSize.
///
/// In zh, this message translates to:
@@ -596,6 +680,30 @@ abstract class AppLocalizations {
/// **'自定义小键盘按键布局与快捷键'**
String get editVirtualKeyboardConfigSubtitle;
/// No description provided for @terminalVirtualKeyboard.
///
/// In zh, this message translates to:
/// **'终端小键盘'**
String get terminalVirtualKeyboard;
/// No description provided for @terminalVirtualKeyboardSubtitle.
///
/// In zh, this message translates to:
/// **'在终端下方显示常用特殊键与指令快捷键'**
String get terminalVirtualKeyboardSubtitle;
/// No description provided for @editTerminalVirtualKeyboardConfig.
///
/// In zh, this message translates to:
/// **'编辑终端键盘配置'**
String get editTerminalVirtualKeyboardConfig;
/// No description provided for @editTerminalVirtualKeyboardConfigSubtitle.
///
/// In zh, this message translates to:
/// **'自定义 Esc / Tab / Ctrl 组合等终端专用按键'**
String get editTerminalVirtualKeyboardConfigSubtitle;
/// No description provided for @virtualKeyboardDialogTitle.
///
/// In zh, this message translates to:
@@ -1259,7 +1367,7 @@ abstract class AppLocalizations {
/// No description provided for @keyboardLabelFormField.
///
/// In zh, this message translates to:
/// **'显示文本 (Label)'**
/// **'显示文本'**
String get keyboardLabelFormField;
/// No description provided for @keyboardLabelFormFieldHint.
@@ -1277,9 +1385,15 @@ abstract class AppLocalizations {
/// No description provided for @keyboardIconFormField.
///
/// In zh, this message translates to:
/// **'图标 (Icon, 可选)'**
/// **'图标 (可选)'**
String get keyboardIconFormField;
/// No description provided for @keyboardIconName.
///
/// In zh, this message translates to:
/// **'{icon, select, undo{撤销} redo{重做} tab{向右缩进} untab{向左缩进} outdent{减少缩进} arrow_left{左箭头} arrow_right{右箭头} arrow_up{上箭头} arrow_down{下箭头} home{移至行首} end{移至行尾} first_page{移至文首} last_page{移至文末} page_up{上翻页} page_down{下翻页} enter{回车} space{空格} escape{退出} insert{插入} clear{清除} keyboard{键盘} backspace{退格} delete{删除} copy{复制} cut{剪切} paste{粘贴} save{保存} search{搜索} select_all{全选} keyboard_hide{收起小键盘} other{{icon}}}'**
String keyboardIconName(String icon);
/// No description provided for @keyboardNoIconOption.
///
/// In zh, this message translates to:
@@ -1289,13 +1403,73 @@ abstract class AppLocalizations {
/// No description provided for @keyboardActionFormField.
///
/// In zh, this message translates to:
/// **'动作类型 (Action)'**
/// **'动作类型'**
String get keyboardActionFormField;
/// No description provided for @keyboardActionName.
///
/// In zh, this message translates to:
/// **'{action, select, input{普通文本} pair{成对符号} command{编辑器命令} modifier{修饰键} key{特殊键} other{{action}}}'**
String keyboardActionName(String action);
/// No description provided for @keyboardActionInputTerminal.
///
/// In zh, this message translates to:
/// **'指令快捷键'**
String get keyboardActionInputTerminal;
/// No description provided for @keyboardKeyFormField.
///
/// In zh, this message translates to:
/// **'特殊键'**
String get keyboardKeyFormField;
/// No description provided for @keyboardKeyGroupNavigation.
///
/// In zh, this message translates to:
/// **'导航键'**
String get keyboardKeyGroupNavigation;
/// No description provided for @keyboardKeyGroupEditing.
///
/// In zh, this message translates to:
/// **'编辑键'**
String get keyboardKeyGroupEditing;
/// No description provided for @keyboardKeyGroupFunctionKeys.
///
/// In zh, this message translates to:
/// **'功能键'**
String get keyboardKeyGroupFunctionKeys;
/// No description provided for @keyboardKeyGroupLetters.
///
/// In zh, this message translates to:
/// **'字母键'**
String get keyboardKeyGroupLetters;
/// No description provided for @keyboardAutoEnter.
///
/// In zh, this message translates to:
/// **'发送后自动回车'**
String get keyboardAutoEnter;
/// No description provided for @keyboardKeyName.
///
/// In zh, this message translates to:
/// **'{key, select, escape{退出} tab{Tab} backtab{反向制表} returnKey{回车} enter{回车} numpadEnter{小键盘回车} backspace{退格} delete{删除} insert{插入} space{空格} numpadClear{清除} arrowUp{上} arrowDown{下} arrowLeft{左} arrowRight{右} home{行首} end{行尾} pageUp{上翻页} pageDown{下翻页} f1{F1} f2{F2} f3{F3} f4{F4} f5{F5} f6{F6} f7{F7} f8{F8} f9{F9} f10{F10} f11{F11} f12{F12} other{{key}}}'**
String keyboardKeyName(String key);
/// No description provided for @keyboardKeyInvalidError.
///
/// In zh, this message translates to:
/// **'该键在终端中不会产生任何输出,请选择列表中的特殊键'**
String get keyboardKeyInvalidError;
/// No description provided for @keyboardValueFormField.
///
/// In zh, this message translates to:
/// **'输入文本内容 (Value)'**
/// **'输入文本内容'**
String get keyboardValueFormField;
/// No description provided for @keyboardValueFormFieldHint.
@@ -1310,42 +1484,60 @@ abstract class AppLocalizations {
/// **'输入文本不能为空'**
String get keyboardValueRequiredError;
/// No description provided for @keyboardPairPresetFormField.
/// No description provided for @keyboardPairValueFormField.
///
/// In zh, this message translates to:
/// **'成对符号预设 (Value)'**
String get keyboardPairPresetFormField;
/// **'成对符号'**
String get keyboardPairValueFormField;
/// No description provided for @keyboardPairValueFormFieldHint.
///
/// In zh, this message translates to:
/// **'例如 ()、[]、\"\"、<>'**
String get keyboardPairValueFormFieldHint;
/// No description provided for @keyboardPairValueRequiredError.
///
/// In zh, this message translates to:
/// **'请输入成对符号'**
String get keyboardPairValueRequiredError;
/// No description provided for @keyboardPairValueInvalidError.
///
/// In zh, this message translates to:
/// **'请输入至少 2 个字符且左右不同的成对符号,如 ()、[]'**
String get keyboardPairValueInvalidError;
/// No description provided for @keyboardCommandPresetFormField.
///
/// In zh, this message translates to:
/// **'预设编辑器命令 (Value)'**
/// **'编辑器命令'**
String get keyboardCommandPresetFormField;
/// No description provided for @keyboardCommandName.
///
/// In zh, this message translates to:
/// **'{command, select, tab{向右缩进} untab{向左缩进} undo{撤销} redo{重做} cursor_left{光标左移} cursor_right{光标右移} cursor_up{光标上移} cursor_down{光标下移} line_start{移动至行首} line_end{移动至行尾} page_start{移动至文首} page_end{移动至文末} copy{复制} cut{剪切} paste{粘贴} delete{删除} select_all{全选} keyboard_hide{收起小键盘} other{{command}}}'**
String keyboardCommandName(String command);
/// No description provided for @keyboardModifierPresetFormField.
///
/// In zh, this message translates to:
/// **'终端修饰键 (Value)'**
/// **'终端修饰键'**
String get keyboardModifierPresetFormField;
/// No description provided for @keyboardTerminalKeyPresetFormField.
/// No description provided for @keyboardModifierName.
///
/// In zh, this message translates to:
/// **'终端按键 (Value)'**
String get keyboardTerminalKeyPresetFormField;
/// **'{modifier, select, ctrl{Ctrl 键} alt{Alt 键} shift{Shift 键} other{{modifier}}}'**
String keyboardModifierName(String modifier);
/// 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:
@@ -1357,6 +1549,276 @@ abstract class AppLocalizations {
/// In zh, this message translates to:
/// **'偏移量必须为整数'**
String get keyboardCursorOffsetIntegerError;
/// No description provided for @recommended.
///
/// In zh, this message translates to:
/// **'推荐'**
String get recommended;
/// No description provided for @presetColors.
///
/// In zh, this message translates to:
/// **'预设颜色'**
String get presetColors;
/// No description provided for @hexColor.
///
/// In zh, this message translates to:
/// **'十六进制颜色'**
String get hexColor;
/// No description provided for @currentColor.
///
/// In zh, this message translates to:
/// **'当前'**
String get currentColor;
/// No description provided for @newColor.
///
/// In zh, this message translates to:
/// **'预览'**
String get newColor;
/// No description provided for @runTasks.
///
/// In zh, this message translates to:
/// **'运行任务'**
String get runTasks;
/// No description provided for @projectDetect.
///
/// In zh, this message translates to:
/// **'项目探测'**
String get projectDetect;
/// No description provided for @projectDetecting.
///
/// In zh, this message translates to:
/// **'正在探测项目...'**
String get projectDetecting;
/// No description provided for @editRunTasks.
///
/// In zh, this message translates to:
/// **'运行任务编辑'**
String get editRunTasks;
/// No description provided for @projectSection.
///
/// In zh, this message translates to:
/// **'项目'**
String get projectSection;
/// No description provided for @showHiddenFiles.
///
/// In zh, this message translates to:
/// **'显示隐藏文件'**
String get showHiddenFiles;
/// No description provided for @showHiddenFilesSubtitle.
///
/// In zh, this message translates to:
/// **'在文件树中展示以点 (.) 开头的隐藏文件与文件夹'**
String get showHiddenFilesSubtitle;
/// No description provided for @searchTasksHint.
///
/// In zh, this message translates to:
/// **'搜索指定任务...'**
String get searchTasksHint;
/// No description provided for @noTasksAvailable.
///
/// In zh, this message translates to:
/// **'暂无可执行任务'**
String get noTasksAvailable;
/// No description provided for @noMatchingTasks.
///
/// In zh, this message translates to:
/// **'无匹配的任务'**
String get noMatchingTasks;
/// No description provided for @userCustomTasks.
///
/// In zh, this message translates to:
/// **'用户自定义任务'**
String get userCustomTasks;
/// No description provided for @systemDetectedTasks.
///
/// In zh, this message translates to:
/// **'系统动态探测任务'**
String get systemDetectedTasks;
/// No description provided for @editCustomTasksTooltip.
///
/// In zh, this message translates to:
/// **'编辑自定义任务'**
String get editCustomTasksTooltip;
/// No description provided for @runTasksConfig.
///
/// In zh, this message translates to:
/// **'运行任务配置'**
String get runTasksConfig;
/// No description provided for @editTask.
///
/// In zh, this message translates to:
/// **'编辑任务'**
String get editTask;
/// No description provided for @addTask.
///
/// In zh, this message translates to:
/// **'新增任务'**
String get addTask;
/// No description provided for @runTasksConfigSubtitle.
///
/// In zh, this message translates to:
/// **'配置将自动保存至项目根目录下的 .code_editor/run_tasks.json'**
String get runTasksConfigSubtitle;
/// No description provided for @noCustomTasksInProject.
///
/// In zh, this message translates to:
/// **'当前项目暂无自定义任务'**
String get noCustomTasksInProject;
/// No description provided for @createNow.
///
/// In zh, this message translates to:
/// **'立即创建'**
String get createNow;
/// No description provided for @saveAndApply.
///
/// In zh, this message translates to:
/// **'保存并应用'**
String get saveAndApply;
/// No description provided for @taskNameRequired.
///
/// In zh, this message translates to:
/// **'任务名称 *'**
String get taskNameRequired;
/// No description provided for @taskNameHint.
///
/// In zh, this message translates to:
/// **'如: 编译并运行 Debug'**
String get taskNameHint;
/// No description provided for @taskNameEmptyError.
///
/// In zh, this message translates to:
/// **'请输入任务名称'**
String get taskNameEmptyError;
/// No description provided for @shellCommandRequired.
///
/// In zh, this message translates to:
/// **'Shell 执行指令 *'**
String get shellCommandRequired;
/// No description provided for @shellCommandHint.
///
/// In zh, this message translates to:
/// **'如: cmake -B build && cmake --build build'**
String get shellCommandHint;
/// No description provided for @shellCommandEmptyError.
///
/// In zh, this message translates to:
/// **'请输入执行指令'**
String get shellCommandEmptyError;
/// No description provided for @taskDescOptional.
///
/// In zh, this message translates to:
/// **'任务描述(选填)'**
String get taskDescOptional;
/// No description provided for @taskDescHint.
///
/// In zh, this message translates to:
/// **'简要说明此任务的用途'**
String get taskDescHint;
/// No description provided for @clearBeforeRun.
///
/// In zh, this message translates to:
/// **'执行前清屏 (clear)'**
String get clearBeforeRun;
/// No description provided for @clearBeforeRunSubtitle.
///
/// In zh, this message translates to:
/// **'在终端输出任务结果前清理历史屏幕'**
String get clearBeforeRunSubtitle;
/// No description provided for @runTasksUpdated.
///
/// In zh, this message translates to:
/// **'运行任务配置已更新'**
String get runTasksUpdated;
/// No description provided for @detectCompletedMessage.
///
/// In zh, this message translates to:
/// **'探测完成,发现 {count} 个可用任务'**
String detectCompletedMessage(int count);
/// No description provided for @pleaseOpenProjectFirst.
///
/// In zh, this message translates to:
/// **'请先打开一个项目'**
String get pleaseOpenProjectFirst;
/// No description provided for @deleteTaskConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要删除任务 \"{name}\" 吗?'**
String deleteTaskConfirmMessage(String name);
/// No description provided for @deleteSelectedTasksConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要删除选中的 {count} 个任务吗?'**
String deleteSelectedTasksConfirmMessage(int count);
/// No description provided for @deleteSelected.
///
/// In zh, this message translates to:
/// **'删除选中'**
String get deleteSelected;
/// No description provided for @selectTasksToDelete.
///
/// In zh, this message translates to:
/// **'选择要删除的任务'**
String get selectTasksToDelete;
/// No description provided for @selectedCount.
///
/// In zh, this message translates to:
/// **'已选 {count} 项'**
String selectedCount(int count);
/// No description provided for @unsavedTaskChangesTitle.
///
/// In zh, this message translates to:
/// **'未保存的任务更改'**
String get unsavedTaskChangesTitle;
/// No description provided for @unsavedTaskChangesMessage.
///
/// In zh, this message translates to:
/// **'当前任务内容已被修改,是否放弃未保存的修改并返回?'**
String get unsavedTaskChangesMessage;
}
class _AppLocalizationsDelegate
+381 -9
View File
@@ -241,6 +241,62 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get codeFontSize => 'Font Size';
@override
String get uiFont => 'Interface Font';
@override
String get selectUiFont => 'Select Interface Font';
@override
String get themeColor => 'Theme Color';
@override
String get selectThemeColor => 'Select Theme Color';
@override
String get terminalBackgroundColor => 'Terminal Background';
@override
String get selectTerminalBackgroundColor => 'Select Terminal Background';
@override
String get uiFontPreview => 'Code Editor interface font preview 123';
@override
String get codeFont => 'Code Font';
@override
String get selectCodeFont => 'Select Code Font';
@override
String get codeFontPreview => 'const app = \"Code Editor\"; // code preview';
@override
String get terminalFont => 'Terminal Font';
@override
String get selectTerminalFont => 'Select Terminal Font';
@override
String get terminalFontPreview => '\$ git status -s # terminal font preview';
@override
String fontName(String font) {
String _temp0 = intl.Intl.selectLogic(font, {
'system_default': 'System Default',
'sans_serif': 'Sans-Serif',
'serif': 'Serif (Songti)',
'monospace': 'System Monospace',
'consolas': 'Consolas',
'courier_new': 'Courier New',
'menlo': 'Menlo / Monaco',
'jetbrains_mono': 'JetBrains Mono',
'fira_code': 'Fira Code',
'other': '$font',
});
return '$_temp0';
}
@override
String get decreaseFontSize => 'Decrease font size';
@@ -281,6 +337,21 @@ class AppLocalizationsEn extends AppLocalizations {
String get editVirtualKeyboardConfigSubtitle =>
'Customize keyboard layout and shortcuts';
@override
String get terminalVirtualKeyboard => 'Terminal Accessory Keyboard';
@override
String get terminalVirtualKeyboardSubtitle =>
'Show special keys and command shortcuts below the terminal';
@override
String get editTerminalVirtualKeyboardConfig =>
'Edit Terminal Keyboard Config';
@override
String get editTerminalVirtualKeyboardConfigSubtitle =>
'Customize Esc / Tab / Ctrl combos and other terminal keys';
@override
String get virtualKeyboardDialogTitle => 'Keyboard Config (JSON)';
@@ -683,6 +754,44 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get keyboardIconFormField => 'Icon (Optional)';
@override
String keyboardIconName(String icon) {
String _temp0 = intl.Intl.selectLogic(icon, {
'undo': 'Undo',
'redo': 'Redo',
'tab': 'Indent',
'untab': 'Outdent',
'outdent': 'Decrease Indent',
'arrow_left': 'Left Arrow',
'arrow_right': 'Right Arrow',
'arrow_up': 'Up Arrow',
'arrow_down': 'Down Arrow',
'home': 'Line Start',
'end': 'Line End',
'first_page': 'Document Start',
'last_page': 'Document End',
'page_up': 'Page Up',
'page_down': 'Page Down',
'enter': 'Enter',
'space': 'Space',
'escape': 'Escape',
'insert': 'Insert',
'clear': 'Clear',
'keyboard': 'Keyboard',
'backspace': 'Backspace',
'delete': 'Delete',
'copy': 'Copy',
'cut': 'Cut',
'paste': 'Paste',
'save': 'Save',
'search': 'Search',
'select_all': 'Select All',
'keyboard_hide': 'Hide Keyboard',
'other': '$icon',
});
return '$_temp0';
}
@override
String get keyboardNoIconOption => 'No icon (Use text)';
@@ -690,7 +799,84 @@ class AppLocalizationsEn extends AppLocalizations {
String get keyboardActionFormField => 'Action';
@override
String get keyboardValueFormField => 'Input Text (Value)';
String keyboardActionName(String action) {
String _temp0 = intl.Intl.selectLogic(action, {
'input': 'Plain Text',
'pair': 'Pair Symbols',
'command': 'Editor Command',
'modifier': 'Modifier Key',
'key': 'Special Key',
'other': '$action',
});
return '$_temp0';
}
@override
String get keyboardActionInputTerminal => 'Command Shortcut';
@override
String get keyboardKeyFormField => 'Special Key';
@override
String get keyboardKeyGroupNavigation => 'Navigation';
@override
String get keyboardKeyGroupEditing => 'Editing';
@override
String get keyboardKeyGroupFunctionKeys => 'Function Keys';
@override
String get keyboardKeyGroupLetters => 'Letters';
@override
String get keyboardAutoEnter => 'Send Enter after';
@override
String keyboardKeyName(String key) {
String _temp0 = intl.Intl.selectLogic(key, {
'escape': 'Escape',
'tab': 'Tab',
'backtab': 'Backtab',
'returnKey': 'Return',
'enter': 'Enter',
'numpadEnter': 'Keypad Enter',
'backspace': 'Backspace',
'delete': 'Delete',
'insert': 'Insert',
'space': 'Space',
'numpadClear': 'Clear',
'arrowUp': 'Up',
'arrowDown': 'Down',
'arrowLeft': 'Left',
'arrowRight': 'Right',
'home': 'Home',
'end': 'End',
'pageUp': 'Page Up',
'pageDown': 'Page Down',
'f1': 'F1',
'f2': 'F2',
'f3': 'F3',
'f4': 'F4',
'f5': 'F5',
'f6': 'F6',
'f7': 'F7',
'f8': 'F8',
'f9': 'F9',
'f10': 'F10',
'f11': 'F11',
'f12': 'F12',
'other': '$key',
});
return '$_temp0';
}
@override
String get keyboardKeyInvalidError =>
'This key produces no output in the terminal; please pick a listed special key';
@override
String get keyboardValueFormField => 'Input Text';
@override
String get keyboardValueFormFieldHint =>
@@ -700,24 +886,63 @@ class AppLocalizationsEn extends AppLocalizations {
String get keyboardValueRequiredError => 'Input text cannot be empty';
@override
String get keyboardPairPresetFormField => 'Pair Symbols Preset (Value)';
String get keyboardPairValueFormField => 'Pair Symbols';
@override
String get keyboardCommandPresetFormField => 'Editor Command Preset (Value)';
String get keyboardPairValueFormFieldHint => 'e.g. (), [], \"\", <>';
@override
String get keyboardModifierPresetFormField => 'Terminal Modifier (Value)';
String get keyboardPairValueRequiredError => 'Please enter the pair symbols';
@override
String get keyboardTerminalKeyPresetFormField => 'Terminal Key (Value)';
String get keyboardPairValueInvalidError =>
'Enter at least 2 characters with different halves, e.g. (), []';
@override
String get keyboardCursorOffsetFormField =>
'Cursor Relative Offset (cursorOffset)';
String get keyboardCommandPresetFormField => 'Editor Command';
@override
String get keyboardCursorOffsetHelper =>
'e.g. For () cursor in center should move left by 1, enter -1';
String keyboardCommandName(String command) {
String _temp0 = intl.Intl.selectLogic(command, {
'tab': 'Indent',
'untab': 'Outdent',
'undo': 'Undo',
'redo': 'Redo',
'cursor_left': 'Cursor Left',
'cursor_right': 'Cursor Right',
'cursor_up': 'Cursor Up',
'cursor_down': 'Cursor Down',
'line_start': 'Move to Line Start',
'line_end': 'Move to Line End',
'page_start': 'Move to Document Start',
'page_end': 'Move to Document End',
'copy': 'Copy',
'cut': 'Cut',
'paste': 'Paste',
'delete': 'Delete',
'select_all': 'Select All',
'keyboard_hide': 'Hide Keyboard',
'other': '$command',
});
return '$_temp0';
}
@override
String get keyboardModifierPresetFormField => 'Terminal Modifier';
@override
String keyboardModifierName(String modifier) {
String _temp0 = intl.Intl.selectLogic(modifier, {
'ctrl': 'Ctrl Key',
'alt': 'Alt Key',
'shift': 'Shift Key',
'other': '$modifier',
});
return '$_temp0';
}
@override
String get keyboardCursorOffsetFormField => 'Cursor Relative Offset';
@override
String get keyboardCursorOffsetRequiredError =>
@@ -725,4 +950,151 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get keyboardCursorOffsetIntegerError => 'Offset must be an integer';
@override
String get recommended => 'Recommended';
@override
String get presetColors => 'Preset Colors';
@override
String get hexColor => 'Hex Color';
@override
String get currentColor => 'Current';
@override
String get newColor => 'Preview';
@override
String get runTasks => 'Run Tasks';
@override
String get projectDetect => 'Detect Project';
@override
String get projectDetecting => 'Detecting project...';
@override
String get editRunTasks => 'Edit Run Tasks';
@override
String get projectSection => 'Project';
@override
String get showHiddenFiles => 'Show Hidden Files';
@override
String get showHiddenFilesSubtitle =>
'Show hidden files and folders starting with dot (.) in file tree';
@override
String get searchTasksHint => 'Search tasks...';
@override
String get noTasksAvailable => 'No executable tasks available';
@override
String get noMatchingTasks => 'No matching tasks found';
@override
String get userCustomTasks => 'User Custom Tasks';
@override
String get systemDetectedTasks => 'System Detected Tasks';
@override
String get editCustomTasksTooltip => 'Edit Custom Tasks';
@override
String get runTasksConfig => 'Run Tasks Configuration';
@override
String get editTask => 'Edit Task';
@override
String get addTask => 'Add Task';
@override
String get runTasksConfigSubtitle =>
'Configuration will be saved to .code_editor/run_tasks.json in project root';
@override
String get noCustomTasksInProject => 'No custom tasks in current project';
@override
String get createNow => 'Create Now';
@override
String get saveAndApply => 'Save & Apply';
@override
String get taskNameRequired => 'Task Name *';
@override
String get taskNameHint => 'e.g. Build & Run Debug';
@override
String get taskNameEmptyError => 'Please enter task name';
@override
String get shellCommandRequired => 'Shell Command *';
@override
String get shellCommandHint => 'e.g. cmake -B build && cmake --build build';
@override
String get shellCommandEmptyError => 'Please enter command';
@override
String get taskDescOptional => 'Description (Optional)';
@override
String get taskDescHint => 'Briefly describe the task purpose';
@override
String get clearBeforeRun => 'Clear Screen (clear)';
@override
String get clearBeforeRunSubtitle =>
'Clear terminal output before executing task';
@override
String get runTasksUpdated => 'Run tasks configuration updated';
@override
String detectCompletedMessage(int count) {
return 'Detection completed, found $count tasks';
}
@override
String get pleaseOpenProjectFirst => 'Please open a project first';
@override
String deleteTaskConfirmMessage(String name) {
return 'Are you sure you want to delete task \"$name\"?';
}
@override
String deleteSelectedTasksConfirmMessage(int count) {
return 'Are you sure you want to delete the selected $count tasks?';
}
@override
String get deleteSelected => 'Delete Selected';
@override
String get selectTasksToDelete => 'Select Tasks to Delete';
@override
String selectedCount(int count) {
return '$count selected';
}
@override
String get unsavedTaskChangesTitle => 'Unsaved Task Changes';
@override
String get unsavedTaskChangesMessage =>
'The task has been modified. Do you want to discard unsaved changes and leave?';
}
+377 -10
View File
@@ -237,6 +237,62 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get codeFontSize => '代码字号缩放';
@override
String get uiFont => '界面字体';
@override
String get selectUiFont => '选择界面字体';
@override
String get themeColor => '主题颜色';
@override
String get selectThemeColor => '选择主题颜色';
@override
String get terminalBackgroundColor => '终端背景颜色';
@override
String get selectTerminalBackgroundColor => '选择终端背景颜色';
@override
String get uiFontPreview => '代码编辑器界面字体预览 Code Editor 123';
@override
String get codeFont => '代码字体';
@override
String get selectCodeFont => '选择代码字体';
@override
String get codeFontPreview => 'const app = \"Code Editor\"; // 代码预览';
@override
String get terminalFont => '终端字体';
@override
String get selectTerminalFont => '选择终端字体';
@override
String get terminalFontPreview => '\$ git status -s # 终端字体预览';
@override
String fontName(String font) {
String _temp0 = intl.Intl.selectLogic(font, {
'system_default': '系统默认',
'sans_serif': '无衬线体',
'serif': '衬线体(宋体)',
'monospace': '系统等宽',
'consolas': 'Consolas',
'courier_new': 'Courier New',
'menlo': 'Menlo / Monaco',
'jetbrains_mono': 'JetBrains Mono',
'fira_code': 'Fira Code',
'other': '$font',
});
return '$_temp0';
}
@override
String get decreaseFontSize => '减小字号';
@@ -275,6 +331,19 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get editVirtualKeyboardConfigSubtitle => '自定义小键盘按键布局与快捷键';
@override
String get terminalVirtualKeyboard => '终端小键盘';
@override
String get terminalVirtualKeyboardSubtitle => '在终端下方显示常用特殊键与指令快捷键';
@override
String get editTerminalVirtualKeyboardConfig => '编辑终端键盘配置';
@override
String get editTerminalVirtualKeyboardConfigSubtitle =>
'自定义 Esc / Tab / Ctrl 组合等终端专用按键';
@override
String get virtualKeyboardDialogTitle => '小键盘配置 (JSON)';
@@ -655,7 +724,7 @@ class AppLocalizationsZh extends AppLocalizations {
String get keyboardEditKeyTitle => '编辑按键';
@override
String get keyboardLabelFormField => '显示文本 (Label)';
String get keyboardLabelFormField => '显示文本';
@override
String get keyboardLabelFormFieldHint => '按键上显示的文本,如 Tab、()、A';
@@ -664,16 +733,130 @@ class AppLocalizationsZh extends AppLocalizations {
String get keyboardLabelOrIconRequiredError => '请输入显示文本或选择图标';
@override
String get keyboardIconFormField => '图标 (Icon, 可选)';
String get keyboardIconFormField => '图标 (可选)';
@override
String keyboardIconName(String icon) {
String _temp0 = intl.Intl.selectLogic(icon, {
'undo': '撤销',
'redo': '重做',
'tab': '向右缩进',
'untab': '向左缩进',
'outdent': '减少缩进',
'arrow_left': '左箭头',
'arrow_right': '右箭头',
'arrow_up': '上箭头',
'arrow_down': '下箭头',
'home': '移至行首',
'end': '移至行尾',
'first_page': '移至文首',
'last_page': '移至文末',
'page_up': '上翻页',
'page_down': '下翻页',
'enter': '回车',
'space': '空格',
'escape': '退出',
'insert': '插入',
'clear': '清除',
'keyboard': '键盘',
'backspace': '退格',
'delete': '删除',
'copy': '复制',
'cut': '剪切',
'paste': '粘贴',
'save': '保存',
'search': '搜索',
'select_all': '全选',
'keyboard_hide': '收起小键盘',
'other': '$icon',
});
return '$_temp0';
}
@override
String get keyboardNoIconOption => '无图标 (使用文本显示)';
@override
String get keyboardActionFormField => '动作类型 (Action)';
String get keyboardActionFormField => '动作类型';
@override
String get keyboardValueFormField => '输入文本内容 (Value)';
String keyboardActionName(String action) {
String _temp0 = intl.Intl.selectLogic(action, {
'input': '普通文本',
'pair': '成对符号',
'command': '编辑器命令',
'modifier': '修饰键',
'key': '特殊键',
'other': '$action',
});
return '$_temp0';
}
@override
String get keyboardActionInputTerminal => '指令快捷键';
@override
String get keyboardKeyFormField => '特殊键';
@override
String get keyboardKeyGroupNavigation => '导航键';
@override
String get keyboardKeyGroupEditing => '编辑键';
@override
String get keyboardKeyGroupFunctionKeys => '功能键';
@override
String get keyboardKeyGroupLetters => '字母键';
@override
String get keyboardAutoEnter => '发送后自动回车';
@override
String keyboardKeyName(String key) {
String _temp0 = intl.Intl.selectLogic(key, {
'escape': '退出',
'tab': 'Tab',
'backtab': '反向制表',
'returnKey': '回车',
'enter': '回车',
'numpadEnter': '小键盘回车',
'backspace': '退格',
'delete': '删除',
'insert': '插入',
'space': '空格',
'numpadClear': '清除',
'arrowUp': '上',
'arrowDown': '下',
'arrowLeft': '左',
'arrowRight': '右',
'home': '行首',
'end': '行尾',
'pageUp': '上翻页',
'pageDown': '下翻页',
'f1': 'F1',
'f2': 'F2',
'f3': 'F3',
'f4': 'F4',
'f5': 'F5',
'f6': 'F6',
'f7': 'F7',
'f8': 'F8',
'f9': 'F9',
'f10': 'F10',
'f11': 'F11',
'f12': 'F12',
'other': '$key',
});
return '$_temp0';
}
@override
String get keyboardKeyInvalidError => '该键在终端中不会产生任何输出,请选择列表中的特殊键';
@override
String get keyboardValueFormField => '输入文本内容';
@override
String get keyboardValueFormFieldHint => '点击后直接插入的文本,如 ;、=、->';
@@ -682,26 +865,210 @@ class AppLocalizationsZh extends AppLocalizations {
String get keyboardValueRequiredError => '输入文本不能为空';
@override
String get keyboardPairPresetFormField => '成对符号预设 (Value)';
String get keyboardPairValueFormField => '成对符号';
@override
String get keyboardCommandPresetFormField => '预设编辑器命令 (Value)';
String get keyboardPairValueFormFieldHint => '例如 ()、[]、\"\"、<>';
@override
String get keyboardModifierPresetFormField => '终端修饰键 (Value)';
String get keyboardPairValueRequiredError => '请输入成对符号';
@override
String get keyboardTerminalKeyPresetFormField => '终端按键 (Value)';
String get keyboardPairValueInvalidError => '请输入至少 2 个字符且左右不同的成对符号,如 ()、[]';
@override
String get keyboardCursorOffsetFormField => '光标相对偏移 (cursorOffset)';
String get keyboardCommandPresetFormField => '编辑器命令';
@override
String get keyboardCursorOffsetHelper => '例如 () 插入后光标居中需向左偏移 1 位,填写 -1';
String keyboardCommandName(String command) {
String _temp0 = intl.Intl.selectLogic(command, {
'tab': '向右缩进',
'untab': '向左缩进',
'undo': '撤销',
'redo': '重做',
'cursor_left': '光标左移',
'cursor_right': '光标右移',
'cursor_up': '光标上移',
'cursor_down': '光标下移',
'line_start': '移动至行首',
'line_end': '移动至行尾',
'page_start': '移动至文首',
'page_end': '移动至文末',
'copy': '复制',
'cut': '剪切',
'paste': '粘贴',
'delete': '删除',
'select_all': '全选',
'keyboard_hide': '收起小键盘',
'other': '$command',
});
return '$_temp0';
}
@override
String get keyboardModifierPresetFormField => '终端修饰键';
@override
String keyboardModifierName(String modifier) {
String _temp0 = intl.Intl.selectLogic(modifier, {
'ctrl': 'Ctrl 键',
'alt': 'Alt 键',
'shift': 'Shift 键',
'other': '$modifier',
});
return '$_temp0';
}
@override
String get keyboardCursorOffsetFormField => '光标相对偏移';
@override
String get keyboardCursorOffsetRequiredError => '请输入光标偏移(通常为 -1)';
@override
String get keyboardCursorOffsetIntegerError => '偏移量必须为整数';
@override
String get recommended => '推荐';
@override
String get presetColors => '预设颜色';
@override
String get hexColor => '十六进制颜色';
@override
String get currentColor => '当前';
@override
String get newColor => '预览';
@override
String get runTasks => '运行任务';
@override
String get projectDetect => '项目探测';
@override
String get projectDetecting => '正在探测项目...';
@override
String get editRunTasks => '运行任务编辑';
@override
String get projectSection => '项目';
@override
String get showHiddenFiles => '显示隐藏文件';
@override
String get showHiddenFilesSubtitle => '在文件树中展示以点 (.) 开头的隐藏文件与文件夹';
@override
String get searchTasksHint => '搜索指定任务...';
@override
String get noTasksAvailable => '暂无可执行任务';
@override
String get noMatchingTasks => '无匹配的任务';
@override
String get userCustomTasks => '用户自定义任务';
@override
String get systemDetectedTasks => '系统动态探测任务';
@override
String get editCustomTasksTooltip => '编辑自定义任务';
@override
String get runTasksConfig => '运行任务配置';
@override
String get editTask => '编辑任务';
@override
String get addTask => '新增任务';
@override
String get runTasksConfigSubtitle =>
'配置将自动保存至项目根目录下的 .code_editor/run_tasks.json';
@override
String get noCustomTasksInProject => '当前项目暂无自定义任务';
@override
String get createNow => '立即创建';
@override
String get saveAndApply => '保存并应用';
@override
String get taskNameRequired => '任务名称 *';
@override
String get taskNameHint => '如: 编译并运行 Debug';
@override
String get taskNameEmptyError => '请输入任务名称';
@override
String get shellCommandRequired => 'Shell 执行指令 *';
@override
String get shellCommandHint => '如: cmake -B build && cmake --build build';
@override
String get shellCommandEmptyError => '请输入执行指令';
@override
String get taskDescOptional => '任务描述(选填)';
@override
String get taskDescHint => '简要说明此任务的用途';
@override
String get clearBeforeRun => '执行前清屏 (clear)';
@override
String get clearBeforeRunSubtitle => '在终端输出任务结果前清理历史屏幕';
@override
String get runTasksUpdated => '运行任务配置已更新';
@override
String detectCompletedMessage(int count) {
return '探测完成,发现 $count 个可用任务';
}
@override
String get pleaseOpenProjectFirst => '请先打开一个项目';
@override
String deleteTaskConfirmMessage(String name) {
return '确定要删除任务 \"$name\" 吗?';
}
@override
String deleteSelectedTasksConfirmMessage(int count) {
return '确定要删除选中的 $count 个任务吗?';
}
@override
String get deleteSelected => '删除选中';
@override
String get selectTasksToDelete => '选择要删除的任务';
@override
String selectedCount(int count) {
return '已选 $count 项';
}
@override
String get unsavedTaskChangesTitle => '未保存的任务更改';
@override
String get unsavedTaskChangesMessage => '当前任务内容已被修改,是否放弃未保存的修改并返回?';
}
+158 -11
View File
@@ -71,6 +71,27 @@
"darkThemeCategory": "暗色系",
"lightThemeCategory": "浅色系",
"codeFontSize": "代码字号缩放",
"uiFont": "界面字体",
"selectUiFont": "选择界面字体",
"themeColor": "主题颜色",
"selectThemeColor": "选择主题颜色",
"terminalBackgroundColor": "终端背景颜色",
"selectTerminalBackgroundColor": "选择终端背景颜色",
"uiFontPreview": "代码编辑器界面字体预览 Code Editor 123",
"codeFont": "代码字体",
"selectCodeFont": "选择代码字体",
"codeFontPreview": "const app = \"Code Editor\"; // 代码预览",
"terminalFont": "终端字体",
"selectTerminalFont": "选择终端字体",
"terminalFontPreview": "$ git status -s # 终端字体预览",
"fontName": "{font, select, system_default{系统默认} sans_serif{无衬线体} serif{衬线体(宋体)} monospace{系统等宽} consolas{Consolas} courier_new{Courier New} menlo{Menlo / Monaco} jetbrains_mono{JetBrains Mono} fira_code{Fira Code} other{{font}}}",
"@fontName": {
"placeholders": {
"font": {
"type": "String"
}
}
},
"decreaseFontSize": "减小字号",
"increaseFontSize": "增大字号",
"fontSizeDialogTitle": "代码字号",
@@ -91,6 +112,10 @@
"virtualKeyboardSubtitle": "在代码编辑区底部显示辅助符号与快捷键",
"editVirtualKeyboardConfig": "编辑键盘配置",
"editVirtualKeyboardConfigSubtitle": "自定义小键盘按键布局与快捷键",
"terminalVirtualKeyboard": "终端小键盘",
"terminalVirtualKeyboardSubtitle": "在终端下方显示常用特殊键与指令快捷键",
"editTerminalVirtualKeyboardConfig": "编辑终端键盘配置",
"editTerminalVirtualKeyboardConfigSubtitle": "自定义 Esc / Tab / Ctrl 组合等终端专用按键",
"virtualKeyboardDialogTitle": "小键盘配置 (JSON)",
"resetDefault": "恢复默认",
"configFormatError": "配置格式错误",
@@ -357,21 +382,143 @@
},
"keyboardAddKeyTitle": "添加按键",
"keyboardEditKeyTitle": "编辑按键",
"keyboardLabelFormField": "显示文本 (Label)",
"keyboardLabelFormField": "显示文本",
"keyboardLabelFormFieldHint": "按键上显示的文本,如 Tab、()、A",
"keyboardLabelOrIconRequiredError": "请输入显示文本或选择图标",
"keyboardIconFormField": "图标 (Icon, 可选)",
"keyboardIconFormField": "图标 (可选)",
"keyboardIconName": "{icon, select, undo{撤销} redo{重做} tab{向右缩进} untab{向左缩进} outdent{减少缩进} arrow_left{左箭头} arrow_right{右箭头} arrow_up{上箭头} arrow_down{下箭头} home{移至行首} end{移至行尾} first_page{移至文首} last_page{移至文末} page_up{上翻页} page_down{下翻页} enter{回车} space{空格} escape{退出} insert{插入} clear{清除} keyboard{键盘} backspace{退格} delete{删除} copy{复制} cut{剪切} paste{粘贴} save{保存} search{搜索} select_all{全选} keyboard_hide{收起小键盘} other{{icon}}}",
"@keyboardIconName": {
"placeholders": {
"icon": {
"type": "String"
}
}
},
"keyboardNoIconOption": "无图标 (使用文本显示)",
"keyboardActionFormField": "动作类型 (Action)",
"keyboardValueFormField": "输入文本内容 (Value)",
"keyboardActionFormField": "动作类型",
"keyboardActionName": "{action, select, input{普通文本} pair{成对符号} command{编辑器命令} modifier{修饰键} key{特殊键} other{{action}}}",
"@keyboardActionName": {
"placeholders": {
"action": {
"type": "String"
}
}
},
"keyboardActionInputTerminal": "指令快捷键",
"keyboardKeyFormField": "特殊键",
"keyboardKeyGroupNavigation": "导航键",
"keyboardKeyGroupEditing": "编辑键",
"keyboardKeyGroupFunctionKeys": "功能键",
"keyboardKeyGroupLetters": "字母键",
"keyboardAutoEnter": "发送后自动回车",
"keyboardKeyName": "{key, select, escape{退出} tab{Tab} backtab{反向制表} returnKey{回车} enter{回车} numpadEnter{小键盘回车} backspace{退格} delete{删除} insert{插入} space{空格} numpadClear{清除} arrowUp{上} arrowDown{下} arrowLeft{左} arrowRight{右} home{行首} end{行尾} pageUp{上翻页} pageDown{下翻页} f1{F1} f2{F2} f3{F3} f4{F4} f5{F5} f6{F6} f7{F7} f8{F8} f9{F9} f10{F10} f11{F11} f12{F12} other{{key}}}",
"@keyboardKeyName": {
"placeholders": {
"key": {
"type": "String"
}
}
},
"keyboardKeyInvalidError": "该键在终端中不会产生任何输出,请选择列表中的特殊键",
"keyboardValueFormField": "输入文本内容",
"keyboardValueFormFieldHint": "点击后直接插入的文本,如 ;、=、->",
"keyboardValueRequiredError": "输入文本不能为空",
"keyboardPairPresetFormField": "成对符号预设 (Value)",
"keyboardCommandPresetFormField": "预设编辑器命令 (Value)",
"keyboardModifierPresetFormField": "终端修饰键 (Value)",
"keyboardTerminalKeyPresetFormField": "终端按键 (Value)",
"keyboardCursorOffsetFormField": "光标相对偏移 (cursorOffset)",
"keyboardCursorOffsetHelper": "例如 () 插入后光标居中需向左偏移 1 位,填写 -1",
"keyboardPairValueFormField": "成对符号",
"keyboardPairValueFormFieldHint": "例如 ()、[]、\"\"、<>",
"keyboardPairValueRequiredError": "请输入成对符号",
"keyboardPairValueInvalidError": "请输入至少 2 个字符且左右不同的成对符号,如 ()、[]",
"keyboardCommandPresetFormField": "编辑器命令",
"keyboardCommandName": "{command, select, tab{向右缩进} untab{向左缩进} undo{撤销} redo{重做} cursor_left{光标左移} cursor_right{光标右移} cursor_up{光标上移} cursor_down{光标下移} line_start{移动至行首} line_end{移动至行尾} page_start{移动至文首} page_end{移动至文末} copy{复制} cut{剪切} paste{粘贴} delete{删除} select_all{全选} keyboard_hide{收起小键盘} other{{command}}}",
"@keyboardCommandName": {
"placeholders": {
"command": {
"type": "String"
}
}
},
"keyboardModifierPresetFormField": "终端修饰键",
"keyboardModifierName": "{modifier, select, ctrl{Ctrl 键} alt{Alt 键} shift{Shift 键} other{{modifier}}}",
"@keyboardModifierName": {
"placeholders": {
"modifier": {
"type": "String"
}
}
},
"keyboardCursorOffsetFormField": "光标相对偏移",
"keyboardCursorOffsetRequiredError": "请输入光标偏移(通常为 -1)",
"keyboardCursorOffsetIntegerError": "偏移量必须为整数"
"keyboardCursorOffsetIntegerError": "偏移量必须为整数",
"recommended": "推荐",
"presetColors": "预设颜色",
"hexColor": "十六进制颜色",
"currentColor": "当前",
"newColor": "预览",
"runTasks": "运行任务",
"projectDetect": "项目探测",
"projectDetecting": "正在探测项目...",
"editRunTasks": "运行任务编辑",
"projectSection": "项目",
"showHiddenFiles": "显示隐藏文件",
"showHiddenFilesSubtitle": "在文件树中展示以点 (.) 开头的隐藏文件与文件夹",
"searchTasksHint": "搜索指定任务...",
"noTasksAvailable": "暂无可执行任务",
"noMatchingTasks": "无匹配的任务",
"userCustomTasks": "用户自定义任务",
"systemDetectedTasks": "系统动态探测任务",
"editCustomTasksTooltip": "编辑自定义任务",
"runTasksConfig": "运行任务配置",
"editTask": "编辑任务",
"addTask": "新增任务",
"runTasksConfigSubtitle": "配置将自动保存至项目根目录下的 .code_editor/run_tasks.json",
"noCustomTasksInProject": "当前项目暂无自定义任务",
"createNow": "立即创建",
"saveAndApply": "保存并应用",
"taskNameRequired": "任务名称 *",
"taskNameHint": "如: 编译并运行 Debug",
"taskNameEmptyError": "请输入任务名称",
"shellCommandRequired": "Shell 执行指令 *",
"shellCommandHint": "如: cmake -B build && cmake --build build",
"shellCommandEmptyError": "请输入执行指令",
"taskDescOptional": "任务描述(选填)",
"taskDescHint": "简要说明此任务的用途",
"clearBeforeRun": "执行前清屏 (clear)",
"clearBeforeRunSubtitle": "在终端输出任务结果前清理历史屏幕",
"runTasksUpdated": "运行任务配置已更新",
"detectCompletedMessage": "探测完成,发现 {count} 个可用任务",
"@detectCompletedMessage": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"pleaseOpenProjectFirst": "请先打开一个项目",
"deleteTaskConfirmMessage": "确定要删除任务 \"{name}\" 吗?",
"@deleteTaskConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSelectedTasksConfirmMessage": "确定要删除选中的 {count} 个任务吗?",
"@deleteSelectedTasksConfirmMessage": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"deleteSelected": "删除选中",
"selectTasksToDelete": "选择要删除的任务",
"selectedCount": "已选 {count} 项",
"@selectedCount": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"unsavedTaskChangesTitle": "未保存的任务更改",
"unsavedTaskChangesMessage": "当前任务内容已被修改,是否放弃未保存的修改并返回?"
}
+15 -27
View File
@@ -3,8 +3,10 @@ import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/project_provider.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/providers/tab_provider.dart';
import 'package:code_editor/providers/run_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/views/main_view.dart';
import 'package:code_editor/utils/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
@@ -28,13 +30,21 @@ class MyApp extends StatelessWidget {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => SettingsProvider()..init()),
ChangeNotifierProvider(create: (_) => ProjectProvider()..init()),
ChangeNotifierProxyProvider<SettingsProvider, ProjectProvider>(
create: (_) => ProjectProvider()..init(),
update: (_, settings, project) {
final pp = project ?? (ProjectProvider()..init());
pp.updateShowHiddenFiles(settings.showHiddenFiles);
return pp;
},
),
ChangeNotifierProxyProvider<ProjectProvider, TabProvider>(
create: (_) => TabProvider()..init(),
update: (_, project, tab) =>
(tab ?? (TabProvider()..init()))..bindProjectProvider(project),
),
ChangeNotifierProvider(create: (_) => TerminalProvider()),
ChangeNotifierProvider(create: (_) => RunProvider()),
ChangeNotifierProxyProvider<TerminalProvider, DistroProvider>(
create: (_) => DistroProvider()..init(),
update: (_, terminal, distro) {
@@ -58,37 +68,15 @@ class MyApp extends StatelessWidget {
supportedLocales: AppLocalizations.supportedLocales,
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
themeMode: settings.appThemeMode,
theme: ThemeData(
useMaterial3: true,
theme: buildAppTheme(
seedColor: settings.appThemeColor,
brightness: Brightness.light,
colorScheme: ColorScheme.fromSeed(
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,
),
darkTheme: ThemeData(
useMaterial3: true,
darkTheme: buildAppTheme(
seedColor: settings.appThemeColor,
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
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,
),
+5 -2
View File
@@ -1,4 +1,7 @@
/// 字体定义与预设常量
///
/// 注意:[name] 仅作为代码内的定义说明,界面展示名称一律取自 l10n
/// (`fontName(id)`),避免中英文文案两处维护。
class AppFontItem {
final String id;
final String name;
@@ -133,7 +136,7 @@ class AppFonts {
/// 预设的开源编程字体配置(用户后续下载字体包放入 assets/fonts/ 并配置 pubspec 后即可即开即用)
static const AppFontItem editorJetBrainsMono = AppFontItem(
id: 'jetbrains_mono',
name: 'JetBrains Mono (推荐)',
name: 'JetBrains Mono',
fontFamily: 'JetBrains Mono',
fallback: ['monospace'],
isMonospace: true,
@@ -200,7 +203,7 @@ class AppFonts {
static const AppFontItem terminalJetBrainsMono = AppFontItem(
id: 'jetbrains_mono',
name: 'JetBrains Mono (推荐)',
name: 'JetBrains Mono',
fontFamily: 'JetBrains Mono',
fallback: ['monospace'],
isMonospace: true,
+108
View File
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
/// 运行任务来源类型
enum TaskSource {
/// 系统动态探测所得(保存在内存,随项目探测刷新)
detected,
/// 用户在 .code_editor/run_tasks.json 中持久化配置
custom,
}
/// 运行任务实体模型
class RunTask {
/// 任务唯一ID
final String id;
/// 任务展示名称
final String name;
/// 发送到终端执行的 Shell 命令(支持 &&、; 串联多条命令)
final String command;
/// 任务来源(探测/用户自定义)
final TaskSource source;
/// 任务补充描述/副标题(通常是命令预览或文件路径)
final String? description;
/// 容器内相对工作路径(为 null 时默认容器工作区 /workspace)
final String? workingDir;
/// 是否在执行该命令前清屏(发送 clear)
final bool clearBeforeRun;
/// UI 展示图标(可选)
final IconData? icon;
const RunTask({
required this.id,
required this.name,
required this.command,
required this.source,
this.description,
this.workingDir,
this.clearBeforeRun = false,
this.icon,
});
/// 从持久化的 JSON Map 构建自定义运行任务
factory RunTask.fromJson(Map<String, dynamic> json) {
return RunTask(
id: json['id'] as String? ?? 'custom_${DateTime.now().microsecondsSinceEpoch}',
name: json['name'] as String? ?? '未命名任务',
command: json['command'] as String? ?? '',
source: TaskSource.custom,
description: json['description'] as String?,
workingDir: json['workingDir'] as String?,
clearBeforeRun: json['clearBeforeRun'] as bool? ?? false,
);
}
/// 序列化为持久化 JSON Map(仅针对用户自定义任务保存)
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'command': command,
if (description != null && description!.isNotEmpty) 'description': description,
if (workingDir != null && workingDir!.isNotEmpty) 'workingDir': workingDir,
'clearBeforeRun': clearBeforeRun,
};
}
RunTask copyWith({
String? id,
String? name,
String? command,
TaskSource? source,
String? description,
String? workingDir,
bool? clearBeforeRun,
IconData? icon,
}) {
return RunTask(
id: id ?? this.id,
name: name ?? this.name,
command: command ?? this.command,
source: source ?? this.source,
description: description ?? this.description,
workingDir: workingDir ?? this.workingDir,
clearBeforeRun: clearBeforeRun ?? this.clearBeforeRun,
icon: icon ?? this.icon,
);
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RunTask &&
runtimeType == other.runtimeType &&
id == other.id &&
name == other.name &&
command == other.command &&
source == other.source;
@override
int get hashCode => id.hashCode ^ name.hashCode ^ command.hashCode ^ source.hashCode;
}
+12 -44
View File
@@ -10,6 +10,7 @@ class TerminalSession {
final String id;
String name;
final String distroId;
final String? workspacePath;
final DateTime createdAt;
final Terminal terminal;
final FocusNode focusNode;
@@ -17,12 +18,14 @@ class TerminalSession {
Pty? _pty;
StreamSubscription? _ptyOutputSub;
bool _isProcessRunning = false;
String _inputBuffer = '';
VoidCallback? onProcessTerminated;
TerminalSession({
required this.id,
this.name = '会话',
this.distroId = 'alpine',
this.workspacePath,
this.onProcessTerminated,
DateTime? createdAt,
int maxLines = 10000,
bool autoStartProcess = false,
@@ -31,7 +34,7 @@ class TerminalSession {
focusNode = FocusNode() {
_initTerminalEvents();
if (autoStartProcess) {
unawaited(startProcess());
unawaited(startProcess(workspacePath: workspacePath));
}
}
@@ -41,14 +44,12 @@ class TerminalSession {
String get bufferText => terminal.buffer.getText();
void _initTerminalEvents() {
// 监听输入直接送往 PTY
// 监听输入直接送往 PTY;若进程已退出或未启动,则完全不处理输入(禁止交互)
terminal.onOutput = (data) {
if (_pty != null && _isProcessRunning) {
try {
_pty!.write(utf8.encode(data));
} catch (_) {}
} else {
_handleLocalEcho(data);
}
};
@@ -62,48 +63,14 @@ class TerminalSession {
};
}
/// 当无底层进程挂接时的本地简易交互回显支持(保证脱机/本地开发时的基础交互与光标跳动)
void _handleLocalEcho(String data) {
for (int i = 0; i < data.length; i++) {
final char = data[i];
if (char == '\r' || char == '\n') {
terminal.write('\r\n');
_executeLocalCommand(_inputBuffer.trim());
_inputBuffer = '';
} else if (char == '\x7f' || char == '\b') {
// 退格键
if (_inputBuffer.isNotEmpty) {
_inputBuffer = _inputBuffer.substring(0, _inputBuffer.length - 1);
terminal.write('\b \b');
}
} else if (char.codeUnitAt(0) >= 32) {
_inputBuffer += char;
terminal.write(char);
}
}
}
void _executeLocalCommand(String cmd) {
if (cmd.isEmpty) {
terminal.write('\$ ');
return;
}
if (cmd == 'clear') {
clear();
terminal.write('\$ ');
return;
}
terminal.write('\x1b[33m[Host fallback]: executed "$cmd"\x1b[0m\r\n');
terminal.write('\$ ');
}
/// 启动底层真实 PTY 进程(连接 PRoot 容器或 Host Shell)
Future<void> startProcess({DistroManager? distroManager, String? workspacePath}) async {
final manager = distroManager ?? DistroManager();
final effectiveWorkspace = workspacePath ?? this.workspacePath;
try {
final config = await manager.buildLaunchConfig(
systemName: distroId,
workspacePath: workspacePath,
workspacePath: effectiveWorkspace,
);
final initialRows = terminal.viewHeight > 0 ? terminal.viewHeight : 24;
@@ -130,18 +97,19 @@ class TerminalSession {
},
onDone: () {
_isProcessRunning = false;
onProcessTerminated?.call();
},
);
_pty!.exitCode.then((code) {
_isProcessRunning = false;
terminal.write('\r\n\x1b[33m[Process exited with code $code]\x1b[0m\r\n');
onProcessTerminated?.call();
});
} catch (e) {
_isProcessRunning = false;
terminal.write('\x1b[1;36mWelcome to Terminal [$distroId]\x1b[0m\r\n');
terminal.write('\x1b[90m(PTY launch failed: $e. Running in local fallback mode.)\x1b[0m\r\n\r\n');
terminal.write('\$ ');
terminal.write('\x1b[31m[PTY launch failed: $e]\x1b[0m\r\n');
onProcessTerminated?.call();
}
}
+481 -71
View File
@@ -15,6 +15,16 @@ class KeyboardIconHelper {
'arrow_down': Icons.arrow_downward,
'home': Icons.vertical_align_top,
'end': Icons.vertical_align_bottom,
'first_page': Icons.first_page,
'last_page': Icons.last_page,
'page_up': Icons.keyboard_double_arrow_up,
'page_down': Icons.keyboard_double_arrow_down,
'enter': Icons.keyboard_return,
'space': Icons.space_bar,
'escape': Icons.cancel_outlined,
'insert': Icons.input,
'clear': Icons.clear,
'keyboard': Icons.keyboard_outlined,
'backspace': Icons.backspace_outlined,
'delete': Icons.delete_outline,
'copy': Icons.copy,
@@ -22,6 +32,7 @@ class KeyboardIconHelper {
'paste': Icons.content_paste,
'save': Icons.save_outlined,
'search': Icons.search,
'select_all': Icons.select_all,
'keyboard_hide': Icons.keyboard_hide_outlined,
};
@@ -36,21 +47,17 @@ class KeyboardIconHelper {
}
/// 虚拟小键盘作用域(编辑区或终端)
///
/// 界面展示名称取自 l10n(`editorScope` / `terminalScope`),此处不再自带文案。
enum KeyboardScope {
editor,
terminal;
String get displayName {
switch (this) {
case KeyboardScope.editor:
return '编辑区';
case KeyboardScope.terminal:
return '终端';
}
}
terminal,
}
/// 按键动作定义项辅助
///
/// 注意:[label] 与 [description] 仅作为代码内的定义说明,界面展示名称一律取自
/// l10n(`keyboardActionName`),避免中英文文案两处维护。
class KeyboardActionOption {
final String action;
final String label;
@@ -64,13 +71,116 @@ class KeyboardActionOption {
}
/// 预设值选项辅助
///
/// 注意:[label] 仅作为代码内的定义说明,界面展示名称一律取自 l10n
/// (`keyboardCommandName` / `keyboardModifierName` / `keyboardKeyName`)。
class KeyboardValueOption {
final String value;
final String label;
/// 下拉菜单中展示的内置图标常量名称(可选,取值同 [KeyboardIconHelper])
final String? icon;
const KeyboardValueOption({
required this.value,
required this.label,
this.icon,
});
}
/// 按键修饰符组合(Ctrl / Alt / Shift)
///
/// 仅在终端作用域的 `key` 动作上有实际含义:xterm 会把它换算成对应转义序列。
/// 三个都为 false 时视为"无修饰",JSON 导出时整个 `mods` 字段省略。
class KeyboardKeyMods {
final bool ctrl;
final bool alt;
final bool shift;
const KeyboardKeyMods({
this.ctrl = false,
this.alt = false,
this.shift = false,
});
/// 无修饰的常量实例
static const KeyboardKeyMods none = KeyboardKeyMods();
bool get isEmpty => !ctrl && !alt && !shift;
bool get isNotEmpty => !isEmpty;
/// 已勾选的修饰键数量
int get count => (ctrl ? 1 : 0) + (alt ? 1 : 0) + (shift ? 1 : 0);
KeyboardKeyMods copyWith({bool? ctrl, bool? alt, bool? shift}) {
return KeyboardKeyMods(
ctrl: ctrl ?? this.ctrl,
alt: alt ?? this.alt,
shift: shift ?? this.shift,
);
}
/// 从 `{"ctrl": true, "alt": false}` 形式的 JSON 解析,非法输入一律视为无修饰
factory KeyboardKeyMods.fromJson(dynamic json) {
if (json is! Map) return none;
return KeyboardKeyMods(
ctrl: json['ctrl'] == true,
alt: json['alt'] == true,
shift: json['shift'] == true,
);
}
Map<String, dynamic> toJson() {
return {
if (ctrl) 'ctrl': true,
if (alt) 'alt': true,
if (shift) 'shift': true,
};
}
@override
bool operator ==(Object other) {
return other is KeyboardKeyMods &&
other.ctrl == ctrl &&
other.alt == alt &&
other.shift == shift;
}
@override
int get hashCode => Object.hash(ctrl, alt, shift);
@override
String toString() {
if (isEmpty) return 'none';
return [
if (ctrl) 'ctrl',
if (alt) 'alt',
if (shift) 'shift',
].join('+');
}
}
/// 终端命名键分组(用于弹窗下拉的分组展示)
enum TerminalKeyGroup {
navigation,
editing,
functionKeys,
letters,
}
/// 终端命名键选项:value 为 xterm `TerminalKey` 的枚举名
class KeyboardNamedKeyOption {
final String value;
final TerminalKeyGroup group;
/// 下拉菜单中展示的内置图标常量名称(可选,取值同 [KeyboardIconHelper])
final String? icon;
const KeyboardNamedKeyOption({
required this.value,
required this.group,
this.icon,
});
}
@@ -78,69 +188,197 @@ class KeyboardValueOption {
class KeyboardScopeHelper {
/// 编辑区支持的动作类型
static const List<KeyboardActionOption> editorActions = [
KeyboardActionOption(action: 'input', label: '普通文本 (input)', description: '直接插入指定文本内容'),
KeyboardActionOption(action: 'pair', label: '成对符号 (pair)', description: '括号/引号等成对符号,支持选区包裹与光标偏移'),
KeyboardActionOption(action: 'command', label: '编辑器命令 (command)', description: '触发缩进、撤销、光标移动等编辑器功能'),
KeyboardActionOption(action: 'input', label: '普通文本', description: '直接插入指定文本内容'),
KeyboardActionOption(action: 'pair', label: '成对符号', description: '括号/引号等成对符号,支持选区包裹与光标偏移'),
KeyboardActionOption(action: 'command', label: '编辑器命令', description: '触发缩进、撤销、光标移动等编辑器功能'),
];
/// 终端支持的动作类型
static const List<KeyboardActionOption> 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、方向键等终端特殊键'),
KeyboardActionOption(action: 'input', label: '指令快捷键', description: '向终端发送一段文本,可附加自动回车'),
KeyboardActionOption(action: 'modifier', label: '修饰键', description: 'Ctrl / Alt / Shift 修饰状态切换'),
KeyboardActionOption(action: 'key', label: '特殊键', description: 'Esc、Tab、方向键、功能键及 Ctrl/Alt 组合'),
];
/// 编辑区预设命令列表
/// 终端动作取值集合(供校验使用)
static const Set<String> terminalActionValues = {'input', 'modifier', 'key'};
/// 编辑区动作取值集合(供校验使用)
static const Set<String> editorActionValues = {'input', 'pair', 'command'};
/// 编辑区预设命令列表(icon 用于下拉菜单前缀展示)
static const List<KeyboardValueOption> 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: '收起小键盘'),
KeyboardValueOption(value: 'tab', label: '向右缩进', icon: 'tab'),
KeyboardValueOption(value: 'untab', label: '向左缩进', icon: 'untab'),
KeyboardValueOption(value: 'undo', label: '撤销', icon: 'undo'),
KeyboardValueOption(value: 'redo', label: '重做', icon: 'redo'),
KeyboardValueOption(value: 'cursor_left', label: '光标左移', icon: 'arrow_left'),
KeyboardValueOption(value: 'cursor_right', label: '光标右移', icon: 'arrow_right'),
KeyboardValueOption(value: 'cursor_up', label: '光标上移', icon: 'arrow_up'),
KeyboardValueOption(value: 'cursor_down', label: '光标下移', icon: 'arrow_down'),
KeyboardValueOption(value: 'line_start', label: '移动至行首', icon: 'home'),
KeyboardValueOption(value: 'line_end', label: '移动至行尾', icon: 'end'),
KeyboardValueOption(value: 'page_start', label: '移动至文首', icon: 'first_page'),
KeyboardValueOption(value: 'page_end', label: '移动至文末', icon: 'last_page'),
KeyboardValueOption(value: 'copy', label: '复制', icon: 'copy'),
KeyboardValueOption(value: 'cut', label: '剪切', icon: 'cut'),
KeyboardValueOption(value: 'paste', label: '粘贴', icon: 'paste'),
KeyboardValueOption(value: 'delete', label: '删除', icon: 'delete'),
KeyboardValueOption(value: 'select_all', label: '全选', icon: 'select_all'),
KeyboardValueOption(value: 'keyboard_hide', label: '收起小键盘', icon: 'keyboard_hide'),
];
/// 编辑区成对符号预设列表
static const List<KeyboardValueOption> editorPairs = [
KeyboardValueOption(value: '()', label: '圆括号 ()'),
KeyboardValueOption(value: '[]', label: '方括号 []'),
KeyboardValueOption(value: '{}', label: '花括号 {}'),
KeyboardValueOption(value: '""', label: '双引号 ""'),
KeyboardValueOption(value: "''", label: "单引号 ''"),
KeyboardValueOption(value: '<>', label: '尖括号 <>'),
// ==========================================
// 终端命名键表(值为 xterm TerminalKey 的枚举名)
//
// 说明:xterm 4.0.0 的默认 keytab 只对下列 31 个命名键定义了转义序列,
// 其余 HID 键码(digit0-9、numpad0-9、media*、gameButton* 等)在默认
// keytab 中没有条目,`Terminal.keyInput` 会返回 false 且不产生任何输出,
// 因此这里作为"终端中真正可用"的键清单,由弹窗下拉与 JSON 校验共用。
// 组合键由弹窗下方的三个修饰键控件(Ctrl / Alt / Shift)叠加产生。
// ==========================================
/// 终端可用命名键(导航键)
static const List<KeyboardNamedKeyOption> terminalNavigationKeys = [
KeyboardNamedKeyOption(value: 'arrowUp', group: TerminalKeyGroup.navigation, icon: 'arrow_up'),
KeyboardNamedKeyOption(value: 'arrowDown', group: TerminalKeyGroup.navigation, icon: 'arrow_down'),
KeyboardNamedKeyOption(value: 'arrowLeft', group: TerminalKeyGroup.navigation, icon: 'arrow_left'),
KeyboardNamedKeyOption(value: 'arrowRight', group: TerminalKeyGroup.navigation, icon: 'arrow_right'),
KeyboardNamedKeyOption(value: 'home', group: TerminalKeyGroup.navigation, icon: 'home'),
KeyboardNamedKeyOption(value: 'end', group: TerminalKeyGroup.navigation, icon: 'end'),
KeyboardNamedKeyOption(value: 'pageUp', group: TerminalKeyGroup.navigation, icon: 'page_up'),
KeyboardNamedKeyOption(value: 'pageDown', group: TerminalKeyGroup.navigation, icon: 'page_down'),
];
/// 终端修饰键预设列表
static const List<KeyboardValueOption> terminalModifiers = [
KeyboardValueOption(value: 'ctrl', label: 'Ctrl 键'),
KeyboardValueOption(value: 'alt', label: 'Alt 键'),
/// 终端可用命名键(编辑键)
static const List<KeyboardNamedKeyOption> terminalEditingKeys = [
KeyboardNamedKeyOption(value: 'escape', group: TerminalKeyGroup.editing, icon: 'escape'),
KeyboardNamedKeyOption(value: 'tab', group: TerminalKeyGroup.editing, icon: 'tab'),
KeyboardNamedKeyOption(value: 'backtab', group: TerminalKeyGroup.editing, icon: 'untab'),
KeyboardNamedKeyOption(value: 'returnKey', group: TerminalKeyGroup.editing, icon: 'enter'),
KeyboardNamedKeyOption(value: 'enter', group: TerminalKeyGroup.editing, icon: 'enter'),
KeyboardNamedKeyOption(value: 'numpadEnter', group: TerminalKeyGroup.editing, icon: 'enter'),
KeyboardNamedKeyOption(value: 'backspace', group: TerminalKeyGroup.editing, icon: 'backspace'),
KeyboardNamedKeyOption(value: 'delete', group: TerminalKeyGroup.editing, icon: 'delete'),
KeyboardNamedKeyOption(value: 'insert', group: TerminalKeyGroup.editing, icon: 'insert'),
KeyboardNamedKeyOption(value: 'space', group: TerminalKeyGroup.editing, icon: 'space'),
KeyboardNamedKeyOption(value: 'numpadClear', group: TerminalKeyGroup.editing, icon: 'clear'),
];
/// 终端按键预设列表
static const List<KeyboardValueOption> 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: '方向右键'),
/// 终端可用命名键(功能键 F1~F12,统一用键盘图标)
static const List<KeyboardNamedKeyOption> terminalFunctionKeys = [
KeyboardNamedKeyOption(value: 'f1', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f2', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f3', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f4', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f5', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f6', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f7', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f8', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f9', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f10', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f11', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
KeyboardNamedKeyOption(value: 'f12', group: TerminalKeyGroup.functionKeys, icon: 'keyboard'),
];
/// 终端全部可用命名键(31 个,按分组顺序拼接)
static const List<KeyboardNamedKeyOption> terminalNamedKeys = [
...terminalNavigationKeys,
...terminalEditingKeys,
...terminalFunctionKeys,
];
/// 终端字母键 keyA ~ keyZ(同样用键盘图标;配合下方修饰键控件可组成 Ctrl+C)
///
/// 用 getter 而不是 `static final`:静态字段在热重载后不会重新初始化,
/// 会让这里的改动(例如给字母键补图标)"看起来没生效"。
static List<KeyboardNamedKeyOption> get terminalLetterKeys => [
for (int i = 0; i < 26; i++)
KeyboardNamedKeyOption(
value: 'key${String.fromCharCode(0x41 + i)}',
group: TerminalKeyGroup.letters,
icon: 'keyboard',
),
];
/// 弹窗下拉可选的终端键(31 命名键 + 26 字母键)
static List<KeyboardNamedKeyOption> get terminalSelectableKeys => [
...terminalNamedKeys,
...terminalLetterKeys,
];
/// 终端特殊键的紧凑显示名,用于按键标签自动生成(符号/缩写无需 l10n)
static String terminalKeyShortLabel(String value) {
switch (value) {
case 'escape':
return 'Esc';
case 'tab':
return 'Tab';
case 'backtab':
return '⇤';
case 'returnKey':
case 'enter':
case 'numpadEnter':
return '⏎';
case 'backspace':
return '⌫';
case 'delete':
return 'Del';
case 'insert':
return 'Ins';
case 'space':
return 'Space';
case 'numpadClear':
return 'Clear';
case 'arrowUp':
return '↑';
case 'arrowDown':
return '↓';
case 'arrowLeft':
return '←';
case 'arrowRight':
return '→';
case 'home':
return 'Home';
case 'end':
return 'End';
case 'pageUp':
return 'PgUp';
case 'pageDown':
return 'PgDn';
default:
if (isLetterKeyName(value)) return value.substring(3);
if (value.length > 1 && value.startsWith('f') && int.tryParse(value.substring(1)) != null) {
return value.toUpperCase();
}
return value;
}
}
/// 终端 action 为 `key` 时的合法 value 集合(31 个命名键 + keyA~keyZ)
static Set<String> get terminalSupportedKeyNames => {
for (final key in terminalNamedKeys) key.value,
for (int i = 0; i < 26; i++) 'key${String.fromCharCode(0x41 + i)}',
};
/// 是否为字母键名(keyA ~ keyZ)
static bool isLetterKeyName(String value) {
if (value.length != 4 || !value.startsWith('key')) return false;
final code = value.codeUnitAt(3);
return code >= 0x41 && code <= 0x5A;
}
/// 判断终端 `key` 动作的 value 是否为受支持的键。
///
/// - 31 个命名键:任意修饰组合都可用
/// - 字母键 keyA~keyZ:**不受修饰符约束**,单独成格时就是该字母本身
/// (运行时走 `charInput`:裸字母发字母,Ctrl/Alt 组合发对应控制序列)
static bool isSupportedTerminalKey(String value) {
return terminalNamedKeys.any((k) => k.value == value) || isLetterKeyName(value);
}
/// 修饰键动作允许的取值
static const Set<String> terminalModifierValues = {'ctrl', 'alt', 'shift'};
}
/// 小键盘单个按键数据模型
@@ -152,25 +390,34 @@ class KeyboardKeyItem {
final String? icon;
/// 动作类型:
/// - 'input': 普通文本输入(默认)
/// - 'pair': 括号/引号等成对符号,支持选区包裹与光标偏移
/// - 'command': 编辑器动作命令,例如 'cursor_left', 'tab', 'undo' 等
/// - 'modifier': 终端修饰键,如 'ctrl', 'alt'
/// - 'terminal_key': 终端按键,如 'esc', 'ctrl_c'
/// - 'input': 普通文本输入(默认)。终端作用域下即"指令快捷键",配合
/// [autoEnter] 可实现"输入并执行"
/// - 'pair': 括号/引号等成对符号,支持选区包裹与光标偏移(仅编辑区)
/// - 'command': 编辑器动作命令,例如 'cursor_left', 'tab', 'undo' 等(仅编辑区)
/// - 'modifier': 终端修饰键,取值 'ctrl' / 'alt' / 'shift'(仅终端)
/// - 'key': 终端特殊键,取值为 xterm `TerminalKey` 枚举名(仅终端)
final String action;
/// 动作附带值(输入的文本或命令名称)
/// 动作附带值(输入的文本、命令名称或特殊键名)
final String value;
/// 光标插入后的相对偏移(如 pair \"()\" 插入后光标向左移动 1 位,则为 -1)
final int cursorOffset;
/// 修饰符组合,仅终端 `key` 动作有效(文本通道不接受修饰符)
final KeyboardKeyMods mods;
/// 仅终端 `input` 动作有效:发送文本后补一个回车符 `\r`,实现"输入即执行"
final bool autoEnter;
const KeyboardKeyItem({
required this.label,
this.icon,
this.action = 'input',
required this.value,
this.cursorOffset = 0,
this.mods = KeyboardKeyMods.none,
this.autoEnter = false,
});
KeyboardKeyItem copyWith({
@@ -180,6 +427,8 @@ class KeyboardKeyItem {
String? action,
String? value,
int? cursorOffset,
KeyboardKeyMods? mods,
bool? autoEnter,
}) {
return KeyboardKeyItem(
label: label ?? this.label,
@@ -187,6 +436,8 @@ class KeyboardKeyItem {
action: action ?? this.action,
value: value ?? this.value,
cursorOffset: cursorOffset ?? this.cursorOffset,
mods: mods ?? this.mods,
autoEnter: autoEnter ?? this.autoEnter,
);
}
@@ -214,6 +465,8 @@ class KeyboardKeyItem {
action: action,
value: value,
cursorOffset: cursorOffset,
mods: KeyboardKeyMods.fromJson(json['mods']),
autoEnter: json['autoEnter'] == true,
);
}
return const KeyboardKeyItem(label: '', value: '');
@@ -231,6 +484,12 @@ class KeyboardKeyItem {
if (cursorOffset != 0) {
map['cursorOffset'] = cursorOffset;
}
if (mods.isNotEmpty) {
map['mods'] = mods.toJson();
}
if (autoEnter) {
map['autoEnter'] = true;
}
return map;
}
}
@@ -339,8 +598,12 @@ class VirtualKeyboardConfig {
};
}
/// 校验 JSON 文本合法性,若合法返回 null,若非法返回具体错误描述
static String? validateJson(String jsonStr) {
/// 校验 JSON 文本合法性,若合法返回 null,若非法返回具体错误描述。
///
/// [scope] 决定按键动作与取值的合法集合:
/// - 编辑区:`input` / `pair` / `command`
/// - 终端:`input`(指令快捷键)/ `modifier` / `key`(特殊键)
static String? validateJson(String jsonStr, [KeyboardScope scope = KeyboardScope.editor]) {
final trimmed = jsonStr.trim();
if (trimmed.isEmpty) {
return '配置内容不能为空';
@@ -435,6 +698,12 @@ class VirtualKeyboardConfig {
if (key.containsKey('cursorOffset') && key['cursorOffset'] is! int) {
return '第 $pageNum 页第 $rowNum 行第 $keyNum 个按键的 "cursorOffset" 必须为整数';
}
final actionError = _validateKeyAction(
key: key,
scope: scope,
location: '第 $pageNum 页第 $rowNum 行第 $keyNum 个按键',
);
if (actionError != null) return actionError;
} else {
return '第 $pageNum 页第 $rowNum 行第 $keyNum 个按键类型错误,只能是文本字符串或对象';
}
@@ -445,9 +714,140 @@ class VirtualKeyboardConfig {
return null;
}
/// 默认配置预设
/// 按作用域校验单个按键对象的 action / value / mods / autoEnter 组合。
///
/// 返回 null 表示合法;否则返回可直接展示给用户的错误描述。
/// 这里的严格程度是刻意为之:宁可保存时报错,也不要在运行时静默无输出
/// (例如把 digit1 当作终端特殊键,或给文本通道挂修饰符)。
static String? _validateKeyAction({
required Map<String, dynamic> key,
required KeyboardScope scope,
required String location,
}) {
final action = key['action']?.toString() ?? 'input';
final value = key['value']?.toString() ?? '';
final mods = KeyboardKeyMods.fromJson(key['mods']);
if (key.containsKey('mods') && key['mods'] != null && key['mods'] is! Map) {
return '$location 的 "mods" 必须是对象,例如 {"ctrl": true}';
}
if (scope == KeyboardScope.editor) {
if (!KeyboardScopeHelper.editorActionValues.contains(action)) {
return '$location 的动作 "$action" 不适用于编辑区,可用动作: '
'${KeyboardScopeHelper.editorActionValues.join(' / ')}';
}
return null;
}
// 终端作用域
if (!KeyboardScopeHelper.terminalActionValues.contains(action)) {
return '$location 的动作 "$action" 不适用于终端,可用动作: '
'${KeyboardScopeHelper.terminalActionValues.join(' / ')}';
}
switch (action) {
case 'modifier':
if (!KeyboardScopeHelper.terminalModifierValues.contains(value)) {
return '$location 的修饰键取值 "$value" 无效,只能是 '
'${KeyboardScopeHelper.terminalModifierValues.join(' / ')}';
}
if (mods.isNotEmpty) {
return '$location 是修饰键动作,不应再附带 "mods"';
}
return null;
case 'key':
if (value.isEmpty) {
return '$location 缺少特殊键值 ("value")';
}
if (!KeyboardScopeHelper.isSupportedTerminalKey(value)) {
return '$location 的特殊键 "$value" 在终端中不会产生任何输出,'
'请选择受支持的命名键(如 escape / tab / arrowUp / f1)或字母键 keyA ~ keyZ';
}
return null;
case 'input':
default:
if (value.isEmpty) {
return '$location 缺少文本内容 ("value")';
}
if (mods.isNotEmpty) {
return '$location 是文本指令,附加 "mods" 不会生效'
'(终端文本通道不接受修饰符,请改用"特殊键"类型)';
}
return null;
}
}
/// 默认配置预设(编辑区)
static VirtualKeyboardConfig defaultConfiguration() => _defaultConfig();
/// 按作用域返回默认配置预设
static VirtualKeyboardConfig defaultForScope(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? defaultTerminalConfiguration() : _defaultConfig();
/// ## 终端小键盘 JSON 结构
///
/// ```json
/// {
/// "pages": [
/// { "count": 7, "keys": [ [ <key>, <key>, ... ], ... ] }
/// ]
/// }
/// ```
///
/// 终端作用域下 `<key>` 有三种动作:
///
/// - **指令快捷键**:`{"label":"cd ..","action":"input","value":"cd ..","autoEnter":true}`
/// `autoEnter` 为 true 时,发送文本后再补一个回车符 `\r`(等价于按下回车),
/// 实现"一格执行命令";value 已以 `\r`/`\n` 结尾时不会重复补。
/// - **特殊键**:`{"label":"^C","action":"key","value":"keyC","mods":{"ctrl":true}}`
/// - `value` 取 xterm `TerminalKey` 的枚举名,可用集合见
/// [KeyboardScopeHelper.terminalNamedKeys](31 个命名键)与
/// [KeyboardScopeHelper.terminalSupportedKeyNames](再加 keyA~keyZ)
/// - `mods` 形如 `{"ctrl":bool,"alt":bool,"shift":bool}`,**仅 `key` 动作有效**;
/// 字母键必须且只能单独搭配 Ctrl 或 Alt,这是 xterm 输入链路的硬限制
/// - **修饰键**:`{"label":"Ctrl","action":"modifier","value":"ctrl"}`
/// `value` ∈ {ctrl, alt, shift},只切换运行时状态(单击一次性 / 双击锁定),不产生输出。
///
/// 编辑区作用域继续使用 `input` / `pair` / `command`;`mods` 与 `autoEnter`
/// 在无值时导出省略,因此既有编辑区配置零迁移。
///
/// 默认终端配置预设:两行特殊键 + 修饰键
///
/// 行1:Esc Tab Ctrl Alt - ↑ 回车
/// 行2:Ins End Shift : ← ↓ →
static VirtualKeyboardConfig defaultTerminalConfiguration() {
return const VirtualKeyboardConfig(
pages: [
KeyboardPageItem(
count: 7,
keys: [
[
KeyboardKeyItem(label: 'Esc', action: 'key', value: 'escape'),
KeyboardKeyItem(label: 'Tab', icon: 'tab', action: 'key', value: 'tab'),
KeyboardKeyItem(label: 'Ctrl', action: 'modifier', value: 'ctrl'),
KeyboardKeyItem(label: 'Alt', action: 'modifier', value: 'alt'),
KeyboardKeyItem(label: '-', action: 'input', value: '-'),
KeyboardKeyItem(label: '↑', icon: 'arrow_up', action: 'key', value: 'arrowUp'),
KeyboardKeyItem(label: '回车', icon: 'enter', action: 'key', value: 'enter'),
],
[
KeyboardKeyItem(label: 'Ins', action: 'key', value: 'insert'),
KeyboardKeyItem(label: 'End', action: 'key', value: 'end'),
KeyboardKeyItem(label: 'Shift', action: 'modifier', value: 'shift'),
KeyboardKeyItem(label: ':', action: 'input', value: ':'),
KeyboardKeyItem(label: '←', icon: 'arrow_left', action: 'key', value: 'arrowLeft'),
KeyboardKeyItem(label: '↓', icon: 'arrow_down', action: 'key', value: 'arrowDown'),
KeyboardKeyItem(label: '→', icon: 'arrow_right', action: 'key', value: 'arrowRight'),
],
],
),
],
);
}
static VirtualKeyboardConfig _defaultConfig() {
return const VirtualKeyboardConfig(
pages: [
@@ -461,8 +861,8 @@ class VirtualKeyboardConfig {
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: 'Undo', icon: 'undo', action: 'command', value: 'undo'),
KeyboardKeyItem(label: 'Redo', icon: 'redo', action: 'command', value: 'redo'),
],
[
KeyboardKeyItem(label: '<-', icon: 'arrow_left', action: 'command', value: 'cursor_left'),
@@ -503,9 +903,19 @@ class VirtualKeyboardConfig {
);
}
/// 转换为格式化好的默认 JSON 字符串
/// 转换为格式化好的默认 JSON 字符串(编辑区)
static String defaultJsonPretty() {
const encoder = JsonEncoder.withIndent(' ');
return encoder.convert(_defaultConfig().toJson());
}
/// 转换为格式化好的默认 JSON 字符串(终端)
static String defaultTerminalJsonPretty() {
const encoder = JsonEncoder.withIndent(' ');
return encoder.convert(defaultTerminalConfiguration().toJson());
}
/// 按作用域返回格式化好的默认 JSON 字符串
static String defaultJsonPrettyFor(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? defaultTerminalJsonPretty() : defaultJsonPretty();
}
+14
View File
@@ -25,6 +25,9 @@ class ProjectProvider extends ChangeNotifier {
//是否正在加载项目
bool _isLoading = false;
//是否显示隐藏文件
bool _showHiddenFiles = true;
// 跨 Provider 协同回调
void Function(String oldPath, String newPath)? onEntityRenamed;
void Function(String deletedPath)? onEntityDeleted;
@@ -37,10 +40,18 @@ class ProjectProvider extends ChangeNotifier {
List<String> get openDirectoryPaths => _history.openDirectoryPaths;
List<FileItem> get items => _items;
bool get isLoading => _isLoading;
bool get showHiddenFiles => _showHiddenFiles;
FileItem? get cutItem => _cutItem;
FileItem? get copiedItem => _copiedItem;
bool get canPaste => _cutItem != null || _copiedItem != null;
void updateShowHiddenFiles(bool show) {
if (_showHiddenFiles != show) {
_showHiddenFiles = show;
refreshTree();
}
}
bool isItemCut(String path) {
if (_cutItem == null) return false;
return _cutItem!.path == path || _cutItem!.path.trim() == path.trim();
@@ -88,6 +99,7 @@ class ProjectProvider extends ChangeNotifier {
? await FileService.instance.buildTree(
cleanPath,
openDirectoryPaths: validOpenPaths,
showHiddenFiles: _showHiddenFiles,
)
: [];
@@ -187,6 +199,7 @@ class ProjectProvider extends ChangeNotifier {
item.path,
depth: item.depth + 1,
openDirectoryPaths: updatedOpenPaths,
showHiddenFiles: _showHiddenFiles,
);
item.children.clear();
item.children.addAll(children);
@@ -218,6 +231,7 @@ class ProjectProvider extends ChangeNotifier {
final items = await FileService.instance.buildTree(
currentRoot,
openDirectoryPaths: _history.openDirectoryPaths,
showHiddenFiles: _showHiddenFiles,
);
String? currentFile = _history.lastOpenedFilePath;
+158
View File
@@ -0,0 +1,158 @@
import 'package:flutter/material.dart';
import '../models/run_task.dart';
import '../services/project_task_detector.dart';
import '../services/run_task_storage_service.dart';
/// 运行任务状态管理 Provider
class RunProvider extends ChangeNotifier {
final RunTaskStorageService _storageService;
RunProvider({RunTaskStorageService? storageService})
: _storageService = storageService ?? RunTaskStorageService();
/// 内存中保存的系统动态探测任务列表(不落盘)
List<RunTask> _detectedTasks = [];
/// 用户持久化配置的自定义任务列表(存放在 .code_editor/run_tasks.json)
List<RunTask> _customTasks = [];
/// 最近一次运行的任务ID(持久化保存)
String? _lastRunTaskId;
/// 最近一次运行的任务(如果有)
RunTask? _lastRunTask;
/// 是否正在探测中(探测期间互斥,防止并发与按钮连点)
bool _isDetecting = false;
/// 当前绑定的工程根路径
String? _currentProjectRoot;
List<RunTask> get detectedTasks => List.unmodifiable(_detectedTasks);
List<RunTask> get customTasks => List.unmodifiable(_customTasks);
RunTask? get lastRunTask => _lastRunTask;
String? get lastRunTaskId => _lastRunTaskId;
bool get isDetecting => _isDetecting;
String? get currentProjectRoot => _currentProjectRoot;
/// 获取当前合并后的所有可用任务列表(自定义任务置顶,随后为探测任务)
List<RunTask> get allTasks => [..._customTasks, ..._detectedTasks];
/// 内部方法:尝试从现有任务列表中匹配 lastRunTaskId
void _resolveLastRunTask() {
if (_lastRunTaskId == null) return;
for (final task in allTasks) {
if (task.id == _lastRunTaskId) {
_lastRunTask = task;
return;
}
}
}
/// 记录最近一次执行的任务并持久化
Future<void> setLastRunTask(RunTask task) async {
_lastRunTask = task;
_lastRunTaskId = task.id;
notifyListeners();
if (_currentProjectRoot != null) {
await _storageService.saveConfig(
projectRoot: _currentProjectRoot!,
tasks: _customTasks,
lastRunTaskId: _lastRunTaskId,
);
}
}
/// 当打开或切换工程时初始化任务(读取持久化任务 + 首次自动探测系统任务)
Future<void> onProjectOpened(String projectRoot, {String? activeFilePath}) async {
_currentProjectRoot = projectRoot;
// 1. 加载持久化的自定义任务与最近运行任务ID
final config = await _storageService.loadConfig(projectRoot);
_customTasks = config.tasks;
_lastRunTaskId = config.lastRunTaskId;
_resolveLastRunTask();
notifyListeners();
// 2. 自动触发一次系统探测
await detectTasks(projectRoot: projectRoot, currentFilePath: activeFilePath);
}
/// 关闭工程时清理状态
void onProjectClosed() {
_currentProjectRoot = null;
_detectedTasks = [];
_customTasks = [];
_lastRunTaskId = null;
_lastRunTask = null;
_isDetecting = false;
notifyListeners();
}
/// 手动或自动触发项目探测
/// [projectRoot] 目标工程路径
/// [currentFilePath] 当前激活的编辑器文件路径
Future<void> detectTasks({
required String projectRoot,
String? currentFilePath,
}) async {
if (_isDetecting) return;
_isDetecting = true;
// 清空内存中的旧探测结果
_detectedTasks = [];
notifyListeners();
try {
final detected = await ProjectTaskDetector.detect(
projectRoot: projectRoot,
currentFilePath: currentFilePath,
);
_detectedTasks = detected;
_resolveLastRunTask();
} catch (e) {
debugPrint('[RunProvider] 项目探测失败: $e');
} finally {
_isDetecting = false;
notifyListeners();
}
}
/// 保存并更新用户自定义任务
Future<void> updateCustomTasks(List<RunTask> updatedTasks) async {
if (_currentProjectRoot == null) return;
_customTasks = List.from(updatedTasks);
_resolveLastRunTask();
notifyListeners();
await _storageService.saveConfig(
projectRoot: _currentProjectRoot!,
tasks: _customTasks,
lastRunTaskId: _lastRunTaskId,
);
}
/// 添加单个自定义任务
Future<void> addCustomTask(RunTask task) async {
final list = List<RunTask>.from(_customTasks);
list.add(task);
await updateCustomTasks(list);
}
/// 删除单个自定义任务
Future<void> removeCustomTask(String taskId) async {
final list = _customTasks.where((t) => t.id != taskId).toList();
await updateCustomTasks(list);
}
/// 修改单个自定义任务
Future<void> editCustomTask(RunTask task) async {
final index = _customTasks.indexWhere((t) => t.id == task.id);
if (index != -1) {
final list = List<RunTask>.from(_customTasks);
list[index] = task;
await updateCustomTasks(list);
}
}
}
+175 -36
View File
@@ -9,6 +9,7 @@ import 'package:shared_preferences/shared_preferences.dart';
class SettingsProvider extends ChangeNotifier {
//外观
static const String _keyAppThemeMode = 'app_theme_mode'; //应用主题
static const String _keyAppThemeColor = 'app_theme_color'; //主题颜色
static const String _keyUiFont = 'app_ui_font'; //界面字体
//编辑区
@@ -22,24 +23,39 @@ class SettingsProvider extends ChangeNotifier {
//终端
static const String _keyTerminalFont = 'terminal_font_family'; //终端字体
static const String _keyTerminalBackgroundColor = 'terminal_background_color'; //终端背景颜色
static const String _keyEnableTerminalVirtualKeyboard = 'enable_terminal_virtual_keyboard'; //终端小键盘启用
static const String _keyTerminalKeyboardConfig = 'terminal_virtual_keyboard_config'; //终端小键盘配置JSON
//项目配置
static const String _keyShowHiddenFiles = 'show_hidden_files'; //显示隐藏文件
//语言
static const String _keyAppLocale = 'app_locale';
ThemeMode _appThemeMode = ThemeMode.system;
Color _appThemeColor = Colors.blue;
String _uiFontId = 'system_default';
EditorTheme _editorTheme = EditorTheme.atomOneDark;
String _editorFontId = 'jetbrains_mono';
String _terminalFontId = 'jetbrains_mono';
Color _terminalBackgroundColor = const Color(0xFF1E1E1E);
double _fontSize = 14.0;
int _indentSize = 4;
bool _wordWrap = false;
bool _enableVirtualKeyboard = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS;
String _virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty();
VirtualKeyboardConfig _virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration();
bool _enableTerminalVirtualKeyboard = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS;
String _terminalKeyboardConfigJson = VirtualKeyboardConfig.defaultTerminalJsonPretty();
VirtualKeyboardConfig _terminalKeyboardConfig = VirtualKeyboardConfig.defaultTerminalConfiguration();
bool _showHiddenFiles = true;
Locale? _locale;
bool get showHiddenFiles => _showHiddenFiles;
ThemeMode get appThemeMode => _appThemeMode;
Color get appThemeColor => _appThemeColor;
String get uiFontId => _uiFontId;
AppFontItem get uiFont => AppFonts.getUiFont(_uiFontId);
@@ -49,6 +65,7 @@ class SettingsProvider extends ChangeNotifier {
String get terminalFontId => _terminalFontId;
AppFontItem get terminalFont => AppFonts.getTerminalFont(_terminalFontId);
Color get terminalBackgroundColor => _terminalBackgroundColor;
double get fontSize => _fontSize;
int get indentSize => _indentSize;
@@ -56,8 +73,89 @@ class SettingsProvider extends ChangeNotifier {
bool get enableVirtualKeyboard => _enableVirtualKeyboard;
String get virtualKeyboardConfigJson => _virtualKeyboardConfigJson;
VirtualKeyboardConfig get virtualKeyboardConfig => _virtualKeyboardConfig;
bool get enableTerminalVirtualKeyboard => _enableTerminalVirtualKeyboard;
String get terminalKeyboardConfigJson => _terminalKeyboardConfigJson;
VirtualKeyboardConfig get terminalKeyboardConfig => _terminalKeyboardConfig;
Locale? get locale => _locale;
// ==========================================
// 小键盘配置:按作用域(编辑区 / 终端)读写两份互不干扰的配置
// ==========================================
/// 读取指定作用域的键盘配置
VirtualKeyboardConfig keyboardConfigFor(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? _terminalKeyboardConfig : _virtualKeyboardConfig;
/// 读取指定作用域的键盘配置 JSON
String keyboardConfigJsonFor(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? _terminalKeyboardConfigJson : _virtualKeyboardConfigJson;
/// 指定作用域的小键盘是否启用(两个开关相互独立)
bool keyboardEnabledFor(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? _enableTerminalVirtualKeyboard : _enableVirtualKeyboard;
static String _enablePrefKey(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? _keyEnableTerminalVirtualKeyboard : _keyEnableVirtualKeyboard;
static String _configPrefKey(KeyboardScope scope) =>
scope == KeyboardScope.terminal ? _keyTerminalKeyboardConfig : _keyVirtualKeyboardConfig;
/// 设置指定作用域小键盘的启用状态
Future<void> setKeyboardEnabled(KeyboardScope scope, bool enable) async {
if (keyboardEnabledFor(scope) == enable) return;
if (scope == KeyboardScope.terminal) {
_enableTerminalVirtualKeyboard = enable;
} else {
_enableVirtualKeyboard = enable;
}
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_enablePrefKey(scope), enable);
} catch (_) {}
}
/// 保存指定作用域的键盘配置 JSON,校验失败返回 false
Future<bool> setKeyboardConfig(KeyboardScope scope, String jsonStr) async {
final err = VirtualKeyboardConfig.validateJson(jsonStr, scope);
if (err != null) {
return false;
}
try {
final decoded = jsonDecode(jsonStr) as Map<String, dynamic>;
final config = VirtualKeyboardConfig.fromJson(decoded);
if (scope == KeyboardScope.terminal) {
_terminalKeyboardConfig = config;
_terminalKeyboardConfigJson = jsonStr;
} else {
_virtualKeyboardConfig = config;
_virtualKeyboardConfigJson = jsonStr;
}
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_configPrefKey(scope), jsonStr);
return true;
} catch (_) {
return false;
}
}
/// 将指定作用域的键盘配置恢复为该作用域的默认预设
Future<void> resetKeyboardConfig(KeyboardScope scope) async {
if (scope == KeyboardScope.terminal) {
_terminalKeyboardConfig = VirtualKeyboardConfig.defaultTerminalConfiguration();
_terminalKeyboardConfigJson = VirtualKeyboardConfig.defaultTerminalJsonPretty();
} else {
_virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration();
_virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty();
}
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_configPrefKey(scope));
} catch (_) {}
}
Future<void> init() async {
await _loadSettings();
}
@@ -75,6 +173,11 @@ class SettingsProvider extends ChangeNotifier {
);
}
final savedThemeColor = prefs.getInt(_keyAppThemeColor);
if (savedThemeColor != null) {
_appThemeColor = Color(savedThemeColor);
}
//设置编辑区
final themeId = prefs.getString(_keyEditorTheme);
_editorTheme = EditorTheme.fromId(themeId);
@@ -102,7 +205,7 @@ class SettingsProvider extends ChangeNotifier {
final savedKeyboardConfig = prefs.getString(_keyVirtualKeyboardConfig);
if (savedKeyboardConfig != null && savedKeyboardConfig.trim().isNotEmpty) {
final err = VirtualKeyboardConfig.validateJson(savedKeyboardConfig);
final err = VirtualKeyboardConfig.validateJson(savedKeyboardConfig, KeyboardScope.editor);
if (err == null) {
try {
final decoded = jsonDecode(savedKeyboardConfig) as Map<String, dynamic>;
@@ -112,6 +215,24 @@ class SettingsProvider extends ChangeNotifier {
}
}
//终端小键盘(独立开关 + 独立配置)
final savedEnableTerminalKeyboard = prefs.getBool(_keyEnableTerminalVirtualKeyboard);
if (savedEnableTerminalKeyboard != null) {
_enableTerminalVirtualKeyboard = savedEnableTerminalKeyboard;
}
final savedTerminalKeyboardConfig = prefs.getString(_keyTerminalKeyboardConfig);
if (savedTerminalKeyboardConfig != null && savedTerminalKeyboardConfig.trim().isNotEmpty) {
final err = VirtualKeyboardConfig.validateJson(savedTerminalKeyboardConfig, KeyboardScope.terminal);
if (err == null) {
try {
final decoded = jsonDecode(savedTerminalKeyboardConfig) as Map<String, dynamic>;
_terminalKeyboardConfig = VirtualKeyboardConfig.fromJson(decoded);
_terminalKeyboardConfigJson = savedTerminalKeyboardConfig;
} catch (_) {}
}
}
//设置字体
final savedUiFont = prefs.getString(_keyUiFont);
if (savedUiFont != null && savedUiFont.isNotEmpty) {
@@ -128,6 +249,17 @@ class SettingsProvider extends ChangeNotifier {
_terminalFontId = savedTerminalFont;
}
final savedTerminalBackground = prefs.getInt(_keyTerminalBackgroundColor);
if (savedTerminalBackground != null) {
_terminalBackgroundColor = Color(savedTerminalBackground);
}
//设置项目配置
final savedShowHiddenFiles = prefs.getBool(_keyShowHiddenFiles);
if (savedShowHiddenFiles != null) {
_showHiddenFiles = savedShowHiddenFiles;
}
//设置语言
final savedLocale = prefs.getString(_keyAppLocale);
if(savedLocale != null && savedLocale.isNotEmpty) {
@@ -150,6 +282,17 @@ class SettingsProvider extends ChangeNotifier {
}catch (_) {}
}
/// 设置主题颜色(Material 3 的 seed color)
Future<void> setAppThemeColor(Color color) async {
if (_appThemeColor.toARGB32() == color.toARGB32()) return;
_appThemeColor = color;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(_keyAppThemeColor, color.toARGB32());
} catch (_) {}
}
Future<void> setEditorTheme(EditorTheme theme) async {
if(_editorTheme.id == theme.id) return;
_editorTheme = theme;
@@ -192,43 +335,17 @@ class SettingsProvider extends ChangeNotifier {
}catch (_) {}
}
Future<void> setEnableVirtualKeyboard(bool enable) async {
if (_enableVirtualKeyboard == enable) return;
_enableVirtualKeyboard = enable;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_keyEnableVirtualKeyboard, enable);
} catch (_) {}
}
/// 编辑区小键盘开关(等价于 `setKeyboardEnabled(KeyboardScope.editor, ...)`)
Future<void> setEnableVirtualKeyboard(bool enable) =>
setKeyboardEnabled(KeyboardScope.editor, enable);
Future<bool> setVirtualKeyboardConfig(String jsonStr) async {
final err = VirtualKeyboardConfig.validateJson(jsonStr);
if (err != null) {
return false;
}
try {
final decoded = jsonDecode(jsonStr) as Map<String, dynamic>;
_virtualKeyboardConfig = VirtualKeyboardConfig.fromJson(decoded);
_virtualKeyboardConfigJson = jsonStr;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyVirtualKeyboardConfig, jsonStr);
return true;
} catch (_) {
return false;
}
}
/// 编辑区小键盘配置(等价于 `setKeyboardConfig(KeyboardScope.editor, ...)`)
Future<bool> setVirtualKeyboardConfig(String jsonStr) =>
setKeyboardConfig(KeyboardScope.editor, jsonStr);
Future<void> resetVirtualKeyboardConfig() async {
_virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration();
_virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty();
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyVirtualKeyboardConfig);
} catch (_) {}
}
/// 编辑区小键盘恢复默认
Future<void> resetVirtualKeyboardConfig() =>
resetKeyboardConfig(KeyboardScope.editor);
Future<void> setLocale(Locale? newLocale) async {
if(_locale == newLocale) return;
@@ -273,4 +390,26 @@ class SettingsProvider extends ChangeNotifier {
await prefs.setString(_keyTerminalFont, fontId);
} catch (_) {}
}
/// 设置终端背景颜色
Future<void> setTerminalBackgroundColor(Color color) async {
if (_terminalBackgroundColor.toARGB32() == color.toARGB32()) return;
_terminalBackgroundColor = color;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(_keyTerminalBackgroundColor, color.toARGB32());
} catch (_) {}
}
/// 设置是否显示隐藏文件
Future<void> setShowHiddenFiles(bool show) async {
if (_showHiddenFiles == show) return;
_showHiddenFiles = show;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_keyShowHiddenFiles, show);
} catch (_) {}
}
}
+28
View File
@@ -34,10 +34,12 @@ class TerminalProvider extends ChangeNotifier {
/// 创建新会话
/// [distroId]: 发行版标识符(如 'alpine', 'host')
/// [workspacePath]: 绑定的工程根目录路径(挂载至容器内部的 /workspace)
/// [activate]: 是否自动跳转切换到该会话。抽屉右上角加号点击时为 false(直接添加但不跳转)。
TerminalSession createSession({
String? name,
String distroId = 'alpine',
String? workspacePath,
bool activate = false,
bool autoStartProcess = true,
}) {
@@ -47,7 +49,11 @@ class TerminalProvider extends ChangeNotifier {
id: 'session_${DateTime.now().microsecondsSinceEpoch}_$nextIndex',
name: sessionName,
distroId: distroId,
workspacePath: workspacePath,
autoStartProcess: autoStartProcess,
onProcessTerminated: () {
notifyListeners();
},
);
_sessions.add(session);
@@ -60,6 +66,28 @@ class TerminalProvider extends ChangeNotifier {
return session;
}
/// 查找或复用绑定了指定工程路径的终端会话
/// 如果存在,直接激活并返回;如果不存在,则新建并激活一个会话
TerminalSession getOrCreateSessionForProject({
required String projectRoot,
String distroId = 'alpine',
String? sessionName,
}) {
final index = _sessions.indexWhere((s) => s.workspacePath == projectRoot);
if (index != -1) {
selectSession(index);
return _sessions[index];
}
return createSession(
name: sessionName,
distroId: distroId,
workspacePath: projectRoot,
activate: true,
autoStartProcess: true,
);
}
/// 切换当前激活的会话
void selectSession(int index) {
if (index >= 0 && index < _sessions.length) {
+3 -1
View File
@@ -14,6 +14,7 @@ class FileService {
int depth = 0,
List<String> openDirectoryPaths = const [],
int maxDepth = 10,
bool showHiddenFiles = true,
}) async {
if(depth > maxDepth) {
return [];
@@ -45,7 +46,7 @@ class FileService {
for(var entity in entities) {
try {
final fileName = p.basename(entity.path);
if (fileName.startsWith('.')) continue;
if (!showHiddenFiles && fileName.startsWith('.')) continue;
final entityPath = p.normalize(entity.path);
String? relativePath;
@@ -64,6 +65,7 @@ class FileService {
depth: depth + 1,
openDirectoryPaths: openDirectoryPaths,
maxDepth: maxDepth,
showHiddenFiles: showHiddenFiles,
);
}
items.add(FileItem(
+279
View File
@@ -0,0 +1,279 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../models/run_task.dart';
/// 负责根据工程文件和当前打开的文件,在内存中动态推导可用的运行任务
class ProjectTaskDetector {
/// 核心探测入口
/// [projectRoot]: 工程根目录(宿主绝对路径)
/// [currentFilePath]: 当前编辑器激活打开的文件(宿主绝对路径,可能为 null)
static Future<List<RunTask>> detect({
required String projectRoot,
String? currentFilePath,
}) async {
final List<RunTask> tasks = [];
final projectDir = Directory(projectRoot);
if (!projectDir.existsSync()) {
return tasks;
}
// 1. 工程级特征文件检测
tasks.addAll(await _detectProjectBuildTasks(projectRoot));
// 2. 当前活跃文件(单文件运行)检测
if (currentFilePath != null && currentFilePath.isNotEmpty) {
final singleTask = _detectSingleFileTask(projectRoot, currentFilePath);
if (singleTask != null) {
// 单文件即时运行置于首位,方便用户直接点击运行
tasks.insert(0, singleTask);
}
}
return tasks;
}
/// 探测构建工程任务(CMake / Gradle / Makefile / npm / Cargo / Dart 等)
static Future<List<RunTask>> _detectProjectBuildTasks(String projectRoot) async {
final List<RunTask> buildTasks = [];
// 1. CMakeLists.txt
final cmakeFile = File(p.join(projectRoot, 'CMakeLists.txt'));
if (cmakeFile.existsSync()) {
final projectName = p.basename(projectRoot);
buildTasks.addAll([
RunTask(
id: 'detected_cmake_build_run',
name: 'CMake: Build & Run',
command: 'cmake -B build && cmake --build build && ./build/$projectName',
source: TaskSource.detected,
description: '配置、编译并尝试启动生成的目标程序',
icon: Icons.play_circle_outline,
),
RunTask(
id: 'detected_cmake_build',
name: 'CMake: Build Only',
command: 'cmake -B build && cmake --build build',
source: TaskSource.detected,
description: '仅执行 cmake 生成与构建',
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_cmake_clean',
name: 'CMake: Clean',
command: 'rm -rf build',
source: TaskSource.detected,
description: '清理构建缓存目录',
icon: Icons.cleaning_services_outlined,
),
]);
}
// 2. Gradle (build.gradle / gradlew)
final gradlewFile = File(p.join(projectRoot, 'gradlew'));
final gradleFile = File(p.join(projectRoot, 'build.gradle'));
final gradleKtsFile = File(p.join(projectRoot, 'build.gradle.kts'));
if (gradlewFile.existsSync() || gradleFile.existsSync() || gradleKtsFile.existsSync()) {
final exec = gradlewFile.existsSync() ? './gradlew' : 'gradle';
buildTasks.addAll([
RunTask(
id: 'detected_gradle_run',
name: 'Gradle: Run',
command: '$exec run',
source: TaskSource.detected,
description: '执行应用程序主入口',
icon: Icons.play_circle_outline,
),
RunTask(
id: 'detected_gradle_assemble',
name: 'Gradle: Assemble Debug',
command: '$exec assembleDebug',
source: TaskSource.detected,
description: '构建调试输出包',
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_gradle_build',
name: 'Gradle: Build',
command: '$exec build',
source: TaskSource.detected,
description: '执行完整构建与测试',
icon: Icons.done_all_outlined,
),
]);
}
// 3. Makefile
final makeFile = File(p.join(projectRoot, 'Makefile'));
if (makeFile.existsSync()) {
buildTasks.add(
const RunTask(
id: 'detected_make_default',
name: 'Make: Default',
command: 'make',
source: TaskSource.detected,
description: '执行默认 Makefile 构建目标',
icon: Icons.build_circle_outlined,
),
);
}
// 4. package.json (Node/Web)
final packageJsonFile = File(p.join(projectRoot, 'package.json'));
if (packageJsonFile.existsSync()) {
buildTasks.addAll([
const RunTask(
id: 'detected_npm_start',
name: 'NPM: Start',
command: 'npm start',
source: TaskSource.detected,
description: '启动 Node 服务或前端开发环境',
icon: Icons.rocket_launch_outlined,
),
const RunTask(
id: 'detected_npm_test',
name: 'NPM: Test',
command: 'npm test',
source: TaskSource.detected,
description: '执行 npm test 测试套件',
icon: Icons.checklist_outlined,
),
]);
}
// 5. Cargo.toml (Rust)
final cargoFile = File(p.join(projectRoot, 'Cargo.toml'));
if (cargoFile.existsSync()) {
buildTasks.addAll([
const RunTask(
id: 'detected_cargo_run',
name: 'Cargo: Run',
command: 'cargo run',
source: TaskSource.detected,
description: '编译并运行 Rust 项目',
icon: Icons.play_circle_outline,
),
const RunTask(
id: 'detected_cargo_build',
name: 'Cargo: Build',
command: 'cargo build',
source: TaskSource.detected,
description: '仅编译 Rust 项目',
icon: Icons.build_outlined,
),
]);
}
// 6. pubspec.yaml (Dart)
final pubspecFile = File(p.join(projectRoot, 'pubspec.yaml'));
if (pubspecFile.existsSync()) {
buildTasks.add(
const RunTask(
id: 'detected_dart_run',
name: 'Dart: Run',
command: 'dart run',
source: TaskSource.detected,
description: '启动 Dart 应用',
icon: Icons.play_circle_outline,
),
);
}
return buildTasks;
}
/// 探测单文件运行指令(基于当前打开的文件)
static RunTask? _detectSingleFileTask(String projectRoot, String currentFilePath) {
final file = File(currentFilePath);
if (!file.existsSync()) return null;
final fileName = p.basename(currentFilePath);
final ext = p.extension(currentFilePath).toLowerCase();
// 转换相对容器的路径(在容器内 /workspace 下执行)
String relPath = p.relative(currentFilePath, from: projectRoot).replaceAll(r'\', '/');
if (!relPath.startsWith('./') && !relPath.startsWith('/')) {
relPath = './$relPath';
}
switch (ext) {
case '.py':
return RunTask(
id: 'detected_single_python',
name: 'Python: $fileName',
command: 'python3 "$relPath"',
source: TaskSource.detected,
description: '运行当前 Python 脚本',
icon: Icons.code,
);
case '.c':
return RunTask(
id: 'detected_single_c',
name: 'GCC: $fileName',
command: 'gcc "$relPath" -o /tmp/a.out && /tmp/a.out',
source: TaskSource.detected,
description: '编译并执行当前 C 源文件',
icon: Icons.terminal,
);
case '.cpp':
case '.cc':
case '.cxx':
return RunTask(
id: 'detected_single_cpp',
name: 'G++: $fileName',
command: 'g++ "$relPath" -o /tmp/a.out && /tmp/a.out',
source: TaskSource.detected,
description: '编译并执行当前 C++ 源文件',
icon: Icons.terminal,
);
case '.sh':
case '.bash':
return RunTask(
id: 'detected_single_sh',
name: 'Shell: $fileName',
command: 'sh "$relPath"',
source: TaskSource.detected,
description: '运行当前 Shell 脚本',
icon: Icons.terminal,
);
case '.dart':
return RunTask(
id: 'detected_single_dart',
name: 'Dart: $fileName',
command: 'dart run "$relPath"',
source: TaskSource.detected,
description: '运行当前 Dart 文件',
icon: Icons.code,
);
case '.go':
return RunTask(
id: 'detected_single_go',
name: 'Go: $fileName',
command: 'go run "$relPath"',
source: TaskSource.detected,
description: '运行当前 Go 源文件',
icon: Icons.code,
);
case '.rs':
return RunTask(
id: 'detected_single_rust',
name: 'Rust: $fileName',
command: 'rustc "$relPath" -o /tmp/a.out && /tmp/a.out',
source: TaskSource.detected,
description: '编译并执行当前 Rust 源文件',
icon: Icons.code,
);
case '.js':
return RunTask(
id: 'detected_single_js',
name: 'Node: $fileName',
command: 'node "$relPath"',
source: TaskSource.detected,
description: '运行当前 JS 脚本',
icon: Icons.javascript,
);
default:
return null;
}
}
}
@@ -0,0 +1,97 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import '../models/run_task.dart';
/// 负责工程目录下 `.code_editor/run_tasks.json` 的读写与持久化管理
class RunTaskStorageService {
static const String configDirName = '.code_editor';
static const String configFileName = 'run_tasks.json';
/// 获取配置文件的绝对 File 对象
File getConfigFile(String projectRoot) {
return File(p.join(projectRoot, configDirName, configFileName));
}
/// 从工程的 `.code_editor/run_tasks.json` 中读取持久化的配置(包括自定义任务与最近运行任务ID)
Future<({List<RunTask> tasks, String? lastRunTaskId})> loadConfig(String projectRoot) async {
try {
final file = getConfigFile(projectRoot);
if (!await file.exists()) {
return (tasks: <RunTask>[], lastRunTaskId: null);
}
final content = await file.readAsString();
if (content.trim().isEmpty) {
return (tasks: <RunTask>[], lastRunTaskId: null);
}
final dynamic decoded = jsonDecode(content);
if (decoded is Map<String, dynamic>) {
final lastId = decoded['lastRunTaskId'] as String?;
final tasksRaw = decoded['tasks'];
List<RunTask> list = [];
if (tasksRaw is List) {
list = tasksRaw
.whereType<Map<String, dynamic>>()
.map((item) => RunTask.fromJson(item))
.toList();
}
return (tasks: list, lastRunTaskId: lastId);
} else if (decoded is List) {
final list = decoded
.whereType<Map<String, dynamic>>()
.map((item) => RunTask.fromJson(item))
.toList();
return (tasks: list, lastRunTaskId: null);
}
return (tasks: <RunTask>[], lastRunTaskId: null);
} catch (e) {
debugPrint('[RunTaskStorageService] 读取 run_tasks.json 失败: $e');
return (tasks: <RunTask>[], lastRunTaskId: null);
}
}
/// 兼容旧方法:直接返回 tasks
Future<List<RunTask>> loadTasks(String projectRoot) async {
final result = await loadConfig(projectRoot);
return result.tasks;
}
/// 将自定义任务列表与最近运行的任务ID持久化保存到 `.code_editor/run_tasks.json`
Future<void> saveConfig({
required String projectRoot,
required List<RunTask> tasks,
String? lastRunTaskId,
}) async {
try {
final file = getConfigFile(projectRoot);
final dir = file.parent;
if (!await dir.exists()) {
await dir.create(recursive: true);
}
final data = {
'version': '1.0',
if (lastRunTaskId != null && lastRunTaskId.isNotEmpty) 'lastRunTaskId': lastRunTaskId,
'tasks': tasks
.where((t) => t.source == TaskSource.custom)
.map((t) => t.toJson())
.toList(),
};
const encoder = JsonEncoder.withIndent(' ');
final jsonStr = encoder.convert(data);
await file.writeAsString(jsonStr, flush: true);
} catch (e) {
debugPrint('[RunTaskStorageService] 保存 run_tasks.json 失败: $e');
rethrow;
}
}
/// 兼容旧方法
Future<void> saveTasks(String projectRoot, List<RunTask> tasks) async {
await saveConfig(projectRoot: projectRoot, tasks: tasks);
}
}
+32
View File
@@ -0,0 +1,32 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// 按"主题色 + 亮暗 + 界面字体"构建应用主题。
///
/// 抽成纯函数便于单测:换一个 seed 应得到不同的 colorScheme。
ThemeData buildAppTheme({
required Color seedColor,
required Brightness brightness,
String? fontFamily,
List<String>? fontFamilyFallback,
}) {
final isLight = brightness == Brightness.light;
return ThemeData(
useMaterial3: true,
brightness: brightness,
colorScheme: ColorScheme.fromSeed(
seedColor: seedColor,
brightness: brightness,
),
appBarTheme: AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: isLight ? Brightness.dark : Brightness.light,
statusBarBrightness: isLight ? Brightness.light : Brightness.dark,
),
),
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
);
}
+38
View File
@@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart' as xterm;
/// 以指定背景色重建终端主题。
///
/// xterm 的 `TerminalTheme` 没有 copyWith 且全部字段必填,所以这里基于
/// `TerminalThemes.defaultTheme` 复制一份,只替换背景;当背景偏亮时同步把
/// 前景、光标切换为深色,避免浅色背景下文字看不清。
xterm.TerminalTheme terminalThemeWithBackground(Color background) {
final base = xterm.TerminalThemes.defaultTheme;
final isLight = background.computeLuminance() > 0.5;
return xterm.TerminalTheme(
cursor: isLight ? const Color(0xFF1F1F1F) : base.cursor,
selection: base.selection,
foreground: isLight ? const Color(0xFF1F1F1F) : base.foreground,
background: background,
black: base.black,
white: base.white,
red: base.red,
green: base.green,
yellow: base.yellow,
blue: base.blue,
magenta: base.magenta,
cyan: base.cyan,
brightBlack: base.brightBlack,
brightRed: base.brightRed,
brightGreen: base.brightGreen,
brightYellow: base.brightYellow,
brightBlue: base.brightBlue,
brightMagenta: base.brightMagenta,
brightCyan: base.brightCyan,
brightWhite: base.brightWhite,
searchHitBackground: base.searchHitBackground,
searchHitBackgroundCurrent: base.searchHitBackgroundCurrent,
searchHitForeground: base.searchHitForeground,
);
}
+183 -2
View File
@@ -1,18 +1,31 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/run_task.dart';
import 'package:code_editor/providers/project_provider.dart';
import 'package:code_editor/providers/run_provider.dart';
import 'package:code_editor/providers/tab_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/views/settings_view.dart';
import 'package:code_editor/views/terminal_view.dart';
import 'package:code_editor/widgets/code_editor_app_bar.dart';
import 'package:code_editor/widgets/code_editor_drawer.dart';
import 'package:code_editor/widgets/code_editor_tab_bar.dart';
import 'package:code_editor/widgets/code_editor_widget.dart';
import 'package:code_editor/views/run_task_edit_view.dart';
import 'package:code_editor/widgets/run_tasks_dialog.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class MainView extends StatelessWidget {
class MainView extends StatefulWidget {
const MainView({super.key});
@override
State<MainView> createState() => _MainViewState();
}
class _MainViewState extends State<MainView> {
String? _lastProjectRoot;
static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) {
return listen ? context.watch<ProjectProvider>() : context.read<ProjectProvider>();
}
@@ -21,6 +34,22 @@ class MainView extends StatelessWidget {
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
}
static RunProvider? _getRunProvider(BuildContext context, {bool listen = false}) {
try {
return listen ? Provider.of<RunProvider>(context, listen: listen) : Provider.of<RunProvider>(context, listen: false);
} catch (_) {
return null;
}
}
static TerminalProvider? _getTerminalProvider(BuildContext context, {bool listen = false}) {
try {
return listen ? Provider.of<TerminalProvider>(context, listen: listen) : Provider.of<TerminalProvider>(context, listen: false);
} catch (_) {
return null;
}
}
void _handleSave(BuildContext context) async {
final tabProvider = _getTabProvider(context);
if (tabProvider.currentFilePath == null || tabProvider.currentFilePath!.isEmpty) {
@@ -52,6 +81,143 @@ class MainView extends StatelessWidget {
final canProceed = await tabProvider.checkUnsavedChanges(context);
if (canProceed && context.mounted) {
await projectProvider.closeProject();
if (context.mounted) {
_getRunProvider(context)?.onProjectClosed();
}
}
}
/// 执行某个具体的运行任务(复用/创建当前工程工作目录的终端并执行指令)
void _executeRunTask(BuildContext context, RunTask task) {
final projectProvider = _getProjectProvider(context);
final l10n = AppLocalizations.of(context)!;
final rootPath = projectProvider.rootPath;
if (rootPath == null || rootPath.isEmpty) {
DialogUtils.showErrorToast(context, l10n.noOpenDirectory);
return;
}
final terminalProvider = _getTerminalProvider(context);
final runProvider = _getRunProvider(context);
// 1. 查找或创建绑定了该工程工作路径的终端会话(保持系统默认会话名称)
final session = terminalProvider?.getOrCreateSessionForProject(
projectRoot: rootPath,
distroId: 'alpine',
);
// 2. 记录最近执行的任务
runProvider?.setLastRunTask(task);
// 3. 跳转至终端视图
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => const TerminalView(),
),
);
// 4. 等待界面跳转后向终端发送指令
Future.delayed(const Duration(milliseconds: 300), () {
if (session != null) {
if (task.clearBeforeRun) {
session.write('clear\r\n');
}
session.write('${task.command}\r\n');
}
});
}
/// 点击运行按钮 (Play):有历史任务或单文件即直接执行,否则弹出任务列表
void _handleRun(BuildContext context) {
final projectProvider = _getProjectProvider(context);
final l10n = AppLocalizations.of(context)!;
final rootPath = projectProvider.rootPath;
if (rootPath == null || rootPath.isEmpty) {
DialogUtils.showErrorToast(context, l10n.pleaseOpenProjectFirst);
return;
}
final runProvider = _getRunProvider(context);
if (runProvider == null) return;
// 优先: 最近运行的任务(若已持久化并存在)
if (runProvider.lastRunTask != null) {
_executeRunTask(context, runProvider.lastRunTask!);
return;
}
// 若没有上一次运行的任务,直接打开运行任务列表
_handleOpenRunTasksDialog(context);
}
/// 打开运行任务选择弹窗
void _handleOpenRunTasksDialog(BuildContext context) {
final runProvider = _getRunProvider(context);
if (runProvider == null) return;
final projectProvider = _getProjectProvider(context);
final l10n = AppLocalizations.of(context)!;
final rootPath = projectProvider.rootPath;
if (rootPath == null || rootPath.isEmpty) {
DialogUtils.showErrorToast(context, l10n.pleaseOpenProjectFirst);
return;
}
RunTasksDialog.show(
context: context,
customTasks: runProvider.customTasks,
detectedTasks: runProvider.detectedTasks,
lastRunTaskId: runProvider.lastRunTaskId ?? runProvider.lastRunTask?.id,
onTaskSelected: (task) => _executeRunTask(context, task),
onEditCustomTasks: () => _handleOpenEditRunTasks(context),
);
}
/// 打开运行任务编辑独立 View
void _handleOpenEditRunTasks(BuildContext context) {
final projectProvider = _getProjectProvider(context);
final l10n = AppLocalizations.of(context)!;
final rootPath = projectProvider.rootPath;
if (rootPath == null || rootPath.isEmpty) {
DialogUtils.showErrorToast(context, l10n.pleaseOpenProjectFirst);
return;
}
final runProvider = _getRunProvider(context);
if (runProvider == null) return;
RunTaskEditView.navigate(
context: context,
currentTasks: runProvider.customTasks,
onSave: (updatedTasks) async {
await runProvider.updateCustomTasks(updatedTasks);
if (context.mounted) {
DialogUtils.showSuccessToast(context, l10n.runTasksUpdated);
}
},
);
}
/// 手动触发项目探测
void _handleProjectDetect(BuildContext context) async {
final projectProvider = _getProjectProvider(context);
final rootPath = projectProvider.rootPath;
if (rootPath == null || rootPath.isEmpty) return;
final tabProvider = _getTabProvider(context);
final runProvider = _getRunProvider(context);
if (runProvider == null) return;
await runProvider.detectTasks(
projectRoot: rootPath,
currentFilePath: tabProvider.currentFilePath,
);
if (context.mounted) {
final l10n = AppLocalizations.of(context)!;
DialogUtils.showSuccessToast(
context,
l10n.detectCompletedMessage(runProvider.detectedTasks.length),
);
}
}
@@ -59,6 +225,7 @@ class MainView extends StatelessWidget {
Widget build(BuildContext context) {
final projectProvider = _getProjectProvider(context, listen: true);
final tabProvider = _getTabProvider(context, listen: true);
final runProvider = _getRunProvider(context, listen: true);
if (projectProvider.isLoading) {
return const Center(child: CircularProgressIndicator());
@@ -68,6 +235,16 @@ class MainView extends StatelessWidget {
final rootPath = projectProvider.rootPath;
final isModified = tabProvider.isModified;
// 当检测到切换了项目根目录时,自动触发初始化并进行一次探测
if (rootPath != null && rootPath != _lastProjectRoot) {
_lastProjectRoot = rootPath;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
runProvider?.onProjectOpened(rootPath, activeFilePath: currentFile);
}
});
}
return PopScope(
canPop: !isModified,
onPopInvokedWithResult: (didPop, result) async {
@@ -86,7 +263,11 @@ class MainView extends StatelessWidget {
onSaveAll: () => _handleSaveAll(context),
onCloseAllTabs: () => _handleCloseAllTabs(context),
onCloseProject: () => _handleCloseProject(context),
onRun: () {},
onRun: () => _handleRun(context),
onRunTasks: () => _handleOpenRunTasksDialog(context),
onProjectDetect: () => _handleProjectDetect(context),
onEditRunTasks: () => _handleOpenEditRunTasks(context),
isDetecting: runProvider?.isDetecting ?? false,
onSettings: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
+204
View File
@@ -0,0 +1,204 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import '../models/run_task.dart';
import '../utils/dialog_utils.dart';
/// 运行任务单项创建/编辑 View(独立页面,点击返回键返回任务配置界面)
class RunTaskDetailView extends StatefulWidget {
final RunTask? initialTask;
final ValueChanged<RunTask> onSave;
const RunTaskDetailView({
super.key,
this.initialTask,
required this.onSave,
});
static Future<void> navigate({
required BuildContext context,
RunTask? initialTask,
required ValueChanged<RunTask> onSave,
}) {
return Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (ctx) => RunTaskDetailView(
initialTask: initialTask,
onSave: onSave,
),
),
);
}
@override
State<RunTaskDetailView> createState() => _RunTaskDetailViewState();
}
class _RunTaskDetailViewState extends State<RunTaskDetailView> {
final _formKey = GlobalKey<FormState>();
late TextEditingController _nameController;
late TextEditingController _commandController;
late TextEditingController _descController;
bool _clearBeforeRun = false;
late String _initialName;
late String _initialCommand;
late String _initialDesc;
late bool _initialClearBeforeRun;
@override
void initState() {
super.initState();
final task = widget.initialTask;
_initialName = task?.name ?? '';
_initialCommand = task?.command ?? '';
_initialDesc = task?.description ?? '';
_initialClearBeforeRun = task?.clearBeforeRun ?? false;
_nameController = TextEditingController(text: _initialName);
_commandController = TextEditingController(text: _initialCommand);
_descController = TextEditingController(text: _initialDesc);
_clearBeforeRun = _initialClearBeforeRun;
}
@override
void dispose() {
_nameController.dispose();
_commandController.dispose();
_descController.dispose();
super.dispose();
}
bool get _isDirty {
return _nameController.text != _initialName ||
_commandController.text != _initialCommand ||
_descController.text != _initialDesc ||
_clearBeforeRun != _initialClearBeforeRun;
}
Future<bool> _confirmDiscardChanges() async {
if (!_isDirty) return true;
final l10n = AppLocalizations.of(context)!;
final shouldDiscard = await DialogUtils.showConfirmDialog(
context,
title: l10n.unsavedTaskChangesTitle,
message: l10n.unsavedTaskChangesMessage,
confirmText: l10n.dontSave,
cancelText: l10n.cancel,
icon: Icon(
Icons.warning_amber_rounded,
color: Theme.of(context).colorScheme.error,
size: 28,
),
);
return shouldDiscard;
}
void _save() {
if (!_formKey.currentState!.validate()) return;
final task = RunTask(
id: widget.initialTask?.id ?? 'custom_${DateTime.now().microsecondsSinceEpoch}',
name: _nameController.text.trim(),
command: _commandController.text.trim(),
source: TaskSource.custom,
description: _descController.text.trim().isEmpty ? null : _descController.text.trim(),
clearBeforeRun: _clearBeforeRun,
);
widget.onSave(task);
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final isEditing = widget.initialTask != null;
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, result) async {
if (didPop) return;
final canDiscard = await _confirmDiscardChanges();
if (canDiscard && context.mounted) {
Navigator.of(context).pop();
}
},
child: Scaffold(
appBar: AppBar(
title: Text(isEditing ? l10n.editTask : l10n.addTask),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: l10n.back,
onPressed: () async {
final canDiscard = await _confirmDiscardChanges();
if (canDiscard && context.mounted) {
Navigator.of(context).pop();
}
},
),
actions: [
IconButton(
icon: const Icon(Icons.check),
tooltip: l10n.done,
onPressed: _save,
),
],
),
body: Form(
key: _formKey,
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: l10n.taskNameRequired,
hintText: l10n.taskNameHint,
border: const OutlineInputBorder(),
isDense: true,
),
validator: (v) => (v == null || v.trim().isEmpty) ? l10n.taskNameEmptyError : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _descController,
decoration: InputDecoration(
labelText: l10n.taskDescOptional,
hintText: l10n.taskDescHint,
border: const OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 16),
TextFormField(
controller: _commandController,
maxLines: 4,
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
decoration: InputDecoration(
labelText: l10n.shellCommandRequired,
hintText: l10n.shellCommandHint,
border: const OutlineInputBorder(),
alignLabelWithHint: true,
isDense: true,
),
validator: (v) => (v == null || v.trim().isEmpty) ? l10n.shellCommandEmptyError : null,
),
const SizedBox(height: 16),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(l10n.clearBeforeRun),
subtitle: Text(l10n.clearBeforeRunSubtitle, style: const TextStyle(fontSize: 12)),
value: _clearBeforeRun,
onChanged: (val) => setState(() => _clearBeforeRun = val),
),
],
),
),
),
),
);
}
}
+337
View File
@@ -0,0 +1,337 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import '../models/run_task.dart';
import 'run_task_detail_view.dart';
/// 运行任务列表配置 View(支持拖动排序、单项与多选删除确认、自动静默保存至 JSON)
class RunTaskEditView extends StatefulWidget {
final List<RunTask> tasks;
final ValueChanged<List<RunTask>> onSave;
const RunTaskEditView({
super.key,
required this.tasks,
required this.onSave,
});
static Future<void> navigate({
required BuildContext context,
required List<RunTask> currentTasks,
required ValueChanged<List<RunTask>> onSave,
}) {
return Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (ctx) => RunTaskEditView(
tasks: currentTasks,
onSave: onSave,
),
),
);
}
@override
State<RunTaskEditView> createState() => _RunTaskEditViewState();
}
class _RunTaskEditViewState extends State<RunTaskEditView> {
late List<RunTask> _taskList;
bool _isSelectionMode = false;
final Set<String> _selectedTaskIds = {};
@override
void initState() {
super.initState();
_taskList = List.from(widget.tasks);
}
/// 任何变动立即写回(直接写回 JSON,无需点击额外保存按钮)
void _persistChanges() {
widget.onSave(List.unmodifiable(_taskList));
}
void _openCreateView() {
RunTaskDetailView.navigate(
context: context,
onSave: (newTask) {
setState(() {
_taskList.add(newTask);
});
_persistChanges();
},
);
}
void _openEditView(RunTask task) {
RunTaskDetailView.navigate(
context: context,
initialTask: task,
onSave: (updatedTask) {
final index = _taskList.indexWhere((t) => t.id == updatedTask.id);
if (index != -1) {
setState(() {
_taskList[index] = updatedTask;
});
_persistChanges();
}
},
);
}
/// 单项删除确认弹窗
Future<void> _confirmDeleteSingle(RunTask task) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.confirmDelete),
content: Text(l10n.deleteTaskConfirmMessage(task.name)),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: Text(l10n.cancel),
),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.error),
onPressed: () => Navigator.of(ctx).pop(true),
child: Text(l10n.delete),
),
],
),
);
if (confirmed == true && mounted) {
setState(() {
_taskList.removeWhere((t) => t.id == task.id);
_selectedTaskIds.remove(task.id);
});
_persistChanges();
}
}
/// 多选批量删除确认弹窗
Future<void> _confirmDeleteBatch() async {
if (_selectedTaskIds.isEmpty) return;
final l10n = AppLocalizations.of(context)!;
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.confirmDelete),
content: Text(l10n.deleteSelectedTasksConfirmMessage(_selectedTaskIds.length)),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: Text(l10n.cancel),
),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.error),
onPressed: () => Navigator.of(ctx).pop(true),
child: Text(l10n.delete),
),
],
),
);
if (confirmed == true && mounted) {
setState(() {
_taskList.removeWhere((t) => _selectedTaskIds.contains(t.id));
_selectedTaskIds.clear();
_isSelectionMode = false;
});
_persistChanges();
}
}
void _toggleSelection(String id) {
setState(() {
if (_selectedTaskIds.contains(id)) {
_selectedTaskIds.remove(id);
if (_selectedTaskIds.isEmpty) {
_isSelectionMode = false;
}
} else {
_selectedTaskIds.add(id);
}
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(
title: Text(_isSelectionMode
? l10n.selectedCount(_selectedTaskIds.length)
: l10n.runTasksConfig),
leading: _isSelectionMode
? IconButton(
icon: const Icon(Icons.close),
onPressed: () {
setState(() {
_isSelectionMode = false;
_selectedTaskIds.clear();
});
},
)
: null,
actions: [
if (_isSelectionMode)
IconButton(
icon: Icon(Icons.delete_outline, color: theme.colorScheme.error),
tooltip: l10n.deleteSelected,
onPressed: _confirmDeleteBatch,
)
else if (_taskList.isNotEmpty)
IconButton(
icon: const Icon(Icons.checklist),
tooltip: l10n.selectTasksToDelete,
onPressed: () {
setState(() {
_isSelectionMode = true;
});
},
),
],
),
body: SafeArea(
child: _taskList.isEmpty ? _buildEmptyView(theme, l10n) : _buildReorderableList(theme, l10n),
),
floatingActionButton: !_isSelectionMode
? FloatingActionButton(
onPressed: _openCreateView,
tooltip: l10n.addTask,
child: const Icon(Icons.add),
)
: null,
);
}
Widget _buildEmptyView(ThemeData theme, AppLocalizations l10n) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.playlist_remove, size: 56, color: theme.colorScheme.outline),
const SizedBox(height: 12),
Text(l10n.noCustomTasksInProject,
style: theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.outline)),
const SizedBox(height: 16),
FilledButton.icon(
icon: const Icon(Icons.add),
label: Text(l10n.createNow),
onPressed: _openCreateView,
),
],
),
);
}
Widget _buildReorderableList(ThemeData theme, AppLocalizations l10n) {
return ReorderableListView.builder(
buildDefaultDragHandles: false,
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _taskList.length,
onReorderItem: (oldIndex, newIndex) {
setState(() {
final task = _taskList.removeAt(oldIndex);
_taskList.insert(newIndex, task);
});
_persistChanges();
},
itemBuilder: (ctx, index) {
final task = _taskList[index];
final isSelected = _selectedTaskIds.contains(task.id);
return Card(
key: ValueKey(task.id),
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
elevation: 0,
color: isSelected
? theme.colorScheme.primaryContainer.withValues(alpha: 0.3)
: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: isSelected
? theme.colorScheme.primary
: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
),
),
child: ListTile(
dense: true,
contentPadding: const EdgeInsets.only(left: 12, right: 4, top: 2, bottom: 2),
leading: _isSelectionMode
? Checkbox(
value: isSelected,
onChanged: (_) => _toggleSelection(task.id),
)
: const CircleAvatar(
radius: 16,
child: Icon(Icons.terminal, size: 18),
),
// 只显示:名称 + 用途(描述)
title: Text(
task.name,
style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: (task.description != null && task.description!.trim().isNotEmpty)
? Text(
task.description!.trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.colorScheme.outline),
)
: null,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (!_isSelectionMode) ...[
IconButton(
icon: const Icon(Icons.edit_outlined, size: 20),
tooltip: l10n.editTask,
onPressed: () => _openEditView(task),
),
IconButton(
icon: Icon(Icons.delete_outline, size: 20, color: theme.colorScheme.error),
tooltip: l10n.delete,
onPressed: () => _confirmDeleteSingle(task),
),
// 最右侧拖动把手,支持长按/拖动排序
ReorderableDragStartListener(
index: index,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Icon(
Icons.drag_handle,
color: theme.colorScheme.outline,
size: 22,
),
),
),
],
],
),
onTap: () {
if (_isSelectionMode) {
_toggleSelection(task.id);
} else {
_openEditView(task);
}
},
onLongPress: () {
if (!_isSelectionMode) {
setState(() {
_isSelectionMode = true;
_selectedTaskIds.add(task.id);
});
}
},
),
);
},
);
}
}
+187 -16
View File
@@ -5,6 +5,7 @@ import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/color_palette_dialog.dart';
import 'virtual_keyboard_config_view.dart';
/// 设置页面
@@ -38,6 +39,7 @@ class SettingsView extends StatelessWidget {
// ==============================
_buildSectionHeader(context, l10n.appearanceSection),
_buildThemeModeTile(context, provider, l10n),
_buildThemeColorTile(context, provider, l10n),
_buildUiFontTile(context, provider),
const Divider(height: 32, indent: 16, endIndent: 16),
@@ -59,13 +61,24 @@ class SettingsView extends StatelessWidget {
// ==============================
// 3. 终端分组 (Terminal)
// ==============================
_buildSectionHeader(context, '终端'),
_buildSectionHeader(context, l10n.terminal),
_buildTerminalBackgroundTile(context, provider, l10n),
_buildTerminalVirtualKeyboardTile(context, provider, l10n),
_buildTerminalVirtualKeyboardConfigTile(context, provider, l10n),
_buildTerminalFontTile(context, provider),
const Divider(height: 32, indent: 16, endIndent: 16),
// ==============================
// 4. 语言分组 (Language)
// 4. 项目分组 (Project)
// ==============================
_buildSectionHeader(context, l10n.projectSection),
_buildShowHiddenFilesTile(context, provider, l10n),
const Divider(height: 32, indent: 16, endIndent: 16),
// ==============================
// 5. 语言分组 (Language)
// ==============================
_buildSectionHeader(context, l10n.languageSection),
_buildLanguageTile(context, provider, l10n),
@@ -178,19 +191,20 @@ class SettingsView extends StatelessWidget {
/// 外观:UI 界面字体条目
Widget _buildUiFontTile(BuildContext context, SettingsProvider provider) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final currentFont = provider.uiFont;
return ListTile(
leading: Icon(Icons.font_download_outlined, color: theme.colorScheme.primary),
title: const Text('界面字体'),
subtitle: Text(currentFont.name),
title: Text(l10n.uiFont),
subtitle: Text(l10n.fontName(currentFont.id)),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showFontSelector(
context,
title: '选择界面字体',
title: l10n.selectUiFont,
fonts: AppFonts.uiFonts,
currentId: provider.uiFontId,
previewSample: '代码编辑器界面字体预览 Code Editor 123',
previewSample: l10n.uiFontPreview,
onSelected: (id) => provider.setUiFontId(id),
);
},
@@ -200,19 +214,25 @@ class SettingsView extends StatelessWidget {
/// 编辑区:代码字体条目
Widget _buildEditorFontTile(BuildContext context, SettingsProvider provider) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final currentFont = provider.editorFont;
final fontName = l10n.fontName(currentFont.id);
final subtitle = currentFont.id == 'jetbrains_mono'
? '$fontName (${l10n.recommended})'
: fontName;
return ListTile(
leading: Icon(Icons.text_fields, color: theme.colorScheme.primary),
title: const Text('代码字体'),
subtitle: Text(currentFont.name),
title: Text(l10n.codeFont),
subtitle: Text(subtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showFontSelector(
context,
title: '选择代码字体',
title: l10n.selectCodeFont,
fonts: AppFonts.editorFonts,
currentId: provider.editorFontId,
previewSample: 'void main() { int a = 123; } // 代码预览',
previewSample: l10n.codeFontPreview,
showRecommendation: true,
onSelected: (id) => provider.setEditorFontId(id),
);
},
@@ -222,25 +242,108 @@ class SettingsView extends StatelessWidget {
/// 终端:终端字体条目
Widget _buildTerminalFontTile(BuildContext context, SettingsProvider provider) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final currentFont = provider.terminalFont;
final fontName = l10n.fontName(currentFont.id);
final subtitle = currentFont.id == 'jetbrains_mono'
? '$fontName (${l10n.recommended})'
: fontName;
return ListTile(
leading: Icon(Icons.terminal, color: theme.colorScheme.primary),
title: const Text('终端字体'),
subtitle: Text(currentFont.name),
leading: Icon(Icons.font_download_outlined, color: theme.colorScheme.primary),
title: Text(l10n.terminalFont),
subtitle: Text(subtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showFontSelector(
context,
title: '选择终端字体',
title: l10n.selectTerminalFont,
fonts: AppFonts.terminalFonts,
currentId: provider.terminalFontId,
previewSample: '\$ git status -s # 终端字体预览',
previewSample: l10n.terminalFontPreview,
showRecommendation: true,
onSelected: (id) => provider.setTerminalFontId(id),
);
},
);
}
/// 外观:主题颜色条目(点击弹出调色板)
Widget _buildThemeColorTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
final current = provider.appThemeColor;
return ListTile(
leading: Icon(Icons.palette_outlined, color: theme.colorScheme.primary),
title: Text(l10n.themeColor),
subtitle: Text(colorToHex(current)),
trailing: _buildColorTrailing(context, current),
onTap: () async {
final picked = await ColorPaletteDialog.show(
context,
title: l10n.selectThemeColor,
current: current,
palette: ColorPaletteDialog.uiPalette,
);
if (picked != null) {
await provider.setAppThemeColor(picked);
}
},
);
}
/// 终端:终端背景颜色条目(点击弹出调色板)
Widget _buildTerminalBackgroundTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
final current = provider.terminalBackgroundColor;
return ListTile(
leading: Icon(Icons.palette_outlined, color: theme.colorScheme.primary),
title: Text(l10n.terminalBackgroundColor),
subtitle: Text(colorToHex(current)),
trailing: _buildColorTrailing(context, current),
onTap: () async {
final picked = await ColorPaletteDialog.show(
context,
title: l10n.selectTerminalBackgroundColor,
current: current,
palette: ColorPaletteDialog.terminalPalette,
);
if (picked != null) {
await provider.setTerminalBackgroundColor(picked);
}
},
);
}
/// 颜色预览圆点 + 右箭头(与"代码高亮主题"条目的尾部样式一致)
Widget _buildColorTrailing(BuildContext context, Color color) {
final theme = Theme.of(context);
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 24,
height: 24,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(color: theme.colorScheme.outlineVariant, width: 1.5),
),
),
const SizedBox(width: 8),
const Icon(Icons.chevron_right),
],
);
}
/// 字体选择底部弹窗
void _showFontSelector(
BuildContext context, {
@@ -249,7 +352,9 @@ class SettingsView extends StatelessWidget {
required String currentId,
required ValueChanged<String> onSelected,
required String previewSample,
bool showRecommendation = false,
}) {
final l10n = AppLocalizations.of(context)!;
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
@@ -280,13 +385,17 @@ class SettingsView extends StatelessWidget {
itemBuilder: (context, index) {
final item = fonts[index];
final isSelected = item.id == currentId;
final isRecommended = showRecommendation && item.id == 'jetbrains_mono';
final fontTitle = isRecommended
? '${l10n.fontName(item.id)} (${l10n.recommended})'
: l10n.fontName(item.id);
return ListTile(
leading: Icon(
item.isMonospace ? Icons.code : Icons.font_download_outlined,
color: isSelected ? theme.colorScheme.primary : null,
),
title: Text(
item.name,
fontTitle,
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected ? theme.colorScheme.primary : null,
@@ -681,6 +790,50 @@ class SettingsView extends StatelessWidget {
/// 终端:终端小键盘开关条目(与编辑区开关相互独立)
Widget _buildTerminalVirtualKeyboardTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
return SwitchListTile(
secondary: Icon(Icons.keyboard_command_key, color: theme.colorScheme.primary),
title: Text(l10n.terminalVirtualKeyboard),
subtitle: Text(l10n.terminalVirtualKeyboardSubtitle),
value: provider.enableTerminalVirtualKeyboard,
onChanged: (val) => provider.setKeyboardEnabled(KeyboardScope.terminal, val),
);
}
/// 终端:终端键盘配置编辑条目
Widget _buildTerminalVirtualKeyboardConfigTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
final enabled = provider.enableTerminalVirtualKeyboard;
return ListTile(
enabled: enabled,
leading: Icon(Icons.tune, color: enabled ? theme.colorScheme.primary : theme.disabledColor),
title: Text(l10n.editTerminalVirtualKeyboardConfig),
subtitle: Text(l10n.editTerminalVirtualKeyboardConfigSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => const VirtualKeyboardConfigView(
scope: KeyboardScope.terminal,
),
),
);
},
);
}
/// 语言:应用语言选择条目
Widget _buildLanguageTile(
BuildContext context,
@@ -769,4 +922,22 @@ class SettingsView extends StatelessWidget {
},
);
}
/// 项目配置:显示隐藏文件开关
Widget _buildShowHiddenFilesTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
return SwitchListTile(
secondary: Icon(Icons.visibility_outlined, color: theme.colorScheme.primary),
title: Text(l10n.showHiddenFiles),
subtitle: Text(l10n.showHiddenFilesSubtitle),
value: provider.showHiddenFiles,
onChanged: (val) {
provider.setShowHiddenFiles(val);
},
);
}
}
+93 -19
View File
@@ -1,15 +1,22 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/terminal_session.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/project_provider.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/utils/terminal_theme_helper.dart';
import 'package:code_editor/widgets/distro_extract_dialog.dart';
import 'package:code_editor/widgets/distro_selector_dialog.dart';
import 'package:code_editor/widgets/terminal_drawer.dart';
import 'package:code_editor/widgets/terminal_keyboard_sink.dart';
import 'package:code_editor/widgets/terminal_modifier_state.dart';
import 'package:code_editor/widgets/virtual_keyboard_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xterm/xterm.dart' as xterm;
import 'package:xterm/xterm.dart' show TerminalInputHandler, defaultInputHandler;
/// 终端视图(支持多系统实例切换、全屏会话保持、右侧抽屉多会话管理与交互)
class TerminalView extends StatefulWidget {
@@ -84,15 +91,17 @@ class _TerminalViewState extends State<TerminalView> {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final provider = context.watch<TerminalProvider>();
final distroProvider = context.watch<DistroProvider?>();
final projectProvider = context.watch<ProjectProvider?>();
final activeSession = provider.activeSession;
final sessions = provider.sessions;
final activeIndex = provider.activeIndex;
final titleText = activeSession?.name ?? l10n.sessionDefaultName;
final currentSystem = activeSession?.distroId ?? distroProvider?.selectedSystem;
final subtitleText = currentSystem != null ? l10n.terminalWithSystem(currentSystem) : l10n.terminal;
final projectRoot = activeSession?.workspacePath ?? projectProvider?.rootPath;
final String? subtitleText = (projectRoot != null && projectRoot.trim().isNotEmpty)
? projectRoot.trim()
: null;
return Scaffold(
key: _scaffoldKey,
@@ -116,14 +125,15 @@ class _TerminalViewState extends State<TerminalView> {
),
overflow: TextOverflow.ellipsis,
),
Text(
subtitleText,
style: TextStyle(
fontSize: 11.0,
color: theme.colorScheme.onSurfaceVariant,
if (subtitleText != null)
Text(
subtitleText,
style: TextStyle(
fontSize: 11.0,
color: theme.colorScheme.onSurfaceVariant,
),
overflow: TextOverflow.ellipsis,
),
overflow: TextOverflow.ellipsis,
),
],
),
actions: [
@@ -180,6 +190,46 @@ class _TerminalSessionBody extends StatefulWidget {
}
class _TerminalSessionBodyState extends State<_TerminalSessionBody> {
/// 小键盘修饰键的运行时状态:键盘组件与终端共用同一份
late final TerminalModifierState _modifiers = TerminalModifierState();
/// 终端原有的输入处理器与输出出口(用于串联,而不是替换)
TerminalInputHandler? _delegateInputHandler;
void Function(String)? _delegateOnOutput;
@override
void initState() {
super.initState();
final terminal = widget.session.terminal;
// ① 按键事件(硬件键盘、小键盘 key 格)都会经过 inputHandler:
// 把运行时修饰键叠加进事件,再交给 xterm 默认链路。
_delegateInputHandler = terminal.inputHandler;
terminal.inputHandler = ModifierAwareInputHandler(
state: _modifiers,
delegate: _delegateInputHandler ?? defaultInputHandler,
);
// ② 软键盘 / IME 打进来的字符不产生 KeyEvent,只能在这里改写。
_delegateOnOutput = terminal.onOutput;
terminal.onOutput = (data) {
final transformed = applyModifierToTypedText(data, _modifiers.mods);
_delegateOnOutput?.call(transformed ?? data);
if (transformed != null) _modifiers.consume();
};
}
@override
void dispose() {
final terminal = widget.session.terminal;
if (terminal.inputHandler is ModifierAwareInputHandler) {
terminal.inputHandler = _delegateInputHandler;
}
terminal.onOutput = _delegateOnOutput;
_modifiers.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final session = widget.session;
@@ -192,18 +242,42 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> {
fontFamilyFallback: terminalFont.fallback,
);
// 终端小键盘:开关与配置均独立于编辑区
final keyboardEnabled = settings?.keyboardEnabledFor(KeyboardScope.terminal) ?? false;
final keyboardConfig = settings?.keyboardConfigFor(KeyboardScope.terminal);
// 终端背景颜色(设置项):容器与 xterm 主题保持一致
final backgroundColor = settings?.terminalBackgroundColor ?? const Color(0xFF1E1E1E);
return Container(
color: const Color(0xFF181818),
color: backgroundColor,
child: SafeArea(
top: false,
child: xterm.TerminalView(
session.terminal,
focusNode: session.focusNode,
autofocus: true,
theme: xterm.TerminalThemes.defaultTheme,
textStyle: terminalStyle,
cursorType: xterm.TerminalCursorType.block,
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
child: Column(
children: [
Expanded(
child: xterm.TerminalView(
session.terminal,
focusNode: session.focusNode,
autofocus: true,
theme: terminalThemeWithBackground(backgroundColor),
textStyle: terminalStyle,
cursorType: xterm.TerminalCursorType.block,
padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
),
),
if (keyboardEnabled && keyboardConfig != null && keyboardConfig.hasKeys)
VirtualKeyboardWidget(
controller: null,
focusNode: session.focusNode,
sink: TerminalKeyboardSink(
terminal: session.terminal,
focusNode: session.focusNode,
),
modifierState: _modifiers,
config: keyboardConfig,
),
],
),
),
);
+27 -20
View File
@@ -43,7 +43,7 @@ class _VirtualKeyboardConfigViewState extends State<VirtualKeyboardConfigView> {
void initState() {
super.initState();
final settingsProvider = context.read<SettingsProvider>();
_config = settingsProvider.virtualKeyboardConfig;
_config = settingsProvider.keyboardConfigFor(widget.scope);
if (_currentPageIndex >= _config.pages.length) {
_currentPageIndex = 0;
}
@@ -77,12 +77,12 @@ class _VirtualKeyboardConfigViewState extends State<VirtualKeyboardConfigView> {
});
}
/// 保存并同步到 SettingsProvider
/// 保存并同步到 SettingsProvider(按作用域写入对应的那份配置)
Future<void> _syncAndSaveConfig() async {
final settingsProvider = context.read<SettingsProvider>();
const encoder = JsonEncoder.withIndent(' ');
final jsonStr = encoder.convert(_config.toJson());
await settingsProvider.setVirtualKeyboardConfig(jsonStr);
await settingsProvider.setKeyboardConfig(widget.scope, jsonStr);
}
/// 恢复默认配置
@@ -109,10 +109,10 @@ class _VirtualKeyboardConfigViewState extends State<VirtualKeyboardConfigView> {
if (confirmed == true) {
if (!mounted) return;
final settingsProvider = context.read<SettingsProvider>();
await settingsProvider.resetVirtualKeyboardConfig();
await settingsProvider.resetKeyboardConfig(widget.scope);
if (!mounted) return;
setState(() {
_config = settingsProvider.virtualKeyboardConfig;
_config = settingsProvider.keyboardConfigFor(widget.scope);
_currentPageIndex = 0;
_expandedRowsByPage.clear();
_scrollOffsetByPage.clear();
@@ -132,13 +132,10 @@ class _VirtualKeyboardConfigViewState extends State<VirtualKeyboardConfigView> {
}
setState(() {
// 新建页面默认为空,不自动新增按键行,由用户手动添加
final newPage = KeyboardPageItem(
count: 7,
keys: [
[
const KeyboardKeyItem(label: 'New', value: 'New'),
],
],
keys: const [],
);
final newPages = List<KeyboardPageItem>.from(_config.pages)..add(newPage);
_config = _config.copyWith(pages: newPages);
@@ -471,10 +468,14 @@ class _VirtualKeyboardConfigViewState extends State<VirtualKeyboardConfigView> {
children: [
Text(
l10n.virtualKeyboardConfigTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
Text(
subtitleText,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurface.withValues(alpha: 0.65),
@@ -531,17 +532,23 @@ class _VirtualKeyboardConfigViewState extends State<VirtualKeyboardConfigView> {
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),
),
],
// 左侧标题需可收缩,右侧“添加新行”按钮才不会把标题挤出右边界
Expanded(
child: Row(
children: [
Icon(Icons.keyboard_alt_outlined, size: 20, color: theme.colorScheme.primary),
const SizedBox(width: 8),
Flexible(
child: Text(
l10n.keyboardPageKeysSectionTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
],
),
),
TextButton.icon(
icon: const Icon(Icons.add, size: 18),
+97 -28
View File
@@ -12,10 +12,14 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
final VoidCallback? onSave;
final VoidCallback? onSaveAll;
final VoidCallback? onRun;
final VoidCallback? onRunTasks;
final VoidCallback? onTerminal;
final VoidCallback? onCloseAllTabs;
final VoidCallback? onCloseProject;
final VoidCallback? onSettings;
final VoidCallback? onProjectDetect;
final VoidCallback? onEditRunTasks;
final bool isDetecting;
const CodeEditorAppBar({
super.key,
@@ -25,10 +29,14 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
this.onSave,
this.onSaveAll,
this.onRun,
this.onRunTasks,
this.onTerminal,
this.onCloseAllTabs,
this.onCloseProject,
this.onSettings,
this.onProjectDetect,
this.onEditRunTasks,
this.isDetecting = false,
});
@override
@@ -121,28 +129,23 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
onPressed: onSave ?? () {},
),
),
Focus(
canRequestFocus: false,
skipTraversal: true,
child: IconButton(
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.terminal),
tooltip: '终端',
onPressed: onTerminal ??
() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => const TerminalView(),
),
);
},
),
),
_MoreMenuButton(
onSaveAll: onSaveAll,
onRunTasks: onRunTasks,
onTerminal: onTerminal ??
() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => const TerminalView(),
),
);
},
onProjectDetect: onProjectDetect,
onEditRunTasks: onEditRunTasks,
onCloseAllTabs: onCloseAllTabs,
onCloseProject: onCloseProject,
onSettings: onSettings,
isDetecting: isDetecting,
),
],
),
@@ -153,15 +156,25 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
/// 基于 OverlayEntry 的右上角更多菜单组件(带对齐右上角缩放淡入淡出动画,非模态不关闭键盘)
class _MoreMenuButton extends StatefulWidget {
final VoidCallback? onSaveAll;
final VoidCallback? onRunTasks;
final VoidCallback? onTerminal;
final VoidCallback? onProjectDetect;
final VoidCallback? onEditRunTasks;
final VoidCallback? onCloseAllTabs;
final VoidCallback? onCloseProject;
final VoidCallback? onSettings;
final bool isDetecting;
const _MoreMenuButton({
this.onSaveAll,
this.onRunTasks,
this.onTerminal,
this.onProjectDetect,
this.onEditRunTasks,
this.onCloseAllTabs,
this.onCloseProject,
this.onSettings,
this.isDetecting = false,
});
@override
@@ -280,12 +293,14 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
),
clipBehavior: Clip.antiAlias,
child: Container(
width: 170,
// 菜单宽度随系统字号放大,避免大字号下文案被截断(上限避免超出窄屏)
width: (170.0 * MediaQuery.textScalerOf(context).scale(1.0)).clamp(170.0, 280.0),
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// 分组 1: 保存所有,运行任务,终端
_buildMenuItem(
icon: Icons.save_as_outlined,
title: l10n.saveAll,
@@ -295,11 +310,19 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
},
),
_buildMenuItem(
icon: Icons.close_fullscreen_outlined,
title: l10n.closeAllTabs,
icon: Icons.playlist_play,
title: l10n.runTasks,
iconColor: onSurfaceColor,
onTap: () {
_closeMenu(onClosed: widget.onCloseAllTabs);
_closeMenu(onClosed: widget.onRunTasks);
},
),
_buildMenuItem(
icon: Icons.terminal,
title: l10n.terminal,
iconColor: onSurfaceColor,
onTap: () {
_closeMenu(onClosed: widget.onTerminal);
},
),
Divider(
@@ -307,6 +330,39 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
thickness: 0.8,
color: theme.colorScheme.outlineVariant,
),
// 分组 2: 项目探测,运行任务编辑
_buildMenuItem(
icon: widget.isDetecting ? Icons.hourglass_top : Icons.radar_outlined,
title: widget.isDetecting ? l10n.projectDetecting : l10n.projectDetect,
iconColor: onSurfaceColor,
enabled: !widget.isDetecting,
onTap: () {
if (widget.isDetecting) return;
_closeMenu(onClosed: widget.onProjectDetect);
},
),
_buildMenuItem(
icon: Icons.tune_outlined,
title: l10n.editRunTasks,
iconColor: onSurfaceColor,
onTap: () {
_closeMenu(onClosed: widget.onEditRunTasks);
},
),
Divider(
height: 9,
thickness: 0.8,
color: theme.colorScheme.outlineVariant,
),
// 分组 3: 关闭所有标签,关闭当前项目
_buildMenuItem(
icon: Icons.close_fullscreen_outlined,
title: l10n.closeAllTabs,
iconColor: onSurfaceColor,
onTap: () {
_closeMenu(onClosed: widget.onCloseAllTabs);
},
),
_buildMenuItem(
icon: Icons.folder_off_outlined,
title: l10n.closeProject,
@@ -320,6 +376,7 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
thickness: 0.8,
color: theme.colorScheme.outlineVariant,
),
// 分组 4: 设置
_buildMenuItem(
icon: Icons.settings,
title: l10n.settings,
@@ -348,10 +405,18 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
required Color iconColor,
required VoidCallback onTap,
bool isDestructive = false,
bool enabled = true,
}) {
final theme = Theme.of(context);
final effectiveColor = enabled
? (isDestructive ? theme.colorScheme.error : iconColor)
: theme.colorScheme.outline.withValues(alpha: 0.5);
final effectiveTextColor = enabled
? (isDestructive ? theme.colorScheme.error : theme.colorScheme.onSurface)
: theme.colorScheme.outline.withValues(alpha: 0.5);
return InkWell(
onTap: onTap,
onTap: enabled ? onTap : null,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
child: Row(
@@ -360,14 +425,18 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
Icon(
icon,
size: 18,
color: isDestructive ? theme.colorScheme.error : iconColor,
color: effectiveColor,
),
const SizedBox(width: 10),
Text(
title,
style: TextStyle(
fontSize: 14.0,
color: isDestructive ? theme.colorScheme.error : theme.colorScheme.onSurface,
Flexible(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14.0,
color: effectiveTextColor,
),
),
),
],
+91 -3
View File
@@ -1,3 +1,4 @@
import 'dart:math';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -17,7 +18,14 @@ class _EditorContextMenuItem extends PopupMenuItem<void> implements PreferredSiz
children: [
Icon(icon, size: 16),
const SizedBox(width: 8),
Text(text, style: const TextStyle(fontSize: 13)),
Flexible(
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13),
),
),
],
),
);
@@ -71,8 +79,34 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
widget.controller.selection.extentOffset != -1 &&
!widget.controller.selection.isCollapsed;
final mediaQuery = MediaQuery.of(context);
final availableBottom = mediaQuery.size.height - mediaQuery.viewInsets.bottom;
TextSelectionToolbarAnchors effectiveAnchors = widget.anchors;
final primary = effectiveAnchors.primaryAnchor;
final secondary = effectiveAnchors.secondaryAnchor;
// 针对虚拟键盘或底栏的全局安全高度校准:
if (secondary != null && secondary.dy + 65.0 > availableBottom) {
effectiveAnchors = TextSelectionToolbarAnchors(
primaryAnchor: Offset(
secondary.dx.clamp(120.0, max(120.0, mediaQuery.size.width - 120.0)),
(availableBottom - 12.0).clamp(mediaQuery.padding.top + 48.0, availableBottom),
),
secondaryAnchor: null,
);
} else if (primary.dy + 60.0 > availableBottom && primary.dx >= 0) {
effectiveAnchors = TextSelectionToolbarAnchors(
primaryAnchor: Offset(
primary.dx.clamp(120.0, max(120.0, mediaQuery.size.width - 120.0)),
(availableBottom - 12.0).clamp(mediaQuery.padding.top + 48.0, availableBottom),
),
secondaryAnchor: null,
);
}
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: widget.anchors,
anchors: effectiveAnchors,
buttonItems: [
if (hasSelection)
ContextMenuButtonItem(
@@ -164,10 +198,11 @@ class CodeEditorToolbarController implements SelectionToolbarController {
anchors: anchors,
);
} else {
final safeAnchors = _sanitizeMobileAnchors(anchors, renderRect);
_mobileController.show(
context: context,
controller: controller,
anchors: anchors,
anchors: safeAnchors,
renderRect: renderRect,
layerLink: layerLink,
visibility: visibility,
@@ -175,6 +210,59 @@ class CodeEditorToolbarController implements SelectionToolbarController {
}
}
/// 智能校准移动端选区工具栏锚点:
/// 1. 优先展示在选区上方(primaryAnchor),避免遮挡当前选中的代码内容及下方代码;
/// 2. 当选区位于视口顶部(上方空间不足 54px 时),智能翻转至选区下方(secondaryAnchor);
/// 3. 当选区靠近视口底部或键盘时,保护次锚点不落入键盘/底栏区域,坚决保持在上方;
/// 4. 水平坐标智能居中并进行安全边缘约束(左右各留出 120px 缓冲),防止菜单按钮溢出屏幕。
static TextSelectionToolbarAnchors _sanitizeMobileAnchors(
TextSelectionToolbarAnchors anchors,
Rect renderRect,
) {
final primary = anchors.primaryAnchor;
final secondary = anchors.secondaryAnchor;
// 确定水平基准坐标并进行安全边距夹取(左右两端预留充足空间以保证多个操作按钮完整可见)
final double rawX = (primary.dx > 0) ? primary.dx : (secondary?.dx ?? renderRect.center.dx);
final double safeX = (renderRect.width > 240.0)
? rawX.clamp(renderRect.left + 120.0, renderRect.right - 120.0)
: renderRect.center.dx;
// 计算选区上方与下方的垂直可用净空间
final double topY = (primary.dy > 0) ? primary.dy : (secondary?.dy ?? renderRect.top + 60.0);
final double bottomY = (secondary != null && secondary.dy > 0) ? secondary.dy : (topY + 30.0);
final double spaceAbove = topY - renderRect.top;
final double spaceBelow = renderRect.bottom - bottomY;
// 规则 1:选区上方空间充足(>= 54.0px,足够容纳工具栏),置于选区上方!
// 选区本身与下方的代码行将保持 100% 清晰可见,绝不遮挡。
if (spaceAbove >= 54.0) {
return TextSelectionToolbarAnchors(
primaryAnchor: Offset(safeX, topY),
secondaryAnchor: spaceBelow >= 64.0 ? Offset(safeX, bottomY) : null,
);
}
// 规则 2:选区位于第一行/第二行(上方空间不足 54px),但下方空间充足(>= 64px)
// 智能翻转至选区下方,保证不超出屏幕顶部也不遮挡第一行
if (spaceBelow >= 64.0) {
return TextSelectionToolbarAnchors(
primaryAnchor: const Offset(-10000, -10000),
secondaryAnchor: Offset(safeX, bottomY),
);
}
// 规则 3:选区跨越很大或上下空间均受限时,安全悬浮于可视区域上边缘内侧
return TextSelectionToolbarAnchors(
primaryAnchor: Offset(
safeX,
(renderRect.top + 56.0).clamp(renderRect.top + 10.0, renderRect.bottom - 10.0),
),
secondaryAnchor: null,
);
}
Future<void> _showDesktopMenu({
required BuildContext context,
required CodeLineEditingController controller,
+15 -17
View File
@@ -82,7 +82,8 @@ class CodeEditorTabBar extends StatelessWidget {
builder: (context, constraints) {
final totalWidth = constraints.maxWidth;
final tabCount = tabs.length;
final equalShare = math.max(28.0, totalWidth / tabCount);
// 下限需容纳内边距(8) + 关闭按钮(18) + 脏标记(10),否则标签内 Row 会右溢出
final equalShare = math.max(40.0, totalWidth / tabCount);
return Theme(
data: theme.copyWith(
@@ -178,26 +179,21 @@ class CodeEditorTabBar extends StatelessWidget {
child: Row(
children: [
Expanded(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (tab.isModified)
Padding(
padding: const EdgeInsets.only(right: 2.0),
child: Text(
'*',
// 脏标记并入同一个 Text.rich,避免它在极窄标签里单独撑破 Row
child: Text.rich(
TextSpan(
children: [
if (tab.isModified)
TextSpan(
text: '*',
style: TextStyle(
color: theme.colorScheme.error,
fontWeight: FontWeight.bold,
fontSize: 12.0,
),
),
),
Flexible(
child: Text(
displayName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
TextSpan(
text: displayName,
style: TextStyle(
fontSize: 12.0,
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
@@ -206,8 +202,10 @@ class CodeEditorTabBar extends StatelessWidget {
: theme.colorScheme.onSurfaceVariant,
),
),
),
],
],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
InkResponse(
+2
View File
@@ -459,6 +459,8 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
scrollController: _scrollController,
wordWrap: activeWordWrap,
toolbarController: _toolbarController,
margin: const EdgeInsets.only(left: 2.0, top: 4.0, right: 8, bottom: 8.0),
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
style: CodeEditorStyle(
fontSize: displayFontSize,
textColor: activeTheme.textColor,
+470
View File
@@ -0,0 +1,470 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
/// 颜色 → `#RRGGBB` 文本(用于工具提示与设置项副标题)
String colorToHex(Color color) {
final argb = color.toARGB32();
final rgb = argb & 0xFFFFFF;
return '#${rgb.toRadixString(16).padLeft(6, '0').toUpperCase()}';
}
/// 通用交互式调色板弹窗:
///
/// 包含 HSV 2D 饱和度/明度调色区、色相滑条、HEX 十六进制编辑、
/// 当前/新色对比预览,以及经典预设色板。
class ColorPaletteDialog extends StatefulWidget {
const ColorPaletteDialog({
super.key,
required this.title,
required this.current,
required this.palette,
});
final String title;
final Color current;
final List<Color> palette;
/// 界面主题色板:Material 主色 + 中性色
static const List<Color> uiPalette = [
Color(0xFFF44336),
Color(0xFFE91E63),
Color(0xFF9C27B0),
Color(0xFF673AB7),
Color(0xFF3F51B5),
Color(0xFF2196F3),
Color(0xFF03A9F4),
Color(0xFF00BCD4),
Color(0xFF009688),
Color(0xFF4CAF50),
Color(0xFF8BC34A),
Color(0xFFCDDC39),
Color(0xFFFFEB3B),
Color(0xFFFFC107),
Color(0xFFFF9800),
Color(0xFFFF5722),
Color(0xFF795548),
Color(0xFF607D8B),
Color(0xFF9E9E9E),
Color(0xFF000000),
];
/// 终端背景色板:常用深色配色 + 少量浅色
static const List<Color> terminalPalette = [
Color(0xFF000000),
Color(0xFF0D1117),
Color(0xFF101418),
Color(0xFF181818),
Color(0xFF1E1E1E),
Color(0xFF1E1E2E),
Color(0xFF212121),
Color(0xFF263238),
Color(0xFF282C34),
Color(0xFF2B2B2B),
Color(0xFF2D2D30),
Color(0xFF303030),
Color(0xFF1B2B34),
Color(0xFF002B36),
Color(0xFF073642),
Color(0xFF3C3836),
Color(0xFFF5F5F5),
Color(0xFFFFFFFF),
];
static Future<Color?> show(
BuildContext context, {
required String title,
required Color current,
required List<Color> palette,
}) {
return showDialog<Color>(
context: context,
builder: (_) => ColorPaletteDialog(
title: title,
current: current,
palette: palette,
),
);
}
@override
State<ColorPaletteDialog> createState() => _ColorPaletteDialogState();
}
class _ColorPaletteDialogState extends State<ColorPaletteDialog> {
late double _hue;
late double _saturation;
late double _value;
late Color _currentColor;
late TextEditingController _hexController;
bool _isInternalHexUpdate = false;
@override
void initState() {
super.initState();
_currentColor = widget.current;
final hsv = HSVColor.fromColor(widget.current);
_hue = hsv.hue;
_saturation = hsv.saturation;
_value = hsv.value;
_hexController = TextEditingController(text: colorToHex(widget.current));
}
@override
void dispose() {
_hexController.dispose();
super.dispose();
}
void _updateColor(Color color, {bool updateHex = true}) {
final hsv = HSVColor.fromColor(color);
setState(() {
_currentColor = color;
if (hsv.saturation > 0 || color.toARGB32() != Colors.black.toARGB32()) {
_hue = hsv.hue;
}
_saturation = hsv.saturation;
_value = hsv.value;
if (updateHex) {
_isInternalHexUpdate = true;
_hexController.text = colorToHex(color);
_isInternalHexUpdate = false;
}
});
}
void _onHexChanged(String text) {
if (_isInternalHexUpdate) return;
String clean = text.trim();
if (clean.startsWith('#')) clean = clean.substring(1);
if (clean.length == 6) {
final val = int.tryParse(clean, radix: 16);
if (val != null) {
final color = Color(0xFF000000 | val);
final hsv = HSVColor.fromColor(color);
setState(() {
_currentColor = color;
if (hsv.saturation > 0 || color.toARGB32() != Colors.black.toARGB32()) {
_hue = hsv.hue;
}
_saturation = hsv.saturation;
_value = hsv.value;
});
}
}
}
void _onSvPan(Offset localPosition, double width, double height) {
final s = (localPosition.dx / width).clamp(0.0, 1.0);
final v = (1.0 - (localPosition.dy / height)).clamp(0.0, 1.0);
setState(() {
_saturation = s;
_value = v;
_currentColor = HSVColor.fromAHSV(1.0, _hue, _saturation, _value).toColor();
_isInternalHexUpdate = true;
_hexController.text = colorToHex(_currentColor);
_isInternalHexUpdate = false;
});
}
void _onHuePan(Offset localPosition, double width) {
final h = (localPosition.dx / width * 360.0).clamp(0.0, 360.0);
setState(() {
_hue = h == 360.0 ? 0.0 : h;
_currentColor = HSVColor.fromAHSV(1.0, _hue, _saturation, _value).toColor();
_isInternalHexUpdate = true;
_hexController.text = colorToHex(_currentColor);
_isInternalHexUpdate = false;
});
}
Widget _buildSaturationValuePicker(double width, double height) {
return GestureDetector(
onPanDown: (details) => _onSvPan(details.localPosition, width, height),
onPanUpdate: (details) => _onSvPan(details.localPosition, width, height),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: SizedBox(
width: width,
height: height,
child: Stack(
children: [
// 色相底层
Container(
color: HSVColor.fromAHSV(1.0, _hue, 1.0, 1.0).toColor(),
),
// 水平渐变(白色 -> 透明)
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Colors.white, Color(0x00FFFFFF)],
),
),
),
// 垂直渐变(透明 -> 黑色)
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black],
),
),
),
// 取色定位圆环指示器
Positioned(
left: (_saturation * width - 10).clamp(-10.0, width - 10.0),
top: ((1.0 - _value) * height - 10).clamp(-10.0, height - 10.0),
child: IgnorePointer(
child: Container(
width: 20,
height: 20,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2.5),
boxShadow: const [
BoxShadow(
color: Colors.black45,
blurRadius: 4,
offset: Offset(0, 1),
),
],
),
),
),
),
],
),
),
),
);
}
Widget _buildHueSlider(double width) {
const double sliderHeight = 22.0;
return GestureDetector(
onPanDown: (details) => _onHuePan(details.localPosition, width),
onPanUpdate: (details) => _onHuePan(details.localPosition, width),
child: ClipRRect(
borderRadius: BorderRadius.circular(sliderHeight / 2),
child: SizedBox(
width: width,
height: sliderHeight,
child: Stack(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(sliderHeight / 2),
gradient: const LinearGradient(
colors: [
Color(0xFFFF0000),
Color(0xFFFFFF00),
Color(0xFF00FF00),
Color(0xFF00FFFF),
Color(0xFF0000FF),
Color(0xFFFF00FF),
Color(0xFFFF0000),
],
),
),
),
Positioned(
left: ((_hue / 360.0) * width - 10).clamp(-10.0, width - 10.0),
top: 1,
child: IgnorePointer(
child: Container(
width: 20,
height: sliderHeight - 2,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2.5),
boxShadow: const [
BoxShadow(
color: Colors.black45,
blurRadius: 3,
offset: Offset(0, 1),
),
],
),
),
),
),
],
),
),
),
);
}
Widget _buildPreviewAndHex(BuildContext context, AppLocalizations l10n) {
final theme = Theme.of(context);
return Row(
children: [
// 初始颜色(点击可快速重置回原色)
Tooltip(
message: '${l10n.currentColor}: ${colorToHex(widget.current)}',
child: InkWell(
onTap: () => _updateColor(widget.current),
borderRadius: BorderRadius.circular(8),
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: widget.current,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
),
),
),
const SizedBox(width: 8),
Icon(Icons.arrow_forward, size: 18, color: theme.colorScheme.outline),
const SizedBox(width: 8),
// 调色后的实时新色预览
Tooltip(
message: '${l10n.newColor}: ${colorToHex(_currentColor)}',
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: _currentColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: theme.colorScheme.primary,
width: 2,
),
boxShadow: [
BoxShadow(
color: _currentColor.withValues(alpha: 0.35),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
),
),
const Spacer(),
// HEX 颜色输入框
SizedBox(
width: 120,
height: 42,
child: TextField(
controller: _hexController,
onChanged: _onHexChanged,
style: const TextStyle(
fontFamily: 'monospace',
fontWeight: FontWeight.bold,
fontSize: 14,
),
decoration: InputDecoration(
isDense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
labelText: l10n.hexColor,
counterText: '',
),
maxLength: 7,
),
),
],
);
}
Widget _buildPresets(BuildContext context, AppLocalizations l10n) {
final theme = Theme.of(context);
final currentRgb = _currentColor.toARGB32() & 0xFFFFFF;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.presetColors,
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (final color in widget.palette)
Tooltip(
message: colorToHex(color),
child: InkWell(
key: ValueKey<int>(color.toARGB32()),
borderRadius: BorderRadius.circular(14),
onTap: () => _updateColor(color),
child: Container(
width: 28,
height: 28,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(
color: (color.toARGB32() & 0xFFFFFF) == currentRgb
? theme.colorScheme.primary
: theme.colorScheme.outlineVariant,
width: (color.toARGB32() & 0xFFFFFF) == currentRgb ? 2.5 : 1,
),
),
child: (color.toARGB32() & 0xFFFFFF) == currentRgb
? Icon(
Icons.check,
size: 16,
color: color.computeLuminance() > 0.5
? Colors.black87
: Colors.white,
)
: null,
),
),
),
],
),
],
);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return AlertDialog(
title: Text(widget.title),
content: SizedBox(
width: 280,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildSaturationValuePicker(280, 130),
const SizedBox(height: 12),
_buildHueSlider(280),
const SizedBox(height: 12),
_buildPreviewAndHex(context, l10n),
const SizedBox(height: 12),
const Divider(height: 1),
const SizedBox(height: 10),
_buildPresets(context, l10n),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(_currentColor),
child: Text(l10n.confirm),
),
],
);
}
}
+14 -2
View File
@@ -60,7 +60,13 @@ class DistroSelectorDialog extends StatelessWidget {
children: [
const Icon(Icons.layers_outlined, size: 18),
const SizedBox(width: 8),
Text(l10n.importBuiltinAlpine),
Flexible(
child: Text(
l10n.importBuiltinAlpine,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
@@ -70,7 +76,13 @@ class DistroSelectorDialog extends StatelessWidget {
children: [
const Icon(Icons.folder_open_outlined, size: 18),
const SizedBox(width: 8),
Text(l10n.importExternalTarGz),
Flexible(
child: Text(
l10n.importExternalTarGz,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
+9 -5
View File
@@ -289,11 +289,15 @@ class _FileItemWidgetState extends State<FileItemWidget> {
children: [
Icon(icon, size: 18, color: iconColor),
const SizedBox(width: 8),
Text(
title,
style: isDestructive
? TextStyle(color: theme.colorScheme.error)
: TextStyle(color: theme.colorScheme.onSurface),
Flexible(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: isDestructive
? TextStyle(color: theme.colorScheme.error)
: TextStyle(color: theme.colorScheme.onSurface),
),
),
],
),
+262
View File
@@ -0,0 +1,262 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import '../models/run_task.dart';
/// 运行任务选择弹窗(带顶部搜索栏、区分系统探测与自定义任务,点击直接调度执行)
class RunTasksDialog extends StatefulWidget {
final List<RunTask> customTasks;
final List<RunTask> detectedTasks;
final String? lastRunTaskId;
final ValueChanged<RunTask> onTaskSelected;
final VoidCallback onEditCustomTasks;
const RunTasksDialog({
super.key,
required this.customTasks,
required this.detectedTasks,
this.lastRunTaskId,
required this.onTaskSelected,
required this.onEditCustomTasks,
});
static Future<void> show({
required BuildContext context,
required List<RunTask> customTasks,
required List<RunTask> detectedTasks,
String? lastRunTaskId,
required ValueChanged<RunTask> onTaskSelected,
required VoidCallback onEditCustomTasks,
}) {
return showDialog<void>(
context: context,
builder: (ctx) => RunTasksDialog(
customTasks: customTasks,
detectedTasks: detectedTasks,
lastRunTaskId: lastRunTaskId,
onTaskSelected: onTaskSelected,
onEditCustomTasks: onEditCustomTasks,
),
);
}
@override
State<RunTasksDialog> createState() => _RunTasksDialogState();
}
class _RunTasksDialogState extends State<RunTasksDialog> {
final TextEditingController _searchController = TextEditingController();
String _searchQuery = '';
@override
void initState() {
super.initState();
_searchController.addListener(() {
setState(() {
_searchQuery = _searchController.text.trim().toLowerCase();
});
});
}
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
bool _matchesQuery(RunTask task) {
if (_searchQuery.isEmpty) return true;
return task.name.toLowerCase().contains(_searchQuery) ||
task.command.toLowerCase().contains(_searchQuery) ||
(task.description?.toLowerCase().contains(_searchQuery) ?? false);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final filteredCustom = widget.customTasks.where(_matchesQuery).toList();
final filteredDetected = widget.detectedTasks.where(_matchesQuery).toList();
final hasAny = filteredCustom.isNotEmpty || filteredDetected.isNotEmpty;
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560, maxHeight: 620),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// 标题栏:简洁标题 + 编辑按钮 + 关闭 X
Row(
children: [
Expanded(
child: Text(
l10n.runTasks,
style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
IconButton(
icon: const Icon(Icons.tune_outlined),
tooltip: l10n.editCustomTasksTooltip,
onPressed: () {
Navigator.of(context).pop();
widget.onEditCustomTasks();
},
),
IconButton(
icon: const Icon(Icons.close),
tooltip: l10n.close,
onPressed: () => Navigator.of(context).pop(),
),
],
),
const SizedBox(height: 12),
// 搜索输入框
TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: l10n.searchTasksHint,
prefixIcon: const Icon(Icons.search),
suffixIcon: _searchQuery.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear, size: 18),
onPressed: () => _searchController.clear(),
)
: null,
isDense: true,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
),
),
const SizedBox(height: 12),
// 任务展示列表
Expanded(
child: !hasAny
? Center(
child: Text(
_searchQuery.isEmpty ? l10n.noTasksAvailable : l10n.noMatchingTasks,
style: theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.outline),
),
)
: ListView(
children: [
if (filteredDetected.isNotEmpty) ...[
_buildSectionHeader(context, l10n.systemDetectedTasks, Icons.radar_outlined),
...filteredDetected.map((task) => _buildTaskItem(context, task)),
const SizedBox(height: 8),
],
if (filteredCustom.isNotEmpty) ...[
_buildSectionHeader(context, l10n.userCustomTasks, Icons.person_outline),
...filteredCustom.map((task) => _buildTaskItem(context, task)),
],
],
),
),
],
),
),
),
);
}
Widget _buildSectionHeader(BuildContext context, String title, IconData icon) {
final theme = Theme.of(context);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 4),
child: Row(
children: [
Icon(icon, size: 16, color: theme.colorScheme.primary),
const SizedBox(width: 6),
Text(
title,
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
],
),
);
}
Widget _buildTaskItem(BuildContext context, RunTask task) {
final theme = Theme.of(context);
final isLastRun = widget.lastRunTaskId != null && widget.lastRunTaskId == task.id;
final cardColor = isLastRun
? Colors.green.withValues(alpha: 0.15)
: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.4);
final borderColor = isLastRun
? Colors.green.withValues(alpha: 0.8)
: theme.colorScheme.outlineVariant.withValues(alpha: 0.5);
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
elevation: 0,
color: cardColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(color: borderColor, width: isLastRun ? 1.5 : 1.0),
),
child: ListTile(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
dense: true,
title: Row(
children: [
Expanded(
child: Text(
task.name,
style: TextStyle(
fontWeight: FontWeight.w600,
color: isLastRun ? Colors.green.shade700 : null,
),
),
),
if (isLastRun)
Container(
margin: const EdgeInsets.only(left: 6),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(4),
),
child: Icon(
Icons.history,
size: 14,
color: Colors.green.shade700,
),
),
],
),
subtitle: (task.description != null && task.description!.trim().isNotEmpty)
? Text(
task.description!.trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurfaceVariant,
),
)
: null,
trailing: CircleAvatar(
radius: 16,
backgroundColor: isLastRun
? Colors.green.withValues(alpha: 0.25)
: theme.colorScheme.primaryContainer,
foregroundColor: isLastRun ? Colors.green : theme.colorScheme.onPrimaryContainer,
child: const Icon(Icons.play_arrow, size: 20),
),
onTap: () {
Navigator.of(context).pop();
widget.onTaskSelected(task);
},
),
);
}
}
+7 -2
View File
@@ -1,5 +1,6 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/project_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/widgets/terminal_session_item_widget.dart';
@@ -60,12 +61,16 @@ class TerminalDrawer extends StatelessWidget {
DialogUtils.showToast(context, l10n.noSystemSelectedWarning);
return;
}
// 基于当前选择的系统创建新终端
// 基于当前选择的系统创建新终端并直接激活进入
final projectRoot = context.read<ProjectProvider?>()?.rootPath;
provider.createSession(
name: l10n.sessionDefaultName,
distroId: currentSystem,
activate: false,
workspacePath: projectRoot,
activate: true,
);
// 自动关闭右侧抽屉,直接进入新创建的会话
Navigator.of(context).maybePop();
},
),
],
+112
View File
@@ -0,0 +1,112 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import '../models/virtual_keyboard_config.dart';
import 'virtual_keyboard_sink.dart';
/// 解析 xterm 的 [TerminalKey] 枚举名,失败返回 null。
///
/// 模型层只保存字符串名(不依赖 xterm),由这里完成到枚举的映射,
/// 名称的合法性在保存配置时已由 [KeyboardScopeHelper.isSupportedTerminalKey] 校验。
TerminalKey? resolveTerminalKey(String name) {
for (final key in TerminalKey.values) {
if (key.name == name) return key;
}
return null;
}
/// 终端实现:把按键语义写入 xterm 终端。
///
/// 所有输入都经 `Terminal.onOutput`,在 `TerminalSession` 中该回调被接到
/// PTY,因此这里等价于用户真按了键盘。
/// 注意不要用 `TerminalSession.write()`——那是往屏幕缓冲区写显示内容。
class TerminalKeyboardSink implements VirtualKeyboardSink {
final Terminal terminal;
final FocusNode? focusNode;
TerminalKeyboardSink({required this.terminal, this.focusNode});
@override
void sendText(String text, {bool appendEnter = false}) {
if (text.isEmpty && !appendEnter) return;
var payload = text;
// 避免用户已在 value 里写了换行时再补一个,造成双回车
if (appendEnter && !payload.endsWith('\r') && !payload.endsWith('\n')) {
payload = '$payload\r';
}
if (payload.isEmpty) return;
// 多字符或含换行时走 paste:会遵循 bracketed paste mode,更安全
if (payload.length > 1 || payload.contains('\n') || payload.contains('\r')) {
terminal.paste(payload);
} else {
terminal.textInput(payload);
}
}
@override
void sendPair(String pairText, int cursorOffset) {
// 终端没有"包裹选区 + 光标偏移"的语义,降级为直接发送文本
sendText(pairText);
}
@override
void sendCommand(String command) {
switch (command.toLowerCase().trim()) {
case 'keyboard_hide':
case 'hide_keyboard':
hideKeyboard();
break;
default:
// 编辑区命令在终端无意义;配置校验已禁止,这里仅作兜底
if (kDebugMode) {
debugPrint('[VirtualKeyboard] 终端不支持编辑器命令: $command');
}
}
}
@override
void sendNamedKey(String keyName, {KeyboardKeyMods mods = KeyboardKeyMods.none}) {
// 字母键走 charInput:无修饰时就是该字母本身,Ctrl/Alt 组合由 xterm 换算
if (KeyboardScopeHelper.isLetterKeyName(keyName)) {
final lowerCode = keyName.codeUnitAt(3) + 0x20; // keyC -> 'c'
final handled = terminal.charInput(lowerCode, ctrl: mods.ctrl, alt: mods.alt);
if (handled) return;
// charInput 不支持的组合(无修饰 / 仅 Shift / Ctrl+非字母)按普通文本发送,
// 与 xterm 自身 `_onInsert` 的"先按键、后退化为文本"策略一致
final letter = String.fromCharCode(lowerCode);
terminal.textInput(mods.shift ? letter.toUpperCase() : letter);
return;
}
final key = resolveTerminalKey(keyName);
if (key == null) {
if (kDebugMode) {
debugPrint('[VirtualKeyboard] 未知的终端特殊键: $keyName');
}
return;
}
final handled = terminal.keyInput(
key,
ctrl: mods.ctrl,
alt: mods.alt,
shift: mods.shift,
);
if (!handled && kDebugMode) {
// 例如 keytab 中不存在的组合:不会产生任何输出
debugPrint('[VirtualKeyboard] 该按键组合在终端不会产生输出: $keyName'
'${mods.isEmpty ? '' : ' ($mods)'}');
}
}
@override
void hideKeyboard() {
focusNode?.unfocus();
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
}
+148
View File
@@ -0,0 +1,148 @@
import 'package:flutter/foundation.dart';
import 'package:xterm/xterm.dart';
import '../models/virtual_keyboard_config.dart';
/// 终端修饰键(小键盘上的 Ctrl / Alt / Shift 格)的运行时状态。
///
/// 语义:
/// - 单击 = 一次性:点亮后由**下一次真实输入**带上并自动熄灭
/// - 双击 = 锁定:持续生效,再点一次解除
///
/// 该状态由键盘组件与终端共用,因此它必须独立于 widget 生命周期存在:
/// 终端据此把修饰符叠加到"硬件键盘按键"和"软键盘打进来的字符"上。
class TerminalModifierState extends ChangeNotifier {
TerminalModifierState({DateTime Function()? clock}) : clock = clock ?? DateTime.now;
/// 双击判定时钟(测试可注入假时钟以确定性地控制单击/双击)
DateTime Function() clock;
/// 双击判定窗口
static const Duration doubleTapWindow = Duration(milliseconds: 350);
final Set<String> _oneshot = <String>{};
final Set<String> _locked = <String>{};
final Map<String, DateTime> _lastTap = <String, DateTime>{};
bool isActive(String modifier) =>
_oneshot.contains(modifier) || _locked.contains(modifier);
bool get isEmpty => _oneshot.isEmpty && _locked.isEmpty;
bool get isNotEmpty => !isEmpty;
/// 当前生效的修饰符组合
KeyboardKeyMods get mods => KeyboardKeyMods(
ctrl: isActive('ctrl'),
alt: isActive('alt'),
shift: isActive('shift'),
);
/// 单击一次性点亮 / 双击锁定 / 点击已锁定项解除
void toggle(String modifier) {
final now = clock();
final last = _lastTap[modifier];
final isDoubleTap = last != null && now.difference(last) < doubleTapWindow;
if (_locked.contains(modifier)) {
_locked.remove(modifier);
_oneshot.remove(modifier);
} else if (isDoubleTap) {
_oneshot.remove(modifier);
_locked.add(modifier);
} else if (_oneshot.contains(modifier)) {
_oneshot.remove(modifier);
} else {
_oneshot.add(modifier);
}
_lastTap[modifier] = now;
notifyListeners();
}
/// 一次性状态被一次真实输入消耗(锁定状态保留)
void consume() {
if (_oneshot.isEmpty) return;
_oneshot.clear();
notifyListeners();
}
/// 清空全部状态
void clear() {
if (isEmpty) return;
_oneshot.clear();
_locked.clear();
_lastTap.clear();
notifyListeners();
}
}
/// 把"软键盘 / IME 直接打进来的文本"按当前修饰键状态改写。
///
/// 软键盘的字符不会产生 Flutter KeyEvent,xterm 内部走的是
/// `terminal.textInput()`,因此只能在 `Terminal.onOutput` 这一层改写。
/// 规则与 xterm 的 `Terminal.charInput` 保持一致:
/// - Ctrl + a~z → 0x01~0x1a
/// - Ctrl + [ \ ] ^ _ → 0x1b~0x1f
/// - Alt + a~z → ESC + 大写字母
/// - Shift + a~z → 大写字母
///
/// 只处理**单个字符**:多字符(粘贴、指令快捷键)原样放过,避免误伤。
/// 返回 null 表示"无需改写"。
String? applyModifierToTypedText(String data, KeyboardKeyMods mods) {
if (mods.isEmpty) return null;
final runes = data.runes.toList();
if (runes.length != 1) return null;
final code = runes.first;
final isLetter = (code >= 0x61 && code <= 0x7a) || (code >= 0x41 && code <= 0x5a);
final lower = (code >= 0x41 && code <= 0x5a) ? code + 0x20 : code;
if (mods.ctrl) {
if (isLetter) return String.fromCharCode(lower - 0x61 + 1);
if (code >= 0x5b && code <= 0x5f) return String.fromCharCode(code - 0x5b + 27);
return null;
}
if (mods.alt && !mods.shift) {
if (isLetter) return String.fromCharCodes([0x1b, lower - 0x20]);
return null;
}
if (mods.shift && code >= 0x61 && code <= 0x7a) {
return String.fromCharCode(code - 0x20);
}
return null;
}
/// 代理输入处理器:把运行时修饰键叠加到按键事件上,再交给 xterm 默认链路。
///
/// 覆盖硬件键盘与"小键盘 key 格"的按键事件(它们都走 `Terminal.keyInput`);
/// 软键盘打进来的字符不产生 KeyEvent,由 [applyModifierToTypedText] 处理。
class ModifierAwareInputHandler implements TerminalInputHandler {
ModifierAwareInputHandler({required this.state, required this.delegate});
final TerminalModifierState state;
final TerminalInputHandler delegate;
@override
String? call(TerminalKeyboardEvent event) {
final mods = state.mods;
final result = delegate(
mods.isEmpty
? event
: event.copyWith(
ctrl: event.ctrl || mods.ctrl,
alt: event.alt || mods.alt,
shift: event.shift || mods.shift,
),
);
// 真的产生了输出才消耗一次性状态,避免"按了没反应还把修饰键吃掉"
if (result != null && mods.isNotEmpty) {
state.consume();
}
return result;
}
}
+21 -5
View File
@@ -26,12 +26,20 @@ class TerminalSessionItemWidget extends StatelessWidget {
final badgeLabel = session.distroId;
final isHost = session.distroId == 'host';
final isTerminated = !session.isProcessRunning;
final textStyle = theme.textTheme.bodyMedium?.copyWith(
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
color: isSelected ? theme.colorScheme.primary : null,
color: isTerminated
? theme.colorScheme.error
: (isSelected ? theme.colorScheme.primary : null),
decoration: isTerminated ? TextDecoration.lineThrough : null,
decorationColor: isTerminated ? theme.colorScheme.error : null,
);
final iconColor = isSelected ? theme.colorScheme.primary : null;
final iconColor = isTerminated
? theme.colorScheme.error
: (isSelected ? theme.colorScheme.primary : null);
return Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
@@ -66,6 +74,8 @@ class TerminalSessionItemWidget extends StatelessWidget {
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 1.5),
// 系统名可能来自用户自定义导入,过长时限宽避免把标题行挤出边界
constraints: const BoxConstraints(maxWidth: 96.0),
decoration: BoxDecoration(
color: isHost
? theme.colorScheme.surfaceContainerHighest
@@ -74,6 +84,8 @@ class TerminalSessionItemWidget extends StatelessWidget {
),
child: Text(
badgeLabel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 10.0,
fontWeight: FontWeight.w600,
@@ -175,9 +187,13 @@ class TerminalSessionItemWidget extends StatelessWidget {
children: [
Icon(icon, size: 18, color: color),
const SizedBox(width: 8),
Text(
title,
style: TextStyle(color: color),
Flexible(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color),
),
),
],
),
+264 -82
View File
@@ -22,12 +22,27 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
late TextEditingController _labelController;
late TextEditingController _valueInputController;
late TextEditingController _pairValueController;
late TextEditingController _cursorOffsetController;
String? _selectedIcon;
late String _selectedAction;
String? _selectedPresetValue;
/// 终端特殊键:所选 TerminalKey 枚举名
String? _selectedNamedKey;
/// 终端特殊键:下方三个修饰键控件组成的组合
KeyboardKeyMods _selectedMods = KeyboardKeyMods.none;
/// 终端修饰键动作:所选的 ctrl / alt / shift
String _selectedModifierValue = 'ctrl';
/// 终端指令快捷键:发送后是否自动回车
bool _autoEnter = false;
bool get _isTerminal => widget.scope == KeyboardScope.terminal;
@override
void initState() {
super.initState();
@@ -35,6 +50,10 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
_labelController = TextEditingController(text: init?.label ?? '');
_valueInputController = TextEditingController(text: init?.value ?? '');
// 成对符号不再依赖预设列表,改为自由输入,默认给出最常用的圆括号
_pairValueController = TextEditingController(
text: (init != null && init.action == 'pair' && init.value.isNotEmpty) ? init.value : '()',
);
_cursorOffsetController = TextEditingController(
text: (init?.cursorOffset ?? (init?.action == 'pair' ? -1 : 0)).toString(),
);
@@ -57,40 +76,147 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
}
void _syncPresetValueFromInitial() {
final currentVal = widget.initialKey?.value ?? '';
final init = widget.initialKey;
final currentVal = init?.value ?? '';
_autoEnter = init?.autoEnter ?? false;
_selectedMods = (init != null && init.action == 'key') ? init.mods : KeyboardKeyMods.none;
// 终端修饰键动作取值
_selectedModifierValue = KeyboardScopeHelper.terminalModifierValues.contains(currentVal)
? currentVal
: KeyboardScopeHelper.terminalModifierValues.first;
// 终端特殊键取值(支持 31 命名键与 keyA~keyZ)
_selectedNamedKey = (init != null &&
init.action == 'key' &&
KeyboardScopeHelper.terminalSupportedKeyNames.contains(currentVal))
? currentVal
: KeyboardScopeHelper.terminalNamedKeys.first.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;
}
_selectedPresetValue = KeyboardScopeHelper.editorCommands.any((c) => c.value == currentVal)
? currentVal
: KeyboardScopeHelper.editorCommands.first.value;
} else {
_selectedPresetValue = null;
}
}
/// 动作在下拉中的显示名(终端作用域下 input 即"指令快捷键")
String _actionLabel(AppLocalizations l10n, String action) {
if (_isTerminal && action == 'input') {
return l10n.keyboardActionInputTerminal;
}
return l10n.keyboardActionName(action);
}
/// 按键标签留空时的兜底文案:特殊键用「修饰符+紧凑键名」,其余沿用 value
String _fallbackLabel(String value, KeyboardKeyMods mods) {
if (_selectedAction != 'key') return value;
final prefix = [
if (mods.ctrl) 'Ctrl',
if (mods.alt) 'Alt',
if (mods.shift) 'Shift',
];
final short = KeyboardScopeHelper.terminalKeyShortLabel(value);
return prefix.isEmpty ? short : '${prefix.join('+')}+$short';
}
/// 终端特殊键下拉:按分组插入不可选的标题项
List<DropdownMenuItem<String?>> _buildNamedKeyItems(AppLocalizations l10n) {
final items = <DropdownMenuItem<String?>>[];
TerminalKeyGroup? lastGroup;
for (final option in KeyboardScopeHelper.terminalSelectableKeys) {
if (option.group != lastGroup) {
lastGroup = option.group;
items.add(
DropdownMenuItem<String?>(
value: null,
enabled: false,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Text(
_groupLabel(l10n, option.group),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
),
);
}
items.add(
DropdownMenuItem<String?>(
value: option.value,
child: Row(
children: [
Icon(KeyboardIconHelper.getIcon(option.icon), size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
// 字母键在每种语言下都显示同一个拉丁字母,无需走 l10n
KeyboardScopeHelper.isLetterKeyName(option.value)
? KeyboardScopeHelper.terminalKeyShortLabel(option.value)
: l10n.keyboardKeyName(option.value),
overflow: TextOverflow.ellipsis,
),
),
],
),
),
);
}
return items;
}
String _groupLabel(AppLocalizations l10n, TerminalKeyGroup group) {
switch (group) {
case TerminalKeyGroup.navigation:
return l10n.keyboardKeyGroupNavigation;
case TerminalKeyGroup.editing:
return l10n.keyboardKeyGroupEditing;
case TerminalKeyGroup.functionKeys:
return l10n.keyboardKeyGroupFunctionKeys;
case TerminalKeyGroup.letters:
return l10n.keyboardKeyGroupLetters;
}
}
/// 下方三个修饰键控件之一;切换后立即重新校验,避免出现静默无效的组合
Widget _buildModifierChip(AppLocalizations l10n, String modifier, bool selected) {
return FilterChip(
label: Text(l10n.keyboardModifierName(modifier)),
selected: selected,
onSelected: (value) {
setState(() {
KeyboardKeyMods mods = _selectedMods;
switch (modifier) {
case 'ctrl':
mods = mods.copyWith(ctrl: value);
break;
case 'alt':
mods = mods.copyWith(alt: value);
break;
case 'shift':
mods = mods.copyWith(shift: value);
break;
}
_selectedMods = mods;
});
_formKey.currentState?.validate();
},
);
}
@override
void dispose() {
_labelController.dispose();
_valueInputController.dispose();
_pairValueController.dispose();
_cursorOffsetController.dispose();
super.dispose();
}
@@ -100,19 +226,19 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
setState(() {
_selectedAction = newAction;
if (_selectedAction == 'pair') {
_selectedPresetValue = KeyboardScopeHelper.editorPairs.first.value;
if (_pairValueController.text.trim().isEmpty) {
_pairValueController.text = '()';
}
if (_cursorOffsetController.text.isEmpty || _cursorOffsetController.text == '0') {
_cursorOffsetController.text = '-1';
}
if (_labelController.text.isEmpty) {
_labelController.text = _selectedPresetValue!;
}
// 标签留空时由 _onSave 回退为成对符号内容,与 input 行为一致
} 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;
_selectedModifierValue = KeyboardScopeHelper.terminalModifierValues.first;
} else if (_selectedAction == 'key') {
_selectedNamedKey ??= KeyboardScopeHelper.terminalNamedKeys.first.value;
} else {
_selectedPresetValue = null;
}
@@ -125,23 +251,37 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
final String label = _labelController.text.trim();
String value;
int cursorOffset = 0;
KeyboardKeyMods mods = KeyboardKeyMods.none;
bool autoEnter = false;
if (_selectedAction == 'input') {
value = _valueInputController.text;
} else {
value = _selectedPresetValue ?? '';
}
if (_selectedAction == 'pair') {
cursorOffset = int.tryParse(_cursorOffsetController.text.trim()) ?? -1;
switch (_selectedAction) {
case 'input':
value = _valueInputController.text;
if (_isTerminal) autoEnter = _autoEnter;
break;
case 'pair':
value = _pairValueController.text.trim();
cursorOffset = int.tryParse(_cursorOffsetController.text.trim()) ?? -1;
break;
case 'key':
value = _selectedNamedKey ?? '';
mods = _selectedMods;
break;
case 'modifier':
value = _selectedModifierValue;
break;
default:
value = _selectedPresetValue ?? '';
}
final keyItem = KeyboardKeyItem(
label: label.isNotEmpty ? label : value,
label: label.isNotEmpty ? label : _fallbackLabel(value, mods),
icon: (_selectedIcon != null && _selectedIcon!.isNotEmpty) ? _selectedIcon : null,
action: _selectedAction,
value: value,
cursorOffset: cursorOffset,
mods: mods,
autoEnter: autoEnter,
);
Navigator.of(context).pop(keyItem);
@@ -208,7 +348,10 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
Icon(KeyboardIconHelper.getIcon(iconKey), size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(iconKey, overflow: TextOverflow.ellipsis),
child: Text(
l10n.keyboardIconName(iconKey),
overflow: TextOverflow.ellipsis,
),
),
],
),
@@ -235,7 +378,10 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
items: availableActions.map(
(actionOption) => DropdownMenuItem<String>(
value: actionOption.action,
child: Text(actionOption.label, overflow: TextOverflow.ellipsis),
child: Text(
_actionLabel(l10n, actionOption.action),
overflow: TextOverflow.ellipsis,
),
),
).toList(),
onChanged: _onActionChanged,
@@ -243,7 +389,7 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
const SizedBox(height: 14),
// 动作值 Value 控件联动
if (_selectedAction == 'input')
if (_selectedAction == 'input') ...[
TextFormField(
controller: _valueInputController,
decoration: InputDecoration(
@@ -258,29 +404,38 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
}
return null;
},
)
),
// 终端指令快捷键:发送后补回车,实现"一格执行命令"
if (_isTerminal)
SwitchListTile(
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(l10n.keyboardAutoEnter),
value: _autoEnter,
onChanged: (val) => setState(() => _autoEnter = val),
),
]
else if (_selectedAction == 'pair')
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: _selectedPresetValue,
TextFormField(
controller: _pairValueController,
decoration: InputDecoration(
labelText: l10n.keyboardPairPresetFormField,
labelText: l10n.keyboardPairValueFormField,
hintText: l10n.keyboardPairValueFormFieldHint,
border: const OutlineInputBorder(),
isDense: true,
),
items: KeyboardScopeHelper.editorPairs.map(
(pair) => DropdownMenuItem<String>(
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;
}
});
validator: (val) {
final v = val?.trim() ?? '';
if (v.isEmpty) {
return l10n.keyboardPairValueRequiredError;
}
final half = v.length ~/ 2;
// 长度不足 2 或左右完全相同(如 "((" )无法构成有效的前后半段
if (v.length < 2 ||
(v.length.isEven && v.substring(0, half) == v.substring(half))) {
return l10n.keyboardPairValueInvalidError;
}
return null;
},
)
else if (_selectedAction == 'command')
@@ -295,7 +450,18 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
items: KeyboardScopeHelper.editorCommands.map(
(cmd) => DropdownMenuItem<String>(
value: cmd.value,
child: Text('${cmd.label} [${cmd.value}]', overflow: TextOverflow.ellipsis),
child: Row(
children: [
Icon(KeyboardIconHelper.getIcon(cmd.icon), size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.keyboardCommandName(cmd.value),
overflow: TextOverflow.ellipsis,
),
),
],
),
),
).toList(),
onChanged: (val) {
@@ -307,45 +473,62 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
else if (_selectedAction == 'modifier')
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: _selectedPresetValue,
initialValue: _selectedModifierValue,
decoration: InputDecoration(
labelText: l10n.keyboardModifierPresetFormField,
border: const OutlineInputBorder(),
isDense: true,
),
items: KeyboardScopeHelper.terminalModifiers.map(
(m) => DropdownMenuItem<String>(
value: m.value,
child: Text(m.label, overflow: TextOverflow.ellipsis),
),
).toList(),
items: KeyboardScopeHelper.terminalModifierValues
.map(
(m) => DropdownMenuItem<String>(
value: m,
child: Text(l10n.keyboardModifierName(m), overflow: TextOverflow.ellipsis),
),
)
.toList(),
onChanged: (val) {
if (val == null) return;
setState(() {
_selectedPresetValue = val;
_selectedModifierValue = val;
});
},
)
else if (_selectedAction == 'terminal_key')
DropdownButtonFormField<String>(
else if (_selectedAction == 'key') ...[
DropdownButtonFormField<String?>(
isExpanded: true,
initialValue: _selectedPresetValue,
initialValue: _selectedNamedKey,
decoration: InputDecoration(
labelText: l10n.keyboardTerminalKeyPresetFormField,
labelText: l10n.keyboardKeyFormField,
border: const OutlineInputBorder(),
isDense: true,
),
items: KeyboardScopeHelper.terminalKeys.map(
(k) => DropdownMenuItem<String>(
value: k.value,
child: Text(k.label, overflow: TextOverflow.ellipsis),
),
).toList(),
items: _buildNamedKeyItems(l10n),
onChanged: (val) {
if (val == null) return;
setState(() {
_selectedPresetValue = val;
_selectedNamedKey = val;
});
},
validator: (val) {
final name = val ?? '';
if (name.isEmpty || !KeyboardScopeHelper.isSupportedTerminalKey(name)) {
return l10n.keyboardKeyInvalidError;
}
return null;
},
),
const SizedBox(height: 12),
// 单独提供三个修饰键:与下拉里选中的键叠加成 Ctrl+C 这类组合
Wrap(
spacing: 8,
children: [
_buildModifierChip(l10n, 'ctrl', _selectedMods.ctrl),
_buildModifierChip(l10n, 'alt', _selectedMods.alt),
_buildModifierChip(l10n, 'shift', _selectedMods.shift),
],
),
],
// 仅当 action == pair 时显示 cursorOffset
if (_selectedAction == 'pair') ...[
@@ -355,7 +538,6 @@ class _KeyEditDialogState extends State<KeyEditDialog> {
keyboardType: const TextInputType.numberWithOptions(signed: true),
decoration: InputDecoration(
labelText: l10n.keyboardCursorOffsetFormField,
helperText: l10n.keyboardCursorOffsetHelper,
border: const OutlineInputBorder(),
isDense: true,
),
@@ -24,9 +24,13 @@ class VirtualKeyboardPageConfigSection extends StatelessWidget {
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),
Expanded(
child: Text(
l10n.keyboardPageConfigSectionTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
],
),
@@ -41,20 +45,24 @@ class VirtualKeyboardPageConfigSection extends StatelessWidget {
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 内的定宽控件会被挤出右边界
Expanded(
child: 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),
),
],
),
),
const SizedBox(width: 12),
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton.filledTonal(
icon: const Icon(Icons.remove, size: 18),
+172
View File
@@ -0,0 +1,172 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:re_editor/re_editor.dart';
import '../models/virtual_keyboard_config.dart';
/// 虚拟小键盘的输入汇聚接口。
///
/// 键盘组件只负责"按键语义"(文本 / 成对符号 / 编辑器命令 / 命名特殊键),
/// 由具体实现决定把语义落到编辑器还是终端上,避免键盘组件per-scope 分叉。
///
/// 不同作用域对同一语义的支持程度不同,不支持的实现应安全降级为空操作,
/// 绝不静默插入无关内容。
abstract class VirtualKeyboardSink {
/// 发送一段文本(编辑区:插入;终端:写入 PTY)
///
/// [appendEnter] 仅终端有意义:发送后补一个回车符,实现"输入即执行"
void sendText(String text, {bool appendEnter = false});
/// 成对符号:有选区时包裹选区,无选区时插入并把光标按 [cursorOffset] 偏移
void sendPair(String pairText, int cursorOffset);
/// 编辑器命令(缩进、撤销、光标移动等)
void sendCommand(String command);
/// 命名特殊键(终端:escape / tab / arrowUp / keyC + Ctrl 组合等)
void sendNamedKey(String keyName, {KeyboardKeyMods mods = KeyboardKeyMods.none});
/// 收起软键盘
void hideKeyboard();
}
/// 编辑区实现:把按键语义落到 [CodeLineEditingController] 上
class EditorKeyboardSink implements VirtualKeyboardSink {
final CodeLineEditingController controller;
final FocusNode? focusNode;
EditorKeyboardSink({required this.controller, this.focusNode});
@override
void sendText(String text, {bool appendEnter = false}) {
if (text.isEmpty) return;
// 编辑区不存在"回车执行"语义,appendEnter 直接忽略(由校验层禁止该组合)
controller.replaceSelection(text);
}
@override
void sendPair(String pairText, int cursorOffset) {
final hasSelection = !controller.selection.isCollapsed &&
controller.selection.baseOffset != -1 &&
controller.selection.extentOffset != -1;
if (hasSelection) {
final selected = controller.selectedText;
if (pairText.length >= 2) {
final left = pairText.substring(0, pairText.length ~/ 2);
final right = pairText.substring(pairText.length ~/ 2);
controller.replaceSelection(left + selected + right);
} else {
controller.replaceSelection(pairText + selected + pairText);
}
return;
}
controller.replaceSelection(pairText);
if (cursorOffset != 0) {
final curSel = controller.selection;
final targetOffset = (curSel.extentOffset + cursorOffset).clamp(0, controller.extentLine.length);
controller.selection = CodeLineSelection.collapsed(
index: curSel.extentIndex,
offset: targetOffset,
);
}
}
@override
void sendCommand(String command) {
final cmd = command.toLowerCase().trim();
switch (cmd) {
case 'tab':
controller.applyIndent();
break;
case 'untab':
case 'outdent':
controller.applyOutdent();
break;
case 'cursor_left':
case 'left':
controller.moveCursor(AxisDirection.left);
break;
case 'cursor_right':
case 'right':
controller.moveCursor(AxisDirection.right);
break;
case 'cursor_up':
case 'up':
controller.moveCursor(AxisDirection.up);
break;
case 'cursor_down':
case 'down':
controller.moveCursor(AxisDirection.down);
break;
case 'line_start':
case 'home':
controller.moveCursorToLineStart();
break;
case 'line_end':
case 'end':
controller.moveCursorToLineEnd();
break;
case 'page_start':
controller.moveCursorToPageStart();
break;
case 'page_end':
controller.moveCursorToPageEnd();
break;
case 'undo':
if (controller.canUndo) {
controller.undo();
}
break;
case 'redo':
if (controller.canRedo) {
controller.redo();
}
break;
case 'copy':
controller.copy();
break;
case 'cut':
controller.cut();
break;
case 'paste':
controller.paste();
break;
case 'backspace':
case 'delete_backward':
controller.deleteBackward();
break;
case 'delete':
case 'delete_forward':
controller.deleteForward();
break;
case 'select_all':
controller.selectAll();
break;
case 'keyboard_hide':
case 'hide_keyboard':
hideKeyboard();
break;
default:
// 未知命令安全降级为直接输入其命令名称或原文本
controller.replaceSelection(command);
break;
}
}
@override
void sendNamedKey(String keyName, {KeyboardKeyMods mods = KeyboardKeyMods.none}) {
// 编辑区没有"终端命名键"概念;配置校验已禁止该组合,这里仅作兜底不产生副作用
if (kDebugMode) {
debugPrint('[VirtualKeyboard] 编辑区不支持命名特殊键: $keyName${mods.isEmpty ? '' : ' ($mods)'}');
}
}
@override
void hideKeyboard() {
focusNode?.unfocus();
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
}
+111 -121
View File
@@ -3,10 +3,22 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:re_editor/re_editor.dart';
import 'virtual_keyboard_sink.dart';
import 'terminal_modifier_state.dart';
/// 编辑器下方的虚拟辅助小键盘组件
class VirtualKeyboardWidget extends StatefulWidget {
final CodeLineEditingController? controller;
final FocusNode? focusNode;
/// 输入汇聚实现。为空时按 [controller] 自动构造编辑区实现;
/// 终端作用域传入 `TerminalKeyboardSink`。
final VirtualKeyboardSink? sink;
/// 终端修饰键运行时状态。终端作用域由外部注入,使终端也能读到同一份状态
/// (把修饰符叠加到软键盘/硬件键盘的输入上);为空时组件内部自建一份。
final TerminalModifierState? modifierState;
final VirtualKeyboardConfig config;
final Color? backgroundColor;
@@ -14,6 +26,8 @@ class VirtualKeyboardWidget extends StatefulWidget {
super.key,
required this.controller,
this.focusNode,
this.sink,
this.modifierState,
required this.config,
this.backgroundColor,
});
@@ -28,6 +42,15 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget>
late AnimationController _animationController;
int _currentPage = 0;
/// 输入汇聚实现(终端作用域由外部注入,否则按 controller 构造编辑区实现)
VirtualKeyboardSink? _sink;
/// 修饰键运行时状态(终端作用域由外部注入,使终端能共用同一份状态)
late TerminalModifierState _modifiers;
/// 是否由本组件创建了 [_modifiers](自建时才负责释放)
bool _ownsModifiers = false;
static const double _rowHeight = 30.0;
static const double _indicatorHeight = 12.0;
@@ -40,18 +63,64 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget>
duration: const Duration(milliseconds: 200),
value: 0.0, // 默认折叠(0.0 表示仅显示第一行,1.0 表示完全展开)
);
_resolveSink();
_resolveModifiers();
}
@override
void didUpdateWidget(covariant VirtualKeyboardWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.sink != widget.sink || oldWidget.controller != widget.controller) {
_resolveSink();
}
if (oldWidget.modifierState != widget.modifierState) {
_releaseModifiers();
_resolveModifiers();
}
}
/// 终端作用域由外部注入 sink;编辑区按 controller 自动构造
void _resolveSink() {
_sink = widget.sink ??
(widget.controller != null
? EditorKeyboardSink(controller: widget.controller!, focusNode: widget.focusNode)
: null);
}
void _resolveModifiers() {
final injected = widget.modifierState;
if (injected != null) {
_modifiers = injected;
_ownsModifiers = false;
} else {
_modifiers = TerminalModifierState();
_ownsModifiers = true;
}
_modifiers.addListener(_onModifiersChanged);
}
void _releaseModifiers() {
_modifiers.removeListener(_onModifiersChanged);
if (_ownsModifiers) {
_modifiers.dispose();
}
}
void _onModifiersChanged() {
if (mounted) setState(() {});
}
@override
void dispose() {
_releaseModifiers();
_pageController.dispose();
_animationController.dispose();
super.dispose();
}
void _handleKeyTap(KeyboardKeyItem keyItem) {
final controller = widget.controller;
if (controller == null) return;
final sink = _sink;
if (sink == null) return;
// 轻微触觉反馈提升敲击手感
HapticFeedback.lightImpact();
@@ -61,133 +130,45 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget>
widget.focusNode!.requestFocus();
}
// 修饰键只切换运行时状态,不产生输出
if (keyItem.action == 'modifier') {
_modifiers.toggle(keyItem.value);
return;
}
final mods = _effectiveMods(keyItem.mods);
switch (keyItem.action) {
case 'command':
_handleCommand(controller, keyItem.value);
sink.sendCommand(keyItem.value);
break;
case 'pair':
_handlePair(controller, keyItem.value, keyItem.cursorOffset);
sink.sendPair(keyItem.value, keyItem.cursorOffset);
break;
case 'key':
sink.sendNamedKey(keyItem.value, mods: mods);
break;
case 'input':
default:
_handleInput(controller, keyItem.value.isNotEmpty ? keyItem.value : keyItem.label);
break;
}
}
void _handleInput(CodeLineEditingController controller, String text) {
if (text.isEmpty) return;
controller.replaceSelection(text);
}
void _handlePair(CodeLineEditingController controller, String pairText, int offset) {
final hasSelection = !controller.selection.isCollapsed &&
controller.selection.baseOffset != -1 &&
controller.selection.extentOffset != -1;
if (hasSelection) {
final selected = controller.selectedText;
if (pairText.length >= 2) {
final left = pairText.substring(0, pairText.length ~/ 2);
final right = pairText.substring(pairText.length ~/ 2);
final wrapped = left + selected + right;
controller.replaceSelection(wrapped);
} else {
controller.replaceSelection(pairText + selected + pairText);
}
} else {
controller.replaceSelection(pairText);
if (offset != 0) {
final curSel = controller.selection;
final targetOffset = (curSel.extentOffset + offset).clamp(0, controller.extentLine.length);
controller.selection = CodeLineSelection.collapsed(
index: curSel.extentIndex,
offset: targetOffset,
sink.sendText(
keyItem.value.isNotEmpty ? keyItem.value : keyItem.label,
appendEnter: keyItem.autoEnter,
);
}
break;
}
// 一次性修饰键被"下一次任意按键"消耗(含 Esc、方向键这类不产生字符的键)
_modifiers.consume();
}
void _handleCommand(CodeLineEditingController controller, String command) {
final cmd = command.toLowerCase().trim();
switch (cmd) {
case 'tab':
controller.applyIndent();
break;
case 'untab':
case 'outdent':
controller.applyOutdent();
break;
case 'cursor_left':
case 'left':
controller.moveCursor(AxisDirection.left);
break;
case 'cursor_right':
case 'right':
controller.moveCursor(AxisDirection.right);
break;
case 'cursor_up':
case 'up':
controller.moveCursor(AxisDirection.up);
break;
case 'cursor_down':
case 'down':
controller.moveCursor(AxisDirection.down);
break;
case 'line_start':
case 'home':
controller.moveCursorToLineStart();
break;
case 'line_end':
case 'end':
controller.moveCursorToLineEnd();
break;
case 'page_start':
controller.moveCursorToPageStart();
break;
case 'page_end':
controller.moveCursorToPageEnd();
break;
case 'undo':
if (controller.canUndo) {
controller.undo();
}
break;
case 'redo':
if (controller.canRedo) {
controller.redo();
}
break;
case 'copy':
controller.copy();
break;
case 'cut':
controller.cut();
break;
case 'paste':
controller.paste();
break;
case 'backspace':
case 'delete_backward':
controller.deleteBackward();
break;
case 'delete':
case 'delete_forward':
controller.deleteForward();
break;
case 'select_all':
controller.selectAll();
break;
case 'keyboard_hide':
case 'hide_keyboard':
widget.focusNode?.unfocus();
SystemChannels.textInput.invokeMethod('TextInput.hide');
break;
default:
// 未知命令安全降级为直接输入其命令名称或原文本
controller.replaceSelection(command);
break;
}
/// 合并按键自身配置的修饰符与运行时激活的修饰符
KeyboardKeyMods _effectiveMods(KeyboardKeyMods own) {
final active = _modifiers.mods;
return KeyboardKeyMods(
ctrl: own.ctrl || active.ctrl,
alt: own.alt || active.alt,
shift: own.shift || active.shift,
);
}
@override
@@ -392,9 +373,18 @@ class _VirtualKeyboardWidgetState extends State<VirtualKeyboardWidget>
Widget _buildKeyButton(KeyboardKeyItem keyItem, bool isDark) {
final iconData = KeyboardIconHelper.getIcon(keyItem.icon);
final btnBgColor = isDark ? const Color(0xFF2C2C2C) : const Color(0xFFFFFFFF);
final btnTextColor = isDark ? const Color(0xFFE0E0E0) : const Color(0xFF303133);
final borderColor = isDark ? const Color(0xFF383838) : const Color(0xFFE4E7ED);
// 修饰键处于激活(一次性或锁定)状态时高亮,让用户看清当前修饰状态
final isModifierActive = keyItem.action == 'modifier' && _modifiers.isActive(keyItem.value);
final btnBgColor = isModifierActive
? (isDark ? const Color(0xFF2F4F6F) : const Color(0xFFD6E6FF))
: (isDark ? const Color(0xFF2C2C2C) : const Color(0xFFFFFFFF));
final btnTextColor = isModifierActive
? (isDark ? const Color(0xFFFFFFFF) : const Color(0xFF0B57D0))
: (isDark ? const Color(0xFFE0E0E0) : const Color(0xFF303133));
final borderColor = isModifierActive
? const Color(0xFF0B57D0)
: (isDark ? const Color(0xFF383838) : const Color(0xFFE4E7ED));
Widget content;
if (iconData != null) {