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>() + .map((d) => LspDiagnostic.fromJson(d)) + .toList(); + + LspWorkspaceEdit? wsEdit; + if (json['edit'] is Map) { + wsEdit = LspWorkspaceEdit.fromJson(json['edit'] as Map); + } + + return LspCodeAction( + title: json['title'] as String? ?? '', + kind: json['kind'] as String?, + diagnostics: diags, + isPreferred: json['isPreferred'] as bool? ?? false, + edit: wsEdit, + ); + } +} + +class LspWorkspaceEdit { + final Map> changes; + + const LspWorkspaceEdit({this.changes = const {}}); + + factory LspWorkspaceEdit.fromJson(Map json) { + final rawChanges = json['changes']; + final Map> result = {}; + if (rawChanges is Map) { + rawChanges.forEach((uri, edits) { + if (edits is List) { + result[uri.toString()] = edits + .whereType>() + .map((e) => LspTextEdit.fromJson(e)) + .toList(); + } + }); + } + return LspWorkspaceEdit(changes: result); + } +} + +class LspTextEdit { + final LspRange range; + final String newText; + + const LspTextEdit({required this.range, required this.newText}); + + factory LspTextEdit.fromJson(Map json) { + return LspTextEdit( + range: LspRange.fromJson(json['range'] as Map? ?? const {}), + newText: json['newText'] as String? ?? '', + ); + } + + Map toJson() => { + 'range': range.toJson(), + 'newText': newText, + }; +} diff --git a/lib/services/lsp/lsp_session.dart b/lib/services/lsp/lsp_session.dart new file mode 100644 index 0000000..e16ef54 --- /dev/null +++ b/lib/services/lsp/lsp_session.dart @@ -0,0 +1,240 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart'; +import '../../models/lsp_language_config.dart'; +import 'lsp_client.dart'; +import 'lsp_diagnostics_store.dart'; +import 'lsp_protocol.dart'; +import 'proot_path_mapper.dart'; + +/// 单个语言服务会话(管理与后台进程的文档增量同步、智能补全与诊断流) +class LspSession { + final LspClient client; + final LspLanguageConfig config; + final String workspaceRoot; + + final Map _fileVersions = {}; + final Map _debounceTimers = {}; + bool _isInitialized = false; + bool get isInitialized => _isInitialized; + + LspSession({ + required this.client, + required this.config, + required this.workspaceRoot, + }) { + _registerNotificationHandlers(); + } + + void _registerNotificationHandlers() { + client.onNotification('textDocument/publishDiagnostics', (params) { + if (params is Map) { + final uri = params['uri'] as String? ?? ''; + final diagsRaw = params['diagnostics'] as List? ?? const []; + final diags = diagsRaw + .whereType>() + .map((d) => LspDiagnostic.fromJson(d)) + .toList(); + + final hostPath = _fromGuestUriToHostPath(uri); + LspDiagnosticsStore.instance.updateDiagnostics(hostPath, diags); + if (hostPath != uri) { + LspDiagnosticsStore.instance.updateDiagnostics(uri, diags); + } + } + }); + } + + /// 发送 initialize 握手报文 + Future initialize() async { + final rootUri = _toGuestUri(workspaceRoot); + final guestRootPath = PRootPathMapper.toGuestPath(workspaceRoot, workspaceRoot); + final initParams = { + 'processId': null, + 'rootUri': rootUri, + 'rootPath': guestRootPath, + 'capabilities': { + 'textDocument': { + 'synchronization': { + 'dynamicRegistration': false, + 'willSave': false, + 'willSaveWaitUntil': false, + 'didSave': true, + }, + 'completion': { + 'dynamicRegistration': false, + 'completionItem': { + 'snippetSupport': true, + 'documentationFormat': ['markdown', 'plaintext'], + }, + }, + 'publishDiagnostics': { + 'relatedInformation': true, + }, + 'codeAction': { + 'codeActionLiteralSupport': { + 'codeActionKind': { + 'valueSet': ['quickfix', 'refactor'], + }, + }, + }, + }, + }, + }; + + try { + final res = await client.sendRequest('initialize', initParams); + if (res != null) { + client.sendNotification('initialized', {}); + _isInitialized = true; + debugPrint('[LspSession] 语言服务初始化成功: ${config.name} (${config.serverCommand})'); + return true; + } + } catch (e) { + debugPrint('[LspSession] 初始化失败: $e'); + } + return false; + } + + /// 文档打开通知 + void didOpen(String filePath, String text) { + final uri = _toGuestUri(filePath); + _fileVersions[filePath] = 1; + + client.sendNotification('textDocument/didOpen', { + 'textDocument': { + 'uri': uri, + 'languageId': config.languageId, + 'version': 1, + 'text': text, + }, + }); + } + + /// 文档内容变更通知(带 250ms 智能防抖) + void didChange(String filePath, String fullText) { + if (!_fileVersions.containsKey(filePath)) { + didOpen(filePath, fullText); + return; + } + + _debounceTimers[filePath]?.cancel(); + _debounceTimers[filePath] = Timer(const Duration(milliseconds: 250), () { + if (client.isClosed) return; + final uri = _toGuestUri(filePath); + final newVersion = (_fileVersions[filePath] ?? 1) + 1; + _fileVersions[filePath] = newVersion; + + client.sendNotification('textDocument/didChange', { + 'textDocument': { + 'uri': uri, + 'version': newVersion, + }, + 'contentChanges': [ + {'text': fullText}, + ], + }); + }); + } + + /// 文档关闭通知 + void didClose(String filePath) { + _debounceTimers[filePath]?.cancel(); + _debounceTimers.remove(filePath); + _fileVersions.remove(filePath); + final uri = _toGuestUri(filePath); + + client.sendNotification('textDocument/didClose', { + 'textDocument': { + 'uri': uri, + }, + }); + } + + /// 获取光标处语义补全项列表 + Future> getCompletions( + String filePath, + int line, + int character, + ) async { + final guestUri = _toGuestUri(filePath); + if (!client.isClosed && _isInitialized) { + try { + final res = await client.sendRequest('textDocument/completion', { + 'textDocument': {'uri': guestUri}, + 'position': {'line': line, 'character': character}, + }); + + if (res is List) { + return res + .whereType>() + .map((item) => LspCompletionItem.fromJson(item)) + .toList(); + } else if (res is Map && res['items'] is List) { + final items = res['items'] as List; + return items + .whereType>() + .map((item) => LspCompletionItem.fromJson(item)) + .toList(); + } + } catch (e) { + debugPrint('[LspSession] 获取补全失败: $e'); + } + } + return const []; + } + + /// 获取指定错误或位置的代码修复操作(QuickFix) + Future> getCodeActions( + String filePath, + LspRange range, + List diagnostics, + ) async { + if (!client.isClosed && _isInitialized) { + try { + final res = await client.sendRequest('textDocument/codeAction', { + 'textDocument': {'uri': _toGuestUri(filePath)}, + 'range': range.toJson(), + 'context': { + 'diagnostics': diagnostics.map((d) => d.toJson()).toList(), + 'only': ['quickfix'], + }, + }); + + if (res is List) { + return res + .whereType>() + .map((a) => LspCodeAction.fromJson(a)) + .toList(); + } + } catch (e) { + debugPrint('[LspSession] 获取 CodeAction 失败: $e'); + } + } + return const []; + } + + /// 转换宿主文件路径为容器内部映射的 URI + String _toGuestUri(String hostFilePath) { + return PRootPathMapper.toGuestUri(hostFilePath, workspaceRoot); + } + + /// 将容器内部的 URI 反向还原为宿主文件绝对路径 + String _fromGuestUriToHostPath(String guestUri) { + return PRootPathMapper.fromGuestUriToHostPath(guestUri, workspaceRoot); + } + + Future close() async { + for (final timer in _debounceTimers.values) { + timer.cancel(); + } + _debounceTimers.clear(); + _fileVersions.clear(); + + try { + await client.sendRequest('shutdown', null, const Duration(seconds: 1)); + client.sendNotification('exit'); + } catch (_) {} + + client.close(); + } +} diff --git a/lib/services/lsp/lsp_workspace_edit_applier.dart b/lib/services/lsp/lsp_workspace_edit_applier.dart new file mode 100644 index 0000000..ad99fb6 --- /dev/null +++ b/lib/services/lsp/lsp_workspace_edit_applier.dart @@ -0,0 +1,84 @@ +import 'package:re_editor/re_editor.dart'; +import 'lsp_protocol.dart'; + +/// 负责将 LSP 服务端返回的 WorkspaceEdit / TextEdit 序列安全、有序地应用到当前编辑器控制器中 +class LspWorkspaceEditApplier { + /// 将 [edit] 应用至 [controller] + static void applyWorkspaceEdit( + CodeLineEditingController controller, + LspWorkspaceEdit edit, { + required String currentFilePath, + }) { + final normalizedTarget = _normalize(currentFilePath); + List? targetEdits; + + for (final entry in edit.changes.entries) { + final normalizedUri = _normalize(entry.key); + if (normalizedTarget.endsWith(normalizedUri) || + normalizedUri.endsWith(normalizedTarget) || + normalizedTarget.toLowerCase() == normalizedUri.toLowerCase()) { + targetEdits = entry.value; + break; + } + } + + if (targetEdits == null || targetEdits.isEmpty) return; + + applyTextEdits(controller, targetEdits); + } + + /// 依据 LSP 规范,对逆向排序后的编辑操作逐一应用,防止前序编辑破坏后续行列偏移 + static void applyTextEdits( + CodeLineEditingController controller, + List edits, + ) { + if (edits.isEmpty) return; + + // 逆序排序:先按行号降序,同行按列号降序 + final sortedEdits = List.from(edits) + ..sort((a, b) { + final lineComp = b.range.start.line.compareTo(a.range.start.line); + if (lineComp != 0) return lineComp; + return b.range.start.character.compareTo(a.range.start.character); + }); + + final totalLines = controller.lineCount; + + for (final te in sortedEdits) { + final startLine = te.range.start.line.clamp(0, totalLines - 1); + final endLine = te.range.end.line.clamp(0, totalLines - 1); + + final startLineLen = controller.codeLines[startLine].text.length; + final endLineLen = controller.codeLines[endLine].text.length; + + final startCol = te.range.start.character.clamp(0, startLineLen); + final endCol = te.range.end.character.clamp(0, endLineLen); + + final selection = CodeLineSelection( + baseIndex: startLine, + baseOffset: startCol, + extentIndex: endLine, + extentOffset: endCol, + ); + + controller.replaceSelection(te.newText, selection); + } + } + + static String _normalize(String input) { + String path = input; + if (path.startsWith('file://')) { + final uri = Uri.tryParse(path); + if (uri != null && uri.hasAbsolutePath) { + path = uri.toFilePath(); + } else { + path = path.substring(7); + } + } + path = path.replaceAll('\\', '/'); + if (path.length >= 2 && path[1] == ':') { + path = path[0].toLowerCase() + path.substring(1); + } + return path; + } +} diff --git a/lib/services/lsp/proot_path_mapper.dart b/lib/services/lsp/proot_path_mapper.dart new file mode 100644 index 0000000..e7dbf76 --- /dev/null +++ b/lib/services/lsp/proot_path_mapper.dart @@ -0,0 +1,71 @@ +import 'package:path/path.dart' as p; + +/// PRoot 容器路径与宿主文件路径双向映射器 +/// +/// 在 Android 手机端 PRoot 架构中: +/// - 宿主端文件真实路径例如:`/data/data/com.example/files/workspace/main.c` 或 Windows 开发测试路径 +/// - PRoot 启动参数将工作区绑定挂载至容器内部 `/workspace` +/// - 发送给 LSP 服务端(如 clangd)的文档 URI 需映射为 `file:///workspace/...` +/// - 接收 LSP 服务端诊断或引用返回的容器 URI 需反向还原为宿主绝对路径 +class PRootPathMapper { + const PRootPathMapper(); + + /// 转换宿主文件路径为容器内部映射的 URI + static String toGuestUri(String hostFilePath, String workspaceRoot) { + if (workspaceRoot.isEmpty) { + return _toFileUri(hostFilePath); + } + + final normHost = p.normalize(hostFilePath).replaceAll('\\', '/'); + final normRoot = p.normalize(workspaceRoot).replaceAll('\\', '/'); + + if (normHost == normRoot) { + return 'file:///workspace'; + } + + if (normHost.startsWith('$normRoot/')) { + final relative = normHost.substring(normRoot.length + 1); + return 'file:///workspace/$relative'; + } + + if (normHost.startsWith(normRoot)) { + final relative = normHost.substring(normRoot.length).replaceFirst(RegExp(r'^/'), ''); + return 'file:///workspace/$relative'; + } + + return _toFileUri(hostFilePath); + } + + /// 转换宿主文件路径为容器内部真实绝对路径(例如 /workspace/src/main.c) + static String toGuestPath(String hostFilePath, String workspaceRoot) { + final uri = toGuestUri(hostFilePath, workspaceRoot); + if (uri.startsWith('file://')) { + return uri.substring('file://'.length); + } + return uri; + } + + /// 将容器内部的 URI 反向还原为宿主文件绝对路径 + static String fromGuestUriToHostPath(String guestUri, String workspaceRoot) { + final normUri = guestUri.replaceAll('\\', '/'); + if (normUri.startsWith('file:///workspace/')) { + final relative = normUri.substring('file:///workspace/'.length); + return p.join(workspaceRoot, relative).replaceAll('\\', '/'); + } + if (normUri == 'file:///workspace') { + return workspaceRoot.replaceAll('\\', '/'); + } + if (normUri.startsWith('file:///')) { + // 普通 file:/// 协议,若未挂载至 /workspace 则直接去除 file:// 前缀 + return normUri.substring('file://'.length); + } + return guestUri; + } + + static String _toFileUri(String path) { + final normalized = p.normalize(path).replaceAll('\\', '/'); + if (normalized.startsWith('file://')) return normalized; + if (normalized.startsWith('/')) return 'file://$normalized'; + return 'file:///$normalized'; + } +} diff --git a/lib/services/lsp_config_service.dart b/lib/services/lsp_config_service.dart index eeeb337..47155d7 100644 --- a/lib/services/lsp_config_service.dart +++ b/lib/services/lsp_config_service.dart @@ -20,7 +20,7 @@ class LspConfigService extends ChangeNotifier { List get configs => List.unmodifiable(_configs); bool get isLoaded => _isLoaded; - /// 获取配置文件路径: `/internal_engine/lsp_languages.json` + /// 获取配置文件路径: `/config/lsp_languages.json` Future getConfigFile() async { final Directory baseDir; if (customBaseDir != null) { @@ -30,7 +30,28 @@ class LspConfigService extends ChangeNotifier { final rootPath = p.basename(appDir.path) == 'files' ? appDir.path : p.join(appDir.path, 'files'); - baseDir = Directory(p.join(rootPath, 'internal_engine')); + baseDir = Directory(p.join(rootPath, 'config')); + + // 自动迁移旧版本放置在 internal_engine 的配置文件并清理旧目录 + try { + final legacyDir = Directory(p.join(rootPath, 'internal_engine')); + final legacyFile = File(p.join(legacyDir.path, 'lsp_languages.json')); + final targetFile = File(p.join(baseDir.path, 'lsp_languages.json')); + + if (legacyFile.existsSync() && !targetFile.existsSync()) { + if (!baseDir.existsSync()) { + baseDir.createSync(recursive: true); + } + legacyFile.copySync(targetFile.path); + } + + if (legacyDir.existsSync()) { + legacyDir.deleteSync(recursive: true); + debugPrint('[LspConfigService] 已迁移并清理旧 internal_engine 目录'); + } + } catch (e) { + debugPrint('[LspConfigService] 清理旧 internal_engine 异常: $e'); + } } if (!baseDir.existsSync()) { @@ -39,7 +60,7 @@ class LspConfigService extends ChangeNotifier { return File(p.join(baseDir.path, 'lsp_languages.json')); } - /// 加载配置,若缺失预设语言则自动增量追加合并并回写 + /// 加载已安装的配置列表。初始为空数组 [],不存在未安装的占位项 Future> loadConfigs({bool forceReload = false}) async { if (_isLoaded && !forceReload) { return _configs; @@ -50,34 +71,28 @@ class LspConfigService extends ChangeNotifier { bool needSave = false; if (!file.existsSync()) { - loaded = List.from(LspLanguageConfig.defaultPresets); + // 初始为空数组,写入持久化文件 + loaded = []; needSave = true; } else { try { - final content = file.readAsStringSync(); - final dynamic raw = jsonDecode(content); - if (raw is List) { - loaded = raw - .map((e) => e is Map - ? LspLanguageConfig.fromJson(e) - : null) - .whereType() - .toList(); + final content = file.readAsStringSync().trim(); + if (content.isNotEmpty) { + final dynamic raw = jsonDecode(content); + if (raw is List) { + loaded = raw + .map((e) => e is Map + ? LspLanguageConfig.fromJson(e) + : null) + .whereType() + .toList(); + } } } catch (e) { - debugPrint('读取 lsp_languages.json 异常: $e,使用默认预设'); - loaded = List.from(LspLanguageConfig.defaultPresets); + debugPrint('读取 lsp_languages.json 异常: $e'); + loaded = []; needSave = true; } - - // 动态增量合并:对比官方预设,若预设中某项 id 本地缺失,则追加进去,默认 enabled: true - final existingIds = loaded.map((e) => e.id).toSet(); - for (final preset in LspLanguageConfig.defaultPresets) { - if (!existingIds.contains(preset.id)) { - loaded.add(preset.copyWith(enabled: true)); - needSave = true; - } - } } _configs = loaded; @@ -118,9 +133,9 @@ class LspConfigService extends ChangeNotifier { notifyListeners(); } - /// 恢复官方默认预设 + /// 清空所有已配置的语言项 Future resetToDefaults() async { - _configs = List.from(LspLanguageConfig.defaultPresets); + _configs = []; await _writeToDisk(); notifyListeners(); } @@ -131,11 +146,10 @@ class LspConfigService extends ChangeNotifier { final normalized = ext.startsWith('.') ? ext.toLowerCase() : '.$ext'.toLowerCase(); for (final config in _configs) { - if (!config.enabled) continue; for (final item in config.fileExtensions) { final itemNorm = item.startsWith('.') ? item.toLowerCase() : '.$item'.toLowerCase(); if (itemNorm == normalized) { - return config; + return config.enabled ? config : null; } } } diff --git a/lib/services/project_modules/maven_project_module.dart b/lib/services/project_modules/maven_project_module.dart new file mode 100644 index 0000000..ab391a6 --- /dev/null +++ b/lib/services/project_modules/maven_project_module.dart @@ -0,0 +1,76 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +import '../../models/run_task.dart'; +import 'project_module.dart'; +import 'project_probe.dart'; + +/// Maven (Java) 工程模块:识别 pom.xml 或 mvnw 包装脚本 +class MavenProjectModule extends ProjectModule { + @override + String get id => 'maven'; + + @override + String get displayName => 'Maven'; + + @override + List get triggerFiles => const ['pom.xml', 'mvnw']; + + @override + bool shouldActivate(Directory projectDir) { + return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync()); + } + + @override + List get requiredToolchainKeys => const ['maven']; + + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + + final root = probe.projectDir; + final hasWrapper = File(p.join(root.path, 'mvnw')).existsSync(); + final cmdPrefix = hasWrapper ? './mvnw' : 'mvn'; + + return ModuleProbeResult.ok(id, [ + RunTask( + id: 'detected_maven_package', + name: 'Maven: Package', + command: '$cmdPrefix package', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.inventory_2_outlined, + ), + RunTask( + id: 'detected_maven_compile', + name: 'Maven: Compile', + command: '$cmdPrefix compile', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.build_outlined, + ), + RunTask( + id: 'detected_maven_test', + name: 'Maven: Test', + command: '$cmdPrefix test', + source: TaskSource.detected, + group: 'verification', + moduleId: id, + icon: Icons.fact_check_outlined, + ), + RunTask( + id: 'detected_maven_clean', + name: 'Maven: Clean', + command: '$cmdPrefix clean', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.cleaning_services_outlined, + ), + ]); + } +} diff --git a/lib/services/project_modules/project_probe.dart b/lib/services/project_modules/project_probe.dart index bb7a19d..1bd21cb 100644 --- a/lib/services/project_modules/project_probe.dart +++ b/lib/services/project_modules/project_probe.dart @@ -4,6 +4,9 @@ import 'package:flutter/foundation.dart'; import '../../models/notice_item.dart'; import '../../models/run_task.dart'; +import '../background_task/background_task.dart'; +import '../background_task/background_task_scheduler.dart'; +import '../background_task/generic_background_task.dart'; import '../distro_manager.dart'; import '../toolchain_service.dart'; @@ -297,15 +300,34 @@ class ProjectProbe { if (commands.isEmpty) return false; final script = commands.join(' && '); - final result = await runHeadless( - script, - timeout: const Duration(minutes: 10), - onStdout: (chunk) { - final line = chunk.trim(); - if (line.isNotEmpty) setInstallLine(line); + + // 接入统一调度器:通过 TaskExecutionScope.packageManager 保证独占排他锁, + // 不与用户同时触发的 LSP 组件安装/卸载冲突 + final task = GenericBackgroundTask( + id: 'probe:toolchains:${toolchainKeys.join('+')}', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + showNotice: false, // 模块探测自身已有专用的 ModulePhaseText 弹窗显示 + runner: (taskContext) async { + if (isCancelled || _disposed) return false; + + final result = await runHeadless( + script, + timeout: const Duration(minutes: 10), + onStdout: (chunk) { + final line = chunk.trim(); + if (line.isNotEmpty) setInstallLine(line); + }, + ); + return result != null && result.exitCode == 0; }, ); - return result != null && result.exitCode == 0; + + try { + return await BackgroundTaskScheduler.instance.submit(task); + } catch (_) { + return false; + } } /// 更新安装进度行(带释放保护,避免取消/释放后写入已 dispose 的 notifier) diff --git a/lib/services/project_modules/python_project_module.dart b/lib/services/project_modules/python_project_module.dart new file mode 100644 index 0000000..dabc3cf --- /dev/null +++ b/lib/services/project_modules/python_project_module.dart @@ -0,0 +1,103 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +import '../../models/run_task.dart'; +import 'project_module.dart'; +import 'project_probe.dart'; + +/// Python 工程模块:识别 requirements.txt、pyproject.toml 等特征 +class PythonProjectModule extends ProjectModule { + @override + String get id => 'python'; + + @override + String get displayName => 'Python'; + + @override + List get triggerFiles => const [ + 'requirements.txt', + 'pyproject.toml', + 'setup.py', + 'Pipfile', + ]; + + @override + bool shouldActivate(Directory projectDir) { + return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync()); + } + + @override + List get requiredToolchainKeys => const ['python3']; + + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + + final tasks = []; + final root = probe.projectDir; + + // 1. 依赖安装任务 + if (File(p.join(root.path, 'requirements.txt')).existsSync()) { + tasks.add( + RunTask( + id: 'detected_python_pip_install', + name: 'Pip: Install Requirements', + command: 'pip3 install -r requirements.txt', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.download_outlined, + ), + ); + } + + // 2. 主入口任务 + if (File(p.join(root.path, 'main.py')).existsSync()) { + tasks.add( + RunTask( + id: 'detected_python_run_main', + name: 'Python: Run main.py', + command: 'python3 main.py', + source: TaskSource.detected, + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + ); + } else if (File(p.join(root.path, 'app.py')).existsSync()) { + tasks.add( + RunTask( + id: 'detected_python_run_app', + name: 'Python: Run app.py', + command: 'python3 app.py', + source: TaskSource.detected, + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + ); + } + + // 3. 测试任务 + final hasTestsDir = Directory(p.join(root.path, 'tests')).existsSync() || + Directory(p.join(root.path, 'test')).existsSync(); + final hasPytestIni = File(p.join(root.path, 'pytest.ini')).existsSync(); + if (hasTestsDir || hasPytestIni) { + tasks.add( + RunTask( + id: 'detected_python_pytest', + name: 'Pytest: Run Tests', + command: 'pytest', + source: TaskSource.detected, + group: 'verification', + moduleId: id, + icon: Icons.fact_check_outlined, + ), + ); + } + + return ModuleProbeResult.ok(id, tasks); + } +} diff --git a/lib/services/project_modules/single_file_task_detector.dart b/lib/services/project_modules/single_file_task_detector.dart index 3f3e273..497a6d3 100644 --- a/lib/services/project_modules/single_file_task_detector.dart +++ b/lib/services/project_modules/single_file_task_detector.dart @@ -30,6 +30,12 @@ class SingleFileTaskDetector { '.go', '.rs', '.js', + '.java', + '.ts', + '.mts', + '.lua', + '.pl', + '.php', }; /// 检查给定文件路径是否属于支持的单文件任务类型 @@ -135,6 +141,52 @@ class SingleFileTaskDetector { group: 'single_file', icon: Icons.javascript, ); + case '.java': + return RunTask( + id: 'detected_single_java', + name: 'Java: $fileName', + command: 'java $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); + case '.ts': + case '.mts': + return RunTask( + id: 'detected_single_ts', + name: 'TypeScript: $fileName', + command: 'npx -y tsx $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.javascript, + ); + case '.lua': + return RunTask( + id: 'detected_single_lua', + name: 'Lua: $fileName', + command: 'lua $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); + case '.pl': + return RunTask( + id: 'detected_single_perl', + name: 'Perl: $fileName', + command: 'perl $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.terminal, + ); + case '.php': + return RunTask( + id: 'detected_single_php', + name: 'PHP: $fileName', + command: 'php $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); default: return null; } diff --git a/lib/services/project_modules/standard_project_modules.dart b/lib/services/project_modules/standard_project_modules.dart index 1bd28a4..10e94f8 100644 --- a/lib/services/project_modules/standard_project_modules.dart +++ b/lib/services/project_modules/standard_project_modules.dart @@ -4,6 +4,9 @@ library; export 'cargo_project_module.dart'; export 'cmake_project_module.dart'; export 'dart_project_module.dart'; +export 'gradle_project_module.dart'; export 'make_project_module.dart'; +export 'maven_project_module.dart'; export 'npm_project_module.dart'; +export 'python_project_module.dart'; export 'single_file_task_detector.dart'; diff --git a/lib/services/project_task_dispatcher.dart b/lib/services/project_task_dispatcher.dart index 34ff997..6e0038a 100644 --- a/lib/services/project_task_dispatcher.dart +++ b/lib/services/project_task_dispatcher.dart @@ -11,9 +11,11 @@ import 'project_modules/cmake_project_module.dart'; import 'project_modules/dart_project_module.dart'; import 'project_modules/gradle_project_module.dart'; import 'project_modules/make_project_module.dart'; +import 'project_modules/maven_project_module.dart'; import 'project_modules/npm_project_module.dart'; import 'project_modules/project_module.dart'; import 'project_modules/project_probe.dart'; +import 'project_modules/python_project_module.dart'; import 'project_modules/single_file_task_detector.dart'; /// 项目任务总调度(对标 VS Code Task Service / IDE 的 ProjectModel 协调器) @@ -43,11 +45,13 @@ class ProjectTaskDispatcher { void _registerDefaultModules() { _modules.addAll([ GradleProjectModule(), + MavenProjectModule(), CMakeProjectModule(), CargoProjectModule(), NpmProjectModule(), MakeProjectModule(), DartProjectModule(), + PythonProjectModule(), ]); } diff --git a/lib/services/toolchain_service.dart b/lib/services/toolchain_service.dart index b1ce6a1..0449e3a 100644 --- a/lib/services/toolchain_service.dart +++ b/lib/services/toolchain_service.dart @@ -10,161 +10,119 @@ class ToolchainRequirement { /// 用户可见的工具名称/描述 final String displayName; - /// 针对不同发行版家族的自动安装指令 - final Map installCommands; + /// Ubuntu 下的自动安装指令 + final String installCommand; const ToolchainRequirement({ required this.checkBinary, required this.displayName, - required this.installCommands, + required this.installCommand, }); - /// 获取指定发行版家族下的安装命令(对于 Ubuntu/Debian 自动前置 dpkg 自愈修复,防止前序中断报错) - String? getInstallCommand(DistroFamily family) { - final cmd = installCommands[family]; - if (cmd == null) return null; - if (family == DistroFamily.ubuntu || family == DistroFamily.debian) { - return 'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $cmd'; - } - return cmd; + /// 获取安装命令(带自动修复前缀) + String get effectiveInstallCommand => + 'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $installCommand'; + + /// 兼容接口 + String? getInstallCommand([DistroFamily? family]) { + if (family == DistroFamily.unknown) return null; + return effectiveInstallCommand; } } -/// 预编译软件源与工具链检测/安装适配服务 +/// 预编译软件源与工具链检测/安装适配服务(专为 Ubuntu 24.04 深度优化) class ToolchainService { /// 已注册的常用编译器与开发工具链元数据 static const Map supportedTools = { 'make': ToolchainRequirement( checkBinary: 'make', displayName: 'make 编译构建工具', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache make build-base', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', - DistroFamily.arch: 'pacman -Sy --noconfirm base-devel', - DistroFamily.fedora: 'dnf install -y make gcc gcc-c++', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', ), 'cmake': ToolchainRequirement( checkBinary: 'cmake', displayName: 'cmake 构建套件', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache cmake make build-base', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential', - DistroFamily.arch: 'pacman -Sy --noconfirm cmake base-devel', - DistroFamily.fedora: 'dnf install -y cmake make gcc gcc-c++', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential', ), 'gcc': ToolchainRequirement( checkBinary: 'gcc', displayName: 'GCC C 语言编译器', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache gcc musl-dev build-base', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', - DistroFamily.arch: 'pacman -Sy --noconfirm base-devel', - DistroFamily.fedora: 'dnf install -y gcc gcc-c++', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', ), 'g++': ToolchainRequirement( checkBinary: 'g++', displayName: 'G++ C++ 编译器', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache g++ musl-dev build-base', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', - DistroFamily.arch: 'pacman -Sy --noconfirm base-devel', - DistroFamily.fedora: 'dnf install -y gcc-c++', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential', ), 'python3': ToolchainRequirement( checkBinary: 'python3', displayName: 'Python 3 运行环境', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip', - DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip', - DistroFamily.fedora: 'dnf install -y python3 python3-pip', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip', ), 'python': ToolchainRequirement( checkBinary: 'python3', displayName: 'Python 3 运行环境', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip', - DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip', - DistroFamily.fedora: 'dnf install -y python3 python3-pip', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip', ), 'npm': ToolchainRequirement( checkBinary: 'npm', displayName: 'Node.js 与 NPM 环境', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm', - DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm', - DistroFamily.fedora: 'dnf install -y nodejs npm', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm', ), 'node': ToolchainRequirement( checkBinary: 'node', displayName: 'Node.js 运行环境', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm', - DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm', - DistroFamily.fedora: 'dnf install -y nodejs npm', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm', ), 'cargo': ToolchainRequirement( checkBinary: 'cargo', displayName: 'Rust 与 Cargo 工具链', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc', - DistroFamily.arch: 'pacman -Sy --noconfirm rust', - DistroFamily.fedora: 'dnf install -y cargo rust', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc', ), 'rustc': ToolchainRequirement( checkBinary: 'rustc', displayName: 'Rust 编译器', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc', - DistroFamily.arch: 'pacman -Sy --noconfirm rust', - DistroFamily.fedora: 'dnf install -y cargo rust', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc', ), 'go': ToolchainRequirement( checkBinary: 'go', displayName: 'Go 语言环境', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache go', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go', - DistroFamily.arch: 'pacman -Sy --noconfirm go', - DistroFamily.fedora: 'dnf install -y golang', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go', ), 'gradle': ToolchainRequirement( checkBinary: 'java', displayName: 'Java / Gradle 运行时', - installCommands: { - DistroFamily.alpine: 'apk update && apk add --no-cache openjdk17-jre-headless', - DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)', - DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)', - DistroFamily.arch: 'pacman -Sy --noconfirm jdk-openjdk', - DistroFamily.fedora: 'dnf install -y java-latest-openjdk-devel', - }, + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)', + ), + 'java': ToolchainRequirement( + checkBinary: 'java', + displayName: 'Java 运行环境 (JDK)', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)', + ), + 'maven': ToolchainRequirement( + checkBinary: 'mvn', + displayName: 'Maven 构建工具', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y maven default-jdk-headless', + ), + 'mvn': ToolchainRequirement( + checkBinary: 'mvn', + displayName: 'Maven 构建工具', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y maven default-jdk-headless', + ), + 'lua': ToolchainRequirement( + checkBinary: 'lua', + displayName: 'Lua 解释器', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y lua5.4', + ), + 'perl': ToolchainRequirement( + checkBinary: 'perl', + displayName: 'Perl 解释器', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y perl', + ), + 'php': ToolchainRequirement( + checkBinary: 'php', + displayName: 'PHP 命令行环境', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y php-cli', ), }; diff --git a/lib/utils/notice_text_resolver.dart b/lib/utils/notice_text_resolver.dart index 9697c3d..ba59762 100644 --- a/lib/utils/notice_text_resolver.dart +++ b/lib/utils/notice_text_resolver.dart @@ -48,5 +48,22 @@ NoticeDisplay resolveNoticeDisplay(AppLocalizations l10n, NoticeText text) { title: l10n.probeFailedTitle(text.moduleDisplayName), subtitle: subtitle, ); + case ComponentInstallPhaseText(): + final title = text.isQueued + ? l10n.componentQueued(text.componentName) + : (text.isUninstall + ? l10n.uninstallingComponent(text.componentName) + : l10n.installingComponent(text.componentName)); + return NoticeDisplay(title: title, subtitle: text.detail); + case ComponentInstallDoneText(): + final title = text.isUninstall + ? l10n.uninstallComponentSuccess(text.componentName) + : l10n.installComponentSuccess(text.componentName); + return NoticeDisplay(title: title); + case ComponentInstallFailureText(): + final title = text.isUninstall + ? l10n.uninstallComponentFailed(text.error ?? '') + : l10n.installComponentFailed(text.error ?? ''); + return NoticeDisplay(title: title, subtitle: text.error); } } diff --git a/lib/utils/syntax_highlight_helper.dart b/lib/utils/syntax_highlight_helper.dart index 1afafd2..da0d9e2 100644 --- a/lib/utils/syntax_highlight_helper.dart +++ b/lib/utils/syntax_highlight_helper.dart @@ -1,6 +1,7 @@ import 'package:path/path.dart' as p; import 'package:re_editor/re_editor.dart'; import 'package:re_highlight/languages/all.dart'; +import 'package:re_highlight/re_highlight.dart'; /// 语法高亮辅助类: /// 1. 基于文件后缀与特殊文件名的 O(1) 语法匹配,彻底避免全量遍历 @@ -175,4 +176,11 @@ class SyntaxHighlightHelper { } return {langId: mode}; } + + /// 获取指定文件对应的 re_highlight 原始 Mode 定义(用于提取语言关键字等) + static Mode? getGrammarModeForFile(String? filePath) { + final langId = getLanguageId(filePath); + if (langId == null) return null; + return builtinAllLanguages[langId]; + } } diff --git a/lib/views/code_completion_management_view.dart b/lib/views/code_completion_management_view.dart index ec1a3f4..2ea05d1 100644 --- a/lib/views/code_completion_management_view.dart +++ b/lib/views/code_completion_management_view.dart @@ -1,10 +1,14 @@ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import '../l10n/app_localizations.dart'; import '../models/lsp_language_config.dart'; +import '../providers/settings_provider.dart'; import '../services/internal_engine_service.dart'; +import '../services/lsp/lsp_manager.dart'; import '../services/lsp_config_service.dart'; import '../utils/dialog_utils.dart'; import '../widgets/lsp_language_edit_dialog.dart'; +import 'main_view.dart'; /// 代码补全与语言服务管理视图 class CodeCompletionManagementView extends StatefulWidget { @@ -21,6 +25,9 @@ class _CodeCompletionManagementViewState final _engineService = InternalEngineService.instance; final Map _installedStatus = {}; + final Set _expandedConfigIds = {}; + /// 记录正在进行后台安装/卸载任务的语言配置 ID 及其动作类型('install' 或 'uninstall') + final Map _busyConfigActions = {}; bool _isLoadingStatus = false; bool _engineReady = false; @@ -61,12 +68,22 @@ class _CodeCompletionManagementViewState if (mounted) { setState(() { _engineReady = true; - _installedStatus.addAll(newStatus); + _installedStatus + ..clear() + ..addAll(newStatus); _isLoadingStatus = false; }); } } + Future _handleToggleEnabled(LspLanguageConfig config) async { + final updated = config.copyWith(enabled: !config.enabled); + if (!updated.enabled) { + await LspManager.instance.stopSession(config.id); + } + await _lspService.updateConfig(updated); + } + Future _handleEdit(LspLanguageConfig config) async { final updated = await LspLanguageEditDialog.show( context, @@ -86,21 +103,57 @@ class _CodeCompletionManagementViewState final newConfig = await LspLanguageEditDialog.show(context); if (newConfig != null && mounted) { final l10n = AppLocalizations.of(context); - await _lspService.updateConfig(newConfig); - if (mounted && l10n != null) { - DialogUtils.showSuccessToast(context, l10n.languageConfigSaved); + if (l10n == null) return; + + final hasPkg = newConfig.package.trim().isNotEmpty; + if (hasPkg) { + final success = await DialogUtils.showSyncLoadingDialog( + context, + message: l10n.installingComponent(newConfig.package), + task: () => InternalEngineService.instance.installPackage(newConfig.package), + ); + + if (!mounted) return; + + if (success) { + await _lspService.updateConfig(newConfig); + if (mounted) { + DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(newConfig.name)); + _checkCommandsStatus(); + } + } else { + if (mounted) { + DialogUtils.showErrorToast( + context, + l10n.installComponentFailed('apt exit with non-zero code'), + ); + } + } + } else { + // 无系统依赖包名直接保存配置 + await _lspService.updateConfig(newConfig); + if (mounted) { + DialogUtils.showSuccessToast(context, l10n.languageConfigSaved); + _checkCommandsStatus(); + } } - _checkCommandsStatus(); } } Future _handleDelete(LspLanguageConfig config) async { final l10n = AppLocalizations.of(context)!; + final isInstalled = _installedStatus[config.id] ?? false; + final hasPackage = config.package.trim().isNotEmpty; + + final contentText = (isInstalled && hasPackage) + ? l10n.deleteLanguageWithPackageConfirmMessage(config.name) + : l10n.deleteLanguageConfirmMessage(config.name); + final confirmed = await showDialog( context: context, builder: (ctx) => AlertDialog( title: Text(l10n.deleteLanguageConfirmTitle), - content: Text(l10n.deleteLanguageConfirmMessage(config.name)), + content: Text(contentText), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(false), @@ -118,60 +171,49 @@ class _CodeCompletionManagementViewState ); if (confirmed == true && mounted) { + // 1. 删除前先优雅停用后台语言服务并清理活跃会话 + await LspManager.instance.stopSession(config.id); + if (!mounted) return; + + if (isInstalled && hasPackage) { + // 同步弹出卸载 dialog,与安装组件保持一致的同步交互体验 + final success = await DialogUtils.showSyncLoadingDialog( + context, + message: l10n.uninstallingComponent(config.name), + task: () => InternalEngineService.instance.uninstallPackage( + config.package, + serverCommand: config.serverCommand, + ), + ); + + if (!mounted) return; + + if (success == true) { + DialogUtils.showSuccessToast( + context, + l10n.uninstallComponentSuccess(config.name), + ); + } else { + // 卸载失败:给出明确提示并中止,避免误删本地配置导致状态脱节 + DialogUtils.showErrorToast( + context, + l10n.uninstallComponentFailed('apt purge non-zero or binary retained'), + ); + return; + } + } + + // 2. 卸载成功(或纯配置项无包):删除本地配置并清除防打扰白名单 await _lspService.deleteConfig(config.id); - setState(() { - _installedStatus.remove(config.id); - }); - } - } + MainView.clearPromptedLanguage(config.id); - Future _handleReset() async { - final l10n = AppLocalizations.of(context)!; - final confirmed = await showDialog( - context: context, - builder: (ctx) => AlertDialog( - title: Text(l10n.resetDefaultLanguages), - content: Text(l10n.resetDefaultLanguagesConfirm), - actions: [ - TextButton( - onPressed: () => Navigator.of(ctx).pop(false), - child: Text(l10n.cancel), - ), - FilledButton( - onPressed: () => Navigator.of(ctx).pop(true), - child: Text(l10n.confirm), - ), - ], - ), - ); - - if (confirmed == true && mounted) { - await _lspService.resetToDefaults(); - _checkCommandsStatus(); - } - } - - Future _handleInstallComponent(LspLanguageConfig config) async { - final l10n = AppLocalizations.of(context)!; - final success = await DialogUtils.showSyncLoadingDialog( - context, - message: l10n.installingComponent(config.apkPackage), - task: () => _engineService.installPackage(config.apkPackage), - ); - - if (!mounted) return; - - if (success) { - DialogUtils.showSuccessToast( - context, - l10n.installComponentSuccess(config.name), - ); - _checkCommandsStatus(); - } else { - DialogUtils.showErrorToast( - context, - l10n.installComponentFailed('apk add exit with non-zero'), - ); + if (mounted) { + setState(() { + _installedStatus.remove(config.id); + _expandedConfigIds.remove(config.id); + }); + _checkCommandsStatus(); + } } } @@ -184,11 +226,6 @@ class _CodeCompletionManagementViewState appBar: AppBar( title: Text(l10n.codeCompletionManagement), actions: [ - IconButton( - icon: const Icon(Icons.restore), - tooltip: l10n.resetDefaultLanguages, - onPressed: _handleReset, - ), IconButton( icon: const Icon(Icons.add), tooltip: l10n.addLanguageConfig, @@ -206,6 +243,8 @@ class _CodeCompletionManagementViewState child: ListView( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), children: [ + _buildCompletionSwitchesCard(context, theme, l10n), + const SizedBox(height: 12), _buildEngineStatusCard(context, theme, l10n), const SizedBox(height: 16), Padding( @@ -230,7 +269,10 @@ class _CodeCompletionManagementViewState ), ), const SizedBox(height: 6), - ...configs.map((cfg) => _buildLanguageItem(context, theme, l10n, cfg)), + if (configs.isEmpty) + _buildEmptyPlaceholder(context, theme, l10n) + else + ...configs.map((cfg) => _buildLanguageItem(context, theme, l10n, cfg)), ], ), ); @@ -239,6 +281,85 @@ class _CodeCompletionManagementViewState ); } + Widget _buildCompletionSwitchesCard( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + ) { + final settings = context.watch(); + if (settings == null) return const SizedBox.shrink(); + + final colorScheme = theme.colorScheme; + return Card( + elevation: 0, + color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.6)), + ), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Text( + l10n.completionSourceSection, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + color: colorScheme.primary, + ), + ), + ), + SwitchListTile( + secondary: const Icon(Icons.hub_outlined), + title: Text(l10n.lspCompletionTitle), + value: settings.enableLspCompletion, + onChanged: (val) => settings.setEnableLspCompletion(val), + ), + ], + ), + ), + ); + } + + Widget _buildEmptyPlaceholder( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + ) { + final colorScheme = theme.colorScheme; + return Container( + margin: const EdgeInsets.symmetric(vertical: 24), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerLowest, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: colorScheme.outlineVariant.withValues(alpha: 0.5), + ), + ), + child: Column( + children: [ + Icon( + Icons.code_off_rounded, + size: 48, + color: colorScheme.outline, + ), + const SizedBox(height: 12), + Text( + l10n.emptyLspLanguagesTitle, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.center, + ), + ], + ), + ); + } + Widget _buildEngineStatusCard( BuildContext context, ThemeData theme, @@ -247,20 +368,18 @@ class _CodeCompletionManagementViewState final isInstalled = _engineReady; final colorScheme = theme.colorScheme; - final (bgColor, borderColor, icon, statusText, subText) = isInstalled + final (bgColor, borderColor, icon, statusText) = isInstalled ? ( colorScheme.surfaceContainerHighest.withValues(alpha: 0.5), colorScheme.outlineVariant, Icon(Icons.check_circle_outline, color: colorScheme.primary, size: 28), l10n.internalEngineStatusReady, - 'Alpine Linux (musl libc)', ) : ( colorScheme.errorContainer.withValues(alpha: 0.3), colorScheme.error.withValues(alpha: 0.5), Icon(Icons.warning_amber_outlined, color: colorScheme.error, size: 28), l10n.internalEngineStatusNotReady, - l10n.internalEngineExtracting, ); return Card( @@ -277,25 +396,12 @@ class _CodeCompletionManagementViewState icon, const SizedBox(width: 14), Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - l10n.internalEngineTitle, - style: theme.textTheme.titleSmall?.copyWith( - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 2), - Text( - '$statusText • $subText', - style: theme.textTheme.bodySmall?.copyWith( - color: isInstalled - ? colorScheme.onSurfaceVariant - : colorScheme.error, - ), - ), - ], + child: Text( + statusText, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + color: isInstalled ? null : colorScheme.error, + ), ), ), if (!isInstalled) @@ -320,163 +426,192 @@ class _CodeCompletionManagementViewState AppLocalizations l10n, LspLanguageConfig config, ) { - final isInstalled = _installedStatus[config.id] ?? false; + final isExpanded = _expandedConfigIds.contains(config.id); + final busyAction = _busyConfigActions[config.id]; + final isBusy = busyAction != null; final colorScheme = theme.colorScheme; + // 状态描边:正在处理为品牌强调色(Primary);启用状态为绿色;未启用时保持普通灰色描边 + final BorderSide borderSide; + if (isBusy) { + borderSide = BorderSide(color: colorScheme.primary, width: 1.5); + } else if (config.enabled) { + borderSide = const BorderSide(color: Colors.green, width: 1.5); + } else { + borderSide = BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.5)); + } + return Card( elevation: 0, margin: const EdgeInsets.symmetric(vertical: 6), color: colorScheme.surfaceContainerLow, + clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( - side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.5)), + side: borderSide, borderRadius: BorderRadius.circular(12), ), - child: Padding( - padding: const EdgeInsets.all(12.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - CircleAvatar( - radius: 16, - backgroundColor: colorScheme.primaryContainer, - child: Text( - config.name.isNotEmpty ? config.name.substring(0, 1).toUpperCase() : '?', - style: TextStyle( - color: colorScheme.onPrimaryContainer, - fontWeight: FontWeight.bold, - fontSize: 14, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 头部:点击折叠/展开,仅显示头像、主标题和折叠指示图标 + InkWell( + onTap: () { + setState(() { + if (isExpanded) { + _expandedConfigIds.remove(config.id); + } else { + _expandedConfigIds.add(config.id); + } + }); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 12.0), + child: Row( + children: [ + CircleAvatar( + radius: 16, + backgroundColor: config.enabled + ? colorScheme.primaryContainer + : colorScheme.surfaceContainerHighest, + child: Text( + config.name.isNotEmpty ? config.name.substring(0, 1).toUpperCase() : '?', + style: TextStyle( + color: config.enabled + ? colorScheme.onPrimaryContainer + : colorScheme.onSurfaceVariant, + fontWeight: FontWeight.bold, + fontSize: 14, + ), ), ), - ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text( + const SizedBox(width: 12), + Expanded( + child: Row( + children: [ + Flexible( + child: Text( config.name, style: theme.textTheme.titleMedium?.copyWith( fontWeight: FontWeight.bold, + color: config.enabled ? null : colorScheme.onSurfaceVariant, + ), + overflow: TextOverflow.ellipsis, + ), + ), + if (isBusy) ...[ + const SizedBox(width: 8), + SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator( + strokeWidth: 2, + color: colorScheme.primary, + ), + ), + const SizedBox(width: 6), + Text( + busyAction == 'uninstall' + ? l10n.uninstallingStatus + : l10n.installingStatus, + style: theme.textTheme.bodySmall?.copyWith( + color: colorScheme.primary, + fontWeight: FontWeight.w500, ), ), - const SizedBox(width: 8), - _buildStatusBadge(theme, l10n, isInstalled), ], - ), - Text( - '${config.serverCommand} (${config.apkPackage}) • id: ${config.languageId}', - style: theme.textTheme.bodySmall?.copyWith( - color: colorScheme.onSurfaceVariant, + ], + ), + ), + Icon( + isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down, + color: colorScheme.onSurfaceVariant, + ), + ], + ), + ), + ), + + // 展开区域:显示文件扩展名标签与功能菜单选项 + if (isExpanded) ...[ + const Divider(height: 1), + Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 14, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 文件后缀标签 + Wrap( + spacing: 6, + runSpacing: 4, + children: config.fileExtensions.map( + (ext) => Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(6), ), + child: Text( + ext, + style: theme.textTheme.labelSmall?.copyWith( + fontFamily: 'JetBrains Mono', + color: colorScheme.onSurfaceVariant, + ), + ), + ), + ).toList(), + ), + const SizedBox(height: 12), + + // 功能菜单:启用/停用、安装组件(若未安装)、编辑、删除 + // 正在进行后台任务时,所有操作均被禁用以防止并发冲突 + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + // 启用 / 停用 + if (!isBusy) + OutlinedButton.icon( + style: OutlinedButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0), + ), + onPressed: () => _handleToggleEnabled(config), + icon: Icon( + config.enabled ? Icons.pause_circle_outline : Icons.play_circle_outline, + size: 16, + ), + label: Text(config.enabled ? l10n.disable : l10n.enable), + ), + + // 编辑配置(后台任务进行中禁用) + OutlinedButton.icon( + style: OutlinedButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0), + ), + onPressed: isBusy ? null : () => _handleEdit(config), + icon: const Icon(Icons.edit_outlined, size: 16), + label: Text(l10n.edit), + ), + + // 删除配置(后台任务进行中禁用) + OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: isBusy ? colorScheme.outline : colorScheme.error, + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0), + ), + onPressed: isBusy ? null : () => _handleDelete(config), + icon: const Icon(Icons.delete_outline, size: 16), + label: Text(l10n.delete), ), ], ), - ), - IconButton( - icon: const Icon(Icons.edit_outlined, size: 20), - tooltip: l10n.editLanguageConfig, - onPressed: () => _handleEdit(config), - ), - IconButton( - icon: const Icon(Icons.delete_outline, size: 20), - tooltip: l10n.delete, - onPressed: () => _handleDelete(config), - ), - ], - ), - const SizedBox(height: 8), - Wrap( - spacing: 6, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - ...config.fileExtensions.map( - (ext) => Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(6), - ), - child: Text( - ext, - style: theme.textTheme.labelSmall?.copyWith( - fontFamily: 'JetBrains Mono', - color: colorScheme.onSurfaceVariant, - ), - ), - ), - ), - if (!isInstalled) - Padding( - padding: const EdgeInsets.only(left: 4), - child: InkWell( - borderRadius: BorderRadius.circular(6), - onTap: () => _handleInstallComponent(config), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - decoration: BoxDecoration( - color: colorScheme.primary.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(6), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.download, size: 14, color: colorScheme.primary), - const SizedBox(width: 4), - Text( - l10n.installComponent, - style: theme.textTheme.labelSmall?.copyWith( - color: colorScheme.primary, - fontWeight: FontWeight.bold, - ), - ), - ], - ), - ), - ), - ), - ], + ], + ), ), ], - ), - ), - ); - } - - Widget _buildStatusBadge( - ThemeData theme, - AppLocalizations l10n, - bool isInstalled, - ) { - final (bgColor, fgColor, text) = isInstalled - ? ( - Colors.green.withValues(alpha: 0.15), - Colors.green.shade700, - l10n.installedStatus, - ) - : ( - Colors.grey.withValues(alpha: 0.2), - Colors.grey.shade700, - l10n.notInstalledStatus, - ); - - return Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), - decoration: BoxDecoration( - color: bgColor, - borderRadius: BorderRadius.circular(4), - ), - child: Text( - text, - style: TextStyle( - color: fgColor, - fontSize: 10, - fontWeight: FontWeight.bold, - ), + ], ), ); } diff --git a/lib/views/distro_management_view.dart b/lib/views/distro_management_view.dart deleted file mode 100644 index 3d3b869..0000000 --- a/lib/views/distro_management_view.dart +++ /dev/null @@ -1,433 +0,0 @@ -import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/models/distro_manifest.dart'; -import 'package:code_editor/providers/settings_provider.dart'; -import 'package:code_editor/services/distro_download_manager.dart'; -import 'package:code_editor/utils/dialog_utils.dart'; -import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; - -/// 独立的系统管理与发行版包选择视图页面 -/// -/// 功能: -/// 1. AppBar 包含返回键与标题“系统管理”(遵循 l10n 国际化)。 -/// 2. 列举当前架构支持的系统安装包(左侧图标、两行名称与版本,无高亮选框,无“内置”字样)。 -/// 3. 安装包项分为两种状态: -/// - 已就绪 (zip 存在): -/// * 不显示“已安装”文本,不显示“安装”按键; -/// * Ubuntu 和 Alpine 为内置包,受保护右侧不显示删除按键; -/// * 在线下载的系统包右侧显示红色删除按钮(二次确认后居中同步转圈删除离线包); -/// * 用户直接点击该项卡片,即代表选中该安装包,返回上一页进行解压创建系统。 -/// - 未下载 / 下载中: -/// * 未下载显示“下载”按键; -/// * 下载中显示百分比进度条与取消按键(取消后清空临时文件)。 -class DistroManagementView extends StatefulWidget { - const DistroManagementView({super.key}); - - @override - State createState() => _DistroManagementViewState(); -} - -class _DistroManagementViewState extends State { - final DistroDownloadManager _downloadManager = DistroDownloadManager(); - final Set _downloadedPackageIds = {}; - - @override - void initState() { - super.initState(); - _downloadManager.addListener(_onDownloadProgressChanged); - _checkDownloadedPackages(); - } - - @override - void dispose() { - _downloadManager.removeListener(_onDownloadProgressChanged); - super.dispose(); - } - - void _onDownloadProgressChanged() { - if (mounted) { - for (final entry in _downloadManager.allProgress.entries) { - if (entry.value.state == DistroDownloadState.completed) { - _downloadedPackageIds.add(entry.key); - } - } - setState(() {}); - } - } - - Future _checkDownloadedPackages() async { - final distros = DistroRepository.currentArchDistros; - final Set downloaded = {}; - for (final d in distros) { - if (!d.isBuiltin && d.currentPackageSource != null) { - if (await _downloadManager.isPackageDownloaded(d.id, d.currentPackageSource)) { - downloaded.add(d.id); - } - } - } - for (final entry in _downloadManager.allProgress.entries) { - if (entry.value.state == DistroDownloadState.completed) { - downloaded.add(entry.key); - } - } - if (mounted) { - setState(() { - _downloadedPackageIds.clear(); - _downloadedPackageIds.addAll(downloaded); - }); - } - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final l10n = AppLocalizations.of(context)!; - - // 当前架构支持的发行版清单 - final distros = DistroRepository.currentArchDistros; - - return Scaffold( - appBar: AppBar( - title: Text( - l10n.distroManagementTitle, - style: const TextStyle(fontWeight: FontWeight.bold), - ), - leading: IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () => Navigator.of(context).pop(), - ), - ), - body: ListView.separated( - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0), - itemCount: distros.length, - separatorBuilder: (_, _) => const SizedBox(height: 10), - itemBuilder: (context, index) { - final item = distros[index]; - final downloadProgress = _downloadManager.getProgress(item.id); - final isDownloaded = _downloadedPackageIds.contains(item.id) || - downloadProgress?.state == DistroDownloadState.completed; - final isReady = item.isBuiltin || isDownloaded; - final isDownloading = downloadProgress?.state == DistroDownloadState.downloading; - - return _buildDistroCard( - context: context, - theme: theme, - l10n: l10n, - item: item, - isReady: isReady, - isDownloading: isDownloading, - downloadProgress: downloadProgress, - ); - }, - ), - ); - } - - Widget _buildDistroCard({ - required BuildContext context, - required ThemeData theme, - required AppLocalizations l10n, - required DistroManifestItem item, - required bool isReady, - required bool isDownloading, - required DistroDownloadProgress? downloadProgress, - }) { - return Card( - elevation: 0, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12.0), - side: BorderSide( - color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4), - width: 1.0, - ), - ), - color: theme.colorScheme.surface, - child: InkWell( - borderRadius: BorderRadius.circular(12.0), - onTap: isReady - ? () { - // 点击已就绪的安装包 item:代表选择该 zip,返回上一页解压创建系统 - Navigator.of(context).pop(item); - } - : null, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - // 1. 系统左侧品牌图标 - Container( - width: 44, - height: 44, - padding: const EdgeInsets.all(6.0), - decoration: BoxDecoration( - color: item.brandColor.withValues(alpha: 0.12), - borderRadius: BorderRadius.circular(10.0), - border: Border.all( - color: item.brandColor.withValues(alpha: 0.3), - width: 1.0, - ), - ), - child: item.assetIconPath != null - ? Image.asset( - item.assetIconPath!, - fit: BoxFit.contain, - errorBuilder: (_, _, _) => Icon( - item.iconData, - color: item.brandColor, - size: 26, - ), - ) - : Icon( - item.iconData, - color: item.brandColor, - size: 26, - ), - ), - const SizedBox(width: 14), - - // 2. 中间两行文本 (系统名与推荐标签 + 版本) - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Flexible( - child: Text( - item.name, - style: TextStyle( - fontSize: 16.0, - fontWeight: FontWeight.bold, - color: theme.colorScheme.onSurface, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - if (item.isRecommended) ...[ - const SizedBox(width: 8), - Container( - padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 2.0), - decoration: BoxDecoration( - color: Colors.amber.shade700.withValues(alpha: 0.15), - borderRadius: BorderRadius.circular(6.0), - border: Border.all( - color: Colors.amber.shade800.withValues(alpha: 0.4), - width: 0.8, - ), - ), - child: Text( - l10n.recommendedTag, - style: TextStyle( - fontSize: 10.5, - fontWeight: FontWeight.bold, - color: Colors.amber.shade800, - ), - ), - ), - ], - ], - ), - const SizedBox(height: 3), - Text( - item.version, - style: TextStyle( - fontSize: 12.0, - color: theme.colorScheme.onSurfaceVariant, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ], - ), - ), - - // 3. 右侧状态与操作按钮 - const SizedBox(width: 10), - _buildTrailingAction( - context: context, - theme: theme, - l10n: l10n, - item: item, - isReady: isReady, - isDownloading: isDownloading, - downloadProgress: downloadProgress, - ), - ], - ), - - // 若处于下载中,展示下载进度条与百分比 - if (isDownloading && downloadProgress != null) ...[ - const SizedBox(height: 12), - Row( - children: [ - Expanded( - child: ClipRRect( - borderRadius: BorderRadius.circular(4.0), - child: LinearProgressIndicator( - value: downloadProgress.totalBytes > 0 - ? downloadProgress.progress - : null, - minHeight: 5, - ), - ), - ), - const SizedBox(width: 10), - Text( - '${(downloadProgress.progress * 100).toStringAsFixed(0)}%', - style: TextStyle( - fontSize: 11.5, - fontWeight: FontWeight.w600, - color: theme.colorScheme.primary, - ), - ), - ], - ), - ], - ], - ), - ), - ), - ); - } - - Widget _buildTrailingAction({ - required BuildContext context, - required ThemeData theme, - required AppLocalizations l10n, - required DistroManifestItem item, - required bool isReady, - required bool isDownloading, - required DistroDownloadProgress? downloadProgress, - }) { - if (isReady) { - // 对于已就绪 (已安装) 的 item (zip 文件): - // 不显示“已安装”文本,不显示“安装”按键。 - // 对于内置 ubuntu 和 alpine,受保护无按键 (SizedBox.shrink); - // 其他在线下载完成的包,右侧直接显示红色删除按钮 - if (item.isBuiltin) { - return const SizedBox.shrink(); - } - - return IconButton( - icon: const Icon(Icons.delete_outline, color: Colors.redAccent, size: 22), - tooltip: l10n.deletePackageTooltip, - onPressed: () => _handleDeleteDownloadedPackage(item), - ); - } - - if (isDownloading) { - // 下载中状态:显示取消下载按钮 - return IconButton( - icon: const Icon(Icons.cancel_outlined, color: Colors.grey, size: 22), - tooltip: l10n.cancelDownloadAction, - onPressed: () => _handleCancelDownload(item), - ); - } - - // 未就绪/未下载状态:显示下载按钮 - return FilledButton.tonalIcon( - icon: const Icon(Icons.download_outlined, size: 18), - label: Text(l10n.downloadAction), - style: FilledButton.styleFrom( - padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), - textStyle: const TextStyle(fontSize: 13.0), - ), - onPressed: () => _handleStartDownload(item), - ); - } - - /// 启动在线下载 - Future _handleStartDownload(DistroManifestItem item) async { - final url = item.currentPackageSource; - final l10n = AppLocalizations.of(context)!; - final settings = context.read(); - final mirror = settings.downloadMirror; - if (url == null || url.isEmpty) return; - - // 前置资源检测:若已下载完备,立即更新状态并拒绝重复下载 - if (await _downloadManager.isPackageDownloaded(item.id, url)) { - if (mounted) { - setState(() { - _downloadedPackageIds.add(item.id); - }); - } - return; - } - - final targetFile = await _downloadManager.startDownload( - distroId: item.id, - downloadUrl: url, - mirror: mirror, - manifestItem: item, - ); - - if (targetFile != null && mounted) { - setState(() { - _downloadedPackageIds.add(item.id); - }); - } else if (mounted) { - final progress = _downloadManager.getProgress(item.id); - if (progress?.state == DistroDownloadState.failed) { - DialogUtils.showErrorToast( - context, - l10n.downloadFailed(progress?.errorMessage ?? ''), - ); - } - } - } - - /// 取消下载确认弹窗 - Future _handleCancelDownload(DistroManifestItem item) async { - final l10n = AppLocalizations.of(context)!; - final confirmed = await DialogUtils.showConfirmDialog( - context, - title: l10n.cancelDownloadConfirmTitle, - message: l10n.cancelDownloadConfirmMessage, - ); - - if (confirmed && mounted) { - await _downloadManager.cancelDownload(item.id); - } - } - - /// 删除已下载的系统安装包(弹确认 Dialog -> 居中转圈同步 Dialog -> 完成) - Future _handleDeleteDownloadedPackage(DistroManifestItem item) async { - final l10n = AppLocalizations.of(context)!; - final confirmed = await DialogUtils.showDestructiveConfirmDialog( - context, - title: l10n.deletePackageConfirmTitle, - message: l10n.deletePackageConfirmMessage(item.name), - confirmText: l10n.permanentDelete, - ); - - if (!confirmed || !mounted) return; - - // 弹出居中转圈的同步等待弹窗,直至删除完毕 - await DialogUtils.showSyncLoadingDialog( - context, - message: l10n.deletingPackageProgress, - task: () async { - try { - await _downloadManager.deletePackage(item.id, item.currentPackageSource); - if (mounted) { - setState(() { - _downloadedPackageIds.remove(item.id); - }); - } - } catch (e) { - if (mounted) { - DialogUtils.showErrorToast(context, e.toString()); - } - } - }, - ); - - if (mounted) { - DialogUtils.showToast(context, l10n.deletePackageSuccess(item.name)); - } - } -} diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index d52359d..e18b77f 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:io'; import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/run_task.dart'; import 'package:code_editor/providers/distro_provider.dart'; @@ -18,12 +19,15 @@ import 'package:code_editor/widgets/code_editor_tab_bar.dart'; import 'package:code_editor/widgets/code_editor_widget.dart'; import 'package:code_editor/views/run_task_edit_view.dart'; import 'package:code_editor/providers/notice_center.dart'; -import 'package:code_editor/widgets/distro_selector_dialog.dart'; +import 'package:code_editor/models/distro_manifest.dart'; +import 'package:code_editor/widgets/distro_extract_dialog.dart'; import 'package:code_editor/widgets/notice_host.dart'; import 'package:code_editor/widgets/probe_cancel_guard.dart'; import 'package:code_editor/widgets/run_tasks_dialog.dart'; import 'package:code_editor/models/lsp_language_config.dart'; +import 'package:code_editor/services/file_service.dart'; import 'package:code_editor/services/internal_engine_service.dart'; +import 'package:code_editor/services/lsp/lsp_manager.dart'; import 'package:code_editor/services/lsp_config_service.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -33,6 +37,11 @@ import 'package:provider/provider.dart'; class MainView extends StatefulWidget { const MainView({super.key}); + /// 清除指定语言或全部语言的防打扰提示记录(卸载组件后恢复提示资格并重置当前文件检查) + static void clearPromptedLanguage(String? languageId) { + _MainViewState.clearPromptedLanguage(languageId); + } + @override State createState() => _MainViewState(); } @@ -43,12 +52,23 @@ class _MainViewState extends State { /// 最近一次已触发探测的 (工程, 系统) 组合,用于去重与"系统就绪后补探测" String? _lastProbeKey; - String? _lastActiveFile; + static String? _globalLastActiveFile; static final Set _promptedLspLanguages = {}; + /// 清除指定语言或全部语言的防打扰提示记录(卸载组件后恢复提示资格并重置当前文件检查) + static void clearPromptedLanguage(String? languageId) { + if (languageId == null) { + _promptedLspLanguages.clear(); + } else { + _promptedLspLanguages.remove(languageId); + } + _globalLastActiveFile = null; + } + @override void initState() { super.initState(); + LspConfigService.instance.addListener(_handleLspConfigChanged); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { InternalEngineService.instance.ensureEngineReady(context); @@ -57,25 +77,101 @@ class _MainViewState extends State { }); } - void _checkLspForFile(String filePath) async { - final ext = p.extension(filePath); - if (ext.isEmpty) return; - await LspConfigService.instance.loadConfigs(); - final config = LspConfigService.instance.findByExtension(ext); - if (config == null) return; + @override + void dispose() { + LspConfigService.instance.removeListener(_handleLspConfigChanged); + super.dispose(); + } - if (!await InternalEngineService.instance.isEngineInstalled()) return; + void _handleLspConfigChanged() { + if (!mounted) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _syncLspForOpenTabs(); + }); + } - final isInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand); - if (!isInstalled && mounted) { - if (!_promptedLspLanguages.contains(config.id)) { - _promptedLspLanguages.add(config.id); - _promptInstallLspComponent(config); + Future _syncLspForOpenTabs({String? preferredFilePath}) async { + if (!mounted) return; + final tabProvider = _getTabProvider(context); + final projectProvider = _getProjectProvider(context); + final workspaceRoot = projectProvider.rootPath; + + final openTabs = tabProvider.openTabs; + final currentPath = preferredFilePath ?? tabProvider.currentFilePath; + + final filesToSync = {}; + for (final tab in openTabs) { + filesToSync[tab.path] = tab.content; + } + if (currentPath != null && !filesToSync.containsKey(currentPath)) { + filesToSync[currentPath] = ''; + } + + for (final entry in filesToSync.entries) { + final path = entry.key; + final ext = p.extension(path); + if (ext.isEmpty) continue; + + final config = LspConfigService.instance.findByExtension(ext); + if (config == null || !config.enabled) continue; + + final isCmdInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand); + if (!isCmdInstalled) continue; + + final existingSession = LspManager.instance.getExistingSession(path); + if (existingSession == null || !existingSession.isInitialized) { + String content = entry.value; + if (content.isEmpty && File(path).existsSync()) { + try { + content = await FileService.instance.readFileContent(path); + } catch (_) {} + } + await LspManager.instance.onFileOpened( + path, + content, + workspaceRoot: workspaceRoot, + ); } } } - Future _promptInstallLspComponent(LspLanguageConfig config) async { + void _checkLspForFile(String filePath) async { + final ext = p.extension(filePath); + if (ext.isEmpty) return; + await LspConfigService.instance.loadConfigs(); + + // 1. 先检查已安装配置中是否有匹配此后缀的组件 + final existing = LspConfigService.instance.findByExtension(ext); + if (existing != null) return; + + final engineInstalled = await InternalEngineService.instance.isEngineInstalled(); + if (!engineInstalled) return; + + // 2. 未在已安装配置中,查找代码内置语言预设模版 + final builtin = LspLanguageConfig.findBuiltinByExtension(ext); + if (builtin == null) return; + + final isInstalled = await InternalEngineService.instance.isCommandInstalled(builtin.serverCommand); + if (isInstalled) { + // 若底层环境意外已存在该命令(例如系统自带或此前安装过),直接补充入库 + await LspConfigService.instance.updateConfig(builtin); + if (mounted) { + await _syncLspForOpenTabs(preferredFilePath: filePath); + } + return; + } + + if (mounted) { + final alreadyPrompted = _promptedLspLanguages.contains(builtin.id); + if (!alreadyPrompted) { + _promptedLspLanguages.add(builtin.id); + _promptInstallLspComponent(builtin, targetFilePath: filePath); + } + } + } + + Future _promptInstallLspComponent(LspLanguageConfig config, {String? targetFilePath}) async { final l10n = AppLocalizations.of(context); if (l10n == null || !mounted) return; @@ -83,7 +179,7 @@ class _MainViewState extends State { context: context, builder: (ctx) => AlertDialog( title: Text(l10n.lspPackageMissingTitle(config.name)), - content: Text(l10n.lspPackageMissingMessage(config.apkPackage, config.serverCommand)), + content: Text(l10n.lspPackageMissingMessage), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(false), @@ -100,15 +196,23 @@ class _MainViewState extends State { if (install == true && mounted) { final success = await DialogUtils.showSyncLoadingDialog( context, - message: l10n.installingComponent(config.apkPackage), - task: () => InternalEngineService.instance.installPackage(config.apkPackage), + message: l10n.installingComponent(config.package), + task: () => InternalEngineService.instance.installPackage(config.package), ); - if (!mounted) return; - if (success) { - DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(config.name)); - } else { - DialogUtils.showErrorToast(context, l10n.installComponentFailed('apk add exit with non-zero')); + if (mounted) { + if (success) { + await LspConfigService.instance.updateConfig(config); + if (mounted) { + DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(config.name)); + await _syncLspForOpenTabs(preferredFilePath: targetFilePath); + } + } else { + DialogUtils.showErrorToast( + context, + l10n.installComponentFailed('apt exit non-zero'), + ); + } } } } @@ -182,7 +286,7 @@ class _MainViewState extends State { } } - /// 提示用户缺失 Linux 执行环境并引导前往系统管理进行配置 + /// 提示用户缺失 Linux 执行环境并引导解压安装 Ubuntu void _showMissingDistroDialog(BuildContext context, String? targetDistro) { final l10n = AppLocalizations.of(context)!; showDialog( @@ -212,12 +316,23 @@ class _MainViewState extends State { child: Text(l10n.cancel), ), ElevatedButton.icon( - onPressed: () { + onPressed: () async { Navigator.of(ctx).pop(); - DistroSelectorDialog.show(context); + final distroProvider = _getDistroProvider(context); + if (distroProvider != null) { + await DistroExtractDialog.show( + context: context, + systemName: DistroRepository.defaultSystemName, + task: (onProgress, isCancelled) => distroProvider.importBuiltinUbuntu( + systemName: DistroRepository.defaultSystemName, + onProgress: onProgress, + isCancelled: isCancelled, + ), + ); + } }, - icon: const Icon(Icons.dns_outlined, size: 18), - label: Text(l10n.systemManagement), + icon: const Icon(Icons.system_update_alt, size: 18), + label: Text(l10n.installNow), ), ], ), @@ -230,24 +345,14 @@ class _MainViewState extends State { final distroProvider = _getDistroProvider(context); final distroManager = DistroManager(); try { - var targetDistro = distroProvider?.selectedSystem; - - if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) { - if (distroProvider != null) { + final isInstalled = await distroManager.isSystemInstalled(DistroRepository.defaultSystemName); + if (isInstalled) { + if (distroProvider != null && distroProvider.selectedSystem == null) { await distroProvider.refreshSystems(); - targetDistro = distroProvider.selectedSystem; - } - if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) { - final physicalSystems = await distroManager.listInstalledSystems(); - if (physicalSystems.isNotEmpty) { - targetDistro = physicalSystems.first; - await distroProvider?.selectSystem(targetDistro); - } } + return DistroRepository.defaultSystemName; } - - final ok = targetDistro != null && await distroManager.isSystemInstalled(targetDistro); - return ok ? targetDistro : null; + return null; } catch (e) { debugPrint('[MainView] 系统可用性解析失败: $e'); return null; @@ -325,6 +430,10 @@ class _MainViewState extends State { final runProvider = _getRunProvider(context); if (runProvider == null) return; + // 确保针对当前活动文件刷新单文件任务(支持当前文件单任务联动) + final currentFilePath = _getTabProvider(context).currentFilePath; + runProvider.refreshSingleFileTask(currentFilePath: currentFilePath); + // 优先: 最近运行的任务(若已持久化并存在且确实属于当前打开的工程) if (runProvider.currentProjectRoot == rootPath && runProvider.lastRunTask != null) { _executeRunTask(context, runProvider.lastRunTask!); @@ -445,7 +554,7 @@ class _MainViewState extends State { DialogUtils.showSuccessToast( context, - l10n.detectCompletedMessage(runProvider.detectedTasks.length), + l10n.detectCompletedMessage(runProvider.allTasks.length), ); } @@ -481,11 +590,12 @@ class _MainViewState extends State { final systemName = _getDistroProvider(context, listen: true)?.selectedSystem; final probeKey = (rootPath == null || systemName == null) ? null : '$rootPath|$systemName'; - if (currentFile != null && currentFile != _lastActiveFile) { - _lastActiveFile = currentFile; + if (currentFile != null && currentFile != _globalLastActiveFile) { + _globalLastActiveFile = currentFile; WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { _checkLspForFile(currentFile); + runProvider?.refreshSingleFileTask(currentFilePath: currentFile); } }); } @@ -515,7 +625,7 @@ class _MainViewState extends State { if (l10n != null && runProvider != null) { DialogUtils.showSuccessToast( this.context, - l10n.detectCompletedMessage(runProvider.detectedTasks.length), + l10n.detectCompletedMessage(runProvider.allTasks.length), ); } }); diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index 58abbd8..a27fd70 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -1,6 +1,5 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/app_font.dart'; -import 'package:code_editor/models/distro_manifest.dart'; import 'package:code_editor/models/editor_theme.dart'; import 'package:code_editor/models/virtual_keyboard_config.dart'; import 'package:code_editor/providers/settings_provider.dart'; @@ -84,15 +83,7 @@ class SettingsView extends StatelessWidget { const Divider(height: 32, indent: 16, endIndent: 16), // ============================== - // 5. 下载分组 (Download) - // ============================== - _buildSectionHeader(context, l10n.downloadSection), - _buildDownloadSourceTile(context, provider, l10n), - - const Divider(height: 32, indent: 16, endIndent: 16), - - // ============================== - // 6. 语言分组 (Language) + // 5. 语言分组 (Language) // ============================== _buildSectionHeader(context, l10n.languageSection), _buildLanguageTile(context, provider, l10n), @@ -1139,98 +1130,4 @@ class SettingsView extends StatelessWidget { }, ); } - - /// 下载:下载源设置条目 - Widget _buildDownloadSourceTile( - BuildContext context, - SettingsProvider provider, - AppLocalizations l10n, - ) { - final theme = Theme.of(context); - final currentMirrorId = provider.downloadMirrorId; - return ListTile( - leading: Icon(Icons.cloud_download_outlined, color: theme.colorScheme.primary), - title: Text(l10n.downloadSource), - subtitle: Text(l10n.mirrorName(currentMirrorId)), - trailing: const Icon(Icons.chevron_right), - onTap: () { - _showDownloadSourceSelector(context, provider, l10n); - }, - ); - } - - /// 显示下载源底部选择器(与字体选择器一致的弹窗体验) - void _showDownloadSourceSelector( - BuildContext context, - SettingsProvider provider, - AppLocalizations l10n, - ) { - showModalBottomSheet( - context: context, - isScrollControlled: true, - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.vertical(top: Radius.circular(20)), - ), - builder: (sheetContext) { - final theme = Theme.of(context); - final mirrors = DistroRepository.availableMirrors; - return SafeArea( - child: ConstrainedBox( - constraints: BoxConstraints( - maxHeight: MediaQuery.of(sheetContext).size.height * 0.65, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.all(16.0), - child: Text( - l10n.selectDownloadSource, - style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), - ), - ), - const Divider(height: 1), - Expanded( - child: ListView.builder( - itemCount: mirrors.length, - itemBuilder: (context, index) { - final item = mirrors[index]; - final isSelected = item.id == provider.downloadMirrorId; - return ListTile( - leading: Icon( - Icons.dns_outlined, - color: isSelected ? theme.colorScheme.primary : null, - ), - title: Text( - l10n.mirrorName(item.id), - style: TextStyle( - fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - color: isSelected ? theme.colorScheme.primary : null, - ), - ), - subtitle: Text( - item.baseUrl, - style: TextStyle( - fontSize: 12.0, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - trailing: isSelected - ? Icon(Icons.check, color: theme.colorScheme.primary) - : null, - onTap: () { - provider.setDownloadMirrorId(item.id); - Navigator.of(sheetContext).pop(); - }, - ); - }, - ), - ), - ], - ), - ), - ); - }, - ); - } } diff --git a/lib/widgets/code_autocomplete_view.dart b/lib/widgets/code_autocomplete_view.dart new file mode 100644 index 0000000..900211a --- /dev/null +++ b/lib/widgets/code_autocomplete_view.dart @@ -0,0 +1,252 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; +import 'package:re_editor/re_editor.dart'; +import '../services/code_completion/smart_prompts_builder.dart'; + +/// 移动端友好的现代化代码智能补全悬浮面板 +class CodeAutocompleteView extends StatefulWidget implements PreferredSizeWidget { + const CodeAutocompleteView({ + super.key, + required this.notifier, + required this.onSelected, + this.width = 270.0, + this.height = 196.0, + }); + + final ValueNotifier notifier; + final ValueChanged onSelected; + final double width; + final double height; + + static const double itemHeight = 36.0; + static const double verticalPadding = 8.0; + static const double borderWidth = 2.0; + + @override + Size get preferredSize { + final prompts = notifier.value.prompts; + if (prompts.isEmpty) return Size(width, 0.0); + final contentHeight = prompts.length * itemHeight + verticalPadding + borderWidth; + final effectiveHeight = contentHeight.clamp(itemHeight + verticalPadding + borderWidth, height); + return Size(width, effectiveHeight); + } + + @override + State createState() => _CodeAutocompleteViewState(); +} + +class _CodeAutocompleteViewState extends State { + final ScrollController _scrollController = ScrollController(); + + @override + void initState() { + super.initState(); + widget.notifier.addListener(_handleValueChanged); + } + + @override + void didUpdateWidget(covariant CodeAutocompleteView oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.notifier != widget.notifier) { + oldWidget.notifier.removeListener(_handleValueChanged); + widget.notifier.addListener(_handleValueChanged); + } + } + + @override + void dispose() { + widget.notifier.removeListener(_handleValueChanged); + _scrollController.dispose(); + super.dispose(); + } + + void _handleValueChanged() { + if (!mounted) return; + final value = widget.notifier.value; + final targetOffset = value.index * CodeAutocompleteView.itemHeight; + if (_scrollController.hasClients && _scrollController.position.hasViewportDimension) { + final currentOffset = _scrollController.offset; + final viewportDimension = _scrollController.position.viewportDimension; + final maxView = currentOffset + viewportDimension - CodeAutocompleteView.itemHeight - CodeAutocompleteView.verticalPadding; + if (targetOffset < currentOffset) { + _scrollController.jumpTo(targetOffset); + } else if (targetOffset > maxView) { + _scrollController.jumpTo(math.max(0.0, targetOffset - viewportDimension + CodeAutocompleteView.itemHeight + CodeAutocompleteView.verticalPadding)); + } + } + setState(() {}); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final value = widget.notifier.value; + final prompts = value.prompts; + + final bgColor = isDark ? const Color(0xFF1E1E2E) : Colors.white; + final borderColor = isDark ? Colors.white12 : Colors.black12; + + return Container( + width: widget.width, + constraints: BoxConstraints(maxHeight: widget.height), + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(10.0), + border: Border.all(color: borderColor, width: 1.0), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: isDark ? 0.45 : 0.15), + blurRadius: 14.0, + offset: const Offset(0, 4), + ), + ], + ), + clipBehavior: Clip.antiAlias, + child: ListView.builder( + controller: _scrollController, + physics: const ClampingScrollPhysics(), + padding: const EdgeInsets.symmetric(vertical: 4.0), + itemCount: prompts.length, + itemExtent: CodeAutocompleteView.itemHeight, + itemBuilder: (context, index) { + final prompt = prompts[index]; + final isSelected = index == value.index; + return _buildPromptItem(context, prompt, isSelected, index, theme, isDark); + }, + ), + ); + } + + Widget _buildPromptItem( + BuildContext context, + CodePrompt prompt, + bool isSelected, + int index, + ThemeData theme, + bool isDark, + ) { + final smart = prompt is SmartPrompt ? prompt : null; + final kind = smart?.kind ?? SmartPromptKind.word; + final typeText = smart?.type ?? ''; + final matchedIndices = smart?.matchedIndices ?? const []; + + final highlightBg = theme.colorScheme.primary.withValues(alpha: isDark ? 0.25 : 0.15); + final defaultBg = Colors.transparent; + + return InkWell( + onTap: () { + widget.notifier.value = widget.notifier.value.copyWith(index: index); + widget.onSelected(widget.notifier.value.autocomplete); + }, + child: Container( + height: CodeAutocompleteView.itemHeight, + color: isSelected ? highlightBg : defaultBg, + padding: const EdgeInsets.symmetric(horizontal: 10.0), + child: Row( + children: [ + _buildKindIcon(kind, theme), + const SizedBox(width: 8.0), + Expanded( + child: _buildHighlightedText(prompt.word, matchedIndices, theme, isSelected), + ), + if (typeText.isNotEmpty) + Text( + typeText, + style: TextStyle( + fontSize: 11.0, + color: isDark ? Colors.white38 : Colors.black38, + fontFamily: 'monospace', + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ); + } + + Widget _buildKindIcon(SmartPromptKind kind, ThemeData theme) { + IconData icon; + Color color; + + switch (kind) { + case SmartPromptKind.keyword: + icon = Icons.vpn_key_rounded; + color = const Color(0xFFC586C0); // 类似 VS Code 关键字粉紫色 + break; + case SmartPromptKind.function: + icon = Icons.functions_rounded; + color = const Color(0xFFDCDCAA); // 函数黄色 + break; + case SmartPromptKind.field: + icon = Icons.data_object_rounded; + color = const Color(0xFF9CDCFE); // 变量浅蓝色 + break; + case SmartPromptKind.type: + icon = Icons.category_rounded; + color = const Color(0xFF4EC9B0); // 类型青绿色 + break; + case SmartPromptKind.constant: + icon = Icons.tag_rounded; + color = const Color(0xFF4FC1FF); // 常量亮天蓝色 + break; + case SmartPromptKind.word: + icon = Icons.text_snippet_outlined; + color = Colors.grey; + break; + } + + return Icon(icon, size: 15.0, color: color); + } + + Widget _buildHighlightedText( + String word, + List matchedIndices, + ThemeData theme, + bool isSelected, + ) { + if (matchedIndices.isEmpty) { + return Text( + word, + style: TextStyle( + fontSize: 13.0, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + fontFamily: 'monospace', + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + } + + final matchedSet = matchedIndices.toSet(); + final List spans = []; + + for (int i = 0; i < word.length; i++) { + final isHit = matchedSet.contains(i); + spans.add( + TextSpan( + text: word[i], + style: TextStyle( + color: isHit ? theme.colorScheme.primary : null, + fontWeight: isHit ? FontWeight.bold : (isSelected ? FontWeight.w600 : FontWeight.normal), + ), + ), + ); + } + + return RichText( + text: TextSpan( + style: TextStyle( + fontSize: 13.0, + color: theme.textTheme.bodyMedium?.color, + fontFamily: 'monospace', + ), + children: spans, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + } +} diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart index 0493f43..3f8b5cc 100644 --- a/lib/widgets/code_editor_app_bar.dart +++ b/lib/widgets/code_editor_app_bar.dart @@ -118,7 +118,7 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { visualDensity: VisualDensity.compact, icon: const Icon(Icons.play_arrow), tooltip: l10n.run, - onPressed: onRun ?? () {}, + onPressed: (isDetecting || onRun == null) ? null : onRun, ), ), Focus( @@ -319,7 +319,9 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi icon: Icons.playlist_play, title: l10n.runTasks, iconColor: onSurfaceColor, + enabled: !widget.isDetecting, onTap: () { + if (widget.isDetecting) return; _closeMenu(onClosed: widget.onRunTasks); }, ), diff --git a/lib/widgets/code_editor_menu.dart b/lib/widgets/code_editor_menu.dart index 1dd53d3..0c94ec8 100644 --- a/lib/widgets/code_editor_menu.dart +++ b/lib/widgets/code_editor_menu.dart @@ -1,6 +1,9 @@ import 'dart:math'; import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/services/lsp/lsp_diagnostics_store.dart'; +import 'package:code_editor/services/lsp/lsp_protocol.dart'; +import 'package:code_editor/widgets/lsp_quick_fix_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:re_editor/re_editor.dart'; @@ -150,6 +153,7 @@ class _MobileSelectionToolbarWidget extends StatefulWidget { final VoidCallback onDismiss; final FocusNode? focusNode; final Rect? renderRect; + final String? Function()? filePathGetter; const _MobileSelectionToolbarWidget({ required this.anchors, @@ -157,6 +161,7 @@ class _MobileSelectionToolbarWidget extends StatefulWidget { required this.onDismiss, this.focusNode, this.renderRect, + this.filePathGetter, }); @override @@ -197,6 +202,12 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi final theme = Theme.of(context); + final filePath = widget.filePathGetter?.call(); + final line = widget.controller.selection.baseIndex; + final diags = (filePath != null && line >= 0) + ? LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, line) + : const []; + final toolbarContent = Material( elevation: 6.0, shadowColor: Colors.black45, @@ -213,6 +224,23 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi child: Row( mainAxisSize: MainAxisSize.min, children: [ + if (diags.isNotEmpty && filePath != null) ...[ + _buildItem( + context, + label: '修复 💡', + onTap: () { + widget.onDismiss(); + LspQuickFixDialog.show( + context, + filePath: filePath, + lineIndex: line, + diagnostics: diags, + controller: widget.controller, + ); + }, + ), + _buildDivider(context), + ], if (hasSelection) ...[ _buildItem( context, @@ -311,6 +339,7 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi /// 自定义代码编辑器选区与右键菜单控制器 class CodeEditorToolbarController implements SelectionToolbarController { final FocusNode? focusNode; + final String? Function()? filePathGetter; late final SelectionToolbarController _mobileController; CodeLineEditingController? _lastController; @@ -319,7 +348,7 @@ class CodeEditorToolbarController implements SelectionToolbarController { LayerLink? _lastLayerLink; ValueNotifier? _lastVisibility; - CodeEditorToolbarController({this.focusNode}) { + CodeEditorToolbarController({this.focusNode, this.filePathGetter}) { _mobileController = MobileSelectionToolbarController( builder: ({ required BuildContext context, @@ -335,6 +364,7 @@ class CodeEditorToolbarController implements SelectionToolbarController { onDismiss: onDismiss, focusNode: focusNode, renderRect: renderRect, + filePathGetter: filePathGetter, ); }, ); @@ -410,6 +440,12 @@ class CodeEditorToolbarController implements SelectionToolbarController { final clipboardData = await Clipboard.getData(Clipboard.kTextPlain); final hasClipboard = clipboardData != null && (clipboardData.text?.isNotEmpty ?? false); + final filePath = filePathGetter?.call(); + final line = controller.selection.baseIndex; + final diags = (filePath != null && line >= 0) + ? LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, line) + : const []; + if (!context.mounted) return; final l10n = AppLocalizations.of(context); @@ -433,6 +469,23 @@ class CodeEditorToolbarController implements SelectionToolbarController { Offset.zero & mediaQuery.size, ), items: [ + if (diags.isNotEmpty && filePath != null) ...[ + _EditorContextMenuItem( + text: '快速修复 (Quick Fix)', + icon: Icons.lightbulb, + enabled: true, + onTap: () { + LspQuickFixDialog.show( + context, + filePath: filePath, + lineIndex: line, + diagnostics: diags, + controller: controller, + ); + }, + ), + const PopupMenuDivider(height: 1), + ], _EditorContextMenuItem( text: l10n?.cut ?? 'Cut', icon: Icons.content_cut, diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index 1e0b700..eb0ceab 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -8,9 +8,17 @@ import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/services/file_service.dart'; import 'package:code_editor/services/file_watcher_service.dart'; +import 'package:code_editor/services/code_completion/smart_prompts_builder.dart'; +import 'package:code_editor/services/lsp/lsp_diagnostics_store.dart'; +import 'package:code_editor/services/lsp/lsp_manager.dart'; +import 'package:code_editor/services/lsp/lsp_protocol.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/utils/syntax_highlight_helper.dart'; +import 'package:code_editor/widgets/code_autocomplete_view.dart'; import 'package:code_editor/widgets/code_editor_menu.dart'; +import 'package:code_editor/widgets/editor/editor_diagnostic_controller.dart'; +import 'package:code_editor/widgets/editor/editor_lsp_coordinator.dart'; +import 'package:code_editor/widgets/editor/editor_overlay_scope.dart'; import 'package:code_editor/widgets/virtual_keyboard_widget.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; @@ -18,6 +26,37 @@ import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; import 'package:re_editor/re_editor.dart'; +/// 行号指示器红/黄圆点装饰器 +class DiagnosticGutterDotDecoration extends Decoration { + final Color color; + final double radius; + + const DiagnosticGutterDotDecoration({ + required this.color, + this.radius = 3.0, + }); + + @override + BoxPainter createBoxPainter([VoidCallback? onChanged]) { + return _DiagnosticGutterDotPainter(this); + } +} + +class _DiagnosticGutterDotPainter extends BoxPainter { + final DiagnosticGutterDotDecoration decoration; + _DiagnosticGutterDotPainter(this.decoration); + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { + final size = configuration.size ?? Size.zero; + final paint = Paint() + ..color = decoration.color + ..style = PaintingStyle.fill; + final center = Offset(offset.dx + 4.0, offset.dy + size.height / 2); + canvas.drawCircle(center, decoration.radius, paint); + } +} + class CodeEditorWidget extends StatefulWidget { final String? rootPath; final String? filePath; @@ -45,12 +84,15 @@ class _CodeEditorWidgetState extends State { CodeScrollController? _scrollController; final FocusNode _focusNode = FocusNode(); late final CodeEditorToolbarController _toolbarController; + final EditorDiagnosticController _diagnosticController = const EditorDiagnosticController(); + final EditorLspCoordinator _lspCoordinator = const EditorLspCoordinator(); bool _isLoading = false; int _currentLoadVersion = 0; String? _errorMessage; String? _currentLoadedPath; int? _currentIndentSize; bool _isShowingConflictDialog = false; + int _currentCursorLine = -1; // 双指捏合实时缩放字号及中心锚定状态 final GlobalKey _editorContainerKey = GlobalKey(); @@ -420,10 +462,26 @@ class _CodeEditorWidgetState extends State { }); } + void _onDiagnosticsChanged() { + if (!mounted || _controller == null) return; + _controller?.forceRepaint(); + if (WidgetsBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) setState(() {}); + }); + } else { + setState(() {}); + } + } + @override void initState() { super.initState(); - _toolbarController = CodeEditorToolbarController(focusNode: _focusNode); + _toolbarController = CodeEditorToolbarController( + focusNode: _focusNode, + filePathGetter: () => _currentLoadedPath ?? widget.filePath, + ); + LspDiagnosticsStore.instance.addListener(_onDiagnosticsChanged); _loadFileContent(); } @@ -454,6 +512,10 @@ class _CodeEditorWidgetState extends State { try { _getTabProvider(context).registerSaveHandler(null); } catch (_) {} + LspDiagnosticsStore.instance.removeListener(_onDiagnosticsChanged); + if (_currentLoadedPath != null) { + LspManager.instance.onFileClosed(_currentLoadedPath!); + } _toolbarController.hide(context); final currentTab = _getCurrentTab(); _saveCurrentTabScrollState(currentTab); @@ -468,6 +530,19 @@ class _CodeEditorWidgetState extends State { void _onTextChanged() { if (!mounted || _controller == null) return; + + final newCursorLine = _controller?.selection.baseIndex ?? -1; + if (_currentCursorLine != newCursorLine) { + _currentCursorLine = newCursorLine; + if (WidgetsBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) setState(() {}); + }); + } else { + setState(() {}); + } + } + final currentTab = _getCurrentTab(); if (currentTab == null || !currentTab.isLoaded) return; // 确保当前活跃 tab 与当前加载的控制器路径严格一致,杜绝切换过程中误写其他 tab @@ -485,6 +560,15 @@ class _CodeEditorWidgetState extends State { currentTab.content = current; currentTab.isModified = isModified; + // LSP 文档变更增量/全量同步及本地语法诊断兜底 + if (_currentLoadedPath != null && _controller != null) { + _lspCoordinator.onFileChanged( + _currentLoadedPath!, + current, + _controller!.codeLines, + ); + } + void notifyProvider() { if (!mounted) return; try { @@ -500,6 +584,34 @@ class _CodeEditorWidgetState extends State { } } + /// 依据 LSP 实时诊断结果,为当前行的代码文本施加波浪下划线(保留已有代码高亮色彩) + TextSpan _buildDiagnosticSpans({ + required BuildContext context, + required int index, + required CodeLine codeLine, + required TextSpan textSpan, + required TextStyle style, + }) { + return _diagnosticController.buildDiagnosticSpans( + context: context, + filePath: _currentLoadedPath ?? widget.filePath, + index: index, + codeLine: codeLine, + textSpan: textSpan, + style: style, + ); + } + + Widget _buildDiagnosticBanner(BuildContext context, List diags, int lineIndex) { + return _diagnosticController.buildDiagnosticBanner( + context: context, + filePath: _currentLoadedPath ?? widget.filePath, + controller: _controller, + diags: diags, + lineIndex: lineIndex, + ); + } + Future _saveFile({bool showToast = false}) async { final currentPath = widget.filePath; if (currentPath == null || currentPath.isEmpty || _controller == null) { @@ -649,6 +761,7 @@ class _CodeEditorWidgetState extends State { AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono; bool showLineNumbers = true; bool pinLineNumbers = true; + bool enableLspCompletion = true; try { final settings = _getSettingsProvider(context, listen: true); activeTheme = settings.editorTheme; @@ -659,6 +772,7 @@ class _CodeEditorWidgetState extends State { enableVirtualKeyboard = settings.enableVirtualKeyboard; keyboardConfig = settings.virtualKeyboardConfig; activeEditorFont = settings.editorFont; + enableLspCompletion = settings.enableLspCompletion; if (_currentIndentSize != null && _currentIndentSize != settings.indentSize) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) _loadFileContent(); @@ -683,77 +797,112 @@ class _CodeEditorWidgetState extends State { onPointerUp: _handlePointerUp, onPointerCancel: _handlePointerCancel, child: Stack( + clipBehavior: Clip.none, children: [ IgnorePointer( ignoring: _isPinching, - child: CodeEditor( - key: ValueKey(_currentLoadedPath), - controller: controller, - focusNode: _focusNode, - scrollController: _scrollController, - wordWrap: activeWordWrap, - pinLineNumbers: pinLineNumbers, - toolbarController: _toolbarController, - margin: EdgeInsets.zero, - extraHorizontalScroll: 160.0, - padding: const EdgeInsets.fromLTRB(6.0, 0.0, 0.0, 0.0), - leadingDivider: showLineNumbers - ? Container( - width: 1.0, - color: activeTheme.gutterTextColor.withValues(alpha: 0.25), - ) - : null, - style: CodeEditorStyle( - fontSize: displayFontSize, - textColor: activeTheme.textColor, - backgroundColor: activeTheme.backgroundColor, - cursorColor: activeTheme.cursorColor, - cursorLineColor: activeTheme.cursorLineColor, - selectionColor: activeTheme.selectionColor, - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - codeTheme: CodeHighlightTheme( - languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath), - theme: activeTheme.highlightTheme, - ), - ), - indicatorBuilder: showLineNumbers - ? (context, editingController, chunkController, notifier) { - return Row( - children: [ - DefaultCodeLineNumber( - controller: editingController, - notifier: notifier, - textStyle: TextStyle( - color: activeTheme.gutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - height: 1.4, - ), - focusedTextStyle: TextStyle( - color: activeTheme.focusedGutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), - fontWeight: FontWeight.bold, - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - height: 1.4, - ), - ), - DefaultCodeChunkIndicator( - width: 20, - controller: chunkController, - notifier: notifier, - painter: DefaultCodeChunkIndicatorPainter( - color: activeTheme.gutterTextColor, - ), - ), - ], + child: Builder( + builder: (context) { + final promptsBuilder = SmartCodeAutocompletePromptsBuilder( + controller: controller, + filePath: _currentLoadedPath ?? widget.filePath, + enableLspCompletion: enableLspCompletion, + ); + return EditorOverlayScope( + key: ValueKey(_currentLoadedPath), + child: CodeAutocomplete( + viewBuilder: (context, notifier, onSelected) { + promptsBuilder.activeNotifier = notifier; + return CodeAutocompleteView( + notifier: notifier, + onSelected: onSelected, ); - } - : null, - ), - ), + }, + promptsBuilder: promptsBuilder, + child: CodeEditor( + key: ValueKey(_currentLoadedPath), + controller: controller, + focusNode: _focusNode, + scrollController: _scrollController, + wordWrap: activeWordWrap, + pinLineNumbers: pinLineNumbers, + toolbarController: _toolbarController, + margin: EdgeInsets.zero, + extraHorizontalScroll: 160.0, + padding: const EdgeInsets.fromLTRB(6.0, 0.0, 0.0, 0.0), + leadingDivider: showLineNumbers + ? Container( + width: 1.0, + color: activeTheme.gutterTextColor.withValues(alpha: 0.25), + ) + : null, + style: CodeEditorStyle( + fontSize: displayFontSize, + textColor: activeTheme.textColor, + backgroundColor: activeTheme.backgroundColor, + cursorColor: activeTheme.cursorColor, + cursorLineColor: activeTheme.cursorLineColor, + selectionColor: activeTheme.selectionColor, + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + codeTheme: CodeHighlightTheme( + languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath), + theme: activeTheme.highlightTheme, + ), + ), + indicatorBuilder: showLineNumbers + ? (context, editingController, chunkController, notifier) { + return Row( + children: [ + DefaultCodeLineNumber( + controller: editingController, + notifier: notifier, + lineDecorationBuilder: (lineIndex) { + final filePath = _currentLoadedPath ?? widget.filePath; + if (filePath == null) return null; + final diags = LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, lineIndex); + if (diags.isEmpty) return null; + final hasError = diags.any((d) => d.severity == LspDiagnosticSeverity.error); + final hasWarning = diags.any((d) => d.severity == LspDiagnosticSeverity.warning); + final dotColor = hasError + ? Colors.redAccent + : (hasWarning ? Colors.amberAccent : Colors.lightBlueAccent); + return DiagnosticGutterDotDecoration(color: dotColor); + }, + textStyle: TextStyle( + color: activeTheme.gutterTextColor, + fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + height: 1.4, + ), + focusedTextStyle: TextStyle( + color: activeTheme.focusedGutterTextColor, + fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontWeight: FontWeight.bold, + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + height: 1.4, + ), + ), + DefaultCodeChunkIndicator( + width: 20, + controller: chunkController, + notifier: notifier, + painter: DefaultCodeChunkIndicatorPainter( + color: activeTheme.gutterTextColor, + ), + ), + ], + ); + } + : null, + ), + ), + ); + }, + ), + ), // 双指缩放实时字号悬浮胶囊提示 if (_isPinching && _activeZoomFontSize != null) Positioned( @@ -794,6 +943,18 @@ class _CodeEditorWidgetState extends State { ), ), ), + if (_currentCursorLine >= 0 && (_currentLoadedPath ?? widget.filePath) != null) ...[ + Builder( + builder: (ctx) { + final diags = LspDiagnosticsStore.instance.getDiagnosticsForLine( + _currentLoadedPath ?? widget.filePath, + _currentCursorLine, + ); + if (diags.isEmpty) return const SizedBox.shrink(); + return _buildDiagnosticBanner(ctx, diags, _currentCursorLine); + }, + ), + ], if (enableVirtualKeyboard && keyboardConfig != null && keyboardConfig.hasKeys) VirtualKeyboardWidget( controller: controller, @@ -866,6 +1027,7 @@ class _CodeEditorWidgetState extends State { final newController = CodeLineEditingController.fromText( normalizedContent, CodeLineOptions(indentSize: activeIndentSize), + _buildDiagnosticSpans, ); _controller = newController; @@ -874,6 +1036,13 @@ class _CodeEditorWidgetState extends State { _errorMessage = null; _isLoading = false; + _lspCoordinator.onFileOpened( + fullFilePath, + normalizedContent, + newController.codeLines, + workspaceRoot: widget.rootPath, + ); + // 必须在 _controller 和 tab 状态准备就绪后再挂载文本监听,避免初始化阶段被误判为脏 newController.addListener(_onTextChanged); @@ -917,6 +1086,7 @@ class _CodeEditorWidgetState extends State { final newController = CodeLineEditingController.fromText( diskContent, CodeLineOptions(indentSize: activeIndentSize), + _buildDiagnosticSpans, ); _controller = newController; @@ -924,6 +1094,13 @@ class _CodeEditorWidgetState extends State { _currentIndentSize = activeIndentSize; _errorMessage = null; + _lspCoordinator.onFileOpened( + fullFilePath, + diskContent, + newController.codeLines, + workspaceRoot: widget.rootPath, + ); + if (tab != null) { tab.content = diskContent; tab.originalContent = diskContent; diff --git a/lib/widgets/distro_selector_dialog.dart b/lib/widgets/distro_selector_dialog.dart deleted file mode 100644 index f9e107d..0000000 --- a/lib/widgets/distro_selector_dialog.dart +++ /dev/null @@ -1,380 +0,0 @@ -import 'dart:io'; -import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/providers/distro_provider.dart'; -import 'package:code_editor/providers/terminal_provider.dart'; -import 'package:code_editor/models/distro_manifest.dart'; -import 'package:code_editor/services/distro_download_manager.dart'; -import 'package:code_editor/utils/dialog_utils.dart'; -import 'package:code_editor/views/distro_management_view.dart'; -import 'package:code_editor/widgets/distro_extract_dialog.dart'; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:path/path.dart' as p; -import 'package:provider/provider.dart'; - -/// 独立的 Linux 系统选择与管理对话框 -class DistroSelectorDialog extends StatelessWidget { - const DistroSelectorDialog({super.key}); - - /// 打开系统选择与管理对话框 - static Future show(BuildContext context) { - return showDialog( - context: context, - builder: (ctx) => const DistroSelectorDialog(), - ); - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final l10n = AppLocalizations.of(context)!; - final distroProvider = context.watch(); - final systems = distroProvider.installedSystems; - final selectedSystem = distroProvider.selectedSystem; - - return AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16.0), - ), - titlePadding: const EdgeInsets.fromLTRB(20.0, 16.0, 12.0, 8.0), - contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), - title: Row( - children: [ - const Icon(Icons.dns_outlined, size: 22, color: Colors.blueAccent), - const SizedBox(width: 8), - Expanded( - child: Text( - l10n.systemManagement, - style: const TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold), - ), - ), - // 导入按钮与下拉选项 - PopupMenuButton( - icon: const Icon(Icons.add_circle_outline, color: Colors.blueAccent), - tooltip: l10n.importNewSystem, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12.0), - ), - onSelected: (action) => _handleImportAction(context, action), - itemBuilder: (context) => [ - PopupMenuItem( - value: 'management_view', - child: Row( - children: [ - const Icon(Icons.apps_rounded, size: 18), - const SizedBox(width: 8), - Flexible( - child: Text( - l10n.importFromApp, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - ), - PopupMenuItem( - value: 'external', - child: Row( - children: [ - const Icon(Icons.folder_open_outlined, size: 18), - const SizedBox(width: 8), - Flexible( - child: Text( - l10n.importExternalTarGz, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - ), - ], - ), - ], - ), - content: SizedBox( - width: double.maxFinite, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: 8.0), - child: Text( - l10n.selectSystemDefaultPrompt, - style: TextStyle( - fontSize: 12.0, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ), - const Divider(height: 1), - Flexible( - child: systems.isEmpty - ? Container( - padding: const EdgeInsets.symmetric(vertical: 32.0), - alignment: Alignment.center, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.layers_clear_outlined, - size: 40, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), - ), - const SizedBox(height: 8), - Text( - l10n.noSystemsPrompt, - style: TextStyle( - fontSize: 13.0, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ) - : ListView.builder( - shrinkWrap: true, - padding: const EdgeInsets.symmetric(vertical: 4.0), - itemCount: systems.length, - itemBuilder: (context, index) { - final system = systems[index]; - final isSelected = system == selectedSystem; - - return Container( - margin: const EdgeInsets.symmetric(vertical: 3.0), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(8.0), - border: Border.all( - color: isSelected - ? theme.colorScheme.primary.withValues(alpha: 0.5) - : theme.colorScheme.outlineVariant.withValues(alpha: 0.4), - width: 1.0, - ), - ), - child: Material( - color: isSelected - ? theme.colorScheme.primaryContainer.withValues(alpha: 0.4) - : Colors.transparent, - borderRadius: BorderRadius.circular(8.0), - child: ListTile( - dense: true, - contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 2.0), - title: Text( - system, - style: TextStyle( - fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - color: isSelected ? theme.colorScheme.primary : null, - fontSize: 14.0, - ), - ), - trailing: IconButton( - icon: Icon( - Icons.delete_outline, - color: theme.colorScheme.error, - size: 20, - ), - tooltip: l10n.deleteSystemTooltip, - onPressed: () => _handleDeleteSystem(context, system), - ), - onTap: () { - distroProvider.selectSystem(system); - }, - ), - ), - ); - }, - ), - ), - ], - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: Text(l10n.done), - ), - ], - ); - } - - /// 处理导入菜单操作 - bool _isValidDistroArchive(String path) { - final lower = path.toLowerCase(); - return lower.endsWith('.tar.gz') || - lower.endsWith('.tgz') || - lower.endsWith('.tar.xz') || - lower.endsWith('.txz') || - lower.endsWith('.tar'); - } - - Future _handleImportAction(BuildContext context, String action) async { - final distroProvider = context.read(); - final l10n = AppLocalizations.of(context)!; - - if (action == 'management_view') { - // 1. 跳转到应用内系统管理页面 - final selectedItem = await Navigator.of(context).push( - MaterialPageRoute(builder: (_) => const DistroManagementView()), - ); - - if (selectedItem != null && context.mounted) { - // 用户直接点击已经安装的 item 本身,代表用户选择了那个 zip,返回后解压创建系统 - await _handleCreateSystemFromManifest(context, selectedItem); - } - } else if (action == 'external') { - // 2. 从外部选择 .tar.gz / .tar.xz 压缩包导入 - final result = await FilePicker.platform.pickFiles( - type: FileType.custom, - allowedExtensions: const ['tar', 'gz', 'tgz', 'xz', 'txz'], - ); - - if (result == null || result.files.single.path == null || !context.mounted) return; - final filePath = result.files.single.path!; - - if (!_isValidDistroArchive(filePath)) { - if (context.mounted) { - DialogUtils.showErrorToast(context, l10n.unsupportedDistroArchiveFormat); - } - return; - } - - final file = File(filePath); - - // 提取默认名称(去掉 .tar.gz, .tgz 等后缀) - String baseName = p.basename(filePath); - if (baseName.endsWith('.tar.gz')) { - baseName = baseName.substring(0, baseName.length - 7); - } else if (baseName.endsWith('.tgz')) { - baseName = baseName.substring(0, baseName.length - 4); - } else { - baseName = p.basenameWithoutExtension(filePath); - } - baseName = baseName.replaceAll(RegExp(r'[^a-zA-Z0-9_\-]'), '_'); - if (baseName.isEmpty) baseName = 'custom_linux'; - - final defaultName = _generateUniqueSystemName(baseName, distroProvider.installedSystems); - - final systemName = await DialogUtils.showInputDialog( - context, - title: l10n.importExternalSystemTitle, - hintText: l10n.systemNameHint, - initialValue: defaultName, - ); - - if (systemName == null || systemName.trim().isEmpty || !context.mounted) return; - final cleanName = systemName.trim(); - - // 模态同步解压 - final success = await DistroExtractDialog.show( - context: context, - systemName: cleanName, - task: (onProgress, isCancelled) { - return distroProvider.importFromCustomTarGz( - systemName: cleanName, - tarGzFile: file, - onProgress: onProgress, - isCancelled: isCancelled, - ); - }, - ); - - if (success && context.mounted) { - DialogUtils.showSuccessToast(context, l10n.externalSystemImportSuccess(cleanName)); - } - } - } - - /// 从选中的发行版安装包解压创建新的系统实例 - Future _handleCreateSystemFromManifest(BuildContext context, DistroManifestItem item) async { - final distroProvider = context.read(); - final l10n = AppLocalizations.of(context)!; - - final defaultName = _generateUniqueSystemName(item.id, distroProvider.installedSystems); - final systemName = await DialogUtils.showInputDialog( - context, - title: l10n.importSystemInstanceTitle(item.name), - hintText: l10n.systemNameHintWithDefault(defaultName), - initialValue: defaultName, - ); - - if (systemName == null || systemName.trim().isEmpty || !context.mounted) return; - final cleanName = systemName.trim(); - - // 模态同步解压 - final success = await DistroExtractDialog.show( - context: context, - systemName: cleanName, - task: (onProgress, isCancelled) async { - if (item.id == 'ubuntu') { - return distroProvider.importBuiltinUbuntu( - systemName: cleanName, - onProgress: onProgress, - isCancelled: isCancelled, - ); - } else if (item.id == 'alpine') { - return distroProvider.importBuiltinAlpine( - systemName: cleanName, - onProgress: onProgress, - isCancelled: isCancelled, - ); - } else { - final file = await DistroDownloadManager().getPackageFile(item.id, item.currentPackageSource!); - return distroProvider.importFromCustomTarGz( - systemName: cleanName, - tarGzFile: file, - onProgress: onProgress, - isCancelled: isCancelled, - ); - } - }, - ); - - if (success && context.mounted) { - DialogUtils.showSuccessToast(context, l10n.systemImportSuccess(cleanName)); - await distroProvider.refreshSystems(); - await distroProvider.selectSystem(cleanName); - } - } - - /// 高危操作:二次确认删除系统 - Future _handleDeleteSystem(BuildContext context, String systemName) async { - final l10n = AppLocalizations.of(context)!; - final confirmed = await DialogUtils.showDestructiveConfirmDialog( - context, - title: l10n.deleteSystemConfirmTitle, - message: l10n.deleteSystemConfirmMessage(systemName), - confirmText: l10n.permanentDelete, - ); - - if (confirmed && context.mounted) { - final distroProvider = context.read(); - final terminalProvider = context.read(); - try { - await distroProvider.deleteSystem(systemName); - terminalProvider?.removeSessionsForDistro(systemName); - if (!distroProvider.hasAnySystem) { - terminalProvider?.clearAllSessions(); - } - if (context.mounted) { - DialogUtils.showToast(context, l10n.deleteSystemSuccess(systemName)); - } - } catch (e) { - if (context.mounted) { - DialogUtils.showErrorToast(context, l10n.deleteSystemFailed(e.toString())); - } - } - } - } - - /// 自动生成不重复的系统实例名 - String _generateUniqueSystemName(String prefix, List existingSystems) { - if (!existingSystems.contains(prefix)) return prefix; - int index = 1; - while (existingSystems.contains('${prefix}_$index')) { - index++; - } - return '${prefix}_$index'; - } -} diff --git a/lib/widgets/editor/editor_diagnostic_controller.dart b/lib/widgets/editor/editor_diagnostic_controller.dart new file mode 100644 index 0000000..dde964c --- /dev/null +++ b/lib/widgets/editor/editor_diagnostic_controller.dart @@ -0,0 +1,266 @@ +import 'dart:math'; +import 'package:flutter/material.dart'; +import 'package:re_editor/re_editor.dart'; +import '../../services/lsp/lsp_diagnostics_store.dart'; +import '../../services/lsp/lsp_protocol.dart'; +import '../lsp_quick_fix_dialog.dart'; + +class _DiagnosticInterval { + final int start; + final int end; + final Color color; + + const _DiagnosticInterval(this.start, this.end, this.color); +} + +class _OffsetTracker { + int value; + _OffsetTracker(this.value); +} + +/// 编辑器代码诊断视图控制器 +/// +/// 专职负责: +/// 1. 依据 LSP 与本地语法诊断,计算行内波浪下划线(保持语法高亮颜色); +/// 2. 构建底部错误与警告横幅,支持一键唤起 LSP 快捷修复。 +class EditorDiagnosticController { + const EditorDiagnosticController(); + + /// 依据实时诊断结果,为当前行的代码文本施加波浪下划线(保留已有代码高亮色彩) + TextSpan buildDiagnosticSpans({ + required BuildContext context, + required String? filePath, + required int index, + required CodeLine codeLine, + required TextSpan textSpan, + required TextStyle style, + }) { + if (filePath == null || codeLine.text.isEmpty) { + return textSpan; + } + + final diagnostics = LspDiagnosticsStore.instance.getDiagnosticsForLine(filePath, index); + if (diagnostics.isEmpty) { + return textSpan; + } + + final lineText = codeLine.text; + final lineLen = lineText.length; + + final intervals = <_DiagnosticInterval>[]; + for (final d in diagnostics) { + final startLine = d.range.start.line; + final endLine = d.range.end.line; + + int startCol = 0; + if (startLine == index) { + startCol = d.range.start.character; + } else if (startLine > index) { + continue; + } + + int endCol = lineLen; + if (endLine == index) { + endCol = d.range.end.character; + } else if (endLine < index) { + continue; + } + + startCol = startCol.clamp(0, lineLen); + endCol = endCol.clamp(0, lineLen); + + // LSP 有时可能返回单点(0 宽)区间,自动扩宽至至少 1 字符高亮以便视觉可见 + if (startCol == endCol) { + if (startCol < lineLen) { + endCol = min(startCol + 1, lineLen); + } else if (startCol > 0) { + startCol = startCol - 1; + } + } + + if (startCol < endCol) { + Color diagColor = Colors.redAccent; + switch (d.severity) { + case LspDiagnosticSeverity.error: + diagColor = Colors.redAccent; + break; + case LspDiagnosticSeverity.warning: + diagColor = Colors.amberAccent; + break; + case LspDiagnosticSeverity.information: + diagColor = Colors.lightBlueAccent; + break; + case LspDiagnosticSeverity.hint: + diagColor = Colors.grey; + break; + } + intervals.add(_DiagnosticInterval(startCol, endCol, diagColor)); + } + } + + if (intervals.isEmpty) { + return textSpan; + } + + return _applyDiagnosticIntervals(textSpan, intervals, _OffsetTracker(0), style); + } + + /// 构建底部单行诊断简报与快捷修复入口横幅 + Widget buildDiagnosticBanner({ + required BuildContext context, + required String? filePath, + required CodeLineEditingController? controller, + required List diags, + required int lineIndex, + }) { + final first = diags.first; + final isErr = diags.any((d) => d.severity == LspDiagnosticSeverity.error); + final color = isErr ? Colors.redAccent : Colors.amber; + final icon = isErr ? Icons.error_outline : Icons.warning_amber_outlined; + + return Material( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + elevation: 2, + child: InkWell( + onTap: () { + if (filePath != null && controller != null) { + LspQuickFixDialog.show( + context, + filePath: filePath, + lineIndex: lineIndex, + diagnostics: diags, + controller: controller, + ); + } + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + border: Border( + top: BorderSide(color: color.withValues(alpha: 0.6), width: 1.5), + ), + ), + child: Row( + children: [ + Icon(icon, size: 16, color: color), + const SizedBox(width: 8), + Expanded( + child: Text( + '行 ${lineIndex + 1}: ${first.message}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.amber.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(4), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon(Icons.lightbulb, size: 12, color: Colors.amber), + SizedBox(width: 2), + Text( + '修复', + style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.amber), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + static TextSpan _applyDiagnosticIntervals( + TextSpan span, + List<_DiagnosticInterval> intervals, + _OffsetTracker tracker, + TextStyle baseStyle, + ) { + final effectiveStyle = span.style ?? baseStyle; + + if (span.children != null && span.children!.isNotEmpty) { + final newChildren = []; + if (span.text != null && span.text!.isNotEmpty) { + final leafSpan = TextSpan(text: span.text, style: effectiveStyle); + newChildren.add(_processLeafTextSpan(leafSpan, intervals, tracker, effectiveStyle)); + } + for (final child in span.children!) { + if (child is TextSpan) { + newChildren.add(_applyDiagnosticIntervals(child, intervals, tracker, effectiveStyle)); + } else { + newChildren.add(child); + } + } + return TextSpan(children: newChildren, style: span.style); + } + + return _processLeafTextSpan(span, intervals, tracker, effectiveStyle); + } + + static TextSpan _processLeafTextSpan( + TextSpan span, + List<_DiagnosticInterval> intervals, + _OffsetTracker tracker, + TextStyle baseStyle, + ) { + final text = span.text; + if (text == null || text.isEmpty) { + return span; + } + + final startOffset = tracker.value; + final endOffset = startOffset + text.length; + tracker.value = endOffset; + + final intersecting = intervals.where((it) => it.end > startOffset && it.start < endOffset).toList(); + if (intersecting.isEmpty) { + return span; + } + + final splitPoints = {startOffset, endOffset}; + for (final it in intersecting) { + if (it.start > startOffset && it.start < endOffset) splitPoints.add(it.start); + if (it.end > startOffset && it.end < endOffset) splitPoints.add(it.end); + } + final sortedPoints = splitPoints.toList()..sort(); + + final chunks = []; + for (int i = 0; i < sortedPoints.length - 1; i++) { + final segStart = sortedPoints[i]; + final segEnd = sortedPoints[i + 1]; + if (segStart >= segEnd) continue; + + final chunkText = text.substring(segStart - startOffset, segEnd - startOffset); + final activeInterval = intersecting.where((it) => it.start <= segStart && it.end >= segEnd).firstOrNull; + + if (activeInterval != null) { + chunks.add(TextSpan( + text: chunkText, + style: (span.style ?? baseStyle).copyWith( + decoration: TextDecoration.underline, + decorationStyle: TextDecorationStyle.wavy, + decorationColor: activeInterval.color, + ), + )); + } else { + chunks.add(TextSpan(text: chunkText, style: span.style)); + } + } + + if (chunks.length == 1 && chunks.first is TextSpan) { + return chunks.first as TextSpan; + } + return TextSpan(children: chunks, style: span.style); + } +} diff --git a/lib/widgets/editor/editor_lsp_coordinator.dart b/lib/widgets/editor/editor_lsp_coordinator.dart new file mode 100644 index 0000000..013ef93 --- /dev/null +++ b/lib/widgets/editor/editor_lsp_coordinator.dart @@ -0,0 +1,45 @@ +import 'package:re_editor/re_editor.dart'; +import '../../services/lsp/lsp_diagnostics_store.dart'; +import '../../services/lsp/lsp_manager.dart'; + +/// 编辑器 LSP 生命周期协调器 +/// +/// 负责: +/// 1. 统一管理文档打开、变更、关闭与 LSP 语言服务器进程的同步; +/// 2. 文档关闭时及时清理诊断缓存; +/// 3. 所有语法纠错与诊断均严格来自真实 LSP 进程的 push 通知,不进行任何本地模糊伪检查。 +class EditorLspCoordinator { + const EditorLspCoordinator(); + + /// 文档打开时同步至 LSP + void onFileOpened( + String filePath, + String content, + CodeLines codeLines, { + String? workspaceRoot, + }) { + LspManager.instance.onFileOpened( + filePath, + content, + workspaceRoot: workspaceRoot, + ); + } + + /// 文档文本内容变更时同步至 LSP 进程 + void onFileChanged( + String filePath, + String content, + CodeLines codeLines, + ) { + final session = LspManager.instance.getExistingSession(filePath); + if (session != null && session.isInitialized) { + LspManager.instance.onFileChanged(filePath, content); + } + } + + /// 文档关闭时清理会话与诊断 + void onFileClosed(String filePath) { + LspManager.instance.onFileClosed(filePath); + LspDiagnosticsStore.instance.removeForFile(filePath); + } +} diff --git a/lib/widgets/editor/editor_overlay_scope.dart b/lib/widgets/editor/editor_overlay_scope.dart new file mode 100644 index 0000000..fbe943c --- /dev/null +++ b/lib/widgets/editor/editor_overlay_scope.dart @@ -0,0 +1,47 @@ +import 'package:flutter/widgets.dart'; + +/// 编辑器专属局部 Overlay 作用域 +/// +/// 核心职责: +/// 1. 为代码补全弹窗(CodeAutocomplete)提供局部 Overlay 承载容器; +/// 2. 控制弹窗的堆叠层级(Z-Order):使其位于编辑器内容之上,但在编辑区底栏(如虚拟小键盘 VirtualKeyboardWidget、诊断横幅)之下; +/// 3. 当父级状态变更时,自动刷新内部根 OverlayEntry,确保代码内容与控制器无缝响应。 +class EditorOverlayScope extends StatefulWidget { + final Widget child; + final Clip clipBehavior; + + const EditorOverlayScope({ + super.key, + required this.child, + this.clipBehavior = Clip.none, + }); + + @override + State createState() => _EditorOverlayScopeState(); +} + +class _EditorOverlayScopeState extends State { + late final OverlayEntry _entry; + + @override + void initState() { + super.initState(); + _entry = OverlayEntry( + builder: (context) => widget.child, + ); + } + + @override + void didUpdateWidget(covariant EditorOverlayScope oldWidget) { + super.didUpdateWidget(oldWidget); + _entry.markNeedsBuild(); + } + + @override + Widget build(BuildContext context) { + return Overlay( + clipBehavior: widget.clipBehavior, + initialEntries: [_entry], + ); + } +} diff --git a/lib/widgets/lsp_language_edit_dialog.dart b/lib/widgets/lsp_language_edit_dialog.dart index 1f8f6ae..adf6e81 100644 --- a/lib/widgets/lsp_language_edit_dialog.dart +++ b/lib/widgets/lsp_language_edit_dialog.dart @@ -34,7 +34,7 @@ class _LspLanguageEditDialogState extends State { late final TextEditingController _extensionsController; late final TextEditingController _commandController; late final TextEditingController _argsController; - late final TextEditingController _apkPackageController; + late final TextEditingController _packageController; @override void initState() { @@ -49,7 +49,7 @@ class _LspLanguageEditDialogState extends State { _argsController = TextEditingController( text: init?.serverArgs.join(' ') ?? '', ); - _apkPackageController = TextEditingController(text: init?.apkPackage ?? ''); + _packageController = TextEditingController(text: init?.package ?? ''); } @override @@ -59,7 +59,7 @@ class _LspLanguageEditDialogState extends State { _extensionsController.dispose(); _commandController.dispose(); _argsController.dispose(); - _apkPackageController.dispose(); + _packageController.dispose(); super.dispose(); } @@ -101,7 +101,7 @@ class _LspLanguageEditDialogState extends State { fileExtensions: cleanedExtensions, serverCommand: _commandController.text.trim(), serverArgs: cleanedArgs, - apkPackage: _apkPackageController.text.trim(), + package: _packageController.text.trim(), enabled: widget.initialConfig?.enabled ?? true, ); @@ -175,7 +175,7 @@ class _LspLanguageEditDialogState extends State { ), const SizedBox(height: 12), TextFormField( - controller: _apkPackageController, + controller: _packageController, decoration: InputDecoration( labelText: l10n.apkPackageField, hintText: l10n.apkPackageFieldHint, diff --git a/lib/widgets/lsp_quick_fix_dialog.dart b/lib/widgets/lsp_quick_fix_dialog.dart new file mode 100644 index 0000000..2e7af73 --- /dev/null +++ b/lib/widgets/lsp_quick_fix_dialog.dart @@ -0,0 +1,153 @@ +import 'package:flutter/material.dart'; +import 'package:re_editor/re_editor.dart'; +import '../services/lsp/lsp_manager.dart'; +import '../services/lsp/lsp_protocol.dart'; +import '../services/lsp/lsp_workspace_edit_applier.dart'; + +/// 快速修复操作弹窗(展示诊断信息及 LSP CodeAction 选项) +class LspQuickFixDialog { + static Future show( + BuildContext context, { + required String filePath, + required int lineIndex, + required List diagnostics, + required CodeLineEditingController controller, + VoidCallback? onDismiss, + }) async { + final session = LspManager.instance.getExistingSession(filePath); + List actions = []; + + if (session != null && diagnostics.isNotEmpty && lineIndex < controller.lineCount) { + final lineLength = controller.codeLines[lineIndex].text.length; + final range = LspRange( + start: LspPosition.pos(lineIndex, 0), + end: LspPosition.pos(lineIndex, lineLength), + ); + try { + actions = await session.getCodeActions(filePath, range, diagnostics); + } catch (_) {} + } + + if (!context.mounted) return; + + await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Theme.of(context).colorScheme.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (ctx) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 36, + height: 4, + decoration: BoxDecoration( + color: Colors.grey.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 12), + Row( + children: [ + const Icon(Icons.lightbulb, color: Colors.amber, size: 20), + const SizedBox(width: 8), + Text( + '代码问题与修复 (第 ${lineIndex + 1} 行)', + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + ], + ), + const SizedBox(height: 12), + ...diagnostics.map((d) { + final isErr = d.severity == LspDiagnosticSeverity.error; + return Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: (isErr ? Colors.redAccent : Colors.amberAccent).withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: (isErr ? Colors.redAccent : Colors.amberAccent).withValues(alpha: 0.3), + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + isErr ? Icons.error_outline : Icons.warning_amber_outlined, + size: 18, + color: isErr ? Colors.redAccent : Colors.amber, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + d.message, + style: TextStyle( + fontSize: 13, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ), + ], + ), + ); + }), + const Divider(height: 16), + if (actions.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + children: [ + Icon( + Icons.info_outline, + size: 16, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Text( + '当前报错未提供自动修复动作', + style: TextStyle( + fontSize: 13, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ) + else + ...actions.map((act) { + return ListTile( + contentPadding: EdgeInsets.zero, + leading: const Icon(Icons.auto_fix_high, color: Colors.blueAccent), + title: Text(act.title, style: const TextStyle(fontSize: 14)), + trailing: act.isPreferred ? const Chip(label: Text('推荐', style: TextStyle(fontSize: 11))) : null, + onTap: () { + Navigator.pop(ctx); + if (act.edit != null) { + LspWorkspaceEditApplier.applyWorkspaceEdit( + controller, + act.edit!, + currentFilePath: filePath, + ); + } + onDismiss?.call(); + }, + ); + }), + ], + ), + ), + ); + }, + ); + } +} diff --git a/packages/re_editor/lib/src/_code_autocomplete.dart b/packages/re_editor/lib/src/_code_autocomplete.dart index fae1006..61b0a46 100644 --- a/packages/re_editor/lib/src/_code_autocomplete.dart +++ b/packages/re_editor/lib/src/_code_autocomplete.dart @@ -136,6 +136,14 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> { ValueChanged? _onAutocomplete; OverlayEntry? _overlayEntry; ValueNotifier? _notifier; + Offset? _position; + double? _lineHeight; + LayerLink? _layerLink; + + final GlobalKey _menuKey = GlobalKey(); + Offset? _pointerDownPosition; + DateTime? _pointerDownTime; + bool _isPointerSliding = false; @override void initState() { @@ -180,6 +188,68 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> { super.didUpdateWidget(oldWidget); } + @override + void dispose() { + dismiss(); + super.dispose(); + } + + void _handleEditorPointerDown(PointerDownEvent event) { + if (_overlayEntry == null) return; + _pointerDownPosition = event.position; + _pointerDownTime = DateTime.now(); + _isPointerSliding = false; + } + + void _handleEditorPointerMove(PointerMoveEvent event) { + if (_overlayEntry == null || _pointerDownPosition == null) return; + if ((event.position - _pointerDownPosition!).distance > kTouchSlop) { + _isPointerSliding = true; + } + } + + void _handleEditorPointerUp(PointerUpEvent event) { + if (_overlayEntry == null || _pointerDownPosition == null) { + _pointerDownPosition = null; + _isPointerSliding = false; + return; + } + + // 用户在编辑区滑动(例如上下或左右滚动代码),坚决不关闭菜单 + if (_isPointerSliding) { + _pointerDownPosition = null; + _isPointerSliding = false; + return; + } + + final duration = DateTime.now().difference(_pointerDownTime ?? DateTime.now()); + _pointerDownPosition = null; + _isPointerSliding = false; + + // 轻触点击判定:时长小于 500ms 且无位移 + if (duration.inMilliseconds > 500) { + return; + } + + // 检查点击位置是否在补全菜单内 + final RenderBox? menuBox = _menuKey.currentContext?.findRenderObject() as RenderBox?; + if (menuBox != null && menuBox.hasSize) { + final localPos = menuBox.globalToLocal(event.position); + if (menuBox.paintBounds.contains(localPos)) { + // 点击在菜单内部,由菜单自身交互逻辑处理,不关闭 + return; + } + } + + // 只有在菜单区域外的编辑区执行了点击(Tap),才关闭菜单 + dismiss(); + } + + void _handleEditorPointerCancel(PointerCancelEvent event) { + _pointerDownPosition = null; + _isPointerSliding = false; + } + @override Widget build(BuildContext context) { return Actions( @@ -187,10 +257,19 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> { CodeShortcutCursorMoveIntent: _navigateAction, CodeShortcutNewLineIntent: _selectAction, }, - child: widget.child + child: Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: _handleEditorPointerDown, + onPointerMove: _handleEditorPointerMove, + onPointerUp: _handleEditorPointerUp, + onPointerCancel: _handleEditorPointerCancel, + child: widget.child, + ), ); } + int _showVersion = 0; + void show({ required LayerLink layerLink, required Offset position, @@ -198,28 +277,84 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> { required CodeLineEditingValue value, required ValueChanged onAutocomplete, }) { - dismiss(); - final CodeAutocompleteEditingValue? autocompleteEditingValue = widget.promptsBuilder.build( + final int version = ++_showVersion; + final dynamic result = widget.promptsBuilder.build( context, value.codeLines[value.selection.extentIndex], value.selection, ); - if (autocompleteEditingValue == null) { + + if (result is Future) { + result.then((resolved) { + if (!mounted || version != _showVersion) return; + if (resolved is CodeAutocompleteEditingValue) { + _displayPrompts( + layerLink: layerLink, + position: position, + lineHeight: lineHeight, + editingValue: resolved, + onAutocomplete: onAutocomplete, + ); + } else { + dismiss(); + } + }); return; } - _notifier = ValueNotifier(autocompleteEditingValue); + + if (result is CodeAutocompleteEditingValue) { + _displayPrompts( + layerLink: layerLink, + position: position, + lineHeight: lineHeight, + editingValue: result, + onAutocomplete: onAutocomplete, + ); + } else { + dismiss(); + } + } + + void _displayPrompts({ + required LayerLink layerLink, + required Offset position, + required double lineHeight, + required CodeAutocompleteEditingValue editingValue, + required ValueChanged onAutocomplete, + }) { + _position = position; + _lineHeight = lineHeight; + _layerLink = layerLink; + _onAutocomplete = onAutocomplete; + + if (_overlayEntry != null && _notifier != null) { + // 已经处于展开状态,原地更新候选列表并重绘 OverlayEntry 计算自适应高度 + _notifier!.value = editingValue; + _overlayEntry!.markNeedsBuild(); + return; + } + + dismiss(); + _position = position; + _lineHeight = lineHeight; + _layerLink = layerLink; + _notifier = ValueNotifier(editingValue); _onAutocomplete = onAutocomplete; _overlayEntry = OverlayEntry( - builder:(context) { - return _buildWidget(context, layerLink, position, lineHeight); + builder: (context) { + return _buildWidget(context); }, ); - Overlay.of(context, rootOverlay: true).insert(_overlayEntry!); + final overlay = Overlay.maybeOf(context, rootOverlay: false) ?? Overlay.of(context, rootOverlay: true); + overlay.insert(_overlayEntry!); _navigateAction.setEnabled(true); _selectAction.setEnabled(true); } void dismiss() { + _position = null; + _lineHeight = null; + _layerLink = null; _notifier = null; _onAutocomplete = null; _overlayEntry?.remove(); @@ -228,39 +363,64 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> { _selectAction.setEnabled(false); } - Widget _buildWidget(BuildContext context, LayerLink layerLink, Offset position, double lineHeight) { + Widget _buildWidget(BuildContext context) { + if (_position == null || _layerLink == null || _notifier == null) { + return const SizedBox.shrink(); + } final PreferredSizeWidget child = widget.viewBuilder(context, _notifier!, (result) { _onAutocomplete?.call(result); }); - final Size screenSize = MediaQuery.of(context).size; - final double offsetX; - if (position.dx + child.preferredSize.width > screenSize.width) { - offsetX = screenSize.width - (position.dx + child.preferredSize.width); - } else { - offsetX = 0; + final mediaQuery = MediaQuery.of(context); + final Size screenSize = mediaQuery.size; + final position = _position!; + + // 水平方向:允许菜单水平自然超出编辑区 + const double offsetX = 0.0; + + // 计算小键盘及局部 Overlay 的底部边界 + final overlay = Overlay.maybeOf(context, rootOverlay: false) ?? Overlay.of(context, rootOverlay: true); + final RenderBox? overlayBox = overlay.context.findRenderObject() as RenderBox?; + double overlayBottomY = screenSize.height; + if (overlayBox != null && overlayBox.hasSize) { + final overlayTopLeft = overlayBox.localToGlobal(Offset.zero); + overlayBottomY = overlayTopLeft.dy + overlayBox.size.height; } - final double offsetY; - if (position.dy + child.preferredSize.height > screenSize.height) { - offsetY = -child.preferredSize.height - lineHeight; + final double systemKeyboardTop = screenSize.height - mediaQuery.viewInsets.bottom; + final double effectiveBottom = min(overlayBottomY, systemKeyboardTop); + + // 计算光标所在行下方的可用高度,并预留 4.0 像素防顶边距 + const double safetyMargin = 4.0; + final double availableHeight = effectiveBottom - position.dy - safetyMargin; + + // 显示位置坚决锁定在当前行下方,绝不在光标上方翻转显示 + const double offsetY = 0.0; + + // 高度自适应:如果顶到了小键盘,那么高度变小,剩余项在内部滑动 + final double desiredHeight = child.preferredSize.height; + const double minSensibleHeight = 44.0; + final double finalHeight; + if (availableHeight < desiredHeight) { + finalHeight = max(minSensibleHeight, availableHeight); } else { - offsetY = 0; + finalHeight = desiredHeight; } + return CompositedTransformFollower( - link: layerLink, + link: _layerLink!, showWhenUnlinked: false, offset: Offset(offsetX, offsetY), child: Align( alignment: Alignment.topLeft, child: Material( color: Colors.transparent, - child: TapRegion( - onTapOutside: (event) { - dismiss(); - }, - child: CodeEditorTapRegion( - child: ExcludeSemantics( + child: CodeEditorTapRegion( + child: ExcludeSemantics( + child: SizedBox( + key: _menuKey, + width: child.preferredSize.width, + height: finalHeight, child: child, - ) + ), ) ), ) diff --git a/packages/re_editor/lib/src/_code_editable.dart b/packages/re_editor/lib/src/_code_editable.dart index 140bb4b..f0eea7c 100644 --- a/packages/re_editor/lib/src/_code_editable.dart +++ b/packages/re_editor/lib/src/_code_editable.dart @@ -401,10 +401,17 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli return; } widget.onChanged?.call(widget.controller.value); + final isTextChanged = widget.controller.codeLines != widget.controller.preValue?.codeLines; if (widget.controller.codeLines != widget.controller.preValue?.codeLines && widget.controller.preValue != null) { widget.selectionOverlayController.hideHandle(); widget.selectionOverlayController.hideToolbar(); + } + if (isTextChanged) { + // 文本发生变更(包括输入字符与退格删除字符),触发补全提示列表自适应重算与刷新 + Future.delayed(const Duration(milliseconds: 50), () { + _updateAutoCompleteState(true); + }); } else { _updateAutoCompleteState(false); } @@ -473,7 +480,11 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli return; } if (!isCodeLineChanged) { - autocompleteState.dismiss(); + if (!widget.controller.selection.isCollapsed || + (widget.controller.preValue != null && + widget.controller.selection.extentIndex != widget.controller.preValue!.selection.extentIndex)) { + autocompleteState.dismiss(); + } return; } if (widget.controller.isComposing || !widget.controller.selection.isCollapsed) { @@ -514,6 +525,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli class _CodeCursorBlinkController extends ValueNotifier { Timer? _timer; + bool _isDisposed = false; _CodeCursorBlinkController() : super(false); @@ -525,10 +537,14 @@ class _CodeCursorBlinkController extends ValueNotifier { if (kIsAndroid || kIsIOS) { // Wait selection position to update Future.delayed(const Duration(milliseconds: 100), () { - value = true; + if (!_isDisposed) { + value = true; + } }); } else { - value = true; + if (!_isDisposed) { + value = true; + } } } @@ -538,15 +554,20 @@ class _CodeCursorBlinkController extends ValueNotifier { } _timer?.cancel(); _timer = null; - value = false; + if (!_isDisposed) { + value = false; + } } void _cursorTick(Timer timer) { - value = !value; + if (!_isDisposed) { + value = !value; + } } @override void dispose() { + _isDisposed = true; stopBlink(); super.dispose(); } diff --git a/packages/re_editor/lib/src/_code_field.dart b/packages/re_editor/lib/src/_code_field.dart index 6a9135d..9a96147 100644 --- a/packages/re_editor/lib/src/_code_field.dart +++ b/packages/re_editor/lib/src/_code_field.dart @@ -1484,12 +1484,8 @@ class _CodeFieldRender extends RenderBox implements MouseTrackerAnnotation { } void _drawHandleLayer(PaintingContext context, LayerLink layer, Offset position, Offset offset) { - final Offset point = Offset( - clampDouble(position.dx, 0.0, size.width), - clampDouble(position.dy, 0.0, size.height), - ); context.pushLayer( - LeaderLayer(link: layer, offset: point + offset), + LeaderLayer(link: layer, offset: position + offset), super.paint, Offset.zero, ); diff --git a/packages/re_editor/lib/src/_code_indicator.dart b/packages/re_editor/lib/src/_code_indicator.dart index 4393f41..18d2cc7 100644 --- a/packages/re_editor/lib/src/_code_indicator.dart +++ b/packages/re_editor/lib/src/_code_indicator.dart @@ -9,7 +9,8 @@ class CodeLineNumberRenderObject extends RenderBox { int _minNumberCount; int _allLineCount; - final String Function(int lineIndex)? _customLineIndex2Text; + String Function(int lineIndex)? _customLineIndex2Text; + Decoration? Function(int lineIndex)? _lineDecorationBuilder; final TextPainter _textPainter; CodeLineNumberRenderObject({ @@ -19,6 +20,7 @@ class CodeLineNumberRenderObject extends RenderBox { required TextStyle focusedTextStyle, required int minNumberCount, String Function(int lineIndex)? custonLineIndex2Text, + Decoration? Function(int lineIndex)? lineDecorationBuilder, }) : _controller = controller, _notifier = notifier, _textStyle = textStyle, @@ -26,6 +28,7 @@ class CodeLineNumberRenderObject extends RenderBox { _minNumberCount = minNumberCount, _allLineCount = controller.lineCount, _customLineIndex2Text = custonLineIndex2Text, + _lineDecorationBuilder = lineDecorationBuilder, _textPainter = TextPainter( textDirection: TextDirection.ltr, ); @@ -82,6 +85,22 @@ class CodeLineNumberRenderObject extends RenderBox { markNeedsLayout(); } + set customLineIndex2Text(String Function(int lineIndex)? value) { + if (_customLineIndex2Text == value) { + return; + } + _customLineIndex2Text = value; + markNeedsPaint(); + } + + set lineDecorationBuilder(Decoration? Function(int lineIndex)? value) { + if (_lineDecorationBuilder == value) { + return; + } + _lineDecorationBuilder = value; + markNeedsPaint(); + } + @override bool hitTestSelf(Offset position) => true; @@ -136,6 +155,19 @@ class CodeLineNumberRenderObject extends RenderBox { int firstLineIndex = _controller.index2lineIndex(value.paragraphs.first.index); for (final CodeLineRenderParagraph paragraph in value.paragraphs) { final lineIndexText = _customLineIndex2Text?.call(firstLineIndex) ?? (firstLineIndex + 1).toString(); + + final decoration = _lineDecorationBuilder?.call(firstLineIndex); + if (decoration != null) { + final painter = decoration.createBoxPainter(markNeedsPaint); + final lineRect = Rect.fromLTWH( + offset.dx, + offset.dy + paragraph.offset.dy, + size.width, + paragraph.preferredLineHeight, + ); + painter.paint(canvas, lineRect.topLeft, ImageConfiguration(size: lineRect.size)); + } + _textPainter.text = TextSpan( text: lineIndexText, style: paragraph.index == value.focusedIndex ? _focusedTextStyle : _textStyle diff --git a/packages/re_editor/lib/src/_code_line.dart b/packages/re_editor/lib/src/_code_line.dart index 1ad82d6..92f8311 100644 --- a/packages/re_editor/lib/src/_code_line.dart +++ b/packages/re_editor/lib/src/_code_line.dart @@ -30,20 +30,24 @@ class _CodeLineEditingControllerImpl extends ValueNotifier } factory _CodeLineEditingControllerImpl.fromText(String? text, [ - CodeLineOptions options = const CodeLineOptions() + CodeLineOptions options = const CodeLineOptions(), + CodeLineSpanBuilder? spanBuilder, ]) { return _CodeLineEditingControllerImpl( codeLines: text?.codeLines ?? _kInitialCodeLines, - options: options + options: options, + spanBuilder: spanBuilder, ); } factory _CodeLineEditingControllerImpl.fromTextAsync(String? text, [ - CodeLineOptions options = const CodeLineOptions() + CodeLineOptions options = const CodeLineOptions(), + CodeLineSpanBuilder? spanBuilder, ]) { final _CodeLineEditingControllerImpl controller = _CodeLineEditingControllerImpl( codeLines: _kInitialCodeLines, - options: options + options: options, + spanBuilder: spanBuilder, ); if (text != null && text.isNotEmpty) { text.codeLinesAsync.then((value) => controller.codeLines = value); diff --git a/packages/re_editor/lib/src/code_autocomplete.dart b/packages/re_editor/lib/src/code_autocomplete.dart index 4e924c6..5a74f71 100644 --- a/packages/re_editor/lib/src/code_autocomplete.dart +++ b/packages/re_editor/lib/src/code_autocomplete.dart @@ -229,7 +229,7 @@ typedef CodeAutocompleteWidgetBuilder = PreferredSizeWidget Function( abstract class CodeAutocompletePromptsBuilder { /// Build the prompts with the current code. - CodeAutocompleteEditingValue? build( + FutureOr build( BuildContext context, CodeLine codeLine, CodeLineSelection selection, diff --git a/packages/re_editor/lib/src/code_indicator.dart b/packages/re_editor/lib/src/code_indicator.dart index 63fc81a..52edc6b 100644 --- a/packages/re_editor/lib/src/code_indicator.dart +++ b/packages/re_editor/lib/src/code_indicator.dart @@ -53,6 +53,7 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget { final TextStyle? focusedTextStyle; final int? minNumberCount; final String Function(int lineIndex)? customLineIndex2Text; + final Decoration? Function(int lineIndex)? lineDecorationBuilder; const DefaultCodeLineNumber({ super.key, @@ -62,6 +63,7 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget { this.focusedTextStyle, this.minNumberCount, this.customLineIndex2Text, + this.lineDecorationBuilder, }); @override @@ -72,6 +74,7 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget { focusedTextStyle: focusedTextStyle ?? _useCodeTextStyle(context, true), minNumberCount: minNumberCount ?? _kDefaultMinNumberCount, custonLineIndex2Text: customLineIndex2Text, + lineDecorationBuilder: lineDecorationBuilder, ); @override @@ -81,7 +84,9 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget { ..notifier = notifier ..textStyle = textStyle ?? _useCodeTextStyle(context, false) ..focusedTextStyle = focusedTextStyle ?? _useCodeTextStyle(context, true) - ..minNumberCount = minNumberCount ?? _kDefaultMinNumberCount; + ..minNumberCount = minNumberCount ?? _kDefaultMinNumberCount + ..customLineIndex2Text = customLineIndex2Text + ..lineDecorationBuilder = lineDecorationBuilder; super.updateRenderObject(context, renderObject); } diff --git a/packages/re_editor/lib/src/code_line.dart b/packages/re_editor/lib/src/code_line.dart index 4f7d107..d949ff6 100644 --- a/packages/re_editor/lib/src/code_line.dart +++ b/packages/re_editor/lib/src/code_line.dart @@ -61,13 +61,15 @@ abstract class CodeLineEditingController extends ValueNotifier _CodeLineEditingControllerImpl.fromText(text, options); + CodeLineOptions options = const CodeLineOptions(), + CodeLineSpanBuilder? spanBuilder, + ]) => _CodeLineEditingControllerImpl.fromText(text, options, spanBuilder); /// Creates a controller for a given file path. The file content will read async. factory CodeLineEditingController.fromTextAsync(String? text, [ - CodeLineOptions options = const CodeLineOptions() - ]) => _CodeLineEditingControllerImpl.fromTextAsync(text, options); + CodeLineOptions options = const CodeLineOptions(), + CodeLineSpanBuilder? spanBuilder, + ]) => _CodeLineEditingControllerImpl.fromTextAsync(text, options, spanBuilder); /// Set the current editor codes. /// diff --git a/test/archive_extractor_test.dart b/test/archive_extractor_test.dart index fea1eb9..0ce2ed9 100644 --- a/test/archive_extractor_test.dart +++ b/test/archive_extractor_test.dart @@ -6,7 +6,12 @@ import 'package:path/path.dart' as p; import 'package:code_editor/services/archive_extractor.dart'; import 'package:code_editor/services/internal_project_service.dart'; -import 'distro_image_resolver_test.dart'; // 借用 encodeValidXz +/// 构造包含合法 XZ 头的字节流用于测试 +List encodeValidXz(List payload) { + // 最小合法 XZ 流结构 (Stream Header + Filter Flags + Data + Footer) + final xzEncoded = XZEncoder().encode(payload); + return xzEncoded; +} void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/test/background_task_scheduler_test.dart b/test/background_task_scheduler_test.dart new file mode 100644 index 0000000..31d4933 --- /dev/null +++ b/test/background_task_scheduler_test.dart @@ -0,0 +1,142 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/models/notice_item.dart'; +import 'package:code_editor/providers/notice_center.dart'; +import 'package:code_editor/services/background_task/background_task.dart'; +import 'package:code_editor/services/background_task/background_task_scheduler.dart'; +import 'package:code_editor/services/background_task/generic_background_task.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('BackgroundTaskScheduler Tests', () { + late NoticeCenter noticeCenter; + late BackgroundTaskScheduler scheduler; + + setUp(() { + noticeCenter = NoticeCenter(); + scheduler = BackgroundTaskScheduler.instance; + scheduler.attachNoticeCenter(noticeCenter); + }); + + test('packageManager scope tasks are executed sequentially without race conditions', () async { + final executionOrder = []; + final activePackageManagerTasks = []; + var maxConcurrentPackageManager = 0; + + Future runTask(String id, Duration duration) async { + activePackageManagerTasks.add(id); + if (activePackageManagerTasks.length > maxConcurrentPackageManager) { + maxConcurrentPackageManager = activePackageManagerTasks.length; + } + await Future.delayed(duration); + executionOrder.add(id); + activePackageManagerTasks.remove(id); + return true; + } + + final task1 = GenericBackgroundTask( + id: 'pkg1', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + runner: (_) => runTask('pkg1', const Duration(milliseconds: 50)), + ); + + final task2 = GenericBackgroundTask( + id: 'pkg2', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + runner: (_) => runTask('pkg2', const Duration(milliseconds: 20)), + ); + + final future1 = scheduler.submit(task1); + final future2 = scheduler.submit(task2); + + await Future.wait([future1, future2]); + + expect(maxConcurrentPackageManager, 1); + expect(executionOrder, ['pkg1', 'pkg2']); + }); + + test('Higher priority task jumps queue ahead of lower priority queued tasks', () async { + final executionOrder = []; + + // 先占住 packageManager 锁 + final blocker = GenericBackgroundTask( + id: 'blocker', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + runner: (_) async { + await Future.delayed(const Duration(milliseconds: 60)); + executionOrder.add('blocker'); + return true; + }, + ); + + final lowPriority = GenericBackgroundTask( + id: 'low', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + runner: (_) async { + executionOrder.add('low'); + return true; + }, + ); + + final highPriority = GenericBackgroundTask( + id: 'high', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.userInitiated, + runner: (_) async { + executionOrder.add('high'); + return true; + }, + ); + + final fBlocker = scheduler.submit(blocker); + // 两个在 blocker 执行期间进入排队 + final fLow = scheduler.submit(lowPriority); + final fHigh = scheduler.submit(highPriority); + + await Future.wait([fBlocker, fLow, fHigh]); + + expect(executionOrder, ['blocker', 'high', 'low']); + }); + + test('Task cancellation removes queued task and notifies NoticeCenter', () async { + // blocker + final blocker = GenericBackgroundTask( + id: 'blocker2', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + runner: (_) => Future.delayed(const Duration(milliseconds: 50), () => true), + ); + + final target = GenericBackgroundTask( + id: 'to_cancel', + scope: TaskExecutionScope.packageManager, + priority: TaskPriority.projectLifecycle, + showNotice: true, + noticeTextBuilder: (state, {detail, error}) => const ComponentInstallPhaseText( + componentName: 'test', + isQueued: true, + ), + runner: (_) async => true, + ); + + final fBlocker = scheduler.submit(blocker); + final fTarget = scheduler.submit(target); + + expect(noticeCenter.visible.any((e) => e.id == 'to_cancel'), isTrue); + + scheduler.cancel('to_cancel'); + + expect(fTarget, throwsA(isA())); + // dismiss 后卡片被标记为 removing(等待 UI 播放退场动画) + expect(noticeCenter.removingIds.contains('to_cancel'), isTrue); + noticeCenter.finalizeDismiss('to_cancel'); + expect(noticeCenter.visible.any((e) => e.id == 'to_cancel'), isFalse); + + await fBlocker; + }); + }); +} diff --git a/test/code_autocomplete_adaptive_test.dart b/test/code_autocomplete_adaptive_test.dart new file mode 100644 index 0000000..6e284ee --- /dev/null +++ b/test/code_autocomplete_adaptive_test.dart @@ -0,0 +1,206 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/widgets/code_autocomplete_view.dart'; +import 'package:re_editor/re_editor.dart'; + +void main() { + group('CodeAutocomplete Adaptive Height and Scrolling Tests', () { + test('CodeAutocompleteView preferredSize dynamically adapts to prompt count', () { + final notifier = ValueNotifier( + const CodeAutocompleteEditingValue( + input: '', + prompts: [ + CodeKeywordPrompt(word: 'first'), + ], + index: 0, + ), + ); + + final view1 = CodeAutocompleteView( + notifier: notifier, + onSelected: (_) {}, + ); + + // 1 item: 1 * 36.0 + 8.0 + 2.0 = 46.0 + expect(view1.preferredSize.height, equals(46.0)); + + // 2 items: 2 * 36.0 + 10.0 = 82.0 + notifier.value = const CodeAutocompleteEditingValue( + input: '', + prompts: [ + CodeKeywordPrompt(word: 'first'), + CodeKeywordPrompt(word: 'second'), + ], + index: 0, + ); + final view2 = CodeAutocompleteView( + notifier: notifier, + onSelected: (_) {}, + ); + expect(view2.preferredSize.height, equals(82.0)); + + // 3 items: 3 * 36.0 + 10.0 = 118.0 + notifier.value = const CodeAutocompleteEditingValue( + input: '', + prompts: [ + CodeKeywordPrompt(word: 'first'), + CodeKeywordPrompt(word: 'second'), + CodeKeywordPrompt(word: 'third'), + ], + index: 0, + ); + final view3 = CodeAutocompleteView( + notifier: notifier, + onSelected: (_) {}, + ); + expect(view3.preferredSize.height, equals(118.0)); + + // 10 items capped at default max height 196.0 + notifier.value = CodeAutocompleteEditingValue( + input: '', + prompts: List.generate(10, (i) => CodeKeywordPrompt(word: 'item_$i')), + index: 0, + ); + final view10 = CodeAutocompleteView( + notifier: notifier, + onSelected: (_) {}, + ); + expect(view10.preferredSize.height, equals(196.0)); + + notifier.dispose(); + }); + + testWidgets('CodeAutocompleteView scrolls smoothly when constrained in limited height', (tester) async { + final notifier = ValueNotifier( + const CodeAutocompleteEditingValue( + input: '', + prompts: [ + CodeKeywordPrompt(word: 'option_1'), + CodeKeywordPrompt(word: 'option_2'), + CodeKeywordPrompt(word: 'option_3'), + ], + index: 0, + ), + ); + + String? selectedWord; + + // 空间不足:强制限制高度为 80.0(只能完整显示约 2 项,第 3 项需要滑动) + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: SizedBox( + width: 270.0, + height: 80.0, + child: CodeAutocompleteView( + notifier: notifier, + onSelected: (result) { + selectedWord = (result as dynamic).word as String?; + }, + ), + ), + ), + ), + ), + ); + + expect(find.text('option_1'), findsOneWidget); + expect(find.text('option_2'), findsOneWidget); + + // 模拟选择第 3 个项目,触发自动滚动 + notifier.value = notifier.value.copyWith(index: 2); + await tester.pumpAndSettle(); + + // 滑动或选择后,第 3 项可见且可点击 + expect(find.text('option_3'), findsOneWidget); + await tester.tap(find.text('option_3')); + await tester.pump(); + + expect(selectedWord, equals('option_3')); + + await tester.pumpWidget(const SizedBox()); + notifier.dispose(); + }); + + testWidgets('Autocomplete does not dismiss on scrolling or operating virtual keyboard, only on tapping editor outside menu', (tester) async { + final controller = CodeLineEditingController.fromText('foo\nbar\nbaz'); + final promptsBuilder = DefaultCodeAutocompletePromptsBuilder( + directPrompts: [ + const CodeKeywordPrompt(word: 'foo_item1'), + const CodeKeywordPrompt(word: 'foo_item2'), + ], + ); + + bool virtualKeyPressed = false; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + Expanded( + child: CodeAutocomplete( + viewBuilder: (context, notifier, onSelected) { + return CodeAutocompleteView( + notifier: notifier, + onSelected: onSelected, + ); + }, + promptsBuilder: promptsBuilder, + child: CodeEditor( + controller: controller, + ), + ), + ), + GestureDetector( + key: const ValueKey('mock_virtual_keyboard'), + onTap: () { + virtualKeyPressed = true; + }, + child: Container( + height: 50, + width: double.infinity, + color: Colors.grey, + child: const Text('Virtual Keyboard Key'), + ), + ), + ], + ), + ), + ), + ); + + // 输入触发补全 + controller.text = 'fo'; + controller.selection = const CodeLineSelection.collapsed(index: 0, offset: 2); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(find.byType(CodeAutocompleteView), findsOneWidget); + + // 1. 操作小键盘控件:不应关闭菜单 + await tester.tap(find.byKey(const ValueKey('mock_virtual_keyboard'))); + await tester.pump(); + expect(virtualKeyPressed, isTrue); + expect(find.byType(CodeAutocompleteView), findsOneWidget); + + // 2. 滑动编辑区:上下滑动拖动代码,不应关闭菜单 + final editorFinder = find.byType(CodeEditor); + await tester.drag(editorFinder, const Offset(0, -60)); + await tester.pump(); + expect(find.byType(CodeAutocompleteView), findsOneWidget); + + // 3. 只有点击到菜单区域外的编辑区,才关闭菜单 + final editorTopLeft = tester.getTopLeft(editorFinder); + await tester.tapAt(editorTopLeft + const Offset(50, 150)); + await tester.pump(); + expect(find.byType(CodeAutocompleteView), findsNothing); + + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(milliseconds: 600)); + controller.dispose(); + }); + }); +} diff --git a/test/completion_pipeline_test.dart b/test/completion_pipeline_test.dart new file mode 100644 index 0000000..b2b72f1 --- /dev/null +++ b/test/completion_pipeline_test.dart @@ -0,0 +1,213 @@ +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/services/code_completion/smart_prompts_builder.dart'; +import 'package:code_editor/services/lsp/lsp_protocol.dart'; +import 'package:code_editor/widgets/editor/editor_diagnostic_controller.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:re_editor/re_editor.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _MockAsyncProvider implements CompletionProvider { + final List results; + _MockAsyncProvider(this.results); + + @override + String get id => 'mock_async'; + + @override + bool get isAsync => true; + + @override + Future> provideCompletions(CompletionContext context) async { + await Future.delayed(const Duration(milliseconds: 10)); + return results; + } + + @override + void dispose() {} +} + +void main() { + group('Completion Pipeline Architecture Tests', () { + test('LspCompletionProvider.fromLspItem maps kinds and details correctly', () { + final lspItem = LspCompletionItem( + label: 'printf', + kind: 3, // Function + detail: 'int printf(const char *format, ...)', + insertText: 'printf', + ); + + final prompt = LspCompletionProvider.fromLspItem(lspItem); + expect(prompt.word, equals('printf')); + expect(prompt.kind, equals(SmartPromptKind.function)); + expect(prompt.type, equals('int printf(const char *format, ...)')); + }); + + test('CompletionEngine.requestCompletionsAsync directly resolves LSP completions with fuzzy score & sorting', () async { + final asyncLsp = _MockAsyncProvider([ + SmartPrompt( + word: 'printf', + kind: SmartPromptKind.function, + type: 'int printf(const char *format, ...)', + sortText: '0001', + ), + SmartPrompt( + word: 'print_custom', + kind: SmartPromptKind.function, + sortText: '0002', + ), + ]); + + final engine = CompletionEngine(providers: [asyncLsp]); + + final ctx = CompletionContext( + input: 'pri', + lineIndex: 0, + characterOffset: 3, + codeLine: const CodeLine('pri'), + selection: const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3), + ); + + final result = await engine.requestCompletionsAsync(ctx); + expect(result, isNotNull); + expect(result!.prompts, isNotEmpty); + expect(result.prompts.first.word, equals('printf')); + expect((result.prompts.first as SmartPrompt).type, equals('int printf(const char *format, ...)')); + expect(result.prompts.map((p) => p.word), contains('print_custom')); + }); + + test('CompletionEngine drops stale request when new request is initiated', () async { + final asyncLsp = _MockAsyncProvider([ + SmartPrompt( + word: 'printf', + kind: SmartPromptKind.function, + ), + ]); + + final engine = CompletionEngine(providers: [asyncLsp]); + + final ctx1 = CompletionContext( + input: 'p', + lineIndex: 0, + characterOffset: 1, + codeLine: const CodeLine('p'), + selection: const CodeLineSelection(baseIndex: 0, baseOffset: 1, extentIndex: 0, extentOffset: 1), + ); + + final ctx2 = CompletionContext( + input: 'pr', + lineIndex: 0, + characterOffset: 2, + codeLine: const CodeLine('pr'), + selection: const CodeLineSelection(baseIndex: 0, baseOffset: 2, extentIndex: 0, extentOffset: 2), + ); + + // 发起两次连续请求,前一次会被后一次作为陈旧请求丢弃 + final future1 = engine.requestCompletionsAsync(ctx1); + final future2 = engine.requestCompletionsAsync(ctx2); + + final res1 = await future1; + final res2 = await future2; + + expect(res1, isNull); // 过期响应返回 null + expect(res2, isNotNull); // 最新响应正常返回 + }); + }); + + group('EditorDiagnosticController Tests', () { + testWidgets('EditorDiagnosticController returns base span when no diagnostics exist', (tester) async { + late BuildContext ctx; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (c) { + ctx = c; + return const SizedBox(); + }, + ), + ), + ); + + const controller = EditorDiagnosticController(); + const baseSpan = TextSpan(text: 'int main() {}'); + final result = controller.buildDiagnosticSpans( + context: ctx, + filePath: 'test.c', + index: 0, + codeLine: const CodeLine('int main() {}'), + textSpan: baseSpan, + style: const TextStyle(), + ); + + expect(result.text, equals('int main() {}')); + }); + }); + + group('Completion Switch & Isolation Tests', () { + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + test('SettingsProvider lsp completion flag persists properly', () async { + final provider = SettingsProvider(); + await provider.init(); + + expect(provider.enableLspCompletion, isTrue); + + await provider.setEnableLspCompletion(false); + expect(provider.enableLspCompletion, isFalse); + + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getBool('enable_lsp_completion'), isFalse); + + // 重新实例化验证从持久化中正确恢复 + final restoredProvider = SettingsProvider(); + await restoredProvider.init(); + expect(restoredProvider.enableLspCompletion, isFalse); + }); + + test('SmartCodeAutocompletePromptsBuilder provider filtering by flag', () { + // 1. 默认开启:仅 1 个 LspCompletionProvider + final builderDefault = SmartCodeAutocompletePromptsBuilder(); + expect(builderDefault.engine.providers.length, equals(1)); + expect(builderDefault.engine.providers.first, isA()); + + // 2. 关闭 LSP:providers 为空 + final builderDisabled = SmartCodeAutocompletePromptsBuilder( + enableLspCompletion: false, + ); + expect(builderDisabled.engine.providers.isEmpty, isTrue); + }); + + test('Pure Backend Mode: SmartCodeAutocompletePromptsBuilder.build returns Future that resolves LSP completions', () async { + final asyncLsp = _MockAsyncProvider([ + SmartPrompt( + word: 'printf', + kind: SmartPromptKind.function, + type: 'int printf(const char *format, ...)', + ), + ]); + + final builder = SmartCodeAutocompletePromptsBuilder( + customProviders: [asyncLsp], + ); + + final result = builder.build( + _FakeBuildContext(), + const CodeLine('pri'), + const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3), + ); + + expect(result, isA>()); + final resolved = await (result as Future); + expect(resolved, isNotNull); + expect(resolved!.prompts.length, equals(1)); + final prompt = resolved.prompts.first as SmartPrompt; + expect(prompt.word, equals('printf')); + expect(prompt.type, equals('int printf(const char *format, ...)')); + }); + }); +} + +class _FakeBuildContext extends Fake implements BuildContext {} diff --git a/test/distro_image_resolver_test.dart b/test/distro_image_resolver_test.dart deleted file mode 100644 index d3f0ceb..0000000 --- a/test/distro_image_resolver_test.dart +++ /dev/null @@ -1,401 +0,0 @@ -import 'dart:convert'; -import 'dart:io'; -import 'dart:typed_data'; -import 'package:archive/archive.dart'; -import 'package:code_editor/models/distro_manifest.dart'; -import 'package:code_editor/services/distro_image_resolver.dart'; -import 'package:code_editor/services/distro_installer.dart'; -import 'package:code_editor/services/low_memory_xz_decoder.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - const sampleIndexSystem = ''' -# LXC Images Mirror index -debian;bookworm;arm64;default;20260912_05:24;/images/debian/bookworm/arm64/default/20260912_05:24/ -debian;bookworm;arm64;default;20260913_05:24;/images/debian/bookworm/arm64/default/20260913_05:24/ -debian;bookworm;amd64;default;20260913_05:24;/images/debian/bookworm/amd64/default/20260913_05:24/ -archlinux;current;arm64;default;20260913_04:18;/images/archlinux/current/arm64/default/20260913_04:18/ -archlinux;current;amd64;default;20260913_04:18;/images/archlinux/current/amd64/default/20260913_04:18/ -fedora;43;arm64;default;20260913_20:33;/images/fedora/43/arm64/default/20260913_20:33/ -fedora;43;amd64;default;20260913_20:33;/images/fedora/43/amd64/default/20260913_20:33/ -'''; - - group('DistroIndexEntry & DistroImageResolver Tests', () { - late DistroImageResolver resolver; - - setUp(() { - resolver = DistroImageResolver(); - resolver.invalidateCache(); - resolver.customIndexContent = sampleIndexSystem; - }); - - tearDown(() { - resolver.customIndexContent = null; - resolver.invalidateCache(); - }); - - test('parseIndex extracts all valid entries', () { - final entries = DistroImageResolver.parseIndex(sampleIndexSystem); - expect(entries.length, 7); - expect(entries.first.distribution, 'debian'); - expect(entries.first.release, 'bookworm'); - expect(entries.first.arch, 'arm64'); - expect(entries.first.variant, 'default'); - expect(entries.first.buildDate, '20260912_05:24'); - expect(entries.first.path, '/images/debian/bookworm/arm64/default/20260912_05:24/'); - }); - - test('toLxcArch maps arm64 and x86_64 correctly', () { - expect(DistroImageResolver.toLxcArch(DistroArch.arm64), 'arm64'); - expect(DistroImageResolver.toLxcArch(DistroArch.x86_64), 'amd64'); - }); - - test('resolveDownloadUrl picks latest build date for debian arm64', () async { - final debian = DistroRepository.getById('debian')!; - final tsinghua = DistroRepository.getMirrorById('tsinghua'); - - final url = await resolver.resolveDownloadUrl( - item: debian, - arch: DistroArch.arm64, - mirror: tsinghua, - ); - - // 应该选择 20260913_05:24 而不是旧的 20260912_05:24 - expect( - url, - 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/20260913_05:24/rootfs.tar.xz', - ); - }); - - test('resolveDownloadUrl resolves archlinux on different mirrors', () async { - final arch = DistroRepository.getById('arch')!; - final bfsu = DistroRepository.getMirrorById('bfsu'); - - final url = await resolver.resolveDownloadUrl( - item: arch, - arch: DistroArch.x86_64, - mirror: bfsu, - ); - - expect( - url, - 'https://mirrors.bfsu.edu.cn/lxc-images/images/archlinux/current/amd64/default/20260913_04:18/rootfs.tar.xz', - ); - }); - - test('resolveDownloadUrl resolves fedora 43 arm64', () async { - final fedora = DistroRepository.getById('fedora')!; - final iscas = DistroRepository.getMirrorById('iscas'); - - final url = await resolver.resolveDownloadUrl( - item: fedora, - arch: DistroArch.arm64, - mirror: iscas, - ); - - expect( - url, - 'https://mirror.iscas.ac.cn/lxc-images/images/fedora/43/arm64/default/20260913_20:33/rootfs.tar.xz', - ); - }); - - test('resolveDownloadUrl throws HttpException when image is not in index', () async { - const emptyIndex = '# Empty index\n'; - resolver.customIndexContent = emptyIndex; - - final debian = DistroRepository.getById('debian')!; - final tsinghua = DistroRepository.getMirrorById('tsinghua'); - - expect( - () => resolver.resolveDownloadUrl( - item: debian, - arch: DistroArch.arm64, - mirror: tsinghua, - ), - throwsA(isA()), - ); - }); - - test('resolveDownloadUrl returns builtin asset path directly for builtin distro', () async { - final alpine = DistroRepository.getById('alpine')!; - final tsinghua = DistroRepository.getMirrorById('tsinghua'); - - final url = await resolver.resolveDownloadUrl( - item: alpine, - arch: DistroArch.arm64, - mirror: tsinghua, - ); - - expect(url, 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz'); - }); - }); - - group('DistroInstaller Archive Decoding Tests', () { - test('installFromBytes succeeds with valid TarGz archive bytes', () async { - // 创建包含一个测试文件的 TarGz 内存包 - final archive = Archive(); - archive.addFile(ArchiveFile('test.txt', 5, utf8.encode('hello'))); - final tarBytes = TarEncoder().encode(archive); - final gzBytes = Uint8List.fromList(GZipEncoder().encode(tarBytes)!); - - final tempDir = Directory.systemTemp.createTempSync('installer_test_'); - try { - await DistroInstaller.installFromBytes( - tarGzBytes: gzBytes, - targetDir: tempDir, - ); - - final testFile = File('${tempDir.path}/test.txt'); - expect(testFile.existsSync(), isTrue); - expect(testFile.readAsStringSync(), 'hello'); - } finally { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - } - }); - - test('installFromBytes succeeds with valid TarXZ archive bytes', () async { - // 创建包含一个测试文件的 TarXZ 内存包 - final archive = Archive(); - archive.addFile(ArchiveFile('greet.txt', 5, utf8.encode('world'))); - final tarBytes = TarEncoder().encode(archive); - final xzBytes = encodeValidXz(tarBytes); - - final tempDir = Directory.systemTemp.createTempSync('installer_xz_test_'); - try { - await DistroInstaller.installFromBytes( - tarGzBytes: xzBytes, - targetDir: tempDir, - ); - - final testFile = File('${tempDir.path}/greet.txt'); - expect(testFile.existsSync(), isTrue); - expect(testFile.readAsStringSync(), 'world'); - } finally { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - } - }); - - test('installFromFile directly extracts TarXZ file on disk', () async { - final archive = Archive(); - archive.addFile(ArchiveFile('direct.txt', 6, utf8.encode('direct'))); - final tarBytes = TarEncoder().encode(archive); - final xzBytes = encodeValidXz(tarBytes); - - final tempDir = Directory.systemTemp.createTempSync('installer_file_test_'); - final archiveFile = File('${tempDir.path}/test.tar.xz'); - archiveFile.writeAsBytesSync(xzBytes); - - final outDir = Directory('${tempDir.path}/rootfs'); - try { - await DistroInstaller.installFromFile( - archiveFile: archiveFile, - targetDir: outDir, - ); - - final testFile = File('${outDir.path}/direct.txt'); - expect(testFile.existsSync(), isTrue); - expect(testFile.readAsStringSync(), 'direct'); - } finally { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - } - }); - - test('installFromFile cancellation throws DistroInstallCancelledException and rolls back targetDir', () async { - final archive = Archive(); - archive.addFile(ArchiveFile('cancel.txt', 6, utf8.encode('cancel'))); - final tarBytes = TarEncoder().encode(archive); - final xzBytes = encodeValidXz(tarBytes); - - final tempDir = Directory.systemTemp.createTempSync('installer_cancel_test_'); - final archiveFile = File('${tempDir.path}/test.tar.xz'); - archiveFile.writeAsBytesSync(xzBytes); - - final outDir = Directory('${tempDir.path}/rootfs'); - try { - expect( - () => DistroInstaller.installFromFile( - archiveFile: archiveFile, - targetDir: outDir, - isCancelled: () => true, - ), - throwsA(isA()), - ); - - // 验证回滚:目标目录不残留 - expect(outDir.existsSync(), isFalse); - } finally { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - } - }); - - test('LowMemoryXZDecoder decodes valid XZ stream directly to sink', () async { - final inputBytes = utf8.encode('Low memory streaming XZ decoding test string! 1234567890'); - final xzBytes = encodeValidXz(inputBytes); - - final tempDir = Directory.systemTemp.createTempSync('low_mem_xz_test_'); - final outFile = File('${tempDir.path}/out.bin'); - final outSink = outFile.openWrite(); - - final decoder = LowMemoryXZDecoder(); - var progressFired = false; - try { - decoder.decodeToSink( - InputStream(xzBytes), - outSink, - onProgress: (decompressed, compPos) { - progressFired = true; - }, - ); - } finally { - await outSink.flush(); - await outSink.close(); - } - - expect(outFile.existsSync(), isTrue); - expect(outFile.readAsBytesSync(), inputBytes); - expect(progressFired, isTrue); - - tempDir.deleteSync(recursive: true); - }); - - test('installFromFile extracts multiple files, subdirectories and reports progress', () async { - final archive = Archive(); - archive.addFile(ArchiveFile('sub/dir/one.txt', 5, utf8.encode('one..'))); - archive.addFile(ArchiveFile('sub/dir/two.txt', 5, utf8.encode('two..'))); - archive.addFile(ArchiveFile('root.txt', 4, utf8.encode('root'))); - final tarBytes = TarEncoder().encode(archive); - final xzBytes = encodeValidXz(tarBytes); - - final tempDir = Directory.systemTemp.createTempSync('installer_multi_test_'); - final archiveFile = File('${tempDir.path}/distro.tar.xz'); - archiveFile.writeAsBytesSync(xzBytes); - - final outDir = Directory('${tempDir.path}/rootfs'); - final progressList = []; - - try { - await DistroInstaller.installFromFile( - archiveFile: archiveFile, - targetDir: outDir, - onProgress: (prog, msg) { - progressList.add(prog); - }, - ); - - expect(File('${outDir.path}/sub/dir/one.txt').readAsStringSync(), 'one..'); - expect(File('${outDir.path}/sub/dir/two.txt').readAsStringSync(), 'two..'); - expect(File('${outDir.path}/root.txt').readAsStringSync(), 'root'); - expect(progressList.isNotEmpty, isTrue); - expect(progressList.last, 1.0); - } finally { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - } - }); - }); -} - -/// 遵循标准 LEB128 与 XZ 格式的纯 Dart 辅助编码器(避免 archive 包中 XZEncoder 的多字节大端序 bug) -Uint8List encodeValidXz(List data) { - void writeLeb128(BytesBuilder out, int value) { - while (value >= 0x80) { - out.addByte((value & 0x7f) | 0x80); - value >>= 7; - } - out.addByte(value & 0x7f); - } - - final out = BytesBuilder(); - out.add([253, 55, 122, 88, 90, 0]); // Header magic - final headerFlags = [0, 0]; - out.add(headerFlags); - final headerCrc = getCrc32(headerFlags); - out.add([headerCrc & 0xff, (headerCrc >> 8) & 0xff, (headerCrc >> 16) & 0xff, (headerCrc >> 24) & 0xff]); - - final lzma2 = BytesBuilder(); - var offset = 0; - var isFirst = true; - while (offset < data.length) { - final chunkLen = (data.length - offset).clamp(1, 65536); - lzma2.addByte(isFirst ? 1 : 2); - isFirst = false; - final lenMinusOne = chunkLen - 1; - lzma2.addByte((lenMinusOne >> 8) & 0xff); - lzma2.addByte(lenMinusOne & 0xff); - lzma2.add(data.sublist(offset, offset + chunkLen)); - offset += chunkLen; - } - lzma2.addByte(0); // end marker - - final lzma2Bytes = lzma2.toBytes(); - - final filter = BytesBuilder(); - writeLeb128(filter, 0x21); // LZMA2 - writeLeb128(filter, 1); - filter.addByte(0); // dict size - - final filterBytes = filter.toBytes(); - final headerSizeWithoutCrc = 1 + 1 + filterBytes.length; - final paddingHeader = (4 - ((headerSizeWithoutCrc + 4) % 4)) % 4; - final totalHeaderSize = headerSizeWithoutCrc + paddingHeader + 4; - - final blockHeader = BytesBuilder(); - blockHeader.addByte((totalHeaderSize ~/ 4) - 1); - blockHeader.addByte(0); // flags - blockHeader.add(filterBytes); - for (var i = 0; i < paddingHeader; i++) { - blockHeader.addByte(0); - } - final bhBytes = blockHeader.toBytes(); - final bhCrc = getCrc32(bhBytes); - - final blockStart = out.length; - out.add(bhBytes); - out.add([bhCrc & 0xff, (bhCrc >> 8) & 0xff, (bhCrc >> 16) & 0xff, (bhCrc >> 24) & 0xff]); - out.add(lzma2Bytes); - - final paddingBlock = (4 - (out.length % 4)) % 4; - for (var i = 0; i < paddingBlock; i++) { - out.addByte(0); - } - - final unpaddedLength = out.length - blockStart - paddingBlock; - - final indexStart = out.length; - final index = BytesBuilder(); - index.addByte(0); // indicator - writeLeb128(index, 1); - writeLeb128(index, unpaddedLength); - writeLeb128(index, data.length); - while (index.length % 4 != 0) { - index.addByte(0); - } - final indexBytes = index.toBytes(); - final indexCrc = getCrc32(indexBytes); - out.add(indexBytes); - out.add([indexCrc & 0xff, (indexCrc >> 8) & 0xff, (indexCrc >> 16) & 0xff, (indexCrc >> 24) & 0xff]); - final indexTotalSize = out.length - indexStart; - - final footer = BytesBuilder(); - final indexSizeField = (indexTotalSize ~/ 4) - 1; - footer.add([indexSizeField & 0xff, (indexSizeField >> 8) & 0xff, (indexSizeField >> 16) & 0xff, (indexSizeField >> 24) & 0xff]); - footer.add([0, 0]); - final footerBytes = footer.toBytes(); - final footerCrc = getCrc32(footerBytes); - out.add([footerCrc & 0xff, (footerCrc >> 8) & 0xff, (footerCrc >> 16) & 0xff, (footerCrc >> 24) & 0xff]); - out.add(footerBytes); - out.add([89, 90]); // 'YZ' - - return out.toBytes(); -} diff --git a/test/distro_management_test.dart b/test/distro_management_test.dart deleted file mode 100644 index 81db168..0000000 --- a/test/distro_management_test.dart +++ /dev/null @@ -1,413 +0,0 @@ -import 'dart:async'; -import 'dart:io'; -import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/models/distro_manifest.dart'; -import 'package:code_editor/providers/distro_provider.dart'; -import 'package:code_editor/providers/settings_provider.dart'; -import 'package:code_editor/providers/terminal_provider.dart'; -import 'package:code_editor/services/distro_download_manager.dart'; -import 'package:code_editor/services/distro_manager.dart'; -import 'package:code_editor/views/distro_management_view.dart'; -import 'package:code_editor/views/settings_view.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:path/path.dart' as p; -import 'package:provider/provider.dart'; -import 'package:shared_preferences/shared_preferences.dart'; - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - late Directory tempBaseDir; - late DistroManager manager; - late DistroProvider distroProvider; - late DistroDownloadManager downloadManager; - late SettingsProvider settingsProvider; - - setUp(() { - SharedPreferences.setMockInitialValues({}); - tempBaseDir = Directory.systemTemp.createTempSync('distro_mgmt_test_'); - manager = DistroManager(); - manager.customBaseDir = tempBaseDir; - distroProvider = DistroProvider(); - settingsProvider = SettingsProvider(); - - downloadManager = DistroDownloadManager(); - downloadManager.customPackagesDir = tempBaseDir; - }); - - tearDown(() { - manager.customBaseDir = null; - downloadManager.customPackagesDir = null; - if (tempBaseDir.existsSync()) { - tempBaseDir.deleteSync(recursive: true); - } - }); - - Widget buildTestableWidget({ - required Widget child, - Locale locale = const Locale('zh'), - }) { - return MultiProvider( - providers: [ - ChangeNotifierProvider.value(value: settingsProvider), - ChangeNotifierProvider.value(value: distroProvider), - ChangeNotifierProvider(create: (_) => TerminalProvider()), - ], - child: MaterialApp( - localizationsDelegates: const [ - AppLocalizations.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [ - Locale('zh'), - Locale('en'), - ], - locale: locale, - home: child, - ), - ); - } - - group('DistroManifest & Repository Tests', () { - test('currentArchDistros only returns systems supported by current arch', () { - final items = DistroRepository.currentArchDistros; - expect(items, isNotEmpty); - - // 验证每个条目在当前架构下都有有效的包源 - for (final item in items) { - expect(item.currentPackageSource, isNotNull); - expect(item.currentPackageSource!.isNotEmpty, isTrue); - } - - // 验证内置系统的 isBuiltin 标识 - final ubuntu = items.firstWhere((e) => e.id == 'ubuntu'); - expect(ubuntu.isBuiltin, isTrue); - expect(ubuntu.isRecommended, isTrue); - - final alpine = items.firstWhere((e) => e.id == 'alpine'); - expect(alpine.isBuiltin, isTrue); - }); - - test('currentArch returns arm64 or x86_64 correctly', () { - final arch = DistroManifestItem.currentArch; - expect(arch == DistroArch.arm64 || arch == DistroArch.x86_64, isTrue); - }); - }); - - group('DistroDownloadManager Tests', () { - test('initial state has no active downloads', () { - final dm = DistroDownloadManager(); - expect(dm.isDownloading('unknown_distro'), isFalse); - expect(dm.getProgress('unknown_distro'), isNull); - }); - - test('package file detection and deletion', () async { - final dm = DistroDownloadManager(); - const distroId = 'debian'; - const fakeUrl = 'https://example.com/debian.tar.xz'; - - expect(await dm.isPackageDownloaded(distroId, fakeUrl), isFalse); - - final file = await dm.getPackageFile(distroId, fakeUrl); - file.writeAsStringSync('fake tar data'); - - expect(await dm.isPackageDownloaded(distroId, fakeUrl), isTrue); - - await dm.deletePackage(distroId, fakeUrl); - expect(await dm.isPackageDownloaded(distroId, fakeUrl), isFalse); - }); - - test('cancelDownload immediately stops background streaming, closes file sinks, and cleans up .part file', () async { - await HttpOverrides.runWithHttpOverrides(() async { - final dm = DistroDownloadManager(); - const distroId = 'test_cancel_distro'; - - // 启动一个本地 HTTP 服务器模拟网络流式下载 - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - final serverUrl = 'http://${server.address.address}:${server.port}/test_image.tar.xz'; - - final serverCompleter = Completer(); - - server.listen((HttpRequest request) async { - request.response.bufferOutput = false; - request.response.statusCode = HttpStatus.ok; - request.response.contentLength = 1000000; - request.response.add(List.filled(1024, 42)); - await request.response.flush(); - - // 挂起等待客户端取消 - await serverCompleter.future; - try { - await request.response.close(); - } catch (_) {} - }); - - final downloadFuture = dm.startDownload( - distroId: distroId, - downloadUrl: serverUrl, - ); - - while ((dm.getProgress(distroId)?.receivedBytes ?? 0) == 0) { - await Future.delayed(const Duration(milliseconds: 10)); - } - expect(dm.isDownloading(distroId), isTrue); - - final partFile = File(p.join(tempBaseDir.path, '${distroId}_rootfs.tar.xz.part')); - expect(partFile.existsSync(), isTrue); - - await dm.cancelDownload(distroId); - - // 验证取消后: - // 1. isDownloading 为 false - expect(dm.isDownloading(distroId), isFalse); - // 2. 进度映射已被重置清理 - expect(dm.getProgress(distroId), isNull); - // 3. .part 临时文件被立即安全删除(Windows 上句柄已完全释放) - expect(partFile.existsSync(), isFalse); - - // 唤醒服务端 - if (!serverCompleter.isCompleted) { - serverCompleter.complete(); - } - - // 等待 startDownload Future 完成,并验证返回值必须为 null 且未生成最终文件 - final resultFile = await downloadFuture; - expect(resultFile, isNull); - - final finalFile = File(p.join(tempBaseDir.path, '${distroId}_rootfs.tar.xz')); - expect(finalFile.existsSync(), isFalse); - - await server.close(force: true); - }, _TestHttpOverrides()); - }); - - test('re-download after cancellation succeeds cleanly', () async { - await HttpOverrides.runWithHttpOverrides(() async { - final dm = DistroDownloadManager(); - const distroId = 'test_redownload_distro'; - - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - final serverUrl = 'http://${server.address.address}:${server.port}/test_image.tar.xz'; - - server.listen((HttpRequest request) async { - request.response.statusCode = HttpStatus.ok; - request.response.contentLength = 50; - request.response.add(List.filled(50, 99)); - await request.response.close(); - }); - - // 下载能成功完成 - final resultFile = await dm.startDownload( - distroId: distroId, - downloadUrl: serverUrl, - ); - - expect(resultFile, isNotNull); - expect(resultFile!.existsSync(), isTrue); - expect(resultFile.lengthSync(), 50); - expect(dm.getProgress(distroId)?.state, DistroDownloadState.completed); - - await server.close(force: true); - }, _TestHttpOverrides()); - }); - - test('startDownload refuses duplicate download and returns existing file when package already exists', () async { - final dm = DistroDownloadManager(); - const distroId = 'test_existing_distro'; - const fakeUrl = 'https://example.com/test_image.tar.xz'; - - final file = await dm.getPackageFile(distroId, fakeUrl); - file.writeAsStringSync('existing package content'); - - expect(await dm.isPackageDownloaded(distroId, fakeUrl), isTrue); - - // 再次调用 startDownload,应立即返回已有文件,且不发起网络请求 - final returnedFile = await dm.startDownload( - distroId: distroId, - downloadUrl: fakeUrl, - ); - - expect(returnedFile, isNotNull); - expect(returnedFile!.path, file.path); - expect(dm.getProgress(distroId)?.state, DistroDownloadState.completed); - expect(returnedFile.readAsStringSync(), 'existing package content'); - }); - }); - - group('DistroManagementView Requirements Tests', () { - testWidgets('1. 内置字样完全移除,2. 安装按钮和已安装文本去掉', (tester) async { - await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView())); - await tester.pumpAndSettle(); - - // 验证返回按键与标题 - expect(find.byIcon(Icons.arrow_back), findsOneWidget); - expect(find.text('系统管理'), findsOneWidget); - - // 验证品牌图标存在 - expect(find.byType(Image), findsWidgets); - - // 1. 验证“内置”字样完全不存在 - expect(find.text('内置'), findsNothing); - expect(find.text('Built-in'), findsNothing); - - // 2. 验证“安装”按键与“已安装”文本完全不存在 - expect(find.text('安装'), findsNothing); - expect(find.text('Install'), findsNothing); - expect(find.text('已安装'), findsNothing); - expect(find.text('Installed'), findsNothing); - - // 3. 验证推荐标签保留 - expect(find.text('推荐'), findsWidgets); - }); - - testWidgets('3. 选中后无高亮边框 (border 无突出 primary 高亮)', (tester) async { - // 预置默认选中 ubuntu - await distroProvider.refreshSystems(); - - await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView())); - await tester.pumpAndSettle(); - - // 获取第一个 Card - final cardFinder = find.byType(Card).first; - final cardWidget = tester.widget(cardFinder); - final shape = cardWidget.shape as RoundedRectangleBorder; - final side = shape.side; - - // 边框宽度为普通 1.0,颜色不是 primary 高亮 - expect(side.width, 1.0); - }); - - testWidgets('4. 内置系统 (ubuntu / alpine) 无法删除,右侧无按键', (tester) async { - await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView())); - await tester.pumpAndSettle(); - - // 在初始未下载任何外部系统的状态下,内置系统右侧没有任何删除按键 - expect(find.byIcon(Icons.delete_outline), findsNothing); - }); - - testWidgets('4. 点击已就绪的 item 本身直接返回 DistroManifestItem', (tester) async { - DistroManifestItem? selectedItem; - await tester.pumpWidget(buildTestableWidget( - child: Builder( - builder: (context) => ElevatedButton( - onPressed: () async { - selectedItem = await Navigator.of(context).push( - MaterialPageRoute(builder: (_) => const DistroManagementView()), - ); - }, - child: const Text('Open'), - ), - ), - )); - await tester.pumpAndSettle(); - - // 打开页面 - await tester.tap(find.text('Open')); - await tester.pumpAndSettle(); - - // 点击已就绪的 Alpine Linux 条目本身 - await tester.tap(find.text('Alpine Linux')); - await tester.pumpAndSettle(); - - // 确认返回了 DistroManifestItem - expect(selectedItem, isNotNull); - expect(selectedItem!.id, 'alpine'); - }); - - testWidgets('4. 下载完成的系统右侧显示红色删除按钮,点击弹出删除安装包确认框', (tester) async { - // 模拟 debian 安装包已存在于本地目录 - final debianFile = File(p.join(tempBaseDir.path, 'debian_rootfs.tar.xz')); - debianFile.writeAsStringSync('dummy content'); - - await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView())); - await tester.pumpAndSettle(); - - // debian 应出现红色删除按钮 - final deleteBtn = find.byIcon(Icons.delete_outline); - expect(deleteBtn, findsOneWidget); - - // 点击删除按钮弹出“确认删除安装包”对话框 - await tester.tap(deleteBtn); - await tester.pumpAndSettle(); - - expect(find.text('确认删除安装包'), findsOneWidget); - }); - - testWidgets('下载完成后页面立即响应更新为就绪状态,无需退出重新进入', (tester) async { - await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView())); - await tester.pumpAndSettle(); - - // 此时 debian 处于未下载状态,显示“下载”按钮 - expect(find.text('下载'), findsWidgets); - - // 模拟下载管理器写入完成包 - final debianFile = await downloadManager.getPackageFile('debian', 'https://example.com/debian.tar.xz'); - debianFile.writeAsStringSync('debian package content'); - - // 触发 startDownload,由于本地文件已完备,会直接更新状态并通知监听器 - await downloadManager.startDownload(distroId: 'debian', downloadUrl: 'https://example.com/debian.tar.xz'); - - await tester.pumpAndSettle(); - - // debian 的卡片立即就绪,出现红色删除按钮 - expect(find.byIcon(Icons.delete_outline), findsOneWidget); - }); - }); - - group('SettingsView Download Mirror Tests', () { - testWidgets('设置页面项目下方展示“下载”分组,默认显示清华源', (tester) async { - await tester.pumpWidget(buildTestableWidget(child: const SettingsView())); - await tester.pumpAndSettle(); - - // 滚动到“下载”分组可见 - await tester.scrollUntilVisible( - find.text('下载'), - 300, - scrollable: find.byType(Scrollable).first, - ); - await tester.pumpAndSettle(); - - // 验证“下载”分组标题与“下载源” - expect(find.text('下载'), findsOneWidget); - expect(find.text('下载源'), findsOneWidget); - expect(find.text('清华大学开源软件镜像站 (推荐)'), findsOneWidget); - }); - - testWidgets('点击下载源弹出底部选择菜单,可自由切换至北外源', (tester) async { - await tester.pumpWidget(buildTestableWidget(child: const SettingsView())); - await tester.pumpAndSettle(); - - // 滚动到“下载源”可见 - await tester.scrollUntilVisible( - find.text('下载源'), - 300, - scrollable: find.byType(Scrollable).first, - ); - await tester.pumpAndSettle(); - - // 点击下载源条目弹出 BottomSheet - await tester.tap(find.text('下载源')); - await tester.pumpAndSettle(); - - expect(find.text('选择下载源'), findsOneWidget); - expect(find.text('北京外国语大学开源软件镜像站'), findsOneWidget); - expect(find.text('中国科学院软件研究所开源镜像站'), findsOneWidget); - expect(find.text('LinuxContainers 官方镜像源'), findsOneWidget); - - // 选中北外源 - await tester.tap(find.text('北京外国语大学开源软件镜像站')); - await tester.pumpAndSettle(); - - // 验证 SettingsProvider 状态更新 - expect(settingsProvider.downloadMirrorId, 'bfsu'); - expect(find.text('北京外国语大学开源软件镜像站'), findsOneWidget); - }); - }); -} - -class _TestHttpOverrides extends HttpOverrides {} - diff --git a/test/distro_multi_system_test.dart b/test/distro_multi_system_test.dart deleted file mode 100644 index 8c08405..0000000 --- a/test/distro_multi_system_test.dart +++ /dev/null @@ -1,525 +0,0 @@ -import 'dart:io'; -import 'dart:typed_data'; -import 'package:archive/archive.dart'; -import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/providers/distro_provider.dart'; -import 'package:code_editor/providers/terminal_provider.dart'; -import 'package:code_editor/services/distro_installer.dart'; -import 'package:code_editor/services/distro_manager.dart'; -import 'package:code_editor/widgets/distro_selector_dialog.dart'; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:path/path.dart' as p; -import 'package:provider/provider.dart'; -import 'package:shared_preferences/shared_preferences.dart'; - -class MockDistroFilePicker extends FilePicker { - String? pickedPath; - - @override - Future pickFiles({ - String? dialogTitle, - String? initialDirectory, - FileType type = FileType.any, - List? allowedExtensions, - Function(FilePickerStatus)? onFileLoading, - bool allowCompression = false, - int compressionQuality = 30, - bool allowMultiple = false, - bool withData = false, - bool withReadStream = false, - bool lockParentWindow = false, - bool readSequential = false, - }) async { - if (pickedPath == null) return null; - return FilePickerResult([ - PlatformFile(name: p.basename(pickedPath!), size: 10, path: pickedPath), - ]); - } - - @override - Future clearTemporaryFiles() async => true; - - @override - Future getDirectoryPath({String? dialogTitle, bool lockParentWindow = false, String? initialDirectory}) async => null; - - @override - Future saveFile({String? dialogTitle, String? fileName, String? initialDirectory, FileType type = FileType.any, List? allowedExtensions, Uint8List? bytes, bool lockParentWindow = false}) async => null; -} - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - late Directory tempBaseDir; - late DistroManager manager; - - setUp(() { - SharedPreferences.setMockInitialValues({}); - tempBaseDir = Directory.systemTemp.createTempSync('distro_multi_test_'); - manager = DistroManager(); - manager.customBaseDir = tempBaseDir; - }); - - tearDown(() { - manager.customSdcardPath = null; - try { - if (tempBaseDir.existsSync()) { - tempBaseDir.deleteSync(recursive: true); - } - } catch (_) {} - }); - - Uint8List createMockRootfsTarGz() { - final archive = Archive(); - archive.addFile(ArchiveFile('bin/sh', 11, 'echo "sh"'.codeUnits)); - archive.addFile(ArchiveFile('etc/os-release', 18, 'NAME="Alpine Linux"'.codeUnits)); - final tarData = TarEncoder().encode(archive); - final gzData = GZipEncoder().encode(tarData); - return Uint8List.fromList(gzData!); - } - - group('DistroManager 多系统实例管理测试', () { - test('初始状态系统列表为空', () async { - final systems = await manager.listInstalledSystems(); - expect(systems, isEmpty); - expect(await manager.hasAnySystem(), isFalse); - }); - - test('空壳 rootfs(只有 etc 缺少 bin)不被视为已安装系统,也不会出现在列表里', () async { - // 复现历史缺陷遗留物:探测流程的 ensure* 会在未安装的系统名下造出 rootfs/etc - final ghostEtc = Directory(p.join(tempBaseDir.path, 'ghost', 'rootfs', 'etc')); - ghostEtc.createSync(recursive: true); - File(p.join(ghostEtc.path, 'resolv.conf')).writeAsStringSync('nameserver 1.1.1.1\n'); - - // 一个真正可用的系统实例 - final realRootfs = Directory(p.join(tempBaseDir.path, 'real', 'rootfs')); - Directory(p.join(realRootfs.path, 'etc')).createSync(recursive: true); - Directory(p.join(realRootfs.path, 'bin')).createSync(recursive: true); - - expect(await manager.listInstalledSystems(), equals(['real'])); - expect(await manager.isSystemInstalled('ghost'), isFalse); - expect(await manager.isSystemInstalled('real'), isTrue); - }); - - test('buildLaunchConfig 对未安装的系统直接抛错,且不在磁盘上创建任何目录', () async { - await expectLater( - manager.buildLaunchConfig( - systemName: 'not_installed', - workspacePath: tempBaseDir.path, - ), - throwsA(isA()), - ); - expect(Directory(p.join(tempBaseDir.path, 'not_installed')).existsSync(), isFalse); - }); - - test('同一 Rootfs 包支持导入并创建多个独立系统实例', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'source_rootfs.tar.gz')); - tempGzFile.writeAsBytesSync(gzBytes); - - // 导入系统 1: alpine - await manager.importFromCustomTarGz( - systemName: 'alpine', - tarGzFile: tempGzFile, - ); - - // 导入系统 2: alpine_dev - await manager.importFromCustomTarGz( - systemName: 'alpine_dev', - tarGzFile: tempGzFile, - ); - - final systems = await manager.listInstalledSystems(); - expect(systems.length, equals(2)); - expect(systems, containsAll(['alpine', 'alpine_dev'])); - - // 验证各自根目录独立存在 - final alpineRootDir = await manager.getSystemRootDir('alpine'); - final devRootDir = await manager.getSystemRootDir('alpine_dev'); - expect(File(p.join(alpineRootDir.path, 'bin', 'sh')).existsSync(), isTrue); - expect(File(p.join(devRootDir.path, 'bin', 'sh')).existsSync(), isTrue); - expect(alpineRootDir.path != devRootDir.path, isTrue); - - // 验证网络配置 (resolv.conf / hosts) 与挂载点 (/workspace, /tmp) - final resolvFile = File(p.join(alpineRootDir.path, 'etc', 'resolv.conf')); - expect(resolvFile.existsSync(), isTrue); - expect(resolvFile.readAsStringSync(), contains('1.1.1.1')); - - final hostsFile = File(p.join(alpineRootDir.path, 'etc', 'hosts')); - expect(hostsFile.existsSync(), isTrue); - expect(hostsFile.readAsStringSync(), contains('127.0.0.1 localhost')); - - expect(Directory(p.join(alpineRootDir.path, 'workspace')).existsSync(), isTrue); - expect(Directory(p.join(alpineRootDir.path, 'tmp')).existsSync(), isTrue); - - // 验证已就绪状态检测 - expect(await manager.isSystemInstalled('alpine'), isTrue); - }); - - test('系统名称校验:非法字符与同名防重', () async { - expect( - () => manager.validateSystemName(''), - throwsArgumentError, - ); - - expect( - () => manager.validateSystemName('bad/name*here'), - throwsArgumentError, - ); - - // 创建一个系统后,同名抛出异常 - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'temp.tar.gz'))..writeAsBytesSync(gzBytes); - await manager.importFromCustomTarGz(systemName: 'my_sys', tarGzFile: tempGzFile); - - expect( - () => manager.validateSystemName('my_sys'), - throwsArgumentError, - ); - }); - - test('解压取消时抛出异常并自动回滚清理残余目录', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'cancel_test.tar.gz'))..writeAsBytesSync(gzBytes); - - bool cancelTriggered = false; - - try { - await manager.importFromCustomTarGz( - systemName: 'cancelled_sys', - tarGzFile: tempGzFile, - onProgress: (prog, msg) { - cancelTriggered = true; - }, - isCancelled: () => cancelTriggered, // 模拟用户在解压循环中点击了取消 - ); - fail('应当抛出 DistroInstallCancelledException'); - } catch (e) { - expect(e, isA()); - } - - // 验证未导入成功的脏目录被清理 - final sysRootDir = await manager.getSystemRootDir('cancelled_sys'); - expect(sysRootDir.existsSync(), isFalse); - expect((await manager.listInstalledSystems()).contains('cancelled_sys'), isFalse); - }); - - test('高危删除系统实例物理清除文件', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'del_test.tar.gz'))..writeAsBytesSync(gzBytes); - - await manager.importFromCustomTarGz(systemName: 'to_delete', tarGzFile: tempGzFile); - expect((await manager.listInstalledSystems()).contains('to_delete'), isTrue); - - await manager.deleteSystem('to_delete'); - expect((await manager.listInstalledSystems()).contains('to_delete'), isFalse); - - final sysDir = Directory(p.join(tempBaseDir.path, 'to_delete')); - expect(sysDir.existsSync(), isFalse); - }); - - test('buildLaunchConfig 准确指向对应系统根目录', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'cfg.tar.gz'))..writeAsBytesSync(gzBytes); - - await manager.importFromCustomTarGz(systemName: 'prod_env', tarGzFile: tempGzFile); - - final launchConfig = await manager.buildLaunchConfig( - systemName: 'prod_env', - workspacePath: tempBaseDir.path, - ); - - expect(launchConfig.arguments, contains('-r')); - final rootDir = await manager.getSystemRootDir('prod_env'); - expect(launchConfig.arguments, contains(rootDir.path)); - expect(launchConfig.arguments, contains('-k')); - expect(launchConfig.arguments, contains('5.4.0-proot')); - expect(launchConfig.environment['PROOT_L2S_DIR'], isNotNull); - expect(launchConfig.environment['SHELL'], equals('/bin/sh')); - expect(launchConfig.arguments, contains('SHELL=/bin/sh')); - expect(launchConfig.arguments, contains('-l')); - expect(launchConfig.arguments, contains('-i')); - }); - - test('buildLaunchConfig 自动检测 rootfs 中的 /bin/bash 并设置为交互式登录 Shell', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'bash_cfg.tar.gz'))..writeAsBytesSync(gzBytes); - - await manager.importFromCustomTarGz(systemName: 'ubuntu_env', tarGzFile: tempGzFile); - final rootDir = await manager.getSystemRootDir('ubuntu_env'); - - // 模拟 Ubuntu 根文件系统中自带的 bash - final bashFile = File(p.join(rootDir.path, 'bin', 'bash')); - await bashFile.create(recursive: true); - - final launchConfig = await manager.buildLaunchConfig( - systemName: 'ubuntu_env', - workspacePath: tempBaseDir.path, - ); - - expect(launchConfig.environment['SHELL'], equals('/bin/bash')); - expect(launchConfig.arguments, contains('SHELL=/bin/bash')); - expect(launchConfig.arguments, contains('/bin/bash')); - expect(launchConfig.arguments, contains('-l')); - expect(launchConfig.arguments, contains('-i')); - - // 验证 Android 宿主特权/辅助组自动写入 /etc/group 与 .hushlogin 生成 - final groupFile = File(p.join(rootDir.path, 'etc', 'group')); - expect(groupFile.existsSync(), isTrue); - final groupContent = groupFile.readAsStringSync(); - expect(groupContent, contains('aid_inet:x:3003:')); - expect(groupContent, contains('aid_ext_data_rw:x:1077:')); - expect(groupContent, contains('aid_everybody:x:9997:')); - - final hushFile = File(p.join(rootDir.path, 'root', '.hushlogin')); - expect(hushFile.existsSync(), isTrue); - }); - - test('buildLaunchConfig 自动挂载 sdcard 目录到 /sdcard 与 /root/sdcard', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'sdcard_cfg.tar.gz'))..writeAsBytesSync(gzBytes); - - await manager.importFromCustomTarGz(systemName: 'sdcard_env', tarGzFile: tempGzFile); - - final fakeSdcard = Directory(p.join(tempBaseDir.path, 'fake_sdcard'))..createSync(); - manager.customSdcardPath = fakeSdcard.path; - - final launchConfig = await manager.buildLaunchConfig( - systemName: 'sdcard_env', - workspacePath: tempBaseDir.path, - ); - - expect(launchConfig.arguments, contains('${fakeSdcard.path}:/sdcard')); - expect(launchConfig.arguments, contains('${fakeSdcard.path}:/root/sdcard')); - - final rootDir = await manager.getSystemRootDir('sdcard_env'); - expect(Directory(p.join(rootDir.path, 'sdcard')).existsSync(), isTrue); - expect(Directory(p.join(rootDir.path, 'root', 'sdcard')).existsSync(), isTrue); - }); - - test('buildLaunchConfig 针对不同发行版(Alpine ash vs passwd 自定义 shell)自适应启动参数', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'alpine_cfg.tar.gz'))..writeAsBytesSync(gzBytes); - - await manager.importFromCustomTarGz(systemName: 'alpine_env', tarGzFile: tempGzFile); - final rootDir = await manager.getSystemRootDir('alpine_env'); - - // 1. 模拟 Alpine(无 bash,自带 ash,/etc/passwd 中 root 为 /bin/ash) - final ashFile = File(p.join(rootDir.path, 'bin', 'ash')); - await ashFile.create(recursive: true); - final passwdFile = File(p.join(rootDir.path, 'etc', 'passwd')); - await passwdFile.writeAsString('root:x:0:0:root:/root:/bin/ash\n'); - - final alpineConfig = await manager.buildLaunchConfig( - systemName: 'alpine_env', - workspacePath: tempBaseDir.path, - ); - expect(alpineConfig.environment['SHELL'], equals('/bin/ash')); - expect(alpineConfig.arguments, contains('/bin/ash')); - expect(alpineConfig.arguments, contains('-l')); - expect(alpineConfig.arguments, contains('-i')); - - // 2. 模拟用户安装并切换为 /bin/zsh - final zshFile = File(p.join(rootDir.path, 'bin', 'zsh')); - await zshFile.create(recursive: true); - await passwdFile.writeAsString('root:x:0:0:root:/root:/bin/zsh\n'); - - final zshConfig = await manager.buildLaunchConfig( - systemName: 'alpine_env', - workspacePath: tempBaseDir.path, - ); - expect(zshConfig.environment['SHELL'], equals('/bin/zsh')); - expect(zshConfig.arguments, contains('/bin/zsh')); - expect(zshConfig.arguments, contains('-l')); - expect(zshConfig.arguments, contains('-i')); - }); - - test('buildLaunchConfig 在 host 模式下正确配置 SHELL 与 -i 交互模式', () async { - final hostConfig = await manager.buildLaunchConfig( - systemName: 'host', - workspacePath: tempBaseDir.path, - ); - - expect(hostConfig.executable, equals('/system/bin/sh')); - expect(hostConfig.arguments, contains('-i')); - expect(hostConfig.environment['SHELL'], equals('/system/bin/sh')); - }); - }); - - group('DistroProvider 状态持久化与系统切换测试', () { - test('默认系统自动选取与持久化切换', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'provider_test.tar.gz'))..writeAsBytesSync(gzBytes); - - final provider = DistroProvider(); - await provider.init(); - expect(provider.selectedSystem, isNull); - - // 导入首个系统,自动选为当前系统 - await provider.importFromCustomTarGz(systemName: 'sys_a', tarGzFile: tempGzFile); - expect(provider.selectedSystem, equals('sys_a')); - expect(provider.installedSystems, contains('sys_a')); - - // 导入第二个系统,自动切换到新系统 - await provider.importFromCustomTarGz(systemName: 'sys_b', tarGzFile: tempGzFile); - expect(provider.selectedSystem, equals('sys_b')); - - // 手动切换回 sys_a 并持久化 - await provider.selectSystem('sys_a'); - expect(provider.selectedSystem, equals('sys_a')); - - final prefs = await SharedPreferences.getInstance(); - expect(prefs.getString('terminal_default_system'), equals('sys_a')); - - // 删除当前选中的系统,自动平滑退回到另一个系统 - await provider.deleteSystem('sys_a'); - expect(provider.installedSystems, equals(['sys_b'])); - expect(provider.selectedSystem, equals('sys_b')); - - // 删除仅剩的系统,回到 null - await provider.deleteSystem('sys_b'); - expect(provider.installedSystems, isEmpty); - expect(provider.selectedSystem, isNull); - }); - - test('删除系统实例时联动清理对应系统的全部终端会话', () async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'session_clean_test.tar.gz'))..writeAsBytesSync(gzBytes); - - final distroProvider = DistroProvider(); - await distroProvider.init(); - - await distroProvider.importFromCustomTarGz(systemName: 'sys_1', tarGzFile: tempGzFile); - await distroProvider.importFromCustomTarGz(systemName: 'sys_2', tarGzFile: tempGzFile); - - final terminalProvider = TerminalProvider(); - distroProvider.onSystemDeleted = (deleted) { - terminalProvider.removeSessionsForDistro(deleted); - if (!distroProvider.hasAnySystem) { - terminalProvider.clearAllSessions(); - } - }; - - // 创建 sys_1 的两个会话,sys_2 的一个会话 - final s1 = terminalProvider.createSession(name: '会话1', distroId: 'sys_1'); - final s2 = terminalProvider.createSession(name: '会话2', distroId: 'sys_1'); - final s3 = terminalProvider.createSession(name: '会话3', distroId: 'sys_2'); - - expect(terminalProvider.sessions.length, equals(3)); - - // 删除 sys_1:应当仅删除 s1 与 s2,保留 s3 - await distroProvider.deleteSystem('sys_1'); - - expect(terminalProvider.sessions.length, equals(1)); - expect(terminalProvider.sessions.first.id, equals(s3.id)); - expect(terminalProvider.sessions.first.distroId, equals('sys_2')); - expect(terminalProvider.sessions.any((s) => s.id == s1.id), isFalse); - expect(terminalProvider.sessions.any((s) => s.id == s2.id), isFalse); - - // 删除最后一个系统 sys_2:所有会话均被清理清空 - await distroProvider.deleteSystem('sys_2'); - expect(terminalProvider.sessions, isEmpty); - }); - - testWidgets('DistroSelectorDialog 列表项仅显示名称,无副标题与前置勾选图标', (tester) async { - final gzBytes = createMockRootfsTarGz(); - final tempGzFile = File(p.join(tempBaseDir.path, 'dialog_ui_test.tar.gz'))..writeAsBytesSync(gzBytes); - - final distroProvider = DistroProvider(); - await tester.runAsync(() async { - await distroProvider.init(); - await distroProvider.importFromCustomTarGz(systemName: 'my_alpine', tarGzFile: tempGzFile); - }); - - await tester.pumpWidget( - MultiProvider( - providers: [ - ChangeNotifierProvider.value(value: distroProvider), - ChangeNotifierProvider(create: (_) => TerminalProvider()), - ], - child: MaterialApp( - locale: const Locale('zh'), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const Scaffold( - body: DistroSelectorDialog(), - ), - ), - ), - ); - await tester.pumpAndSettle(); - - // 验证系统管理标题来自 l10n - expect(find.text('系统管理'), findsOneWidget); - - // 验证系统名称正常显示 - expect(find.text('my_alpine'), findsOneWidget); - - // 验证无旧版副标题文字(如“当前默认系统”、“点击切换为默认”) - expect(find.text('当前默认系统'), findsNothing); - expect(find.text('点击切换为默认'), findsNothing); - - // 验证无前置勾选图标 - expect(find.byIcon(Icons.check_circle), findsNothing); - expect(find.byIcon(Icons.radio_button_unchecked), findsNothing); - - // 验证存在高危删除按钮 - expect(find.byIcon(Icons.delete_outline), findsOneWidget); - }); - - testWidgets('DistroSelectorDialog 导入外部系统选择不支持的格式时显示错误 Toast 并中止流程', (tester) async { - final mockPicker = MockDistroFilePicker(); - FilePicker.platform = mockPicker; - - // 设置选中的文件为不受支持的格式(如 .zip 或 .txt) - final unsupportedFile = File(p.join(tempBaseDir.path, 'rootfs_image.zip'))..writeAsStringSync('zip content'); - mockPicker.pickedPath = unsupportedFile.path; - - final distroProvider = DistroProvider(); - await tester.runAsync(() async { - await distroProvider.init(); - }); - - await tester.pumpWidget( - MultiProvider( - providers: [ - ChangeNotifierProvider.value(value: distroProvider), - ChangeNotifierProvider(create: (_) => TerminalProvider()), - ], - child: MaterialApp( - locale: const Locale('zh'), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const Scaffold( - body: DistroSelectorDialog(), - ), - ), - ), - ); - await tester.pumpAndSettle(); - - // 点击导入按钮打开 PopupMenu - final importButton = find.byIcon(Icons.add_circle_outline); - expect(importButton, findsOneWidget); - await tester.tap(importButton); - await tester.pumpAndSettle(); - - // 点击“从外部导入 (.tar.gz)” - final externalItem = find.text('从外部导入 (.tar.gz)'); - expect(externalItem, findsOneWidget); - await tester.tap(externalItem); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - - // 验证不应弹出系统名称输入弹窗 - expect(find.text('导入外部系统'), findsNothing); - - // 验证弹出指定格式错误 Toast - expect(find.text('不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)'), findsOneWidget); - - // 等待 Toast 定时器安全结束 - await tester.pump(const Duration(seconds: 3)); - }); - }); -} diff --git a/test/editor_overlay_hierarchy_test.dart b/test/editor_overlay_hierarchy_test.dart new file mode 100644 index 0000000..50e6f0b --- /dev/null +++ b/test/editor_overlay_hierarchy_test.dart @@ -0,0 +1,80 @@ +import 'package:code_editor/services/code_completion/smart_prompts_builder.dart'; +import 'package:code_editor/widgets/code_autocomplete_view.dart'; +import 'package:code_editor/widgets/editor/editor_overlay_scope.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:re_editor/re_editor.dart'; + +void main() { + group('Editor Overlay Hierarchy Tests', () { + testWidgets('CodeAutocomplete uses local EditorOverlayScope instead of root overlay', (tester) async { + final controller = CodeLineEditingController.fromText('pri'); + final promptsBuilder = SmartCodeAutocompletePromptsBuilder( + controller: controller, + directPrompts: [ + CodeKeywordPrompt(word: 'printf'), + ], + ); + + bool tappedBottomButton = false; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + Expanded( + child: EditorOverlayScope( + child: CodeAutocomplete( + viewBuilder: (context, notifier, onSelected) { + promptsBuilder.activeNotifier = notifier; + return CodeAutocompleteView( + notifier: notifier, + onSelected: onSelected, + ); + }, + promptsBuilder: promptsBuilder, + child: CodeEditor( + autofocus: false, + controller: controller, + ), + ), + ), + ), + // 模拟小键盘(在 Column 中位于 Editor 下方) + GestureDetector( + key: const ValueKey('virtual_keyboard_btn'), + onTap: () { + tappedBottomButton = true; + }, + child: Container( + height: 50, + width: double.infinity, + color: Colors.blue, + child: const Text('Virtual Key ;'), + ), + ), + ], + ), + ), + ), + ); + + // 获取当前所有的 Overlay + final overlays = tester.widgetList(find.byType(Overlay)).toList(); + // 至少应该有 2 个 Overlay:1 个是 MaterialApp/Navigator 的 root overlay,1 个是 EditorOverlayScope 的 local overlay + expect(overlays.length, greaterThanOrEqualTo(2)); + + // 验证底部的模拟小键盘正常渲染 + expect(find.byKey(const ValueKey('virtual_keyboard_btn')), findsOneWidget); + + // 点击虚拟小键盘,验证点击事件正常响应且不受干扰 + await tester.tap(find.byKey(const ValueKey('virtual_keyboard_btn'))); + expect(tappedBottomButton, isTrue); + + // 清理测试组件树 + await tester.pumpWidget(const SizedBox()); + controller.dispose(); + }); + }); +} diff --git a/test/extended_project_modules_and_single_file_test.dart b/test/extended_project_modules_and_single_file_test.dart new file mode 100644 index 0000000..7348678 --- /dev/null +++ b/test/extended_project_modules_and_single_file_test.dart @@ -0,0 +1,232 @@ +import 'dart:io'; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/lsp_language_config.dart'; +import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/services/project_modules/maven_project_module.dart'; +import 'package:code_editor/services/project_modules/project_probe.dart'; +import 'package:code_editor/services/project_modules/python_project_module.dart'; +import 'package:code_editor/services/project_modules/single_file_task_detector.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; +import 'package:code_editor/services/toolchain_service.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempDir; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('extended_modules_test_'); + }); + + tearDown(() { + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + group('SingleFileTaskDetector Extended Tests', () { + test('Detects Java single file', () { + final javaFile = File(p.join(tempDir.path, 'Hello.java'))..writeAsStringSync('public class Hello {}'); + expect(SingleFileTaskDetector.isSupported(javaFile.path), isTrue); + + final task = SingleFileTaskDetector.detect(tempDir.path, javaFile.path); + expect(task, isNotNull); + expect(task!.id, equals('detected_single_java')); + expect(task.name, equals('Java: Hello.java')); + expect(task.command, contains('java ')); + }); + + test('Detects TypeScript single file', () { + final tsFile = File(p.join(tempDir.path, 'index.ts'))..writeAsStringSync('console.log(42);'); + expect(SingleFileTaskDetector.isSupported(tsFile.path), isTrue); + + final task = SingleFileTaskDetector.detect(tempDir.path, tsFile.path); + expect(task, isNotNull); + expect(task!.id, equals('detected_single_ts')); + expect(task.command, contains('npx -y tsx')); + }); + + test('Detects Lua, Perl, PHP single files', () { + final luaFile = File(p.join(tempDir.path, 'script.lua'))..writeAsStringSync('print("hi")'); + final plFile = File(p.join(tempDir.path, 'script.pl'))..writeAsStringSync('print "hi";'); + final phpFile = File(p.join(tempDir.path, 'index.php'))..writeAsStringSync(' t.id).toList(); + expect(taskIds, contains('detected_python_pip_install')); + expect(taskIds, contains('detected_python_run_main')); + expect(taskIds, contains('detected_python_pytest')); + }); + }); + + group('MavenProjectModule Tests', () { + test('Activates on pom.xml and supports mvnw wrapper', () async { + File(p.join(tempDir.path, 'pom.xml')).writeAsStringSync(''); + File(p.join(tempDir.path, 'mvnw')).writeAsStringSync('#!/bin/sh'); + + final module = MavenProjectModule(); + expect(module.shouldActivate(tempDir), isTrue); + + final dispatcher = ProjectTaskDispatcher(); + final probe = dispatcher.createProbe( + projectRoot: tempDir.path, + systemName: 'ubuntu', + ); + + final result = await module.probe(probe); + expect(result.status, equals(ModuleProbeStatus.ok)); + final taskIds = result.tasks.map((t) => t.id).toList(); + expect(taskIds, contains('detected_maven_package')); + expect(taskIds, contains('detected_maven_compile')); + expect(taskIds, contains('detected_maven_test')); + expect(taskIds, contains('detected_maven_clean')); + + // Verifies ./mvnw was used because wrapper exists + final pkgTask = result.tasks.firstWhere((t) => t.id == 'detected_maven_package'); + expect(pkgTask.command, equals('./mvnw package')); + }); + }); + + group('ToolchainService Extended Tests', () { + test('Supported tools contain java, maven, lua, perl, php', () { + expect(ToolchainService.supportedTools.containsKey('java'), isTrue); + expect(ToolchainService.supportedTools.containsKey('maven'), isTrue); + expect(ToolchainService.supportedTools.containsKey('mvn'), isTrue); + expect(ToolchainService.supportedTools.containsKey('lua'), isTrue); + expect(ToolchainService.supportedTools.containsKey('perl'), isTrue); + expect(ToolchainService.supportedTools.containsKey('php'), isTrue); + }); + }); + + group('LspLanguageConfig Presets Extended Tests', () { + test('Builtin presets contain Java, TypeScript, Lua', () { + final javaPreset = LspLanguageConfig.findBuiltinByExtension('.java'); + expect(javaPreset, isNotNull); + expect(javaPreset!.id, equals('java')); + + final tsPreset = LspLanguageConfig.findBuiltinByExtension('.ts'); + expect(tsPreset, isNotNull); + expect(tsPreset!.id, equals('typescript')); + + final luaPreset = LspLanguageConfig.findBuiltinByExtension('.lua'); + expect(luaPreset, isNotNull); + expect(luaPreset!.id, equals('lua')); + }); + }); + + + group('Localization Coverage Tests', () { + testWidgets('Localized descriptions exist for all new tasks in zh and en without throwing', (tester) async { + late AppLocalizations l10nZh; + late AppLocalizations l10nEn; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('zh'), Locale('en')], + locale: const Locale('zh'), + home: Builder( + builder: (ctx) { + l10nZh = AppLocalizations.of(ctx)!; + return const SizedBox(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('zh'), Locale('en')], + locale: const Locale('en'), + home: Builder( + builder: (ctx) { + l10nEn = AppLocalizations.of(ctx)!; + return const SizedBox(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + const newTaskIds = [ + 'detected_single_java', + 'detected_single_ts', + 'detected_single_lua', + 'detected_single_perl', + 'detected_single_php', + 'detected_python_pip_install', + 'detected_python_run_main', + 'detected_python_pytest', + 'detected_maven_package', + 'detected_maven_compile', + 'detected_maven_test', + 'detected_maven_clean', + ]; + + for (final id in newTaskIds) { + final task = RunTask( + id: id, + name: id, + command: 'echo 1', + source: TaskSource.detected, + ); + final descZh = task.getLocalizedDescription(l10nZh); + final descEn = task.getLocalizedDescription(l10nEn); + + expect(descZh.isNotEmpty, isTrue, reason: '$id zh description should not be empty'); + expect(descEn.isNotEmpty, isTrue, reason: '$id en description should not be empty'); + expect(descZh != descEn, isTrue, reason: '$id zh and en descriptions should be distinct'); + } + }); + }); +} diff --git a/test/fuzzy_matcher_test.dart b/test/fuzzy_matcher_test.dart new file mode 100644 index 0000000..6fe6d3b --- /dev/null +++ b/test/fuzzy_matcher_test.dart @@ -0,0 +1,66 @@ +import 'package:code_editor/services/code_completion/fuzzy_matcher.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('FuzzyMatcher Tests', () { + test('Exact match gives highest score', () { + final res = FuzzyMatcher.match('print', 'print'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThanOrEqualTo(2000)); + }); + + test('Case-sensitive prefix match', () { + final res = FuzzyMatcher.match('pri', 'print'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThanOrEqualTo(1500)); + }); + + test('Case-insensitive prefix match', () { + final res = FuzzyMatcher.match('pri', 'PrintStream'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThanOrEqualTo(1000)); + }); + + test('CamelCase match (e.g. fb -> FloatingActionButton)', () { + final res = FuzzyMatcher.match('fab', 'FloatingActionButton'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThanOrEqualTo(500)); + expect(res.matchedIndices, equals([0, 8, 14])); + }); + + test('Snake_case match (e.g. tf -> text_field)', () { + final res = FuzzyMatcher.match('tf', 'text_field'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThanOrEqualTo(500)); + expect(res.matchedIndices, equals([0, 5])); + }); + + test('Subsequence match', () { + final res = FuzzyMatcher.match('pnt', 'print'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThan(400)); + }); + + test('Typo tolerance / error correction (e.g. prnt -> print)', () { + final res = FuzzyMatcher.match('prnt', 'print'); + expect(res.isMatch, isTrue); + }); + + test('Typo tolerance with 1 char mistake (e.g. prib -> print)', () { + final res = FuzzyMatcher.match('prib', 'print'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThan(100)); + }); + + test('Typo tolerance for length mistake (e.g. lenght -> length)', () { + final res = FuzzyMatcher.match('lenght', 'length'); + expect(res.isMatch, isTrue); + expect(res.score, greaterThan(100)); + }); + + test('Completely unrelated word does not match', () { + final res = FuzzyMatcher.match('xyz', 'print'); + expect(res.isMatch, isFalse); + }); + }); +} diff --git a/test/internal_engine_and_lsp_config_test.dart b/test/internal_engine_and_lsp_config_test.dart index fc9ca2b..04fa7d8 100644 --- a/test/internal_engine_and_lsp_config_test.dart +++ b/test/internal_engine_and_lsp_config_test.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/lsp_language_config.dart'; import 'package:code_editor/services/internal_engine_service.dart'; import 'package:code_editor/services/lsp_config_service.dart'; import 'package:code_editor/views/code_completion_management_view.dart'; @@ -57,20 +58,18 @@ void main() { } group('LspConfigService Tests', () { - test('Initial load creates default presets and writes to disk', () async { + test('Initial load returns empty list and writes empty json to disk', () async { final configs = await lspConfigService.loadConfigs(forceReload: true); - expect(configs.isNotEmpty, isTrue); - expect(configs.any((c) => c.id == 'c_cpp'), isTrue); - expect(configs.any((c) => c.id == 'rust'), isTrue); + expect(configs.isEmpty, isTrue); final file = await lspConfigService.getConfigFile(); expect(file.existsSync(), isTrue); final content = jsonDecode(file.readAsStringSync()) as List; - expect(content.length, equals(configs.length)); + expect(content.isEmpty, isTrue); }); - test('Incremental merge appends missing default presets without overwriting user configs', () async { + test('Loads pre-existing custom configs from disk without auto-injecting uninstalled presets', () async { final file = await lspConfigService.getConfigFile(); // Write only custom Python config const customConfig = [ @@ -81,61 +80,99 @@ void main() { 'fileExtensions': ['.py', '.pyw'], 'serverCommand': 'my_pylsp', 'serverArgs': ['--verbose'], - 'apkPackage': 'py3-lsp-server', + 'package': 'python3-pylsp', 'enabled': true, } ]; file.writeAsStringSync(jsonEncode(customConfig)); final configs = await lspConfigService.loadConfigs(forceReload: true); - // User's custom python must be preserved - final pyConfig = configs.firstWhere((c) => c.id == 'python'); + expect(configs.length, equals(1)); + final pyConfig = configs.first; + expect(pyConfig.id, equals('python')); expect(pyConfig.name, equals('My Custom Python')); expect(pyConfig.serverCommand, equals('my_pylsp')); - // Missing presets like c_cpp, rust must be incrementally added - expect(configs.any((c) => c.id == 'c_cpp'), isTrue); - expect(configs.any((c) => c.id == 'rust'), isTrue); - expect(configs.any((c) => c.id == 'go'), isTrue); + // Missing presets like c_cpp, rust are NOT automatically added to installed list + expect(configs.any((c) => c.id == 'c_cpp'), isFalse); + expect(configs.any((c) => c.id == 'rust'), isFalse); + expect(configs.any((c) => c.id == 'go'), isFalse); }); - test('findByExtension resolves language config correctly', () async { + test('LspLanguageConfig.findBuiltinByExtension resolves builtin templates correctly', () { + final cPreset = LspLanguageConfig.findBuiltinByExtension('.c'); + expect(cPreset, isNotNull); + expect(cPreset!.id, equals('c_cpp')); + + final cppPreset = LspLanguageConfig.findBuiltinByExtension('cpp'); + expect(cppPreset, isNotNull); + expect(cppPreset!.id, equals('c_cpp')); + + final pyPreset = LspLanguageConfig.findBuiltinByExtension('.py'); + expect(pyPreset, isNotNull); + expect(pyPreset!.id, equals('python')); + + final unknown = LspLanguageConfig.findBuiltinByExtension('.unknown'); + expect(unknown, isNull); + }); + + test('LspConfigService.findByExtension only returns installed and enabled configs', () async { await lspConfigService.loadConfigs(forceReload: true); - final cConfig = lspConfigService.findByExtension('.c'); - expect(cConfig, isNotNull); - expect(cConfig!.id, equals('c_cpp')); + // When no configs are installed, findByExtension must return null (not builtin preset) + expect(lspConfigService.findByExtension('.cpp'), isNull); + expect(lspConfigService.findByExtension('cpp'), isNull); + expect(lspConfigService.findByExtension('.py'), isNull); - final cppConfig = lspConfigService.findByExtension('cpp'); - expect(cppConfig, isNotNull); - expect(cppConfig!.id, equals('c_cpp')); + // Install C/C++ config + const sample = LspLanguageConfig( + id: 'c_cpp', + name: 'C / C++', + languageId: 'cpp', + fileExtensions: ['.c', '.cpp', '.h'], + serverCommand: 'clangd', + package: 'clangd', + ); + await lspConfigService.updateConfig(sample); - final pyConfig = lspConfigService.findByExtension('.py'); - expect(pyConfig, isNotNull); - expect(pyConfig!.id, equals('python')); + // Now it should resolve + expect(lspConfigService.findByExtension('.cpp'), isNotNull); + expect(lspConfigService.findByExtension('cpp')!.id, equals('c_cpp')); - final unknown = lspConfigService.findByExtension('.unknown'); - expect(unknown, isNull); + // If disabled, it should return null + final disabledSample = sample.copyWith(enabled: false); + await lspConfigService.updateConfig(disabledSample); + expect(lspConfigService.findByExtension('.cpp'), isNull); }); test('updateConfig, deleteConfig and resetToDefaults work and persist to disk', () async { await lspConfigService.loadConfigs(forceReload: true); - // 1. Update config - final originalC = lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp'); - final modifiedC = originalC.copyWith(serverCommand: 'clangd-18'); - await lspConfigService.updateConfig(modifiedC); + // 1. Add / Update config + const sample = LspLanguageConfig( + id: 'c_cpp', + name: 'C / C++', + languageId: 'cpp', + fileExtensions: ['.c', '.cpp', '.h'], + serverCommand: 'clangd', + package: 'clangd', + ); + await lspConfigService.updateConfig(sample); + expect(lspConfigService.configs.any((c) => c.id == 'c_cpp'), isTrue); + final modifiedC = sample.copyWith(serverCommand: 'clangd-18'); + await lspConfigService.updateConfig(modifiedC); expect(lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp').serverCommand, equals('clangd-18')); // 2. Delete config - await lspConfigService.deleteConfig('shell'); - expect(lspConfigService.configs.any((c) => c.id == 'shell'), isFalse); + await lspConfigService.deleteConfig('c_cpp'); + expect(lspConfigService.configs.any((c) => c.id == 'c_cpp'), isFalse); - // 3. Reset to defaults + // 3. Reset to defaults (clears configs) + await lspConfigService.updateConfig(sample); + expect(lspConfigService.configs.isNotEmpty, isTrue); await lspConfigService.resetToDefaults(); - expect(lspConfigService.configs.any((c) => c.id == 'shell'), isTrue); - expect(lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp').serverCommand, equals('clangd')); + expect(lspConfigService.configs.isEmpty, isTrue); }); }); @@ -158,7 +195,7 @@ void main() { }); group('CodeCompletionManagementView & LspLanguageEditDialog Widget Tests', () { - testWidgets('Management view renders all language items and engine card in Chinese', (tester) async { + testWidgets('Management view renders empty placeholder when no language is installed', (tester) async { await lspConfigService.loadConfigs(forceReload: true); await tester.pumpWidget(buildTestWidget( @@ -168,11 +205,39 @@ void main() { await tester.pumpAndSettle(); expect(find.text('代码补全管理'), findsOneWidget); - expect(find.text('内部代码智能引擎 (Alpine)'), findsOneWidget); + expect(find.text('引擎未启动'), findsOneWidget); + expect(find.text('暂无已安装的代码智能组件'), findsOneWidget); + }); + + testWidgets('Management view renders installed language items in Chinese', (tester) async { + await lspConfigService.loadConfigs(forceReload: true); + await lspConfigService.updateConfig(const LspLanguageConfig( + id: 'c_cpp', + name: 'C / C++', + languageId: 'cpp', + fileExtensions: ['.c', '.cpp', '.h'], + serverCommand: 'clangd', + package: 'clangd', + )); + await lspConfigService.updateConfig(const LspLanguageConfig( + id: 'python', + name: 'Python', + languageId: 'python', + fileExtensions: ['.py'], + serverCommand: 'pylsp', + package: 'python3-pylsp', + )); + + await tester.pumpWidget(buildTestWidget( + child: const CodeCompletionManagementView(), + locale: const Locale('zh'), + )); + await tester.pumpAndSettle(); + + expect(find.text('代码补全管理'), findsOneWidget); + expect(find.text('引擎未启动'), findsOneWidget); expect(find.text('C / C++'), findsOneWidget); expect(find.text('Python'), findsOneWidget); - expect(find.text('Rust'), findsOneWidget); - expect(find.text('Go'), findsOneWidget); }); testWidgets('Management view renders without hardcoded text in English', (tester) async { @@ -185,13 +250,21 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Code Completion Management'), findsOneWidget); - expect(find.text('Internal Code Intelligence Engine (Alpine)'), findsOneWidget); - expect(find.byTooltip('Reset to Defaults'), findsOneWidget); + expect(find.text('Engine Not Started'), findsOneWidget); expect(find.byTooltip('Add Language Configuration'), findsOneWidget); + expect(find.text('No code intelligence components installed'), findsOneWidget); }); testWidgets('Edit button pops LspLanguageEditDialog and saves modifications', (tester) async { await lspConfigService.loadConfigs(forceReload: true); + await lspConfigService.updateConfig(const LspLanguageConfig( + id: 'c_cpp', + name: 'C / C++', + languageId: 'cpp', + fileExtensions: ['.c', '.cpp', '.h'], + serverCommand: 'clangd', + package: 'clangd', + )); await tester.pumpWidget(buildTestWidget( child: const CodeCompletionManagementView(), @@ -199,9 +272,13 @@ void main() { )); await tester.pumpAndSettle(); - // Tap first edit icon + // Click C / C++ card to expand it + await tester.tap(find.text('C / C++')); + await tester.pumpAndSettle(); + + // Tap edit button in the expanded menu final editButtons = find.byIcon(Icons.edit_outlined); - expect(editButtons, findsWidgets); + expect(editButtons, findsOneWidget); await tester.tap(editButtons.first); await tester.pumpAndSettle(); @@ -228,6 +305,14 @@ void main() { testWidgets('Delete button prompts confirmation and removes language', (tester) async { await lspConfigService.loadConfigs(forceReload: true); + await lspConfigService.updateConfig(const LspLanguageConfig( + id: 'python', + name: 'Python', + languageId: 'python', + fileExtensions: ['.py'], + serverCommand: 'pylsp', + package: 'python3-pylsp', + )); await tester.pumpWidget(buildTestWidget( child: const CodeCompletionManagementView(), @@ -237,16 +322,20 @@ void main() { expect(find.text('Python'), findsOneWidget); - // Find delete button for Python (index 1) + // Click Python card to expand it + await tester.tap(find.text('Python')); + await tester.pumpAndSettle(); + + // Find delete button in the expanded Python card final deleteButtons = find.byIcon(Icons.delete_outline); - await tester.tap(deleteButtons.at(1)); + await tester.tap(deleteButtons.first); await tester.pumpAndSettle(); expect(find.text('删除语言配置'), findsOneWidget); expect(find.text('确定要删除 Python 的代码补全配置吗?'), findsOneWidget); - // Confirm delete - await tester.tap(find.text('删除')); + // Confirm delete in dialog + await tester.tap(find.widgetWithText(FilledButton, '删除')); await tester.pumpAndSettle(); // Python should now be gone @@ -256,5 +345,21 @@ void main() { // Settle SnackBar timer await tester.pump(const Duration(seconds: 4)); }); + + testWidgets('CodeCompletionManagementView renders without overflow on narrow device (320px width)', (tester) async { + await lspConfigService.loadConfigs(forceReload: true); + tester.view.physicalSize = const Size(320 * 2.0, 640 * 2.0); + tester.view.devicePixelRatio = 2.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget(buildTestWidget( + child: const CodeCompletionManagementView(), + locale: const Locale('en'), + )); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'Narrow layout in English should not have any RenderFlex overflow'); + }); }); } diff --git a/test/lsp_integration_test.dart b/test/lsp_integration_test.dart new file mode 100644 index 0000000..3403d21 --- /dev/null +++ b/test/lsp_integration_test.dart @@ -0,0 +1,329 @@ +import 'package:code_editor/services/lsp/lsp_diagnostics_store.dart'; +import 'package:code_editor/services/lsp/lsp_protocol.dart'; +import 'package:code_editor/services/lsp/lsp_workspace_edit_applier.dart'; +import 'package:code_editor/widgets/editor/editor_lsp_coordinator.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:re_editor/re_editor.dart'; + +void main() { + group('LSP 协议与数据模型测试', () { + test('LspPosition 与 LspRange 范围包含与行交集判断', () { + const pos1 = LspPosition(line: 2, character: 4); + const pos2 = LspPosition(line: 2, character: 10); + const range = LspRange(start: pos1, end: pos2); + + expect(range.contains(2, 4), isTrue); + expect(range.contains(2, 7), isTrue); + expect(range.contains(2, 10), isTrue); + expect(range.contains(2, 3), isFalse); + expect(range.contains(2, 11), isFalse); + expect(range.contains(1, 4), isFalse); + expect(range.contains(3, 4), isFalse); + + expect(range.overlapsLine(2), isTrue); + expect(range.overlapsLine(1), isFalse); + expect(range.overlapsLine(3), isFalse); + + const multiLineRange = LspRange( + start: LspPosition(line: 1, character: 5), + end: LspPosition(line: 3, character: 2), + ); + expect(multiLineRange.overlapsLine(1), isTrue); + expect(multiLineRange.overlapsLine(2), isTrue); + expect(multiLineRange.overlapsLine(3), isTrue); + expect(multiLineRange.overlapsLine(0), isFalse); + expect(multiLineRange.overlapsLine(4), isFalse); + }); + + test('LspDiagnostic 序列化与严重等级解析', () { + final json = { + 'range': { + 'start': {'line': 5, 'character': 2}, + 'end': {'line': 5, 'character': 8}, + }, + 'severity': 1, + 'message': "Use of undeclared identifier 'foo'", + 'source': 'clangd', + }; + + final diag = LspDiagnostic.fromJson(json); + expect(diag.isError, isTrue); + expect(diag.isWarning, isFalse); + expect(diag.message, "Use of undeclared identifier 'foo'"); + expect(diag.source, 'clangd'); + expect(diag.range.start.line, 5); + expect(diag.range.start.character, 2); + }); + + test('LspCompletionItem 解析与文本插入兼容', () { + final json = { + 'label': 'printf', + 'kind': 3, // Function + 'detail': 'int printf(const char *format, ...)', + 'documentation': 'Formatted output conversion.', + 'insertText': 'printf', + }; + + final item = LspCompletionItem.fromJson(json); + expect(item.label, 'printf'); + expect(item.effectiveInsertText, 'printf'); + expect(item.detail, contains('int printf')); + expect(item.documentation, contains('Formatted output')); + }); + + test('LspCodeAction 与 LspWorkspaceEdit 解析', () { + final json = { + 'title': "Include ", + 'kind': 'quickfix', + 'isPreferred': true, + 'edit': { + 'changes': { + 'file:///workspace/main.c': [ + { + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 0, 'character': 0}, + }, + 'newText': '#include \n', + } + ] + } + } + }; + + final action = LspCodeAction.fromJson(json); + expect(action.title, 'Include '); + expect(action.isPreferred, isTrue); + expect(action.edit, isNotNull); + expect(action.edit!.changes.containsKey('file:///workspace/main.c'), isTrue); + expect(action.edit!.changes['file:///workspace/main.c']!.first.newText, '#include \n'); + }); + }); + + group('LspDiagnosticsStore 存储与路径统一测试', () { + final store = LspDiagnosticsStore.instance; + + setUp(() { + store.clear(); + }); + + test('多文件诊断隔离与跨平台路径匹配', () { + const diag1 = LspDiagnostic( + range: LspRange( + start: LspPosition(line: 0, character: 0), + end: LspPosition(line: 0, character: 5), + ), + severity: LspDiagnosticSeverity.error, + message: 'Syntax error', + ); + + store.updateDiagnostics('D:/Project/src/main.c', [diag1]); + + // 各种变体路径均能精确匹配 + expect(store.getDiagnosticsForFile('d:/Project/src/main.c'), hasLength(1)); + expect(store.getDiagnosticsForFile('file:///D:/Project/src/main.c'), hasLength(1)); + expect(store.getDiagnosticsForFile(r'D:\Project\src\main.c'), hasLength(1)); + expect(store.getDiagnosticsForFile('D:/Project/src/other.c'), isEmpty); + + final line0Diags = store.getDiagnosticsForLine('D:/Project/src/main.c', 0); + expect(line0Diags, hasLength(1)); + expect(line0Diags.first.message, 'Syntax error'); + + final line1Diags = store.getDiagnosticsForLine('D:/Project/src/main.c', 1); + expect(line1Diags, isEmpty); + }); + + test('getDiagnosticAt 精准定位与就近容错', () { + const diag = LspDiagnostic( + range: LspRange( + start: LspPosition(line: 3, character: 5), + end: LspPosition(line: 3, character: 10), + ), + severity: LspDiagnosticSeverity.warning, + message: 'Unused variable', + ); + + store.updateDiagnostics('/workspace/test.c', [diag]); + + // 精准命中区间 [5, 10] + expect(store.getDiagnosticAt('/workspace/test.c', 3, 6)?.message, 'Unused variable'); + // 同行就近返回 + expect(store.getDiagnosticAt('/workspace/test.c', 3, 2)?.message, 'Unused variable'); + // 不同行返回 null + expect(store.getDiagnosticAt('/workspace/test.c', 4, 6), isNull); + }); + }); + + group('LspWorkspaceEditApplier 逆向安全应用测试', () { + test('单行局部替换', () { + final controller = CodeLineEditingController.fromText( + 'int main() {\n int val = foo();\n return 0;\n}', + ); + + final edit = LspWorkspaceEdit( + changes: { + 'file:///src/main.c': [ + const LspTextEdit( + range: LspRange( + start: LspPosition(line: 1, character: 12), + end: LspPosition(line: 1, character: 15), + ), + newText: 'bar', + ), + ], + }, + ); + + LspWorkspaceEditApplier.applyWorkspaceEdit(controller, edit, currentFilePath: '/src/main.c'); + expect(controller.codeLines[1].text, ' int val = bar();'); + }); + + test('同一行多处编辑自动逆序应用,不破坏列号偏移', () { + final controller = CodeLineEditingController.fromText( + 'AAA BBB CCC', + ); + + // 顺序为正向传入:先改 AAA 为 12345,再改 CCC 为 9 + final edits = [ + const LspTextEdit( + range: LspRange( + start: LspPosition(line: 0, character: 0), + end: LspPosition(line: 0, character: 3), + ), + newText: '12345', + ), + const LspTextEdit( + range: LspRange( + start: LspPosition(line: 0, character: 8), + end: LspPosition(line: 0, character: 11), + ), + newText: '9', + ), + ]; + + LspWorkspaceEditApplier.applyTextEdits(controller, edits); + // CCC 变成了 9,AAA 变成了 12345,中间 BBB 完整无损 + expect(controller.codeLines[0].text, '12345 BBB 9'); + }); + + test('跨行插入与头部插入', () { + final controller = CodeLineEditingController.fromText( + 'int x = 1;\nint y = 2;', + ); + + final edit = LspWorkspaceEdit( + changes: { + 'file:///test.c': [ + const LspTextEdit( + range: LspRange( + start: LspPosition(line: 0, character: 0), + end: LspPosition(line: 0, character: 0), + ), + newText: '// header\n', + ), + ], + }, + ); + + LspWorkspaceEditApplier.applyWorkspaceEdit(controller, edit, currentFilePath: 'test.c'); + expect(controller.codeLines[0].text, '// header'); + expect(controller.codeLines[1].text, 'int x = 1;'); + expect(controller.codeLines[2].text, 'int y = 2;'); + }); + }); + + group('CodeLineSpanBuilder 波浪下划线扩展测试', () { + testWidgets('控制器支持注入 spanBuilder 并不破坏基础文本', (tester) async { + late BuildContext testContext; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (ctx) { + testContext = ctx; + return const SizedBox(); + }, + ), + ), + ); + + bool spanBuilderCalled = false; + final controller = CodeLineEditingController.fromText( + 'int a = 10;\nfloat b = 20.0;', + const CodeLineOptions(), + ({ + required BuildContext context, + required int index, + required CodeLine codeLine, + required TextSpan textSpan, + required TextStyle style, + }) { + spanBuilderCalled = true; + return TextSpan( + text: codeLine.text, + style: style.copyWith( + decoration: TextDecoration.underline, + decorationStyle: TextDecorationStyle.wavy, + decorationColor: Colors.redAccent, + ), + ); + }, + ); + + expect(controller.codeLines.length, 2); + expect(controller.codeLines[0].text, 'int a = 10;'); + expect(controller.codeLines[1].text, 'float b = 20.0;'); + + final span = controller.buildTextSpan( + context: testContext, + index: 0, + textSpan: const TextSpan(text: 'int a = 10;'), + style: const TextStyle(), + ); + expect(spanBuilderCalled, isTrue); + expect(span.style?.decoration, equals(TextDecoration.underline)); + }); + }); + + group('EditorLspCoordinator 纯 LSP 协调与诊断生命周期测试', () { + test('无 LSP 服务时打开或修改文件绝不注入任何本地伪诊断', () { + const coordinator = EditorLspCoordinator(); + const testPath = '/test/unsupported/main.fake'; + final codeLines = CodeLines.fromText('int a = 10\nprintf("ok");'); + + // 确保初始状态干净 + LspDiagnosticsStore.instance.removeForFile(testPath); + expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty); + + // 打开文件 + coordinator.onFileOpened(testPath, 'int a = 10\nprintf("ok");', codeLines); + expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty); + + // 修改文件 + coordinator.onFileChanged(testPath, 'int a = 10', codeLines); + expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty); + }); + + test('文件关闭时自动清理该文件的 LSP 诊断', () { + const coordinator = EditorLspCoordinator(); + const testPath = '/test/project/main.c'; + + // 模拟 LSP 写入了诊断 + LspDiagnosticsStore.instance.updateDiagnostics(testPath, const [ + LspDiagnostic( + range: LspRange( + start: LspPosition(line: 0, character: 0), + end: LspPosition(line: 0, character: 5), + ), + message: 'LSP compile error', + ), + ]); + expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isNotEmpty); + + // 关闭文件 + coordinator.onFileClosed(testPath); + expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty); + }); + }); +} diff --git a/test/lsp_uninstall_and_lifecycle_test.dart b/test/lsp_uninstall_and_lifecycle_test.dart new file mode 100644 index 0000000..925e5b0 --- /dev/null +++ b/test/lsp_uninstall_and_lifecycle_test.dart @@ -0,0 +1,23 @@ +import 'package:code_editor/services/lsp/lsp_manager.dart'; +import 'package:code_editor/views/main_view.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('LSP Lifecycle & Uninstall Tests', () { + test('LspManager.stopSession handles nonexistent session gracefully', () async { + final manager = LspManager.instance; + // 停止一个未启动的 session 不抛出异常 + await expectLater(manager.stopSession('nonexistent_id'), completes); + }); + + test('MainView.clearPromptedLanguage removes record and allows re-prompting', () { + // 首次清除 + MainView.clearPromptedLanguage('c_cpp'); + MainView.clearPromptedLanguage(null); + // 清空全部后不抛异常 + expect(() => MainView.clearPromptedLanguage(null), returnsNormally); + }); + }); +} diff --git a/test/probe_boundary_test.dart b/test/probe_boundary_test.dart index c966498..55e872d 100644 --- a/test/probe_boundary_test.dart +++ b/test/probe_boundary_test.dart @@ -301,6 +301,26 @@ void main() { final txtFile = File(p.join(projectA.path, 'notes.txt'))..writeAsStringSync('hi'); provider.refreshSingleFileTask(currentFilePath: txtFile.path); expect(provider.taskTable.tasksOf(RunTaskType.singleFile), isEmpty); + + // 上一次运行单文件任务时的联动测试: + // 1. 在 cpp 文件设置单文件任务为 lastRunTask + provider.refreshSingleFileTask(currentFilePath: cppFile.path); + final cppTask = provider.taskTable.tasksOf(RunTaskType.singleFile).first; + await provider.setLastRunTask(cppTask); + expect(provider.lastRunTask?.id, 'detected_single_cpp'); + + // 2. 切换到 python 文件 -> lastRunTask 自动联动为当前 py 文件的任务 + provider.refreshSingleFileTask(currentFilePath: pyFile.path); + expect(provider.lastRunTask?.id, 'detected_single_python'); + expect(provider.lastRunTask?.name, 'Python: main.py'); + + // 3. 切换到不可运行文件(txt)-> lastRunTask 安全置空,不误跑切走的文件 + provider.refreshSingleFileTask(currentFilePath: txtFile.path); + expect(provider.lastRunTask, isNull); + + // 4. 再切回 cpp 文件 -> 重新恢复为 cpp 单文件任务 + provider.refreshSingleFileTask(currentFilePath: cppFile.path); + expect(provider.lastRunTask?.id, 'detected_single_cpp'); }); test('未映射到内置类型的自定义模块:任务归入 other,不能丢', () async { diff --git a/test/proot_path_mapper_test.dart b/test/proot_path_mapper_test.dart new file mode 100644 index 0000000..3f4efdd --- /dev/null +++ b/test/proot_path_mapper_test.dart @@ -0,0 +1,130 @@ +import 'dart:io'; +import 'package:code_editor/services/lsp/cpp_project_helper.dart'; +import 'package:code_editor/services/lsp/proot_path_mapper.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + group('PRootPathMapper Tests', () { + test('toGuestUri maps subpath within workspaceRoot to file:///workspace/...', () { + final guestUri = PRootPathMapper.toGuestUri( + '/data/data/com.example/files/workspace/src/main.c', + '/data/data/com.example/files/workspace', + ); + expect(guestUri, equals('file:///workspace/src/main.c')); + }); + + test('toGuestUri maps root directory itself to file:///workspace', () { + final guestUri = PRootPathMapper.toGuestUri( + '/data/data/com.example/files/workspace', + '/data/data/com.example/files/workspace', + ); + expect(guestUri, equals('file:///workspace')); + }); + + test('toGuestUri leaves path outside workspaceRoot with file:/// scheme', () { + final guestUri = PRootPathMapper.toGuestUri( + '/system/etc/hosts', + '/data/data/com.example/files/workspace', + ); + expect(guestUri, equals('file:///system/etc/hosts')); + }); + + test('fromGuestUriToHostPath restores guest URI to host absolute path', () { + final hostPath = PRootPathMapper.fromGuestUriToHostPath( + 'file:///workspace/src/main.c', + '/data/data/com.example/files/workspace', + ); + expect(hostPath.replaceAll('\\', '/'), equals('/data/data/com.example/files/workspace/src/main.c')); + }); + + test('fromGuestUriToHostPath restores root /workspace', () { + final hostPath = PRootPathMapper.fromGuestUriToHostPath( + 'file:///workspace', + '/data/data/com.example/files/workspace', + ); + expect(hostPath.replaceAll('\\', '/'), equals('/data/data/com.example/files/workspace')); + }); + + test('fromGuestUriToHostPath handles external file:/// URIs', () { + final hostPath = PRootPathMapper.fromGuestUriToHostPath( + 'file:///system/etc/hosts', + '/data/data/com.example/files/workspace', + ); + expect(hostPath.replaceAll('\\', '/'), equals('/system/etc/hosts')); + }); + + test('toGuestPath maps host workspace and subpath to container absolute path', () { + final guestPath = PRootPathMapper.toGuestPath( + '/data/data/com.example/files/workspace/src/main.c', + '/data/data/com.example/files/workspace', + ); + expect(guestPath, equals('/workspace/src/main.c')); + + final guestRoot = PRootPathMapper.toGuestPath( + '/data/data/com.example/files/workspace', + '/data/data/com.example/files/workspace', + ); + expect(guestRoot, equals('/workspace')); + }); + }); + + group('CppProjectHelper Tests', () { + late Directory tempProjectDir; + + setUp(() { + tempProjectDir = Directory.systemTemp.createTempSync('cpp_helper_test_'); + }); + + tearDown(() { + if (tempProjectDir.existsSync()) { + tempProjectDir.deleteSync(recursive: true); + } + }); + + test('Do nothing if compile_commands.json already exists in root', () async { + final existing = File(p.join(tempProjectDir.path, 'compile_commands.json')); + existing.writeAsStringSync('[]'); + + await CppProjectHelper.ensureCompileFlags(tempProjectDir.path); + + final flagsFile = File(p.join(tempProjectDir.path, 'compile_flags.txt')); + expect(flagsFile.existsSync(), isFalse); + }); + + test('Generates .clangd when build/compile_commands.json exists', () async { + final buildDir = Directory(p.join(tempProjectDir.path, 'build'))..createSync(); + File(p.join(buildDir.path, 'compile_commands.json')).writeAsStringSync('[]'); + + await CppProjectHelper.ensureCompileFlags(tempProjectDir.path); + + final clangdFile = File(p.join(tempProjectDir.path, '.clangd')); + expect(clangdFile.existsSync(), isTrue); + expect(clangdFile.readAsStringSync(), contains('CompilationDatabase: build')); + }); + + test('Auto scans header directories and generates compile_flags.txt with -I and -std=c++17', () async { + // Create include/, src/, and ggml/include/ + final incDir = Directory(p.join(tempProjectDir.path, 'include'))..createSync(); + final srcDir = Directory(p.join(tempProjectDir.path, 'src'))..createSync(); + final ggmlIncDir = Directory(p.join(tempProjectDir.path, 'ggml', 'include'))..createSync(recursive: true); + + // Add dummy headers + File(p.join(incDir.path, 'llama.h')).writeAsStringSync('#pragma once'); + File(p.join(srcDir.path, 'llama-impl.h')).writeAsStringSync('#pragma once'); + File(p.join(ggmlIncDir.path, 'ggml.h')).writeAsStringSync('#pragma once'); + + await CppProjectHelper.ensureCompileFlags(tempProjectDir.path); + + final flagsFile = File(p.join(tempProjectDir.path, 'compile_flags.txt')); + expect(flagsFile.existsSync(), isTrue); + + final content = flagsFile.readAsStringSync(); + expect(content, contains('-Iinclude')); + expect(content, contains('-Isrc')); + expect(content, contains('-Iggml/include')); + expect(content, contains('-xc++')); + expect(content, contains('-std=c++17')); + }); + }); +} diff --git a/test/proot_perl_fix_test.dart b/test/proot_perl_fix_test.dart new file mode 100644 index 0000000..e41144b --- /dev/null +++ b/test/proot_perl_fix_test.dart @@ -0,0 +1,67 @@ +import 'dart:io'; +import 'package:code_editor/services/distro_installer.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + late Directory tempRootDir; + + setUp(() { + tempBaseDir = Directory.systemTemp.createTempSync('proot_perl_fix_test_'); + tempRootDir = Directory(p.join(tempBaseDir.path, 'debian', 'rootfs'))..createSync(recursive: true); + }); + + tearDown(() { + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + }); + + group('PRoot Perl Fix Tests', () { + test('ensureDpkgConfiguration creates /etc/dpkg/dpkg.cfg.d/01_proot with force-unsafe-io', () async { + // 1. Initially without /etc/dpkg, should do nothing + await DistroInstaller.ensureDpkgConfiguration(tempRootDir); + expect(Directory(p.join(tempRootDir.path, 'etc', 'dpkg')).existsSync(), isFalse); + + // 2. With /etc/dpkg present, should create 01_proot + final dpkgDir = Directory(p.join(tempRootDir.path, 'etc', 'dpkg'))..createSync(recursive: true); + await DistroInstaller.ensureDpkgConfiguration(tempRootDir); + + final prootCfg = File(p.join(dpkgDir.path, 'dpkg.cfg.d', '01_proot')); + expect(prootCfg.existsSync(), isTrue); + expect(prootCfg.readAsStringSync(), equals('force-unsafe-io\n')); + }); + + test('buildLaunchConfig places .l2s inside rootDir and migrates legacy .l2s', () async { + // Setup legacy external .l2s directory + final legacyL2sDir = Directory(p.join(tempBaseDir.path, 'debian', '.l2s'))..createSync(recursive: true); + File(p.join(legacyL2sDir.path, 'meta_link_1')).writeAsStringSync('stand-in-content'); + + // Setup /bin/sh inside rootDir so targetShell resolves cleanly + final binDir = Directory(p.join(tempRootDir.path, 'bin'))..createSync(recursive: true); + File(p.join(binDir.path, 'sh')).writeAsStringSync('#!/bin/sh'); + + final launchConfig = await DistroManager().buildLaunchConfig( + systemName: 'debian', + customRootDir: tempRootDir, + ); + + // Verify guest environment has PROOT_L2S_DIR=/.l2s + expect(launchConfig.arguments, contains('PROOT_L2S_DIR=/.l2s')); + + // Verify host environment PROOT_L2S_DIR points to rootDir/.l2s + final targetL2sDir = Directory(p.join(tempRootDir.path, '.l2s')); + expect(targetL2sDir.existsSync(), isTrue); + expect(launchConfig.environment['PROOT_L2S_DIR'], equals(targetL2sDir.path)); + + // Verify legacy file was migrated + final migratedFile = File(p.join(targetL2sDir.path, 'meta_link_1')); + expect(migratedFile.existsSync(), isTrue); + expect(migratedFile.readAsStringSync(), equals('stand-in-content')); + }); + }); +} diff --git a/test/smart_prompts_builder_test.dart b/test/smart_prompts_builder_test.dart new file mode 100644 index 0000000..1922f2b --- /dev/null +++ b/test/smart_prompts_builder_test.dart @@ -0,0 +1,183 @@ +import 'package:code_editor/services/code_completion/smart_prompts_builder.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:re_editor/re_editor.dart'; + +class _MockLspCompletionProvider implements CompletionProvider { + final List mockPrompts; + _MockLspCompletionProvider(this.mockPrompts); + + @override + String get id => 'mock_lsp'; + + @override + bool get isAsync => true; + + @override + Future> provideCompletions(CompletionContext context) async { + return mockPrompts; + } + + @override + void dispose() {} +} + +void main() { + group('SmartCodeAutocompletePromptsBuilder LSP Tests', () { + testWidgets('SmartCodeAutocompletePromptsBuilder requests LSP asynchronously and applies fuzzy filter', (tester) async { + late BuildContext testContext; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (ctx) { + testContext = ctx; + return const SizedBox(); + }, + ), + ), + ); + + final provider = _MockLspCompletionProvider([ + SmartPrompt(word: 'print', kind: SmartPromptKind.function), + SmartPrompt(word: 'printf', kind: SmartPromptKind.function, type: 'int printf(const char *format, ...)'), + SmartPrompt(word: 'length', kind: SmartPromptKind.field), + SmartPrompt(word: 'FloatingActionButton', kind: SmartPromptKind.type), + ]); + + final builder = SmartCodeAutocompletePromptsBuilder( + customProviders: [provider], + ); + + // 1. Normal prefix 'pri' + final res1Future = builder.build( + testContext, + const CodeLine('pri'), + const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3), + ); + expect(res1Future, isA>()); + final res1 = await (res1Future as Future); + expect(res1, isNotNull); + expect(res1!.prompts.map((p) => p.word), containsAll(['print', 'printf'])); + + // 2. Typo correction: 'prnt' -> matches 'print' + final res2 = await (builder.build( + testContext, + const CodeLine('prnt'), + const CodeLineSelection(baseIndex: 0, baseOffset: 4, extentIndex: 0, extentOffset: 4), + ) as Future); + expect(res2, isNotNull); + expect(res2!.prompts.map((p) => p.word), contains('print')); + + // 3. Typo correction: 'lenght' -> matches 'length' + final res3 = await (builder.build( + testContext, + const CodeLine('lenght'), + const CodeLineSelection(baseIndex: 0, baseOffset: 6, extentIndex: 0, extentOffset: 6), + ) as Future); + expect(res3, isNotNull); + expect(res3!.prompts.map((p) => p.word), contains('length')); + + // 4. CamelCase: 'fab' -> matches 'FloatingActionButton' + final res4 = await (builder.build( + testContext, + const CodeLine('fab'), + const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3), + ) as Future); + expect(res4, isNotNull); + expect(res4!.prompts.first.word, equals('FloatingActionButton')); + }); + + testWidgets('字符串字面量内部不触发补全', (tester) async { + late BuildContext testContext; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (ctx) { + testContext = ctx; + return const SizedBox(); + }, + ), + ), + ); + + final provider = _MockLspCompletionProvider([ + SmartPrompt(word: 'printf', kind: SmartPromptKind.function), + ]); + + final builder = SmartCodeAutocompletePromptsBuilder( + customProviders: [provider], + ); + + // 光标处于 "hello pri" 内部 + final res = builder.build( + testContext, + const CodeLine('"hello pri"'), + const CodeLineSelection(baseIndex: 0, baseOffset: 10, extentIndex: 0, extentOffset: 10), + ); + expect(res, isNull); + }); + + testWidgets('输入点 . 触发符能正确触发异步补全', (tester) async { + late BuildContext testContext; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (ctx) { + testContext = ctx; + return const SizedBox(); + }, + ), + ), + ); + + final provider = _MockLspCompletionProvider([ + SmartPrompt(word: 'size', kind: SmartPromptKind.field), + SmartPrompt(word: 'clear', kind: SmartPromptKind.function), + ]); + + final builder = SmartCodeAutocompletePromptsBuilder( + customProviders: [provider], + ); + + final res = await (builder.build( + testContext, + const CodeLine('list.'), + const CodeLineSelection(baseIndex: 0, baseOffset: 5, extentIndex: 0, extentOffset: 5), + ) as Future); + + expect(res, isNotNull); + expect(res!.prompts.map((p) => p.word), containsAll(['size', 'clear'])); + }); + + testWidgets('当禁用 LSP 补全时直接返回 null 不打扰输入', (tester) async { + late BuildContext testContext; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Builder( + builder: (ctx) { + testContext = ctx; + return const SizedBox(); + }, + ), + ), + ); + + final builder = SmartCodeAutocompletePromptsBuilder( + enableLspCompletion: false, + ); + + final res = builder.build( + testContext, + const CodeLine('pri'), + const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3), + ); + + // 未装配任何 provider,直接返回 null + expect(res, isNull); + }); + }); +} diff --git a/test/terminal_test.dart b/test/terminal_test.dart index 61b1392..9ee3753 100644 --- a/test/terminal_test.dart +++ b/test/terminal_test.dart @@ -45,29 +45,8 @@ class FakeDistroProvider extends DistroProvider { } @override - Future deleteSystem(String systemName) async { - _systems.remove(systemName); - if (_selected == systemName) { - _selected = _systems.isNotEmpty ? _systems.first : null; - } - notifyListeners(); - } - - @override - Future importBuiltinAlpine({ - required String systemName, - dynamic onProgress, - bool Function()? isCancelled, - }) async { - _systems.add(systemName); - _selected = systemName; - notifyListeners(); - } - - @override - Future importFromCustomTarGz({ - required String systemName, - required dynamic tarGzFile, + Future importBuiltinUbuntu({ + String systemName = 'ubuntu', dynamic onProgress, bool Function()? isCancelled, }) async { diff --git a/test/toolchain_service_test.dart b/test/toolchain_service_test.dart index 86a22fe..d657488 100644 --- a/test/toolchain_service_test.dart +++ b/test/toolchain_service_test.dart @@ -94,14 +94,6 @@ void main() { expect(resolved, equals('echo "test" && ls -la')); }); - test('Alpine generates apk install preamble for make', () { - final resolved = ToolchainService.resolveCommand('make', DistroFamily.alpine); - expect(resolved, contains('command -v make')); - expect(resolved, contains('apk update && apk add --no-cache make build-base')); - expect(resolved, contains('make 编译构建工具')); - expect(resolved, endsWith('&& (make)')); - }); - test('Ubuntu generates apt-get install preamble for make', () { final resolved = ToolchainService.resolveCommand('make', DistroFamily.ubuntu); expect(resolved, contains('command -v make')); @@ -110,24 +102,10 @@ void main() { expect(resolved, endsWith('&& (make)')); }); - test('Debian generates apt-get install preamble for cmake', () { - final resolved = ToolchainService.resolveCommand('cmake -B build', DistroFamily.debian); - expect(resolved, contains('command -v cmake')); - expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential')); - expect(resolved, endsWith('&& (cmake -B build)')); - }); - - test('Arch generates pacman install preamble for gcc', () { - final resolved = ToolchainService.resolveCommand('gcc main.c', DistroFamily.arch); - expect(resolved, contains('command -v gcc')); - expect(resolved, contains('pacman -Sy --noconfirm base-devel')); - expect(resolved, endsWith('&& (gcc main.c)')); - }); - - test('Fedora generates dnf install preamble for python3', () { - final resolved = ToolchainService.resolveCommand('python3 app.py', DistroFamily.fedora); + test('All toolchain resolutions map to Ubuntu apt-get command', () { + final resolved = ToolchainService.resolveCommand('python3 app.py', DistroFamily.ubuntu); expect(resolved, contains('command -v python3')); - expect(resolved, contains('dnf install -y python3 python3-pip')); + expect(resolved, contains('apt-get install -y python3 python3-pip')); expect(resolved, endsWith('&& (python3 app.py)')); }); @@ -391,15 +369,13 @@ gcc main.c -o app } }); - test('ToolchainRequirement getInstallCommand automatically adds dpkg self-healing for Ubuntu and Debian', () { + test('ToolchainRequirement getInstallCommand automatically adds dpkg self-healing', () { final makeReq = ToolchainService.supportedTools['make']!; final ubuntuCmd = makeReq.getInstallCommand(DistroFamily.ubuntu); - final debianCmd = makeReq.getInstallCommand(DistroFamily.debian); - final alpineCmd = makeReq.getInstallCommand(DistroFamily.alpine); + final defaultCmd = makeReq.effectiveInstallCommand; expect(ubuntuCmd, contains('dpkg --configure -a')); - expect(debianCmd, contains('dpkg --configure -a')); - expect(alpineCmd, isNot(contains('dpkg --configure -a'))); + expect(defaultCmd, contains('dpkg --configure -a')); }); }); } diff --git a/test/widget_test.dart b/test/widget_test.dart index 1020bb6..7161ae1 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -40,8 +40,6 @@ import 'package:code_editor/widgets/virtual_keyboard_page_drawer.dart'; import 'package:code_editor/widgets/terminal_session_item_widget.dart'; import 'package:code_editor/models/terminal_session.dart'; import 'package:code_editor/providers/terminal_provider.dart'; -import 'package:code_editor/providers/distro_provider.dart'; -import 'package:code_editor/widgets/distro_selector_dialog.dart'; import 'package:code_editor/widgets/code_editor_app_bar.dart'; import 'package:code_editor/widgets/code_editor_drawer.dart'; import 'package:code_editor/utils/dialog_utils.dart'; @@ -3114,6 +3112,45 @@ void main() { ); }); + testWidgets('CodeEditorAppBar disables run button and runTasks menu item when isDetecting is true', (tester) async { + bool runCalled = false; + bool runTasksCalled = false; + + await tester.pumpWidget( + localizedApp( + Scaffold( + appBar: CodeEditorAppBar( + filePath: '/test/main.dart', + isDetecting: true, + onRun: () => runCalled = true, + onRunTasks: () => runTasksCalled = true, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 1. 运行按钮 (Play) 处于禁用状态 + final playBtnFinder = find.widgetWithIcon(IconButton, Icons.play_arrow); + expect(playBtnFinder, findsOneWidget); + final playBtn = tester.widget(playBtnFinder); + expect(playBtn.onPressed, isNull); + + // 2. 打开右上角更多菜单 + final moreBtnFinder = find.byIcon(Icons.more_vert); + expect(moreBtnFinder, findsOneWidget); + await tester.tap(moreBtnFinder); + await tester.pumpAndSettle(); + + // 3. 点击运行任务菜单项,验证不会触发回调 + final runTasksItemFinder = find.byIcon(Icons.playlist_play); + expect(runTasksItemFinder, findsOneWidget); + await tester.tap(runTasksItemFinder); + await tester.pumpAndSettle(); + expect(runTasksCalled, isFalse); + expect(runCalled, isFalse); + }); + testWidgets('VirtualKeyboardConfigView', (tester) async { await pumpNarrow( tester, @@ -3261,27 +3298,6 @@ void main() { await tester.pumpWidget(const SizedBox()); }); - testWidgets('DistroSelectorDialog import popup (en)', (tester) async { - await pumpNarrow( - tester, - MultiProvider( - providers: [ - ChangeNotifierProvider.value(value: DistroProvider()), - ChangeNotifierProvider.value(value: TerminalProvider()), - ], - child: localizedApp( - const Scaffold(body: DistroSelectorDialog()), - locale: const Locale('en'), - ), - ), - ); - - // 展开“导入系统”弹出菜单 - await tester.tap(find.byIcon(Icons.add_circle_outline)); - await tester.pumpAndSettle(); - expect(tester.takeException(), isNull, reason: '导入菜单展开后不应溢出'); - }); - testWidgets('CodeEditorTabBar with many modified tabs', (tester) async { final tabProvider = TabProvider(); for (int i = 0; i < 12; i++) {