This commit is contained in:
LZX committed 2026-09-17 16:32:27 +08:00
1 parent 5ac164b407
commit f93f6095af
94 files changed
+7877 -4018

No files matched your search

+72 -18
View File
@@ -610,6 +610,18 @@
"detectedTaskSingleGoDesc": "Run current Go source file",
"detectedTaskSingleRustDesc": "Compile and execute current Rust source file",
"detectedTaskSingleJsDesc": "Run current JavaScript script",
"detectedTaskSingleJavaDesc": "Run current Java source file directly",
"detectedTaskSingleTsDesc": "Run current TypeScript script",
"detectedTaskSingleLuaDesc": "Run current Lua script",
"detectedTaskSinglePerlDesc": "Run current Perl script",
"detectedTaskSinglePhpDesc": "Run current PHP script",
"detectedTaskPythonPipInstallDesc": "Install requirements via pip",
"detectedTaskPythonRunMainDesc": "Execute Python project main entrypoint",
"detectedTaskPythonPytestDesc": "Run pytest test suite",
"detectedTaskMavenPackageDesc": "Package Maven project (mvn package)",
"detectedTaskMavenCompileDesc": "Compile Maven project sources (mvn compile)",
"detectedTaskMavenTestDesc": "Run Maven unit tests (mvn test)",
"detectedTaskMavenCleanDesc": "Clean Maven target output directory (mvn clean)",
"missingDistroTitle": "System Environment Not Ready",
"noDistroAvailableContent": "No available Linux execution environment detected.\n\nProject tasks need to run inside a Linux container. Please install or download a Linux system first (e.g. Ubuntu or Alpine).",
"distroNotInstalledContent": "System \"{distro}\" is not installed or has been removed.\n\nPlease install it in System Management or select another available system.",
@@ -827,10 +839,15 @@
},
"codeCompletionManagement": "Code Completion Management",
"codeCompletionSubtitle": "Manage language servers and code intelligence toolchains",
"internalEngineTitle": "Internal Code Intelligence Engine (Alpine)",
"completionSourceSection": "Completion Data Sources & Switches",
"localCompletionTitle": "Local Base Completion",
"localCompletionSubtitle": "Built-in language keywords and document lexical heuristic extraction",
"lspCompletionTitle": "Backend Language Server",
"lspCompletionSubtitle": "Request real semantic types and function parameters from background compilers",
"internalEngineTitle": "Runtime & Code Intelligence Engine (Ubuntu)",
"internalEngineStatusReady": "Engine Ready",
"internalEngineStatusNotReady": "Engine Not Ready",
"internalEngineExtracting": "Preparing internal code intelligence engine...",
"internalEngineStatusNotReady": "Engine Not Started",
"internalEngineExtracting": "Preparing built-in Ubuntu environment & intelligence engine...",
"installedStatus": "Ready",
"notInstalledStatus": "Component Not Installed",
"installComponent": "Install Component",
@@ -858,10 +875,18 @@
}
}
},
"uninstallingComponent": "Uninstalling {pkg} and cleaning configuration...",
"@uninstallingComponent": {
"placeholders": {
"pkg": {
"type": "String"
}
}
},
"editLanguageConfig": "Edit Language Configuration",
"addLanguageConfig": "Add Language Configuration",
"deleteLanguageConfirmTitle": "Delete Language Configuration",
"deleteLanguageConfirmMessage": "Are you sure you want to delete code completion config for {name}?",
"deleteLanguageConfirmMessage": "Are you sure you want to delete the code completion configuration for {name}?",
"@deleteLanguageConfirmMessage": {
"placeholders": {
"name": {
@@ -869,8 +894,16 @@
}
}
},
"resetDefaultLanguages": "Reset to Defaults",
"resetDefaultLanguagesConfirm": "Are you sure you want to reset all language configurations to defaults?",
"deleteLanguageWithPackageConfirmMessage": "Are you sure you want to delete the code completion configuration for {name}? Installed packages will be uninstalled.",
"@deleteLanguageWithPackageConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"resetDefaultLanguages": "Reset Default Configurations",
"resetDefaultLanguagesConfirm": "Are you sure you want to reset all language configurations to official default presets?",
"languageDisplayName": "Language Name",
"languageDisplayNameHint": "e.g. C / C++",
"languageIdField": "Language ID",
@@ -880,9 +913,9 @@
"serverCommandField": "Server Command",
"serverCommandFieldHint": "e.g. clangd",
"serverArgsField": "Server Arguments",
"serverArgsFieldHint": "Space or comma separated",
"apkPackageField": "Alpine APK Package",
"apkPackageFieldHint": "For one-click install, e.g. clang-extra-tools",
"serverArgsFieldHint": "Space or comma-separated arguments",
"apkPackageField": "Ubuntu Package Name (APT)",
"apkPackageFieldHint": "For one-click install, e.g. clangd or python3-pylsp",
"lspPackageMissingTitle": "{language} code intelligence component not installed",
"@lspPackageMissingTitle": {
"placeholders": {
@@ -891,18 +924,39 @@
}
}
},
"lspPackageMissingMessage": "Install {pkg} ({command}) to enable code completion and error diagnostics",
"@lspPackageMissingMessage": {
"lspPackageMissingMessage": "Install the component to enable code completion and error diagnostics",
"installNow": "Install Now",
"fieldRequired": "This field is required",
"languageConfigSaved": "Language configuration saved",
"enable": "Enable",
"disable": "Disable",
"edit": "Edit",
"componentQueued": "{name} queued…",
"@componentQueued": {
"placeholders": {
"pkg": {
"type": "String"
},
"command": {
"name": {
"type": "String"
}
}
},
"installNow": "Install Now",
"fieldRequired": "This field is required",
"languageConfigSaved": "Language configuration saved"
"uninstallComponentSuccess": "{name} component uninstalled successfully",
"@uninstallComponentSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"uninstallComponentFailed": "Failed to uninstall component: {error}",
"@uninstallComponentFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"installingStatus": "Installing…",
"uninstallingStatus": "Uninstalling…",
"emptyLspLanguagesTitle": "No code intelligence components installed",
"emptyLspLanguagesSubtitle": "Open any source file to trigger installation on demand, or click \"+\" to add manually"
}
+181 -7
View File
@@ -2144,6 +2144,78 @@ abstract class AppLocalizations {
/// **'运行当前 JS 脚本'**
String get detectedTaskSingleJsDesc;
/// No description provided for @detectedTaskSingleJavaDesc.
///
/// In zh, this message translates to:
/// **'直接运行当前 Java 源文件'**
String get detectedTaskSingleJavaDesc;
/// No description provided for @detectedTaskSingleTsDesc.
///
/// In zh, this message translates to:
/// **'运行当前 TypeScript 脚本'**
String get detectedTaskSingleTsDesc;
/// No description provided for @detectedTaskSingleLuaDesc.
///
/// In zh, this message translates to:
/// **'运行当前 Lua 脚本'**
String get detectedTaskSingleLuaDesc;
/// No description provided for @detectedTaskSinglePerlDesc.
///
/// In zh, this message translates to:
/// **'运行当前 Perl 脚本'**
String get detectedTaskSinglePerlDesc;
/// No description provided for @detectedTaskSinglePhpDesc.
///
/// In zh, this message translates to:
/// **'运行当前 PHP 脚本'**
String get detectedTaskSinglePhpDesc;
/// No description provided for @detectedTaskPythonPipInstallDesc.
///
/// In zh, this message translates to:
/// **'安装项目 requirements 依赖包'**
String get detectedTaskPythonPipInstallDesc;
/// No description provided for @detectedTaskPythonRunMainDesc.
///
/// In zh, this message translates to:
/// **'执行 Python 项目主程序'**
String get detectedTaskPythonRunMainDesc;
/// No description provided for @detectedTaskPythonPytestDesc.
///
/// In zh, this message translates to:
/// **'运行 pytest 测试用例'**
String get detectedTaskPythonPytestDesc;
/// No description provided for @detectedTaskMavenPackageDesc.
///
/// In zh, this message translates to:
/// **'打包 Maven 项目 (mvn package)'**
String get detectedTaskMavenPackageDesc;
/// No description provided for @detectedTaskMavenCompileDesc.
///
/// In zh, this message translates to:
/// **'编译 Maven 项目源码 (mvn compile)'**
String get detectedTaskMavenCompileDesc;
/// No description provided for @detectedTaskMavenTestDesc.
///
/// In zh, this message translates to:
/// **'运行 Maven 单元测试 (mvn test)'**
String get detectedTaskMavenTestDesc;
/// No description provided for @detectedTaskMavenCleanDesc.
///
/// In zh, this message translates to:
/// **'清理 Maven 目标输出目录 (mvn clean)'**
String get detectedTaskMavenCleanDesc;
/// No description provided for @missingDistroTitle.
///
/// In zh, this message translates to:
@@ -2546,10 +2618,40 @@ abstract class AppLocalizations {
/// **'管理各编程语言的智能补全与报错工具链'**
String get codeCompletionSubtitle;
/// No description provided for @completionSourceSection.
///
/// In zh, this message translates to:
/// **'补全数据源与开关'**
String get completionSourceSection;
/// No description provided for @localCompletionTitle.
///
/// In zh, this message translates to:
/// **'本地基础补全'**
String get localCompletionTitle;
/// No description provided for @localCompletionSubtitle.
///
/// In zh, this message translates to:
/// **'包含语言内置关键字与当前文档词法启发式提取'**
String get localCompletionSubtitle;
/// No description provided for @lspCompletionTitle.
///
/// In zh, this message translates to:
/// **'后端语言服务补全'**
String get lspCompletionTitle;
/// No description provided for @lspCompletionSubtitle.
///
/// In zh, this message translates to:
/// **'向后台编译器守护进程请求真实语义类型与函数参数补全'**
String get lspCompletionSubtitle;
/// No description provided for @internalEngineTitle.
///
/// In zh, this message translates to:
/// **'内部代码智能引擎 (Alpine)'**
/// **'代码运行与智能补全引擎 (Ubuntu)'**
String get internalEngineTitle;
/// No description provided for @internalEngineStatusReady.
@@ -2561,13 +2663,13 @@ abstract class AppLocalizations {
/// No description provided for @internalEngineStatusNotReady.
///
/// In zh, this message translates to:
/// **'引擎未就绪'**
/// **'引擎未启动'**
String get internalEngineStatusNotReady;
/// No description provided for @internalEngineExtracting.
///
/// In zh, this message translates to:
/// **'正在准备内置代码智能引擎...'**
/// **'正在准备内置 Ubuntu 开发环境与智能补全引擎...'**
String get internalEngineExtracting;
/// No description provided for @installComponent.
@@ -2594,6 +2696,12 @@ abstract class AppLocalizations {
/// **'组件安装失败: {error}'**
String installComponentFailed(String error);
/// No description provided for @uninstallingComponent.
///
/// In zh, this message translates to:
/// **'正在卸载 {pkg} 并清理配置...'**
String uninstallingComponent(String pkg);
/// No description provided for @editLanguageConfig.
///
/// In zh, this message translates to:
@@ -2618,6 +2726,12 @@ abstract class AppLocalizations {
/// **'确定要删除 {name} 的代码补全配置吗?'**
String deleteLanguageConfirmMessage(String name);
/// No description provided for @deleteLanguageWithPackageConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要删除 {name} 的代码补全配置吗?已安装的软件包将一并卸载。'**
String deleteLanguageWithPackageConfirmMessage(String name);
/// No description provided for @resetDefaultLanguages.
///
/// In zh, this message translates to:
@@ -2693,13 +2807,13 @@ abstract class AppLocalizations {
/// No description provided for @apkPackageField.
///
/// In zh, this message translates to:
/// **'Alpine 依赖包名'**
/// **'Ubuntu 依赖包名 (APT)'**
String get apkPackageField;
/// No description provided for @apkPackageFieldHint.
///
/// In zh, this message translates to:
/// **'用于一键安装,如 clang-extra-tools'**
/// **'用于一键安装,如 clangd 或 python3-pylsp'**
String get apkPackageFieldHint;
/// No description provided for @lspPackageMissingTitle.
@@ -2711,8 +2825,8 @@ abstract class AppLocalizations {
/// No description provided for @lspPackageMissingMessage.
///
/// In zh, this message translates to:
/// **'安装 {pkg} ({command}) 即可获得精准代码补全与错误检查'**
String lspPackageMissingMessage(String pkg, String command);
/// **'安装组件即可获得精准代码补全与错误检查'**
String get lspPackageMissingMessage;
/// No description provided for @installNow.
///
@@ -2731,6 +2845,66 @@ abstract class AppLocalizations {
/// In zh, this message translates to:
/// **'语言配置已保存'**
String get languageConfigSaved;
/// No description provided for @enable.
///
/// In zh, this message translates to:
/// **'启用'**
String get enable;
/// No description provided for @disable.
///
/// In zh, this message translates to:
/// **'停用'**
String get disable;
/// No description provided for @edit.
///
/// In zh, this message translates to:
/// **'编辑'**
String get edit;
/// No description provided for @componentQueued.
///
/// In zh, this message translates to:
/// **'{name} 排队等待中…'**
String componentQueued(String name);
/// No description provided for @uninstallComponentSuccess.
///
/// In zh, this message translates to:
/// **'{name} 组件卸载成功'**
String uninstallComponentSuccess(String name);
/// No description provided for @uninstallComponentFailed.
///
/// In zh, this message translates to:
/// **'组件卸载失败: {error}'**
String uninstallComponentFailed(String error);
/// No description provided for @installingStatus.
///
/// In zh, this message translates to:
/// **'正在安装…'**
String get installingStatus;
/// No description provided for @uninstallingStatus.
///
/// In zh, this message translates to:
/// **'正在卸载…'**
String get uninstallingStatus;
/// No description provided for @emptyLspLanguagesTitle.
///
/// In zh, this message translates to:
/// **'暂无已安装的代码智能组件'**
String get emptyLspLanguagesTitle;
/// No description provided for @emptyLspLanguagesSubtitle.
///
/// In zh, this message translates to:
/// **'在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加'**
String get emptyLspLanguagesSubtitle;
}
class _AppLocalizationsDelegate
+117 -12
View File
@@ -1290,6 +1290,47 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get detectedTaskSingleJsDesc => 'Run current JavaScript script';
@override
String get detectedTaskSingleJavaDesc =>
'Run current Java source file directly';
@override
String get detectedTaskSingleTsDesc => 'Run current TypeScript script';
@override
String get detectedTaskSingleLuaDesc => 'Run current Lua script';
@override
String get detectedTaskSinglePerlDesc => 'Run current Perl script';
@override
String get detectedTaskSinglePhpDesc => 'Run current PHP script';
@override
String get detectedTaskPythonPipInstallDesc => 'Install requirements via pip';
@override
String get detectedTaskPythonRunMainDesc =>
'Execute Python project main entrypoint';
@override
String get detectedTaskPythonPytestDesc => 'Run pytest test suite';
@override
String get detectedTaskMavenPackageDesc =>
'Package Maven project (mvn package)';
@override
String get detectedTaskMavenCompileDesc =>
'Compile Maven project sources (mvn compile)';
@override
String get detectedTaskMavenTestDesc => 'Run Maven unit tests (mvn test)';
@override
String get detectedTaskMavenCleanDesc =>
'Clean Maven target output directory (mvn clean)';
@override
String get missingDistroTitle => 'System Environment Not Ready';
@@ -1542,19 +1583,36 @@ class AppLocalizationsEn extends AppLocalizations {
String get codeCompletionSubtitle =>
'Manage language servers and code intelligence toolchains';
@override
String get completionSourceSection => 'Completion Data Sources & Switches';
@override
String get localCompletionTitle => 'Local Base Completion';
@override
String get localCompletionSubtitle =>
'Built-in language keywords and document lexical heuristic extraction';
@override
String get lspCompletionTitle => 'Backend Language Server';
@override
String get lspCompletionSubtitle =>
'Request real semantic types and function parameters from background compilers';
@override
String get internalEngineTitle =>
'Internal Code Intelligence Engine (Alpine)';
'Runtime & Code Intelligence Engine (Ubuntu)';
@override
String get internalEngineStatusReady => 'Engine Ready';
@override
String get internalEngineStatusNotReady => 'Engine Not Ready';
String get internalEngineStatusNotReady => 'Engine Not Started';
@override
String get internalEngineExtracting =>
'Preparing internal code intelligence engine...';
'Preparing built-in Ubuntu environment & intelligence engine...';
@override
String get installComponent => 'Install Component';
@@ -1574,6 +1632,11 @@ class AppLocalizationsEn extends AppLocalizations {
return 'Failed to install component: $error';
}
@override
String uninstallingComponent(String pkg) {
return 'Uninstalling $pkg and cleaning configuration...';
}
@override
String get editLanguageConfig => 'Edit Language Configuration';
@@ -1585,15 +1648,20 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String deleteLanguageConfirmMessage(String name) {
return 'Are you sure you want to delete code completion config for $name?';
return 'Are you sure you want to delete the code completion configuration for $name?';
}
@override
String get resetDefaultLanguages => 'Reset to Defaults';
String deleteLanguageWithPackageConfirmMessage(String name) {
return 'Are you sure you want to delete the code completion configuration for $name? Installed packages will be uninstalled.';
}
@override
String get resetDefaultLanguages => 'Reset Default Configurations';
@override
String get resetDefaultLanguagesConfirm =>
'Are you sure you want to reset all language configurations to defaults?';
'Are you sure you want to reset all language configurations to official default presets?';
@override
String get languageDisplayName => 'Language Name';
@@ -1624,14 +1692,14 @@ class AppLocalizationsEn extends AppLocalizations {
String get serverArgsField => 'Server Arguments';
@override
String get serverArgsFieldHint => 'Space or comma separated';
String get serverArgsFieldHint => 'Space or comma-separated arguments';
@override
String get apkPackageField => 'Alpine APK Package';
String get apkPackageField => 'Ubuntu Package Name (APT)';
@override
String get apkPackageFieldHint =>
'For one-click install, e.g. clang-extra-tools';
'For one-click install, e.g. clangd or python3-pylsp';
@override
String lspPackageMissingTitle(String language) {
@@ -1639,9 +1707,8 @@ class AppLocalizationsEn extends AppLocalizations {
}
@override
String lspPackageMissingMessage(String pkg, String command) {
return 'Install $pkg ($command) to enable code completion and error diagnostics';
}
String get lspPackageMissingMessage =>
'Install the component to enable code completion and error diagnostics';
@override
String get installNow => 'Install Now';
@@ -1651,4 +1718,42 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get languageConfigSaved => 'Language configuration saved';
@override
String get enable => 'Enable';
@override
String get disable => 'Disable';
@override
String get edit => 'Edit';
@override
String componentQueued(String name) {
return '$name queued…';
}
@override
String uninstallComponentSuccess(String name) {
return '$name component uninstalled successfully';
}
@override
String uninstallComponentFailed(String error) {
return 'Failed to uninstall component: $error';
}
@override
String get installingStatus => 'Installing…';
@override
String get uninstallingStatus => 'Uninstalling…';
@override
String get emptyLspLanguagesTitle =>
'No code intelligence components installed';
@override
String get emptyLspLanguagesSubtitle =>
'Open any source file to trigger installation on demand, or click \"+\" to add manually';
}
+104 -8
View File
@@ -1251,6 +1251,42 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get detectedTaskSingleJsDesc => '运行当前 JS 脚本';
@override
String get detectedTaskSingleJavaDesc => '直接运行当前 Java 源文件';
@override
String get detectedTaskSingleTsDesc => '运行当前 TypeScript 脚本';
@override
String get detectedTaskSingleLuaDesc => '运行当前 Lua 脚本';
@override
String get detectedTaskSinglePerlDesc => '运行当前 Perl 脚本';
@override
String get detectedTaskSinglePhpDesc => '运行当前 PHP 脚本';
@override
String get detectedTaskPythonPipInstallDesc => '安装项目 requirements 依赖包';
@override
String get detectedTaskPythonRunMainDesc => '执行 Python 项目主程序';
@override
String get detectedTaskPythonPytestDesc => '运行 pytest 测试用例';
@override
String get detectedTaskMavenPackageDesc => '打包 Maven 项目 (mvn package)';
@override
String get detectedTaskMavenCompileDesc => '编译 Maven 项目源码 (mvn compile)';
@override
String get detectedTaskMavenTestDesc => '运行 Maven 单元测试 (mvn test)';
@override
String get detectedTaskMavenCleanDesc => '清理 Maven 目标输出目录 (mvn clean)';
@override
String get missingDistroTitle => '系统环境未就绪';
@@ -1499,16 +1535,31 @@ class AppLocalizationsZh extends AppLocalizations {
String get codeCompletionSubtitle => '管理各编程语言的智能补全与报错工具链';
@override
String get internalEngineTitle => '内部代码智能引擎 (Alpine)';
String get completionSourceSection => '补全数据源与开关';
@override
String get localCompletionTitle => '本地基础补全';
@override
String get localCompletionSubtitle => '包含语言内置关键字与当前文档词法启发式提取';
@override
String get lspCompletionTitle => '后端语言服务补全';
@override
String get lspCompletionSubtitle => '向后台编译器守护进程请求真实语义类型与函数参数补全';
@override
String get internalEngineTitle => '代码运行与智能补全引擎 (Ubuntu)';
@override
String get internalEngineStatusReady => '引擎已就绪';
@override
String get internalEngineStatusNotReady => '引擎未就绪';
String get internalEngineStatusNotReady => '引擎未启动';
@override
String get internalEngineExtracting => '正在准备内置代码智能引擎...';
String get internalEngineExtracting => '正在准备内置 Ubuntu 开发环境与智能补全引擎...';
@override
String get installComponent => '安装组件';
@@ -1528,6 +1579,11 @@ class AppLocalizationsZh extends AppLocalizations {
return '组件安装失败: $error';
}
@override
String uninstallingComponent(String pkg) {
return '正在卸载 $pkg 并清理配置...';
}
@override
String get editLanguageConfig => '编辑语言配置';
@@ -1542,6 +1598,11 @@ class AppLocalizationsZh extends AppLocalizations {
return '确定要删除 $name 的代码补全配置吗?';
}
@override
String deleteLanguageWithPackageConfirmMessage(String name) {
return '确定要删除 $name 的代码补全配置吗?已安装的软件包将一并卸载。';
}
@override
String get resetDefaultLanguages => '恢复默认配置';
@@ -1579,10 +1640,10 @@ class AppLocalizationsZh extends AppLocalizations {
String get serverArgsFieldHint => '多个参数以空格或逗号分隔';
@override
String get apkPackageField => 'Alpine 依赖包名';
String get apkPackageField => 'Ubuntu 依赖包名 (APT)';
@override
String get apkPackageFieldHint => '用于一键安装,如 clang-extra-tools';
String get apkPackageFieldHint => '用于一键安装,如 clangd 或 python3-pylsp';
@override
String lspPackageMissingTitle(String language) {
@@ -1590,9 +1651,7 @@ class AppLocalizationsZh extends AppLocalizations {
}
@override
String lspPackageMissingMessage(String pkg, String command) {
return '安装 $pkg ($command) 即可获得精准代码补全与错误检查';
}
String get lspPackageMissingMessage => '安装组件即可获得精准代码补全与错误检查';
@override
String get installNow => '一键安装';
@@ -1602,4 +1661,41 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get languageConfigSaved => '语言配置已保存';
@override
String get enable => '启用';
@override
String get disable => '停用';
@override
String get edit => '编辑';
@override
String componentQueued(String name) {
return '$name 排队等待中…';
}
@override
String uninstallComponentSuccess(String name) {
return '$name 组件卸载成功';
}
@override
String uninstallComponentFailed(String error) {
return '组件卸载失败: $error';
}
@override
String get installingStatus => '正在安装…';
@override
String get uninstallingStatus => '正在卸载…';
@override
String get emptyLspLanguagesTitle => '暂无已安装的代码智能组件';
@override
String get emptyLspLanguagesSubtitle =>
'在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加';
}
+68 -14
View File
@@ -610,6 +610,18 @@
"detectedTaskSingleGoDesc": "运行当前 Go 源文件",
"detectedTaskSingleRustDesc": "编译并执行当前 Rust 源文件",
"detectedTaskSingleJsDesc": "运行当前 JS 脚本",
"detectedTaskSingleJavaDesc": "直接运行当前 Java 源文件",
"detectedTaskSingleTsDesc": "运行当前 TypeScript 脚本",
"detectedTaskSingleLuaDesc": "运行当前 Lua 脚本",
"detectedTaskSinglePerlDesc": "运行当前 Perl 脚本",
"detectedTaskSinglePhpDesc": "运行当前 PHP 脚本",
"detectedTaskPythonPipInstallDesc": "安装项目 requirements 依赖包",
"detectedTaskPythonRunMainDesc": "执行 Python 项目主程序",
"detectedTaskPythonPytestDesc": "运行 pytest 测试用例",
"detectedTaskMavenPackageDesc": "打包 Maven 项目 (mvn package)",
"detectedTaskMavenCompileDesc": "编译 Maven 项目源码 (mvn compile)",
"detectedTaskMavenTestDesc": "运行 Maven 单元测试 (mvn test)",
"detectedTaskMavenCleanDesc": "清理 Maven 目标输出目录 (mvn clean)",
"missingDistroTitle": "系统环境未就绪",
"noDistroAvailableContent": "未检测到可用的 Linux 执行环境。\n\n工程任务需要在 Linux 容器环境中运行。请先安装或下载 Linux 系统(如 Ubuntu 或 Alpine)。",
"distroNotInstalledContent": "系统 \"{distro}\" 尚未安装或已被清理。\n\n请在系统管理中安装该系统,或选择其他已就绪的系统。",
@@ -827,10 +839,15 @@
},
"codeCompletionManagement": "代码补全管理",
"codeCompletionSubtitle": "管理各编程语言的智能补全与报错工具链",
"internalEngineTitle": "内部代码智能引擎 (Alpine)",
"completionSourceSection": "补全数据源与开关",
"localCompletionTitle": "本地基础补全",
"localCompletionSubtitle": "包含语言内置关键字与当前文档词法启发式提取",
"lspCompletionTitle": "后端语言服务补全",
"lspCompletionSubtitle": "向后台编译器守护进程请求真实语义类型与函数参数补全",
"internalEngineTitle": "代码运行与智能补全引擎 (Ubuntu)",
"internalEngineStatusReady": "引擎已就绪",
"internalEngineStatusNotReady": "引擎未就绪",
"internalEngineExtracting": "正在准备内置代码智能引擎...",
"internalEngineStatusNotReady": "引擎未启动",
"internalEngineExtracting": "正在准备内置 Ubuntu 开发环境与智能补全引擎...",
"installedStatus": "已就绪",
"notInstalledStatus": "未安装组件",
"installComponent": "安装组件",
@@ -858,6 +875,14 @@
}
}
},
"uninstallingComponent": "正在卸载 {pkg} 并清理配置...",
"@uninstallingComponent": {
"placeholders": {
"pkg": {
"type": "String"
}
}
},
"editLanguageConfig": "编辑语言配置",
"addLanguageConfig": "新增语言配置",
"deleteLanguageConfirmTitle": "删除语言配置",
@@ -869,6 +894,14 @@
}
}
},
"deleteLanguageWithPackageConfirmMessage": "确定要删除 {name} 的代码补全配置吗?已安装的软件包将一并卸载。",
"@deleteLanguageWithPackageConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"resetDefaultLanguages": "恢复默认配置",
"resetDefaultLanguagesConfirm": "确定将所有语言配置重置为官方默认预设吗?",
"languageDisplayName": "语言名称",
@@ -881,8 +914,8 @@
"serverCommandFieldHint": "例如: clangd",
"serverArgsField": "启动参数",
"serverArgsFieldHint": "多个参数以空格或逗号分隔",
"apkPackageField": "Alpine 依赖包名",
"apkPackageFieldHint": "用于一键安装,如 clang-extra-tools",
"apkPackageField": "Ubuntu 依赖包名 (APT)",
"apkPackageFieldHint": "用于一键安装,如 clangd 或 python3-pylsp",
"lspPackageMissingTitle": "未安装 {language} 代码智能组件",
"@lspPackageMissingTitle": {
"placeholders": {
@@ -891,18 +924,39 @@
}
}
},
"lspPackageMissingMessage": "安装 {pkg} ({command}) 即可获得精准代码补全与错误检查",
"@lspPackageMissingMessage": {
"lspPackageMissingMessage": "安装组件即可获得精准代码补全与错误检查",
"installNow": "一键安装",
"fieldRequired": "此项不能为空",
"languageConfigSaved": "语言配置已保存",
"enable": "启用",
"disable": "停用",
"edit": "编辑",
"componentQueued": "{name} 排队等待中…",
"@componentQueued": {
"placeholders": {
"pkg": {
"type": "String"
},
"command": {
"name": {
"type": "String"
}
}
},
"installNow": "一键安装",
"fieldRequired": "此项不能为空",
"languageConfigSaved": "语言配置已保存"
"uninstallComponentSuccess": "{name} 组件卸载成功",
"@uninstallComponentSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"uninstallComponentFailed": "组件卸载失败: {error}",
"@uninstallComponentFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"installingStatus": "正在安装…",
"uninstallingStatus": "正在卸载…",
"emptyLspLanguagesTitle": "暂无已安装的代码智能组件",
"emptyLspLanguagesSubtitle": "在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加"
}
+8 -1
View File
@@ -6,6 +6,7 @@ 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/services/background_task/background_task_scheduler.dart';
import 'package:code_editor/views/main_view.dart';
import 'package:code_editor/utils/app_theme.dart';
import 'package:flutter/material.dart';
@@ -45,7 +46,13 @@ class MyApp extends StatelessWidget {
(tab ?? (TabProvider()..init()))..bindProjectProvider(project),
),
ChangeNotifierProvider(create: (_) => TerminalProvider()),
ChangeNotifierProvider(create: (_) => NoticeCenter()),
ChangeNotifierProvider(
create: (_) {
final nc = NoticeCenter();
BackgroundTaskScheduler.instance.attachNoticeCenter(nc);
return nc;
},
),
ChangeNotifierProvider(
create: (context) => RunProvider(noticeCenter: context.read<NoticeCenter>()),
),
+24 -213
View File
@@ -7,78 +7,22 @@ enum DistroArch {
x86_64,
}
/// LXC 容器镜像元数据规格(用于根据下载源动态解析真实下载路径)
class LxcImageSpec {
/// 发行版代号 (例如 'debian', 'archlinux', 'fedora')
final String distribution;
/// 版本标识 (例如 'bookworm', 'current', '43')
final String release;
/// 变体标识 (例如 'default', 'cloud')
final String variant;
const LxcImageSpec({
required this.distribution,
required this.release,
this.variant = 'default',
});
}
/// 发行版下载镜像源定义
class DistroMirror {
final String id;
final String name;
final String baseUrl;
final bool isDefault;
const DistroMirror({
required this.id,
required this.name,
required this.baseUrl,
this.isDefault = false,
});
}
/// 发行版条目清单模型
/// 单一主系统条目清单模型
class DistroManifestItem {
/// 唯一标识符 (例如 'ubuntu', 'alpine', 'debian')
final String id;
/// 显示名称 (例如 'Ubuntu', 'Alpine Linux', 'Debian')
final String name;
/// 版本文本 (例如 '24.04.5 LTS', '3.20.3', '12 (Bookworm)')
final String version;
/// 是否推荐
final bool isRecommended;
/// 是否为软件内置安装包(打包在 assets 中,受删除保护且无需网络下载)
final bool isBuiltin;
/// LXC 镜像元数据(在线下载型系统专属,用于动态源解析器自动发现真实路径)
final LxcImageSpec? lxcSpec;
/// 对应架构资源包映射 (架构 -> 下载 URL 或 Asset 路径)
final Map<DistroArch, String> packages;
/// 系统图标或装饰图标
final IconData iconData;
/// 品牌主题色(用于图标底色/装饰)
final Color brandColor;
/// 本地资产图标路径 (例如 'assets/icons/distros/ubuntu.png')
final String? assetIconPath;
const DistroManifestItem({
required this.id,
required this.name,
required this.version,
this.isRecommended = false,
this.isBuiltin = false,
this.lxcSpec,
this.isBuiltin = true,
required this.packages,
required this.iconData,
required this.brandColor,
@@ -99,175 +43,42 @@ class DistroManifestItem {
return packages.containsKey(currentArch);
}
/// 获取当前设备适用的资源包路径或 URL
/// 获取当前设备适用的内置资源包路径
String? get currentPackageSource {
return packages[currentArch];
}
}
/// 系统资源库静态目录(包含内置与经过验证的高速在线源)
/// 系统资源库静态目录(单一内置系统:Ubuntu 24.04 LTS)
class DistroRepository {
static const List<DistroManifestItem> availableDistros = [
// 1. Ubuntu 24.04 LTS (推荐,软件内置)
DistroManifestItem(
id: 'ubuntu',
name: 'Ubuntu',
version: '24.04.5 LTS (Noble Numbat)',
isRecommended: true,
isBuiltin: true,
iconData: Icons.donut_large_rounded,
brandColor: Color(0xFFE95420), // Ubuntu Orange
assetIconPath: 'assets/icons/distros/ubuntu.png',
packages: {
DistroArch.arm64: 'assets/distros/ubuntu-base-24.04.5-base-arm64.tar.gz',
DistroArch.x86_64: 'assets/distros/ubuntu-base-24.04.5-base-x86_64.tar.gz',
},
),
// 2. Alpine 3.20 (软件内置)
DistroManifestItem(
id: 'alpine',
name: 'Alpine Linux',
version: '3.20.3 (musl libc)',
isRecommended: false,
isBuiltin: true,
iconData: Icons.landscape_rounded,
brandColor: Color(0xFF0D597F), // Alpine Blue
assetIconPath: 'assets/icons/distros/alpine.png',
packages: {
DistroArch.arm64: 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz',
DistroArch.x86_64: 'assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz',
},
),
// 3. Debian 12 (Bookworm) - 在线下载,不占 APK 体积
DistroManifestItem(
id: 'debian',
name: 'Debian',
version: '12 (Bookworm)',
isRecommended: false,
isBuiltin: false,
lxcSpec: LxcImageSpec(
distribution: 'debian',
release: 'bookworm',
variant: 'default',
),
iconData: Icons.all_inclusive_rounded,
brandColor: Color(0xFFA80030), // Debian Red
assetIconPath: 'assets/icons/distros/debian.png',
packages: {
DistroArch.arm64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/20260913_05:24/rootfs.tar.xz',
DistroArch.x86_64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/amd64/default/20260913_05:24/rootfs.tar.xz',
},
),
// 4. Arch Linux - 在线源
DistroManifestItem(
id: 'arch',
name: 'Arch Linux',
version: 'Rolling Release',
isRecommended: false,
isBuiltin: false,
lxcSpec: LxcImageSpec(
distribution: 'archlinux',
release: 'current',
variant: 'default',
),
iconData: Icons.change_history_rounded,
brandColor: Color(0xFF1793D1), // Arch Cyan
assetIconPath: 'assets/icons/distros/arch.png',
packages: {
DistroArch.arm64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/archlinux/current/arm64/default/20260913_04:18/rootfs.tar.xz',
DistroArch.x86_64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/archlinux/current/amd64/default/20260913_04:18/rootfs.tar.xz',
},
),
// 5. Fedora 43 - 在线源
DistroManifestItem(
id: 'fedora',
name: 'Fedora',
version: '43 (Container Base)',
isRecommended: false,
isBuiltin: false,
lxcSpec: LxcImageSpec(
distribution: 'fedora',
release: '43',
variant: 'default',
),
iconData: Icons.language_rounded,
brandColor: Color(0xFF51A2DA), // Fedora Blue
assetIconPath: 'assets/icons/distros/fedora.png',
packages: {
DistroArch.arm64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/fedora/43/arm64/default/20260913_20:33/rootfs.tar.xz',
DistroArch.x86_64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/fedora/43/amd64/default/20260913_20:33/rootfs.tar.xz',
},
),
];
/// 可选的高速开源软件镜像源
static const List<DistroMirror> availableMirrors = [
DistroMirror(
id: 'tsinghua',
name: 'Tsinghua TUNA Mirror',
baseUrl: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/',
isDefault: true,
),
DistroMirror(
id: 'bfsu',
name: 'BFSU Open Source Mirror',
baseUrl: 'https://mirrors.bfsu.edu.cn/lxc-images/',
),
DistroMirror(
id: 'iscas',
name: 'ISCAS Open Source Mirror',
baseUrl: 'https://mirror.iscas.ac.cn/lxc-images/',
),
DistroMirror(
id: 'official',
name: 'LinuxContainers Official Mirror',
baseUrl: 'https://images.linuxcontainers.org/',
),
];
/// 默认推荐镜像源(清华大学源)
static DistroMirror get defaultMirror =>
availableMirrors.firstWhere((m) => m.isDefault, orElse: () => availableMirrors.first);
/// 根据 ID 检索镜像源
static DistroMirror getMirrorById(String id) {
return availableMirrors.firstWhere(
(m) => m.id == id,
orElse: () => defaultMirror,
);
}
/// 根据当前机器架构过滤,仅返回本架构支持的发行版列表
static List<DistroManifestItem> get currentArchDistros {
return availableDistros.where((d) => d.isSupportedOnCurrentDevice).toList();
}
/// 默认系统实例名称
static const String defaultSystemName = 'ubuntu';
/// 根据 ID 查找发行版配置
static const DistroManifestItem ubuntuItem = DistroManifestItem(
id: defaultSystemName,
name: 'Ubuntu',
version: '24.04.5 LTS (Noble Numbat)',
isBuiltin: true,
iconData: Icons.donut_large_rounded,
brandColor: Color(0xFFE95420), // Ubuntu Orange
assetIconPath: 'assets/icons/distros/ubuntu.png',
packages: {
DistroArch.arm64: 'assets/distros/ubuntu-base-24.04.5-base-arm64.tar.gz',
DistroArch.x86_64: 'assets/distros/ubuntu-base-24.04.5-base-x86_64.tar.gz',
},
);
static const List<DistroManifestItem> availableDistros = [ubuntuItem];
/// 根据 ID 查找系统配置
static DistroManifestItem? getById(String id) {
try {
return availableDistros.firstWhere((e) => e.id == id);
} catch (_) {
return null;
}
if (id == defaultSystemName) return ubuntuItem;
return null;
}
/// 内置 Ubuntu 资源包路径(自动匹配当前 CPU 架构)
static String get builtinUbuntuAssetPath {
return getById('ubuntu')?.currentPackageSource ??
return ubuntuItem.currentPackageSource ??
'assets/distros/ubuntu-base-24.04.5-base-arm64.tar.gz';
}
/// 内置 Alpine 资源包路径(自动匹配当前 CPU 架构)
static String get builtinAlpineAssetPath {
return getById('alpine')?.currentPackageSource ??
'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz';
}
}
+67 -12
View File
@@ -5,9 +5,13 @@ class LspLanguageConfig {
final List<String> fileExtensions;
final String serverCommand;
final List<String> serverArgs;
final String apkPackage;
final String package;
final bool enabled;
/// 兼容别名
String get apkPackage => package;
String get aptPackage => package;
const LspLanguageConfig({
required this.id,
required this.name,
@@ -15,11 +19,12 @@ class LspLanguageConfig {
required this.fileExtensions,
required this.serverCommand,
this.serverArgs = const [],
required this.apkPackage,
required this.package,
this.enabled = true,
});
factory LspLanguageConfig.fromJson(Map<String, dynamic> json) {
final pkg = (json['package'] ?? json['aptPackage'] ?? json['apkPackage']) as String? ?? '';
return LspLanguageConfig(
id: json['id'] as String? ?? '',
name: json['name'] as String? ?? '',
@@ -34,7 +39,7 @@ class LspLanguageConfig {
?.map((e) => e.toString())
.toList() ??
[],
apkPackage: json['apkPackage'] as String? ?? '',
package: pkg,
enabled: json['enabled'] as bool? ?? true,
);
}
@@ -47,7 +52,8 @@ class LspLanguageConfig {
'fileExtensions': fileExtensions,
'serverCommand': serverCommand,
'serverArgs': serverArgs,
'apkPackage': apkPackage,
'package': package,
'apkPackage': package,
'enabled': enabled,
};
}
@@ -59,6 +65,7 @@ class LspLanguageConfig {
List<String>? fileExtensions,
String? serverCommand,
List<String>? serverArgs,
String? package,
String? apkPackage,
bool? enabled,
}) {
@@ -69,13 +76,13 @@ class LspLanguageConfig {
fileExtensions: fileExtensions ?? this.fileExtensions,
serverCommand: serverCommand ?? this.serverCommand,
serverArgs: serverArgs ?? this.serverArgs,
apkPackage: apkPackage ?? this.apkPackage,
package: package ?? apkPackage ?? this.package,
enabled: enabled ?? this.enabled,
);
}
/// 官方默认预设语言列表
static List<LspLanguageConfig> get defaultPresets => [
/// 官方内置语言支持模版(基于 Ubuntu 官方 apt 工具链,仅作探测与安装指引,不默认写入用户配置)
static List<LspLanguageConfig> get builtinPresets => [
const LspLanguageConfig(
id: 'c_cpp',
name: 'C / C++',
@@ -83,7 +90,7 @@ class LspLanguageConfig {
fileExtensions: ['.c', '.cpp', '.cc', '.cxx', '.h', '.hpp'],
serverCommand: 'clangd',
serverArgs: ['--background-index'],
apkPackage: 'clang-extra-tools',
package: 'clangd',
enabled: true,
),
const LspLanguageConfig(
@@ -93,7 +100,7 @@ class LspLanguageConfig {
fileExtensions: ['.py'],
serverCommand: 'pylsp',
serverArgs: [],
apkPackage: 'py3-lsp-server',
package: 'python3-pylsp',
enabled: true,
),
const LspLanguageConfig(
@@ -103,7 +110,7 @@ class LspLanguageConfig {
fileExtensions: ['.rs'],
serverCommand: 'rust-analyzer',
serverArgs: [],
apkPackage: 'rust-analyzer',
package: 'rust-analyzer',
enabled: true,
),
const LspLanguageConfig(
@@ -113,7 +120,7 @@ class LspLanguageConfig {
fileExtensions: ['.go'],
serverCommand: 'gopls',
serverArgs: [],
apkPackage: 'gopls',
package: 'gopls',
enabled: true,
),
const LspLanguageConfig(
@@ -123,8 +130,56 @@ class LspLanguageConfig {
fileExtensions: ['.sh', '.bash'],
serverCommand: 'bash-language-server',
serverArgs: ['start'],
apkPackage: 'bash-language-server',
package: 'bash-language-server',
enabled: true,
),
const LspLanguageConfig(
id: 'java',
name: 'Java',
languageId: 'java',
fileExtensions: ['.java'],
serverCommand: 'jdtls',
serverArgs: [],
package: 'jdtls',
enabled: true,
),
const LspLanguageConfig(
id: 'typescript',
name: 'TypeScript',
languageId: 'typescript',
fileExtensions: ['.ts', '.mts', '.tsx'],
serverCommand: 'typescript-language-server',
serverArgs: ['--stdio'],
package: 'typescript-language-server',
enabled: true,
),
const LspLanguageConfig(
id: 'lua',
name: 'Lua',
languageId: 'lua',
fileExtensions: ['.lua'],
serverCommand: 'lua-language-server',
serverArgs: [],
package: 'lua-language-server',
enabled: true,
),
];
/// 保持向后兼容别名
static List<LspLanguageConfig> get defaultPresets => builtinPresets;
/// 根据文件后缀从内置预设模版中匹配支持的语言
static LspLanguageConfig? findBuiltinByExtension(String ext) {
if (ext.isEmpty) return null;
final normalized = ext.startsWith('.') ? ext.toLowerCase() : '.$ext'.toLowerCase();
for (final preset in builtinPresets) {
for (final item in preset.fileExtensions) {
final itemNorm = item.startsWith('.') ? item.toLowerCase() : '.$item'.toLowerCase();
if (itemNorm == normalized) {
return preset;
}
}
}
return null;
}
}
+39
View File
@@ -82,6 +82,45 @@ class ModuleFailureText extends NoticeText {
});
}
/// 后台组件安装/卸载阶段通知(支持排队、执行中)
class ComponentInstallPhaseText extends NoticeText {
final String componentName;
final bool isUninstall;
final bool isQueued;
final String? detail;
const ComponentInstallPhaseText({
required this.componentName,
this.isUninstall = false,
this.isQueued = false,
this.detail,
});
}
/// 后台组件安装/卸载成功通知
class ComponentInstallDoneText extends NoticeText {
final String componentName;
final bool isUninstall;
const ComponentInstallDoneText({
required this.componentName,
this.isUninstall = false,
});
}
/// 后台组件安装/卸载失败通知
class ComponentInstallFailureText extends NoticeText {
final String componentName;
final bool isUninstall;
final String? error;
const ComponentInstallFailureText({
required this.componentName,
this.isUninstall = false,
this.error,
});
}
/// 一条通知(业务无关:任务探测、以后的下载/编译进度都可复用)
@immutable
class NoticeItem {
+25
View File
@@ -139,6 +139,31 @@ class RunTask {
return l10n.detectedTaskSingleRustDesc;
case 'detected_single_js':
return l10n.detectedTaskSingleJsDesc;
case 'detected_single_java':
return l10n.detectedTaskSingleJavaDesc;
case 'detected_single_ts':
return l10n.detectedTaskSingleTsDesc;
case 'detected_single_lua':
return l10n.detectedTaskSingleLuaDesc;
case 'detected_single_perl':
return l10n.detectedTaskSinglePerlDesc;
case 'detected_single_php':
return l10n.detectedTaskSinglePhpDesc;
case 'detected_python_pip_install':
return l10n.detectedTaskPythonPipInstallDesc;
case 'detected_python_run_main':
case 'detected_python_run_app':
return l10n.detectedTaskPythonRunMainDesc;
case 'detected_python_pytest':
return l10n.detectedTaskPythonPytestDesc;
case 'detected_maven_package':
return l10n.detectedTaskMavenPackageDesc;
case 'detected_maven_compile':
return l10n.detectedTaskMavenCompileDesc;
case 'detected_maven_test':
return l10n.detectedTaskMavenTestDesc;
case 'detected_maven_clean':
return l10n.detectedTaskMavenCleanDesc;
default:
return description ?? '';
}
+12 -73
View File
@@ -1,12 +1,10 @@
import 'dart:io';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/distro_installer.dart';
import '../services/distro_manager.dart';
/// 终端多系统状态与默认系统持久化管理器
/// 终端系统状态管理器(单一内置 Ubuntu 环境)
class DistroProvider with ChangeNotifier {
static const String _prefKeyDefaultSystem = 'terminal_default_system';
final DistroManager _manager = DistroManager();
@@ -37,42 +35,27 @@ class DistroProvider with ChangeNotifier {
notifyListeners();
}
/// 重新扫描已安装的系统并校准当前默认选中项
/// 重新扫描已安装的系统并校准状态
Future<void> refreshSystems() async {
final systems = await _manager.listInstalledSystems();
_installedSystems = systems;
final prefs = await SharedPreferences.getInstance();
final savedSystem = prefs.getString(_prefKeyDefaultSystem);
if (savedSystem != null && _installedSystems.contains(savedSystem)) {
_selectedSystem = savedSystem;
} else if (_installedSystems.isNotEmpty) {
_selectedSystem = _installedSystems.first;
await prefs.setString(_prefKeyDefaultSystem, _selectedSystem!);
final isInstalled = await _manager.isSystemInstalled(DistroRepository.defaultSystemName);
if (isInstalled) {
_installedSystems = [DistroRepository.defaultSystemName];
_selectedSystem = DistroRepository.defaultSystemName;
} else {
_installedSystems = [];
_selectedSystem = null;
await prefs.remove(_prefKeyDefaultSystem);
}
notifyListeners();
}
/// 选择指定系统为当前活跃系统并持久化为默认系统
/// 选择指定系统为当前活跃系统(仅支持默认 Ubuntu)
Future<void> selectSystem(String systemName) async {
if (!_installedSystems.contains(systemName)) return;
if (_selectedSystem != systemName) {
_selectedSystem = systemName;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_prefKeyDefaultSystem, systemName);
notifyListeners();
}
await refreshSystems();
}
/// 从应用内置资源导入 Ubuntu 24.04 系统实例
Future<void> importBuiltinUbuntu({
required String systemName,
String systemName = DistroRepository.defaultSystemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
@@ -82,51 +65,7 @@ class DistroProvider with ChangeNotifier {
isCancelled: isCancelled,
);
// 导入成功后刷新列表并自动选为当前系统
await refreshSystems();
await selectSystem(systemName);
}
/// 从应用内置资源导入 Alpine 系统实例(保留备用)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await _manager.importBuiltinAlpine(
systemName: systemName,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 导入成功后刷新列表并自动选为当前系统
await refreshSystems();
await selectSystem(systemName);
}
/// 从外部 .tar.gz 压缩包导入自定义系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await _manager.importFromCustomTarGz(
systemName: systemName,
tarGzFile: tarGzFile,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 导入成功后刷新列表并自动选为当前系统
await refreshSystems();
await selectSystem(systemName);
}
/// 高危操作:删除指定系统实例
Future<void> deleteSystem(String systemName) async {
await _manager.deleteSystem(systemName);
onSystemDeleted?.call(systemName);
// 导入成功后刷新列表
await refreshSystems();
}
}
+14
View File
@@ -126,6 +126,20 @@ class RunProvider extends ChangeNotifier {
void _resolveLastRunTask() {
_lastRunTask = null;
if (_lastRunTaskId == null) return;
// 单文件任务联动:如果上一次执行的任务是单文件任务(以 detected_single_ 开头)
if (_lastRunTaskId!.startsWith('detected_single_')) {
final singleTasks = _taskTable.tasksOf(RunTaskType.singleFile);
if (singleTasks.isNotEmpty) {
// 当前文件支持单文件运行,自动联动为当前文件的单文件任务
_lastRunTask = singleTasks.first;
_lastRunTaskId = singleTasks.first.id;
return;
}
// 当前文件不支持单文件运行,清除当前可执行的 _lastRunTask(保留 _lastRunTaskId 以便切回可运行文件时恢复)
return;
}
for (final task in allTasks) {
if (task.id == _lastRunTaskId) {
_lastRunTask = task;
+19 -15
View File
@@ -1,6 +1,5 @@
import 'dart:convert';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/models/editor_theme.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:flutter/foundation.dart';
@@ -34,8 +33,8 @@ class SettingsProvider extends ChangeNotifier {
//项目配置
static const String _keyShowHiddenFiles = 'show_hidden_files'; //显示隐藏文件
//下载配置
static const String _keyDownloadMirrorId = 'download_mirror_id'; //下载源镜像ID
//代码补全
static const String _keyEnableLspCompletion = 'enable_lsp_completion'; //LSP智能代码补全启用
//语言
static const String _keyAppLocale = 'app_locale';
@@ -60,12 +59,13 @@ class SettingsProvider extends ChangeNotifier {
String _terminalKeyboardConfigJson = VirtualKeyboardConfig.defaultTerminalJsonPretty();
VirtualKeyboardConfig _terminalKeyboardConfig = VirtualKeyboardConfig.defaultTerminalConfiguration();
bool _showHiddenFiles = true;
String _downloadMirrorId = 'tsinghua'; // 默认清华源
bool _enableLspCompletion = true;
Locale? _locale;
bool get showHiddenFiles => _showHiddenFiles;
String get downloadMirrorId => _downloadMirrorId;
DistroMirror get downloadMirror => DistroRepository.getMirrorById(_downloadMirrorId);
@Deprecated('本地补全已完全移除')
bool get enableLocalCompletion => false;
bool get enableLspCompletion => _enableLspCompletion;
ThemeMode get appThemeMode => _appThemeMode;
Color get appThemeColor => _appThemeColor;
@@ -291,10 +291,10 @@ class SettingsProvider extends ChangeNotifier {
_showHiddenFiles = savedShowHiddenFiles;
}
//设置下载源镜像配置
final savedMirrorId = prefs.getString(_keyDownloadMirrorId);
if (savedMirrorId != null && savedMirrorId.isNotEmpty) {
_downloadMirrorId = savedMirrorId;
//设置代码补全
final savedEnableLspCompletion = prefs.getBool(_keyEnableLspCompletion);
if (savedEnableLspCompletion != null) {
_enableLspCompletion = savedEnableLspCompletion;
}
//设置语言
@@ -482,14 +482,18 @@ class SettingsProvider extends ChangeNotifier {
} catch (_) {}
}
/// 设置系统安装包下载镜像源
Future<void> setDownloadMirrorId(String mirrorId) async {
if (_downloadMirrorId == mirrorId) return;
_downloadMirrorId = mirrorId;
/// 设置是否启用本地基础补全(本地补全已移除,保留此方法仅作向后兼容)
@Deprecated('本地补全已完全移除')
Future<void> setEnableLocalCompletion(bool enable) async {}
/// 设置是否启用LSP后端代码补全
Future<void> setEnableLspCompletion(bool enable) async {
if (_enableLspCompletion == enable) return;
_enableLspCompletion = enable;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyDownloadMirrorId, mirrorId);
await prefs.setBool(_keyEnableLspCompletion, enable);
} catch (_) {}
}
}
@@ -0,0 +1,123 @@
import '../../models/distro_manifest.dart';
import '../../models/notice_item.dart';
import '../distro_manager.dart';
import '../internal_engine_service.dart';
import 'background_task.dart';
/// Ubuntu APT 软件包安装与卸载任务
///
/// 运行在 [TaskExecutionScope.packageManager] 互斥域内,
/// 保证同一时刻全局只有一个 apt-get/dpkg 命令执行,杜绝锁冲突。
class AptPackageTask extends BackgroundTask<bool> {
final String packageName;
final String componentDisplayName;
final bool isUninstall;
@override
final TaskPriority priority;
AptPackageTask({
required this.packageName,
required this.componentDisplayName,
this.isUninstall = false,
this.priority = TaskPriority.userInitiated,
});
@override
String get id => 'pkg:${isUninstall ? 'remove' : 'install'}:$packageName';
@override
TaskExecutionScope get scope => TaskExecutionScope.packageManager;
@override
NoticeText? createNoticeText(
BackgroundTaskState state, {
String? detail,
String? error,
}) {
switch (state) {
case BackgroundTaskState.queued:
return ComponentInstallPhaseText(
componentName: componentDisplayName,
isUninstall: isUninstall,
isQueued: true,
);
case BackgroundTaskState.running:
return ComponentInstallPhaseText(
componentName: componentDisplayName,
isUninstall: isUninstall,
isQueued: false,
detail: detail,
);
case BackgroundTaskState.completed:
return ComponentInstallDoneText(
componentName: componentDisplayName,
isUninstall: isUninstall,
);
case BackgroundTaskState.failed:
return ComponentInstallFailureText(
componentName: componentDisplayName,
isUninstall: isUninstall,
error: error,
);
case BackgroundTaskState.cancelled:
return null;
}
}
@override
Future<bool> execute(TaskExecutionContext context) async {
final engine = InternalEngineService.instance;
if (!await engine.isEngineInstalled() || packageName.trim().isEmpty) {
return false;
}
final rootfs = await engine.getRootfsDir();
final cmd = isUninstall
? 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; '
'dpkg --configure -a 2>/dev/null || true; '
'apt-get remove --purge -y ${packageName.trim()} && '
'apt-get autoremove -y'
: 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; '
'dpkg --configure -a 2>/dev/null || true; '
'apt-get update && '
'apt-get install -y --no-install-recommends ${packageName.trim()}';
final res = await DistroManager().runHeadlessCommand(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: cmd,
timeout: isUninstall ? const Duration(minutes: 5) : const Duration(minutes: 10),
cancelToken: context.cancelToken,
onStdout: (chunk) {
final line = chunk.trim();
if (line.isNotEmpty) {
context.updateDetail(line);
}
},
);
if (context.isCancelled) {
// 被取消后,进行一次后台锁自愈
_healDpkgLock(rootfs);
return false;
}
final success = res != null && res.exitCode == 0;
if (!success) {
throw Exception(
'apt process exited with code ${res?.exitCode ?? -1}: ${res?.stderr}',
);
}
return true;
}
void _healDpkgLock(dynamic rootfs) {
DistroManager().runHeadlessCommand(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: 'dpkg --configure -a 2>/dev/null || true',
timeout: const Duration(seconds: 30),
);
}
}
@@ -0,0 +1,91 @@
import '../../models/notice_item.dart';
import '../distro_manager.dart';
/// 任务执行范围(互斥域)
enum TaskExecutionScope {
/// 包管理器域:严格单线程串行(Ubuntu 下 apt-get / dpkg 独占锁保护)
packageManager,
/// 独占域:暂停所有其它任务,独自运行
exclusive,
/// 共享只读域:允许与其他非 exclusive 任务并发运行(如无副作用的检查、扫描)
shared,
}
/// 任务优先级(值越大越靠前出队)
enum TaskPriority implements Comparable<TaskPriority> {
/// 用户主动触发(如用户点击安装/卸载组件):最高优先
userInitiated(100),
/// 项目生命周期触发(如打开工程后的模块依赖探测):标准优先级
projectLifecycle(50),
/// 静默预热/后台空闲:低优先级
backgroundIdle(10);
final int value;
const TaskPriority(this.value);
@override
int compareTo(TaskPriority other) => other.value.compareTo(value);
}
/// 任务执行状态
enum BackgroundTaskState {
queued,
running,
completed,
failed,
cancelled,
}
/// 任务执行上下文
class TaskExecutionContext {
/// 用于中断底层进程的取消令牌
final HeadlessCancelToken cancelToken;
/// 实时输出行/副标题更新
final void Function(String line) updateDetail;
/// 进度百分比更新(0.0 ~ 1.0)
final void Function(double? progress) updateProgress;
const TaskExecutionContext({
required this.cancelToken,
required this.updateDetail,
required this.updateProgress,
});
bool get isCancelled => cancelToken.isCancelled;
}
/// 全局后台任务抽象接口
abstract class BackgroundTask<T> {
/// 全局唯一任务 ID(同时作为右上角通知 NoticeItem 的 id)
String get id;
/// 互斥作用域
TaskExecutionScope get scope;
/// 优先级
TaskPriority get priority => TaskPriority.projectLifecycle;
/// 是否在 NoticeCenter 中展示右上角悬浮通知
bool get showNotice => true;
/// 根据状态生成对应的结构化通知文案(无硬编码)
NoticeText? createNoticeText(BackgroundTaskState state, {String? detail, String? error});
/// 核心执行体
Future<T> execute(TaskExecutionContext context);
/// 取消回调
void onCancelled() {}
/// 失败回调
void onFailure(Object error, StackTrace stackTrace) {}
/// 成功回调
void onSuccess(T result) {}
}
@@ -0,0 +1,302 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../models/notice_item.dart';
import '../../providers/notice_center.dart';
import '../distro_manager.dart';
import 'background_task.dart';
/// 待执行任务包装条目
class _QueuedTaskEntry<T> {
final BackgroundTask<T> task;
final Completer<T> completer;
final HeadlessCancelToken cancelToken;
_QueuedTaskEntry({
required this.task,
required this.completer,
required this.cancelToken,
});
}
/// 统一后台任务调度中心
///
/// 核心职责:
/// 1. 任务排队与优先级排序;
/// 2. [TaskExecutionScope] 资源互斥域管控(针对 Ubuntu 单底座 apt/dpkg 独占锁,严格串行 packageManager 域);
/// 3. 与 [NoticeCenter] 双向联动(反映入队、执行中、成功淡出、失败驻留,UI 取消联动底层进程中断);
/// 4. 任务取消与失败时的环境自愈保护。
class BackgroundTaskScheduler {
BackgroundTaskScheduler._();
static final BackgroundTaskScheduler instance = BackgroundTaskScheduler._();
NoticeCenter? _noticeCenter;
/// 待执行任务队列
final List<_QueuedTaskEntry> _queue = [];
/// 正在运行的任务集合
final Map<String, _QueuedTaskEntry> _runningTasks = {};
/// 绑定全局通知中心
void attachNoticeCenter(NoticeCenter noticeCenter) {
_noticeCenter = noticeCenter;
}
/// 提交一个后台任务
Future<T> submit<T>(BackgroundTask<T> task) {
final completer = Completer<T>();
final cancelToken = HeadlessCancelToken();
final entry = _QueuedTaskEntry<T>(
task: task,
completer: completer,
cancelToken: cancelToken,
);
// 插入并按优先级降序排序(优先级高在先)
_queue.add(entry);
_queue.sort((a, b) => a.task.priority.compareTo(b.task.priority));
// 通知中心同步:若任务配置了通知,则先发入队卡片
if (task.showNotice && _noticeCenter != null) {
final text = task.createNoticeText(BackgroundTaskState.queued);
if (text != null) {
_noticeCenter!.push(
NoticeItem(
id: task.id,
kind: NoticeKind.progress,
text: text,
onUserDismiss: () => cancel(task.id),
),
);
}
}
_scheduleNext();
return completer.future;
}
/// 取消指定 ID 的任务(若在队列中则移除,若在运行中则触发 cancelToken)
void cancel(String taskId) {
// 1. 检查队列中尚未启动的任务
final qIndex = _queue.indexWhere((e) => e.task.id == taskId);
if (qIndex != -1) {
final entry = _queue.removeAt(qIndex);
entry.cancelToken.cancel();
try {
entry.task.onCancelled();
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
if (!entry.completer.isCompleted) {
entry.completer.completeError(
const CancellationException('Task cancelled before start'),
);
}
_noticeCenter?.dismiss(taskId);
return;
}
// 2. 检查正在运行的任务
final running = _runningTasks[taskId];
if (running != null) {
running.cancelToken.cancel();
try {
running.task.onCancelled();
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
// 不直接 dismiss,等待执行体退出抛出/退出时自然结算
}
}
/// 是否有任务正在占用 packageManager 锁
bool get isPackageManagerBusy {
return _runningTasks.values
.any((e) => e.task.scope == TaskExecutionScope.packageManager);
}
/// 是否有独占任务正在运行
bool get isExclusiveBusy {
return _runningTasks.values
.any((e) => e.task.scope == TaskExecutionScope.exclusive);
}
/// 正在运行的任务总数
int get runningCount => _runningTasks.length;
/// 等待队列中的任务总数
int get queuedCount => _queue.length;
/// 核心调度分配逻辑
void _scheduleNext() {
if (_queue.isEmpty) return;
// 若当前有 exclusive 任务正在运行,阻塞一切新任务
if (isExclusiveBusy) return;
for (int i = 0; i < _queue.length; i++) {
final candidate = _queue[i];
final scope = candidate.task.scope;
if (scope == TaskExecutionScope.exclusive) {
// 独占任务必须等待当前所有运行中的任务全部结束才能起跑
if (_runningTasks.isEmpty) {
_queue.removeAt(i);
_executeTask(candidate);
}
return;
} else if (scope == TaskExecutionScope.packageManager) {
// 包管理器任务要求单线排他
if (!isPackageManagerBusy) {
_queue.removeAt(i);
_executeTask(candidate);
// 继续检查后续队列中是否有可以并发执行的 shared 任务
_scheduleNext();
return;
}
} else if (scope == TaskExecutionScope.shared) {
// 共享任务可以并发运行(受最大并发限制,如 4)
if (_runningTasks.length < 4) {
_queue.removeAt(i);
_executeTask(candidate);
_scheduleNext();
return;
}
}
}
}
Future<void> _executeTask(_QueuedTaskEntry entry) async {
final task = entry.task;
_runningTasks[task.id] = entry;
// 更新为运行中通知
if (task.showNotice && _noticeCenter != null) {
final text = task.createNoticeText(BackgroundTaskState.running);
if (text != null) {
_noticeCenter!.update(
task.id,
kind: NoticeKind.progress,
text: text,
);
}
}
final context = TaskExecutionContext(
cancelToken: entry.cancelToken,
updateDetail: (detail) {
if (!entry.cancelToken.isCancelled && task.showNotice && _noticeCenter != null) {
final text = task.createNoticeText(BackgroundTaskState.running, detail: detail);
if (text != null) {
_noticeCenter!.update(task.id, text: text);
}
}
},
updateProgress: (progress) {
if (!entry.cancelToken.isCancelled && task.showNotice && _noticeCenter != null) {
_noticeCenter!.update(task.id, progress: progress);
}
},
);
try {
final result = await task.execute(context);
_runningTasks.remove(task.id);
if (entry.cancelToken.isCancelled) {
try {
task.onCancelled();
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
_noticeCenter?.dismiss(task.id);
if (!entry.completer.isCompleted) {
entry.completer.completeError(
const CancellationException('Task was cancelled during execution'),
);
}
} else {
try {
task.onSuccess(result);
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onSuccess 异常: ');
}
if (task.showNotice && _noticeCenter != null) {
final doneText = task.createNoticeText(BackgroundTaskState.completed);
if (doneText != null) {
_noticeCenter!.complete(
task.id,
kind: NoticeKind.success,
text: doneText,
autoCloseAfter: const Duration(seconds: 3),
);
} else {
_noticeCenter!.dismiss(task.id);
}
}
if (!entry.completer.isCompleted) {
entry.completer.complete(result);
}
}
} catch (e, stack) {
_runningTasks.remove(task.id);
if (entry.cancelToken.isCancelled) {
try {
task.onCancelled();
} catch (err) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
_noticeCenter?.dismiss(task.id);
if (!entry.completer.isCompleted) {
entry.completer.completeError(
const CancellationException('Task was cancelled'),
);
}
} else {
try {
task.onFailure(e, stack);
} catch (err) {
debugPrint('[BackgroundTaskScheduler] onFailure 异常: ');
}
if (task.showNotice && _noticeCenter != null) {
final failText = task.createNoticeText(
BackgroundTaskState.failed,
error: e.toString(),
);
if (failText != null) {
_noticeCenter!.complete(
task.id,
kind: NoticeKind.failure,
text: failText,
sticky: true,
);
} else {
_noticeCenter!.dismiss(task.id);
}
}
if (!entry.completer.isCompleted) {
entry.completer.completeError(e, stack);
}
}
} finally {
// 触发后续调度
_scheduleNext();
}
}
}
/// 取消异常定义
class CancellationException implements Exception {
final String message;
const CancellationException([this.message = 'Operation was cancelled']);
@override
String toString() => 'CancellationException: ';
}
@@ -0,0 +1,36 @@
import '../../models/notice_item.dart';
import 'background_task.dart';
/// 包装一个函数执行体到后台调度系统(如探测中的依赖自动安装等)
class GenericBackgroundTask<T> extends BackgroundTask<T> {
@override
final String id;
@override
final TaskExecutionScope scope;
@override
final TaskPriority priority;
@override
final bool showNotice;
final Future<T> Function(TaskExecutionContext context) runner;
final NoticeText? Function(BackgroundTaskState state, {String? detail, String? error})? noticeTextBuilder;
GenericBackgroundTask({
required this.id,
required this.scope,
this.priority = TaskPriority.projectLifecycle,
this.showNotice = false,
required this.runner,
this.noticeTextBuilder,
});
@override
NoticeText? createNoticeText(BackgroundTaskState state, {String? detail, String? error}) {
return noticeTextBuilder?.call(state, detail: detail, error: error);
}
@override
Future<T> execute(TaskExecutionContext context) {
return runner(context);
}
}
@@ -0,0 +1,136 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:re_editor/re_editor.dart';
import '../fuzzy_matcher.dart';
import '../providers/completion_provider.dart';
import 'completion_types.dart';
/// 补全调度引擎 (Completion Engine)
///
/// 核心职责:
/// 1. 0ms 同步聚合本地所有同步 Provider(关键字、词法启发提取),保证首帧流畅弹出;
/// 2. 异步发起 LSP 或远程 Provider 请求;
/// 3. 基于 requestId 与版本号防抖校验,杜绝陈旧回包覆盖;
/// 4. 统一执行 Fuzzy 模糊匹配打分、sortText 权重排序与截断;
/// 5. 动态向绑定的 ValueNotifier 推流更新,实现平滑渐进增强。
class CompletionEngine {
CompletionEngine({
required this.providers,
this.maxSuggestions = 40,
});
final List<CompletionProvider> providers;
final int maxSuggestions;
int _lastRequestId = 0;
/// 异步直接请求补全(专为 LSP 异步语义流优化设计)
Future<CodeAutocompleteEditingValue?> requestCompletionsAsync(
CompletionContext context,
) async {
final currentRequestId = ++_lastRequestId;
final currentInput = context.input;
try {
final results = await Future.wait(
providers.map((p) async {
try {
final res = await p.provideCompletions(context);
return res;
} catch (_) {
return <SmartPrompt>[];
}
}),
);
// 请求过期(用户已键入新内容或已移动光标),直接废弃
if (currentRequestId != _lastRequestId) return null;
final allPrompts = <SmartPrompt>[];
final seenWords = <String>{};
for (final list in results) {
for (final p in list) {
if (seenWords.add(p.word)) {
allPrompts.add(p);
}
}
}
if (allPrompts.isEmpty) return null;
return scoreAndFilter(allPrompts, currentInput);
} catch (_) {
return null;
}
}
/// 兼容推流式调用
CodeAutocompleteEditingValue? requestCompletions(
CompletionContext context, {
ValueNotifier<CodeAutocompleteEditingValue>? notifier,
}) {
if (notifier != null) {
requestCompletionsAsync(context).then((value) {
if (value != null) {
notifier.value = value;
}
});
}
return null;
}
/// 模糊匹配打分、权重排序与截取
CodeAutocompleteEditingValue? scoreAndFilter(List<SmartPrompt> candidates, String input) {
if (candidates.isEmpty) {
return null;
}
final List<SmartPrompt> matchedPrompts = [];
for (final candidate in candidates) {
if (input.isEmpty) {
matchedPrompts.add(candidate.copyWithScore(
score: 100,
matchedIndices: const [],
));
} else {
final result = FuzzyMatcher.match(input, candidate.word);
if (result.isMatch) {
matchedPrompts.add(candidate.copyWithScore(
score: result.score,
matchedIndices: result.matchedIndices,
));
}
}
}
if (matchedPrompts.isEmpty) {
return null;
}
// 按照得分降序排序,相同得分若有 LSP sortText 则依据 sortText 升序,否则按字典序升序
matchedPrompts.sort((a, b) {
final scoreCompare = b.score.compareTo(a.score);
if (scoreCompare != 0) return scoreCompare;
if (a.sortText != null && b.sortText != null) {
final sortCompare = a.sortText!.compareTo(b.sortText!);
if (sortCompare != 0) return sortCompare;
}
return a.word.compareTo(b.word);
});
// 截取前 maxSuggestions 条最佳结果,保证 60fps 流畅渲染
final limitedPrompts = matchedPrompts.take(maxSuggestions).toList();
return CodeAutocompleteEditingValue(
input: input,
prompts: limitedPrompts,
index: 0,
);
}
void dispose() {
_lastRequestId++;
for (final provider in providers) {
provider.dispose();
}
}
}
@@ -0,0 +1,112 @@
import 'package:flutter/widgets.dart';
import 'package:re_editor/re_editor.dart';
import '../fuzzy_matcher.dart';
/// 补全候选词类别
enum SmartPromptKind {
keyword,
function,
field,
type,
constant,
word,
}
/// 具有模糊匹配打分与高亮索引的工业级智能补全 Prompt
class SmartPrompt extends CodePrompt {
SmartPrompt({
required super.word,
this.type,
this.kind = SmartPromptKind.word,
this.customAutocomplete,
this.parameters = const {},
this.score = 0,
this.matchedIndices = const [],
this.detail,
this.documentation,
this.sortText,
});
final String? type;
final SmartPromptKind kind;
final CodeAutocompleteResult? customAutocomplete;
final Map<String, String> parameters;
final String? detail;
final String? documentation;
final String? sortText;
int score;
List<int> matchedIndices;
@override
CodeAutocompleteResult get autocomplete {
if (customAutocomplete != null) {
return customAutocomplete!;
}
if (kind == SmartPromptKind.function && parameters.isNotEmpty) {
final paramStr = parameters.keys.join(', ');
return CodeAutocompleteResult(
input: '',
word: '$word($paramStr)',
selection: TextSelection.collapsed(offset: word.length + 1),
);
}
return CodeAutocompleteResult.fromWord(word);
}
@override
bool match(String input) {
if (input.isEmpty) return true;
final res = FuzzyMatcher.match(input, word);
if (res.isMatch) {
score = res.score;
matchedIndices = res.matchedIndices;
return true;
}
return false;
}
SmartPrompt copyWithScore({
required int score,
required List<int> matchedIndices,
}) {
return SmartPrompt(
word: word,
type: type,
kind: kind,
customAutocomplete: customAutocomplete,
parameters: parameters,
score: score,
matchedIndices: matchedIndices,
detail: detail,
documentation: documentation,
sortText: sortText,
);
}
}
/// 代码补全上下文请求参数
class CompletionContext {
final String input;
final String? triggerCharacter;
final String? target;
final String? filePath;
final int lineIndex;
final int characterOffset;
final CodeLine codeLine;
final CodeLines? codeLines;
final CodeLineSelection selection;
const CompletionContext({
required this.input,
this.triggerCharacter,
this.target,
this.filePath,
required this.lineIndex,
required this.characterOffset,
required this.codeLine,
this.codeLines,
required this.selection,
});
bool get isDotTrigger => triggerCharacter == '.';
}
@@ -0,0 +1,247 @@
import 'dart:math';
/// 模糊匹配与打字纠错结果
class FuzzyMatchResult {
const FuzzyMatchResult({
required this.isMatch,
required this.score,
this.matchedIndices = const [],
});
static const notMatched = FuzzyMatchResult(isMatch: false, score: -1);
final bool isMatch;
final int score;
final List<int> matchedIndices;
}
/// 工业级代码模糊匹配与容错纠错打分器
class FuzzyMatcher {
const FuzzyMatcher();
/// 对 [pattern](用户输入)与 [target](候选词)进行匹配打分
///
/// 支持:
/// 1. 精确匹配 / 精确前缀匹配 (Prefix Match)
/// 2. 忽略大小写前缀匹配 (Case-insensitive Prefix)
/// 3. 驼峰与下划线缩写匹配 (CamelCase / Snake_case)
/// 4. 连续子序列匹配 (Subsequence Match with Consecutive Bonus)
/// 5. 打字手误纠错 (Typo Tolerance / Levenshtein Distance)
static FuzzyMatchResult match(String pattern, String target) {
if (pattern.isEmpty) {
return const FuzzyMatchResult(isMatch: true, score: 100);
}
if (target.isEmpty) {
return FuzzyMatchResult.notMatched;
}
// 1. 完全相同
if (pattern == target) {
return FuzzyMatchResult(
isMatch: true,
score: 3000,
matchedIndices: List.generate(pattern.length, (i) => i),
);
}
// 2. 严格区分大小写的前缀匹配 (最高优先级)
if (target.startsWith(pattern)) {
final score = 2000 - (target.length - pattern.length);
return FuzzyMatchResult(
isMatch: true,
score: score,
matchedIndices: List.generate(pattern.length, (i) => i),
);
}
final lowerPattern = pattern.toLowerCase();
final lowerTarget = target.toLowerCase();
// 3. 忽略大小写的前缀匹配
if (lowerTarget.startsWith(lowerPattern)) {
final score = 1500 - (target.length - pattern.length);
return FuzzyMatchResult(
isMatch: true,
score: score,
matchedIndices: List.generate(pattern.length, (i) => i),
);
}
// 4. 驼峰与下划线缩写匹配 (例如 "fb" 匹配 "FloatingActionButton", "tv" 匹配 "text_view")
final camelMatch = _matchCamelOrSeparator(lowerPattern, target);
if (camelMatch.isMatch) {
return camelMatch;
}
// 5. 字符子序列匹配 (Subsequence Match)
final subseqMatch = _matchSubsequence(lowerPattern, lowerTarget, target);
if (subseqMatch.isMatch) {
return subseqMatch;
}
// 6. 拼写手误纠错 (Typo Tolerance / Levenshtein Distance)
// 当输入字符长度 >= 3 时,允许前缀 1 处编辑距离错误(如 prnt -> print, lenght -> length)
// 当输入字符长度 >= 6 时,允许前缀 2 处编辑距离错误
if (pattern.length >= 3) {
final typoMatch = _matchTypo(lowerPattern, lowerTarget, target);
if (typoMatch.isMatch) {
return typoMatch;
}
}
return FuzzyMatchResult.notMatched;
}
/// 驼峰与分隔符匹配
static FuzzyMatchResult _matchCamelOrSeparator(String lowerPattern, String target) {
final List<int> wordStartIndices = [];
for (int i = 0; i < target.length; i++) {
final char = target[i];
if (i == 0) {
wordStartIndices.add(i);
} else if (char == '_' || char == '-' || char == '.') {
if (i + 1 < target.length) {
wordStartIndices.add(i + 1);
}
} else {
final isUpper = char.toUpperCase() == char && char.toLowerCase() != char;
final prevChar = target[i - 1];
final isPrevLower = prevChar.toLowerCase() == prevChar && prevChar.toUpperCase() != prevChar;
if (isUpper && isPrevLower) {
wordStartIndices.add(i);
}
}
}
if (lowerPattern.length <= wordStartIndices.length) {
int pIdx = 0;
final List<int> matched = [];
for (final sIdx in wordStartIndices) {
if (pIdx < lowerPattern.length &&
target[sIdx].toLowerCase() == lowerPattern[pIdx]) {
matched.add(sIdx);
pIdx++;
}
}
if (pIdx == lowerPattern.length) {
final score = 1000 - (target.length - lowerPattern.length) * 2;
return FuzzyMatchResult(
isMatch: true,
score: max(score, 600),
matchedIndices: matched,
);
}
}
return FuzzyMatchResult.notMatched;
}
/// 子序列匹配(考虑连续命中加分)
static FuzzyMatchResult _matchSubsequence(
String lowerPattern,
String lowerTarget,
String target,
) {
int pIdx = 0;
int tIdx = 0;
final List<int> matched = [];
int consecutiveCount = 0;
int score = 700;
while (pIdx < lowerPattern.length && tIdx < lowerTarget.length) {
if (lowerPattern[pIdx] == lowerTarget[tIdx]) {
matched.add(tIdx);
// 大小写一致加分
if (pIdx < target.length && target[tIdx] == lowerPattern[pIdx]) {
score += 10;
}
// 连续匹配加分
if (matched.length > 1 && matched.last == matched[matched.length - 2] + 1) {
consecutiveCount++;
score += consecutiveCount * 25;
} else {
consecutiveCount = 0;
}
pIdx++;
}
tIdx++;
}
if (pIdx == lowerPattern.length) {
score -= matched.first * 15;
score -= (target.length - lowerPattern.length) * 2;
return FuzzyMatchResult(
isMatch: true,
score: max(score, 450),
matchedIndices: matched,
);
}
return FuzzyMatchResult.notMatched;
}
/// 打字手误纠错(基于编辑距离对比前缀)
static FuzzyMatchResult _matchTypo(
String lowerPattern,
String lowerTarget,
String target,
) {
final int pLen = lowerPattern.length;
final int minLen = max(1, pLen - 1);
final int maxLen = min(lowerTarget.length, pLen + 1);
int bestDistance = 999;
int bestPrefixLen = pLen;
for (int len = minLen; len <= maxLen; len++) {
final prefix = lowerTarget.substring(0, len);
final dist = _levenshteinDistance(lowerPattern, prefix);
if (dist < bestDistance) {
bestDistance = dist;
bestPrefixLen = len;
}
}
final int maxAllowedDist = pLen >= 6 ? 2 : 1;
if (bestDistance <= maxAllowedDist) {
final score = 380 - (bestDistance * 80) - (target.length - pLen);
return FuzzyMatchResult(
isMatch: true,
score: max(score, 150),
matchedIndices: List.generate(min(bestPrefixLen, target.length), (i) => i),
);
}
return FuzzyMatchResult.notMatched;
}
/// 计算两个字符串的 Levenshtein 编辑距离
static int _levenshteinDistance(String s1, String s2) {
if (s1 == s2) return 0;
if (s1.isEmpty) return s2.length;
if (s2.isEmpty) return s1.length;
List<int> prev = List<int>.generate(s2.length + 1, (i) => i);
List<int> curr = List<int>.filled(s2.length + 1, 0);
for (int i = 0; i < s1.length; i++) {
curr[0] = i + 1;
for (int j = 0; j < s2.length; j++) {
final cost = (s1[i] == s2[j]) ? 0 : 1;
curr[j + 1] = min(
curr[j] + 1,
min(
prev[j + 1] + 1,
prev[j] + cost,
),
);
}
final temp = prev;
prev = curr;
curr = temp;
}
return prev[s2.length];
}
}
@@ -0,0 +1,17 @@
import 'dart:async';
import '../core/completion_types.dart';
/// 补全数据源提供者抽象契约
abstract class CompletionProvider {
/// 提供者唯一标识
String get id;
/// 是否为异步远程数据源(如 LSP)
bool get isAsync => false;
/// 依据上下文提供补全候选项
FutureOr<List<SmartPrompt>> provideCompletions(CompletionContext context);
/// 释放资源
void dispose() {}
}
@@ -0,0 +1,96 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:re_editor/re_editor.dart';
import '../../lsp/lsp_manager.dart';
import '../../lsp/lsp_protocol.dart';
import '../core/completion_types.dart';
import 'completion_provider.dart';
/// 远程 LSP 语言服务补全数据源提供者
class LspCompletionProvider implements CompletionProvider {
const LspCompletionProvider();
@override
String get id => 'lsp';
@override
bool get isAsync => true;
@override
Future<List<SmartPrompt>> provideCompletions(CompletionContext context) async {
final filePath = context.filePath;
if (filePath == null || filePath.isEmpty) {
return const [];
}
final session = LspManager.instance.getExistingSession(filePath);
if (session == null || !session.isInitialized) {
return const [];
}
final lspItems = await session.getCompletions(
filePath,
context.lineIndex,
context.characterOffset,
);
return lspItems.map(fromLspItem).toList();
}
/// 将 LSP 原始协议的 LspCompletionItem 转换为统一领域模型 SmartPrompt
static SmartPrompt fromLspItem(LspCompletionItem item) {
SmartPromptKind kind;
switch (item.kind) {
case 2: // Method
case 3: // Function
case 4: // Constructor
kind = SmartPromptKind.function;
break;
case 5: // Field
case 6: // Variable
case 10: // Property
kind = SmartPromptKind.field;
break;
case 7: // Class
case 8: // Interface
case 13: // Enum
case 22: // Struct
case 25: // TypeParameter
kind = SmartPromptKind.type;
break;
case 14: // Keyword
kind = SmartPromptKind.keyword;
break;
case 21: // Constant
kind = SmartPromptKind.constant;
break;
default:
kind = SmartPromptKind.word;
}
final insert = item.effectiveInsertText;
final word = item.label.isNotEmpty ? item.label : insert;
CodeAutocompleteResult? customAuto;
if (insert != word) {
customAuto = CodeAutocompleteResult(
input: '',
word: insert,
selection: TextSelection.collapsed(offset: insert.length),
);
}
return SmartPrompt(
word: word,
kind: kind,
type: item.detail,
detail: item.detail,
documentation: item.documentation,
sortText: item.sortText,
customAutocomplete: customAuto,
);
}
@override
void dispose() {}
}
@@ -0,0 +1,144 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:re_editor/re_editor.dart';
import 'core/completion_engine.dart';
import 'core/completion_types.dart';
import 'providers/completion_provider.dart';
import 'providers/lsp_completion_provider.dart';
export 'core/completion_engine.dart';
export 'core/completion_types.dart';
export 'providers/completion_provider.dart';
export 'providers/lsp_completion_provider.dart';
/// 工业级智能代码补全构建器适配器
///
/// 实现 re_editor 的 CodeAutocompletePromptsBuilder 协议,
/// 将编辑器的输入上下文规范化后,转派给 LSP CompletionEngine 异步调度处理。
class SmartCodeAutocompletePromptsBuilder implements CodeAutocompletePromptsBuilder {
SmartCodeAutocompletePromptsBuilder({
this.controller,
this.filePath,
this.enableLspCompletion = true,
@Deprecated('本地补全已完全移除,此参数无效') bool enableLocalCompletion = false,
@Deprecated('本地补全已完全移除,此参数无效') dynamic language,
@Deprecated('本地补全已完全移除,此参数无效') List<CodePrompt> keywordPrompts = const [],
@Deprecated('本地补全已完全移除,此参数无效') List<CodePrompt> directPrompts = const [],
@Deprecated('本地补全已完全移除,此参数无效') Map<String, List<CodePrompt>> relatedPrompts = const {},
List<CompletionProvider>? customProviders,
}) {
final providers = <CompletionProvider>[
if (customProviders != null)
...customProviders
else if (enableLspCompletion)
const LspCompletionProvider(),
];
engine = CompletionEngine(providers: providers);
}
final CodeLineEditingController? controller;
final String? filePath;
final bool enableLspCompletion;
late final CompletionEngine engine;
/// 当前活跃的悬浮面板 ValueNotifier(由 CodeAutocompleteView 动态注入绑定)
ValueNotifier<CodeAutocompleteEditingValue>? activeNotifier;
@override
FutureOr<CodeAutocompleteEditingValue?> build(
BuildContext context,
CodeLine codeLine,
CodeLineSelection selection,
) {
if (!enableLspCompletion || engine.providers.isEmpty) {
return null;
}
final String text = codeLine.text;
if (selection.extentOffset > text.length) {
return null;
}
final Characters charactersBefore = text.substring(0, selection.extentOffset).characters;
if (charactersBefore.isEmpty) {
return null;
}
// 检查是否在普通闭合双引号或单引号字符串中(简易校验)
final String linePrefix = text.substring(0, selection.extentOffset);
final int singleQuoteCount = "'".allMatches(linePrefix).length;
final int doubleQuoteCount = '"'.allMatches(linePrefix).length;
if (singleQuoteCount % 2 == 1 || doubleQuoteCount % 2 == 1) {
// 位于字符串字面量内部,不触发代码智能补全
return null;
}
final String input;
String? triggerCharacter;
String? target;
if (charactersBefore.takeLast(1).string == '.') {
triggerCharacter = '.';
input = '';
int start = charactersBefore.length - 2;
for (; start >= 0; start--) {
final char = charactersBefore.elementAt(start);
if (!_isValidIdentifierChar(char)) {
break;
}
}
target = charactersBefore.getRange(start + 1, charactersBefore.length - 1).string;
} else {
int start = charactersBefore.length - 1;
for (; start >= 0; start--) {
final char = charactersBefore.elementAt(start);
if (!_isValidIdentifierChar(char)) {
break;
}
}
input = charactersBefore.getRange(start + 1, charactersBefore.length).string;
if (input.isEmpty) {
return null;
}
if (start > 0 && charactersBefore.elementAt(start) == '.') {
triggerCharacter = '.';
final int mark = start;
for (start = start - 1; start >= 0; start--) {
final char = charactersBefore.elementAt(start);
if (!_isValidIdentifierChar(char)) {
break;
}
}
target = charactersBefore.getRange(start + 1, mark).string;
}
}
final completionContext = CompletionContext(
input: input,
triggerCharacter: triggerCharacter,
target: target,
filePath: filePath,
lineIndex: selection.extentIndex,
characterOffset: selection.extentOffset,
codeLine: codeLine,
codeLines: controller?.codeLines,
selection: selection,
);
// 原生异步发起 LSP 智能语义补全请求
return engine.requestCompletionsAsync(completionContext);
}
static bool _isValidIdentifierChar(String char) {
if (char.isEmpty) return false;
final code = char.codeUnitAt(0);
return (code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) || // a-z
(code >= 48 && code <= 57) || // 0-9
code == 95; // _
}
}
-448
View File
@@ -1,448 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../models/distro_manifest.dart';
import 'distro_image_resolver.dart';
/// 系统包下载状态枚举
enum DistroDownloadState {
notStarted,
downloading,
completed,
cancelled,
failed,
}
/// 单个系统的下载状态快照
class DistroDownloadProgress {
final String distroId;
final DistroDownloadState state;
final double progress; // 0.0 ~ 1.0
final int receivedBytes;
final int totalBytes;
final String? errorMessage;
final File? targetFile;
const DistroDownloadProgress({
required this.distroId,
required this.state,
this.progress = 0.0,
this.receivedBytes = 0,
this.totalBytes = -1,
this.errorMessage,
this.targetFile,
});
DistroDownloadProgress copyWith({
DistroDownloadState? state,
double? progress,
int? receivedBytes,
int? totalBytes,
String? errorMessage,
File? targetFile,
}) {
return DistroDownloadProgress(
distroId: distroId,
state: state ?? this.state,
progress: progress ?? this.progress,
receivedBytes: receivedBytes ?? this.receivedBytes,
totalBytes: totalBytes ?? this.totalBytes,
errorMessage: errorMessage ?? this.errorMessage,
targetFile: targetFile ?? this.targetFile,
);
}
}
/// 下载被取消异常
class DistroDownloadCancelledException implements Exception {
final String message;
const DistroDownloadCancelledException([this.message = 'Download cancelled']);
@override
String toString() => message;
}
/// 全局异步系统镜像下载管理器(单例模式)
class DistroDownloadManager extends ChangeNotifier {
static final DistroDownloadManager _instance = DistroDownloadManager._internal();
factory DistroDownloadManager() => _instance;
DistroDownloadManager._internal();
final Map<String, DistroDownloadProgress> _progressMap = {};
final Map<String, HttpClientRequest> _activeRequests = {};
final Map<String, HttpClient> _activeClients = {};
final Map<String, StreamSubscription<List<int>>> _activeSubscriptions = {};
final Map<String, IOSink> _activeSinks = {};
final Map<String, Completer<void>> _activeCompleters = {};
final Set<String> _cancelledDistroIds = {};
@visibleForTesting
Directory? customPackagesDir;
/// 获取系统安装包持久化存储目录: `<app_dir>/distro_packages`
Future<Directory> getPackagesDir() async {
if (customPackagesDir != null) return customPackagesDir!;
final appDir = await getApplicationSupportDirectory();
final dir = Directory(p.join(appDir.path, 'distro_packages'));
if (!dir.existsSync()) {
dir.createSync(recursive: true);
}
return dir;
}
/// 获取指定系统的安装包文件对象
Future<File> getPackageFile(String distroId, [String? downloadUrl]) async {
final dir = await getPackagesDir();
final ext = (downloadUrl?.endsWith('.tar.gz') ?? false) ? '.tar.gz' : '.tar.xz';
final targetFile = File(p.join(dir.path, '${distroId}_rootfs$ext'));
if (targetFile.existsSync()) return targetFile;
final altExt = ext == '.tar.xz' ? '.tar.gz' : '.tar.xz';
final altFile = File(p.join(dir.path, '${distroId}_rootfs$altExt'));
if (altFile.existsSync()) return altFile;
return targetFile;
}
/// 检测指定系统的离线安装包是否已下载完备
Future<bool> isPackageDownloaded(String distroId, [String? downloadUrl]) async {
final dir = await getPackagesDir();
final xzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.xz'));
final gzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.gz'));
return (xzFile.existsSync() && xzFile.lengthSync() > 0) ||
(gzFile.existsSync() && gzFile.lengthSync() > 0);
}
/// 物理删除已下载的系统安装包
Future<void> deletePackage(String distroId, [String? downloadUrl]) async {
if (isDownloading(distroId)) {
await cancelDownload(distroId);
}
final dir = await getPackagesDir();
final files = [
File(p.join(dir.path, '${distroId}_rootfs.tar.xz')),
File(p.join(dir.path, '${distroId}_rootfs.tar.gz')),
];
for (final f in files) {
if (f.existsSync()) {
try {
f.deleteSync();
} catch (_) {}
}
}
_progressMap.remove(distroId);
notifyListeners();
}
/// 获取所有正在跟踪的下载任务快照
Map<String, DistroDownloadProgress> get allProgress => Map.unmodifiable(_progressMap);
/// 查询指定系统的下载状态
DistroDownloadProgress? getProgress(String distroId) => _progressMap[distroId];
/// 是否正在下载
bool isDownloading(String distroId) {
final status = _progressMap[distroId];
return status != null && status.state == DistroDownloadState.downloading;
}
/// 启动异步流式下载
Future<File?> startDownload({
required String distroId,
required String downloadUrl,
DistroMirror? mirror,
DistroManifestItem? manifestItem,
}) async {
if (isDownloading(distroId)) return null;
// 资源检测:若本地已存在完整的离线镜像包,拒绝重复下载并直接返回已有文件
if (await isPackageDownloaded(distroId, downloadUrl)) {
final existingFile = await getPackageFile(distroId, downloadUrl);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
targetFile: existingFile,
);
notifyListeners();
return existingFile;
}
// 清除历史取消标记
_cancelledDistroIds.remove(distroId);
// 状态更新为 downloading
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.downloading,
progress: 0.0,
);
notifyListeners();
String actualDownloadUrl = downloadUrl;
if (manifestItem != null && manifestItem.lxcSpec != null) {
try {
final activeMirror = mirror ?? DistroRepository.defaultMirror;
actualDownloadUrl = await DistroImageResolver().resolveDownloadUrl(
item: manifestItem,
arch: DistroManifestItem.currentArch,
mirror: activeMirror,
);
} catch (e) {
if (_cancelledDistroIds.contains(distroId)) {
_cleanupCancelledState(distroId);
return null;
}
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.failed,
errorMessage: e.toString(),
);
notifyListeners();
return null;
}
}
if (_cancelledDistroIds.contains(distroId)) {
_cleanupCancelledState(distroId);
return null;
}
// 二次资源检测:解析目标 URL 后再次检测文件是否完备
if (await isPackageDownloaded(distroId, actualDownloadUrl)) {
final existingFile = await getPackageFile(distroId, actualDownloadUrl);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
targetFile: existingFile,
);
notifyListeners();
return existingFile;
}
final targetFile = await getPackageFile(distroId, actualDownloadUrl);
final partFilePath = '${targetFile.path}.part';
final partFile = File(partFilePath);
HttpClient? client;
IOSink? sink;
StreamSubscription<List<int>>? subscription;
final completer = Completer<void>();
_activeCompleters[distroId] = completer;
try {
if (partFile.existsSync()) {
try {
partFile.deleteSync();
} catch (_) {}
}
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
client = HttpClient()
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
_activeClients[distroId] = client;
final uri = Uri.parse(actualDownloadUrl);
final request = await client.getUrl(uri);
_activeRequests[distroId] = request;
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
final response = await request.close();
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
if (response.statusCode != HttpStatus.ok) {
throw HttpException('HTTP Error: ${response.statusCode} ${response.reasonPhrase}');
}
final total = response.contentLength;
int received = 0;
sink = partFile.openWrite();
_activeSinks[distroId] = sink;
subscription = response.listen(
(chunk) {
if (_cancelledDistroIds.contains(distroId)) {
subscription?.cancel();
return;
}
sink?.add(chunk);
received += chunk.length;
final prog = total > 0 ? (received / total).clamp(0.0, 1.0) : 0.0;
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.downloading,
progress: prog,
receivedBytes: received,
totalBytes: total,
);
notifyListeners();
},
onDone: () async {
if (_cancelledDistroIds.contains(distroId)) {
if (!completer.isCompleted) {
completer.completeError(const DistroDownloadCancelledException());
}
return;
}
try {
await sink?.flush();
await sink?.close();
sink = null;
} catch (_) {}
if (!completer.isCompleted) {
completer.complete();
}
},
onError: (e) {
if (!completer.isCompleted) {
completer.completeError(e);
}
},
cancelOnError: true,
);
_activeSubscriptions[distroId] = subscription;
await completer.future;
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
// 下载完成,原子重命名 .part -> targetFile
if (targetFile.existsSync()) {
targetFile.deleteSync();
}
partFile.renameSync(targetFile.path);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: received,
totalBytes: total,
targetFile: targetFile,
);
notifyListeners();
return targetFile;
} catch (e) {
final isCancelled = _cancelledDistroIds.contains(distroId) ||
e is DistroDownloadCancelledException;
// 无论如何先关闭写入流,确保文件句柄释放
try {
await sink?.close();
} catch (_) {}
// 清理临时文件
if (partFile.existsSync()) {
try {
partFile.deleteSync();
} catch (_) {}
}
if (isCancelled) {
_cleanupCancelledState(distroId);
} else {
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.failed,
errorMessage: e.toString(),
);
notifyListeners();
}
return null;
} finally {
_activeRequests.remove(distroId);
_activeSubscriptions.remove(distroId);
_activeSinks.remove(distroId);
_activeCompleters.remove(distroId);
final c = _activeClients.remove(distroId);
try {
c?.close(force: true);
} catch (_) {}
_cancelledDistroIds.remove(distroId);
}
}
/// 取消下载并清理已下载的临时缓存资源
Future<void> cancelDownload(String distroId) async {
_cancelledDistroIds.add(distroId);
// 1. 中断活跃 Completer
final completer = _activeCompleters.remove(distroId);
if (completer != null && !completer.isCompleted) {
completer.completeError(const DistroDownloadCancelledException());
}
// 2. 中断 Request 并强力关闭 HttpClient(立即熔断底层 TCP Socket,避免 sub.cancel() 陷入 socket 耗尽等待)
final request = _activeRequests.remove(distroId);
if (request != null) {
try {
request.abort();
} catch (_) {}
}
final client = _activeClients.remove(distroId);
if (client != null) {
try {
client.close(force: true);
} catch (_) {}
}
// 3. 取消活跃 Stream 订阅以停止接收数据包(不阻塞等待 drain)
final sub = _activeSubscriptions.remove(distroId);
if (sub != null) {
try {
unawaited(sub.cancel());
} catch (_) {}
}
// 4. 关闭文件写入流以释放文件句柄(Windows 平台必须关闭方可删除)
final sink = _activeSinks.remove(distroId);
if (sink != null) {
try {
await sink.close();
} catch (_) {}
}
// 5. 立即清除临时 .part 文件
try {
final dir = await getPackagesDir();
final partFiles = [
File(p.join(dir.path, '${distroId}_rootfs.tar.gz.part')),
File(p.join(dir.path, '${distroId}_rootfs.tar.xz.part')),
];
for (final f in partFiles) {
if (f.existsSync()) {
f.deleteSync();
}
}
} catch (_) {}
// 6. 重置状态并通知刷新
_cleanupCancelledState(distroId);
}
void _cleanupCancelledState(String distroId) {
_progressMap.remove(distroId);
notifyListeners();
}
/// 重置已完成或失败的状态
void resetState(String distroId) {
_progressMap.remove(distroId);
notifyListeners();
}
}
-183
View File
@@ -1,183 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import '../models/distro_manifest.dart';
/// LXC 镜像源索引行条目
class DistroIndexEntry {
final String distribution;
final String release;
final String arch;
final String variant;
final String buildDate;
final String path;
const DistroIndexEntry({
required this.distribution,
required this.release,
required this.arch,
required this.variant,
required this.buildDate,
required this.path,
});
factory DistroIndexEntry.fromLine(String line) {
final parts = line.trim().split(';');
if (parts.length < 6) {
throw FormatException('Invalid index line: $line');
}
return DistroIndexEntry(
distribution: parts[0],
release: parts[1],
arch: parts[2],
variant: parts[3],
buildDate: parts[4],
path: parts[5],
);
}
}
/// 发行版镜像真实下载链接解析器(遵循 LinuxContainers 标准 index-system 规范)
class DistroImageResolver {
static final DistroImageResolver _instance = DistroImageResolver._internal();
factory DistroImageResolver() => _instance;
DistroImageResolver._internal();
/// 缓存的解析结果 (key: "mirrorId:distroId:arch", value: url)
final Map<String, String> _resolvedUrlCache = {};
/// 缓存的 index-system 纯文本内容 (key: mirrorId, value: (cachedTime, content))
final Map<String, (DateTime, String)> _indexContentCache = {};
/// 索引缓存有效期 (1 小时)
static const Duration cacheTtl = Duration(hours: 1);
@visibleForTesting
String? customIndexContent;
/// 清空指定系统或所有缓存
void invalidateCache({String? distroId}) {
if (distroId != null) {
_resolvedUrlCache.removeWhere((key, _) => key.contains(':$distroId:'));
} else {
_resolvedUrlCache.clear();
_indexContentCache.clear();
}
}
/// 将系统架构枚举映射为 LXC 索引架构命名(arm64 -> arm64, x86_64 -> amd64)
static String toLxcArch(DistroArch arch) {
switch (arch) {
case DistroArch.arm64:
return 'arm64';
case DistroArch.x86_64:
return 'amd64';
}
}
/// 动态解析指定发行版在指定镜像源上的最新真实下载 URL
Future<String> resolveDownloadUrl({
required DistroManifestItem item,
required DistroArch arch,
required DistroMirror mirror,
bool forceRefresh = false,
}) async {
// 内置系统直接返回静态资源路径
if (item.isBuiltin) {
return item.packages[arch] ?? '';
}
final spec = item.lxcSpec;
if (spec == null) {
return item.packages[arch] ?? '';
}
final cacheKey = '${mirror.id}:${item.id}:${arch.name}';
if (!forceRefresh && _resolvedUrlCache.containsKey(cacheKey)) {
return _resolvedUrlCache[cacheKey]!;
}
// 1. 获取对应镜像源的 meta/1.0/index-system 索引
final indexContent = await _fetchIndexContent(mirror, forceRefresh: forceRefresh);
// 2. 解析为条目列表
final entries = parseIndex(indexContent);
final targetArch = toLxcArch(arch);
// 3. 匹配符合发行版、版本、变体及 CPU 架构的条目
final matching = entries.where((e) =>
e.distribution.toLowerCase() == spec.distribution.toLowerCase() &&
e.release.toLowerCase() == spec.release.toLowerCase() &&
e.arch.toLowerCase() == targetArch.toLowerCase() &&
e.variant.toLowerCase() == spec.variant.toLowerCase(),
).toList();
if (matching.isEmpty) {
throw HttpException(
'Image not found in mirror ${mirror.name}: ${spec.distribution}/${spec.release}/$targetArch',
);
}
// 4. 按 buildDate 降序排序,取最新一次构建
matching.sort((a, b) => b.buildDate.compareTo(a.buildDate));
final latestEntry = matching.first;
// 5. 组合目标真实 URL
final base = mirror.baseUrl.replaceAll(RegExp(r'/+$'), '');
final relPath = latestEntry.path.replaceAll(RegExp(r'^/+'), '');
final fullUrl = '$base/$relPath' 'rootfs.tar.xz';
_resolvedUrlCache[cacheKey] = fullUrl;
return fullUrl;
}
/// 解析 index-system 纯文本内容为条目列表
static List<DistroIndexEntry> parseIndex(String content) {
final lines = content.split('\n');
final List<DistroIndexEntry> list = [];
for (final line in lines) {
final trimmed = line.trim();
if (trimmed.isEmpty || trimmed.startsWith('#')) continue;
try {
list.add(DistroIndexEntry.fromLine(trimmed));
} catch (_) {}
}
return list;
}
/// 从网络拉取镜像源的 meta/1.0/index-system
Future<String> _fetchIndexContent(DistroMirror mirror, {bool forceRefresh = false}) async {
if (customIndexContent != null) {
return customIndexContent!;
}
final now = DateTime.now();
if (!forceRefresh && _indexContentCache.containsKey(mirror.id)) {
final (cachedAt, text) = _indexContentCache[mirror.id]!;
if (now.difference(cachedAt) < cacheTtl) {
return text;
}
}
HttpClient? client;
try {
client = HttpClient()
..connectionTimeout = const Duration(seconds: 15)
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
final indexUrl = '${mirror.baseUrl.replaceAll(RegExp(r'/+$'), '')}/meta/1.0/index-system';
final request = await client.getUrl(Uri.parse(indexUrl));
final response = await request.close().timeout(const Duration(seconds: 20));
if (response.statusCode != HttpStatus.ok) {
throw HttpException('Failed to fetch mirror index from ${mirror.name}: HTTP ${response.statusCode}');
}
final body = await response.transform(utf8.decoder).join();
_indexContentCache[mirror.id] = (now, body);
return body;
} finally {
client?.close();
}
}
}
+93
View File
@@ -687,6 +687,99 @@ class DistroInstaller {
// 8. 自动配置 Java 运行时动态链接路径
await ensureJavaConfiguration(rootfsDir);
// 9. 自动配置 Debian/Ubuntu 容器环境策略(policy-rc.d 屏蔽守护进程启动,解决 dpkg error code 1)
await ensureAptPolicyAndDiversions(rootfsDir);
// 10. 自动配置 Debian/Ubuntu dpkg 优化(force-unsafe-io 解决硬链接解包与 I/O 阻塞异常)
await ensureDpkgConfiguration(rootfsDir);
}
/// 自动配置 Debian / Ubuntu 容器环境 dpkg 优化配置(解决 fsync/I/O 阻塞与权限死锁)
/// 对标 proot-distro:
/// 写入 `/etc/dpkg/dpkg.cfg.d/01_proot`,包含 `force-unsafe-io`
static Future<void> ensureDpkgConfiguration(Directory rootfsDir) async {
try {
final etcDpkgDir = Directory(p.join(rootfsDir.path, 'etc', 'dpkg'));
if (!etcDpkgDir.existsSync()) return;
final dpkgCfgD = Directory(p.join(etcDpkgDir.path, 'dpkg.cfg.d'));
if (!dpkgCfgD.existsSync()) {
dpkgCfgD.createSync(recursive: true);
}
final prootCfg = File(p.join(dpkgCfgD.path, '01_proot'));
const prootCfgContent = 'force-unsafe-io\n';
if (!prootCfg.existsSync() || prootCfg.readAsStringSync() != prootCfgContent) {
prootCfg.writeAsStringSync(prootCfgContent, flush: true);
debugPrint('[DistroInstaller] 成功配置 /etc/dpkg/dpkg.cfg.d/01_proot (force-unsafe-io)');
}
} catch (e) {
debugPrint('[DistroInstaller] 配置 dpkg 优化策略异常 (非阻塞): $e');
}
}
/// 自动适配 Debian/Ubuntu 容器环境的包管理器策略与服务屏蔽
/// 对标 proot-distro:
/// 1. 注入 `/usr/sbin/policy-rc.d` 返回 101,禁止包安装过程启动 systemd/init 服务;
/// 2. 伪装 `start-stop-daemon`,避免 postinst 脚本因守护进程调用失败导致 dpkg 退出码 1;
/// 3. 设置 APT 默认静默与非交互模式,避免缺少 apt-utils 时 debconf 异常。
static Future<void> ensureAptPolicyAndDiversions(Directory rootfsDir) async {
try {
final etcAptDir = Directory(p.join(rootfsDir.path, 'etc', 'apt'));
if (!etcAptDir.existsSync()) return;
// 同步检查并配置 dpkg 选项
await ensureDpkgConfiguration(rootfsDir);
// 1. /usr/sbin/policy-rc.d (exit 101)
final sbinDir = Directory(p.join(rootfsDir.path, 'usr', 'sbin'));
if (!sbinDir.existsSync()) {
sbinDir.createSync(recursive: true);
}
final policyRcD = File(p.join(sbinDir.path, 'policy-rc.d'));
const policyContent = '#!/bin/sh\nexit 101\n';
if (!policyRcD.existsSync() || policyRcD.readAsStringSync() != policyContent) {
policyRcD.writeAsStringSync(policyContent, flush: true);
if (!Platform.isWindows) {
try {
await Process.run('chmod', ['755', policyRcD.path]);
} catch (_) {}
}
debugPrint('[DistroInstaller] 成功注入 /usr/sbin/policy-rc.d');
}
// 2. /usr/sbin/start-stop-daemon (exit 0 伪装,避免无 init 守护进程报错)
final startStopDaemon = File(p.join(sbinDir.path, 'start-stop-daemon'));
const daemonStubContent = '#!/bin/sh\nexit 0\n';
if (!startStopDaemon.existsSync()) {
startStopDaemon.writeAsStringSync(daemonStubContent, flush: true);
if (!Platform.isWindows) {
try {
await Process.run('chmod', ['755', startStopDaemon.path]);
} catch (_) {}
}
debugPrint('[DistroInstaller] 成功伪装 /usr/sbin/start-stop-daemon');
}
// 3. /etc/apt/apt.conf.d/99no-install-recommends 与 debconf 配置
final aptConfD = Directory(p.join(etcAptDir.path, 'apt.conf.d'));
if (!aptConfD.existsSync()) {
aptConfD.createSync(recursive: true);
}
final aptSettings = File(p.join(aptConfD.path, '99proot-container'));
const aptSettingsContent =
'APT::Install-Recommends "false";\n'
'APT::Install-Suggests "false";\n'
'APT::Get::Assume-Yes "true";\n'
'Dpkg::Use-Pty "0";\n';
if (!aptSettings.existsSync() || aptSettings.readAsStringSync() != aptSettingsContent) {
aptSettings.writeAsStringSync(aptSettingsContent, flush: true);
debugPrint('[DistroInstaller] 成功配置 /etc/apt/apt.conf.d/99proot-container');
}
} catch (e) {
debugPrint('[DistroInstaller] 配置 APT policy-rc.d 策略异常 (非阻塞): $e');
}
}
/// 自动部署标准 SSL CA 证书链(让 APT / Curl / Git 默认支持 HTTPS)
+30 -52
View File
@@ -257,53 +257,7 @@ class DistroManager {
);
}
/// 从应用内置资源导入 Alpine Linux 系统实例(保留备用)
///
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
final assetPath = DistroRepository.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置 Alpine 系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 从用户本地指定的 .tar.gz / .tar.xz 压缩包导入外部系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
if (!tarGzFile.existsSync()) {
throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}');
}
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromFile(
archiveFile: tarGzFile,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 高危操作:彻底删除指定系统实例及其所有存储数据
Future<void> deleteSystem(String systemName) async {
@@ -432,11 +386,14 @@ class DistroManager {
// 确保 Java 运行时动态链接配置就绪(解决 /usr/bin/java 符号链接找不到 libjli.so)
await DistroInstaller.ensureJavaConfiguration(rootDir);
// 确保 Debian/Ubuntu 容器环境策略就绪(policy-rc.d 屏蔽守护进程自启,解决 dpkg error code 1)
await DistroInstaller.ensureAptPolicyAndDiversions(rootDir);
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
final shmDir = await _ensureShmDir(systemName, customBaseDir: customRootDir?.parent);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范)
final l2sDir = await _ensureL2sDir(systemName, customBaseDir: customRootDir?.parent);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范,位于 rootfs/.l2s)
final l2sDir = await _ensureL2sDir(systemName, rootDir, customBaseDir: customRootDir?.parent);
// 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据)
final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: customRootDir?.parent);
@@ -555,6 +512,7 @@ class DistroManager {
'TERM=xterm-256color',
'COLORTERM=truecolor',
'LANG=C.UTF-8',
'PROOT_L2S_DIR=/.l2s',
if (guestJavaHome != null) 'JAVA_HOME=$guestJavaHome',
if (guestJavaHome != null)
'PATH=$guestJavaHome/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
@@ -638,14 +596,34 @@ class DistroManager {
}
}
/// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro login/__init__.py)
Future<Directory?> _ensureL2sDir(String systemName, {Directory? customBaseDir}) async {
/// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro l2s.py,位于 rootfs/.l2s)
Future<Directory?> _ensureL2sDir(String systemName, Directory rootDir, {Directory? customBaseDir}) async {
try {
final baseDir = customBaseDir ?? await getBaseDistrosDir();
final l2sDir = Directory(p.join(baseDir.path, systemName, '.l2s'));
final l2sDir = Directory(p.join(rootDir.path, '.l2s'));
if (!l2sDir.existsSync()) {
l2sDir.createSync(recursive: true);
}
// 自动迁移旧版本放置在 rootfs 外部的 .l2s 目录 (<rootDir.parent>/.l2s)
try {
final legacyL2sDir = Directory(p.join(rootDir.parent.path, '.l2s'));
if (legacyL2sDir.existsSync() && legacyL2sDir.path != l2sDir.path) {
final entries = legacyL2sDir.listSync();
for (final entry in entries) {
final targetPath = p.join(l2sDir.path, p.basename(entry.path));
if (!File(targetPath).existsSync() && !Directory(targetPath).existsSync()) {
entry.renameSync(targetPath);
}
}
try {
legacyL2sDir.deleteSync(recursive: true);
} catch (_) {}
debugPrint('[DistroManager] 已平滑迁移旧版本外部 .l2s 目录至 rootfs/.l2s');
}
} catch (e) {
debugPrint('[DistroManager] 迁移旧 .l2s 异常 (非阻塞): $e');
}
return l2sDir;
} catch (e) {
debugPrint('创建容器 .l2s 目录失败 (非阻塞): $e');
+124 -61
View File
@@ -1,9 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../l10n/app_localizations.dart';
import '../models/distro_manifest.dart';
@@ -11,7 +9,7 @@ import '../widgets/distro_extract_dialog.dart';
import 'distro_installer.dart';
import 'distro_manager.dart';
/// 内部私有代码智能引擎服务 (files/internal_engine/alpine)
/// 代码智能与运行时引擎服务(基于统一主系统 Ubuntu 24.04)
class InternalEngineService extends ChangeNotifier {
static final InternalEngineService instance = InternalEngineService._();
InternalEngineService._();
@@ -23,48 +21,36 @@ class InternalEngineService extends ChangeNotifier {
bool _isChecking = false;
bool get isChecking => _isChecking;
/// 获取引擎主目录: `<files>/internal_engine/alpine`
Future<Directory> getEngineDir() async {
/// 获取主系统 Ubuntu rootfs 目录
Future<Directory> getRootfsDir() async {
if (customEngineDir != null) {
return customEngineDir!;
}
final appDir = await getApplicationSupportDirectory();
final rootPath = p.basename(appDir.path) == 'files'
? appDir.path
: p.join(appDir.path, 'files');
final engineDir = Directory(p.join(rootPath, 'internal_engine', 'alpine'));
if (!engineDir.existsSync()) {
engineDir.createSync(recursive: true);
}
return engineDir;
return DistroManager().getSystemRootDir(DistroRepository.defaultSystemName);
}
/// 获取 rootfs 目录: `<files>/internal_engine/alpine/rootfs`
Future<Directory> getRootfsDir() async {
final engineDir = await getEngineDir();
return Directory(p.join(engineDir.path, 'rootfs'));
}
/// 兼容旧方法命名
Future<Directory> getEngineDir() => getRootfsDir();
/// 检查内置 Alpine 引擎是否已完整安装
/// 检查主系统 Ubuntu 是否已完整安装
Future<bool> isEngineInstalled() async {
try {
final engineDir = await getEngineDir();
final marker = File(p.join(engineDir.path, '.installed'));
if (!marker.existsSync()) return false;
if (customEngineDir != null) {
final marker = File(p.join(customEngineDir!.path, '.installed'));
if (marker.existsSync()) return true;
final binDir = Directory(p.join(customEngineDir!.path, 'bin'));
final etcDir = Directory(p.join(customEngineDir!.path, 'etc'));
return binDir.existsSync() && etcDir.existsSync();
}
final rootfs = await getRootfsDir();
if (!rootfs.existsSync()) return false;
final binDir = Directory(p.join(rootfs.path, 'bin'));
final etcDir = Directory(p.join(rootfs.path, 'etc'));
return binDir.existsSync() && etcDir.existsSync();
return await DistroManager().isSystemInstalled(DistroRepository.defaultSystemName);
} catch (e) {
debugPrint('检查内置引擎异常: $e');
debugPrint('检查代码智能运行引擎异常: $e');
return false;
}
}
/// 确保内置引擎已准备完毕;若未安装,弹出模态解压弹窗进行解压
/// 确保内置 Ubuntu 引擎已准备完毕;若未安装,弹出模态解压弹窗进行解压
Future<bool> ensureEngineReady(BuildContext context) async {
if (await isEngineInstalled()) {
return true;
@@ -79,7 +65,7 @@ class InternalEngineService extends ChangeNotifier {
try {
final success = await DistroExtractDialog.show(
context: context,
systemName: l10n?.internalEngineTitle ?? '内部代码智能引擎 (Alpine)',
systemName: l10n?.internalEngineTitle ?? '代码运行与智能补全引擎 (Ubuntu)',
task: (onProgress, isCancelled) async {
await extractEngine(
onProgress: onProgress,
@@ -94,41 +80,31 @@ class InternalEngineService extends ChangeNotifier {
} catch (e) {
_isChecking = false;
notifyListeners();
debugPrint('解压内部引擎失败: $e');
debugPrint('解压 Ubuntu 引擎失败: $e');
return false;
}
}
/// 解压 Asset 中的 Alpine minirootfs 到私有引擎目录
/// 解压 Asset 中的 Ubuntu 到主系统目录
Future<void> extractEngine({
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final assetPath = DistroRepository.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置 Alpine 系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final rootfsDir = await getRootfsDir();
if (!rootfsDir.existsSync()) {
rootfsDir.createSync(recursive: true);
if (customEngineDir != null) {
// 测试模式下解压或标记
final marker = File(p.join(customEngineDir!.path, '.installed'));
await marker.writeAsString('ready');
return;
}
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: rootfsDir,
await DistroManager().importBuiltinUbuntu(
systemName: DistroRepository.defaultSystemName,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 写入安装完成标记文件
final engineDir = await getEngineDir();
final marker = File(p.join(engineDir.path, '.installed'));
await marker.writeAsString('ready');
}
/// 检查某命令(如 clangd, rust-analyzer)是否在内置 Alpine 中已安装
/// 检查某命令(如 clangd, rust-analyzer, pylsp)是否在系统已安装
Future<bool> isCommandInstalled(String command) async {
if (!await isEngineInstalled() || command.trim().isEmpty) {
return false;
@@ -137,39 +113,126 @@ class InternalEngineService extends ChangeNotifier {
try {
final rootfs = await getRootfsDir();
final res = await DistroManager().runHeadlessCommand(
systemName: 'alpine_internal',
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: 'command -v ${command.trim()} >/dev/null 2>&1 && echo CE_OK',
timeout: const Duration(seconds: 15),
);
return res?.stdout.toString().contains('CE_OK') ?? false;
} catch (e) {
debugPrint('检查内置引擎命令异常: $e');
debugPrint('检查引擎命令异常: $e');
return false;
}
}
/// 在内置 Alpine 中安装指定 apk 软件包
/// 在 Ubuntu 系统中安装指定 apt 软件包
Future<bool> installPackage(
String apkPackage, {
String packageName, {
void Function(String chunk)? onOutput,
}) async {
if (!await isEngineInstalled() || apkPackage.trim().isEmpty) {
if (!await isEngineInstalled() || packageName.trim().isEmpty) {
return false;
}
try {
final rootfs = await getRootfsDir();
final installCmd =
'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; '
'dpkg --configure -a 2>/dev/null || true; '
'apt-get update && '
'apt-get install -y --no-install-recommends ${packageName.trim()}';
final res = await DistroManager().runHeadlessCommand(
systemName: 'alpine_internal',
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: 'apk add --no-cache ${apkPackage.trim()}',
timeout: const Duration(minutes: 5),
command: installCmd,
timeout: const Duration(minutes: 10),
onStdout: onOutput,
);
return res != null && res.exitCode == 0;
} catch (e) {
debugPrint('安装内置引擎软件包异常: $e');
debugPrint('安装引擎软件包异常: $e');
return false;
}
}
/// 在 Ubuntu 系统中彻底卸载指定 apt 软件包及清理对应命令
Future<bool> uninstallPackage(
String packageName, {
String? serverCommand,
void Function(String chunk)? onOutput,
}) async {
final cleanPkg = packageName.trim();
if (!await isEngineInstalled() || cleanPkg.isEmpty) {
return false;
}
try {
final rootfs = await getRootfsDir();
final cleanCmd = serverCommand?.trim();
// 1. 若指定了服务命令,先在容器内强杀残留进程,避免文件占用导致卸载失败
final killSection = (cleanCmd != null && cleanCmd.isNotEmpty)
? 'pkill -9 -f "$cleanCmd" 2>/dev/null || true; '
: '';
// 2. 针对特定虚包/版本衍生包进行包名扩展 purge
// 例如 clangd 会衍生出 clangd-15, clang-tools-15 等
final String targetsToPurge;
if (cleanPkg == 'clangd') {
targetsToPurge = 'clangd clangd* clang-tools*';
} else {
targetsToPurge = cleanPkg;
}
// 3. 二次兜底检测:如果命令仍残留,尝试通过 dpkg -S 查询实际宿主包并 purge,或清理残留可执行文件
final cmdCleanupSection = (cleanCmd != null && cleanCmd.isNotEmpty)
? '''
BIN_PATH=\$(command -v "$cleanCmd" 2>/dev/null || true)
if [ -n "\$BIN_PATH" ]; then
OWNER_PKG=\$(dpkg -S "\$BIN_PATH" 2>/dev/null | cut -d: -f1 | head -n 1 || true)
if [ -n "\$OWNER_PKG" ]; then
apt-get remove --purge -y "\$OWNER_PKG" 2>/dev/null || true
fi
rm -f "\$BIN_PATH" 2>/dev/null || true
fi
'''
: '';
final uninstallCmd = '''
export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true
$killSection
dpkg --configure -a 2>/dev/null || true
apt-get remove --purge -y $targetsToPurge
apt-get autoremove --purge -y
$cmdCleanupSection
''';
final res = await DistroManager().runHeadlessCommand(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: uninstallCmd,
timeout: const Duration(minutes: 5),
onStdout: onOutput,
);
final success = res != null && res.exitCode == 0;
if (!success) {
return false;
}
// 4. 若提供了 serverCommand,确凿验证该命令在系统中是否已不存在
if (cleanCmd != null && cleanCmd.isNotEmpty) {
final stillExists = await isCommandInstalled(cleanCmd);
if (stillExists) {
debugPrint('[InternalEngineService] 警告: 卸载脚本完成后命令 $cleanCmd 仍残留');
return false;
}
}
return true;
} catch (e) {
debugPrint('卸载引擎软件包异常: $e');
return false;
}
}
+152
View File
@@ -0,0 +1,152 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
/// C/C++ 工程头文件搜索路径与编译数据库辅助器
///
/// 当用户打开 CMake 或普通 C/C++ 工程时,若缺少 compile_commands.json,
/// clangd 默认仅在单文件所在目录与系统库中搜索头文件,导致多目录项目(如 include/、src/、common/)
/// 中相互引用的头文件报错“file not found”。
/// 本类负责在启动 clangd 前:
/// 1. 检查是否存在 compile_commands.json、compile_flags.txt 或 .clangd,若存在则绝不覆盖;
/// 2. 检查 build/、out/ 等子构建目录下是否有 compile_commands.json,若有则自动生成 .clangd 配置指向该目录;
/// 3. 若均不存在,自动扫描项目下包含头文件的常见源码目录,推导并生成轻量合理的 compile_flags.txt。
class CppProjectHelper {
const CppProjectHelper._();
static const Set<String> _ignoredDirNames = {
'.git',
'.vscode',
'.idea',
'.dart_tool',
'build',
'out',
'dist',
'bin',
'obj',
'node_modules',
'cache',
'tmp',
};
static const Set<String> _headerExtensions = {
'.h',
'.hpp',
'.hxx',
'.hh',
'.inl',
};
/// 确保指定工作区根目录下具备 clangd 编译配置
static Future<void> ensureCompileFlags(String workspaceRoot) async {
if (workspaceRoot.isEmpty) return;
final rootDir = Directory(workspaceRoot);
if (!rootDir.existsSync()) return;
// 1. 若项目根目录已有配置,直接返回
final rootCompileCommands = File(p.join(workspaceRoot, 'compile_commands.json'));
final rootCompileFlags = File(p.join(workspaceRoot, 'compile_flags.txt'));
final rootClangd = File(p.join(workspaceRoot, '.clangd'));
if (rootCompileCommands.existsSync() ||
rootCompileFlags.existsSync() ||
rootClangd.existsSync()) {
return;
}
// 2. 检查常见构建输出子目录下是否存在 compile_commands.json
final candidateBuildDirs = ['build', 'out', 'cmake-build-debug', 'cmake-build-release'];
for (final buildDirName in candidateBuildDirs) {
final candidateFile = File(p.join(workspaceRoot, buildDirName, 'compile_commands.json'));
if (candidateFile.existsSync()) {
try {
final content = 'CompileFlags:\n CompilationDatabase: $buildDirName\n';
rootClangd.writeAsStringSync(content, flush: true);
debugPrint('[CppProjectHelper] 检测到 $buildDirName/compile_commands.json,已生成 .clangd 映射');
return;
} catch (e) {
debugPrint('[CppProjectHelper] 写入 .clangd 失败: $e');
}
}
}
// 3. 扫描项目目录,收集包含头文件的目录
final relativeIncludeDirs = <String>{};
_scanHeaderDirs(rootDir, rootDir, relativeIncludeDirs, currentDepth: 0, maxDepth: 3);
if (relativeIncludeDirs.isEmpty) return;
// 排序:常用顶级目录优先展示
final sortedDirs = relativeIncludeDirs.toList()
..sort((a, b) {
int score(String path) {
if (path == 'include') return 0;
if (path == 'src') return 1;
if (path == 'common') return 2;
if (path.endsWith('/include')) return 3;
if (path.endsWith('/src')) return 4;
return 5;
}
final scoreA = score(a);
final scoreB = score(b);
if (scoreA != scoreB) return scoreA.compareTo(scoreB);
return a.compareTo(b);
});
final buffer = StringBuffer();
for (final dir in sortedDirs) {
buffer.writeln('-I$dir');
}
buffer.writeln('-xc++');
buffer.writeln('-std=c++17');
try {
rootCompileFlags.writeAsStringSync(buffer.toString(), flush: true);
debugPrint('[CppProjectHelper] 已为工程自动生成 compile_flags.txt (${sortedDirs.length} 个头文件路径)');
} catch (e) {
debugPrint('[CppProjectHelper] 写入 compile_flags.txt 异常: $e');
}
}
static void _scanHeaderDirs(
Directory root,
Directory current,
Set<String> result, {
required int currentDepth,
required int maxDepth,
}) {
if (currentDepth > maxDepth) return;
try {
final entries = current.listSync(followLinks: false);
bool dirHasHeader = false;
final subDirs = <Directory>[];
for (final entry in entries) {
if (entry is File) {
final ext = p.extension(entry.path).toLowerCase();
if (_headerExtensions.contains(ext)) {
dirHasHeader = true;
}
} else if (entry is Directory) {
final dirName = p.basename(entry.path);
if (!dirName.startsWith('.') && !_ignoredDirNames.contains(dirName.toLowerCase())) {
subDirs.add(entry);
}
}
}
if (dirHasHeader) {
final rel = p.relative(current.path, from: root.path).replaceAll('\\', '/');
if (rel.isNotEmpty && rel != '.') {
result.add(rel);
}
}
for (final sub in subDirs) {
_scanHeaderDirs(root, sub, result, currentDepth: currentDepth + 1, maxDepth: maxDepth);
}
} catch (_) {}
}
}
+255
View File
@@ -0,0 +1,255 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
class LspException implements Exception {
final int code;
final String message;
final dynamic data;
const LspException(this.code, this.message, [this.data]);
@override
String toString() => 'LspException($code): $message';
}
/// 基于标准输入输出(stdio)的原生高性能 JSON-RPC 2.0 LSP 客户端
class LspClient {
final Process _process;
final StreamSubscription<List<int>> _stdoutSub;
final StreamSubscription<List<int>> _stderrSub;
int _nextId = 1;
final Map<int, Completer<dynamic>> _pendingRequests = {};
final Map<String, List<void Function(dynamic params)>> _notificationListeners = {};
final List<int> _buffer = [];
bool _isClosed = false;
bool get isClosed => _isClosed;
/// 串行异步写入链,杜绝并发写入 stdin 导致 StreamSink is bound to a stream 异常
Future<void> _writeQueue = Future.value();
LspClient(this._process)
: _stdoutSub = _process.stdout.listen(null),
_stderrSub = _process.stderr.listen(null) {
_stdoutSub.onData(_handleStdoutData);
_stderrSub.onData(_handleStderrData);
_process.exitCode.then((code) {
debugPrint('[LspClient] 语言服务进程退出: $code');
close();
});
}
/// 注册监听服务端的单向通知(如 textDocument/publishDiagnostics)
void onNotification(String method, void Function(dynamic params) handler) {
_notificationListeners.putIfAbsent(method, () => []).add(handler);
}
/// 发送 JSON-RPC 2.0 请求并等待响应结果
Future<T?> sendRequest<T>(String method, [dynamic params, Duration timeout = const Duration(seconds: 10)]) async {
if (_isClosed) {
throw StateError('LspClient 已关闭,无法发送请求: $method');
}
final id = _nextId++;
final completer = Completer<dynamic>();
_pendingRequests[id] = completer;
final payload = {
'jsonrpc': '2.0',
'id': id,
'method': method,
if (params != null) 'params': params,
};
_sendMessage(payload);
try {
final res = await completer.future.timeout(timeout);
return res as T?;
} on TimeoutException {
_pendingRequests.remove(id);
debugPrint('[LspClient] 请求超时: $method (id: $id)');
return null;
} catch (e) {
_pendingRequests.remove(id);
rethrow;
}
}
/// 发送单向通知(无需回复,如 textDocument/didChange, didOpen)
void sendNotification(String method, [dynamic params]) {
if (_isClosed) return;
final payload = {
'jsonrpc': '2.0',
'method': method,
if (params != null) 'params': params,
};
_sendMessage(payload);
}
void _sendMessage(Map<String, dynamic> payload) {
if (_isClosed) return;
_writeQueue = _writeQueue.then((_) async {
if (_isClosed) return;
try {
final jsonStr = jsonEncode(payload);
final bodyBytes = utf8.encode(jsonStr);
final headerStr = 'Content-Length: ${bodyBytes.length}\r\n\r\n';
final headerBytes = ascii.encode(headerStr);
_process.stdin.add(headerBytes);
_process.stdin.add(bodyBytes);
await _process.stdin.flush();
} catch (e) {
debugPrint('[LspClient] 发送消息异常: $e');
}
}).catchError((e) {
debugPrint('[LspClient] 消息写入队列异常: $e');
});
}
void _handleStdoutData(List<int> chunk) {
_buffer.addAll(chunk);
while (true) {
final headerEnd = _findHeaderEnd(_buffer);
if (headerEnd == -1) break;
final headerBytes = _buffer.sublist(0, headerEnd);
final headerStr = ascii.decode(headerBytes, allowInvalid: true);
final contentLength = _parseContentLength(headerStr);
if (contentLength == null) {
// 异常头部,跳过4字节分隔符
_buffer.removeRange(0, headerEnd + 4);
continue;
}
final totalMsgLength = headerEnd + 4 + contentLength;
if (_buffer.length < totalMsgLength) {
// 数据包尚未完整接收,等待下一个 chunk
break;
}
final bodyBytes = _buffer.sublist(headerEnd + 4, totalMsgLength);
_buffer.removeRange(0, totalMsgLength);
try {
final bodyStr = utf8.decode(bodyBytes, allowMalformed: true);
final dynamic msg = jsonDecode(bodyStr);
if (msg is Map<String, dynamic>) {
_dispatchMessage(msg);
}
} catch (e) {
debugPrint('[LspClient] 解析消息体异常: $e');
}
}
}
void _dispatchMessage(Map<String, dynamic> msg) {
final id = msg['id'];
final method = msg['method'] as String?;
// 1. 响应我们之前发送的 Request (id != null, 无 method)
if (id != null && method == null) {
final intId = id is int ? id : int.tryParse(id.toString());
if (intId != null && _pendingRequests.containsKey(intId)) {
final completer = _pendingRequests.remove(intId)!;
if (msg.containsKey('error')) {
final err = msg['error'];
if (err is Map) {
completer.completeError(LspException(
err['code'] as int? ?? -1,
err['message'] as String? ?? 'Unknown error',
err['data'],
));
} else {
completer.completeError(LspException(-1, err.toString()));
}
} else {
completer.complete(msg['result']);
}
}
return;
}
// 2. 服务端主动推送的单向通知 (id == null, 有 method)
if (method != null && id == null) {
final listeners = _notificationListeners[method];
if (listeners != null) {
for (final listener in listeners) {
try {
listener(msg['params']);
} catch (e) {
debugPrint('[LspClient] 通知监听执行异常 ($method): $e');
}
}
}
return;
}
// 3. 服务端向客户端发送的请求 (id != null, 有 method,如 workspace/configuration)
if (method != null && id != null) {
_handleServerRequest(id, method, msg['params']);
}
}
void _handleServerRequest(dynamic id, String method, dynamic params) {
// 基础应答:返回 null 或空配置,避免服务端挂起
final reply = {
'jsonrpc': '2.0',
'id': id,
'result': null,
};
_sendMessage(reply);
}
void _handleStderrData(List<int> chunk) {
// 记录语言服务器的 stderr 日志(调试信息)
final text = utf8.decode(chunk, allowMalformed: true);
if (kDebugMode) {
debugPrint('[LSP Stderr] $text');
}
}
int _findHeaderEnd(List<int> buf) {
// 匹配 \r\n\r\n (13, 10, 13, 10)
for (int i = 0; i <= buf.length - 4; i++) {
if (buf[i] == 13 && buf[i + 1] == 10 && buf[i + 2] == 13 && buf[i + 3] == 10) {
return i;
}
}
return -1;
}
int? _parseContentLength(String headerStr) {
for (final line in headerStr.split('\r\n')) {
final parts = line.split(':');
if (parts.length >= 2 && parts[0].trim().toLowerCase() == 'content-length') {
return int.tryParse(parts[1].trim());
}
}
return null;
}
void close() {
if (_isClosed) return;
_isClosed = true;
for (final completer in _pendingRequests.values) {
if (!completer.isCompleted) {
completer.completeError(const LspException(-32099, 'LspClient 已关闭'));
}
}
_pendingRequests.clear();
_notificationListeners.clear();
_stdoutSub.cancel();
_stderrSub.cancel();
try {
_process.kill();
} catch (_) {}
}
}
@@ -0,0 +1,87 @@
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'lsp_protocol.dart';
/// 全局代码错误诊断管理器(按文件 URI / 绝对路径存储报错区间与等级)
class LspDiagnosticsStore extends ChangeNotifier {
static final LspDiagnosticsStore instance = LspDiagnosticsStore._();
LspDiagnosticsStore._();
/// filePath -> `List<LspDiagnostic>`
final Map<String, List<LspDiagnostic>> _diagnosticsByFile = {};
/// 更新某个文件的诊断列表
void updateDiagnostics(String uriOrPath, List<LspDiagnostic> diagnostics) {
final normalized = _normalizePath(uriOrPath);
if (diagnostics.isEmpty) {
_diagnosticsByFile.remove(normalized);
} else {
// 按错误起始行号和字符列号升序排序
final sorted = List<LspDiagnostic>.from(diagnostics)
..sort((a, b) {
final lineComp = a.range.start.line.compareTo(b.range.start.line);
if (lineComp != 0) return lineComp;
return a.range.start.character.compareTo(b.range.start.character);
});
_diagnosticsByFile[normalized] = sorted;
}
notifyListeners();
}
/// 获取指定文件的全部诊断
List<LspDiagnostic> getDiagnosticsForFile(String? filePath) {
if (filePath == null || filePath.isEmpty) return const [];
return _diagnosticsByFile[_normalizePath(filePath)] ?? const [];
}
/// 获取指定文件在第 [line] 行(0-indexed)上的所有诊断
List<LspDiagnostic> getDiagnosticsForLine(String? filePath, int line) {
if (filePath == null || filePath.isEmpty) return const [];
final all = _diagnosticsByFile[_normalizePath(filePath)];
if (all == null || all.isEmpty) return const [];
return all.where((d) => d.range.overlapsLine(line)).toList();
}
/// 获取指定文件在第 [line] 行、第 [character] 列上的精确诊断项
LspDiagnostic? getDiagnosticAt(String? filePath, int line, int character) {
final list = getDiagnosticsForLine(filePath, line);
for (final d in list) {
if (d.range.contains(line, character)) {
return d;
}
}
// 若光标在该行但未精确在区间内,返回该行的第一个报错
return list.isNotEmpty ? list.first : null;
}
/// 清空所有诊断
void clear() {
_diagnosticsByFile.clear();
notifyListeners();
}
/// 移除指定文件的诊断
void removeForFile(String? filePath) {
if (filePath == null) return;
if (_diagnosticsByFile.remove(_normalizePath(filePath)) != null) {
notifyListeners();
}
}
String _normalizePath(String input) {
String path = input;
if (path.startsWith('file://')) {
final uri = Uri.tryParse(path);
if (uri != null && uri.hasAbsolutePath) {
path = uri.toFilePath();
} else {
path = path.substring(7);
}
}
path = p.normalize(path).replaceAll('\\', '/');
if (path.length >= 2 && path[1] == ':') {
path = path[0].toLowerCase() + path.substring(1);
}
return path;
}
}
+197
View File
@@ -0,0 +1,197 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import '../../models/distro_manifest.dart';
import '../distro_manager.dart';
import '../internal_engine_service.dart';
import '../lsp_config_service.dart';
import 'cpp_project_helper.dart';
import 'lsp_client.dart';
import 'lsp_session.dart';
/// 全局语言服务(LSP)调度管理中心
class LspManager extends ChangeNotifier {
static final LspManager instance = LspManager._();
LspManager._();
final Map<String, LspSession> _activeSessions = {};
final Map<String, Future<LspSession?>> _startingSessions = {};
/// 获取或拉起匹配当前文件的语言服务会话
Future<LspSession?> getOrCreateSession(String filePath, {String? workspaceRoot}) async {
final ext = p.extension(filePath);
if (ext.isEmpty) return null;
final config = LspConfigService.instance.findByExtension(ext);
if (config == null || !config.enabled) return null;
// 检查是否已有存活会话
final existing = _activeSessions[config.id];
if (existing != null && !existing.client.isClosed) {
return existing;
}
// 防止并发重复拉起同一个服务
if (_startingSessions.containsKey(config.id)) {
return _startingSessions[config.id];
}
final future = _startSession(config, filePath, workspaceRoot);
_startingSessions[config.id] = future;
try {
final session = await future;
if (session != null) {
_activeSessions[config.id] = session;
}
return session;
} finally {
_startingSessions.remove(config.id);
}
}
Future<LspSession?> _startSession(
dynamic config,
String filePath,
String? workspaceRoot,
) async {
try {
// 1. 检查 Ubuntu 引擎和命令是否就绪
final engineInstalled = await InternalEngineService.instance.isEngineInstalled();
if (!engineInstalled) return null;
final cmdInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand);
if (!cmdInstalled) {
debugPrint('[LspManager] 服务命令未安装: ${config.serverCommand}');
return null;
}
final effectiveRoot = workspaceRoot ?? p.dirname(filePath);
// 若为 C/C++ 项目,在启动 clangd 前确保推导并配置头文件与编译标志
if (config.id == 'c_cpp') {
try {
await CppProjectHelper.ensureCompileFlags(effectiveRoot);
} catch (e) {
debugPrint('[LspManager] 确保 C/C++ 编译标志失败: $e');
}
}
final rootfs = await InternalEngineService.instance.getRootfsDir();
final effectiveArgs = List<String>.from(config.serverArgs ?? const []);
if (config.id == 'c_cpp') {
if (!effectiveArgs.any((a) => a.startsWith('--query-driver'))) {
effectiveArgs.add('--query-driver=/usr/bin/*,/usr/local/bin/*');
}
if (!effectiveArgs.any((a) => a.startsWith('--header-insertion'))) {
effectiveArgs.add('--header-insertion=iwyu');
}
}
final cmdWithArgs = [
config.serverCommand,
...effectiveArgs,
].join(' ');
final launchConfig = await DistroManager().buildLaunchConfig(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
workspacePath: effectiveRoot,
customCommand: cmdWithArgs,
);
debugPrint('[LspManager] 正在拉起语言服务进程: ${launchConfig.toCommandLine()}');
final process = await Process.start(
launchConfig.executable,
launchConfig.arguments,
environment: launchConfig.environment,
workingDirectory: launchConfig.workingDirectory,
);
final client = LspClient(process);
final session = LspSession(
client: client,
config: config,
workspaceRoot: effectiveRoot,
);
final success = await session.initialize();
if (success) {
notifyListeners();
return session;
} else {
await session.close();
return null;
}
} catch (e) {
debugPrint('[LspManager] 拉起语言服务异常: $e');
return null;
}
}
/// 获取当前已存活的会话(不触发异步拉起)
LspSession? getExistingSession(String filePath) {
final ext = p.extension(filePath);
if (ext.isEmpty) return null;
final config = LspConfigService.instance.findByExtension(ext);
if (config == null) return null;
final session = _activeSessions[config.id];
if (session != null && !session.client.isClosed) {
return session;
}
return null;
}
/// 响应文档打开
Future<void> onFileOpened(String filePath, String text, {String? workspaceRoot}) async {
final session = await getOrCreateSession(filePath, workspaceRoot: workspaceRoot);
session?.didOpen(filePath, text);
}
/// 响应文档编辑(带防抖通知)
void onFileChanged(String filePath, String fullText) {
final session = getExistingSession(filePath);
session?.didChange(filePath, fullText);
}
/// 响应文档关闭
void onFileClosed(String filePath) {
final session = getExistingSession(filePath);
session?.didClose(filePath);
}
/// 停用并释放指定语言配置的后台服务会话
Future<void> stopSession(String configId) async {
// 1. 若当前正在异步拉起中,等待启动完成后再关闭
if (_startingSessions.containsKey(configId)) {
try {
final session = await _startingSessions[configId];
await session?.close();
} catch (_) {}
_startingSessions.remove(configId);
}
// 2. 关闭并清理已存活的会话
final session = _activeSessions.remove(configId);
if (session != null) {
try {
await session.close();
} catch (e) {
debugPrint('[LspManager] 关闭语言会话异常 ($configId): $e');
}
notifyListeners();
}
}
/// 关闭并回收所有后台语言服务进程
Future<void> disposeAll() async {
for (final session in _activeSessions.values) {
await session.close();
}
_activeSessions.clear();
_startingSessions.clear();
notifyListeners();
}
}
+258
View File
@@ -0,0 +1,258 @@
/// LSP (Language Server Protocol) 核心协议数据模型
class LspPosition {
final int line;
final int character;
const LspPosition({required this.line, required this.character});
const LspPosition.pos(this.line, this.character);
factory LspPosition.fromJson(Map<String, dynamic> json) {
return LspPosition(
line: json['line'] as int? ?? 0,
character: json['character'] as int? ?? 0,
);
}
Map<String, dynamic> toJson() => {
'line': line,
'character': character,
};
@override
String toString() => '$line:$character';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LspPosition && line == other.line && character == other.character;
@override
int get hashCode => Object.hash(line, character);
}
class LspRange {
final LspPosition start;
final LspPosition end;
const LspRange({required this.start, required this.end});
factory LspRange.fromJson(Map<String, dynamic> json) {
return LspRange(
start: LspPosition.fromJson(json['start'] as Map<String, dynamic>? ?? const {}),
end: LspPosition.fromJson(json['end'] as Map<String, dynamic>? ?? const {}),
);
}
Map<String, dynamic> toJson() => {
'start': start.toJson(),
'end': end.toJson(),
};
/// 检查给定行列号是否处于当前区间内部(闭区间)
bool contains(int l, int c) {
if (l < start.line || l > end.line) return false;
if (l == start.line && c < start.character) return false;
if (l == end.line && c > end.character) return false;
return true;
}
/// 检查区间是否与某一行有交集
bool overlapsLine(int l) {
return l >= start.line && l <= end.line;
}
@override
String toString() => '$start-$end';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LspRange && start == other.start && end == other.end;
@override
int get hashCode => Object.hash(start, end);
}
/// 诊断等级常量定义(对齐 LSP 规范)
abstract class LspDiagnosticSeverity {
static const int error = 1;
static const int warning = 2;
static const int information = 3;
static const int hint = 4;
}
/// 编译器诊断错误与告警
class LspDiagnostic {
final LspRange range;
final int severity; // 1: Error, 2: Warning, 3: Information, 4: Hint
final dynamic code;
final String? source;
final String message;
final dynamic data;
const LspDiagnostic({
required this.range,
this.severity = 1,
this.code,
this.source,
required this.message,
this.data,
});
bool get isError => severity == 1;
bool get isWarning => severity == 2;
factory LspDiagnostic.fromJson(Map<String, dynamic> json) {
return LspDiagnostic(
range: LspRange.fromJson(json['range'] as Map<String, dynamic>? ?? const {}),
severity: json['severity'] as int? ?? 1,
code: json['code'],
source: json['source'] as String?,
message: json['message'] as String? ?? '',
data: json['data'],
);
}
Map<String, dynamic> toJson() => {
'range': range.toJson(),
'severity': severity,
if (code != null) 'code': code,
if (source != null) 'source': source,
'message': message,
if (data != null) 'data': data,
};
}
/// 语义补全项
class LspCompletionItem {
final String label;
final int? kind;
final String? detail;
final String? documentation;
final String? sortText;
final String? filterText;
final String? insertText;
final int? insertTextFormat; // 1: PlainText, 2: Snippet
final dynamic textEdit;
const LspCompletionItem({
required this.label,
this.kind,
this.detail,
this.documentation,
this.sortText,
this.filterText,
this.insertText,
this.insertTextFormat,
this.textEdit,
});
factory LspCompletionItem.fromJson(Map<String, dynamic> json) {
String? doc;
final rawDoc = json['documentation'];
if (rawDoc is String) {
doc = rawDoc;
} else if (rawDoc is Map && rawDoc['value'] is String) {
doc = rawDoc['value'] as String;
}
return LspCompletionItem(
label: json['label'] as String? ?? '',
kind: json['kind'] as int?,
detail: json['detail'] as String?,
documentation: doc,
sortText: json['sortText'] as String?,
filterText: json['filterText'] as String?,
insertText: json['insertText'] as String?,
insertTextFormat: json['insertTextFormat'] as int?,
textEdit: json['textEdit'],
);
}
/// 补全文本内容
String get effectiveInsertText {
if (textEdit is Map && textEdit['newText'] is String) {
return textEdit['newText'] as String;
}
return insertText ?? label;
}
}
/// 快速修复与代码动作
class LspCodeAction {
final String title;
final String? kind;
final List<LspDiagnostic> diagnostics;
final bool isPreferred;
final LspWorkspaceEdit? edit;
const LspCodeAction({
required this.title,
this.kind,
this.diagnostics = const [],
this.isPreferred = false,
this.edit,
});
factory LspCodeAction.fromJson(Map<String, dynamic> json) {
final diagsRaw = json['diagnostics'] as List? ?? const [];
final diags = diagsRaw
.whereType<Map<String, dynamic>>()
.map((d) => LspDiagnostic.fromJson(d))
.toList();
LspWorkspaceEdit? wsEdit;
if (json['edit'] is Map) {
wsEdit = LspWorkspaceEdit.fromJson(json['edit'] as Map<String, dynamic>);
}
return LspCodeAction(
title: json['title'] as String? ?? '',
kind: json['kind'] as String?,
diagnostics: diags,
isPreferred: json['isPreferred'] as bool? ?? false,
edit: wsEdit,
);
}
}
class LspWorkspaceEdit {
final Map<String, List<LspTextEdit>> changes;
const LspWorkspaceEdit({this.changes = const {}});
factory LspWorkspaceEdit.fromJson(Map<String, dynamic> json) {
final rawChanges = json['changes'];
final Map<String, List<LspTextEdit>> result = {};
if (rawChanges is Map) {
rawChanges.forEach((uri, edits) {
if (edits is List) {
result[uri.toString()] = edits
.whereType<Map<String, dynamic>>()
.map((e) => LspTextEdit.fromJson(e))
.toList();
}
});
}
return LspWorkspaceEdit(changes: result);
}
}
class LspTextEdit {
final LspRange range;
final String newText;
const LspTextEdit({required this.range, required this.newText});
factory LspTextEdit.fromJson(Map<String, dynamic> json) {
return LspTextEdit(
range: LspRange.fromJson(json['range'] as Map<String, dynamic>? ?? const {}),
newText: json['newText'] as String? ?? '',
);
}
Map<String, dynamic> toJson() => {
'range': range.toJson(),
'newText': newText,
};
}
+240
View File
@@ -0,0 +1,240 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../models/lsp_language_config.dart';
import 'lsp_client.dart';
import 'lsp_diagnostics_store.dart';
import 'lsp_protocol.dart';
import 'proot_path_mapper.dart';
/// 单个语言服务会话(管理与后台进程的文档增量同步、智能补全与诊断流)
class LspSession {
final LspClient client;
final LspLanguageConfig config;
final String workspaceRoot;
final Map<String, int> _fileVersions = {};
final Map<String, Timer> _debounceTimers = {};
bool _isInitialized = false;
bool get isInitialized => _isInitialized;
LspSession({
required this.client,
required this.config,
required this.workspaceRoot,
}) {
_registerNotificationHandlers();
}
void _registerNotificationHandlers() {
client.onNotification('textDocument/publishDiagnostics', (params) {
if (params is Map<String, dynamic>) {
final uri = params['uri'] as String? ?? '';
final diagsRaw = params['diagnostics'] as List? ?? const [];
final diags = diagsRaw
.whereType<Map<String, dynamic>>()
.map((d) => LspDiagnostic.fromJson(d))
.toList();
final hostPath = _fromGuestUriToHostPath(uri);
LspDiagnosticsStore.instance.updateDiagnostics(hostPath, diags);
if (hostPath != uri) {
LspDiagnosticsStore.instance.updateDiagnostics(uri, diags);
}
}
});
}
/// 发送 initialize 握手报文
Future<bool> initialize() async {
final rootUri = _toGuestUri(workspaceRoot);
final guestRootPath = PRootPathMapper.toGuestPath(workspaceRoot, workspaceRoot);
final initParams = {
'processId': null,
'rootUri': rootUri,
'rootPath': guestRootPath,
'capabilities': {
'textDocument': {
'synchronization': {
'dynamicRegistration': false,
'willSave': false,
'willSaveWaitUntil': false,
'didSave': true,
},
'completion': {
'dynamicRegistration': false,
'completionItem': {
'snippetSupport': true,
'documentationFormat': ['markdown', 'plaintext'],
},
},
'publishDiagnostics': {
'relatedInformation': true,
},
'codeAction': {
'codeActionLiteralSupport': {
'codeActionKind': {
'valueSet': ['quickfix', 'refactor'],
},
},
},
},
},
};
try {
final res = await client.sendRequest('initialize', initParams);
if (res != null) {
client.sendNotification('initialized', {});
_isInitialized = true;
debugPrint('[LspSession] 语言服务初始化成功: ${config.name} (${config.serverCommand})');
return true;
}
} catch (e) {
debugPrint('[LspSession] 初始化失败: $e');
}
return false;
}
/// 文档打开通知
void didOpen(String filePath, String text) {
final uri = _toGuestUri(filePath);
_fileVersions[filePath] = 1;
client.sendNotification('textDocument/didOpen', {
'textDocument': {
'uri': uri,
'languageId': config.languageId,
'version': 1,
'text': text,
},
});
}
/// 文档内容变更通知(带 250ms 智能防抖)
void didChange(String filePath, String fullText) {
if (!_fileVersions.containsKey(filePath)) {
didOpen(filePath, fullText);
return;
}
_debounceTimers[filePath]?.cancel();
_debounceTimers[filePath] = Timer(const Duration(milliseconds: 250), () {
if (client.isClosed) return;
final uri = _toGuestUri(filePath);
final newVersion = (_fileVersions[filePath] ?? 1) + 1;
_fileVersions[filePath] = newVersion;
client.sendNotification('textDocument/didChange', {
'textDocument': {
'uri': uri,
'version': newVersion,
},
'contentChanges': [
{'text': fullText},
],
});
});
}
/// 文档关闭通知
void didClose(String filePath) {
_debounceTimers[filePath]?.cancel();
_debounceTimers.remove(filePath);
_fileVersions.remove(filePath);
final uri = _toGuestUri(filePath);
client.sendNotification('textDocument/didClose', {
'textDocument': {
'uri': uri,
},
});
}
/// 获取光标处语义补全项列表
Future<List<LspCompletionItem>> getCompletions(
String filePath,
int line,
int character,
) async {
final guestUri = _toGuestUri(filePath);
if (!client.isClosed && _isInitialized) {
try {
final res = await client.sendRequest('textDocument/completion', {
'textDocument': {'uri': guestUri},
'position': {'line': line, 'character': character},
});
if (res is List) {
return res
.whereType<Map<String, dynamic>>()
.map((item) => LspCompletionItem.fromJson(item))
.toList();
} else if (res is Map && res['items'] is List) {
final items = res['items'] as List;
return items
.whereType<Map<String, dynamic>>()
.map((item) => LspCompletionItem.fromJson(item))
.toList();
}
} catch (e) {
debugPrint('[LspSession] 获取补全失败: $e');
}
}
return const [];
}
/// 获取指定错误或位置的代码修复操作(QuickFix)
Future<List<LspCodeAction>> getCodeActions(
String filePath,
LspRange range,
List<LspDiagnostic> diagnostics,
) async {
if (!client.isClosed && _isInitialized) {
try {
final res = await client.sendRequest('textDocument/codeAction', {
'textDocument': {'uri': _toGuestUri(filePath)},
'range': range.toJson(),
'context': {
'diagnostics': diagnostics.map((d) => d.toJson()).toList(),
'only': ['quickfix'],
},
});
if (res is List) {
return res
.whereType<Map<String, dynamic>>()
.map((a) => LspCodeAction.fromJson(a))
.toList();
}
} catch (e) {
debugPrint('[LspSession] 获取 CodeAction 失败: $e');
}
}
return const [];
}
/// 转换宿主文件路径为容器内部映射的 URI
String _toGuestUri(String hostFilePath) {
return PRootPathMapper.toGuestUri(hostFilePath, workspaceRoot);
}
/// 将容器内部的 URI 反向还原为宿主文件绝对路径
String _fromGuestUriToHostPath(String guestUri) {
return PRootPathMapper.fromGuestUriToHostPath(guestUri, workspaceRoot);
}
Future<void> close() async {
for (final timer in _debounceTimers.values) {
timer.cancel();
}
_debounceTimers.clear();
_fileVersions.clear();
try {
await client.sendRequest('shutdown', null, const Duration(seconds: 1));
client.sendNotification('exit');
} catch (_) {}
client.close();
}
}
@@ -0,0 +1,84 @@
import 'package:re_editor/re_editor.dart';
import 'lsp_protocol.dart';
/// 负责将 LSP 服务端返回的 WorkspaceEdit / TextEdit 序列安全、有序地应用到当前编辑器控制器中
class LspWorkspaceEditApplier {
/// 将 [edit] 应用至 [controller]
static void applyWorkspaceEdit(
CodeLineEditingController controller,
LspWorkspaceEdit edit, {
required String currentFilePath,
}) {
final normalizedTarget = _normalize(currentFilePath);
List<LspTextEdit>? targetEdits;
for (final entry in edit.changes.entries) {
final normalizedUri = _normalize(entry.key);
if (normalizedTarget.endsWith(normalizedUri) ||
normalizedUri.endsWith(normalizedTarget) ||
normalizedTarget.toLowerCase() == normalizedUri.toLowerCase()) {
targetEdits = entry.value;
break;
}
}
if (targetEdits == null || targetEdits.isEmpty) return;
applyTextEdits(controller, targetEdits);
}
/// 依据 LSP 规范,对逆向排序后的编辑操作逐一应用,防止前序编辑破坏后续行列偏移
static void applyTextEdits(
CodeLineEditingController controller,
List<LspTextEdit> edits,
) {
if (edits.isEmpty) return;
// 逆序排序:先按行号降序,同行按列号降序
final sortedEdits = List<LspTextEdit>.from(edits)
..sort((a, b) {
final lineComp = b.range.start.line.compareTo(a.range.start.line);
if (lineComp != 0) return lineComp;
return b.range.start.character.compareTo(a.range.start.character);
});
final totalLines = controller.lineCount;
for (final te in sortedEdits) {
final startLine = te.range.start.line.clamp(0, totalLines - 1);
final endLine = te.range.end.line.clamp(0, totalLines - 1);
final startLineLen = controller.codeLines[startLine].text.length;
final endLineLen = controller.codeLines[endLine].text.length;
final startCol = te.range.start.character.clamp(0, startLineLen);
final endCol = te.range.end.character.clamp(0, endLineLen);
final selection = CodeLineSelection(
baseIndex: startLine,
baseOffset: startCol,
extentIndex: endLine,
extentOffset: endCol,
);
controller.replaceSelection(te.newText, selection);
}
}
static String _normalize(String input) {
String path = input;
if (path.startsWith('file://')) {
final uri = Uri.tryParse(path);
if (uri != null && uri.hasAbsolutePath) {
path = uri.toFilePath();
} else {
path = path.substring(7);
}
}
path = path.replaceAll('\\', '/');
if (path.length >= 2 && path[1] == ':') {
path = path[0].toLowerCase() + path.substring(1);
}
return path;
}
}
+71
View File
@@ -0,0 +1,71 @@
import 'package:path/path.dart' as p;
/// PRoot 容器路径与宿主文件路径双向映射器
///
/// 在 Android 手机端 PRoot 架构中:
/// - 宿主端文件真实路径例如:`/data/data/com.example/files/workspace/main.c` 或 Windows 开发测试路径
/// - PRoot 启动参数将工作区绑定挂载至容器内部 `/workspace`
/// - 发送给 LSP 服务端(如 clangd)的文档 URI 需映射为 `file:///workspace/...`
/// - 接收 LSP 服务端诊断或引用返回的容器 URI 需反向还原为宿主绝对路径
class PRootPathMapper {
const PRootPathMapper();
/// 转换宿主文件路径为容器内部映射的 URI
static String toGuestUri(String hostFilePath, String workspaceRoot) {
if (workspaceRoot.isEmpty) {
return _toFileUri(hostFilePath);
}
final normHost = p.normalize(hostFilePath).replaceAll('\\', '/');
final normRoot = p.normalize(workspaceRoot).replaceAll('\\', '/');
if (normHost == normRoot) {
return 'file:///workspace';
}
if (normHost.startsWith('$normRoot/')) {
final relative = normHost.substring(normRoot.length + 1);
return 'file:///workspace/$relative';
}
if (normHost.startsWith(normRoot)) {
final relative = normHost.substring(normRoot.length).replaceFirst(RegExp(r'^/'), '');
return 'file:///workspace/$relative';
}
return _toFileUri(hostFilePath);
}
/// 转换宿主文件路径为容器内部真实绝对路径(例如 /workspace/src/main.c)
static String toGuestPath(String hostFilePath, String workspaceRoot) {
final uri = toGuestUri(hostFilePath, workspaceRoot);
if (uri.startsWith('file://')) {
return uri.substring('file://'.length);
}
return uri;
}
/// 将容器内部的 URI 反向还原为宿主文件绝对路径
static String fromGuestUriToHostPath(String guestUri, String workspaceRoot) {
final normUri = guestUri.replaceAll('\\', '/');
if (normUri.startsWith('file:///workspace/')) {
final relative = normUri.substring('file:///workspace/'.length);
return p.join(workspaceRoot, relative).replaceAll('\\', '/');
}
if (normUri == 'file:///workspace') {
return workspaceRoot.replaceAll('\\', '/');
}
if (normUri.startsWith('file:///')) {
// 普通 file:/// 协议,若未挂载至 /workspace 则直接去除 file:// 前缀
return normUri.substring('file://'.length);
}
return guestUri;
}
static String _toFileUri(String path) {
final normalized = p.normalize(path).replaceAll('\\', '/');
if (normalized.startsWith('file://')) return normalized;
if (normalized.startsWith('/')) return 'file://$normalized';
return 'file:///$normalized';
}
}
+42 -28
View File
@@ -20,7 +20,7 @@ class LspConfigService extends ChangeNotifier {
List<LspLanguageConfig> get configs => List.unmodifiable(_configs);
bool get isLoaded => _isLoaded;
/// 获取配置文件路径: `<files>/internal_engine/lsp_languages.json`
/// 获取配置文件路径: `<files>/config/lsp_languages.json`
Future<File> getConfigFile() async {
final Directory baseDir;
if (customBaseDir != null) {
@@ -30,7 +30,28 @@ class LspConfigService extends ChangeNotifier {
final rootPath = p.basename(appDir.path) == 'files'
? appDir.path
: p.join(appDir.path, 'files');
baseDir = Directory(p.join(rootPath, 'internal_engine'));
baseDir = Directory(p.join(rootPath, 'config'));
// 自动迁移旧版本放置在 internal_engine 的配置文件并清理旧目录
try {
final legacyDir = Directory(p.join(rootPath, 'internal_engine'));
final legacyFile = File(p.join(legacyDir.path, 'lsp_languages.json'));
final targetFile = File(p.join(baseDir.path, 'lsp_languages.json'));
if (legacyFile.existsSync() && !targetFile.existsSync()) {
if (!baseDir.existsSync()) {
baseDir.createSync(recursive: true);
}
legacyFile.copySync(targetFile.path);
}
if (legacyDir.existsSync()) {
legacyDir.deleteSync(recursive: true);
debugPrint('[LspConfigService] 已迁移并清理旧 internal_engine 目录');
}
} catch (e) {
debugPrint('[LspConfigService] 清理旧 internal_engine 异常: $e');
}
}
if (!baseDir.existsSync()) {
@@ -39,7 +60,7 @@ class LspConfigService extends ChangeNotifier {
return File(p.join(baseDir.path, 'lsp_languages.json'));
}
/// 加载配置,若缺失预设语言则自动增量追加合并并回写
/// 加载已安装的配置列表。初始为空数组 [],不存在未安装的占位项
Future<List<LspLanguageConfig>> loadConfigs({bool forceReload = false}) async {
if (_isLoaded && !forceReload) {
return _configs;
@@ -50,34 +71,28 @@ class LspConfigService extends ChangeNotifier {
bool needSave = false;
if (!file.existsSync()) {
loaded = List.from(LspLanguageConfig.defaultPresets);
// 初始为空数组,写入持久化文件
loaded = [];
needSave = true;
} else {
try {
final content = file.readAsStringSync();
final dynamic raw = jsonDecode(content);
if (raw is List) {
loaded = raw
.map((e) => e is Map<String, dynamic>
? LspLanguageConfig.fromJson(e)
: null)
.whereType<LspLanguageConfig>()
.toList();
final content = file.readAsStringSync().trim();
if (content.isNotEmpty) {
final dynamic raw = jsonDecode(content);
if (raw is List) {
loaded = raw
.map((e) => e is Map<String, dynamic>
? LspLanguageConfig.fromJson(e)
: null)
.whereType<LspLanguageConfig>()
.toList();
}
}
} catch (e) {
debugPrint('读取 lsp_languages.json 异常: $e,使用默认预设');
loaded = List.from(LspLanguageConfig.defaultPresets);
debugPrint('读取 lsp_languages.json 异常: $e');
loaded = [];
needSave = true;
}
// 动态增量合并:对比官方预设,若预设中某项 id 本地缺失,则追加进去,默认 enabled: true
final existingIds = loaded.map((e) => e.id).toSet();
for (final preset in LspLanguageConfig.defaultPresets) {
if (!existingIds.contains(preset.id)) {
loaded.add(preset.copyWith(enabled: true));
needSave = true;
}
}
}
_configs = loaded;
@@ -118,9 +133,9 @@ class LspConfigService extends ChangeNotifier {
notifyListeners();
}
/// 恢复官方默认预设
/// 清空所有已配置的语言项
Future<void> resetToDefaults() async {
_configs = List.from(LspLanguageConfig.defaultPresets);
_configs = [];
await _writeToDisk();
notifyListeners();
}
@@ -131,11 +146,10 @@ class LspConfigService extends ChangeNotifier {
final normalized = ext.startsWith('.') ? ext.toLowerCase() : '.$ext'.toLowerCase();
for (final config in _configs) {
if (!config.enabled) continue;
for (final item in config.fileExtensions) {
final itemNorm = item.startsWith('.') ? item.toLowerCase() : '.$item'.toLowerCase();
if (itemNorm == normalized) {
return config;
return config.enabled ? config : null;
}
}
}
@@ -0,0 +1,76 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../../models/run_task.dart';
import 'project_module.dart';
import 'project_probe.dart';
/// Maven (Java) 工程模块:识别 pom.xml 或 mvnw 包装脚本
class MavenProjectModule extends ProjectModule {
@override
String get id => 'maven';
@override
String get displayName => 'Maven';
@override
List<String> get triggerFiles => const ['pom.xml', 'mvnw'];
@override
bool shouldActivate(Directory projectDir) {
return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync());
}
@override
List<String> get requiredToolchainKeys => const ['maven'];
@override
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
final root = probe.projectDir;
final hasWrapper = File(p.join(root.path, 'mvnw')).existsSync();
final cmdPrefix = hasWrapper ? './mvnw' : 'mvn';
return ModuleProbeResult.ok(id, [
RunTask(
id: 'detected_maven_package',
name: 'Maven: Package',
command: '$cmdPrefix package',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.inventory_2_outlined,
),
RunTask(
id: 'detected_maven_compile',
name: 'Maven: Compile',
command: '$cmdPrefix compile',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_maven_test',
name: 'Maven: Test',
command: '$cmdPrefix test',
source: TaskSource.detected,
group: 'verification',
moduleId: id,
icon: Icons.fact_check_outlined,
),
RunTask(
id: 'detected_maven_clean',
name: 'Maven: Clean',
command: '$cmdPrefix clean',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.cleaning_services_outlined,
),
]);
}
}
@@ -4,6 +4,9 @@ import 'package:flutter/foundation.dart';
import '../../models/notice_item.dart';
import '../../models/run_task.dart';
import '../background_task/background_task.dart';
import '../background_task/background_task_scheduler.dart';
import '../background_task/generic_background_task.dart';
import '../distro_manager.dart';
import '../toolchain_service.dart';
@@ -297,15 +300,34 @@ class ProjectProbe {
if (commands.isEmpty) return false;
final script = commands.join(' && ');
final result = await runHeadless(
script,
timeout: const Duration(minutes: 10),
onStdout: (chunk) {
final line = chunk.trim();
if (line.isNotEmpty) setInstallLine(line);
// 接入统一调度器:通过 TaskExecutionScope.packageManager 保证独占排他锁,
// 不与用户同时触发的 LSP 组件安装/卸载冲突
final task = GenericBackgroundTask<bool>(
id: 'probe:toolchains:${toolchainKeys.join('+')}',
scope: TaskExecutionScope.packageManager,
priority: TaskPriority.projectLifecycle,
showNotice: false, // 模块探测自身已有专用的 ModulePhaseText 弹窗显示
runner: (taskContext) async {
if (isCancelled || _disposed) return false;
final result = await runHeadless(
script,
timeout: const Duration(minutes: 10),
onStdout: (chunk) {
final line = chunk.trim();
if (line.isNotEmpty) setInstallLine(line);
},
);
return result != null && result.exitCode == 0;
},
);
return result != null && result.exitCode == 0;
try {
return await BackgroundTaskScheduler.instance.submit(task);
} catch (_) {
return false;
}
}
/// 更新安装进度行(带释放保护,避免取消/释放后写入已 dispose 的 notifier)
@@ -0,0 +1,103 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../../models/run_task.dart';
import 'project_module.dart';
import 'project_probe.dart';
/// Python 工程模块:识别 requirements.txt、pyproject.toml 等特征
class PythonProjectModule extends ProjectModule {
@override
String get id => 'python';
@override
String get displayName => 'Python';
@override
List<String> get triggerFiles => const [
'requirements.txt',
'pyproject.toml',
'setup.py',
'Pipfile',
];
@override
bool shouldActivate(Directory projectDir) {
return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync());
}
@override
List<String> get requiredToolchainKeys => const ['python3'];
@override
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
final tasks = <RunTask>[];
final root = probe.projectDir;
// 1. 依赖安装任务
if (File(p.join(root.path, 'requirements.txt')).existsSync()) {
tasks.add(
RunTask(
id: 'detected_python_pip_install',
name: 'Pip: Install Requirements',
command: 'pip3 install -r requirements.txt',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.download_outlined,
),
);
}
// 2. 主入口任务
if (File(p.join(root.path, 'main.py')).existsSync()) {
tasks.add(
RunTask(
id: 'detected_python_run_main',
name: 'Python: Run main.py',
command: 'python3 main.py',
source: TaskSource.detected,
group: 'application',
moduleId: id,
icon: Icons.play_circle_outline,
),
);
} else if (File(p.join(root.path, 'app.py')).existsSync()) {
tasks.add(
RunTask(
id: 'detected_python_run_app',
name: 'Python: Run app.py',
command: 'python3 app.py',
source: TaskSource.detected,
group: 'application',
moduleId: id,
icon: Icons.play_circle_outline,
),
);
}
// 3. 测试任务
final hasTestsDir = Directory(p.join(root.path, 'tests')).existsSync() ||
Directory(p.join(root.path, 'test')).existsSync();
final hasPytestIni = File(p.join(root.path, 'pytest.ini')).existsSync();
if (hasTestsDir || hasPytestIni) {
tasks.add(
RunTask(
id: 'detected_python_pytest',
name: 'Pytest: Run Tests',
command: 'pytest',
source: TaskSource.detected,
group: 'verification',
moduleId: id,
icon: Icons.fact_check_outlined,
),
);
}
return ModuleProbeResult.ok(id, tasks);
}
}
@@ -30,6 +30,12 @@ class SingleFileTaskDetector {
'.go',
'.rs',
'.js',
'.java',
'.ts',
'.mts',
'.lua',
'.pl',
'.php',
};
/// 检查给定文件路径是否属于支持的单文件任务类型
@@ -135,6 +141,52 @@ class SingleFileTaskDetector {
group: 'single_file',
icon: Icons.javascript,
);
case '.java':
return RunTask(
id: 'detected_single_java',
name: 'Java: $fileName',
command: 'java $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.code,
);
case '.ts':
case '.mts':
return RunTask(
id: 'detected_single_ts',
name: 'TypeScript: $fileName',
command: 'npx -y tsx $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.javascript,
);
case '.lua':
return RunTask(
id: 'detected_single_lua',
name: 'Lua: $fileName',
command: 'lua $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.code,
);
case '.pl':
return RunTask(
id: 'detected_single_perl',
name: 'Perl: $fileName',
command: 'perl $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.terminal,
);
case '.php':
return RunTask(
id: 'detected_single_php',
name: 'PHP: $fileName',
command: 'php $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.code,
);
default:
return null;
}
@@ -4,6 +4,9 @@ library;
export 'cargo_project_module.dart';
export 'cmake_project_module.dart';
export 'dart_project_module.dart';
export 'gradle_project_module.dart';
export 'make_project_module.dart';
export 'maven_project_module.dart';
export 'npm_project_module.dart';
export 'python_project_module.dart';
export 'single_file_task_detector.dart';
@@ -11,9 +11,11 @@ import 'project_modules/cmake_project_module.dart';
import 'project_modules/dart_project_module.dart';
import 'project_modules/gradle_project_module.dart';
import 'project_modules/make_project_module.dart';
import 'project_modules/maven_project_module.dart';
import 'project_modules/npm_project_module.dart';
import 'project_modules/project_module.dart';
import 'project_modules/project_probe.dart';
import 'project_modules/python_project_module.dart';
import 'project_modules/single_file_task_detector.dart';
/// 项目任务总调度(对标 VS Code Task Service / IDE 的 ProjectModel 协调器)
@@ -43,11 +45,13 @@ class ProjectTaskDispatcher {
void _registerDefaultModules() {
_modules.addAll([
GradleProjectModule(),
MavenProjectModule(),
CMakeProjectModule(),
CargoProjectModule(),
NpmProjectModule(),
MakeProjectModule(),
DartProjectModule(),
PythonProjectModule(),
]);
}
+54 -96
View File
@@ -10,161 +10,119 @@ class ToolchainRequirement {
/// 用户可见的工具名称/描述
final String displayName;
/// 针对不同发行版家族的自动安装指令
final Map<DistroFamily, String> installCommands;
/// Ubuntu 下的自动安装指令
final String installCommand;
const ToolchainRequirement({
required this.checkBinary,
required this.displayName,
required this.installCommands,
required this.installCommand,
});
/// 获取指定发行版家族下的安装命令(对于 Ubuntu/Debian 自动前置 dpkg 自愈修复,防止前序中断报错)
String? getInstallCommand(DistroFamily family) {
final cmd = installCommands[family];
if (cmd == null) return null;
if (family == DistroFamily.ubuntu || family == DistroFamily.debian) {
return 'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $cmd';
}
return cmd;
/// 获取安装命令(带自动修复前缀)
String get effectiveInstallCommand =>
'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $installCommand';
/// 兼容接口
String? getInstallCommand([DistroFamily? family]) {
if (family == DistroFamily.unknown) return null;
return effectiveInstallCommand;
}
}
/// 预编译软件源与工具链检测/安装适配服务
/// 预编译软件源与工具链检测/安装适配服务(专为 Ubuntu 24.04 深度优化)
class ToolchainService {
/// 已注册的常用编译器与开发工具链元数据
static const Map<String, ToolchainRequirement> supportedTools = {
'make': ToolchainRequirement(
checkBinary: 'make',
displayName: 'make 编译构建工具',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache make build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y make gcc gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
),
'cmake': ToolchainRequirement(
checkBinary: 'cmake',
displayName: 'cmake 构建套件',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache cmake make build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm cmake base-devel',
DistroFamily.fedora: 'dnf install -y cmake make gcc gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
),
'gcc': ToolchainRequirement(
checkBinary: 'gcc',
displayName: 'GCC C 语言编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache gcc musl-dev build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y gcc gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
),
'g++': ToolchainRequirement(
checkBinary: 'g++',
displayName: 'G++ C++ 编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache g++ musl-dev build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
),
'python3': ToolchainRequirement(
checkBinary: 'python3',
displayName: 'Python 3 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
),
'python': ToolchainRequirement(
checkBinary: 'python3',
displayName: 'Python 3 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
),
'npm': ToolchainRequirement(
checkBinary: 'npm',
displayName: 'Node.js 与 NPM 环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
DistroFamily.fedora: 'dnf install -y nodejs npm',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
),
'node': ToolchainRequirement(
checkBinary: 'node',
displayName: 'Node.js 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
DistroFamily.fedora: 'dnf install -y nodejs npm',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
),
'cargo': ToolchainRequirement(
checkBinary: 'cargo',
displayName: 'Rust 与 Cargo 工具链',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
DistroFamily.fedora: 'dnf install -y cargo rust',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
),
'rustc': ToolchainRequirement(
checkBinary: 'rustc',
displayName: 'Rust 编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
DistroFamily.fedora: 'dnf install -y cargo rust',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
),
'go': ToolchainRequirement(
checkBinary: 'go',
displayName: 'Go 语言环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache go',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
DistroFamily.arch: 'pacman -Sy --noconfirm go',
DistroFamily.fedora: 'dnf install -y golang',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
),
'gradle': ToolchainRequirement(
checkBinary: 'java',
displayName: 'Java / Gradle 运行时',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache openjdk17-jre-headless',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
DistroFamily.arch: 'pacman -Sy --noconfirm jdk-openjdk',
DistroFamily.fedora: 'dnf install -y java-latest-openjdk-devel',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
),
'java': ToolchainRequirement(
checkBinary: 'java',
displayName: 'Java 运行环境 (JDK)',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
),
'maven': ToolchainRequirement(
checkBinary: 'mvn',
displayName: 'Maven 构建工具',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y maven default-jdk-headless',
),
'mvn': ToolchainRequirement(
checkBinary: 'mvn',
displayName: 'Maven 构建工具',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y maven default-jdk-headless',
),
'lua': ToolchainRequirement(
checkBinary: 'lua',
displayName: 'Lua 解释器',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y lua5.4',
),
'perl': ToolchainRequirement(
checkBinary: 'perl',
displayName: 'Perl 解释器',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y perl',
),
'php': ToolchainRequirement(
checkBinary: 'php',
displayName: 'PHP 命令行环境',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y php-cli',
),
};
+17
View File
@@ -48,5 +48,22 @@ NoticeDisplay resolveNoticeDisplay(AppLocalizations l10n, NoticeText text) {
title: l10n.probeFailedTitle(text.moduleDisplayName),
subtitle: subtitle,
);
case ComponentInstallPhaseText():
final title = text.isQueued
? l10n.componentQueued(text.componentName)
: (text.isUninstall
? l10n.uninstallingComponent(text.componentName)
: l10n.installingComponent(text.componentName));
return NoticeDisplay(title: title, subtitle: text.detail);
case ComponentInstallDoneText():
final title = text.isUninstall
? l10n.uninstallComponentSuccess(text.componentName)
: l10n.installComponentSuccess(text.componentName);
return NoticeDisplay(title: title);
case ComponentInstallFailureText():
final title = text.isUninstall
? l10n.uninstallComponentFailed(text.error ?? '')
: l10n.installComponentFailed(text.error ?? '');
return NoticeDisplay(title: title, subtitle: text.error);
}
}
+8
View File
@@ -1,6 +1,7 @@
import 'package:path/path.dart' as p;
import 'package:re_editor/re_editor.dart';
import 'package:re_highlight/languages/all.dart';
import 'package:re_highlight/re_highlight.dart';
/// 语法高亮辅助类:
/// 1. 基于文件后缀与特殊文件名的 O(1) 语法匹配,彻底避免全量遍历
@@ -175,4 +176,11 @@ class SyntaxHighlightHelper {
}
return {langId: mode};
}
/// 获取指定文件对应的 re_highlight 原始 Mode 定义(用于提取语言关键字等)
static Mode? getGrammarModeForFile(String? filePath) {
final langId = getLanguageId(filePath);
if (langId == null) return null;
return builtinAllLanguages[langId];
}
}
+355 -220
View File
@@ -1,10 +1,14 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../l10n/app_localizations.dart';
import '../models/lsp_language_config.dart';
import '../providers/settings_provider.dart';
import '../services/internal_engine_service.dart';
import '../services/lsp/lsp_manager.dart';
import '../services/lsp_config_service.dart';
import '../utils/dialog_utils.dart';
import '../widgets/lsp_language_edit_dialog.dart';
import 'main_view.dart';
/// 代码补全与语言服务管理视图
class CodeCompletionManagementView extends StatefulWidget {
@@ -21,6 +25,9 @@ class _CodeCompletionManagementViewState
final _engineService = InternalEngineService.instance;
final Map<String, bool> _installedStatus = {};
final Set<String> _expandedConfigIds = {};
/// 记录正在进行后台安装/卸载任务的语言配置 ID 及其动作类型('install' 或 'uninstall')
final Map<String, String> _busyConfigActions = {};
bool _isLoadingStatus = false;
bool _engineReady = false;
@@ -61,12 +68,22 @@ class _CodeCompletionManagementViewState
if (mounted) {
setState(() {
_engineReady = true;
_installedStatus.addAll(newStatus);
_installedStatus
..clear()
..addAll(newStatus);
_isLoadingStatus = false;
});
}
}
Future<void> _handleToggleEnabled(LspLanguageConfig config) async {
final updated = config.copyWith(enabled: !config.enabled);
if (!updated.enabled) {
await LspManager.instance.stopSession(config.id);
}
await _lspService.updateConfig(updated);
}
Future<void> _handleEdit(LspLanguageConfig config) async {
final updated = await LspLanguageEditDialog.show(
context,
@@ -86,21 +103,57 @@ class _CodeCompletionManagementViewState
final newConfig = await LspLanguageEditDialog.show(context);
if (newConfig != null && mounted) {
final l10n = AppLocalizations.of(context);
await _lspService.updateConfig(newConfig);
if (mounted && l10n != null) {
DialogUtils.showSuccessToast(context, l10n.languageConfigSaved);
if (l10n == null) return;
final hasPkg = newConfig.package.trim().isNotEmpty;
if (hasPkg) {
final success = await DialogUtils.showSyncLoadingDialog<bool>(
context,
message: l10n.installingComponent(newConfig.package),
task: () => InternalEngineService.instance.installPackage(newConfig.package),
);
if (!mounted) return;
if (success) {
await _lspService.updateConfig(newConfig);
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(newConfig.name));
_checkCommandsStatus();
}
} else {
if (mounted) {
DialogUtils.showErrorToast(
context,
l10n.installComponentFailed('apt exit with non-zero code'),
);
}
}
} else {
// 无系统依赖包名直接保存配置
await _lspService.updateConfig(newConfig);
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.languageConfigSaved);
_checkCommandsStatus();
}
}
_checkCommandsStatus();
}
}
Future<void> _handleDelete(LspLanguageConfig config) async {
final l10n = AppLocalizations.of(context)!;
final isInstalled = _installedStatus[config.id] ?? false;
final hasPackage = config.package.trim().isNotEmpty;
final contentText = (isInstalled && hasPackage)
? l10n.deleteLanguageWithPackageConfirmMessage(config.name)
: l10n.deleteLanguageConfirmMessage(config.name);
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.deleteLanguageConfirmTitle),
content: Text(l10n.deleteLanguageConfirmMessage(config.name)),
content: Text(contentText),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
@@ -118,60 +171,49 @@ class _CodeCompletionManagementViewState
);
if (confirmed == true && mounted) {
// 1. 删除前先优雅停用后台语言服务并清理活跃会话
await LspManager.instance.stopSession(config.id);
if (!mounted) return;
if (isInstalled && hasPackage) {
// 同步弹出卸载 dialog,与安装组件保持一致的同步交互体验
final success = await DialogUtils.showSyncLoadingDialog<bool>(
context,
message: l10n.uninstallingComponent(config.name),
task: () => InternalEngineService.instance.uninstallPackage(
config.package,
serverCommand: config.serverCommand,
),
);
if (!mounted) return;
if (success == true) {
DialogUtils.showSuccessToast(
context,
l10n.uninstallComponentSuccess(config.name),
);
} else {
// 卸载失败:给出明确提示并中止,避免误删本地配置导致状态脱节
DialogUtils.showErrorToast(
context,
l10n.uninstallComponentFailed('apt purge non-zero or binary retained'),
);
return;
}
}
// 2. 卸载成功(或纯配置项无包):删除本地配置并清除防打扰白名单
await _lspService.deleteConfig(config.id);
setState(() {
_installedStatus.remove(config.id);
});
}
}
MainView.clearPromptedLanguage(config.id);
Future<void> _handleReset() async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.resetDefaultLanguages),
content: Text(l10n.resetDefaultLanguagesConfirm),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: Text(l10n.confirm),
),
],
),
);
if (confirmed == true && mounted) {
await _lspService.resetToDefaults();
_checkCommandsStatus();
}
}
Future<void> _handleInstallComponent(LspLanguageConfig config) async {
final l10n = AppLocalizations.of(context)!;
final success = await DialogUtils.showSyncLoadingDialog<bool>(
context,
message: l10n.installingComponent(config.apkPackage),
task: () => _engineService.installPackage(config.apkPackage),
);
if (!mounted) return;
if (success) {
DialogUtils.showSuccessToast(
context,
l10n.installComponentSuccess(config.name),
);
_checkCommandsStatus();
} else {
DialogUtils.showErrorToast(
context,
l10n.installComponentFailed('apk add exit with non-zero'),
);
if (mounted) {
setState(() {
_installedStatus.remove(config.id);
_expandedConfigIds.remove(config.id);
});
_checkCommandsStatus();
}
}
}
@@ -184,11 +226,6 @@ class _CodeCompletionManagementViewState
appBar: AppBar(
title: Text(l10n.codeCompletionManagement),
actions: [
IconButton(
icon: const Icon(Icons.restore),
tooltip: l10n.resetDefaultLanguages,
onPressed: _handleReset,
),
IconButton(
icon: const Icon(Icons.add),
tooltip: l10n.addLanguageConfig,
@@ -206,6 +243,8 @@ class _CodeCompletionManagementViewState
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
children: [
_buildCompletionSwitchesCard(context, theme, l10n),
const SizedBox(height: 12),
_buildEngineStatusCard(context, theme, l10n),
const SizedBox(height: 16),
Padding(
@@ -230,7 +269,10 @@ class _CodeCompletionManagementViewState
),
),
const SizedBox(height: 6),
...configs.map((cfg) => _buildLanguageItem(context, theme, l10n, cfg)),
if (configs.isEmpty)
_buildEmptyPlaceholder(context, theme, l10n)
else
...configs.map((cfg) => _buildLanguageItem(context, theme, l10n, cfg)),
],
),
);
@@ -239,6 +281,85 @@ class _CodeCompletionManagementViewState
);
}
Widget _buildCompletionSwitchesCard(
BuildContext context,
ThemeData theme,
AppLocalizations l10n,
) {
final settings = context.watch<SettingsProvider?>();
if (settings == null) return const SizedBox.shrink();
final colorScheme = theme.colorScheme;
return Card(
elevation: 0,
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.6)),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
l10n.completionSourceSection,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
color: colorScheme.primary,
),
),
),
SwitchListTile(
secondary: const Icon(Icons.hub_outlined),
title: Text(l10n.lspCompletionTitle),
value: settings.enableLspCompletion,
onChanged: (val) => settings.setEnableLspCompletion(val),
),
],
),
),
);
}
Widget _buildEmptyPlaceholder(
BuildContext context,
ThemeData theme,
AppLocalizations l10n,
) {
final colorScheme = theme.colorScheme;
return Container(
margin: const EdgeInsets.symmetric(vertical: 24),
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLowest,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.5),
),
),
child: Column(
children: [
Icon(
Icons.code_off_rounded,
size: 48,
color: colorScheme.outline,
),
const SizedBox(height: 12),
Text(
l10n.emptyLspLanguagesTitle,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
],
),
);
}
Widget _buildEngineStatusCard(
BuildContext context,
ThemeData theme,
@@ -247,20 +368,18 @@ class _CodeCompletionManagementViewState
final isInstalled = _engineReady;
final colorScheme = theme.colorScheme;
final (bgColor, borderColor, icon, statusText, subText) = isInstalled
final (bgColor, borderColor, icon, statusText) = isInstalled
? (
colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
colorScheme.outlineVariant,
Icon(Icons.check_circle_outline, color: colorScheme.primary, size: 28),
l10n.internalEngineStatusReady,
'Alpine Linux (musl libc)',
)
: (
colorScheme.errorContainer.withValues(alpha: 0.3),
colorScheme.error.withValues(alpha: 0.5),
Icon(Icons.warning_amber_outlined, color: colorScheme.error, size: 28),
l10n.internalEngineStatusNotReady,
l10n.internalEngineExtracting,
);
return Card(
@@ -277,25 +396,12 @@ class _CodeCompletionManagementViewState
icon,
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.internalEngineTitle,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 2),
Text(
'$statusText • $subText',
style: theme.textTheme.bodySmall?.copyWith(
color: isInstalled
? colorScheme.onSurfaceVariant
: colorScheme.error,
),
),
],
child: Text(
statusText,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
color: isInstalled ? null : colorScheme.error,
),
),
),
if (!isInstalled)
@@ -320,163 +426,192 @@ class _CodeCompletionManagementViewState
AppLocalizations l10n,
LspLanguageConfig config,
) {
final isInstalled = _installedStatus[config.id] ?? false;
final isExpanded = _expandedConfigIds.contains(config.id);
final busyAction = _busyConfigActions[config.id];
final isBusy = busyAction != null;
final colorScheme = theme.colorScheme;
// 状态描边:正在处理为品牌强调色(Primary);启用状态为绿色;未启用时保持普通灰色描边
final BorderSide borderSide;
if (isBusy) {
borderSide = BorderSide(color: colorScheme.primary, width: 1.5);
} else if (config.enabled) {
borderSide = const BorderSide(color: Colors.green, width: 1.5);
} else {
borderSide = BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.5));
}
return Card(
elevation: 0,
margin: const EdgeInsets.symmetric(vertical: 6),
color: colorScheme.surfaceContainerLow,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.5)),
side: borderSide,
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 16,
backgroundColor: colorScheme.primaryContainer,
child: Text(
config.name.isNotEmpty ? config.name.substring(0, 1).toUpperCase() : '?',
style: TextStyle(
color: colorScheme.onPrimaryContainer,
fontWeight: FontWeight.bold,
fontSize: 14,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 头部:点击折叠/展开,仅显示头像、主标题和折叠指示图标
InkWell(
onTap: () {
setState(() {
if (isExpanded) {
_expandedConfigIds.remove(config.id);
} else {
_expandedConfigIds.add(config.id);
}
});
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 12.0),
child: Row(
children: [
CircleAvatar(
radius: 16,
backgroundColor: config.enabled
? colorScheme.primaryContainer
: colorScheme.surfaceContainerHighest,
child: Text(
config.name.isNotEmpty ? config.name.substring(0, 1).toUpperCase() : '?',
style: TextStyle(
color: config.enabled
? colorScheme.onPrimaryContainer
: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
const SizedBox(width: 12),
Expanded(
child: Row(
children: [
Flexible(
child: Text(
config.name,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: config.enabled ? null : colorScheme.onSurfaceVariant,
),
overflow: TextOverflow.ellipsis,
),
),
if (isBusy) ...[
const SizedBox(width: 8),
SizedBox(
width: 12,
height: 12,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.primary,
),
),
const SizedBox(width: 6),
Text(
busyAction == 'uninstall'
? l10n.uninstallingStatus
: l10n.installingStatus,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.primary,
fontWeight: FontWeight.w500,
),
),
const SizedBox(width: 8),
_buildStatusBadge(theme, l10n, isInstalled),
],
),
Text(
'${config.serverCommand} (${config.apkPackage}) • id: ${config.languageId}',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
],
),
),
Icon(
isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
color: colorScheme.onSurfaceVariant,
),
],
),
),
),
// 展开区域:显示文件扩展名标签与功能菜单选项
if (isExpanded) ...[
const Divider(height: 1),
Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 文件后缀标签
Wrap(
spacing: 6,
runSpacing: 4,
children: config.fileExtensions.map(
(ext) => Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: Text(
ext,
style: theme.textTheme.labelSmall?.copyWith(
fontFamily: 'JetBrains Mono',
color: colorScheme.onSurfaceVariant,
),
),
),
).toList(),
),
const SizedBox(height: 12),
// 功能菜单:启用/停用、安装组件(若未安装)、编辑、删除
// 正在进行后台任务时,所有操作均被禁用以防止并发冲突
Wrap(
spacing: 8,
runSpacing: 8,
children: [
// 启用 / 停用
if (!isBusy)
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
),
onPressed: () => _handleToggleEnabled(config),
icon: Icon(
config.enabled ? Icons.pause_circle_outline : Icons.play_circle_outline,
size: 16,
),
label: Text(config.enabled ? l10n.disable : l10n.enable),
),
// 编辑配置(后台任务进行中禁用)
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
),
onPressed: isBusy ? null : () => _handleEdit(config),
icon: const Icon(Icons.edit_outlined, size: 16),
label: Text(l10n.edit),
),
// 删除配置(后台任务进行中禁用)
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: isBusy ? colorScheme.outline : colorScheme.error,
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
),
onPressed: isBusy ? null : () => _handleDelete(config),
icon: const Icon(Icons.delete_outline, size: 16),
label: Text(l10n.delete),
),
],
),
),
IconButton(
icon: const Icon(Icons.edit_outlined, size: 20),
tooltip: l10n.editLanguageConfig,
onPressed: () => _handleEdit(config),
),
IconButton(
icon: const Icon(Icons.delete_outline, size: 20),
tooltip: l10n.delete,
onPressed: () => _handleDelete(config),
),
],
),
const SizedBox(height: 8),
Wrap(
spacing: 6,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
...config.fileExtensions.map(
(ext) => Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: Text(
ext,
style: theme.textTheme.labelSmall?.copyWith(
fontFamily: 'JetBrains Mono',
color: colorScheme.onSurfaceVariant,
),
),
),
),
if (!isInstalled)
Padding(
padding: const EdgeInsets.only(left: 4),
child: InkWell(
borderRadius: BorderRadius.circular(6),
onTap: () => _handleInstallComponent(config),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: colorScheme.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.download, size: 14, color: colorScheme.primary),
const SizedBox(width: 4),
Text(
l10n.installComponent,
style: theme.textTheme.labelSmall?.copyWith(
color: colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
],
],
),
),
],
),
),
);
}
Widget _buildStatusBadge(
ThemeData theme,
AppLocalizations l10n,
bool isInstalled,
) {
final (bgColor, fgColor, text) = isInstalled
? (
Colors.green.withValues(alpha: 0.15),
Colors.green.shade700,
l10n.installedStatus,
)
: (
Colors.grey.withValues(alpha: 0.2),
Colors.grey.shade700,
l10n.notInstalledStatus,
);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(4),
),
child: Text(
text,
style: TextStyle(
color: fgColor,
fontSize: 10,
fontWeight: FontWeight.bold,
),
],
),
);
}
-433
View File
@@ -1,433 +0,0 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/services/distro_download_manager.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
/// 独立的系统管理与发行版包选择视图页面
///
/// 功能:
/// 1. AppBar 包含返回键与标题“系统管理”(遵循 l10n 国际化)。
/// 2. 列举当前架构支持的系统安装包(左侧图标、两行名称与版本,无高亮选框,无“内置”字样)。
/// 3. 安装包项分为两种状态:
/// - 已就绪 (zip 存在):
/// * 不显示“已安装”文本,不显示“安装”按键;
/// * Ubuntu 和 Alpine 为内置包,受保护右侧不显示删除按键;
/// * 在线下载的系统包右侧显示红色删除按钮(二次确认后居中同步转圈删除离线包);
/// * 用户直接点击该项卡片,即代表选中该安装包,返回上一页进行解压创建系统。
/// - 未下载 / 下载中:
/// * 未下载显示“下载”按键;
/// * 下载中显示百分比进度条与取消按键(取消后清空临时文件)。
class DistroManagementView extends StatefulWidget {
const DistroManagementView({super.key});
@override
State<DistroManagementView> createState() => _DistroManagementViewState();
}
class _DistroManagementViewState extends State<DistroManagementView> {
final DistroDownloadManager _downloadManager = DistroDownloadManager();
final Set<String> _downloadedPackageIds = {};
@override
void initState() {
super.initState();
_downloadManager.addListener(_onDownloadProgressChanged);
_checkDownloadedPackages();
}
@override
void dispose() {
_downloadManager.removeListener(_onDownloadProgressChanged);
super.dispose();
}
void _onDownloadProgressChanged() {
if (mounted) {
for (final entry in _downloadManager.allProgress.entries) {
if (entry.value.state == DistroDownloadState.completed) {
_downloadedPackageIds.add(entry.key);
}
}
setState(() {});
}
}
Future<void> _checkDownloadedPackages() async {
final distros = DistroRepository.currentArchDistros;
final Set<String> downloaded = {};
for (final d in distros) {
if (!d.isBuiltin && d.currentPackageSource != null) {
if (await _downloadManager.isPackageDownloaded(d.id, d.currentPackageSource)) {
downloaded.add(d.id);
}
}
}
for (final entry in _downloadManager.allProgress.entries) {
if (entry.value.state == DistroDownloadState.completed) {
downloaded.add(entry.key);
}
}
if (mounted) {
setState(() {
_downloadedPackageIds.clear();
_downloadedPackageIds.addAll(downloaded);
});
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
// 当前架构支持的发行版清单
final distros = DistroRepository.currentArchDistros;
return Scaffold(
appBar: AppBar(
title: Text(
l10n.distroManagementTitle,
style: const TextStyle(fontWeight: FontWeight.bold),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
),
body: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
itemCount: distros.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final item = distros[index];
final downloadProgress = _downloadManager.getProgress(item.id);
final isDownloaded = _downloadedPackageIds.contains(item.id) ||
downloadProgress?.state == DistroDownloadState.completed;
final isReady = item.isBuiltin || isDownloaded;
final isDownloading = downloadProgress?.state == DistroDownloadState.downloading;
return _buildDistroCard(
context: context,
theme: theme,
l10n: l10n,
item: item,
isReady: isReady,
isDownloading: isDownloading,
downloadProgress: downloadProgress,
);
},
),
);
}
Widget _buildDistroCard({
required BuildContext context,
required ThemeData theme,
required AppLocalizations l10n,
required DistroManifestItem item,
required bool isReady,
required bool isDownloading,
required DistroDownloadProgress? downloadProgress,
}) {
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
side: BorderSide(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
width: 1.0,
),
),
color: theme.colorScheme.surface,
child: InkWell(
borderRadius: BorderRadius.circular(12.0),
onTap: isReady
? () {
// 点击已就绪的安装包 item:代表选择该 zip,返回上一页解压创建系统
Navigator.of(context).pop(item);
}
: null,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
// 1. 系统左侧品牌图标
Container(
width: 44,
height: 44,
padding: const EdgeInsets.all(6.0),
decoration: BoxDecoration(
color: item.brandColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: item.brandColor.withValues(alpha: 0.3),
width: 1.0,
),
),
child: item.assetIconPath != null
? Image.asset(
item.assetIconPath!,
fit: BoxFit.contain,
errorBuilder: (_, _, _) => Icon(
item.iconData,
color: item.brandColor,
size: 26,
),
)
: Icon(
item.iconData,
color: item.brandColor,
size: 26,
),
),
const SizedBox(width: 14),
// 2. 中间两行文本 (系统名与推荐标签 + 版本)
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
item.name,
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
if (item.isRecommended) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 2.0),
decoration: BoxDecoration(
color: Colors.amber.shade700.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(6.0),
border: Border.all(
color: Colors.amber.shade800.withValues(alpha: 0.4),
width: 0.8,
),
),
child: Text(
l10n.recommendedTag,
style: TextStyle(
fontSize: 10.5,
fontWeight: FontWeight.bold,
color: Colors.amber.shade800,
),
),
),
],
],
),
const SizedBox(height: 3),
Text(
item.version,
style: TextStyle(
fontSize: 12.0,
color: theme.colorScheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
// 3. 右侧状态与操作按钮
const SizedBox(width: 10),
_buildTrailingAction(
context: context,
theme: theme,
l10n: l10n,
item: item,
isReady: isReady,
isDownloading: isDownloading,
downloadProgress: downloadProgress,
),
],
),
// 若处于下载中,展示下载进度条与百分比
if (isDownloading && downloadProgress != null) ...[
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(4.0),
child: LinearProgressIndicator(
value: downloadProgress.totalBytes > 0
? downloadProgress.progress
: null,
minHeight: 5,
),
),
),
const SizedBox(width: 10),
Text(
'${(downloadProgress.progress * 100).toStringAsFixed(0)}%',
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w600,
color: theme.colorScheme.primary,
),
),
],
),
],
],
),
),
),
);
}
Widget _buildTrailingAction({
required BuildContext context,
required ThemeData theme,
required AppLocalizations l10n,
required DistroManifestItem item,
required bool isReady,
required bool isDownloading,
required DistroDownloadProgress? downloadProgress,
}) {
if (isReady) {
// 对于已就绪 (已安装) 的 item (zip 文件):
// 不显示“已安装”文本,不显示“安装”按键。
// 对于内置 ubuntu 和 alpine,受保护无按键 (SizedBox.shrink);
// 其他在线下载完成的包,右侧直接显示红色删除按钮
if (item.isBuiltin) {
return const SizedBox.shrink();
}
return IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.redAccent, size: 22),
tooltip: l10n.deletePackageTooltip,
onPressed: () => _handleDeleteDownloadedPackage(item),
);
}
if (isDownloading) {
// 下载中状态:显示取消下载按钮
return IconButton(
icon: const Icon(Icons.cancel_outlined, color: Colors.grey, size: 22),
tooltip: l10n.cancelDownloadAction,
onPressed: () => _handleCancelDownload(item),
);
}
// 未就绪/未下载状态:显示下载按钮
return FilledButton.tonalIcon(
icon: const Icon(Icons.download_outlined, size: 18),
label: Text(l10n.downloadAction),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
textStyle: const TextStyle(fontSize: 13.0),
),
onPressed: () => _handleStartDownload(item),
);
}
/// 启动在线下载
Future<void> _handleStartDownload(DistroManifestItem item) async {
final url = item.currentPackageSource;
final l10n = AppLocalizations.of(context)!;
final settings = context.read<SettingsProvider>();
final mirror = settings.downloadMirror;
if (url == null || url.isEmpty) return;
// 前置资源检测:若已下载完备,立即更新状态并拒绝重复下载
if (await _downloadManager.isPackageDownloaded(item.id, url)) {
if (mounted) {
setState(() {
_downloadedPackageIds.add(item.id);
});
}
return;
}
final targetFile = await _downloadManager.startDownload(
distroId: item.id,
downloadUrl: url,
mirror: mirror,
manifestItem: item,
);
if (targetFile != null && mounted) {
setState(() {
_downloadedPackageIds.add(item.id);
});
} else if (mounted) {
final progress = _downloadManager.getProgress(item.id);
if (progress?.state == DistroDownloadState.failed) {
DialogUtils.showErrorToast(
context,
l10n.downloadFailed(progress?.errorMessage ?? ''),
);
}
}
}
/// 取消下载确认弹窗
Future<void> _handleCancelDownload(DistroManifestItem item) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showConfirmDialog(
context,
title: l10n.cancelDownloadConfirmTitle,
message: l10n.cancelDownloadConfirmMessage,
);
if (confirmed && mounted) {
await _downloadManager.cancelDownload(item.id);
}
}
/// 删除已下载的系统安装包(弹确认 Dialog -> 居中转圈同步 Dialog -> 完成)
Future<void> _handleDeleteDownloadedPackage(DistroManifestItem item) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
context,
title: l10n.deletePackageConfirmTitle,
message: l10n.deletePackageConfirmMessage(item.name),
confirmText: l10n.permanentDelete,
);
if (!confirmed || !mounted) return;
// 弹出居中转圈的同步等待弹窗,直至删除完毕
await DialogUtils.showSyncLoadingDialog<void>(
context,
message: l10n.deletingPackageProgress,
task: () async {
try {
await _downloadManager.deletePackage(item.id, item.currentPackageSource);
if (mounted) {
setState(() {
_downloadedPackageIds.remove(item.id);
});
}
} catch (e) {
if (mounted) {
DialogUtils.showErrorToast(context, e.toString());
}
}
},
);
if (mounted) {
DialogUtils.showToast(context, l10n.deletePackageSuccess(item.name));
}
}
}
+157 -47
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:io';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/run_task.dart';
import 'package:code_editor/providers/distro_provider.dart';
@@ -18,12 +19,15 @@ 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/providers/notice_center.dart';
import 'package:code_editor/widgets/distro_selector_dialog.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/widgets/distro_extract_dialog.dart';
import 'package:code_editor/widgets/notice_host.dart';
import 'package:code_editor/widgets/probe_cancel_guard.dart';
import 'package:code_editor/widgets/run_tasks_dialog.dart';
import 'package:code_editor/models/lsp_language_config.dart';
import 'package:code_editor/services/file_service.dart';
import 'package:code_editor/services/internal_engine_service.dart';
import 'package:code_editor/services/lsp/lsp_manager.dart';
import 'package:code_editor/services/lsp_config_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -33,6 +37,11 @@ import 'package:provider/provider.dart';
class MainView extends StatefulWidget {
const MainView({super.key});
/// 清除指定语言或全部语言的防打扰提示记录(卸载组件后恢复提示资格并重置当前文件检查)
static void clearPromptedLanguage(String? languageId) {
_MainViewState.clearPromptedLanguage(languageId);
}
@override
State<MainView> createState() => _MainViewState();
}
@@ -43,12 +52,23 @@ class _MainViewState extends State<MainView> {
/// 最近一次已触发探测的 (工程, 系统) 组合,用于去重与"系统就绪后补探测"
String? _lastProbeKey;
String? _lastActiveFile;
static String? _globalLastActiveFile;
static final Set<String> _promptedLspLanguages = {};
/// 清除指定语言或全部语言的防打扰提示记录(卸载组件后恢复提示资格并重置当前文件检查)
static void clearPromptedLanguage(String? languageId) {
if (languageId == null) {
_promptedLspLanguages.clear();
} else {
_promptedLspLanguages.remove(languageId);
}
_globalLastActiveFile = null;
}
@override
void initState() {
super.initState();
LspConfigService.instance.addListener(_handleLspConfigChanged);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
InternalEngineService.instance.ensureEngineReady(context);
@@ -57,25 +77,101 @@ class _MainViewState extends State<MainView> {
});
}
void _checkLspForFile(String filePath) async {
final ext = p.extension(filePath);
if (ext.isEmpty) return;
await LspConfigService.instance.loadConfigs();
final config = LspConfigService.instance.findByExtension(ext);
if (config == null) return;
@override
void dispose() {
LspConfigService.instance.removeListener(_handleLspConfigChanged);
super.dispose();
}
if (!await InternalEngineService.instance.isEngineInstalled()) return;
void _handleLspConfigChanged() {
if (!mounted) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_syncLspForOpenTabs();
});
}
final isInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand);
if (!isInstalled && mounted) {
if (!_promptedLspLanguages.contains(config.id)) {
_promptedLspLanguages.add(config.id);
_promptInstallLspComponent(config);
Future<void> _syncLspForOpenTabs({String? preferredFilePath}) async {
if (!mounted) return;
final tabProvider = _getTabProvider(context);
final projectProvider = _getProjectProvider(context);
final workspaceRoot = projectProvider.rootPath;
final openTabs = tabProvider.openTabs;
final currentPath = preferredFilePath ?? tabProvider.currentFilePath;
final filesToSync = <String, String>{};
for (final tab in openTabs) {
filesToSync[tab.path] = tab.content;
}
if (currentPath != null && !filesToSync.containsKey(currentPath)) {
filesToSync[currentPath] = '';
}
for (final entry in filesToSync.entries) {
final path = entry.key;
final ext = p.extension(path);
if (ext.isEmpty) continue;
final config = LspConfigService.instance.findByExtension(ext);
if (config == null || !config.enabled) continue;
final isCmdInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand);
if (!isCmdInstalled) continue;
final existingSession = LspManager.instance.getExistingSession(path);
if (existingSession == null || !existingSession.isInitialized) {
String content = entry.value;
if (content.isEmpty && File(path).existsSync()) {
try {
content = await FileService.instance.readFileContent(path);
} catch (_) {}
}
await LspManager.instance.onFileOpened(
path,
content,
workspaceRoot: workspaceRoot,
);
}
}
}
Future<void> _promptInstallLspComponent(LspLanguageConfig config) async {
void _checkLspForFile(String filePath) async {
final ext = p.extension(filePath);
if (ext.isEmpty) return;
await LspConfigService.instance.loadConfigs();
// 1. 先检查已安装配置中是否有匹配此后缀的组件
final existing = LspConfigService.instance.findByExtension(ext);
if (existing != null) return;
final engineInstalled = await InternalEngineService.instance.isEngineInstalled();
if (!engineInstalled) return;
// 2. 未在已安装配置中,查找代码内置语言预设模版
final builtin = LspLanguageConfig.findBuiltinByExtension(ext);
if (builtin == null) return;
final isInstalled = await InternalEngineService.instance.isCommandInstalled(builtin.serverCommand);
if (isInstalled) {
// 若底层环境意外已存在该命令(例如系统自带或此前安装过),直接补充入库
await LspConfigService.instance.updateConfig(builtin);
if (mounted) {
await _syncLspForOpenTabs(preferredFilePath: filePath);
}
return;
}
if (mounted) {
final alreadyPrompted = _promptedLspLanguages.contains(builtin.id);
if (!alreadyPrompted) {
_promptedLspLanguages.add(builtin.id);
_promptInstallLspComponent(builtin, targetFilePath: filePath);
}
}
}
Future<void> _promptInstallLspComponent(LspLanguageConfig config, {String? targetFilePath}) async {
final l10n = AppLocalizations.of(context);
if (l10n == null || !mounted) return;
@@ -83,7 +179,7 @@ class _MainViewState extends State<MainView> {
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.lspPackageMissingTitle(config.name)),
content: Text(l10n.lspPackageMissingMessage(config.apkPackage, config.serverCommand)),
content: Text(l10n.lspPackageMissingMessage),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
@@ -100,15 +196,23 @@ class _MainViewState extends State<MainView> {
if (install == true && mounted) {
final success = await DialogUtils.showSyncLoadingDialog<bool>(
context,
message: l10n.installingComponent(config.apkPackage),
task: () => InternalEngineService.instance.installPackage(config.apkPackage),
message: l10n.installingComponent(config.package),
task: () => InternalEngineService.instance.installPackage(config.package),
);
if (!mounted) return;
if (success) {
DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(config.name));
} else {
DialogUtils.showErrorToast(context, l10n.installComponentFailed('apk add exit with non-zero'));
if (mounted) {
if (success) {
await LspConfigService.instance.updateConfig(config);
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(config.name));
await _syncLspForOpenTabs(preferredFilePath: targetFilePath);
}
} else {
DialogUtils.showErrorToast(
context,
l10n.installComponentFailed('apt exit non-zero'),
);
}
}
}
}
@@ -182,7 +286,7 @@ class _MainViewState extends State<MainView> {
}
}
/// 提示用户缺失 Linux 执行环境并引导前往系统管理进行配置
/// 提示用户缺失 Linux 执行环境并引导解压安装 Ubuntu
void _showMissingDistroDialog(BuildContext context, String? targetDistro) {
final l10n = AppLocalizations.of(context)!;
showDialog<void>(
@@ -212,12 +316,23 @@ class _MainViewState extends State<MainView> {
child: Text(l10n.cancel),
),
ElevatedButton.icon(
onPressed: () {
onPressed: () async {
Navigator.of(ctx).pop();
DistroSelectorDialog.show(context);
final distroProvider = _getDistroProvider(context);
if (distroProvider != null) {
await DistroExtractDialog.show(
context: context,
systemName: DistroRepository.defaultSystemName,
task: (onProgress, isCancelled) => distroProvider.importBuiltinUbuntu(
systemName: DistroRepository.defaultSystemName,
onProgress: onProgress,
isCancelled: isCancelled,
),
);
}
},
icon: const Icon(Icons.dns_outlined, size: 18),
label: Text(l10n.systemManagement),
icon: const Icon(Icons.system_update_alt, size: 18),
label: Text(l10n.installNow),
),
],
),
@@ -230,24 +345,14 @@ class _MainViewState extends State<MainView> {
final distroProvider = _getDistroProvider(context);
final distroManager = DistroManager();
try {
var targetDistro = distroProvider?.selectedSystem;
if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) {
if (distroProvider != null) {
final isInstalled = await distroManager.isSystemInstalled(DistroRepository.defaultSystemName);
if (isInstalled) {
if (distroProvider != null && distroProvider.selectedSystem == null) {
await distroProvider.refreshSystems();
targetDistro = distroProvider.selectedSystem;
}
if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) {
final physicalSystems = await distroManager.listInstalledSystems();
if (physicalSystems.isNotEmpty) {
targetDistro = physicalSystems.first;
await distroProvider?.selectSystem(targetDistro);
}
}
return DistroRepository.defaultSystemName;
}
final ok = targetDistro != null && await distroManager.isSystemInstalled(targetDistro);
return ok ? targetDistro : null;
return null;
} catch (e) {
debugPrint('[MainView] 系统可用性解析失败: $e');
return null;
@@ -325,6 +430,10 @@ class _MainViewState extends State<MainView> {
final runProvider = _getRunProvider(context);
if (runProvider == null) return;
// 确保针对当前活动文件刷新单文件任务(支持当前文件单任务联动)
final currentFilePath = _getTabProvider(context).currentFilePath;
runProvider.refreshSingleFileTask(currentFilePath: currentFilePath);
// 优先: 最近运行的任务(若已持久化并存在且确实属于当前打开的工程)
if (runProvider.currentProjectRoot == rootPath && runProvider.lastRunTask != null) {
_executeRunTask(context, runProvider.lastRunTask!);
@@ -445,7 +554,7 @@ class _MainViewState extends State<MainView> {
DialogUtils.showSuccessToast(
context,
l10n.detectCompletedMessage(runProvider.detectedTasks.length),
l10n.detectCompletedMessage(runProvider.allTasks.length),
);
}
@@ -481,11 +590,12 @@ class _MainViewState extends State<MainView> {
final systemName = _getDistroProvider(context, listen: true)?.selectedSystem;
final probeKey = (rootPath == null || systemName == null) ? null : '$rootPath|$systemName';
if (currentFile != null && currentFile != _lastActiveFile) {
_lastActiveFile = currentFile;
if (currentFile != null && currentFile != _globalLastActiveFile) {
_globalLastActiveFile = currentFile;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_checkLspForFile(currentFile);
runProvider?.refreshSingleFileTask(currentFilePath: currentFile);
}
});
}
@@ -515,7 +625,7 @@ class _MainViewState extends State<MainView> {
if (l10n != null && runProvider != null) {
DialogUtils.showSuccessToast(
this.context,
l10n.detectCompletedMessage(runProvider.detectedTasks.length),
l10n.detectCompletedMessage(runProvider.allTasks.length),
);
}
});
+1 -104
View File
@@ -1,6 +1,5 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/models/editor_theme.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:code_editor/providers/settings_provider.dart';
@@ -84,15 +83,7 @@ class SettingsView extends StatelessWidget {
const Divider(height: 32, indent: 16, endIndent: 16),
// ==============================
// 5. 下载分组 (Download)
// ==============================
_buildSectionHeader(context, l10n.downloadSection),
_buildDownloadSourceTile(context, provider, l10n),
const Divider(height: 32, indent: 16, endIndent: 16),
// ==============================
// 6. 语言分组 (Language)
// 5. 语言分组 (Language)
// ==============================
_buildSectionHeader(context, l10n.languageSection),
_buildLanguageTile(context, provider, l10n),
@@ -1139,98 +1130,4 @@ class SettingsView extends StatelessWidget {
},
);
}
/// 下载:下载源设置条目
Widget _buildDownloadSourceTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
final currentMirrorId = provider.downloadMirrorId;
return ListTile(
leading: Icon(Icons.cloud_download_outlined, color: theme.colorScheme.primary),
title: Text(l10n.downloadSource),
subtitle: Text(l10n.mirrorName(currentMirrorId)),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showDownloadSourceSelector(context, provider, l10n);
},
);
}
/// 显示下载源底部选择器(与字体选择器一致的弹窗体验)
void _showDownloadSourceSelector(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (sheetContext) {
final theme = Theme.of(context);
final mirrors = DistroRepository.availableMirrors;
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(sheetContext).size.height * 0.65,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
l10n.selectDownloadSource,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
const Divider(height: 1),
Expanded(
child: ListView.builder(
itemCount: mirrors.length,
itemBuilder: (context, index) {
final item = mirrors[index];
final isSelected = item.id == provider.downloadMirrorId;
return ListTile(
leading: Icon(
Icons.dns_outlined,
color: isSelected ? theme.colorScheme.primary : null,
),
title: Text(
l10n.mirrorName(item.id),
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected ? theme.colorScheme.primary : null,
),
),
subtitle: Text(
item.baseUrl,
style: TextStyle(
fontSize: 12.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
trailing: isSelected
? Icon(Icons.check, color: theme.colorScheme.primary)
: null,
onTap: () {
provider.setDownloadMirrorId(item.id);
Navigator.of(sheetContext).pop();
},
);
},
),
),
],
),
),
);
},
);
}
}
+252
View File
@@ -0,0 +1,252 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:re_editor/re_editor.dart';
import '../services/code_completion/smart_prompts_builder.dart';
/// 移动端友好的现代化代码智能补全悬浮面板
class CodeAutocompleteView extends StatefulWidget implements PreferredSizeWidget {
const CodeAutocompleteView({
super.key,
required this.notifier,
required this.onSelected,
this.width = 270.0,
this.height = 196.0,
});
final ValueNotifier<CodeAutocompleteEditingValue> notifier;
final ValueChanged<CodeAutocompleteResult> onSelected;
final double width;
final double height;
static const double itemHeight = 36.0;
static const double verticalPadding = 8.0;
static const double borderWidth = 2.0;
@override
Size get preferredSize {
final prompts = notifier.value.prompts;
if (prompts.isEmpty) return Size(width, 0.0);
final contentHeight = prompts.length * itemHeight + verticalPadding + borderWidth;
final effectiveHeight = contentHeight.clamp(itemHeight + verticalPadding + borderWidth, height);
return Size(width, effectiveHeight);
}
@override
State<CodeAutocompleteView> createState() => _CodeAutocompleteViewState();
}
class _CodeAutocompleteViewState extends State<CodeAutocompleteView> {
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
widget.notifier.addListener(_handleValueChanged);
}
@override
void didUpdateWidget(covariant CodeAutocompleteView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.notifier != widget.notifier) {
oldWidget.notifier.removeListener(_handleValueChanged);
widget.notifier.addListener(_handleValueChanged);
}
}
@override
void dispose() {
widget.notifier.removeListener(_handleValueChanged);
_scrollController.dispose();
super.dispose();
}
void _handleValueChanged() {
if (!mounted) return;
final value = widget.notifier.value;
final targetOffset = value.index * CodeAutocompleteView.itemHeight;
if (_scrollController.hasClients && _scrollController.position.hasViewportDimension) {
final currentOffset = _scrollController.offset;
final viewportDimension = _scrollController.position.viewportDimension;
final maxView = currentOffset + viewportDimension - CodeAutocompleteView.itemHeight - CodeAutocompleteView.verticalPadding;
if (targetOffset < currentOffset) {
_scrollController.jumpTo(targetOffset);
} else if (targetOffset > maxView) {
_scrollController.jumpTo(math.max(0.0, targetOffset - viewportDimension + CodeAutocompleteView.itemHeight + CodeAutocompleteView.verticalPadding));
}
}
setState(() {});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final value = widget.notifier.value;
final prompts = value.prompts;
final bgColor = isDark ? const Color(0xFF1E1E2E) : Colors.white;
final borderColor = isDark ? Colors.white12 : Colors.black12;
return Container(
width: widget.width,
constraints: BoxConstraints(maxHeight: widget.height),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(color: borderColor, width: 1.0),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: isDark ? 0.45 : 0.15),
blurRadius: 14.0,
offset: const Offset(0, 4),
),
],
),
clipBehavior: Clip.antiAlias,
child: ListView.builder(
controller: _scrollController,
physics: const ClampingScrollPhysics(),
padding: const EdgeInsets.symmetric(vertical: 4.0),
itemCount: prompts.length,
itemExtent: CodeAutocompleteView.itemHeight,
itemBuilder: (context, index) {
final prompt = prompts[index];
final isSelected = index == value.index;
return _buildPromptItem(context, prompt, isSelected, index, theme, isDark);
},
),
);
}
Widget _buildPromptItem(
BuildContext context,
CodePrompt prompt,
bool isSelected,
int index,
ThemeData theme,
bool isDark,
) {
final smart = prompt is SmartPrompt ? prompt : null;
final kind = smart?.kind ?? SmartPromptKind.word;
final typeText = smart?.type ?? '';
final matchedIndices = smart?.matchedIndices ?? const [];
final highlightBg = theme.colorScheme.primary.withValues(alpha: isDark ? 0.25 : 0.15);
final defaultBg = Colors.transparent;
return InkWell(
onTap: () {
widget.notifier.value = widget.notifier.value.copyWith(index: index);
widget.onSelected(widget.notifier.value.autocomplete);
},
child: Container(
height: CodeAutocompleteView.itemHeight,
color: isSelected ? highlightBg : defaultBg,
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Row(
children: [
_buildKindIcon(kind, theme),
const SizedBox(width: 8.0),
Expanded(
child: _buildHighlightedText(prompt.word, matchedIndices, theme, isSelected),
),
if (typeText.isNotEmpty)
Text(
typeText,
style: TextStyle(
fontSize: 11.0,
color: isDark ? Colors.white38 : Colors.black38,
fontFamily: 'monospace',
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
);
}
Widget _buildKindIcon(SmartPromptKind kind, ThemeData theme) {
IconData icon;
Color color;
switch (kind) {
case SmartPromptKind.keyword:
icon = Icons.vpn_key_rounded;
color = const Color(0xFFC586C0); // 类似 VS Code 关键字粉紫色
break;
case SmartPromptKind.function:
icon = Icons.functions_rounded;
color = const Color(0xFFDCDCAA); // 函数黄色
break;
case SmartPromptKind.field:
icon = Icons.data_object_rounded;
color = const Color(0xFF9CDCFE); // 变量浅蓝色
break;
case SmartPromptKind.type:
icon = Icons.category_rounded;
color = const Color(0xFF4EC9B0); // 类型青绿色
break;
case SmartPromptKind.constant:
icon = Icons.tag_rounded;
color = const Color(0xFF4FC1FF); // 常量亮天蓝色
break;
case SmartPromptKind.word:
icon = Icons.text_snippet_outlined;
color = Colors.grey;
break;
}
return Icon(icon, size: 15.0, color: color);
}
Widget _buildHighlightedText(
String word,
List<int> matchedIndices,
ThemeData theme,
bool isSelected,
) {
if (matchedIndices.isEmpty) {
return Text(
word,
style: TextStyle(
fontSize: 13.0,
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
fontFamily: 'monospace',
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
final matchedSet = matchedIndices.toSet();
final List<TextSpan> spans = [];
for (int i = 0; i < word.length; i++) {
final isHit = matchedSet.contains(i);
spans.add(
TextSpan(
text: word[i],
style: TextStyle(
color: isHit ? theme.colorScheme.primary : null,
fontWeight: isHit ? FontWeight.bold : (isSelected ? FontWeight.w600 : FontWeight.normal),
),
),
);
}
return RichText(
text: TextSpan(
style: TextStyle(
fontSize: 13.0,
color: theme.textTheme.bodyMedium?.color,
fontFamily: 'monospace',
),
children: spans,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
}
+3 -1
View File
@@ -118,7 +118,7 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.play_arrow),
tooltip: l10n.run,
onPressed: onRun ?? () {},
onPressed: (isDetecting || onRun == null) ? null : onRun,
),
),
Focus(
@@ -319,7 +319,9 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi
icon: Icons.playlist_play,
title: l10n.runTasks,
iconColor: onSurfaceColor,
enabled: !widget.isDetecting,
onTap: () {
if (widget.isDetecting) return;
_closeMenu(onClosed: widget.onRunTasks);
},
),
+54 -1
View File
@@ -1,6 +1,9 @@
import 'dart:math';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/services/lsp/lsp_diagnostics_store.dart';
import 'package:code_editor/services/lsp/lsp_protocol.dart';
import 'package:code_editor/widgets/lsp_quick_fix_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:re_editor/re_editor.dart';
@@ -150,6 +153,7 @@ class _MobileSelectionToolbarWidget extends StatefulWidget {
final VoidCallback onDismiss;
final FocusNode? focusNode;
final Rect? renderRect;
final String? Function()? filePathGetter;
const _MobileSelectionToolbarWidget({
required this.anchors,
@@ -157,6 +161,7 @@ class _MobileSelectionToolbarWidget extends StatefulWidget {
required this.onDismiss,
this.focusNode,
this.renderRect,
this.filePathGetter,
});
@override
@@ -197,6 +202,12 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
final theme = Theme.of(context);
final filePath = widget.filePathGetter?.call();
final line = widget.controller.selection.baseIndex;
final diags = (filePath != null && line >= 0)
? LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, line)
: const <LspDiagnostic>[];
final toolbarContent = Material(
elevation: 6.0,
shadowColor: Colors.black45,
@@ -213,6 +224,23 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (diags.isNotEmpty && filePath != null) ...[
_buildItem(
context,
label: '修复 💡',
onTap: () {
widget.onDismiss();
LspQuickFixDialog.show(
context,
filePath: filePath,
lineIndex: line,
diagnostics: diags,
controller: widget.controller,
);
},
),
_buildDivider(context),
],
if (hasSelection) ...[
_buildItem(
context,
@@ -311,6 +339,7 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
/// 自定义代码编辑器选区与右键菜单控制器
class CodeEditorToolbarController implements SelectionToolbarController {
final FocusNode? focusNode;
final String? Function()? filePathGetter;
late final SelectionToolbarController _mobileController;
CodeLineEditingController? _lastController;
@@ -319,7 +348,7 @@ class CodeEditorToolbarController implements SelectionToolbarController {
LayerLink? _lastLayerLink;
ValueNotifier<bool>? _lastVisibility;
CodeEditorToolbarController({this.focusNode}) {
CodeEditorToolbarController({this.focusNode, this.filePathGetter}) {
_mobileController = MobileSelectionToolbarController(
builder: ({
required BuildContext context,
@@ -335,6 +364,7 @@ class CodeEditorToolbarController implements SelectionToolbarController {
onDismiss: onDismiss,
focusNode: focusNode,
renderRect: renderRect,
filePathGetter: filePathGetter,
);
},
);
@@ -410,6 +440,12 @@ class CodeEditorToolbarController implements SelectionToolbarController {
final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
final hasClipboard = clipboardData != null && (clipboardData.text?.isNotEmpty ?? false);
final filePath = filePathGetter?.call();
final line = controller.selection.baseIndex;
final diags = (filePath != null && line >= 0)
? LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, line)
: const <LspDiagnostic>[];
if (!context.mounted) return;
final l10n = AppLocalizations.of(context);
@@ -433,6 +469,23 @@ class CodeEditorToolbarController implements SelectionToolbarController {
Offset.zero & mediaQuery.size,
),
items: [
if (diags.isNotEmpty && filePath != null) ...[
_EditorContextMenuItem(
text: '快速修复 (Quick Fix)',
icon: Icons.lightbulb,
enabled: true,
onTap: () {
LspQuickFixDialog.show(
context,
filePath: filePath,
lineIndex: line,
diagnostics: diags,
controller: controller,
);
},
),
const PopupMenuDivider(height: 1),
],
_EditorContextMenuItem(
text: l10n?.cut ?? 'Cut',
icon: Icons.content_cut,
+245 -68
View File
@@ -8,9 +8,17 @@ import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/providers/tab_provider.dart';
import 'package:code_editor/services/file_service.dart';
import 'package:code_editor/services/file_watcher_service.dart';
import 'package:code_editor/services/code_completion/smart_prompts_builder.dart';
import 'package:code_editor/services/lsp/lsp_diagnostics_store.dart';
import 'package:code_editor/services/lsp/lsp_manager.dart';
import 'package:code_editor/services/lsp/lsp_protocol.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/utils/syntax_highlight_helper.dart';
import 'package:code_editor/widgets/code_autocomplete_view.dart';
import 'package:code_editor/widgets/code_editor_menu.dart';
import 'package:code_editor/widgets/editor/editor_diagnostic_controller.dart';
import 'package:code_editor/widgets/editor/editor_lsp_coordinator.dart';
import 'package:code_editor/widgets/editor/editor_overlay_scope.dart';
import 'package:code_editor/widgets/virtual_keyboard_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
@@ -18,6 +26,37 @@ import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:re_editor/re_editor.dart';
/// 行号指示器红/黄圆点装饰器
class DiagnosticGutterDotDecoration extends Decoration {
final Color color;
final double radius;
const DiagnosticGutterDotDecoration({
required this.color,
this.radius = 3.0,
});
@override
BoxPainter createBoxPainter([VoidCallback? onChanged]) {
return _DiagnosticGutterDotPainter(this);
}
}
class _DiagnosticGutterDotPainter extends BoxPainter {
final DiagnosticGutterDotDecoration decoration;
_DiagnosticGutterDotPainter(this.decoration);
@override
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
final size = configuration.size ?? Size.zero;
final paint = Paint()
..color = decoration.color
..style = PaintingStyle.fill;
final center = Offset(offset.dx + 4.0, offset.dy + size.height / 2);
canvas.drawCircle(center, decoration.radius, paint);
}
}
class CodeEditorWidget extends StatefulWidget {
final String? rootPath;
final String? filePath;
@@ -45,12 +84,15 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
CodeScrollController? _scrollController;
final FocusNode _focusNode = FocusNode();
late final CodeEditorToolbarController _toolbarController;
final EditorDiagnosticController _diagnosticController = const EditorDiagnosticController();
final EditorLspCoordinator _lspCoordinator = const EditorLspCoordinator();
bool _isLoading = false;
int _currentLoadVersion = 0;
String? _errorMessage;
String? _currentLoadedPath;
int? _currentIndentSize;
bool _isShowingConflictDialog = false;
int _currentCursorLine = -1;
// 双指捏合实时缩放字号及中心锚定状态
final GlobalKey _editorContainerKey = GlobalKey();
@@ -420,10 +462,26 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
});
}
void _onDiagnosticsChanged() {
if (!mounted || _controller == null) return;
_controller?.forceRepaint();
if (WidgetsBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() {});
});
} else {
setState(() {});
}
}
@override
void initState() {
super.initState();
_toolbarController = CodeEditorToolbarController(focusNode: _focusNode);
_toolbarController = CodeEditorToolbarController(
focusNode: _focusNode,
filePathGetter: () => _currentLoadedPath ?? widget.filePath,
);
LspDiagnosticsStore.instance.addListener(_onDiagnosticsChanged);
_loadFileContent();
}
@@ -454,6 +512,10 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
try {
_getTabProvider(context).registerSaveHandler(null);
} catch (_) {}
LspDiagnosticsStore.instance.removeListener(_onDiagnosticsChanged);
if (_currentLoadedPath != null) {
LspManager.instance.onFileClosed(_currentLoadedPath!);
}
_toolbarController.hide(context);
final currentTab = _getCurrentTab();
_saveCurrentTabScrollState(currentTab);
@@ -468,6 +530,19 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
void _onTextChanged() {
if (!mounted || _controller == null) return;
final newCursorLine = _controller?.selection.baseIndex ?? -1;
if (_currentCursorLine != newCursorLine) {
_currentCursorLine = newCursorLine;
if (WidgetsBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() {});
});
} else {
setState(() {});
}
}
final currentTab = _getCurrentTab();
if (currentTab == null || !currentTab.isLoaded) return;
// 确保当前活跃 tab 与当前加载的控制器路径严格一致,杜绝切换过程中误写其他 tab
@@ -485,6 +560,15 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
currentTab.content = current;
currentTab.isModified = isModified;
// LSP 文档变更增量/全量同步及本地语法诊断兜底
if (_currentLoadedPath != null && _controller != null) {
_lspCoordinator.onFileChanged(
_currentLoadedPath!,
current,
_controller!.codeLines,
);
}
void notifyProvider() {
if (!mounted) return;
try {
@@ -500,6 +584,34 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
}
}
/// 依据 LSP 实时诊断结果,为当前行的代码文本施加波浪下划线(保留已有代码高亮色彩)
TextSpan _buildDiagnosticSpans({
required BuildContext context,
required int index,
required CodeLine codeLine,
required TextSpan textSpan,
required TextStyle style,
}) {
return _diagnosticController.buildDiagnosticSpans(
context: context,
filePath: _currentLoadedPath ?? widget.filePath,
index: index,
codeLine: codeLine,
textSpan: textSpan,
style: style,
);
}
Widget _buildDiagnosticBanner(BuildContext context, List<LspDiagnostic> diags, int lineIndex) {
return _diagnosticController.buildDiagnosticBanner(
context: context,
filePath: _currentLoadedPath ?? widget.filePath,
controller: _controller,
diags: diags,
lineIndex: lineIndex,
);
}
Future<bool> _saveFile({bool showToast = false}) async {
final currentPath = widget.filePath;
if (currentPath == null || currentPath.isEmpty || _controller == null) {
@@ -649,6 +761,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono;
bool showLineNumbers = true;
bool pinLineNumbers = true;
bool enableLspCompletion = true;
try {
final settings = _getSettingsProvider(context, listen: true);
activeTheme = settings.editorTheme;
@@ -659,6 +772,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
enableVirtualKeyboard = settings.enableVirtualKeyboard;
keyboardConfig = settings.virtualKeyboardConfig;
activeEditorFont = settings.editorFont;
enableLspCompletion = settings.enableLspCompletion;
if (_currentIndentSize != null && _currentIndentSize != settings.indentSize) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _loadFileContent();
@@ -683,77 +797,112 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
onPointerUp: _handlePointerUp,
onPointerCancel: _handlePointerCancel,
child: Stack(
clipBehavior: Clip.none,
children: [
IgnorePointer(
ignoring: _isPinching,
child: CodeEditor(
key: ValueKey(_currentLoadedPath),
controller: controller,
focusNode: _focusNode,
scrollController: _scrollController,
wordWrap: activeWordWrap,
pinLineNumbers: pinLineNumbers,
toolbarController: _toolbarController,
margin: EdgeInsets.zero,
extraHorizontalScroll: 160.0,
padding: const EdgeInsets.fromLTRB(6.0, 0.0, 0.0, 0.0),
leadingDivider: showLineNumbers
? Container(
width: 1.0,
color: activeTheme.gutterTextColor.withValues(alpha: 0.25),
)
: null,
style: CodeEditorStyle(
fontSize: displayFontSize,
textColor: activeTheme.textColor,
backgroundColor: activeTheme.backgroundColor,
cursorColor: activeTheme.cursorColor,
cursorLineColor: activeTheme.cursorLineColor,
selectionColor: activeTheme.selectionColor,
fontFamily: activeEditorFont.fontFamily,
fontFamilyFallback: activeEditorFont.fallback,
codeTheme: CodeHighlightTheme(
languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath),
theme: activeTheme.highlightTheme,
),
),
indicatorBuilder: showLineNumbers
? (context, editingController, chunkController, notifier) {
return Row(
children: [
DefaultCodeLineNumber(
controller: editingController,
notifier: notifier,
textStyle: TextStyle(
color: activeTheme.gutterTextColor,
fontSize: (displayFontSize - 1).clamp(9.0, 30.0),
fontFamily: activeEditorFont.fontFamily,
fontFamilyFallback: activeEditorFont.fallback,
height: 1.4,
),
focusedTextStyle: TextStyle(
color: activeTheme.focusedGutterTextColor,
fontSize: (displayFontSize - 1).clamp(9.0, 30.0),
fontWeight: FontWeight.bold,
fontFamily: activeEditorFont.fontFamily,
fontFamilyFallback: activeEditorFont.fallback,
height: 1.4,
),
),
DefaultCodeChunkIndicator(
width: 20,
controller: chunkController,
notifier: notifier,
painter: DefaultCodeChunkIndicatorPainter(
color: activeTheme.gutterTextColor,
),
),
],
child: Builder(
builder: (context) {
final promptsBuilder = SmartCodeAutocompletePromptsBuilder(
controller: controller,
filePath: _currentLoadedPath ?? widget.filePath,
enableLspCompletion: enableLspCompletion,
);
return EditorOverlayScope(
key: ValueKey(_currentLoadedPath),
child: CodeAutocomplete(
viewBuilder: (context, notifier, onSelected) {
promptsBuilder.activeNotifier = notifier;
return CodeAutocompleteView(
notifier: notifier,
onSelected: onSelected,
);
}
: null,
),
),
},
promptsBuilder: promptsBuilder,
child: CodeEditor(
key: ValueKey(_currentLoadedPath),
controller: controller,
focusNode: _focusNode,
scrollController: _scrollController,
wordWrap: activeWordWrap,
pinLineNumbers: pinLineNumbers,
toolbarController: _toolbarController,
margin: EdgeInsets.zero,
extraHorizontalScroll: 160.0,
padding: const EdgeInsets.fromLTRB(6.0, 0.0, 0.0, 0.0),
leadingDivider: showLineNumbers
? Container(
width: 1.0,
color: activeTheme.gutterTextColor.withValues(alpha: 0.25),
)
: null,
style: CodeEditorStyle(
fontSize: displayFontSize,
textColor: activeTheme.textColor,
backgroundColor: activeTheme.backgroundColor,
cursorColor: activeTheme.cursorColor,
cursorLineColor: activeTheme.cursorLineColor,
selectionColor: activeTheme.selectionColor,
fontFamily: activeEditorFont.fontFamily,
fontFamilyFallback: activeEditorFont.fallback,
codeTheme: CodeHighlightTheme(
languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath),
theme: activeTheme.highlightTheme,
),
),
indicatorBuilder: showLineNumbers
? (context, editingController, chunkController, notifier) {
return Row(
children: [
DefaultCodeLineNumber(
controller: editingController,
notifier: notifier,
lineDecorationBuilder: (lineIndex) {
final filePath = _currentLoadedPath ?? widget.filePath;
if (filePath == null) return null;
final diags = LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, lineIndex);
if (diags.isEmpty) return null;
final hasError = diags.any((d) => d.severity == LspDiagnosticSeverity.error);
final hasWarning = diags.any((d) => d.severity == LspDiagnosticSeverity.warning);
final dotColor = hasError
? Colors.redAccent
: (hasWarning ? Colors.amberAccent : Colors.lightBlueAccent);
return DiagnosticGutterDotDecoration(color: dotColor);
},
textStyle: TextStyle(
color: activeTheme.gutterTextColor,
fontSize: (displayFontSize - 1).clamp(9.0, 30.0),
fontFamily: activeEditorFont.fontFamily,
fontFamilyFallback: activeEditorFont.fallback,
height: 1.4,
),
focusedTextStyle: TextStyle(
color: activeTheme.focusedGutterTextColor,
fontSize: (displayFontSize - 1).clamp(9.0, 30.0),
fontWeight: FontWeight.bold,
fontFamily: activeEditorFont.fontFamily,
fontFamilyFallback: activeEditorFont.fallback,
height: 1.4,
),
),
DefaultCodeChunkIndicator(
width: 20,
controller: chunkController,
notifier: notifier,
painter: DefaultCodeChunkIndicatorPainter(
color: activeTheme.gutterTextColor,
),
),
],
);
}
: null,
),
),
);
},
),
),
// 双指缩放实时字号悬浮胶囊提示
if (_isPinching && _activeZoomFontSize != null)
Positioned(
@@ -794,6 +943,18 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
),
),
),
if (_currentCursorLine >= 0 && (_currentLoadedPath ?? widget.filePath) != null) ...[
Builder(
builder: (ctx) {
final diags = LspDiagnosticsStore.instance.getDiagnosticsForLine(
_currentLoadedPath ?? widget.filePath,
_currentCursorLine,
);
if (diags.isEmpty) return const SizedBox.shrink();
return _buildDiagnosticBanner(ctx, diags, _currentCursorLine);
},
),
],
if (enableVirtualKeyboard && keyboardConfig != null && keyboardConfig.hasKeys)
VirtualKeyboardWidget(
controller: controller,
@@ -866,6 +1027,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
final newController = CodeLineEditingController.fromText(
normalizedContent,
CodeLineOptions(indentSize: activeIndentSize),
_buildDiagnosticSpans,
);
_controller = newController;
@@ -874,6 +1036,13 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
_errorMessage = null;
_isLoading = false;
_lspCoordinator.onFileOpened(
fullFilePath,
normalizedContent,
newController.codeLines,
workspaceRoot: widget.rootPath,
);
// 必须在 _controller 和 tab 状态准备就绪后再挂载文本监听,避免初始化阶段被误判为脏
newController.addListener(_onTextChanged);
@@ -917,6 +1086,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
final newController = CodeLineEditingController.fromText(
diskContent,
CodeLineOptions(indentSize: activeIndentSize),
_buildDiagnosticSpans,
);
_controller = newController;
@@ -924,6 +1094,13 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
_currentIndentSize = activeIndentSize;
_errorMessage = null;
_lspCoordinator.onFileOpened(
fullFilePath,
diskContent,
newController.codeLines,
workspaceRoot: widget.rootPath,
);
if (tab != null) {
tab.content = diskContent;
tab.originalContent = diskContent;
-380
View File
@@ -1,380 +0,0 @@
import 'dart:io';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/services/distro_download_manager.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/views/distro_management_view.dart';
import 'package:code_editor/widgets/distro_extract_dialog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
/// 独立的 Linux 系统选择与管理对话框
class DistroSelectorDialog extends StatelessWidget {
const DistroSelectorDialog({super.key});
/// 打开系统选择与管理对话框
static Future<void> show(BuildContext context) {
return showDialog<void>(
context: context,
builder: (ctx) => const DistroSelectorDialog(),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final distroProvider = context.watch<DistroProvider>();
final systems = distroProvider.installedSystems;
final selectedSystem = distroProvider.selectedSystem;
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
titlePadding: const EdgeInsets.fromLTRB(20.0, 16.0, 12.0, 8.0),
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
title: Row(
children: [
const Icon(Icons.dns_outlined, size: 22, color: Colors.blueAccent),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.systemManagement,
style: const TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold),
),
),
// 导入按钮与下拉选项
PopupMenuButton<String>(
icon: const Icon(Icons.add_circle_outline, color: Colors.blueAccent),
tooltip: l10n.importNewSystem,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
onSelected: (action) => _handleImportAction(context, action),
itemBuilder: (context) => [
PopupMenuItem(
value: 'management_view',
child: Row(
children: [
const Icon(Icons.apps_rounded, size: 18),
const SizedBox(width: 8),
Flexible(
child: Text(
l10n.importFromApp,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
PopupMenuItem(
value: 'external',
child: Row(
children: [
const Icon(Icons.folder_open_outlined, size: 18),
const SizedBox(width: 8),
Flexible(
child: Text(
l10n.importExternalTarGz,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
],
),
],
),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
l10n.selectSystemDefaultPrompt,
style: TextStyle(
fontSize: 12.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
),
const Divider(height: 1),
Flexible(
child: systems.isEmpty
? Container(
padding: const EdgeInsets.symmetric(vertical: 32.0),
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.layers_clear_outlined,
size: 40,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
),
const SizedBox(height: 8),
Text(
l10n.noSystemsPrompt,
style: TextStyle(
fontSize: 13.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
)
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 4.0),
itemCount: systems.length,
itemBuilder: (context, index) {
final system = systems[index];
final isSelected = system == selectedSystem;
return Container(
margin: const EdgeInsets.symmetric(vertical: 3.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8.0),
border: Border.all(
color: isSelected
? theme.colorScheme.primary.withValues(alpha: 0.5)
: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
width: 1.0,
),
),
child: Material(
color: isSelected
? theme.colorScheme.primaryContainer.withValues(alpha: 0.4)
: Colors.transparent,
borderRadius: BorderRadius.circular(8.0),
child: ListTile(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 2.0),
title: Text(
system,
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected ? theme.colorScheme.primary : null,
fontSize: 14.0,
),
),
trailing: IconButton(
icon: Icon(
Icons.delete_outline,
color: theme.colorScheme.error,
size: 20,
),
tooltip: l10n.deleteSystemTooltip,
onPressed: () => _handleDeleteSystem(context, system),
),
onTap: () {
distroProvider.selectSystem(system);
},
),
),
);
},
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.done),
),
],
);
}
/// 处理导入菜单操作
bool _isValidDistroArchive(String path) {
final lower = path.toLowerCase();
return lower.endsWith('.tar.gz') ||
lower.endsWith('.tgz') ||
lower.endsWith('.tar.xz') ||
lower.endsWith('.txz') ||
lower.endsWith('.tar');
}
Future<void> _handleImportAction(BuildContext context, String action) async {
final distroProvider = context.read<DistroProvider>();
final l10n = AppLocalizations.of(context)!;
if (action == 'management_view') {
// 1. 跳转到应用内系统管理页面
final selectedItem = await Navigator.of(context).push<DistroManifestItem>(
MaterialPageRoute(builder: (_) => const DistroManagementView()),
);
if (selectedItem != null && context.mounted) {
// 用户直接点击已经安装的 item 本身,代表用户选择了那个 zip,返回后解压创建系统
await _handleCreateSystemFromManifest(context, selectedItem);
}
} else if (action == 'external') {
// 2. 从外部选择 .tar.gz / .tar.xz 压缩包导入
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: const ['tar', 'gz', 'tgz', 'xz', 'txz'],
);
if (result == null || result.files.single.path == null || !context.mounted) return;
final filePath = result.files.single.path!;
if (!_isValidDistroArchive(filePath)) {
if (context.mounted) {
DialogUtils.showErrorToast(context, l10n.unsupportedDistroArchiveFormat);
}
return;
}
final file = File(filePath);
// 提取默认名称(去掉 .tar.gz, .tgz 等后缀)
String baseName = p.basename(filePath);
if (baseName.endsWith('.tar.gz')) {
baseName = baseName.substring(0, baseName.length - 7);
} else if (baseName.endsWith('.tgz')) {
baseName = baseName.substring(0, baseName.length - 4);
} else {
baseName = p.basenameWithoutExtension(filePath);
}
baseName = baseName.replaceAll(RegExp(r'[^a-zA-Z0-9_\-]'), '_');
if (baseName.isEmpty) baseName = 'custom_linux';
final defaultName = _generateUniqueSystemName(baseName, distroProvider.installedSystems);
final systemName = await DialogUtils.showInputDialog(
context,
title: l10n.importExternalSystemTitle,
hintText: l10n.systemNameHint,
initialValue: defaultName,
);
if (systemName == null || systemName.trim().isEmpty || !context.mounted) return;
final cleanName = systemName.trim();
// 模态同步解压
final success = await DistroExtractDialog.show(
context: context,
systemName: cleanName,
task: (onProgress, isCancelled) {
return distroProvider.importFromCustomTarGz(
systemName: cleanName,
tarGzFile: file,
onProgress: onProgress,
isCancelled: isCancelled,
);
},
);
if (success && context.mounted) {
DialogUtils.showSuccessToast(context, l10n.externalSystemImportSuccess(cleanName));
}
}
}
/// 从选中的发行版安装包解压创建新的系统实例
Future<void> _handleCreateSystemFromManifest(BuildContext context, DistroManifestItem item) async {
final distroProvider = context.read<DistroProvider>();
final l10n = AppLocalizations.of(context)!;
final defaultName = _generateUniqueSystemName(item.id, distroProvider.installedSystems);
final systemName = await DialogUtils.showInputDialog(
context,
title: l10n.importSystemInstanceTitle(item.name),
hintText: l10n.systemNameHintWithDefault(defaultName),
initialValue: defaultName,
);
if (systemName == null || systemName.trim().isEmpty || !context.mounted) return;
final cleanName = systemName.trim();
// 模态同步解压
final success = await DistroExtractDialog.show(
context: context,
systemName: cleanName,
task: (onProgress, isCancelled) async {
if (item.id == 'ubuntu') {
return distroProvider.importBuiltinUbuntu(
systemName: cleanName,
onProgress: onProgress,
isCancelled: isCancelled,
);
} else if (item.id == 'alpine') {
return distroProvider.importBuiltinAlpine(
systemName: cleanName,
onProgress: onProgress,
isCancelled: isCancelled,
);
} else {
final file = await DistroDownloadManager().getPackageFile(item.id, item.currentPackageSource!);
return distroProvider.importFromCustomTarGz(
systemName: cleanName,
tarGzFile: file,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
},
);
if (success && context.mounted) {
DialogUtils.showSuccessToast(context, l10n.systemImportSuccess(cleanName));
await distroProvider.refreshSystems();
await distroProvider.selectSystem(cleanName);
}
}
/// 高危操作:二次确认删除系统
Future<void> _handleDeleteSystem(BuildContext context, String systemName) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
context,
title: l10n.deleteSystemConfirmTitle,
message: l10n.deleteSystemConfirmMessage(systemName),
confirmText: l10n.permanentDelete,
);
if (confirmed && context.mounted) {
final distroProvider = context.read<DistroProvider>();
final terminalProvider = context.read<TerminalProvider?>();
try {
await distroProvider.deleteSystem(systemName);
terminalProvider?.removeSessionsForDistro(systemName);
if (!distroProvider.hasAnySystem) {
terminalProvider?.clearAllSessions();
}
if (context.mounted) {
DialogUtils.showToast(context, l10n.deleteSystemSuccess(systemName));
}
} catch (e) {
if (context.mounted) {
DialogUtils.showErrorToast(context, l10n.deleteSystemFailed(e.toString()));
}
}
}
}
/// 自动生成不重复的系统实例名
String _generateUniqueSystemName(String prefix, List<String> existingSystems) {
if (!existingSystems.contains(prefix)) return prefix;
int index = 1;
while (existingSystems.contains('${prefix}_$index')) {
index++;
}
return '${prefix}_$index';
}
}
@@ -0,0 +1,266 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:re_editor/re_editor.dart';
import '../../services/lsp/lsp_diagnostics_store.dart';
import '../../services/lsp/lsp_protocol.dart';
import '../lsp_quick_fix_dialog.dart';
class _DiagnosticInterval {
final int start;
final int end;
final Color color;
const _DiagnosticInterval(this.start, this.end, this.color);
}
class _OffsetTracker {
int value;
_OffsetTracker(this.value);
}
/// 编辑器代码诊断视图控制器
///
/// 专职负责:
/// 1. 依据 LSP 与本地语法诊断,计算行内波浪下划线(保持语法高亮颜色);
/// 2. 构建底部错误与警告横幅,支持一键唤起 LSP 快捷修复。
class EditorDiagnosticController {
const EditorDiagnosticController();
/// 依据实时诊断结果,为当前行的代码文本施加波浪下划线(保留已有代码高亮色彩)
TextSpan buildDiagnosticSpans({
required BuildContext context,
required String? filePath,
required int index,
required CodeLine codeLine,
required TextSpan textSpan,
required TextStyle style,
}) {
if (filePath == null || codeLine.text.isEmpty) {
return textSpan;
}
final diagnostics = LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, index);
if (diagnostics.isEmpty) {
return textSpan;
}
final lineText = codeLine.text;
final lineLen = lineText.length;
final intervals = <_DiagnosticInterval>[];
for (final d in diagnostics) {
final startLine = d.range.start.line;
final endLine = d.range.end.line;
int startCol = 0;
if (startLine == index) {
startCol = d.range.start.character;
} else if (startLine > index) {
continue;
}
int endCol = lineLen;
if (endLine == index) {
endCol = d.range.end.character;
} else if (endLine < index) {
continue;
}
startCol = startCol.clamp(0, lineLen);
endCol = endCol.clamp(0, lineLen);
// LSP 有时可能返回单点(0 宽)区间,自动扩宽至至少 1 字符高亮以便视觉可见
if (startCol == endCol) {
if (startCol < lineLen) {
endCol = min(startCol + 1, lineLen);
} else if (startCol > 0) {
startCol = startCol - 1;
}
}
if (startCol < endCol) {
Color diagColor = Colors.redAccent;
switch (d.severity) {
case LspDiagnosticSeverity.error:
diagColor = Colors.redAccent;
break;
case LspDiagnosticSeverity.warning:
diagColor = Colors.amberAccent;
break;
case LspDiagnosticSeverity.information:
diagColor = Colors.lightBlueAccent;
break;
case LspDiagnosticSeverity.hint:
diagColor = Colors.grey;
break;
}
intervals.add(_DiagnosticInterval(startCol, endCol, diagColor));
}
}
if (intervals.isEmpty) {
return textSpan;
}
return _applyDiagnosticIntervals(textSpan, intervals, _OffsetTracker(0), style);
}
/// 构建底部单行诊断简报与快捷修复入口横幅
Widget buildDiagnosticBanner({
required BuildContext context,
required String? filePath,
required CodeLineEditingController? controller,
required List<LspDiagnostic> diags,
required int lineIndex,
}) {
final first = diags.first;
final isErr = diags.any((d) => d.severity == LspDiagnosticSeverity.error);
final color = isErr ? Colors.redAccent : Colors.amber;
final icon = isErr ? Icons.error_outline : Icons.warning_amber_outlined;
return Material(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
elevation: 2,
child: InkWell(
onTap: () {
if (filePath != null && controller != null) {
LspQuickFixDialog.show(
context,
filePath: filePath,
lineIndex: lineIndex,
diagnostics: diags,
controller: controller,
);
}
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: color.withValues(alpha: 0.6), width: 1.5),
),
),
child: Row(
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 8),
Expanded(
child: Text(
'行 ${lineIndex + 1}: ${first.message}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.amber.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.lightbulb, size: 12, color: Colors.amber),
SizedBox(width: 2),
Text(
'修复',
style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.amber),
),
],
),
),
],
),
),
),
);
}
static TextSpan _applyDiagnosticIntervals(
TextSpan span,
List<_DiagnosticInterval> intervals,
_OffsetTracker tracker,
TextStyle baseStyle,
) {
final effectiveStyle = span.style ?? baseStyle;
if (span.children != null && span.children!.isNotEmpty) {
final newChildren = <InlineSpan>[];
if (span.text != null && span.text!.isNotEmpty) {
final leafSpan = TextSpan(text: span.text, style: effectiveStyle);
newChildren.add(_processLeafTextSpan(leafSpan, intervals, tracker, effectiveStyle));
}
for (final child in span.children!) {
if (child is TextSpan) {
newChildren.add(_applyDiagnosticIntervals(child, intervals, tracker, effectiveStyle));
} else {
newChildren.add(child);
}
}
return TextSpan(children: newChildren, style: span.style);
}
return _processLeafTextSpan(span, intervals, tracker, effectiveStyle);
}
static TextSpan _processLeafTextSpan(
TextSpan span,
List<_DiagnosticInterval> intervals,
_OffsetTracker tracker,
TextStyle baseStyle,
) {
final text = span.text;
if (text == null || text.isEmpty) {
return span;
}
final startOffset = tracker.value;
final endOffset = startOffset + text.length;
tracker.value = endOffset;
final intersecting = intervals.where((it) => it.end > startOffset && it.start < endOffset).toList();
if (intersecting.isEmpty) {
return span;
}
final splitPoints = <int>{startOffset, endOffset};
for (final it in intersecting) {
if (it.start > startOffset && it.start < endOffset) splitPoints.add(it.start);
if (it.end > startOffset && it.end < endOffset) splitPoints.add(it.end);
}
final sortedPoints = splitPoints.toList()..sort();
final chunks = <InlineSpan>[];
for (int i = 0; i < sortedPoints.length - 1; i++) {
final segStart = sortedPoints[i];
final segEnd = sortedPoints[i + 1];
if (segStart >= segEnd) continue;
final chunkText = text.substring(segStart - startOffset, segEnd - startOffset);
final activeInterval = intersecting.where((it) => it.start <= segStart && it.end >= segEnd).firstOrNull;
if (activeInterval != null) {
chunks.add(TextSpan(
text: chunkText,
style: (span.style ?? baseStyle).copyWith(
decoration: TextDecoration.underline,
decorationStyle: TextDecorationStyle.wavy,
decorationColor: activeInterval.color,
),
));
} else {
chunks.add(TextSpan(text: chunkText, style: span.style));
}
}
if (chunks.length == 1 && chunks.first is TextSpan) {
return chunks.first as TextSpan;
}
return TextSpan(children: chunks, style: span.style);
}
}
@@ -0,0 +1,45 @@
import 'package:re_editor/re_editor.dart';
import '../../services/lsp/lsp_diagnostics_store.dart';
import '../../services/lsp/lsp_manager.dart';
/// 编辑器 LSP 生命周期协调器
///
/// 负责:
/// 1. 统一管理文档打开、变更、关闭与 LSP 语言服务器进程的同步;
/// 2. 文档关闭时及时清理诊断缓存;
/// 3. 所有语法纠错与诊断均严格来自真实 LSP 进程的 push 通知,不进行任何本地模糊伪检查。
class EditorLspCoordinator {
const EditorLspCoordinator();
/// 文档打开时同步至 LSP
void onFileOpened(
String filePath,
String content,
CodeLines codeLines, {
String? workspaceRoot,
}) {
LspManager.instance.onFileOpened(
filePath,
content,
workspaceRoot: workspaceRoot,
);
}
/// 文档文本内容变更时同步至 LSP 进程
void onFileChanged(
String filePath,
String content,
CodeLines codeLines,
) {
final session = LspManager.instance.getExistingSession(filePath);
if (session != null && session.isInitialized) {
LspManager.instance.onFileChanged(filePath, content);
}
}
/// 文档关闭时清理会话与诊断
void onFileClosed(String filePath) {
LspManager.instance.onFileClosed(filePath);
LspDiagnosticsStore.instance.removeForFile(filePath);
}
}
@@ -0,0 +1,47 @@
import 'package:flutter/widgets.dart';
/// 编辑器专属局部 Overlay 作用域
///
/// 核心职责:
/// 1. 为代码补全弹窗(CodeAutocomplete)提供局部 Overlay 承载容器;
/// 2. 控制弹窗的堆叠层级(Z-Order):使其位于编辑器内容之上,但在编辑区底栏(如虚拟小键盘 VirtualKeyboardWidget、诊断横幅)之下;
/// 3. 当父级状态变更时,自动刷新内部根 OverlayEntry,确保代码内容与控制器无缝响应。
class EditorOverlayScope extends StatefulWidget {
final Widget child;
final Clip clipBehavior;
const EditorOverlayScope({
super.key,
required this.child,
this.clipBehavior = Clip.none,
});
@override
State<EditorOverlayScope> createState() => _EditorOverlayScopeState();
}
class _EditorOverlayScopeState extends State<EditorOverlayScope> {
late final OverlayEntry _entry;
@override
void initState() {
super.initState();
_entry = OverlayEntry(
builder: (context) => widget.child,
);
}
@override
void didUpdateWidget(covariant EditorOverlayScope oldWidget) {
super.didUpdateWidget(oldWidget);
_entry.markNeedsBuild();
}
@override
Widget build(BuildContext context) {
return Overlay(
clipBehavior: widget.clipBehavior,
initialEntries: [_entry],
);
}
}
+5 -5
View File
@@ -34,7 +34,7 @@ class _LspLanguageEditDialogState extends State<LspLanguageEditDialog> {
late final TextEditingController _extensionsController;
late final TextEditingController _commandController;
late final TextEditingController _argsController;
late final TextEditingController _apkPackageController;
late final TextEditingController _packageController;
@override
void initState() {
@@ -49,7 +49,7 @@ class _LspLanguageEditDialogState extends State<LspLanguageEditDialog> {
_argsController = TextEditingController(
text: init?.serverArgs.join(' ') ?? '',
);
_apkPackageController = TextEditingController(text: init?.apkPackage ?? '');
_packageController = TextEditingController(text: init?.package ?? '');
}
@override
@@ -59,7 +59,7 @@ class _LspLanguageEditDialogState extends State<LspLanguageEditDialog> {
_extensionsController.dispose();
_commandController.dispose();
_argsController.dispose();
_apkPackageController.dispose();
_packageController.dispose();
super.dispose();
}
@@ -101,7 +101,7 @@ class _LspLanguageEditDialogState extends State<LspLanguageEditDialog> {
fileExtensions: cleanedExtensions,
serverCommand: _commandController.text.trim(),
serverArgs: cleanedArgs,
apkPackage: _apkPackageController.text.trim(),
package: _packageController.text.trim(),
enabled: widget.initialConfig?.enabled ?? true,
);
@@ -175,7 +175,7 @@ class _LspLanguageEditDialogState extends State<LspLanguageEditDialog> {
),
const SizedBox(height: 12),
TextFormField(
controller: _apkPackageController,
controller: _packageController,
decoration: InputDecoration(
labelText: l10n.apkPackageField,
hintText: l10n.apkPackageFieldHint,
+153
View File
@@ -0,0 +1,153 @@
import 'package:flutter/material.dart';
import 'package:re_editor/re_editor.dart';
import '../services/lsp/lsp_manager.dart';
import '../services/lsp/lsp_protocol.dart';
import '../services/lsp/lsp_workspace_edit_applier.dart';
/// 快速修复操作弹窗(展示诊断信息及 LSP CodeAction 选项)
class LspQuickFixDialog {
static Future<void> show(
BuildContext context, {
required String filePath,
required int lineIndex,
required List<LspDiagnostic> diagnostics,
required CodeLineEditingController controller,
VoidCallback? onDismiss,
}) async {
final session = LspManager.instance.getExistingSession(filePath);
List<LspCodeAction> actions = [];
if (session != null && diagnostics.isNotEmpty && lineIndex < controller.lineCount) {
final lineLength = controller.codeLines[lineIndex].text.length;
final range = LspRange(
start: LspPosition.pos(lineIndex, 0),
end: LspPosition.pos(lineIndex, lineLength),
);
try {
actions = await session.getCodeActions(filePath, range, diagnostics);
} catch (_) {}
}
if (!context.mounted) return;
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Theme.of(context).colorScheme.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (ctx) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
width: 36,
height: 4,
decoration: BoxDecoration(
color: Colors.grey.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(2),
),
),
),
const SizedBox(height: 12),
Row(
children: [
const Icon(Icons.lightbulb, color: Colors.amber, size: 20),
const SizedBox(width: 8),
Text(
'代码问题与修复 (第 ${lineIndex + 1} 行)',
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
],
),
const SizedBox(height: 12),
...diagnostics.map((d) {
final isErr = d.severity == LspDiagnosticSeverity.error;
return Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: (isErr ? Colors.redAccent : Colors.amberAccent).withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: (isErr ? Colors.redAccent : Colors.amberAccent).withValues(alpha: 0.3),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
isErr ? Icons.error_outline : Icons.warning_amber_outlined,
size: 18,
color: isErr ? Colors.redAccent : Colors.amber,
),
const SizedBox(width: 8),
Expanded(
child: Text(
d.message,
style: TextStyle(
fontSize: 13,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
],
),
);
}),
const Divider(height: 16),
if (actions.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Row(
children: [
Icon(
Icons.info_outline,
size: 16,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(width: 8),
Text(
'当前报错未提供自动修复动作',
style: TextStyle(
fontSize: 13,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
)
else
...actions.map((act) {
return ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.auto_fix_high, color: Colors.blueAccent),
title: Text(act.title, style: const TextStyle(fontSize: 14)),
trailing: act.isPreferred ? const Chip(label: Text('推荐', style: TextStyle(fontSize: 11))) : null,
onTap: () {
Navigator.pop(ctx);
if (act.edit != null) {
LspWorkspaceEditApplier.applyWorkspaceEdit(
controller,
act.edit!,
currentFilePath: filePath,
);
}
onDismiss?.call();
},
);
}),
],
),
),
);
},
);
}
}