diff --git a/LSP_DEBUG_GUIDE.md b/LSP_DEBUG_GUIDE.md
new file mode 100644
index 0000000..5b70dff
--- /dev/null
+++ b/LSP_DEBUG_GUIDE.md
@@ -0,0 +1,82 @@
+# LSP 服务启用与全链路 Debug 打点排查手册
+
+为了彻底排查后台 `clangd` 等语言服务器为何未启用、未响应或未触发补全,我们在整个 LSP 的**生命周期、配置匹配、进程拉起、通信协议与补全调度推流**各个核心节点注入了全套 `[LSP-DEBUG]` 追踪日志。
+
+---
+
+## 1. Debug 打点分布位置一览表
+
+| 序号 | 链路阶段 | 文件路径 | 方法 / 代码行位置 | 关键调试内容 |
+| :--- | :--- | :--- | :--- | :--- |
+| **1** | **编辑区生命周期** | [`lib/widgets/code_editor_widget.dart`](file:///d:/Flutter/Projects/code_editor/lib/widgets/code_editor_widget.dart) | `_loadFileContent`
`_onTextChanged` | 打印当前打开文件绝对路径、工程根目录、文件内容长度,及文件修改事件 |
+| **2** | **协调器分发** | [`lib/widgets/editor/editor_lsp_coordinator.dart`](file:///d:/Flutter/Projects/code_editor/lib/widgets/editor/editor_lsp_coordinator.dart) | `onFileOpened`
`onFileChanged` | 打印协调器分发状态、查询是否存在存活会话、是否进入本地词法诊断兜底 |
+| **3** | **配置匹配与进程拉起** | [`lib/services/lsp/lsp_manager.dart`](file:///d:/Flutter/Projects/code_editor/lib/services/lsp/lsp_manager.dart) | `getOrCreateSession`
`_startSession`
`getExistingSession`
`onFileOpened` | 1. 打印扩展名与配置匹配结果
2. 打印 Ubuntu 引擎安装检测结果
3. 打印命令(clangd)安装检测结果
4. 打印拼装的 PRoot 容器完整命令行
5. 打印子进程 PID 或拉起异常
6. 打印 `session.initialize()` 握手结果 |
+| **4** | **会话与协议层** | [`lib/services/lsp/lsp_session.dart`](file:///d:/Flutter/Projects/code_editor/lib/services/lsp/lsp_session.dart) | `initialize`
`didOpen`
`didChange`
`getCompletions` | 1. 打印 `initialize` 请求入参与回包类型
2. 打印 `textDocument/didOpen` 映射的容器内部 guestUri
3. 打印 `textDocument/didChange` 防抖触发与版本号
4. 打印 `textDocument/completion` 耗时与回包条数 |
+| **5** | **Stdio 底层通讯** | [`lib/services/lsp/lsp_client.dart`](file:///d:/Flutter/Projects/code_editor/lib/services/lsp/lsp_client.dart) | `sendRequest`
`sendNotification`
`_dispatchMessage`
`_handleStderrData` | 1. 打印发往 clangd 的 Request/Notification 方法名与 ID
2. 打印收到的 Response 结果或 JSON-RPC 错误码
3. **打印 clangd 进程输出的所有 stderr 原始日志** |
+| **6** | **补全提供者** | [`lib/services/code_completion/providers/lsp_completion_provider.dart`](file:///d:/Flutter/Projects/code_editor/lib/services/code_completion/providers/lsp_completion_provider.dart) | `provideCompletions` | 打印收到的补全触发字符、光标行列号、当前 session 存活与初始化状态、后端返回的语义补全条数 |
+| **7** | **补全调度流水线** | [`lib/services/code_completion/core/completion_engine.dart`](file:///d:/Flutter/Projects/code_editor/lib/services/code_completion/core/completion_engine.dart) | `requestCompletions` | 打印当前激活的 Providers 列表、同步候选数、异步 Provider 调用耗时、聚合条数与向 UI 推流事件 |
+
+---
+
+## 2. 日志前缀说明与标准排查轨迹
+
+所有调试日志均统一带有 `[LSP-DEBUG]` 前缀,方便通过关键字高亮或过滤:
+
+```bash
+# 在终端中仅查看 LSP 调试信息(Windows PowerShell)
+flutter run | Select-String "\[LSP-DEBUG\]"
+
+# 或在 Android 设备上使用 adb logcat 过滤
+adb logcat | grep -E "\[LSP-DEBUG\]|flutter"
+```
+
+### 正常工作时的完整日志时序:
+```text
+[LSP-DEBUG][Editor] 磁盘冷加载读取文件成功,通知 LSP 打开: path=/sdcard/.../main.c, rootPath=/sdcard/...
+[LSP-DEBUG][Coordinator] onFileOpened 被触发: filePath=/sdcard/.../main.c
+[LSP-DEBUG][Manager] onFileOpened 被触发: filePath=/sdcard/.../main.c
+[LSP-DEBUG][Manager] getOrCreateSession 触发: filePath=/sdcard/.../main.c, ext=.c
+[LSP-DEBUG][Manager] 匹配配置结果: config=c_cpp, name=C / C++, enabled=true, serverCommand=clangd
+[LSP-DEBUG][Manager] 开始创建并拉起新会话: configId=c_cpp
+[LSP-DEBUG][Manager] 检查 Ubuntu 引擎安装状态: isEngineInstalled=true
+[LSP-DEBUG][Manager] 检查命令安装状态 (clangd): isCommandInstalled=true
+[LSP-DEBUG][Manager] 准备执行拉起命令: /data/user/0/.../libproot.so ... clangd --background-index
+[LSP-DEBUG][Manager] 语言服务子进程已启动, PID: 12345
+[LSP-DEBUG][Manager] 正在进行 session.initialize() 握手...
+[LSP-DEBUG][Client] 发送 Request: id=1, method=initialize, timeout=10s
+[LSP-DEBUG][Client] 收到 Request 响应: id=1, hasError=false
+[LSP-DEBUG][Session] 语言服务初始化成功并发送 initialized 通知: C / C++ (clangd)
+[LSP-DEBUG][Manager] session.initialize() 结果: success=true
+[LSP-DEBUG][Manager] 会话拉起成功并缓存: configId=c_cpp
+[LSP-DEBUG][Manager] onFileOpened 正在调用 session.didOpen
+[LSP-DEBUG][Session] 发送 textDocument/didOpen: filePath=/sdcard/.../main.c -> uri=file:///...
+[LSP-DEBUG][Client] 发送 Notification: method=textDocument/didOpen
+
+# 当你在编辑器中键入字符(如 pri)时:
+[LSP-DEBUG][Engine] requestCompletions 触发: input="pri", providers=[lsp(async=true)]
+[LSP-DEBUG][Engine] 启动异步请求: requestId=1, asyncProviders=[lsp]
+[LSP-DEBUG][Engine] 正在调用异步 Provider: lsp
+[LSP-DEBUG][Provider] 收到 LSP 补全请求: input="pri", line=3, col=4
+[LSP-DEBUG][Provider] 查询会话结果: session=true, isInitialized=true, isClosed=false
+[LSP-DEBUG][Session] getCompletions: ... line=3, col=4
+[LSP-DEBUG][Client] 发送 Request: id=2, method=textDocument/completion
+[LSP-DEBUG][Client] 收到 Request 响应: id=2, hasError=false
+[LSP-DEBUG][Session] 解析 CompletionList items 成功, 条数: 15
+[LSP-DEBUG][Provider] session.getCompletions 耗时: 38ms, 返回条数: 15
+[LSP-DEBUG][Engine] 聚合所有异步结果数: 15
+[LSP-DEBUG][Engine] 合并后过滤展示条数: 15, 准备推流至 ValueNotifier
+[LSP-DEBUG][Engine] ValueNotifier 推流成功!
+```
+
+---
+
+## 3. 常见断点排查指南
+
+| 现象 / 日志断点 | 发生点 | 真正原因与对策 |
+| :--- | :--- | :--- |
+| **`[Manager] 未找到匹配配置或配置已被禁用`** | `LspManager.getOrCreateSession` | 检查配置管理中该语言扩展名(如 `.c`)是否已配置并处于启用状态。 |
+| **`[Manager] 阻断: Ubuntu 引擎未安装`** | `LspManager._startSession` | `InternalEngineService.isEngineInstalled()` 为 false。说明 App 尚未解压容器运行环境。 |
+| **`[Manager] 阻断: 服务命令未在引擎中检测到: clangd`** | `LspManager._startSession` | `isCommandInstalled('clangd')` 判定失败。说明容器环境中 `command -v clangd` 未输出 CE_OK,需确认容器中 clangd 是否已配置在 PATH 路径下。 |
+| **`[Manager] 语言服务子进程已启动, PID: xxx` 紧接着进程退出** | `LspClient 进程退出: xxx` | 关注 `[LSP-DEBUG][Stderr]` 打印的原始错误(如缺失共享库 `libc++.so`、权限被拒、参数不支持等)。 |
+| **`[Client] Request 超时失败: method=initialize`** | `LspClient.sendRequest` | clangd 启动后挂起,未能在 10 秒内应答 initialize 请求。通常是 PRoot 路径映射或 stdin 管道堵塞。 |
+| **`[Provider] 会话不存在或未完成初始化`** | `LspCompletionProvider.provideCompletions` | 说明输入时,前面的文件打开握手尚未完成,或拉起失败导致 session 为 null。 |
diff --git a/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so b/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so
index 855067a..0ebe389 100644
Binary files a/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so and b/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so differ
diff --git a/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so b/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so
index a5374c3..6d8d74a 100644
Binary files a/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so and b/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so differ
diff --git a/android/app/src/main/cpp/libfix_seccomp.c b/android/app/src/main/cpp/libfix_seccomp.c
index a7dffc4..5464c52 100644
--- a/android/app/src/main/cpp/libfix_seccomp.c
+++ b/android/app/src/main/cpp/libfix_seccomp.c
@@ -165,6 +165,7 @@ static inline long my_syscall6(long n, long a1, long a2, long a3, long a4, long
#endif
+#define AT_FDCWD -100
#define AT_SYMLINK_NOFOLLOW 0x100
#define ENOENT 2
@@ -179,13 +180,17 @@ static inline int set_errno_and_return(long ret) {
}
/* -------------------------------------------------------------------------
- * utimensat() / fchownat(): survive PRoot's --link2symlink hardlink stand-ins.
+ * utimensat() / fchownat() / chown() / lchown(): survive PRoot's --link2symlink hardlink stand-ins.
*
* apk 在装完文件后会对
/.apk. 做两件"跟随符号链接"语义的操作:
* utimensat(dirfd, name, times, 0) 保 mtime → 维护老的 proot 需要它
* fchownat(dirfd, name, 0, 0, 0) 设 owner → 新版 proot(link2symlink 重写后)需要它
* 二者都会解析进 l2s 的隐藏替身(guest 不可解析)→ ENOENT。
* 带 AT_SYMLINK_NOFOLLOW 重试即可作用于替身自身(最接近硬链接语义)。
+ *
+ * 对于 Debian/Ubuntu (dpkg):
+ * dpkg 在解包硬链接(如 perl 软件包)时会直接调用 chown()。glibc 下 chown() 是内联系统调用,
+ * 不走 fchownat 的 PLT 拦截。因此显式导出 chown 与 lchown,转发至带容错机制的 fchownat。
* ------------------------------------------------------------------------- */
__attribute__((visibility("default")))
int utimensat(int dirfd, const char *path, const void *times, int flags) {
@@ -219,6 +224,16 @@ int fchownat(int dirfd, const char *path, int owner, int group, int flags) {
return set_errno_and_return(ret);
}
+__attribute__((visibility("default")))
+int chown(const char *path, int owner, int group) {
+ return fchownat(AT_FDCWD, path, owner, group, 0);
+}
+
+__attribute__((visibility("default")))
+int lchown(const char *path, int owner, int group) {
+ return fchownat(AT_FDCWD, path, owner, group, AT_SYMLINK_NOFOLLOW);
+}
+
#if defined(__x86_64__)
/* -------------------------------------------------------------------------
diff --git a/assets/shims/arm64-v8a/libfix_seccomp.so b/assets/shims/arm64-v8a/libfix_seccomp.so
index 855067a..0ebe389 100644
Binary files a/assets/shims/arm64-v8a/libfix_seccomp.so and b/assets/shims/arm64-v8a/libfix_seccomp.so differ
diff --git a/assets/shims/x86_64/libfix_seccomp.so b/assets/shims/x86_64/libfix_seccomp.so
index a5374c3..6d8d74a 100644
Binary files a/assets/shims/x86_64/libfix_seccomp.so and b/assets/shims/x86_64/libfix_seccomp.so differ
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 36603e9..87c0780 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -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"
}
\ No newline at end of file
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 78ba0f4..df004aa 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -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
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index bf445ba..0c54158 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -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';
}
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 98b63ce..1fd7699 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -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 =>
+ '在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加';
}
diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb
index 5ef15ea..c02afd2 100644
--- a/lib/l10n/app_zh.arb
+++ b/lib/l10n/app_zh.arb
@@ -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": "在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加"
}
\ No newline at end of file
diff --git a/lib/main.dart b/lib/main.dart
index badd8c7..f6fe5ee 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -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()),
),
diff --git a/lib/models/distro_manifest.dart b/lib/models/distro_manifest.dart
index e317546..8f94d2d 100644
--- a/lib/models/distro_manifest.dart
+++ b/lib/models/distro_manifest.dart
@@ -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 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 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 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 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 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';
- }
}
diff --git a/lib/models/lsp_language_config.dart b/lib/models/lsp_language_config.dart
index 628f6b6..2586913 100644
--- a/lib/models/lsp_language_config.dart
+++ b/lib/models/lsp_language_config.dart
@@ -5,9 +5,13 @@ class LspLanguageConfig {
final List fileExtensions;
final String serverCommand;
final List 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 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? fileExtensions,
String? serverCommand,
List? 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 get defaultPresets => [
+ /// 官方内置语言支持模版(基于 Ubuntu 官方 apt 工具链,仅作探测与安装指引,不默认写入用户配置)
+ static List 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 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;
+ }
}
diff --git a/lib/models/notice_item.dart b/lib/models/notice_item.dart
index aead7ec..a5d5a9c 100644
--- a/lib/models/notice_item.dart
+++ b/lib/models/notice_item.dart
@@ -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 {
diff --git a/lib/models/run_task.dart b/lib/models/run_task.dart
index 4756263..f58c9f3 100644
--- a/lib/models/run_task.dart
+++ b/lib/models/run_task.dart
@@ -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 ?? '';
}
diff --git a/lib/providers/distro_provider.dart b/lib/providers/distro_provider.dart
index 796572a..bbe0655 100644
--- a/lib/providers/distro_provider.dart
+++ b/lib/providers/distro_provider.dart
@@ -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 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 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 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 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 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 deleteSystem(String systemName) async {
- await _manager.deleteSystem(systemName);
- onSystemDeleted?.call(systemName);
+ // 导入成功后刷新列表
await refreshSystems();
}
}
diff --git a/lib/providers/run_provider.dart b/lib/providers/run_provider.dart
index 6e57162..710c7d6 100644
--- a/lib/providers/run_provider.dart
+++ b/lib/providers/run_provider.dart
@@ -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;
diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart
index b431d30..5e85d71 100644
--- a/lib/providers/settings_provider.dart
+++ b/lib/providers/settings_provider.dart
@@ -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 setDownloadMirrorId(String mirrorId) async {
- if (_downloadMirrorId == mirrorId) return;
- _downloadMirrorId = mirrorId;
+ /// 设置是否启用本地基础补全(本地补全已移除,保留此方法仅作向后兼容)
+ @Deprecated('本地补全已完全移除')
+ Future setEnableLocalCompletion(bool enable) async {}
+
+ /// 设置是否启用LSP后端代码补全
+ Future 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 (_) {}
}
}
diff --git a/lib/services/background_task/apt_package_task.dart b/lib/services/background_task/apt_package_task.dart
new file mode 100644
index 0000000..949d05c
--- /dev/null
+++ b/lib/services/background_task/apt_package_task.dart
@@ -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 {
+ 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 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),
+ );
+ }
+}
diff --git a/lib/services/background_task/background_task.dart b/lib/services/background_task/background_task.dart
new file mode 100644
index 0000000..c771389
--- /dev/null
+++ b/lib/services/background_task/background_task.dart
@@ -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 {
+ /// 用户主动触发(如用户点击安装/卸载组件):最高优先
+ 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 {
+ /// 全局唯一任务 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 execute(TaskExecutionContext context);
+
+ /// 取消回调
+ void onCancelled() {}
+
+ /// 失败回调
+ void onFailure(Object error, StackTrace stackTrace) {}
+
+ /// 成功回调
+ void onSuccess(T result) {}
+}
diff --git a/lib/services/background_task/background_task_scheduler.dart b/lib/services/background_task/background_task_scheduler.dart
new file mode 100644
index 0000000..0a7975c
--- /dev/null
+++ b/lib/services/background_task/background_task_scheduler.dart
@@ -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 {
+ final BackgroundTask task;
+ final Completer 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 _runningTasks = {};
+
+ /// 绑定全局通知中心
+ void attachNoticeCenter(NoticeCenter noticeCenter) {
+ _noticeCenter = noticeCenter;
+ }
+
+ /// 提交一个后台任务
+ Future submit(BackgroundTask task) {
+ final completer = Completer();
+ final cancelToken = HeadlessCancelToken();
+
+ final entry = _QueuedTaskEntry(
+ 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 _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: ';
+}
diff --git a/lib/services/background_task/generic_background_task.dart b/lib/services/background_task/generic_background_task.dart
new file mode 100644
index 0000000..d712034
--- /dev/null
+++ b/lib/services/background_task/generic_background_task.dart
@@ -0,0 +1,36 @@
+import '../../models/notice_item.dart';
+import 'background_task.dart';
+
+/// 包装一个函数执行体到后台调度系统(如探测中的依赖自动安装等)
+class GenericBackgroundTask extends BackgroundTask {
+ @override
+ final String id;
+ @override
+ final TaskExecutionScope scope;
+ @override
+ final TaskPriority priority;
+ @override
+ final bool showNotice;
+
+ final Future 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 execute(TaskExecutionContext context) {
+ return runner(context);
+ }
+}
diff --git a/lib/services/code_completion/core/completion_engine.dart b/lib/services/code_completion/core/completion_engine.dart
new file mode 100644
index 0000000..154c9bf
--- /dev/null
+++ b/lib/services/code_completion/core/completion_engine.dart
@@ -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 providers;
+ final int maxSuggestions;
+
+ int _lastRequestId = 0;
+
+ /// 异步直接请求补全(专为 LSP 异步语义流优化设计)
+ Future 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 [];
+ }
+ }),
+ );
+
+ // 请求过期(用户已键入新内容或已移动光标),直接废弃
+ if (currentRequestId != _lastRequestId) return null;
+
+ final allPrompts = [];
+ final seenWords = {};
+ 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? notifier,
+ }) {
+ if (notifier != null) {
+ requestCompletionsAsync(context).then((value) {
+ if (value != null) {
+ notifier.value = value;
+ }
+ });
+ }
+ return null;
+ }
+
+ /// 模糊匹配打分、权重排序与截取
+ CodeAutocompleteEditingValue? scoreAndFilter(List candidates, String input) {
+ if (candidates.isEmpty) {
+ return null;
+ }
+
+ final List 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();
+ }
+ }
+}
diff --git a/lib/services/code_completion/core/completion_types.dart b/lib/services/code_completion/core/completion_types.dart
new file mode 100644
index 0000000..44cdfcb
--- /dev/null
+++ b/lib/services/code_completion/core/completion_types.dart
@@ -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 parameters;
+ final String? detail;
+ final String? documentation;
+ final String? sortText;
+ int score;
+ List 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 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 == '.';
+}
diff --git a/lib/services/code_completion/fuzzy_matcher.dart b/lib/services/code_completion/fuzzy_matcher.dart
new file mode 100644
index 0000000..b1a652a
--- /dev/null
+++ b/lib/services/code_completion/fuzzy_matcher.dart
@@ -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 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 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 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 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 prev = List.generate(s2.length + 1, (i) => i);
+ List curr = List.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];
+ }
+}
diff --git a/lib/services/code_completion/providers/completion_provider.dart b/lib/services/code_completion/providers/completion_provider.dart
new file mode 100644
index 0000000..509d00a
--- /dev/null
+++ b/lib/services/code_completion/providers/completion_provider.dart
@@ -0,0 +1,17 @@
+import 'dart:async';
+import '../core/completion_types.dart';
+
+/// 补全数据源提供者抽象契约
+abstract class CompletionProvider {
+ /// 提供者唯一标识
+ String get id;
+
+ /// 是否为异步远程数据源(如 LSP)
+ bool get isAsync => false;
+
+ /// 依据上下文提供补全候选项
+ FutureOr> provideCompletions(CompletionContext context);
+
+ /// 释放资源
+ void dispose() {}
+}
diff --git a/lib/services/code_completion/providers/lsp_completion_provider.dart b/lib/services/code_completion/providers/lsp_completion_provider.dart
new file mode 100644
index 0000000..f947ec8
--- /dev/null
+++ b/lib/services/code_completion/providers/lsp_completion_provider.dart
@@ -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> 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() {}
+}
diff --git a/lib/services/code_completion/smart_prompts_builder.dart b/lib/services/code_completion/smart_prompts_builder.dart
new file mode 100644
index 0000000..3b53aa7
--- /dev/null
+++ b/lib/services/code_completion/smart_prompts_builder.dart
@@ -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 keywordPrompts = const [],
+ @Deprecated('本地补全已完全移除,此参数无效') List directPrompts = const [],
+ @Deprecated('本地补全已完全移除,此参数无效') Map> relatedPrompts = const {},
+ List? customProviders,
+ }) {
+ final providers = [
+ 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? activeNotifier;
+
+ @override
+ FutureOr 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; // _
+ }
+}
+
diff --git a/lib/services/distro_download_manager.dart b/lib/services/distro_download_manager.dart
deleted file mode 100644
index f25410e..0000000
--- a/lib/services/distro_download_manager.dart
+++ /dev/null
@@ -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 _progressMap = {};
- final Map _activeRequests = {};
- final Map _activeClients = {};
- final Map>> _activeSubscriptions = {};
- final Map _activeSinks = {};
- final Map> _activeCompleters = {};
- final Set _cancelledDistroIds = {};
-
- @visibleForTesting
- Directory? customPackagesDir;
-
- /// 获取系统安装包持久化存储目录: `/distro_packages`
- Future 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 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 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 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 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 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>? subscription;
- final completer = Completer();
- _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 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();
- }
-}
diff --git a/lib/services/distro_image_resolver.dart b/lib/services/distro_image_resolver.dart
deleted file mode 100644
index 4e7a90a..0000000
--- a/lib/services/distro_image_resolver.dart
+++ /dev/null
@@ -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 _resolvedUrlCache = {};
-
- /// 缓存的 index-system 纯文本内容 (key: mirrorId, value: (cachedTime, content))
- final Map _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 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 parseIndex(String content) {
- final lines = content.split('\n');
- final List 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 _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();
- }
- }
-}
diff --git a/lib/services/distro_installer.dart b/lib/services/distro_installer.dart
index 1d99c4b..da0d019 100644
--- a/lib/services/distro_installer.dart
+++ b/lib/services/distro_installer.dart
@@ -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 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 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)
diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart
index b2e1929..98e5721 100644
--- a/lib/services/distro_manager.dart
+++ b/lib/services/distro_manager.dart
@@ -257,53 +257,7 @@ class DistroManager {
);
}
- /// 从应用内置资源导入 Alpine Linux 系统实例(保留备用)
- ///
- /// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
- Future 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 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 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 _ensureL2sDir(String systemName, {Directory? customBaseDir}) async {
+ /// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro l2s.py,位于 rootfs/.l2s)
+ Future _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 目录 (/.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');
diff --git a/lib/services/internal_engine_service.dart b/lib/services/internal_engine_service.dart
index 1232a54..e38ca1d 100644
--- a/lib/services/internal_engine_service.dart
+++ b/lib/services/internal_engine_service.dart
@@ -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;
- /// 获取引擎主目录: `/internal_engine/alpine`
- Future getEngineDir() async {
+ /// 获取主系统 Ubuntu rootfs 目录
+ Future 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 目录: `/internal_engine/alpine/rootfs`
- Future getRootfsDir() async {
- final engineDir = await getEngineDir();
- return Directory(p.join(engineDir.path, 'rootfs'));
- }
+ /// 兼容旧方法命名
+ Future getEngineDir() => getRootfsDir();
- /// 检查内置 Alpine 引擎是否已完整安装
+ /// 检查主系统 Ubuntu 是否已完整安装
Future 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 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 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 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 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 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;
}
}
diff --git a/lib/services/lsp/cpp_project_helper.dart b/lib/services/lsp/cpp_project_helper.dart
new file mode 100644
index 0000000..082a9de
--- /dev/null
+++ b/lib/services/lsp/cpp_project_helper.dart
@@ -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 _ignoredDirNames = {
+ '.git',
+ '.vscode',
+ '.idea',
+ '.dart_tool',
+ 'build',
+ 'out',
+ 'dist',
+ 'bin',
+ 'obj',
+ 'node_modules',
+ 'cache',
+ 'tmp',
+ };
+
+ static const Set _headerExtensions = {
+ '.h',
+ '.hpp',
+ '.hxx',
+ '.hh',
+ '.inl',
+ };
+
+ /// 确保指定工作区根目录下具备 clangd 编译配置
+ static Future 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 = {};
+ _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 result, {
+ required int currentDepth,
+ required int maxDepth,
+ }) {
+ if (currentDepth > maxDepth) return;
+
+ try {
+ final entries = current.listSync(followLinks: false);
+ bool dirHasHeader = false;
+
+ final subDirs = [];
+ 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 (_) {}
+ }
+}
diff --git a/lib/services/lsp/lsp_client.dart b/lib/services/lsp/lsp_client.dart
new file mode 100644
index 0000000..67d7dba
--- /dev/null
+++ b/lib/services/lsp/lsp_client.dart
@@ -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> _stdoutSub;
+ final StreamSubscription> _stderrSub;
+
+ int _nextId = 1;
+ final Map> _pendingRequests = {};
+ final Map> _notificationListeners = {};
+
+ final List _buffer = [];
+ bool _isClosed = false;
+ bool get isClosed => _isClosed;
+
+ /// 串行异步写入链,杜绝并发写入 stdin 导致 StreamSink is bound to a stream 异常
+ Future _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 sendRequest(String method, [dynamic params, Duration timeout = const Duration(seconds: 10)]) async {
+ if (_isClosed) {
+ throw StateError('LspClient 已关闭,无法发送请求: $method');
+ }
+
+ final id = _nextId++;
+ final completer = Completer();
+ _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 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 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) {
+ _dispatchMessage(msg);
+ }
+ } catch (e) {
+ debugPrint('[LspClient] 解析消息体异常: $e');
+ }
+ }
+ }
+
+ void _dispatchMessage(Map 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 chunk) {
+ // 记录语言服务器的 stderr 日志(调试信息)
+ final text = utf8.decode(chunk, allowMalformed: true);
+ if (kDebugMode) {
+ debugPrint('[LSP Stderr] $text');
+ }
+ }
+
+ int _findHeaderEnd(List 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 (_) {}
+ }
+}
diff --git a/lib/services/lsp/lsp_diagnostics_store.dart b/lib/services/lsp/lsp_diagnostics_store.dart
new file mode 100644
index 0000000..6d918dd
--- /dev/null
+++ b/lib/services/lsp/lsp_diagnostics_store.dart
@@ -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`
+ final Map> _diagnosticsByFile = {};
+
+ /// 更新某个文件的诊断列表
+ void updateDiagnostics(String uriOrPath, List diagnostics) {
+ final normalized = _normalizePath(uriOrPath);
+ if (diagnostics.isEmpty) {
+ _diagnosticsByFile.remove(normalized);
+ } else {
+ // 按错误起始行号和字符列号升序排序
+ final sorted = List.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 getDiagnosticsForFile(String? filePath) {
+ if (filePath == null || filePath.isEmpty) return const [];
+ return _diagnosticsByFile[_normalizePath(filePath)] ?? const [];
+ }
+
+ /// 获取指定文件在第 [line] 行(0-indexed)上的所有诊断
+ List 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;
+ }
+}
diff --git a/lib/services/lsp/lsp_manager.dart b/lib/services/lsp/lsp_manager.dart
new file mode 100644
index 0000000..6ab44d7
--- /dev/null
+++ b/lib/services/lsp/lsp_manager.dart
@@ -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 _activeSessions = {};
+ final Map> _startingSessions = {};
+
+ /// 获取或拉起匹配当前文件的语言服务会话
+ Future 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 _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.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 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 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 disposeAll() async {
+ for (final session in _activeSessions.values) {
+ await session.close();
+ }
+ _activeSessions.clear();
+ _startingSessions.clear();
+ notifyListeners();
+ }
+}
diff --git a/lib/services/lsp/lsp_protocol.dart b/lib/services/lsp/lsp_protocol.dart
new file mode 100644
index 0000000..244704f
--- /dev/null
+++ b/lib/services/lsp/lsp_protocol.dart
@@ -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 json) {
+ return LspPosition(
+ line: json['line'] as int? ?? 0,
+ character: json['character'] as int? ?? 0,
+ );
+ }
+
+ Map 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 json) {
+ return LspRange(
+ start: LspPosition.fromJson(json['start'] as Map? ?? const {}),
+ end: LspPosition.fromJson(json['end'] as Map? ?? const {}),
+ );
+ }
+
+ Map 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 json) {
+ return LspDiagnostic(
+ range: LspRange.fromJson(json['range'] as Map? ?? const {}),
+ severity: json['severity'] as int? ?? 1,
+ code: json['code'],
+ source: json['source'] as String?,
+ message: json['message'] as String? ?? '',
+ data: json['data'],
+ );
+ }
+
+ Map 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 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 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 json) {
+ final diagsRaw = json['diagnostics'] as List? ?? const [];
+ final diags = diagsRaw
+ .whereType