From 5ac164b407c9d4cb651a7d1c07add3b4632ade26 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Wed, 16 Sep 2026 21:52:25 +0800 Subject: [PATCH] 1 --- lib/l10n/app_en.arb | 82 ++- lib/l10n/app_localizations.dart | 202 +++++++- lib/l10n/app_localizations_en.dart | 121 ++++- lib/l10n/app_localizations_zh.dart | 115 ++++- lib/l10n/app_zh.arb | 82 ++- lib/models/lsp_language_config.dart | 130 +++++ lib/services/distro_manager.dart | 90 +++- lib/services/internal_engine_service.dart | 176 +++++++ lib/services/lsp_config_service.dart | 155 ++++++ lib/services/toolchain_service.dart | 11 +- .../code_completion_management_view.dart | 483 ++++++++++++++++++ lib/views/main_view.dart | 83 +++ lib/views/settings_view.dart | 24 + lib/views/terminal_view.dart | 10 +- lib/widgets/lsp_language_edit_dialog.dart | 203 ++++++++ lib/widgets/terminal_drawer.dart | 11 +- test/internal_engine_and_lsp_config_test.dart | 260 ++++++++++ test/toolchain_service_test.dart | 54 +- 18 files changed, 2249 insertions(+), 43 deletions(-) create mode 100644 lib/models/lsp_language_config.dart create mode 100644 lib/services/internal_engine_service.dart create mode 100644 lib/services/lsp_config_service.dart create mode 100644 lib/views/code_completion_management_view.dart create mode 100644 lib/widgets/lsp_language_edit_dialog.dart create mode 100644 test/internal_engine_and_lsp_config_test.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7be60d3..36603e9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -824,5 +824,85 @@ "type": "String" } } - } + }, + "codeCompletionManagement": "Code Completion Management", + "codeCompletionSubtitle": "Manage language servers and code intelligence toolchains", + "internalEngineTitle": "Internal Code Intelligence Engine (Alpine)", + "internalEngineStatusReady": "Engine Ready", + "internalEngineStatusNotReady": "Engine Not Ready", + "internalEngineExtracting": "Preparing internal code intelligence engine...", + "installedStatus": "Ready", + "notInstalledStatus": "Component Not Installed", + "installComponent": "Install Component", + "installingComponent": "Installing {pkg}...", + "@installingComponent": { + "placeholders": { + "pkg": { + "type": "String" + } + } + }, + "installComponentSuccess": "{name} component installed successfully", + "@installComponentSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "installComponentFailed": "Failed to install component: {error}", + "@installComponentFailed": { + "placeholders": { + "error": { + "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": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "resetDefaultLanguages": "Reset to Defaults", + "resetDefaultLanguagesConfirm": "Are you sure you want to reset all language configurations to defaults?", + "languageDisplayName": "Language Name", + "languageDisplayNameHint": "e.g. C / C++", + "languageIdField": "Language ID", + "languageIdFieldHint": "For LSP protocol identification, e.g. cpp, rust", + "fileExtensionsField": "File Extensions", + "fileExtensionsFieldHint": "Comma-separated, e.g. .c, .cpp, .h", + "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", + "lspPackageMissingTitle": "{language} code intelligence component not installed", + "@lspPackageMissingTitle": { + "placeholders": { + "language": { + "type": "String" + } + } + }, + "lspPackageMissingMessage": "Install {pkg} ({command}) to enable code completion and error diagnostics", + "@lspPackageMissingMessage": { + "placeholders": { + "pkg": { + "type": "String" + }, + "command": { + "type": "String" + } + } + }, + "installNow": "Install Now", + "fieldRequired": "This field is required", + "languageConfigSaved": "Language configuration saved" } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index feb0c50..78ba0f4 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1073,13 +1073,13 @@ abstract class AppLocalizations { /// No description provided for @installedStatus. /// /// In zh, this message translates to: - /// **'已安装'** + /// **'已就绪'** String get installedStatus; /// No description provided for @notInstalledStatus. /// /// In zh, this message translates to: - /// **'未安装'** + /// **'未安装组件'** String get notInstalledStatus; /// No description provided for @downloadingStatus. @@ -2533,6 +2533,204 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'导入文件失败: {error}'** String importFilesFailed(String error); + + /// No description provided for @codeCompletionManagement. + /// + /// In zh, this message translates to: + /// **'代码补全管理'** + String get codeCompletionManagement; + + /// No description provided for @codeCompletionSubtitle. + /// + /// In zh, this message translates to: + /// **'管理各编程语言的智能补全与报错工具链'** + String get codeCompletionSubtitle; + + /// No description provided for @internalEngineTitle. + /// + /// In zh, this message translates to: + /// **'内部代码智能引擎 (Alpine)'** + String get internalEngineTitle; + + /// No description provided for @internalEngineStatusReady. + /// + /// In zh, this message translates to: + /// **'引擎已就绪'** + String get internalEngineStatusReady; + + /// 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: + /// **'正在准备内置代码智能引擎...'** + String get internalEngineExtracting; + + /// No description provided for @installComponent. + /// + /// In zh, this message translates to: + /// **'安装组件'** + String get installComponent; + + /// No description provided for @installingComponent. + /// + /// In zh, this message translates to: + /// **'正在安装 {pkg}...'** + String installingComponent(String pkg); + + /// No description provided for @installComponentSuccess. + /// + /// In zh, this message translates to: + /// **'{name} 组件安装成功'** + String installComponentSuccess(String name); + + /// No description provided for @installComponentFailed. + /// + /// In zh, this message translates to: + /// **'组件安装失败: {error}'** + String installComponentFailed(String error); + + /// No description provided for @editLanguageConfig. + /// + /// In zh, this message translates to: + /// **'编辑语言配置'** + String get editLanguageConfig; + + /// No description provided for @addLanguageConfig. + /// + /// In zh, this message translates to: + /// **'新增语言配置'** + String get addLanguageConfig; + + /// No description provided for @deleteLanguageConfirmTitle. + /// + /// In zh, this message translates to: + /// **'删除语言配置'** + String get deleteLanguageConfirmTitle; + + /// No description provided for @deleteLanguageConfirmMessage. + /// + /// In zh, this message translates to: + /// **'确定要删除 {name} 的代码补全配置吗?'** + String deleteLanguageConfirmMessage(String name); + + /// No description provided for @resetDefaultLanguages. + /// + /// In zh, this message translates to: + /// **'恢复默认配置'** + String get resetDefaultLanguages; + + /// No description provided for @resetDefaultLanguagesConfirm. + /// + /// In zh, this message translates to: + /// **'确定将所有语言配置重置为官方默认预设吗?'** + String get resetDefaultLanguagesConfirm; + + /// No description provided for @languageDisplayName. + /// + /// In zh, this message translates to: + /// **'语言名称'** + String get languageDisplayName; + + /// No description provided for @languageDisplayNameHint. + /// + /// In zh, this message translates to: + /// **'例如: C / C++'** + String get languageDisplayNameHint; + + /// No description provided for @languageIdField. + /// + /// In zh, this message translates to: + /// **'语言标识 (Language ID)'** + String get languageIdField; + + /// No description provided for @languageIdFieldHint. + /// + /// In zh, this message translates to: + /// **'用于 LSP 协议识别,如 cpp, rust'** + String get languageIdFieldHint; + + /// No description provided for @fileExtensionsField. + /// + /// In zh, this message translates to: + /// **'文件后缀'** + String get fileExtensionsField; + + /// No description provided for @fileExtensionsFieldHint. + /// + /// In zh, this message translates to: + /// **'以逗号分隔,如 .c, .cpp, .h'** + String get fileExtensionsFieldHint; + + /// No description provided for @serverCommandField. + /// + /// In zh, this message translates to: + /// **'服务启动命令'** + String get serverCommandField; + + /// No description provided for @serverCommandFieldHint. + /// + /// In zh, this message translates to: + /// **'例如: clangd'** + String get serverCommandFieldHint; + + /// No description provided for @serverArgsField. + /// + /// In zh, this message translates to: + /// **'启动参数'** + String get serverArgsField; + + /// No description provided for @serverArgsFieldHint. + /// + /// In zh, this message translates to: + /// **'多个参数以空格或逗号分隔'** + String get serverArgsFieldHint; + + /// No description provided for @apkPackageField. + /// + /// In zh, this message translates to: + /// **'Alpine 依赖包名'** + String get apkPackageField; + + /// No description provided for @apkPackageFieldHint. + /// + /// In zh, this message translates to: + /// **'用于一键安装,如 clang-extra-tools'** + String get apkPackageFieldHint; + + /// No description provided for @lspPackageMissingTitle. + /// + /// In zh, this message translates to: + /// **'未安装 {language} 代码智能组件'** + String lspPackageMissingTitle(String language); + + /// No description provided for @lspPackageMissingMessage. + /// + /// In zh, this message translates to: + /// **'安装 {pkg} ({command}) 即可获得精准代码补全与错误检查'** + String lspPackageMissingMessage(String pkg, String command); + + /// No description provided for @installNow. + /// + /// In zh, this message translates to: + /// **'一键安装'** + String get installNow; + + /// No description provided for @fieldRequired. + /// + /// In zh, this message translates to: + /// **'此项不能为空'** + String get fieldRequired; + + /// No description provided for @languageConfigSaved. + /// + /// In zh, this message translates to: + /// **'语言配置已保存'** + String get languageConfigSaved; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 528be17..bf445ba 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -558,10 +558,10 @@ class AppLocalizationsEn extends AppLocalizations { String get distroManagementTitle => 'System Management'; @override - String get installedStatus => 'Installed'; + String get installedStatus => 'Ready'; @override - String get notInstalledStatus => 'Not Installed'; + String get notInstalledStatus => 'Component Not Installed'; @override String get downloadingStatus => 'Downloading'; @@ -1534,4 +1534,121 @@ class AppLocalizationsEn extends AppLocalizations { String importFilesFailed(String error) { return 'Failed to import files: $error'; } + + @override + String get codeCompletionManagement => 'Code Completion Management'; + + @override + String get codeCompletionSubtitle => + 'Manage language servers and code intelligence toolchains'; + + @override + String get internalEngineTitle => + 'Internal Code Intelligence Engine (Alpine)'; + + @override + String get internalEngineStatusReady => 'Engine Ready'; + + @override + String get internalEngineStatusNotReady => 'Engine Not Ready'; + + @override + String get internalEngineExtracting => + 'Preparing internal code intelligence engine...'; + + @override + String get installComponent => 'Install Component'; + + @override + String installingComponent(String pkg) { + return 'Installing $pkg...'; + } + + @override + String installComponentSuccess(String name) { + return '$name component installed successfully'; + } + + @override + String installComponentFailed(String error) { + return 'Failed to install component: $error'; + } + + @override + String get editLanguageConfig => 'Edit Language Configuration'; + + @override + String get addLanguageConfig => 'Add Language Configuration'; + + @override + String get deleteLanguageConfirmTitle => 'Delete Language Configuration'; + + @override + String deleteLanguageConfirmMessage(String name) { + return 'Are you sure you want to delete code completion config for $name?'; + } + + @override + String get resetDefaultLanguages => 'Reset to Defaults'; + + @override + String get resetDefaultLanguagesConfirm => + 'Are you sure you want to reset all language configurations to defaults?'; + + @override + String get languageDisplayName => 'Language Name'; + + @override + String get languageDisplayNameHint => 'e.g. C / C++'; + + @override + String get languageIdField => 'Language ID'; + + @override + String get languageIdFieldHint => + 'For LSP protocol identification, e.g. cpp, rust'; + + @override + String get fileExtensionsField => 'File Extensions'; + + @override + String get fileExtensionsFieldHint => 'Comma-separated, e.g. .c, .cpp, .h'; + + @override + String get serverCommandField => 'Server Command'; + + @override + String get serverCommandFieldHint => 'e.g. clangd'; + + @override + String get serverArgsField => 'Server Arguments'; + + @override + String get serverArgsFieldHint => 'Space or comma separated'; + + @override + String get apkPackageField => 'Alpine APK Package'; + + @override + String get apkPackageFieldHint => + 'For one-click install, e.g. clang-extra-tools'; + + @override + String lspPackageMissingTitle(String language) { + return '$language code intelligence component not installed'; + } + + @override + String lspPackageMissingMessage(String pkg, String command) { + return 'Install $pkg ($command) to enable code completion and error diagnostics'; + } + + @override + String get installNow => 'Install Now'; + + @override + String get fieldRequired => 'This field is required'; + + @override + String get languageConfigSaved => 'Language configuration saved'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index c9330e2..98b63ce 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -545,10 +545,10 @@ class AppLocalizationsZh extends AppLocalizations { String get distroManagementTitle => '系统管理'; @override - String get installedStatus => '已安装'; + String get installedStatus => '已就绪'; @override - String get notInstalledStatus => '未安装'; + String get notInstalledStatus => '未安装组件'; @override String get downloadingStatus => '下载中'; @@ -1491,4 +1491,115 @@ class AppLocalizationsZh extends AppLocalizations { String importFilesFailed(String error) { return '导入文件失败: $error'; } + + @override + String get codeCompletionManagement => '代码补全管理'; + + @override + String get codeCompletionSubtitle => '管理各编程语言的智能补全与报错工具链'; + + @override + String get internalEngineTitle => '内部代码智能引擎 (Alpine)'; + + @override + String get internalEngineStatusReady => '引擎已就绪'; + + @override + String get internalEngineStatusNotReady => '引擎未就绪'; + + @override + String get internalEngineExtracting => '正在准备内置代码智能引擎...'; + + @override + String get installComponent => '安装组件'; + + @override + String installingComponent(String pkg) { + return '正在安装 $pkg...'; + } + + @override + String installComponentSuccess(String name) { + return '$name 组件安装成功'; + } + + @override + String installComponentFailed(String error) { + return '组件安装失败: $error'; + } + + @override + String get editLanguageConfig => '编辑语言配置'; + + @override + String get addLanguageConfig => '新增语言配置'; + + @override + String get deleteLanguageConfirmTitle => '删除语言配置'; + + @override + String deleteLanguageConfirmMessage(String name) { + return '确定要删除 $name 的代码补全配置吗?'; + } + + @override + String get resetDefaultLanguages => '恢复默认配置'; + + @override + String get resetDefaultLanguagesConfirm => '确定将所有语言配置重置为官方默认预设吗?'; + + @override + String get languageDisplayName => '语言名称'; + + @override + String get languageDisplayNameHint => '例如: C / C++'; + + @override + String get languageIdField => '语言标识 (Language ID)'; + + @override + String get languageIdFieldHint => '用于 LSP 协议识别,如 cpp, rust'; + + @override + String get fileExtensionsField => '文件后缀'; + + @override + String get fileExtensionsFieldHint => '以逗号分隔,如 .c, .cpp, .h'; + + @override + String get serverCommandField => '服务启动命令'; + + @override + String get serverCommandFieldHint => '例如: clangd'; + + @override + String get serverArgsField => '启动参数'; + + @override + String get serverArgsFieldHint => '多个参数以空格或逗号分隔'; + + @override + String get apkPackageField => 'Alpine 依赖包名'; + + @override + String get apkPackageFieldHint => '用于一键安装,如 clang-extra-tools'; + + @override + String lspPackageMissingTitle(String language) { + return '未安装 $language 代码智能组件'; + } + + @override + String lspPackageMissingMessage(String pkg, String command) { + return '安装 $pkg ($command) 即可获得精准代码补全与错误检查'; + } + + @override + String get installNow => '一键安装'; + + @override + String get fieldRequired => '此项不能为空'; + + @override + String get languageConfigSaved => '语言配置已保存'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 96ff9ab..5ef15ea 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -824,5 +824,85 @@ "type": "String" } } - } + }, + "codeCompletionManagement": "代码补全管理", + "codeCompletionSubtitle": "管理各编程语言的智能补全与报错工具链", + "internalEngineTitle": "内部代码智能引擎 (Alpine)", + "internalEngineStatusReady": "引擎已就绪", + "internalEngineStatusNotReady": "引擎未就绪", + "internalEngineExtracting": "正在准备内置代码智能引擎...", + "installedStatus": "已就绪", + "notInstalledStatus": "未安装组件", + "installComponent": "安装组件", + "installingComponent": "正在安装 {pkg}...", + "@installingComponent": { + "placeholders": { + "pkg": { + "type": "String" + } + } + }, + "installComponentSuccess": "{name} 组件安装成功", + "@installComponentSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "installComponentFailed": "组件安装失败: {error}", + "@installComponentFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "editLanguageConfig": "编辑语言配置", + "addLanguageConfig": "新增语言配置", + "deleteLanguageConfirmTitle": "删除语言配置", + "deleteLanguageConfirmMessage": "确定要删除 {name} 的代码补全配置吗?", + "@deleteLanguageConfirmMessage": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "resetDefaultLanguages": "恢复默认配置", + "resetDefaultLanguagesConfirm": "确定将所有语言配置重置为官方默认预设吗?", + "languageDisplayName": "语言名称", + "languageDisplayNameHint": "例如: C / C++", + "languageIdField": "语言标识 (Language ID)", + "languageIdFieldHint": "用于 LSP 协议识别,如 cpp, rust", + "fileExtensionsField": "文件后缀", + "fileExtensionsFieldHint": "以逗号分隔,如 .c, .cpp, .h", + "serverCommandField": "服务启动命令", + "serverCommandFieldHint": "例如: clangd", + "serverArgsField": "启动参数", + "serverArgsFieldHint": "多个参数以空格或逗号分隔", + "apkPackageField": "Alpine 依赖包名", + "apkPackageFieldHint": "用于一键安装,如 clang-extra-tools", + "lspPackageMissingTitle": "未安装 {language} 代码智能组件", + "@lspPackageMissingTitle": { + "placeholders": { + "language": { + "type": "String" + } + } + }, + "lspPackageMissingMessage": "安装 {pkg} ({command}) 即可获得精准代码补全与错误检查", + "@lspPackageMissingMessage": { + "placeholders": { + "pkg": { + "type": "String" + }, + "command": { + "type": "String" + } + } + }, + "installNow": "一键安装", + "fieldRequired": "此项不能为空", + "languageConfigSaved": "语言配置已保存" } \ No newline at end of file diff --git a/lib/models/lsp_language_config.dart b/lib/models/lsp_language_config.dart new file mode 100644 index 0000000..628f6b6 --- /dev/null +++ b/lib/models/lsp_language_config.dart @@ -0,0 +1,130 @@ +class LspLanguageConfig { + final String id; + final String name; + final String languageId; + final List fileExtensions; + final String serverCommand; + final List serverArgs; + final String apkPackage; + final bool enabled; + + const LspLanguageConfig({ + required this.id, + required this.name, + required this.languageId, + required this.fileExtensions, + required this.serverCommand, + this.serverArgs = const [], + required this.apkPackage, + this.enabled = true, + }); + + factory LspLanguageConfig.fromJson(Map json) { + return LspLanguageConfig( + id: json['id'] as String? ?? '', + name: json['name'] as String? ?? '', + languageId: json['languageId'] as String? ?? '', + fileExtensions: (json['fileExtensions'] as List?) + ?.map((e) => e.toString().trim()) + .where((e) => e.isNotEmpty) + .toList() ?? + [], + serverCommand: json['serverCommand'] as String? ?? '', + serverArgs: (json['serverArgs'] as List?) + ?.map((e) => e.toString()) + .toList() ?? + [], + apkPackage: json['apkPackage'] as String? ?? '', + enabled: json['enabled'] as bool? ?? true, + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'languageId': languageId, + 'fileExtensions': fileExtensions, + 'serverCommand': serverCommand, + 'serverArgs': serverArgs, + 'apkPackage': apkPackage, + 'enabled': enabled, + }; + } + + LspLanguageConfig copyWith({ + String? id, + String? name, + String? languageId, + List? fileExtensions, + String? serverCommand, + List? serverArgs, + String? apkPackage, + bool? enabled, + }) { + return LspLanguageConfig( + id: id ?? this.id, + name: name ?? this.name, + languageId: languageId ?? this.languageId, + fileExtensions: fileExtensions ?? this.fileExtensions, + serverCommand: serverCommand ?? this.serverCommand, + serverArgs: serverArgs ?? this.serverArgs, + apkPackage: apkPackage ?? this.apkPackage, + enabled: enabled ?? this.enabled, + ); + } + + /// 官方默认预设语言列表 + static List get defaultPresets => [ + const LspLanguageConfig( + id: 'c_cpp', + name: 'C / C++', + languageId: 'cpp', + fileExtensions: ['.c', '.cpp', '.cc', '.cxx', '.h', '.hpp'], + serverCommand: 'clangd', + serverArgs: ['--background-index'], + apkPackage: 'clang-extra-tools', + enabled: true, + ), + const LspLanguageConfig( + id: 'python', + name: 'Python', + languageId: 'python', + fileExtensions: ['.py'], + serverCommand: 'pylsp', + serverArgs: [], + apkPackage: 'py3-lsp-server', + enabled: true, + ), + const LspLanguageConfig( + id: 'rust', + name: 'Rust', + languageId: 'rust', + fileExtensions: ['.rs'], + serverCommand: 'rust-analyzer', + serverArgs: [], + apkPackage: 'rust-analyzer', + enabled: true, + ), + const LspLanguageConfig( + id: 'go', + name: 'Go', + languageId: 'go', + fileExtensions: ['.go'], + serverCommand: 'gopls', + serverArgs: [], + apkPackage: 'gopls', + enabled: true, + ), + const LspLanguageConfig( + id: 'shell', + name: 'Shell Script', + languageId: 'shellscript', + fileExtensions: ['.sh', '.bash'], + serverCommand: 'bash-language-server', + serverArgs: ['start'], + apkPackage: 'bash-language-server', + enabled: true, + ), + ]; +} diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index 0c80b4d..b2e1929 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -51,24 +51,37 @@ enum DistroFamily { class HeadlessCancelToken { Process? _process; bool _cancelled = false; + Directory? _rootDir; bool get isCancelled => _cancelled; - void _attach(Process process) { + void _attach(Process process, {Directory? rootDir}) { _process = process; + _rootDir = rootDir; if (_cancelled) { try { process.kill(ProcessSignal.sigkill); } catch (_) {} + if (rootDir != null) { + DistroManager().cleanStaleLocks(rootDir); + } } } - /// 取消:标记状态并杀掉当前子进程(若有) + /// 取消:标记状态并先尝试发送 SIGINT 优雅退出,随后超时强杀并清理陈旧锁 void cancel() { _cancelled = true; try { - _process?.kill(ProcessSignal.sigkill); + _process?.kill(ProcessSignal.sigint); } catch (_) {} + Future.delayed(const Duration(milliseconds: 300), () { + try { + _process?.kill(ProcessSignal.sigkill); + } catch (_) {} + if (_rootDir != null) { + DistroManager().cleanStaleLocks(_rootDir!); + } + }); } } @@ -373,6 +386,7 @@ class DistroManager { String? workspacePath, String prootPath = 'proot', String? customCommand, + Directory? customRootDir, }) async { // 1. 本地 Shell 特殊处理 if (systemName == 'host') { @@ -393,7 +407,7 @@ class DistroManager { } // 2. Linux 容器 (PRoot 隔离环境) - final rootDir = await getSystemRootDir(systemName); + final rootDir = customRootDir ?? await getSystemRootDir(systemName); // 前置守卫:rootfs 必须先真实存在。否则下方一系列 ensure*(DNS/CA 证书/shm/l2s/sysdata) // 会 recursive 地创建出一套空壳目录,把"并不存在的系统"伪造成系统选择器里的已安装项。 if (!rootDir.existsSync()) { @@ -419,13 +433,13 @@ class DistroManager { await DistroInstaller.ensureJavaConfiguration(rootDir); // 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失) - final shmDir = await _ensureShmDir(systemName); + final shmDir = await _ensureShmDir(systemName, customBaseDir: customRootDir?.parent); // 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范) - final l2sDir = await _ensureL2sDir(systemName); + final l2sDir = await _ensureL2sDir(systemName, customBaseDir: customRootDir?.parent); // 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据) - final sysdataDir = await _ensureSysdataDir(systemName); + final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: customRootDir?.parent); String tmpPath = '/tmp'; try { @@ -610,9 +624,9 @@ class DistroManager { } /// 确保容器实例拥有独立的 POSIX 共享内存目录(对标 proot-distro shm.py) - Future _ensureShmDir(String systemName) async { + Future _ensureShmDir(String systemName, {Directory? customBaseDir}) async { try { - final baseDir = await getBaseDistrosDir(); + final baseDir = customBaseDir ?? await getBaseDistrosDir(); final shmDir = Directory(p.join(baseDir.path, systemName, 'shm')); if (!shmDir.existsSync()) { shmDir.createSync(recursive: true); @@ -625,9 +639,9 @@ class DistroManager { } /// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro login/__init__.py) - Future _ensureL2sDir(String systemName) async { + Future _ensureL2sDir(String systemName, {Directory? customBaseDir}) async { try { - final baseDir = await getBaseDistrosDir(); + final baseDir = customBaseDir ?? await getBaseDistrosDir(); final l2sDir = Directory(p.join(baseDir.path, systemName, '.l2s')); if (!l2sDir.existsSync()) { l2sDir.createSync(recursive: true); @@ -640,9 +654,9 @@ class DistroManager { } /// 确保容器实例拥有独立的 sysdata 桩目录与 SELinux 覆盖节点(对标 proot-distro sysdata.py) - Future _ensureSysdataDir(String systemName) async { + Future _ensureSysdataDir(String systemName, {Directory? customBaseDir}) async { try { - final baseDir = await getBaseDistrosDir(); + final baseDir = customBaseDir ?? await getBaseDistrosDir(); final sysdataDir = Directory(p.join(baseDir.path, systemName, 'sysdata')); if (!sysdataDir.existsSync()) { sysdataDir.createSync(recursive: true); @@ -824,9 +838,14 @@ class DistroManager { } } - /// 清理此前异常崩溃或中断留下的陈旧锁文件(防止 groupadd/useradd 等报 /etc/*.lock 锁占用或找不到) + /// 清理此前异常崩溃或中断留下的陈旧锁文件(防止 groupadd/useradd 等报 /etc/*.lock 锁占用,以及 APT/APK 包管理器死锁) + void cleanStaleLocks(Directory rootDir) { + _cleanStaleLocks(rootDir); + } + void _cleanStaleLocks(Directory rootDir) { try { + // 1. /etc 目录下的陈旧锁文件与备份文件(防止 groupadd/useradd 等报 /etc/*.lock 锁占用或找不到) final etcDir = Directory(p.join(rootDir.path, 'etc')); if (etcDir.existsSync()) { for (final entry in etcDir.listSync(followLinks: false)) { @@ -843,6 +862,41 @@ class DistroManager { } } } + + // 2. Debian / Ubuntu (APT / dpkg) 核心锁文件 + final dpkgLockFiles = [ + p.join(rootDir.path, 'var', 'lib', 'dpkg', 'lock'), + p.join(rootDir.path, 'var', 'lib', 'dpkg', 'lock-frontend'), + p.join(rootDir.path, 'var', 'lib', 'apt', 'lists', 'lock'), + p.join(rootDir.path, 'var', 'cache', 'apt', 'archives', 'lock'), + ]; + for (final filePath in dpkgLockFiles) { + final f = File(filePath); + if (f.existsSync()) { + try { + f.deleteSync(); + debugPrint('[DistroManager] 清理 APT/dpkg 陈旧锁文件: $filePath'); + } catch (_) {} + } + } + + // 3. Alpine Linux (APK) 锁文件 + final apkLock = File(p.join(rootDir.path, 'lib', 'apk', 'db', 'lock')); + if (apkLock.existsSync()) { + try { + apkLock.deleteSync(); + debugPrint('[DistroManager] 清理 APK 陈旧锁文件: ${apkLock.path}'); + } catch (_) {} + } + + // 4. Fedora / RPM 锁文件 + final rpmLock = File(p.join(rootDir.path, 'var', 'lib', 'rpm', '.rpm.lock')); + if (rpmLock.existsSync()) { + try { + rpmLock.deleteSync(); + debugPrint('[DistroManager] 清理 RPM 陈旧锁文件: ${rpmLock.path}'); + } catch (_) {} + } } catch (e) { debugPrint('[DistroManager] 清理陈旧锁文件异常 (非阻塞): $e'); } @@ -862,12 +916,15 @@ class DistroManager { Duration timeout = const Duration(seconds: 120), HeadlessCancelToken? cancelToken, void Function(String chunk)? onStdout, + Directory? customRootDir, }) async { try { + final rootDir = customRootDir ?? (await getSystemRootDir(systemName)); final config = await buildLaunchConfig( systemName: systemName, workspacePath: workspacePath, customCommand: command, + customRootDir: customRootDir, ); final process = await Process.start( @@ -876,11 +933,12 @@ class DistroManager { environment: config.environment, workingDirectory: config.workingDirectory, ); - cancelToken?._attach(process); + cancelToken?._attach(process, rootDir: rootDir); if (cancelToken?.isCancelled ?? false) { try { process.kill(ProcessSignal.sigkill); } catch (_) {} + _cleanStaleLocks(rootDir); return null; } @@ -903,6 +961,7 @@ class DistroManager { try { process.kill(ProcessSignal.sigkill); } catch (_) {} + _cleanStaleLocks(rootDir); return -1; }, ); @@ -913,6 +972,7 @@ class DistroManager { ); if (cancelToken?.isCancelled ?? false) { + _cleanStaleLocks(rootDir); return null; } diff --git a/lib/services/internal_engine_service.dart b/lib/services/internal_engine_service.dart new file mode 100644 index 0000000..1232a54 --- /dev/null +++ b/lib/services/internal_engine_service.dart @@ -0,0 +1,176 @@ +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'; +import '../widgets/distro_extract_dialog.dart'; +import 'distro_installer.dart'; +import 'distro_manager.dart'; + +/// 内部私有代码智能引擎服务 (files/internal_engine/alpine) +class InternalEngineService extends ChangeNotifier { + static final InternalEngineService instance = InternalEngineService._(); + InternalEngineService._(); + + /// 测试自定义引擎根目录 + @visibleForTesting + Directory? customEngineDir; + + bool _isChecking = false; + bool get isChecking => _isChecking; + + /// 获取引擎主目录: `/internal_engine/alpine` + Future getEngineDir() 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; + } + + /// 获取 rootfs 目录: `/internal_engine/alpine/rootfs` + Future getRootfsDir() async { + final engineDir = await getEngineDir(); + return Directory(p.join(engineDir.path, 'rootfs')); + } + + /// 检查内置 Alpine 引擎是否已完整安装 + Future isEngineInstalled() async { + try { + final engineDir = await getEngineDir(); + final marker = File(p.join(engineDir.path, '.installed')); + if (!marker.existsSync()) return false; + + 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(); + } catch (e) { + debugPrint('检查内置引擎异常: $e'); + return false; + } + } + + /// 确保内置引擎已准备完毕;若未安装,弹出模态解压弹窗进行解压 + Future ensureEngineReady(BuildContext context) async { + if (await isEngineInstalled()) { + return true; + } + + if (!context.mounted) return false; + final l10n = AppLocalizations.of(context); + + _isChecking = true; + notifyListeners(); + + try { + final success = await DistroExtractDialog.show( + context: context, + systemName: l10n?.internalEngineTitle ?? '内部代码智能引擎 (Alpine)', + task: (onProgress, isCancelled) async { + await extractEngine( + onProgress: onProgress, + isCancelled: isCancelled, + ); + }, + ); + + _isChecking = false; + notifyListeners(); + return success; + } catch (e) { + _isChecking = false; + notifyListeners(); + debugPrint('解压内部引擎失败: $e'); + return false; + } + } + + /// 解压 Asset 中的 Alpine minirootfs 到私有引擎目录 + 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); + } + + await DistroInstaller.installFromBytes( + tarGzBytes: bytes, + targetDir: rootfsDir, + onProgress: onProgress, + isCancelled: isCancelled, + ); + + // 写入安装完成标记文件 + final engineDir = await getEngineDir(); + final marker = File(p.join(engineDir.path, '.installed')); + await marker.writeAsString('ready'); + } + + /// 检查某命令(如 clangd, rust-analyzer)是否在内置 Alpine 中已安装 + Future isCommandInstalled(String command) async { + if (!await isEngineInstalled() || command.trim().isEmpty) { + return false; + } + + try { + final rootfs = await getRootfsDir(); + final res = await DistroManager().runHeadlessCommand( + systemName: 'alpine_internal', + 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'); + return false; + } + } + + /// 在内置 Alpine 中安装指定 apk 软件包 + Future installPackage( + String apkPackage, { + void Function(String chunk)? onOutput, + }) async { + if (!await isEngineInstalled() || apkPackage.trim().isEmpty) { + return false; + } + + try { + final rootfs = await getRootfsDir(); + final res = await DistroManager().runHeadlessCommand( + systemName: 'alpine_internal', + customRootDir: rootfs, + command: 'apk add --no-cache ${apkPackage.trim()}', + timeout: const Duration(minutes: 5), + onStdout: onOutput, + ); + return res != null && res.exitCode == 0; + } catch (e) { + debugPrint('安装内置引擎软件包异常: $e'); + return false; + } + } +} diff --git a/lib/services/lsp_config_service.dart b/lib/services/lsp_config_service.dart new file mode 100644 index 0000000..eeeb337 --- /dev/null +++ b/lib/services/lsp_config_service.dart @@ -0,0 +1,155 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import '../models/lsp_language_config.dart'; + +/// 语言服务器配置管理器 +class LspConfigService extends ChangeNotifier { + static final LspConfigService instance = LspConfigService._(); + LspConfigService._(); + + /// 测试自定义存储目录 + @visibleForTesting + Directory? customBaseDir; + + List _configs = []; + bool _isLoaded = false; + + List get configs => List.unmodifiable(_configs); + bool get isLoaded => _isLoaded; + + /// 获取配置文件路径: `/internal_engine/lsp_languages.json` + Future getConfigFile() async { + final Directory baseDir; + if (customBaseDir != null) { + baseDir = customBaseDir!; + } else { + final appDir = await getApplicationSupportDirectory(); + final rootPath = p.basename(appDir.path) == 'files' + ? appDir.path + : p.join(appDir.path, 'files'); + baseDir = Directory(p.join(rootPath, 'internal_engine')); + } + + if (!baseDir.existsSync()) { + baseDir.createSync(recursive: true); + } + return File(p.join(baseDir.path, 'lsp_languages.json')); + } + + /// 加载配置,若缺失预设语言则自动增量追加合并并回写 + Future> loadConfigs({bool forceReload = false}) async { + if (_isLoaded && !forceReload) { + return _configs; + } + + final file = await getConfigFile(); + List loaded = []; + bool needSave = false; + + if (!file.existsSync()) { + loaded = List.from(LspLanguageConfig.defaultPresets); + 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(); + } + } catch (e) { + debugPrint('读取 lsp_languages.json 异常: $e,使用默认预设'); + loaded = List.from(LspLanguageConfig.defaultPresets); + 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; + _isLoaded = true; + + if (needSave) { + await _writeToDisk(); + } + + notifyListeners(); + return _configs; + } + + /// 保存完整配置列表到本地 JSON + Future saveConfigs(List newConfigs) async { + _configs = List.from(newConfigs); + _isLoaded = true; + await _writeToDisk(); + notifyListeners(); + } + + /// 更新或新增某项语言配置 + Future updateConfig(LspLanguageConfig config) async { + final index = _configs.indexWhere((e) => e.id == config.id); + if (index >= 0) { + _configs[index] = config; + } else { + _configs.add(config); + } + await _writeToDisk(); + notifyListeners(); + } + + /// 删除某项语言配置 + Future deleteConfig(String id) async { + _configs.removeWhere((e) => e.id == id); + await _writeToDisk(); + notifyListeners(); + } + + /// 恢复官方默认预设 + Future resetToDefaults() async { + _configs = List.from(LspLanguageConfig.defaultPresets); + await _writeToDisk(); + notifyListeners(); + } + + /// 根据文件扩展名查找匹配的已启用语言配置 + LspLanguageConfig? findByExtension(String ext) { + if (ext.isEmpty) return null; + 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 null; + } + + Future _writeToDisk() async { + try { + final file = await getConfigFile(); + final encoder = const JsonEncoder.withIndent(' '); + final jsonString = encoder.convert(_configs.map((e) => e.toJson()).toList()); + file.writeAsStringSync(jsonString, flush: true); + } catch (e) { + debugPrint('保存 lsp_languages.json 失败: $e'); + } + } +} diff --git a/lib/services/toolchain_service.dart b/lib/services/toolchain_service.dart index f80dfd7..b1ce6a1 100644 --- a/lib/services/toolchain_service.dart +++ b/lib/services/toolchain_service.dart @@ -19,8 +19,15 @@ class ToolchainRequirement { required this.installCommands, }); - /// 获取指定发行版家族下的安装命令 - String? getInstallCommand(DistroFamily family) => installCommands[family]; + /// 获取指定发行版家族下的安装命令(对于 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; + } } /// 预编译软件源与工具链检测/安装适配服务 diff --git a/lib/views/code_completion_management_view.dart b/lib/views/code_completion_management_view.dart new file mode 100644 index 0000000..ec1a3f4 --- /dev/null +++ b/lib/views/code_completion_management_view.dart @@ -0,0 +1,483 @@ +import 'package:flutter/material.dart'; +import '../l10n/app_localizations.dart'; +import '../models/lsp_language_config.dart'; +import '../services/internal_engine_service.dart'; +import '../services/lsp_config_service.dart'; +import '../utils/dialog_utils.dart'; +import '../widgets/lsp_language_edit_dialog.dart'; + +/// 代码补全与语言服务管理视图 +class CodeCompletionManagementView extends StatefulWidget { + const CodeCompletionManagementView({super.key}); + + @override + State createState() => + _CodeCompletionManagementViewState(); +} + +class _CodeCompletionManagementViewState + extends State { + final _lspService = LspConfigService.instance; + final _engineService = InternalEngineService.instance; + + final Map _installedStatus = {}; + bool _isLoadingStatus = false; + bool _engineReady = false; + + @override + void initState() { + super.initState(); + _loadData(); + } + + Future _loadData() async { + await _lspService.loadConfigs(); + await _checkCommandsStatus(); + } + + Future _checkCommandsStatus() async { + if (!mounted) return; + setState(() => _isLoadingStatus = true); + + final engineReady = await _engineService.isEngineInstalled(); + if (!engineReady) { + if (mounted) { + setState(() { + _engineReady = false; + _installedStatus.clear(); + _isLoadingStatus = false; + }); + } + return; + } + + final newStatus = {}; + for (final config in _lspService.configs) { + final isInstalled = + await _engineService.isCommandInstalled(config.serverCommand); + newStatus[config.id] = isInstalled; + } + + if (mounted) { + setState(() { + _engineReady = true; + _installedStatus.addAll(newStatus); + _isLoadingStatus = false; + }); + } + } + + Future _handleEdit(LspLanguageConfig config) async { + final updated = await LspLanguageEditDialog.show( + context, + initialConfig: config, + ); + if (updated != null && mounted) { + final l10n = AppLocalizations.of(context); + await _lspService.updateConfig(updated); + if (mounted && l10n != null) { + DialogUtils.showSuccessToast(context, l10n.languageConfigSaved); + } + _checkCommandsStatus(); + } + } + + Future _handleAdd() async { + 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); + } + _checkCommandsStatus(); + } + } + + Future _handleDelete(LspLanguageConfig config) async { + final l10n = AppLocalizations.of(context)!; + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(l10n.deleteLanguageConfirmTitle), + content: Text(l10n.deleteLanguageConfirmMessage(config.name)), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(ctx).colorScheme.error, + ), + onPressed: () => Navigator.of(ctx).pop(true), + child: Text(l10n.delete), + ), + ], + ), + ); + + if (confirmed == true && mounted) { + await _lspService.deleteConfig(config.id); + setState(() { + _installedStatus.remove(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'), + ); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + + return Scaffold( + 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, + onPressed: _handleAdd, + ), + ], + ), + body: ListenableBuilder( + listenable: _lspService, + builder: (context, _) { + final configs = _lspService.configs; + + return RefreshIndicator( + onRefresh: _checkCommandsStatus, + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + children: [ + _buildEngineStatusCard(context, theme, l10n), + const SizedBox(height: 16), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), + child: Row( + children: [ + Text( + l10n.languageSection, + style: theme.textTheme.titleSmall?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + const Spacer(), + if (_isLoadingStatus) + const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ], + ), + ), + const SizedBox(height: 6), + ...configs.map((cfg) => _buildLanguageItem(context, theme, l10n, cfg)), + ], + ), + ); + }, + ), + ); + } + + Widget _buildEngineStatusCard( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + ) { + final isInstalled = _engineReady; + final colorScheme = theme.colorScheme; + + final (bgColor, borderColor, icon, statusText, subText) = 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( + elevation: 0, + color: bgColor, + shape: RoundedRectangleBorder( + side: BorderSide(color: borderColor), + borderRadius: BorderRadius.circular(12), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + children: [ + 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, + ), + ), + ], + ), + ), + if (!isInstalled) + TextButton( + onPressed: () async { + final ready = await _engineService.ensureEngineReady(context); + if (ready && context.mounted) { + _checkCommandsStatus(); + } + }, + child: Text(l10n.installNow), + ), + ], + ), + ), + ); + } + + Widget _buildLanguageItem( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + LspLanguageConfig config, + ) { + final isInstalled = _installedStatus[config.id] ?? false; + final colorScheme = theme.colorScheme; + + return Card( + elevation: 0, + margin: const EdgeInsets.symmetric(vertical: 6), + color: colorScheme.surfaceContainerLow, + shape: RoundedRectangleBorder( + side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.5)), + 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, + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + config.name, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(width: 8), + _buildStatusBadge(theme, l10n, isInstalled), + ], + ), + Text( + '${config.serverCommand} (${config.apkPackage}) • id: ${config.languageId}', + style: theme.textTheme.bodySmall?.copyWith( + color: colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + 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/main_view.dart b/lib/views/main_view.dart index 536feb4..d52359d 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -22,8 +22,12 @@ import 'package:code_editor/widgets/distro_selector_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/internal_engine_service.dart'; +import 'package:code_editor/services/lsp_config_service.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; class MainView extends StatefulWidget { @@ -39,6 +43,76 @@ class _MainViewState extends State { /// 最近一次已触发探测的 (工程, 系统) 组合,用于去重与"系统就绪后补探测" String? _lastProbeKey; + String? _lastActiveFile; + static final Set _promptedLspLanguages = {}; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + InternalEngineService.instance.ensureEngineReady(context); + LspConfigService.instance.loadConfigs(); + } + }); + } + + 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; + + if (!await InternalEngineService.instance.isEngineInstalled()) return; + + final isInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand); + if (!isInstalled && mounted) { + if (!_promptedLspLanguages.contains(config.id)) { + _promptedLspLanguages.add(config.id); + _promptInstallLspComponent(config); + } + } + } + + Future _promptInstallLspComponent(LspLanguageConfig config) async { + final l10n = AppLocalizations.of(context); + if (l10n == null || !mounted) return; + + final install = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(l10n.lspPackageMissingTitle(config.name)), + content: Text(l10n.lspPackageMissingMessage(config.apkPackage, config.serverCommand)), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () => Navigator.of(ctx).pop(true), + child: Text(l10n.installNow), + ), + ], + ), + ); + + if (install == true && mounted) { + final success = await DialogUtils.showSyncLoadingDialog( + context, + message: l10n.installingComponent(config.apkPackage), + task: () => InternalEngineService.instance.installPackage(config.apkPackage), + ); + if (!mounted) return; + + if (success) { + DialogUtils.showSuccessToast(context, l10n.installComponentSuccess(config.name)); + } else { + DialogUtils.showErrorToast(context, l10n.installComponentFailed('apk add exit with non-zero')); + } + } + } + static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) { return listen ? context.watch() : context.read(); } @@ -407,6 +481,15 @@ 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; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _checkLspForFile(currentFile); + } + }); + } + if (rootPath == null) { if (_lastProjectRoot != null) { _lastProjectRoot = null; diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index 1591c74..58abbd8 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -7,6 +7,7 @@ import 'package:code_editor/providers/settings_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../widgets/color_palette_dialog.dart'; +import 'code_completion_management_view.dart'; import 'virtual_keyboard_config_view.dart'; /// 设置页面 @@ -58,6 +59,7 @@ class SettingsView extends StatelessWidget { _buildPinLineNumbersTile(context, provider, l10n), _buildVirtualKeyboardTile(context, provider, l10n), _buildVirtualKeyboardConfigTile(context, provider, l10n), + _buildCodeCompletionManagementTile(context, l10n), const Divider(height: 32, indent: 16, endIndent: 16), @@ -963,6 +965,28 @@ class SettingsView extends StatelessWidget { ); } + /// 编辑区:代码补全与语言服务管理条目 + Widget _buildCodeCompletionManagementTile( + BuildContext context, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + + return ListTile( + leading: Icon(Icons.psychology_outlined, color: theme.colorScheme.primary), + title: Text(l10n.codeCompletionManagement), + subtitle: Text(l10n.codeCompletionSubtitle), + trailing: const Icon(Icons.chevron_right), + onTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const CodeCompletionManagementView(), + ), + ); + }, + ); + } + /// 终端:终端小键盘开关条目(与编辑区开关相互独立) diff --git a/lib/views/terminal_view.dart b/lib/views/terminal_view.dart index 51d9039..0f34613 100644 --- a/lib/views/terminal_view.dart +++ b/lib/views/terminal_view.dart @@ -9,7 +9,6 @@ import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; import 'package:code_editor/utils/terminal_theme_helper.dart'; import 'package:code_editor/widgets/distro_extract_dialog.dart'; -import 'package:code_editor/widgets/distro_selector_dialog.dart'; import 'package:code_editor/widgets/terminal_drawer.dart'; import 'package:code_editor/widgets/terminal_keyboard_sink.dart'; import 'package:code_editor/widgets/terminal_modifier_state.dart'; @@ -150,14 +149,7 @@ class _TerminalViewState extends State { ], ), actions: [ - // 系统选择与管理按钮(位于会话列表左侧) - IconButton( - icon: const Icon(Icons.dns_outlined), - tooltip: l10n.systemManagementTooltip, - onPressed: () { - DistroSelectorDialog.show(context); - }, - ), + // 系统选择与管理入口已收敛隐藏,统一使用默认主系统 (Ubuntu) IconButton( icon: const Icon(Icons.format_list_bulleted), tooltip: l10n.sessionListTooltip, diff --git a/lib/widgets/lsp_language_edit_dialog.dart b/lib/widgets/lsp_language_edit_dialog.dart new file mode 100644 index 0000000..1f8f6ae --- /dev/null +++ b/lib/widgets/lsp_language_edit_dialog.dart @@ -0,0 +1,203 @@ +import 'package:flutter/material.dart'; +import '../l10n/app_localizations.dart'; +import '../models/lsp_language_config.dart'; + +/// 语言配置编辑 / 新增弹窗表单 +class LspLanguageEditDialog extends StatefulWidget { + final LspLanguageConfig? initialConfig; + + const LspLanguageEditDialog({ + super.key, + this.initialConfig, + }); + + /// 快捷弹出对话框,返回修改后的配置或 null(若取消) + static Future show( + BuildContext context, { + LspLanguageConfig? initialConfig, + }) { + return showDialog( + context: context, + builder: (ctx) => LspLanguageEditDialog(initialConfig: initialConfig), + ); + } + + @override + State createState() => _LspLanguageEditDialogState(); +} + +class _LspLanguageEditDialogState extends State { + final _formKey = GlobalKey(); + + late final TextEditingController _nameController; + late final TextEditingController _languageIdController; + late final TextEditingController _extensionsController; + late final TextEditingController _commandController; + late final TextEditingController _argsController; + late final TextEditingController _apkPackageController; + + @override + void initState() { + super.initState(); + final init = widget.initialConfig; + _nameController = TextEditingController(text: init?.name ?? ''); + _languageIdController = TextEditingController(text: init?.languageId ?? ''); + _extensionsController = TextEditingController( + text: init?.fileExtensions.join(', ') ?? '', + ); + _commandController = TextEditingController(text: init?.serverCommand ?? ''); + _argsController = TextEditingController( + text: init?.serverArgs.join(' ') ?? '', + ); + _apkPackageController = TextEditingController(text: init?.apkPackage ?? ''); + } + + @override + void dispose() { + _nameController.dispose(); + _languageIdController.dispose(); + _extensionsController.dispose(); + _commandController.dispose(); + _argsController.dispose(); + _apkPackageController.dispose(); + super.dispose(); + } + + void _onSave() { + if (!_formKey.currentState!.validate()) { + return; + } + + final rawExtensions = _extensionsController.text.split(RegExp(r'[,,\s]+')); + final cleanedExtensions = []; + for (final raw in rawExtensions) { + final trimmed = raw.trim(); + if (trimmed.isEmpty) continue; + final withDot = trimmed.startsWith('.') ? trimmed : '.$trimmed'; + if (!cleanedExtensions.contains(withDot)) { + cleanedExtensions.add(withDot); + } + } + + final rawArgs = _argsController.text.trim(); + final cleanedArgs = rawArgs.isEmpty + ? [] + : rawArgs + .split(RegExp(r'[\s,]+')) + .map((e) => e.trim()) + .where((e) => e.isNotEmpty) + .toList(); + + final id = widget.initialConfig?.id ?? + _nameController.text + .trim() + .toLowerCase() + .replaceAll(RegExp(r'[^a-z0-9_]'), '_'); + + final updated = LspLanguageConfig( + id: id.isEmpty ? 'custom_lang_${DateTime.now().millisecondsSinceEpoch}' : id, + name: _nameController.text.trim(), + languageId: _languageIdController.text.trim(), + fileExtensions: cleanedExtensions, + serverCommand: _commandController.text.trim(), + serverArgs: cleanedArgs, + apkPackage: _apkPackageController.text.trim(), + enabled: widget.initialConfig?.enabled ?? true, + ); + + Navigator.of(context).pop(updated); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final isEditing = widget.initialConfig != null; + + return AlertDialog( + title: Text(isEditing ? l10n.editLanguageConfig : l10n.addLanguageConfig), + content: SingleChildScrollView( + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextFormField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.languageDisplayName, + hintText: l10n.languageDisplayNameHint, + prefixIcon: const Icon(Icons.title, size: 20), + ), + validator: (v) => + (v == null || v.trim().isEmpty) ? l10n.fieldRequired : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _languageIdController, + decoration: InputDecoration( + labelText: l10n.languageIdField, + hintText: l10n.languageIdFieldHint, + prefixIcon: const Icon(Icons.code, size: 20), + ), + validator: (v) => + (v == null || v.trim().isEmpty) ? l10n.fieldRequired : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _extensionsController, + decoration: InputDecoration( + labelText: l10n.fileExtensionsField, + hintText: l10n.fileExtensionsFieldHint, + prefixIcon: const Icon(Icons.extension_outlined, size: 20), + ), + validator: (v) => + (v == null || v.trim().isEmpty) ? l10n.fieldRequired : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _commandController, + decoration: InputDecoration( + labelText: l10n.serverCommandField, + hintText: l10n.serverCommandFieldHint, + prefixIcon: const Icon(Icons.terminal, size: 20), + ), + validator: (v) => + (v == null || v.trim().isEmpty) ? l10n.fieldRequired : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _argsController, + decoration: InputDecoration( + labelText: l10n.serverArgsField, + hintText: l10n.serverArgsFieldHint, + prefixIcon: const Icon(Icons.tune, size: 20), + ), + ), + const SizedBox(height: 12), + TextFormField( + controller: _apkPackageController, + decoration: InputDecoration( + labelText: l10n.apkPackageField, + hintText: l10n.apkPackageFieldHint, + prefixIcon: const Icon(Icons.inventory_2_outlined, size: 20), + ), + validator: (v) => + (v == null || v.trim().isEmpty) ? l10n.fieldRequired : null, + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: _onSave, + child: Text(l10n.save), + ), + ], + ); + } +} diff --git a/lib/widgets/terminal_drawer.dart b/lib/widgets/terminal_drawer.dart index 19a70f1..1d623c9 100644 --- a/lib/widgets/terminal_drawer.dart +++ b/lib/widgets/terminal_drawer.dart @@ -1,8 +1,8 @@ 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/project_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; -import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/widgets/terminal_session_item_widget.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -56,12 +56,9 @@ class TerminalDrawer extends StatelessWidget { ), onPressed: () { final distroProvider = context.read(); - final currentSystem = distroProvider?.selectedSystem; - if (currentSystem == null) { - DialogUtils.showToast(context, l10n.noSystemSelectedWarning); - return; - } - // 基于当前选择的系统创建新终端并直接激活进入 + final currentSystem = distroProvider?.selectedSystem ?? DistroRepository.defaultSystemName; + + // 基于当前系统(默认 Ubuntu)创建新终端并直接激活进入 final projectRoot = context.read()?.rootPath; provider.createSession( name: l10n.sessionDefaultName, diff --git a/test/internal_engine_and_lsp_config_test.dart b/test/internal_engine_and_lsp_config_test.dart new file mode 100644 index 0000000..fc9ca2b --- /dev/null +++ b/test/internal_engine_and_lsp_config_test.dart @@ -0,0 +1,260 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:code_editor/l10n/app_localizations.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'; +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:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + late LspConfigService lspConfigService; + late InternalEngineService engineService; + + setUp(() { + SharedPreferences.setMockInitialValues({}); + tempBaseDir = Directory.systemTemp.createTempSync('lsp_engine_test_'); + + lspConfigService = LspConfigService.instance; + lspConfigService.customBaseDir = tempBaseDir; + + engineService = InternalEngineService.instance; + engineService.customEngineDir = Directory(p.join(tempBaseDir.path, 'alpine')); + }); + + tearDown(() { + lspConfigService.customBaseDir = null; + engineService.customEngineDir = null; + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + }); + + Widget buildTestWidget({ + required Widget child, + Locale locale = const Locale('zh'), + }) { + return MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [ + Locale('zh'), + Locale('en'), + ], + locale: locale, + home: child, + ); + } + + group('LspConfigService Tests', () { + test('Initial load creates default presets and writes 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); + + final file = await lspConfigService.getConfigFile(); + expect(file.existsSync(), isTrue); + + final content = jsonDecode(file.readAsStringSync()) as List; + expect(content.length, equals(configs.length)); + }); + + test('Incremental merge appends missing default presets without overwriting user configs', () async { + final file = await lspConfigService.getConfigFile(); + // Write only custom Python config + const customConfig = [ + { + 'id': 'python', + 'name': 'My Custom Python', + 'languageId': 'python', + 'fileExtensions': ['.py', '.pyw'], + 'serverCommand': 'my_pylsp', + 'serverArgs': ['--verbose'], + 'apkPackage': 'py3-lsp-server', + '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(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); + }); + + test('findByExtension resolves language config correctly', () async { + await lspConfigService.loadConfigs(forceReload: true); + + final cConfig = lspConfigService.findByExtension('.c'); + expect(cConfig, isNotNull); + expect(cConfig!.id, equals('c_cpp')); + + final cppConfig = lspConfigService.findByExtension('cpp'); + expect(cppConfig, isNotNull); + expect(cppConfig!.id, equals('c_cpp')); + + final pyConfig = lspConfigService.findByExtension('.py'); + expect(pyConfig, isNotNull); + expect(pyConfig!.id, equals('python')); + + final unknown = lspConfigService.findByExtension('.unknown'); + expect(unknown, 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); + + 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); + + // 3. Reset to defaults + await lspConfigService.resetToDefaults(); + expect(lspConfigService.configs.any((c) => c.id == 'shell'), isTrue); + expect(lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp').serverCommand, equals('clangd')); + }); + }); + + group('InternalEngineService Tests', () { + test('isEngineInstalled returns false when not installed', () async { + final installed = await engineService.isEngineInstalled(); + expect(installed, isFalse); + }); + + test('isEngineInstalled returns true when .installed and rootfs exist', () async { + final engineDir = await engineService.getEngineDir(); + final rootfs = await engineService.getRootfsDir(); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + File(p.join(engineDir.path, '.installed')).writeAsStringSync('ready'); + + final installed = await engineService.isEngineInstalled(); + expect(installed, isTrue); + }); + }); + + group('CodeCompletionManagementView & LspLanguageEditDialog Widget Tests', () { + testWidgets('Management view renders all language items and engine card in Chinese', (tester) async { + await lspConfigService.loadConfigs(forceReload: true); + + await tester.pumpWidget(buildTestWidget( + child: const CodeCompletionManagementView(), + locale: const Locale('zh'), + )); + await tester.pumpAndSettle(); + + expect(find.text('代码补全管理'), findsOneWidget); + expect(find.text('内部代码智能引擎 (Alpine)'), 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 { + await lspConfigService.loadConfigs(forceReload: true); + + await tester.pumpWidget(buildTestWidget( + child: const CodeCompletionManagementView(), + locale: const Locale('en'), + )); + 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.byTooltip('Add Language Configuration'), findsOneWidget); + }); + + testWidgets('Edit button pops LspLanguageEditDialog and saves modifications', (tester) async { + await lspConfigService.loadConfigs(forceReload: true); + + await tester.pumpWidget(buildTestWidget( + child: const CodeCompletionManagementView(), + locale: const Locale('zh'), + )); + await tester.pumpAndSettle(); + + // Tap first edit icon + final editButtons = find.byIcon(Icons.edit_outlined); + expect(editButtons, findsWidgets); + + await tester.tap(editButtons.first); + await tester.pumpAndSettle(); + + // Dialog is shown + expect(find.text('编辑语言配置'), findsOneWidget); + expect(find.text('语言名称'), findsOneWidget); + + // Modify language name + final nameField = find.widgetWithText(TextFormField, 'C / C++'); + await tester.enterText(nameField, 'C / C++ (Clang)'); + + // Tap Save + await tester.tap(find.text('保存')); + await tester.pumpAndSettle(); + + // Updated name is shown in list + expect(find.text('C / C++ (Clang)'), findsOneWidget); + expect(lspConfigService.configs.any((c) => c.name == 'C / C++ (Clang)'), isTrue); + + // Settle SnackBar timer + await tester.pump(const Duration(seconds: 4)); + }); + + testWidgets('Delete button prompts confirmation and removes language', (tester) async { + await lspConfigService.loadConfigs(forceReload: true); + + await tester.pumpWidget(buildTestWidget( + child: const CodeCompletionManagementView(), + locale: const Locale('zh'), + )); + await tester.pumpAndSettle(); + + expect(find.text('Python'), findsOneWidget); + + // Find delete button for Python (index 1) + final deleteButtons = find.byIcon(Icons.delete_outline); + await tester.tap(deleteButtons.at(1)); + await tester.pumpAndSettle(); + + expect(find.text('删除语言配置'), findsOneWidget); + expect(find.text('确定要删除 Python 的代码补全配置吗?'), findsOneWidget); + + // Confirm delete + await tester.tap(find.text('删除')); + await tester.pumpAndSettle(); + + // Python should now be gone + expect(find.text('Python'), findsNothing); + expect(lspConfigService.configs.any((c) => c.id == 'python'), isFalse); + + // Settle SnackBar timer + await tester.pump(const Duration(seconds: 4)); + }); + }); +} diff --git a/test/toolchain_service_test.dart b/test/toolchain_service_test.dart index 58f5511..86a22fe 100644 --- a/test/toolchain_service_test.dart +++ b/test/toolchain_service_test.dart @@ -347,9 +347,59 @@ gcc main.c -o app ); session.write('Some previous output'); session.clear(); - // clear emits VT100 ANSI sequences - expect(session.bufferText.trim(), isEmpty); session.dispose(); }); }); + + group('PackageManager Lock Cleanup & Self Healing Tests', () { + test('cleanStaleLocks removes APT/dpkg, APK, RPM, and /etc lock files', () { + final tempDir = Directory.systemTemp.createTempSync('lock_cleanup_test_'); + try { + // Create dummy lock files + final filesToCreate = [ + 'etc/group.lock', + 'etc/passwd.lock', + 'var/lib/dpkg/lock', + 'var/lib/dpkg/lock-frontend', + 'var/lib/apt/lists/lock', + 'var/cache/apt/archives/lock', + 'lib/apk/db/lock', + 'var/lib/rpm/.rpm.lock', + ]; + + for (final rel in filesToCreate) { + final file = File(p.join(tempDir.path, rel)); + file.createSync(recursive: true); + expect(file.existsSync(), isTrue); + } + + // Non-lock files should not be deleted + final normalFile = File(p.join(tempDir.path, 'var/lib/dpkg/status')); + normalFile.createSync(recursive: true); + + DistroManager().cleanStaleLocks(tempDir); + + for (final rel in filesToCreate) { + final file = File(p.join(tempDir.path, rel)); + expect(file.existsSync(), isFalse, reason: '$rel should have been deleted'); + } + expect(normalFile.existsSync(), isTrue, reason: 'Normal status file should remain'); + } finally { + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + } + }); + + test('ToolchainRequirement getInstallCommand automatically adds dpkg self-healing for Ubuntu and Debian', () { + final makeReq = ToolchainService.supportedTools['make']!; + final ubuntuCmd = makeReq.getInstallCommand(DistroFamily.ubuntu); + final debianCmd = makeReq.getInstallCommand(DistroFamily.debian); + final alpineCmd = makeReq.getInstallCommand(DistroFamily.alpine); + + expect(ubuntuCmd, contains('dpkg --configure -a')); + expect(debianCmd, contains('dpkg --configure -a')); + expect(alpineCmd, isNot(contains('dpkg --configure -a'))); + }); + }); }