From 59125d185c998f88cff32f3def63d08ac6383d38 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Wed, 16 Sep 2026 20:43:39 +0800 Subject: [PATCH] 1 --- android/app/src/main/AndroidManifest.xml | 12 + .../code_editor/AppDocumentsProvider.kt | 188 +++++ assets/gradle/code_editor_model.init.gradle | 97 +++ lib/l10n/app_en.arb | 143 +++- lib/l10n/app_localizations.dart | 180 +++++ lib/l10n/app_localizations_en.dart | 125 +++ lib/l10n/app_localizations_zh.dart | 122 +++ lib/l10n/app_zh.arb | 143 +++- lib/main.dart | 6 +- lib/models/notice_item.dart | 156 ++++ lib/models/project_task_table.dart | 48 ++ lib/models/run_task_type.dart | 62 ++ lib/providers/notice_center.dart | 186 +++++ lib/providers/project_provider.dart | 34 + lib/providers/run_provider.dart | 739 ++++++++++++++---- lib/services/distro_manager.dart | 66 +- lib/services/file_service.dart | 6 +- .../project_modules/cargo_project_module.dart | 104 +++ .../project_modules/cmake_project_module.dart | 79 ++ .../project_modules/dart_project_module.dart | 60 ++ .../project_modules/gradle_ide_model.dart | 228 ++++++ .../gradle_project_module.dart | 415 ++++------ .../project_modules/make_project_module.dart | 95 +++ .../project_modules/npm_project_module.dart | 88 +++ .../project_modules/project_module.dart | 90 ++- .../project_modules/project_probe.dart | 329 ++++++++ .../single_file_task_detector.dart | 142 ++++ .../standard_project_modules.dart | 218 +----- lib/services/project_task_detector.dart | 19 - lib/services/project_task_dispatcher.dart | 467 ++++++----- lib/services/run_task_storage_service.dart | 23 +- lib/utils/notice_text_resolver.dart | 52 ++ lib/views/main_view.dart | 172 ++-- lib/widgets/code_editor_app_bar.dart | 10 +- lib/widgets/code_editor_drawer.dart | 90 ++- lib/widgets/code_editor_widget.dart | 119 ++- lib/widgets/notice_host.dart | 351 +++++++++ lib/widgets/probe_cancel_guard.dart | 49 ++ lib/widgets/run_tasks_dialog.dart | 241 +++--- lib/widgets/terminal_entry_guard.dart | 49 ++ .../re_editor/lib/src/_code_editable.dart | 19 +- .../re_editor/lib/src/_code_extensions.dart | 4 +- packages/re_editor/lib/src/_code_field.dart | 23 +- .../re_editor/lib/src/_code_paragraph.dart | 17 +- packages/re_editor/lib/src/_code_scroll.dart | 180 ++++- .../re_editor/lib/src/_code_selection.dart | 4 +- pubspec.yaml | 1 + test/code_editor_menu_test.dart | 68 ++ test/code_editor_paragraph_refresh_test.dart | 115 +++ test/distro_multi_system_test.dart | 27 + test/drawer_import_files_test.dart | 257 ++++++ test/gradle_ide_model_test.dart | 144 ++++ test/gradle_project_module_test.dart | 349 +++------ test/notice_center_test.dart | 111 +++ test/notice_host_test.dart | 189 +++++ test/probe_boundary_test.dart | 721 +++++++++++++++++ test/probe_cancel_guard_test.dart | 147 ++++ test/probe_fix_verification_test.dart | 223 ++++++ test/project_probe_queue_test.dart | 316 ++++++++ test/run_provider_probe_split_test.dart | 281 +++++++ test/run_system_test.dart | 167 +++- test/terminal_entry_guard_test.dart | 79 ++ test/terminal_font_size_and_gesture_test.dart | 3 +- test/widget_test.dart | 57 ++ 64 files changed, 7912 insertions(+), 1393 deletions(-) create mode 100644 android/app/src/main/kotlin/com/example/code_editor/AppDocumentsProvider.kt create mode 100644 assets/gradle/code_editor_model.init.gradle create mode 100644 lib/models/notice_item.dart create mode 100644 lib/models/project_task_table.dart create mode 100644 lib/models/run_task_type.dart create mode 100644 lib/providers/notice_center.dart create mode 100644 lib/services/project_modules/cargo_project_module.dart create mode 100644 lib/services/project_modules/cmake_project_module.dart create mode 100644 lib/services/project_modules/dart_project_module.dart create mode 100644 lib/services/project_modules/gradle_ide_model.dart create mode 100644 lib/services/project_modules/make_project_module.dart create mode 100644 lib/services/project_modules/npm_project_module.dart create mode 100644 lib/services/project_modules/project_probe.dart create mode 100644 lib/services/project_modules/single_file_task_detector.dart delete mode 100644 lib/services/project_task_detector.dart create mode 100644 lib/utils/notice_text_resolver.dart create mode 100644 lib/widgets/notice_host.dart create mode 100644 lib/widgets/probe_cancel_guard.dart create mode 100644 lib/widgets/terminal_entry_guard.dart create mode 100644 test/code_editor_paragraph_refresh_test.dart create mode 100644 test/drawer_import_files_test.dart create mode 100644 test/gradle_ide_model_test.dart create mode 100644 test/notice_center_test.dart create mode 100644 test/notice_host_test.dart create mode 100644 test/probe_boundary_test.dart create mode 100644 test/probe_cancel_guard_test.dart create mode 100644 test/probe_fix_verification_test.dart create mode 100644 test/project_probe_queue_test.dart create mode 100644 test/run_provider_probe_split_test.dart create mode 100644 test/terminal_entry_guard_test.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 969e2f7..72198cf 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -37,6 +37,18 @@ + + + + + + + ?): Cursor { + val result = MatrixCursor(projection ?: DEFAULT_ROOT_PROJECTION) + val row = result.newRow() + row.add(DocumentsContract.Root.COLUMN_ROOT_ID, ROOT_ID) + row.add(DocumentsContract.Root.COLUMN_DOCUMENT_ID, getDocIdForFile(baseDir)) + row.add(DocumentsContract.Root.COLUMN_TITLE, "CodeEditor") + row.add(DocumentsContract.Root.COLUMN_SUMMARY, "files") + row.add( + DocumentsContract.Root.COLUMN_FLAGS, + DocumentsContract.Root.FLAG_SUPPORTS_CREATE or + DocumentsContract.Root.FLAG_SUPPORTS_IS_CHILD or + DocumentsContract.Root.FLAG_LOCAL_ONLY + ) + row.add(DocumentsContract.Root.COLUMN_ICON, R.mipmap.ic_launcher) + row.add(DocumentsContract.Root.COLUMN_AVAILABLE_BYTES, baseDir.freeSpace) + return result + } + + override fun queryDocument(documentId: String?, projection: Array?): Cursor { + val result = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) + val file = getFileForDocId(documentId) + includeFile(result, file) + return result + } + + override fun queryChildDocuments( + parentDocumentId: String?, + projection: Array?, + sortOrder: String? + ): Cursor { + val result = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) + val parent = getFileForDocId(parentDocumentId) + parent.listFiles()?.forEach { file -> + includeFile(result, file) + } + return result + } + + override fun openDocument( + documentId: String?, + mode: String?, + signal: CancellationSignal? + ): ParcelFileDescriptor { + val file = getFileForDocId(documentId) + val accessMode = ParcelFileDescriptor.parseMode(mode) + return ParcelFileDescriptor.open(file, accessMode) + } + + override fun createDocument( + parentDocumentId: String?, + mimeType: String?, + displayName: String? + ): String { + val parent = getFileForDocId(parentDocumentId) + val file = File(parent, displayName ?: "unnamed") + if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) { + if (!file.mkdir() && !file.isDirectory) { + throw FileNotFoundException("无法创建目录: ${file.path}") + } + } else { + if (!file.createNewFile() && !file.isFile) { + throw FileNotFoundException("无法创建文件: ${file.path}") + } + } + return getDocIdForFile(file) + } + + override fun deleteDocument(documentId: String?) { + val file = getFileForDocId(documentId) + if (!file.deleteRecursively()) { + throw FileNotFoundException("无法删除: ${file.path}") + } + } + + override fun renameDocument(documentId: String?, displayName: String?): String? { + if (displayName == null) throw FileNotFoundException("新名称不能为空") + val file = getFileForDocId(documentId) + val target = File(file.parentFile, displayName) + if (!file.renameTo(target)) { + throw FileNotFoundException("重命名失败: ${file.path} -> ${target.path}") + } + return getDocIdForFile(target) + } + + override fun isChildDocument(parentDocumentId: String?, documentId: String?): Boolean { + val parent = getFileForDocId(parentDocumentId) + val child = getFileForDocId(documentId) + return child.canonicalPath.startsWith(parent.canonicalPath) + } + + private fun getFileForDocId(docId: String?): File { + if (docId == null) throw FileNotFoundException("DocId 不能为空") + val file = File(docId) + if (!file.exists()) { + throw FileNotFoundException("文件不存在: ${file.path}") + } + return file + } + + private fun getDocIdForFile(file: File): String { + return file.absolutePath + } + + private fun includeFile(result: MatrixCursor, file: File) { + val row = result.newRow() + row.add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, getDocIdForFile(file)) + row.add(DocumentsContract.Document.COLUMN_DISPLAY_NAME, file.name) + row.add(DocumentsContract.Document.COLUMN_LAST_MODIFIED, file.lastModified()) + row.add(DocumentsContract.Document.COLUMN_SIZE, file.length()) + + var flags = DocumentsContract.Document.FLAG_SUPPORTS_DELETE or + DocumentsContract.Document.FLAG_SUPPORTS_RENAME + + if (file.isDirectory) { + flags = flags or DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE + row.add(DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.MIME_TYPE_DIR) + } else { + flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_WRITE + val mime = getMimeType(file) + row.add(DocumentsContract.Document.COLUMN_MIME_TYPE, mime) + } + row.add(DocumentsContract.Document.COLUMN_FLAGS, flags) + } + + private fun getMimeType(file: File): String { + val ext = file.extension + return if (ext.isNotEmpty()) { + MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.lowercase()) ?: "application/octet-stream" + } else { + "application/octet-stream" + } + } +} diff --git a/assets/gradle/code_editor_model.init.gradle b/assets/gradle/code_editor_model.init.gradle new file mode 100644 index 0000000..5997447 --- /dev/null +++ b/assets/gradle/code_editor_model.init.gradle @@ -0,0 +1,97 @@ +// code_editor 结构化探测脚本(Gradle init script) +// +// 作用:把 Gradle 自身的项目/任务模型序列化成 JSON,写入工程内的 +// .code_editor/gradle_ide_model.json(该目录同时被挂载为容器内 /workspace), +// Flutter 端直接按字段读取 —— 不再解析任何人类可读文本输出。 +// +// 调用方式(由 App 生成,见 GradleProjectModule): +// LC_ALL=C LANG=C sh ./gradlew --console=plain -q -I .code_editor/code_editor_model.init.gradle help +// +// 说明:本文件由 App 在 warmUp 阶段写入工程目录,请勿手工修改(会被覆盖)。 + +import groovy.json.JsonOutput + +gradle.projectsEvaluated { + try { + def root = gradle.rootProject + def projects = [] + + root.allprojects.each { proj -> + def tasks = [] + try { + proj.tasks.each { t -> + def group = null + def description = null + try { group = t.group } catch (ignored) { } + try { description = t.description } catch (ignored) { } + tasks << [ + name : t.name, + path : t.path, + group : group, + description: description, + type : t.class.name + ] + } + } catch (ignored) { } + + def plugins = [] + try { plugins = proj.plugins.collect { it.class.name } } catch (ignored) { } + + def sourceSets = [] + try { + def ss = proj.extensions.findByName('sourceSets') + if (ss != null) { + sourceSets = ss.names.toList() + } + } catch (ignored) { } + + def configurations = [] + try { + configurations = proj.configurations.names.toList() + } catch (ignored) { } + + def javaVersion = null + try { + def ext = proj.extensions.findByName('java') + if (ext != null && ext.hasProperty('sourceCompatibility')) { + javaVersion = ext.sourceCompatibility?.toString() + } + } catch (ignored) { } + + projects << [ + path : proj.path, + name : proj.name, + description : proj.description, + buildFile : proj.buildFile?.absolutePath, + plugins : plugins, + sourceSets : sourceSets, + configurations: configurations, + javaVersion : javaVersion, + tasks : tasks + ] + } + + def model = [ + schema : 1, + generatedAt : System.currentTimeMillis(), + gradleVersion: gradle.gradleVersion, + rootProject : root.name, + projects : projects + ] + + def outFile = new File(root.projectDir, '.code_editor/gradle_ide_model.json') + outFile.parentFile?.mkdirs() + outFile.setText(JsonOutput.toJson(model), 'UTF-8') + } catch (Throwable error) { + // 失败时写入错误信息,便于 App 侧归类失败原因(而不是静默失败) + try { + def root = gradle.rootProject + def outFile = new File(root.projectDir, '.code_editor/gradle_ide_model.json') + outFile.parentFile?.mkdirs() + outFile.setText(JsonOutput.toJson([ + schema: 0, + error : error.toString() + ]), 'UTF-8') + } catch (ignored) { } + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 0772689..7be60d3 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -683,5 +683,146 @@ "cut": "Cut", "paste": "Paste", "selectAll": "Select All", - "copiedToClipboard": "Copied to clipboard" + "copiedToClipboard": "Copied to clipboard", + "probeBannerPreparing": "Preparing {module} environment…", + "@probeBannerPreparing": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeBannerDetecting": "Detecting {module} tasks…", + "@probeBannerDetecting": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeBannerFinalizing": "Finalizing detection result…", + "probePhaseQueued": "{module} queued…", + "@probePhaseQueued": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probePhaseCheckingDependency": "Checking {module} dependencies…", + "@probePhaseCheckingDependency": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probePhaseInstallingDependency": "Installing {module} dependencies…", + "@probePhaseInstallingDependency": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeDoneWithCount": "{module} finished · {count} tasks found", + "@probeDoneWithCount": { + "placeholders": { + "module": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "probeFailureDependencyInstallFailed": "Failed to auto-install dependency {tool}", + "@probeFailureDependencyInstallFailed": { + "placeholders": { + "tool": { + "type": "String" + } + } + }, + "taskTypeSingleFile": "Current File Task", + "taskTypeOther": "Other Tasks", + "probeAlreadyRunning": "Detection already in progress, please wait…", + "probeBusyEnterTerminalTitle": "Task detection in progress", + "probeBusyEnterTerminalMessage": "Project task detection is running in the background (it uses the current container for build-tool introspection and dependency installation).\n\nEntering the terminal and running installs or builds may block or conflict with it.\n\nDo you still want to open the terminal?", + "probeEnterTerminalAnyway": "Open Terminal Anyway", + "probeCancelConfirmTitle": "Cancel this detection?", + "probeCancelConfirmMessage": "The running detection will be aborted immediately: results of finished modules are kept, unfinished modules will be skipped.", + "probeKeepDetecting": "Keep detecting", + "cancelProbe": "Cancel detection", + "probeBudgetExceededTitle": "Detection aborted (time budget exceeded)", + "probeBudgetExceededMessage": "{completed}/{total} modules finished; the rest were skipped. You can re-detect later.", + "@probeBudgetExceededMessage": { + "placeholders": { + "completed": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "probeBannerClose": "Close", + "probeDone": "{module} task detection finished", + "@probeDone": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeFailedTitle": "{module} task detection failed", + "@probeFailedTitle": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeFailureToolchainMissing": "{tool} was not found in the current system. Install it in System Management first.", + "@probeFailureToolchainMissing": { + "placeholders": { + "tool": { + "type": "String" + } + } + }, + "probeFailureExecutionFailed": "Build tool execution failed: {detail}", + "@probeFailureExecutionFailed": { + "placeholders": { + "detail": { + "type": "String" + } + } + }, + "probeFailureUnparsable": "Unable to parse build tool output (possible version mismatch)", + "probeFailureTimeout": "Detection timed out and was aborted", + "noticeQueueMore": "{count} more in progress", + "@noticeQueueMore": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "importFilesSuccess": "Successfully imported {count} files", + "@importFilesSuccess": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "importFilesFailed": "Failed to import files: {error}", + "@importFilesFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 4d1a05a..feb0c50 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2353,6 +2353,186 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'已复制到剪贴板'** String get copiedToClipboard; + + /// No description provided for @probeBannerPreparing. + /// + /// In zh, this message translates to: + /// **'正在准备 {module} 探测环境…'** + String probeBannerPreparing(String module); + + /// No description provided for @probeBannerDetecting. + /// + /// In zh, this message translates to: + /// **'正在探测 {module} 任务…'** + String probeBannerDetecting(String module); + + /// No description provided for @probeBannerFinalizing. + /// + /// In zh, this message translates to: + /// **'正在整理探测结果…'** + String get probeBannerFinalizing; + + /// No description provided for @probePhaseQueued. + /// + /// In zh, this message translates to: + /// **'{module} 排队等待中…'** + String probePhaseQueued(String module); + + /// No description provided for @probePhaseCheckingDependency. + /// + /// In zh, this message translates to: + /// **'正在检查 {module} 依赖…'** + String probePhaseCheckingDependency(String module); + + /// No description provided for @probePhaseInstallingDependency. + /// + /// In zh, this message translates to: + /// **'正在安装 {module} 依赖…'** + String probePhaseInstallingDependency(String module); + + /// No description provided for @probeDoneWithCount. + /// + /// In zh, this message translates to: + /// **'{module} 探测完成 · 发现 {count} 个任务'** + String probeDoneWithCount(String module, int count); + + /// No description provided for @probeFailureDependencyInstallFailed. + /// + /// In zh, this message translates to: + /// **'依赖 {tool} 自动安装失败'** + String probeFailureDependencyInstallFailed(String tool); + + /// No description provided for @taskTypeSingleFile. + /// + /// In zh, this message translates to: + /// **'当前文件任务'** + String get taskTypeSingleFile; + + /// No description provided for @taskTypeOther. + /// + /// In zh, this message translates to: + /// **'其他任务'** + String get taskTypeOther; + + /// No description provided for @probeAlreadyRunning. + /// + /// In zh, this message translates to: + /// **'正在探测中,请稍候…'** + String get probeAlreadyRunning; + + /// No description provided for @probeBusyEnterTerminalTitle. + /// + /// In zh, this message translates to: + /// **'任务探测进行中'** + String get probeBusyEnterTerminalTitle; + + /// No description provided for @probeBusyEnterTerminalMessage. + /// + /// In zh, this message translates to: + /// **'项目任务探测正在后台进行(会占用当前容器执行构建工具自省与依赖安装)。\n\n此时进入终端并进行安装软件包、构建等操作,可能与探测互相阻塞或产生异常。\n\n是否仍要进入终端?'** + String get probeBusyEnterTerminalMessage; + + /// No description provided for @probeEnterTerminalAnyway. + /// + /// In zh, this message translates to: + /// **'继续进入终端'** + String get probeEnterTerminalAnyway; + + /// No description provided for @probeCancelConfirmTitle. + /// + /// In zh, this message translates to: + /// **'取消本次探测?'** + String get probeCancelConfirmTitle; + + /// No description provided for @probeCancelConfirmMessage. + /// + /// In zh, this message translates to: + /// **'正在进行的探测会被立即中止:已完成模块的结果会保留,未完成的模块将被跳过。'** + String get probeCancelConfirmMessage; + + /// No description provided for @probeKeepDetecting. + /// + /// In zh, this message translates to: + /// **'继续探测'** + String get probeKeepDetecting; + + /// No description provided for @cancelProbe. + /// + /// In zh, this message translates to: + /// **'取消探测'** + String get cancelProbe; + + /// No description provided for @probeBudgetExceededTitle. + /// + /// In zh, this message translates to: + /// **'探测超时已中止'** + String get probeBudgetExceededTitle; + + /// No description provided for @probeBudgetExceededMessage. + /// + /// In zh, this message translates to: + /// **'已完成 {completed}/{total} 个模块,剩余模块本次跳过。可稍后重新探测。'** + String probeBudgetExceededMessage(int completed, int total); + + /// No description provided for @probeBannerClose. + /// + /// In zh, this message translates to: + /// **'关闭'** + String get probeBannerClose; + + /// No description provided for @probeDone. + /// + /// In zh, this message translates to: + /// **'{module} 任务探测完成'** + String probeDone(String module); + + /// No description provided for @probeFailedTitle. + /// + /// In zh, this message translates to: + /// **'{module} 任务探测失败'** + String probeFailedTitle(String module); + + /// No description provided for @probeFailureToolchainMissing. + /// + /// In zh, this message translates to: + /// **'当前系统内未找到 {tool},请先在系统管理中安装'** + String probeFailureToolchainMissing(String tool); + + /// No description provided for @probeFailureExecutionFailed. + /// + /// In zh, this message translates to: + /// **'构建工具执行失败:{detail}'** + String probeFailureExecutionFailed(String detail); + + /// No description provided for @probeFailureUnparsable. + /// + /// In zh, this message translates to: + /// **'无法识别构建工具输出(可能版本不兼容)'** + String get probeFailureUnparsable; + + /// No description provided for @probeFailureTimeout. + /// + /// In zh, this message translates to: + /// **'探测超时,已中止'** + String get probeFailureTimeout; + + /// No description provided for @noticeQueueMore. + /// + /// In zh, this message translates to: + /// **'还有 {count} 项进行中'** + String noticeQueueMore(int count); + + /// No description provided for @importFilesSuccess. + /// + /// In zh, this message translates to: + /// **'成功导入 {count} 个文件'** + String importFilesSuccess(int count); + + /// No description provided for @importFilesFailed. + /// + /// In zh, this message translates to: + /// **'导入文件失败: {error}'** + String importFilesFailed(String error); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 5108654..528be17 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1409,4 +1409,129 @@ class AppLocalizationsEn extends AppLocalizations { @override String get copiedToClipboard => 'Copied to clipboard'; + + @override + String probeBannerPreparing(String module) { + return 'Preparing $module environment…'; + } + + @override + String probeBannerDetecting(String module) { + return 'Detecting $module tasks…'; + } + + @override + String get probeBannerFinalizing => 'Finalizing detection result…'; + + @override + String probePhaseQueued(String module) { + return '$module queued…'; + } + + @override + String probePhaseCheckingDependency(String module) { + return 'Checking $module dependencies…'; + } + + @override + String probePhaseInstallingDependency(String module) { + return 'Installing $module dependencies…'; + } + + @override + String probeDoneWithCount(String module, int count) { + return '$module finished · $count tasks found'; + } + + @override + String probeFailureDependencyInstallFailed(String tool) { + return 'Failed to auto-install dependency $tool'; + } + + @override + String get taskTypeSingleFile => 'Current File Task'; + + @override + String get taskTypeOther => 'Other Tasks'; + + @override + String get probeAlreadyRunning => + 'Detection already in progress, please wait…'; + + @override + String get probeBusyEnterTerminalTitle => 'Task detection in progress'; + + @override + String get probeBusyEnterTerminalMessage => + 'Project task detection is running in the background (it uses the current container for build-tool introspection and dependency installation).\n\nEntering the terminal and running installs or builds may block or conflict with it.\n\nDo you still want to open the terminal?'; + + @override + String get probeEnterTerminalAnyway => 'Open Terminal Anyway'; + + @override + String get probeCancelConfirmTitle => 'Cancel this detection?'; + + @override + String get probeCancelConfirmMessage => + 'The running detection will be aborted immediately: results of finished modules are kept, unfinished modules will be skipped.'; + + @override + String get probeKeepDetecting => 'Keep detecting'; + + @override + String get cancelProbe => 'Cancel detection'; + + @override + String get probeBudgetExceededTitle => + 'Detection aborted (time budget exceeded)'; + + @override + String probeBudgetExceededMessage(int completed, int total) { + return '$completed/$total modules finished; the rest were skipped. You can re-detect later.'; + } + + @override + String get probeBannerClose => 'Close'; + + @override + String probeDone(String module) { + return '$module task detection finished'; + } + + @override + String probeFailedTitle(String module) { + return '$module task detection failed'; + } + + @override + String probeFailureToolchainMissing(String tool) { + return '$tool was not found in the current system. Install it in System Management first.'; + } + + @override + String probeFailureExecutionFailed(String detail) { + return 'Build tool execution failed: $detail'; + } + + @override + String get probeFailureUnparsable => + 'Unable to parse build tool output (possible version mismatch)'; + + @override + String get probeFailureTimeout => 'Detection timed out and was aborted'; + + @override + String noticeQueueMore(int count) { + return '$count more in progress'; + } + + @override + String importFilesSuccess(int count) { + return 'Successfully imported $count files'; + } + + @override + String importFilesFailed(String error) { + return 'Failed to import files: $error'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 73b7c48..c9330e2 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1369,4 +1369,126 @@ class AppLocalizationsZh extends AppLocalizations { @override String get copiedToClipboard => '已复制到剪贴板'; + + @override + String probeBannerPreparing(String module) { + return '正在准备 $module 探测环境…'; + } + + @override + String probeBannerDetecting(String module) { + return '正在探测 $module 任务…'; + } + + @override + String get probeBannerFinalizing => '正在整理探测结果…'; + + @override + String probePhaseQueued(String module) { + return '$module 排队等待中…'; + } + + @override + String probePhaseCheckingDependency(String module) { + return '正在检查 $module 依赖…'; + } + + @override + String probePhaseInstallingDependency(String module) { + return '正在安装 $module 依赖…'; + } + + @override + String probeDoneWithCount(String module, int count) { + return '$module 探测完成 · 发现 $count 个任务'; + } + + @override + String probeFailureDependencyInstallFailed(String tool) { + return '依赖 $tool 自动安装失败'; + } + + @override + String get taskTypeSingleFile => '当前文件任务'; + + @override + String get taskTypeOther => '其他任务'; + + @override + String get probeAlreadyRunning => '正在探测中,请稍候…'; + + @override + String get probeBusyEnterTerminalTitle => '任务探测进行中'; + + @override + String get probeBusyEnterTerminalMessage => + '项目任务探测正在后台进行(会占用当前容器执行构建工具自省与依赖安装)。\n\n此时进入终端并进行安装软件包、构建等操作,可能与探测互相阻塞或产生异常。\n\n是否仍要进入终端?'; + + @override + String get probeEnterTerminalAnyway => '继续进入终端'; + + @override + String get probeCancelConfirmTitle => '取消本次探测?'; + + @override + String get probeCancelConfirmMessage => + '正在进行的探测会被立即中止:已完成模块的结果会保留,未完成的模块将被跳过。'; + + @override + String get probeKeepDetecting => '继续探测'; + + @override + String get cancelProbe => '取消探测'; + + @override + String get probeBudgetExceededTitle => '探测超时已中止'; + + @override + String probeBudgetExceededMessage(int completed, int total) { + return '已完成 $completed/$total 个模块,剩余模块本次跳过。可稍后重新探测。'; + } + + @override + String get probeBannerClose => '关闭'; + + @override + String probeDone(String module) { + return '$module 任务探测完成'; + } + + @override + String probeFailedTitle(String module) { + return '$module 任务探测失败'; + } + + @override + String probeFailureToolchainMissing(String tool) { + return '当前系统内未找到 $tool,请先在系统管理中安装'; + } + + @override + String probeFailureExecutionFailed(String detail) { + return '构建工具执行失败:$detail'; + } + + @override + String get probeFailureUnparsable => '无法识别构建工具输出(可能版本不兼容)'; + + @override + String get probeFailureTimeout => '探测超时,已中止'; + + @override + String noticeQueueMore(int count) { + return '还有 $count 项进行中'; + } + + @override + String importFilesSuccess(int count) { + return '成功导入 $count 个文件'; + } + + @override + String importFilesFailed(String error) { + return '导入文件失败: $error'; + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index dec1e5f..96ff9ab 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -683,5 +683,146 @@ "cut": "剪切", "paste": "粘贴", "selectAll": "全选", - "copiedToClipboard": "已复制到剪贴板" + "copiedToClipboard": "已复制到剪贴板", + "probeBannerPreparing": "正在准备 {module} 探测环境…", + "@probeBannerPreparing": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeBannerDetecting": "正在探测 {module} 任务…", + "@probeBannerDetecting": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeBannerFinalizing": "正在整理探测结果…", + "probePhaseQueued": "{module} 排队等待中…", + "@probePhaseQueued": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probePhaseCheckingDependency": "正在检查 {module} 依赖…", + "@probePhaseCheckingDependency": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probePhaseInstallingDependency": "正在安装 {module} 依赖…", + "@probePhaseInstallingDependency": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeDoneWithCount": "{module} 探测完成 · 发现 {count} 个任务", + "@probeDoneWithCount": { + "placeholders": { + "module": { + "type": "String" + }, + "count": { + "type": "int" + } + } + }, + "probeFailureDependencyInstallFailed": "依赖 {tool} 自动安装失败", + "@probeFailureDependencyInstallFailed": { + "placeholders": { + "tool": { + "type": "String" + } + } + }, + "taskTypeSingleFile": "当前文件任务", + "taskTypeOther": "其他任务", + "probeAlreadyRunning": "正在探测中,请稍候…", + "probeBusyEnterTerminalTitle": "任务探测进行中", + "probeBusyEnterTerminalMessage": "项目任务探测正在后台进行(会占用当前容器执行构建工具自省与依赖安装)。\n\n此时进入终端并进行安装软件包、构建等操作,可能与探测互相阻塞或产生异常。\n\n是否仍要进入终端?", + "probeEnterTerminalAnyway": "继续进入终端", + "probeCancelConfirmTitle": "取消本次探测?", + "probeCancelConfirmMessage": "正在进行的探测会被立即中止:已完成模块的结果会保留,未完成的模块将被跳过。", + "probeKeepDetecting": "继续探测", + "cancelProbe": "取消探测", + "probeBudgetExceededTitle": "探测超时已中止", + "probeBudgetExceededMessage": "已完成 {completed}/{total} 个模块,剩余模块本次跳过。可稍后重新探测。", + "@probeBudgetExceededMessage": { + "placeholders": { + "completed": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "probeBannerClose": "关闭", + "probeDone": "{module} 任务探测完成", + "@probeDone": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeFailedTitle": "{module} 任务探测失败", + "@probeFailedTitle": { + "placeholders": { + "module": { + "type": "String" + } + } + }, + "probeFailureToolchainMissing": "当前系统内未找到 {tool},请先在系统管理中安装", + "@probeFailureToolchainMissing": { + "placeholders": { + "tool": { + "type": "String" + } + } + }, + "probeFailureExecutionFailed": "构建工具执行失败:{detail}", + "@probeFailureExecutionFailed": { + "placeholders": { + "detail": { + "type": "String" + } + } + }, + "probeFailureUnparsable": "无法识别构建工具输出(可能版本不兼容)", + "probeFailureTimeout": "探测超时,已中止", + "noticeQueueMore": "还有 {count} 项进行中", + "@noticeQueueMore": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "importFilesSuccess": "成功导入 {count} 个文件", + "@importFilesSuccess": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "importFilesFailed": "导入文件失败: {error}", + "@importFilesFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 0cf48fd..badd8c7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,6 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/providers/distro_provider.dart'; +import 'package:code_editor/providers/notice_center.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; @@ -44,7 +45,10 @@ class MyApp extends StatelessWidget { (tab ?? (TabProvider()..init()))..bindProjectProvider(project), ), ChangeNotifierProvider(create: (_) => TerminalProvider()), - ChangeNotifierProvider(create: (_) => RunProvider()), + ChangeNotifierProvider(create: (_) => NoticeCenter()), + ChangeNotifierProvider( + create: (context) => RunProvider(noticeCenter: context.read()), + ), ChangeNotifierProxyProvider( create: (_) => DistroProvider()..init(), update: (_, terminal, distro) { diff --git a/lib/models/notice_item.dart b/lib/models/notice_item.dart new file mode 100644 index 0000000..aead7ec --- /dev/null +++ b/lib/models/notice_item.dart @@ -0,0 +1,156 @@ +import 'package:flutter/foundation.dart'; + +/// 通知条目类型(决定默认配色与图标) +enum NoticeKind { + /// 进行中(带进度圈) + progress, + + /// 已完成 + success, + + /// 失败(默认保留到手动关闭) + failure, + + /// 纯信息 + info, +} + +/// 探测阶段(对应 l10n 文案 key) +/// +/// 队列线性执行:每个模块依次经历 +/// [queued] 排队 → [checkingDependency] 依赖检测 → [installingDependency] 自动补全 +/// → [detecting] 执行探测 → [finalizing] 结果整理。 +enum ProbeNoticePhase { queued, checkingDependency, installingDependency, detecting, finalizing } + +/// 探测失败分类(对应 l10n 文案 key) +enum NoticeFailure { + toolchainMissing, + dependencyInstallFailed, + executionFailed, + unparsable, + timeout, +} + +/// 结构化通知文案:**模型层不含任何用户可见字符串**, +/// 实际文字由 UI 层 `resolveNoticeDisplay()` 通过 l10n 解析(禁止硬编码)。 +sealed class NoticeText { + const NoticeText(); +} + +/// 模块探测阶段文案:排队 / 依赖检测 / 自动补全 / 执行探测 / 整理 +class ModulePhaseText extends NoticeText { + /// 模块展示名(如 'Gradle',来自 ProjectModule.displayName,不是文案) + final String moduleDisplayName; + final ProbeNoticePhase phase; + + /// 可选技术细节(例如安装过程中的最后一行输出),展示为副标题 + final String? detail; + + const ModulePhaseText({ + required this.moduleDisplayName, + required this.phase, + this.detail, + }); +} + +/// 模块探测完成(带发现的任务数) +class ModuleDoneText extends NoticeText { + final String moduleDisplayName; + final int taskCount; + + const ModuleDoneText(this.moduleDisplayName, {this.taskCount = 0}); +} + +/// 整轮探测因超出时间预算而中止(已完成 [completed]/[total] 个模块) +class ProbeBudgetExceededText extends NoticeText { + final int completed; + final int total; + + const ProbeBudgetExceededText({required this.completed, required this.total}); +} + +/// 模块探测失败(带失败分类与可选技术细节,如缺失的工具名 / stderr 末尾) +class ModuleFailureText extends NoticeText { + final String moduleDisplayName; + final NoticeFailure failure; + final String? detail; + + const ModuleFailureText({ + required this.moduleDisplayName, + required this.failure, + this.detail, + }); +} + +/// 一条通知(业务无关:任务探测、以后的下载/编译进度都可复用) +@immutable +class NoticeItem { + /// 稳定标识(如 'probe:gradle'),用于插入/移除动画定位与就地更新 + final String id; + + final NoticeKind kind; + final NoticeText text; + + /// 0..1 进度;null 表示不定进度 + final double? progress; + + /// 完成后是否必须由用户手动关闭(失败场景用) + final bool sticky; + + /// 完成后延时自动关闭(成功场景用) + final Duration? autoCloseAfter; + + /// 用户点击 × 时的附加动作(例如"正在探测"的通知被关闭 => 取消探测) + final VoidCallback? onUserDismiss; + + /// 关闭前是否需要二次确认(破坏性操作,例如取消正在进行的探测) + final bool confirmBeforeDismiss; + + const NoticeItem({ + required this.id, + required this.kind, + required this.text, + this.progress, + this.sticky = false, + this.autoCloseAfter, + this.onUserDismiss, + this.confirmBeforeDismiss = false, + }); + + NoticeItem copyWith({ + NoticeKind? kind, + NoticeText? text, + double? progress, + bool? sticky, + Duration? autoCloseAfter, + bool? confirmBeforeDismiss, + bool clearProgress = false, + bool clearAutoClose = false, + }) { + return NoticeItem( + id: id, + kind: kind ?? this.kind, + text: text ?? this.text, + progress: clearProgress ? null : (progress ?? this.progress), + sticky: sticky ?? this.sticky, + autoCloseAfter: + clearAutoClose ? null : (autoCloseAfter ?? this.autoCloseAfter), + onUserDismiss: onUserDismiss, + confirmBeforeDismiss: confirmBeforeDismiss ?? this.confirmBeforeDismiss, + ); + } + + @override + bool operator ==(Object other) => + other is NoticeItem && + other.id == id && + other.kind == kind && + other.text == text && + other.progress == progress && + other.sticky == sticky && + other.autoCloseAfter == autoCloseAfter; + + @override + int get hashCode => + Object.hash(id, kind, text, progress, sticky, autoCloseAfter); +} diff --git a/lib/models/project_task_table.dart b/lib/models/project_task_table.dart new file mode 100644 index 0000000..f8f8daa --- /dev/null +++ b/lib/models/project_task_table.dart @@ -0,0 +1,48 @@ +import 'run_task.dart'; +import 'run_task_type.dart'; + +/// 当前工程的系统任务内存表:**类型 → 任务数组**(哈希表)。 +/// +/// * 进入项目时逐类型加载; +/// * 某个模块探测完成,就只写入自己类型那一格([replaceType]); +/// * UI 按类型逐段渲染([nonEmptyTypes] 给出非空类型,顺序即枚举顺序)。 +class ProjectTaskTable { + final Map> _byType = { + for (final type in RunTaskType.values) type: [], + }; + + List tasksOf(RunTaskType type) => List.unmodifiable(_byType[type] ?? const []); + + /// 非空类型(按枚举顺序,即 UI 展示顺序) + List get nonEmptyTypes => + [for (final type in RunTaskType.values) if ((_byType[type] ?? const []).isNotEmpty) type]; + + bool get isEmpty => _byType.values.every((tasks) => tasks.isEmpty); + + int get totalCount => _byType.values.fold(0, (sum, tasks) => sum + tasks.length); + + /// 模块探测完成 -> 覆盖写入自己类型那一格 + void replaceType(RunTaskType type, List tasks) { + _byType[type] = List.from(tasks); + } + + /// 用户自定义任务写入 user 类型 + void setUserTasks(List tasks) => replaceType(RunTaskType.user, tasks); + + void clear() { + for (final type in RunTaskType.values) { + _byType[type] = []; + } + } + + /// 按类型顺序展开的全部任务(用户任务在最后) + List get allOrdered => [ + for (final type in RunTaskType.values) ...?_byType[type], + ]; + + /// 全部探测任务(不含用户自定义任务) + List get detectedTasks => [ + for (final type in RunTaskType.values) + if (type != RunTaskType.user) ...?_byType[type], + ]; +} diff --git a/lib/models/run_task_type.dart b/lib/models/run_task_type.dart new file mode 100644 index 0000000..cf75a63 --- /dev/null +++ b/lib/models/run_task_type.dart @@ -0,0 +1,62 @@ +import 'run_task.dart'; + +/// 内置任务类型(完全可枚举):UI 按"类型 → 具体任务"分组呈现。 +/// +/// 顺序即 UI 展示顺序;[user] 永远在最后。 +/// 每个探测模块对应一个类型,模块探测出的任务只写入自己类型那一格。 +enum RunTaskType { + gradle, + cmake, + cargo, + npm, + make, + dart, + + /// 未映射到内置类型模块的探测任务(例如运行时注册的自定义模块) + other, + singleFile, + user; + + /// 该类型对应的模块 id(非模块类型返回 null) + String? get moduleId => switch (this) { + RunTaskType.gradle => 'gradle', + RunTaskType.cmake => 'cmake', + RunTaskType.cargo => 'cargo', + RunTaskType.npm => 'npm', + RunTaskType.make => 'make', + RunTaskType.dart => 'dart', + RunTaskType.other => null, + RunTaskType.singleFile => null, + RunTaskType.user => null, + }; + + /// 是否为"可执行真实自省/可重新同步"的模块类型 + bool get isModuleType => moduleId != null; + + /// 类型展示名(模块类型为专有名词,不做本地化;用户任务/单文件走 l10n) + static const Map _byModuleId = { + 'gradle': RunTaskType.gradle, + 'cmake': RunTaskType.cmake, + 'cargo': RunTaskType.cargo, + 'npm': RunTaskType.npm, + 'make': RunTaskType.make, + 'dart': RunTaskType.dart, + }; + + /// 模块 id -> 类型 + static RunTaskType? fromModuleId(String? moduleId) { + if (moduleId == null || moduleId.isEmpty) return null; + return _byModuleId[moduleId]; + } + + /// 单条任务归属的类型 + static RunTaskType ofTask(RunTask task) { + if (task.source == TaskSource.custom) return RunTaskType.user; + final byModule = fromModuleId(task.moduleId); + if (byModule != null) return byModule; + if (task.group == 'single_file') return RunTaskType.singleFile; + // 有模块归属但未映射到内置类型(自定义模块)-> other;其它无模块任务才算用户可见兜底 + if (task.moduleId != null && task.moduleId!.isNotEmpty) return RunTaskType.other; + return RunTaskType.user; + } +} diff --git a/lib/providers/notice_center.dart b/lib/providers/notice_center.dart new file mode 100644 index 0000000..f614dcb --- /dev/null +++ b/lib/providers/notice_center.dart @@ -0,0 +1,186 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../models/notice_item.dart'; + +/// 通知中心:负责"可见槽位 + 等待队列"的调度与状态流转。 +/// +/// 设计要点(业务无关,可被任意后台任务复用): +/// * [push] 插入一条通知:可视槽位未满立即展示,否则进入队列; +/// * [dismiss] 关闭一条:先标记为"正在移除"(让 UI 播放退场动画), +/// 动画结束回调 [finalizeDismiss] 真正移除,并**自动把队列首条补位弹出**; +/// * [complete] 标记完成:成功类可带 [NoticeItem.autoCloseAfter] 延时自动关闭; +/// 失败类 [NoticeItem.sticky] 不自动关闭,避免失败被静默吞掉。 +/// +/// 注意:本类只持有纯数据,不含 Widget、不含任何用户可见字符串。 +class NoticeCenter extends ChangeNotifier { + NoticeCenter({this.visibleLimit = 3}); + + /// 同时可见的最大通知条数(其余排队,关闭后自动补位) + final int visibleLimit; + + final List _visible = []; + final List _queued = []; + final Set _removing = {}; + final Map _autoCloseTimers = {}; + + /// 当前可见通知(索引 0 在最上方,最新插入的在上) + List get visible => List.unmodifiable(_visible); + + /// 等待补位的通知(先进先出) + List get queued => List.unmodifiable(_queued); + + /// 正在播放退场动画的通知 id + Set get removingIds => Set.unmodifiable(_removing); + + bool get isEmpty => _visible.isEmpty && _queued.isEmpty; + + /// 插入一条通知;返回其 id + String push(NoticeItem item) { + // 同 id 重复插入:视为就地更新,避免出现两张同源卡片 + if (_indexOf(item.id) != -1) { + update( + item.id, + kind: item.kind, + text: item.text, + progress: item.progress, + ); + return item.id; + } + + if (_visible.length < visibleLimit) { + _visible.insert(0, item); + } else { + _queued.add(item); + } + notifyListeners(); + return item.id; + } + + /// 就地更新(不改变位置、不重播插入动画) + void update( + String id, { + NoticeKind? kind, + NoticeText? text, + double? progress, + bool clearProgress = false, + }) { + final idx = _indexOf(id); + if (idx == -1) return; + final isVisible = idx < _visible.length; + final list = isVisible ? _visible : _queued; + final i = isVisible ? idx : idx - _visible.length; + + final current = list[i]; + final next = current.copyWith( + kind: kind, + text: text, + progress: progress, + clearProgress: clearProgress, + ); + if (next == current) return; + list[i] = next; + notifyListeners(); + } + + /// 标记某条通知"已完成"(成功可自动关闭;失败请传 sticky 语义的 item) + void complete( + String id, { + required NoticeKind kind, + NoticeText? text, + Duration? autoCloseAfter, + bool sticky = false, + bool? confirmBeforeDismiss, + bool clearProgress = true, + }) { + final idx = _indexOf(id); + if (idx == -1) return; + final isVisible = idx < _visible.length; + final list = isVisible ? _visible : _queued; + final i = isVisible ? idx : idx - _visible.length; + + list[i] = list[i].copyWith( + kind: kind, + text: text, + sticky: sticky, + autoCloseAfter: autoCloseAfter, + confirmBeforeDismiss: confirmBeforeDismiss, + clearProgress: clearProgress, + ); + notifyListeners(); + + _autoCloseTimers.remove(id)?.cancel(); + if (!sticky && autoCloseAfter != null && isVisible) { + _autoCloseTimers[id] = Timer(autoCloseAfter, () => dismiss(id)); + } + } + + /// 请求关闭:可见条目先播放退场动画(由 UI 在动画结束后调用 [finalizeDismiss]); + /// 仍在队列中的条目直接移除,并补位。 + void dismiss(String id) { + _autoCloseTimers.remove(id)?.cancel(); + + if (_removing.contains(id)) return; + + final qIdx = _queued.indexWhere((e) => e.id == id); + if (qIdx != -1) { + _queued.removeAt(qIdx); + _promoteFromQueue(); + notifyListeners(); + return; + } + + if (_visible.any((e) => e.id == id)) { + _removing.add(id); + notifyListeners(); + } + } + + /// 退场动画结束回调:真正移除并立即把队列首条补位弹出 + void finalizeDismiss(String id) { + final removed = _visible.indexWhere((e) => e.id == id); + _removing.remove(id); + if (removed != -1) { + _visible.removeAt(removed); + } + _promoteFromQueue(); + notifyListeners(); + } + + /// 关闭全部(同时清理队列与所有自动关闭定时器) + void dismissAll() { + for (final timer in _autoCloseTimers.values) { + timer.cancel(); + } + _autoCloseTimers.clear(); + _removing.clear(); + _visible.clear(); + _queued.clear(); + notifyListeners(); + } + + void _promoteFromQueue() { + while (_visible.length < visibleLimit && _queued.isNotEmpty) { + _visible.add(_queued.removeAt(0)); + } + } + + /// 返回 id 在 [_visible] ++ [_queued] 中的线性索引,找不到返回 -1 + int _indexOf(String id) { + final v = _visible.indexWhere((e) => e.id == id); + if (v != -1) return v; + final q = _queued.indexWhere((e) => e.id == id); + if (q != -1) return _visible.length + q; + return -1; + } + + @override + void dispose() { + for (final timer in _autoCloseTimers.values) { + timer.cancel(); + } + _autoCloseTimers.clear(); + super.dispose(); + } +} diff --git a/lib/providers/project_provider.dart b/lib/providers/project_provider.dart index d4db6b0..7deb296 100644 --- a/lib/providers/project_provider.dart +++ b/lib/providers/project_provider.dart @@ -315,6 +315,40 @@ class ProjectProvider extends ChangeNotifier { } } + /// 从外部导入文件到指定目录(通常为项目根目录,支持多选文件) + Future importFiles(String destinationDir, List files) async { + final destDir = Directory(destinationDir); + if (!await destDir.exists()) { + await destDir.create(recursive: true); + } + + int importedCount = 0; + for (final file in files) { + final rawName = file.name.trim().isNotEmpty + ? file.name.trim() + : (file.path != null ? p.basename(file.path!) : ''); + if (rawName.isEmpty) continue; + + final targetPath = await FileService.instance.getUniqueTargetPath( + p.join(destinationDir, rawName), + false, + ); + + if (file.path != null && file.path!.isNotEmpty) { + await File(file.path!).copy(targetPath); + importedCount++; + } else if (file.bytes != null) { + await File(targetPath).writeAsBytes(file.bytes!); + importedCount++; + } + } + + if (importedCount > 0) { + await refreshTree(); + } + return importedCount; + } + Future createFile(String parentDir, String name) async { final targetPath = p.join(parentDir, name.trim()); await FileService.instance.createFile(targetPath); diff --git a/lib/providers/run_provider.dart b/lib/providers/run_provider.dart index 37d8360..6e57162 100644 --- a/lib/providers/run_provider.dart +++ b/lib/providers/run_provider.dart @@ -1,28 +1,49 @@ -import 'package:flutter/material.dart'; +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../models/notice_item.dart'; +import '../models/project_task_table.dart'; import '../models/run_task.dart'; +import '../models/run_task_type.dart'; import '../services/distro_manager.dart'; import '../services/project_task_dispatcher.dart'; +import '../services/project_modules/project_module.dart'; +import '../services/project_modules/project_probe.dart'; import '../services/run_task_storage_service.dart'; +import 'notice_center.dart'; /// 运行任务状态管理 Provider +/// +/// 探测相关职责已收敛为"探测会话"模型: +/// * 每次探测创建一次 [ProjectProbe],进度通过 [probeProgress] 暴露给 UI; +/// * 每个模块对应一条通知([NoticeCenter]),并发模块 = 多条通知并存; +/// * 失败按 [ModuleProbeResult] 结构化上报,绝不返回硬编码兜底任务。 class RunProvider extends ChangeNotifier { final RunTaskStorageService _storageService; final ProjectTaskDispatcher _dispatcher; final DistroManager _distroManager; + final NoticeCenter? _noticeCenter; RunProvider({ RunTaskStorageService? storageService, ProjectTaskDispatcher? dispatcher, DistroManager? distroManager, + NoticeCenter? noticeCenter, + Duration? probeBudget, }) : _storageService = storageService ?? RunTaskStorageService(), _dispatcher = dispatcher ?? ProjectTaskDispatcher.instance, - _distroManager = distroManager ?? DistroManager(); + _distroManager = distroManager ?? DistroManager(), + _noticeCenter = noticeCenter, + _probeBudget = probeBudget ?? ProjectProbe.defaultBudget; - /// 内存中保存的系统动态探测任务列表(不落盘) - List _detectedTasks = []; + /// 整轮探测的时间预算(超出后剩余模块跳过,并弹一条可关闭的提示) + final Duration _probeBudget; - /// 用户持久化配置的自定义任务列表(存放在 .code_editor/run_tasks.json) - List _customTasks = []; + /// 当前工程的系统任务内存表:**类型 → 任务数组**(哈希表) + /// + /// 进入项目时逐类型加载;模块探测完成即写入自己类型那一格(增量更新)。 + final ProjectTaskTable _taskTable = ProjectTaskTable(); /// 最近一次运行的任务ID(持久化保存) String? _lastRunTaskId; @@ -30,28 +51,76 @@ class RunProvider extends ChangeNotifier { /// 最近一次运行的任务(如果有) RunTask? _lastRunTask; - /// 是否正在总体探测中(探测期间互斥,防止并发与按钮连点) - bool _isDetecting = false; - /// 当前绑定的工程根路径 String? _currentProjectRoot; - /// 正在后台执行深度同步自省的模块集合(如 'gradle') - final Set _syncingModules = {}; + /// 当前工程最近活跃打开的文件路径(用于维持当前文件任务) + String? _lastActiveFilePath; - List get detectedTasks => List.unmodifiable(_detectedTasks); - List get customTasks => List.unmodifiable(_customTasks); + /// 当前进行中的探测会话(null 表示空闲) + ProjectProbe? _activeProbe; + ProjectProbeReport? _lastProbeReport; + final List _activeProbeNoticeIds = []; + + /// 本轮已结算(成功/失败/跳过)的模块通知 id: + /// 这些卡片内容已定稿,后续队列进度不得再覆盖它们 + /// (否则完成卡片会被回写为"排队等待中…",失败原因也会被冲掉) + final Set _finishedProbeNoticeIds = {}; + + /// 用户探测并发合并:正在执行的那次 + 是否需要补跑一次 + Future? _userProbeInFlight; + bool _userProbePending = false; + + /// 已释放标记:探测可能在释放后才返回,避免对已 dispose 的 notifier 通知 + bool _disposed = false; + + /// 安全通知(释放后不再触发) + void _notify() { + if (_disposed) return; + super.notifyListeners(); + } + + /// 类型 → 任务数组(UI 按类型分段渲染) + ProjectTaskTable get taskTable => _taskTable; + + List get detectedTasks => List.unmodifiable(_taskTable.detectedTasks); + List get customTasks => _taskTable.tasksOf(RunTaskType.user); RunTask? get lastRunTask => _lastRunTask; String? get lastRunTaskId => _lastRunTaskId; - bool get isDetecting => _isDetecting; String? get currentProjectRoot => _currentProjectRoot; - Set get syncingModules => Set.unmodifiable(_syncingModules); - bool isModuleSyncing(String moduleId) => _syncingModules.contains(moduleId); - bool get isAnyModuleSyncing => _syncingModules.isNotEmpty; + /// 探测是否进行中(含模块依赖检测与自动补全) + bool get isDetecting => _activeProbe != null; - /// 获取当前合并后的所有可用任务列表(自定义任务置顶,随后为探测任务) - List get allTasks => [..._customTasks, ..._detectedTasks]; + @visibleForTesting + ProjectProbe? get activeProbeForTest => _activeProbe; + + /// 当前探测进度(null 表示无进行中的探测) + ValueListenable? get probeProgress => _activeProbe?.progress; + + /// 最近一次探测的结构化报告 + ProjectProbeReport? get lastProbeReport => _lastProbeReport; + + /// 正在探测/同步的模块 id(供"重新同步"按钮显示 loading) + Set get syncingModules { + final probe = _activeProbe; + if (probe == null) return const {}; + final only = probe.onlyModuleId; + if (only != null) return {only}; + return {for (final m in probe.progress.value?.queue ?? const []) m.id}; + } + + bool isModuleSyncing(String moduleId) => syncingModules.contains(moduleId); + + /// 需要跑真实构建工具自省、因而支持"重新同步真实任务"的模块 id + List get resyncableModuleIds => + [for (final m in _dispatcher.modules) if (m.supportsResync) m.id]; + + /// 模块展示名(用于 UI 文案插值;找不到时回退为 id) + String moduleDisplayName(String moduleId) => _moduleDisplayName(moduleId); + + /// 获取当前合并后的所有可用任务列表(自定义任务置顶,随后为各类型探测任务) + List get allTasks => [...customTasks, ..._taskTable.detectedTasks]; /// 内部方法:尝试从现有任务列表中匹配 lastRunTaskId void _resolveLastRunTask() { @@ -65,43 +134,33 @@ class RunProvider extends ChangeNotifier { } } - /// 记录最近一次执行的任务并持久化 + /// 记录最近一次执行的任务("上一次执行任务"与用户任务一样持久化在 JSON 中) Future setLastRunTask(RunTask task) async { _lastRunTask = task; _lastRunTaskId = task.id; - notifyListeners(); + _notify(); - if (_currentProjectRoot != null) { - await _storageService.saveConfig( - projectRoot: _currentProjectRoot!, - tasks: _customTasks, + final root = _currentProjectRoot; + if (root != null) { + // 只更新 lastRunTaskId,保留磁盘上已有的用户任务(内存可能尚未加载完) + await _storageService.saveLastRunTaskId( + projectRoot: root, lastRunTaskId: _lastRunTaskId, ); } + + // 与用户任务同样的处理:写盘后用用户探测把内存态从磁盘校准一次(含并发合并) + await probeUser(projectRoot: root); } - /// 当打开或切换工程时初始化任务(读取持久化任务 + 首次自动探测系统任务) - Future onProjectOpened(String projectRoot, {String? activeFilePath, String systemName = 'ubuntu'}) async { + /// 当打开或切换工程时初始化任务(进入项目即自动探测) + /// + /// [systemName] 必须传入当前真实选中的系统;为空时**只做用户探测**(系统探测会因无系统被跳过), + /// 等系统就绪后由入口处的去重逻辑自动补一次。 + Future onProjectOpened(String projectRoot, {String? activeFilePath, String? systemName}) async { _currentProjectRoot = projectRoot; - // 切换工程时首先立即清空上一工程的内存任务状态,防止跨项目污染 - _detectedTasks = []; - _customTasks = []; - _lastRunTaskId = null; - _lastRunTask = null; - _syncingModules.clear(); - notifyListeners(); - - // 1. 加载持久化的自定义任务与最近运行任务ID - final config = await _storageService.loadConfig(projectRoot); - if (_currentProjectRoot != projectRoot) return; - - _customTasks = config.tasks; - _lastRunTaskId = config.lastRunTaskId; - _resolveLastRunTask(); - notifyListeners(); - - // 2. 自动触发一次系统探测(优先读模块本地持久化缓存,秒开无感) - await detectTasks( + _lastActiveFilePath = activeFilePath; + await probeProject( projectRoot: projectRoot, currentFilePath: activeFilePath, systemName: systemName, @@ -110,150 +169,488 @@ class RunProvider extends ChangeNotifier { /// 关闭工程时清理状态 void onProjectClosed() { + cancelActiveProbe(); _currentProjectRoot = null; - _detectedTasks = []; - _customTasks = []; + _lastActiveFilePath = null; + _taskTable.clear(); _lastRunTaskId = null; _lastRunTask = null; - _isDetecting = false; - _syncingModules.clear(); - notifyListeners(); + _lastProbeReport = null; + _notify(); } - /// 手动或自动触发项目探测 - /// [projectRoot] 目标工程路径 - /// [currentFilePath] 当前激活的编辑器文件路径 - /// [forceRefresh] 是否强制重新自省探测 - Future detectTasks({ + /// ===================== 探测层(三个函数) ===================== + + /// 探测函数(总入口):**终止正在运行的模块 + 清空内存任务表**,然后依次执行 + /// [probeUser](用户探测:磁盘 → 内存)与 [probeSystem](系统探测:模块队列 → 内存)。 + /// + /// 进入项目、切换工程、手动"项目探测"都走它。 + Future probeProject({ required String projectRoot, String? currentFilePath, - String systemName = 'ubuntu', - bool forceRefresh = false, + String? systemName, }) async { - if (_isDetecting) return; + // 1. 终止进行中的模块(取消会话:容器内子进程会被立即杀掉) + cancelActiveProbe(); - _isDetecting = true; - _detectedTasks = []; - _resolveLastRunTask(); - notifyListeners(); - - try { - final detected = await _dispatcher.detect( - projectRoot: projectRoot, - currentFilePath: currentFilePath, - systemName: systemName, - storageService: _storageService, - distroManager: _distroManager, - forceRefresh: forceRefresh, - ); - if (_currentProjectRoot == projectRoot) { - _detectedTasks = detected; - _resolveLastRunTask(); - } - } catch (e) { - debugPrint('[RunProvider] 项目探测失败: $e'); - } finally { - _isDetecting = false; - notifyListeners(); - } - } - - /// 异步重新同步/深度自省某个特定模块的任务(如 Gradle) - /// 在后台静默运行,并无缝将结果合并入当前 detectedTasks - Future syncModuleTasks( - String moduleId, { - String systemName = 'ubuntu', - }) async { - if (_currentProjectRoot == null) return; - if (_syncingModules.contains(moduleId)) return; - - final projectRoot = _currentProjectRoot!; - _syncingModules.add(moduleId); - notifyListeners(); - - try { - final moduleTasks = await _dispatcher.syncModule( - moduleId: moduleId, - projectRoot: projectRoot, - systemName: systemName, - storageService: _storageService, - distroManager: _distroManager, - ); - - if (_currentProjectRoot == projectRoot && moduleTasks.isNotEmpty) { - _detectedTasks = _mergeModuleTasks(_detectedTasks, moduleId, moduleTasks); - _resolveLastRunTask(); - } - } catch (e) { - debugPrint('[RunProvider] 模块 $moduleId 深度自省失败: $e'); - } finally { - _syncingModules.remove(moduleId); - notifyListeners(); - } - } - - /// 合并替换指定模块在 detectedTasks 中的条目,保持原有相对排布 - List _mergeModuleTasks(List current, String moduleId, List updated) { - final result = []; - bool inserted = false; - - for (final task in current) { - final isThisModule = task.moduleId == moduleId || - task.id.startsWith('${moduleId}_') || - task.id.startsWith('detected_${moduleId}_'); - - if (isThisModule) { - if (!inserted) { - result.addAll(updated); - inserted = true; - } - } else { - result.add(task); - } + if (_currentProjectRoot != projectRoot) { + _currentProjectRoot = projectRoot; } - if (!inserted) { - result.addAll(updated); + // 2. 清空内存任务表(系统任务只存在于内存,用户任务随后由用户探测重新载入) + _taskTable.clear(); + _lastRunTask = null; + _notify(); + + // 3. 用户探测(快:读磁盘 → 覆盖内存 user 格与"上次执行任务") + await probeUser(projectRoot: projectRoot); + + // 4. 当前文件任务(快:本地重算,0ms 立即展现,不需等耗时的容器探测) + final activeFile = currentFilePath ?? _lastActiveFilePath; + if (activeFile != null && activeFile.isNotEmpty) { + _applySingleFileTask(projectRoot, activeFile); + _notify(); } - return result; - } - - /// 保存并更新用户自定义任务 - Future updateCustomTasks(List updatedTasks) async { - if (_currentProjectRoot == null) return; - - _customTasks = List.from(updatedTasks); - _resolveLastRunTask(); - notifyListeners(); - - await _storageService.saveConfig( - projectRoot: _currentProjectRoot!, - tasks: _customTasks, - lastRunTaskId: _lastRunTaskId, + // 5. 系统探测(慢:模块队列线性执行 → 写入各自的类型格) + await probeSystem( + projectRoot: projectRoot, + currentFilePath: currentFilePath, + systemName: systemName, ); } - /// 添加单个自定义任务 - Future addCustomTask(RunTask task) async { - final list = List.from(_customTasks); - list.add(task); - await updateCustomTasks(list); + /// 用户主动点击"项目探测":若已有探测在进行则拒绝,由 UI 弹出 toast 提示。 + /// 返回 true 表示已开始探测。 + Future requestProjectProbe({ + required String projectRoot, + String? currentFilePath, + String? systemName, + }) async { + if (isDetecting) return false; + await probeProject( + projectRoot: projectRoot, + currentFilePath: currentFilePath, + systemName: systemName, + ); + return true; } - /// 删除单个自定义任务 - Future removeCustomTask(String taskId) async { - final list = _customTasks.where((t) => t.id != taskId).toList(); - await updateCustomTasks(list); - } + /// 用户探测:从磁盘载入用户自定义任务与"上一次执行任务",并**覆盖**内存中的用户类型格。 + /// + /// 并发合并:短时间内被连续触发(例如用户连续编辑几十次任务)时,正在执行的那次结束后 + /// 最多再补跑一次,保证"最后一次编辑一定生效",同时不会放大磁盘 IO。 + Future probeUser({String? projectRoot}) async { + final root = projectRoot ?? _currentProjectRoot; + if (root == null) return; - /// 修改单个自定义任务 - Future editCustomTask(RunTask task) async { - final index = _customTasks.indexWhere((t) => t.id == task.id); - if (index != -1) { - final list = List.from(_customTasks); - list[index] = task; - await updateCustomTasks(list); + // 同步绑定工程根:这样"期间切换了工程"能被下面的守卫准确识别并丢弃结果 + _currentProjectRoot ??= root; + + final inFlight = _userProbeInFlight; + if (inFlight != null) { + _userProbePending = true; + return inFlight; + } + + final completer = Completer(); + _userProbeInFlight = completer.future; + try { + await _loadUserState(root); + } catch (e) { + debugPrint('[RunProvider] 用户探测失败: $e'); + } finally { + _userProbeInFlight = null; + completer.complete(); + if (_userProbePending) { + _userProbePending = false; + unawaited(probeUser(projectRoot: root)); + } } } + + Future _loadUserState(String projectRoot) async { + final config = await _storageService.loadConfig(projectRoot); + if (_currentProjectRoot != projectRoot) return; + + // 覆盖内存中的用户任务(而不是合并),并同步"上次执行任务" + _taskTable.setUserTasks(config.tasks); + _lastRunTaskId = config.lastRunTaskId; + _resolveLastRunTask(); + _notify(); + } + + /// 系统探测:模块发现 → 入队 → 线性执行三动作,结果逐模块写入内存任务表。 + Future probeSystem({ + required String projectRoot, + String? currentFilePath, + String? systemName, + String? onlyModuleId, + }) async { + // 单模块同步时只清该模块类型;整轮探测时清空全部构建模块类型(用户任务格与当前文件格不动) + if (onlyModuleId == null) { + for (final type in RunTaskType.values) { + if (type == RunTaskType.user || type == RunTaskType.singleFile) continue; + _taskTable.replaceType(type, const []); + } + } else { + final type = RunTaskType.fromModuleId(onlyModuleId); + if (type != null) _taskTable.replaceType(type, const []); + } + _notify(); + + // 终止可能仍在后台执行的旧探测会话,防止与新会话并发争抢包管理器锁与资源 + if (_activeProbe != null) { + _activeProbe?.cancel(); + _activeProbe = null; + } + + // 清理上一轮遗留的探测通知,避免新探测的进度更新到正在退场的卡片上 + _clearProbeNotices(); + + final probe = _dispatcher.createProbe( + projectRoot: projectRoot, + currentFilePath: currentFilePath, + systemName: systemName, + distroManager: _distroManager, + onlyModuleId: onlyModuleId, + budget: _probeBudget, + ); + _activeProbe = probe; + + // 进度 -> 通知(队列中每个模块一条;当前模块显示三动作阶段,其余显示排队) + void onProgress() { + if (!identical(_activeProbe, probe)) return; + final progress = probe.progress.value; + if (progress == null || _noticeCenter == null) return; + _syncProbeNotices(progress, probe); + _notify(); + } + + probe.progress.addListener(onProgress); + + // 结果 -> 立即写入类型表 + 结算该模块弹窗(无需等整轮探测结束) + void onModuleResult(ProjectModule module, ModuleProbeResult result) { + // 边界:探测已被取消 / 已被新的探测取代 / 工程已切换时,结果必须丢弃, + // 否则会把上一个工程(或已被取消的会话)的任务写进当前工程的内存表。 + if (!identical(_activeProbe, probe) || probe.isCancelled) return; + if (_currentProjectRoot != projectRoot) return; + _applyModuleResult(module, result); + _notify(); + } + + ProjectProbeReport report; + try { + report = await _dispatcher.run(probe, onModuleResult: onModuleResult); + } catch (e) { + debugPrint('[RunProvider] 系统探测失败: $e'); + report = ProjectProbeReport.empty(systemName ?? ''); + } finally { + probe.progress.removeListener(onProgress); + } + + if (!identical(_activeProbe, probe)) { + // 期间被取消或已被新的探测取代:会话由这里释放,结果一律丢弃 + probe.dispose(); + return; + } + _activeProbe = null; + + // 仅当"仍是同一个工程"且"本次是整轮探测"时才收尾(单模块同步不动当前文件格) + if (_currentProjectRoot == projectRoot && !probe.isCancelled) { + _lastProbeReport = report; + if (onlyModuleId == null) { + final activeFile = currentFilePath ?? _lastActiveFilePath; + if (activeFile != null && activeFile.isNotEmpty) { + _applySingleFileTask(projectRoot, activeFile); + } + } + _resolveLastRunTask(); + } + + _finishProbeNotices(report, cancelled: probe.isCancelled); + + // 预算中止:补一条可关闭的说明(× 保留,用户可自行关闭或稍后重新探测) + if (!probe.isCancelled && report.abortedByBudget && !_disposed) { + _noticeCenter?.push(NoticeItem( + id: 'probe:budget', + kind: NoticeKind.failure, + text: ProbeBudgetExceededText( + completed: report.completedModules, + total: report.totalModules, + ), + sticky: true, + )); + } + + probe.dispose(); + _notify(); + } + + /// 把"当前打开文件"的任务写入 singleFile(当前文件)类型格。 + /// + /// 边界:本地重算而不是从报告里挑——即使工程没有任何模块被激活(报告为空), + /// 当前文件任务也必须照常出现。 + void _applySingleFileTask(String projectRoot, String? currentFilePath) { + if (_disposed) return; + if (currentFilePath != null && currentFilePath.isNotEmpty) { + _lastActiveFilePath = currentFilePath; + } + final effectivePath = currentFilePath ?? _lastActiveFilePath; + final single = (effectivePath == null || effectivePath.isEmpty) + ? null + : ProjectTaskDispatcher.detectSingleFileTask(projectRoot, effectivePath); + _taskTable.replaceType( + RunTaskType.singleFile, + single == null ? const [] : [single], + ); + } + + /// 当前打开文件变化时本地重算当前文件任务(不跑容器、不触发系统探测) + /// + /// 边界:当前文件任务与"当前打开的文件"强相关,切标签页后必须立即更新, + /// 否则列表里会残留上一个文件的运行项。 + void refreshSingleFileTask({String? currentFilePath}) { + final root = _currentProjectRoot; + if (root == null) return; + if (currentFilePath != null && currentFilePath.isNotEmpty) { + _lastActiveFilePath = currentFilePath; + } + _applySingleFileTask(root, currentFilePath ?? _lastActiveFilePath); + _resolveLastRunTask(); + _notify(); + } + + /// 单模块强制重新同步(系统探测的一个特例) + Future syncModuleTasks( + String moduleId, { + String? systemName, + String? currentFilePath, + }) async { + final projectRoot = _currentProjectRoot; + if (projectRoot == null) return; + if (isModuleSyncing(moduleId)) return; + + await probeSystem( + projectRoot: projectRoot, + currentFilePath: currentFilePath, + systemName: systemName, + onlyModuleId: moduleId, + ); + } + + /// 取消当前探测(切换工程 / 用户关闭提示 / 关闭弹窗时调用) + void cancelActiveProbe() { + final probe = _activeProbe; + if (probe == null) return; + probe.cancel(); + _clearProbeNotices(); + _activeProbe = null; + _notify(); + } + + /// 单个模块探测结束:写入它自己类型的那一格 + 结算它的弹窗 + void _applyModuleResult(ProjectModule module, ModuleProbeResult result) { + // 边界:运行时注册的自定义模块没有内置类型映射 -> 归入 other(不能丢任务) + final type = RunTaskType.fromModuleId(module.id) ?? RunTaskType.other; + _taskTable.replaceType( + type, + result.status == ModuleProbeStatus.ok ? result.tasks : const [], + ); + if (_currentProjectRoot != null) { + _resolveLastRunTask(); + } + + final center = _noticeCenter; + if (center == null) return; + final noticeId = _noticeIdFor(module.id); + _finishedProbeNoticeIds.add(noticeId); + switch (result.status) { + case ModuleProbeStatus.ok: + center.complete( + noticeId, + kind: NoticeKind.success, + text: ModuleDoneText(module.displayName, taskCount: result.tasks.length), + autoCloseAfter: const Duration(milliseconds: 1500), + // 模块已结束:关闭这张卡片不再具有破坏性,无需再二次确认 + confirmBeforeDismiss: false, + ); + break; + case ModuleProbeStatus.failed: + center.complete( + noticeId, + kind: NoticeKind.failure, + text: ModuleFailureText( + moduleDisplayName: module.displayName, + failure: result.failure ?? NoticeFailure.executionFailed, + detail: result.failureDetail, + ), + sticky: true, + confirmBeforeDismiss: false, + ); + break; + case ModuleProbeStatus.cancelled: + case ModuleProbeStatus.skippedByBudget: + center.dismiss(noticeId); + break; + } + } + + /// 依据队列进度为每个模块建立/更新通知条目 + /// + /// 队列线性执行:当前模块显示它正在做的动作(依赖检测/自动补全/执行探测), + /// 队列中其它模块统一显示"排队等待中"。 + void _syncProbeNotices(ProbeProgress progress, ProjectProbe probe) { + final center = _noticeCenter; + if (center == null) return; + + final currentPhase = switch (progress.phase) { + ProbePhase.queued => ProbeNoticePhase.queued, + ProbePhase.checkingDependency => ProbeNoticePhase.checkingDependency, + ProbePhase.installingDependency => ProbeNoticePhase.installingDependency, + ProbePhase.probing => ProbeNoticePhase.detecting, + ProbePhase.finalizing => ProbeNoticePhase.finalizing, + }; + final installDetail = probe.installLine.value; + + for (final module in progress.queue) { + final noticeId = _noticeIdFor(module.id); + // 已结算的模块不再改写:否则完成/失败卡片会被回写成"排队等待中…" + if (_finishedProbeNoticeIds.contains(noticeId)) continue; + + final isCurrent = progress.current?.id == module.id; + final phase = isCurrent ? currentPhase : ProbeNoticePhase.queued; + final text = ModulePhaseText( + moduleDisplayName: module.displayName, + phase: phase, + detail: isCurrent && phase == ProbeNoticePhase.installingDependency + ? installDetail + : null, + ); + + if (!_activeProbeNoticeIds.contains(noticeId)) { + _activeProbeNoticeIds.add(noticeId); + center.push(NoticeItem( + id: noticeId, + kind: NoticeKind.progress, + text: text, + // 进行中的通知被用户 × 掉 => 取消本次探测;这是破坏性操作,关闭前二次确认 + onUserDismiss: cancelActiveProbe, + confirmBeforeDismiss: true, + )); + } else { + center.update(noticeId, kind: NoticeKind.progress, text: text); + } + } + } + + /// 整轮探测收尾:把仍未结算的进度条目关掉(结果已由 [_applyModuleResult] 逐模块结算) + void _finishProbeNotices(ProjectProbeReport report, {required bool cancelled}) { + final center = _noticeCenter; + if (center == null) { + _activeProbeNoticeIds.clear(); + _finishedProbeNoticeIds.clear(); + return; + } + + if (cancelled) { + _clearProbeNotices(); + return; + } + + final resolved = {for (final id in report.moduleResults.keys) _noticeIdFor(id)}; + for (final noticeId in List.from(_activeProbeNoticeIds)) { + if (!resolved.contains(noticeId)) { + center.dismiss(noticeId); + } + } + _activeProbeNoticeIds + ..clear() + ..addAll(resolved); + _finishedProbeNoticeIds.clear(); + } + + void _clearProbeNotices() { + final center = _noticeCenter; + if (center == null) { + _activeProbeNoticeIds.clear(); + _finishedProbeNoticeIds.clear(); + return; + } + for (final noticeId in _activeProbeNoticeIds) { + center.dismiss(noticeId); + } + _activeProbeNoticeIds.clear(); + _finishedProbeNoticeIds.clear(); + } + + String _noticeIdFor(String moduleId) => 'probe:$moduleId'; + + String _moduleDisplayName(String moduleId) => + _dispatcher.getModule(moduleId)?.displayName ?? moduleId; + + /// 保存用户自定义任务:**先写盘,再调用用户探测**从磁盘覆盖内存中的用户任务格。 + /// + /// 用户连续编辑时,[probeUser] 会把并发调用合并成"正在跑的那次 + 最多补跑一次", + /// 既保证最后一次编辑生效,又不会把磁盘 IO 放大几十倍。 + Future updateCustomTasks(List updatedTasks) async { + final root = _currentProjectRoot; + if (root == null) return; + + await _storageService.saveConfig( + projectRoot: root, + tasks: updatedTasks, + lastRunTaskId: _lastRunTaskId, + ); + + await probeUser(projectRoot: root); + } + + /// 添加单个自定义任务(以**磁盘**为基准做读改写,避免内存未加载完时丢失已有任务) + Future addCustomTask(RunTask task) { + return _mutateCustomTasks((list) => [...list, task]); + } + + /// 删除单个自定义任务(以磁盘为基准) + Future removeCustomTask(String taskId) { + return _mutateCustomTasks((list) => list.where((t) => t.id != taskId).toList()); + } + + /// 修改单个自定义任务(以磁盘为基准;磁盘上不存在则追加) + Future editCustomTask(RunTask task) { + return _mutateCustomTasks((list) { + final index = list.indexWhere((t) => t.id == task.id); + if (index == -1) return [...list, task]; + final next = List.from(list); + next[index] = task; + return next; + }); + } + + /// 读改写用户任务:先读磁盘上的当前列表,应用 [mutate] 后再写回, + /// 最后用用户探测把内存态从磁盘覆盖一次(含并发合并)。 + Future _mutateCustomTasks(List Function(List current) mutate) async { + final root = _currentProjectRoot; + if (root == null) return; + + final existing = (await _storageService.loadConfig(root)).tasks; + await _storageService.saveConfig( + projectRoot: root, + tasks: mutate(existing), + lastRunTaskId: _lastRunTaskId, + ); + + await probeUser(projectRoot: root); + } + + @override + void dispose() { + // 只取消,不释放会话:探测协程仍在运行,会在自己的收尾分支里 dispose, + // 这里提前 dispose 会造成"取消后写入已释放 notifier"的 use-after-dispose。 + _disposed = true; + _activeProbe?.cancel(); + _activeProbe = null; + _userProbePending = false; + super.dispose(); + } } diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index b272b67..0c80b4d 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -46,6 +46,32 @@ enum DistroFamily { unknown, } +/// 后台静默命令的取消令牌:把子进程句柄暴露给上层(如任务探测会话), +/// 支持"切换工程 / 关闭弹窗 / 用户取消"时立即终止容器内的长时间探测。 +class HeadlessCancelToken { + Process? _process; + bool _cancelled = false; + + bool get isCancelled => _cancelled; + + void _attach(Process process) { + _process = process; + if (_cancelled) { + try { + process.kill(ProcessSignal.sigkill); + } catch (_) {} + } + } + + /// 取消:标记状态并杀掉当前子进程(若有) + void cancel() { + _cancelled = true; + try { + _process?.kill(ProcessSignal.sigkill); + } catch (_) {} + } +} + /// Linux 发行版与多系统实例管理器服务(单例模式,易扩展) class DistroManager { static final DistroManager _instance = DistroManager._internal(); @@ -80,6 +106,10 @@ class DistroManager { } /// 获取当前已创建并解压成功的系统实例列表(文件夹名称即系统名称) + /// + /// 判定标准与 [isSystemInstalled] 保持一致:rootfs 内必须同时具备 `etc` 与 `bin`。 + /// 仅存在 `rootfs` 空壳(例如历史版本探测流程遗留的目录)不计入,避免"幽灵系统" + /// 出现在系统选择器里却在启动时必然失败。 Future> listInstalledSystems() async { final baseDir = await getBaseDistrosDir(); if (!baseDir.existsSync()) return []; @@ -89,9 +119,12 @@ class DistroManager { for (final entity in entities) { if (entity is Directory) { final name = p.basename(entity.path); - // 若子目录存在 rootfs/ 且包含基础目录结构,则视为有效系统实例 final rootDir = Directory(p.join(entity.path, 'rootfs')); - if (rootDir.existsSync()) { + if (!rootDir.existsSync()) continue; + // 基本目录结构校验:必须具备 etc 与 bin 才算真正可用的系统实例 + final hasEtc = Directory(p.join(rootDir.path, 'etc')).existsSync(); + final hasBin = Directory(p.join(rootDir.path, 'bin')).existsSync(); + if (hasEtc && hasBin) { systems.add(name); } } @@ -361,6 +394,11 @@ class DistroManager { // 2. Linux 容器 (PRoot 隔离环境) final rootDir = await getSystemRootDir(systemName); + // 前置守卫:rootfs 必须先真实存在。否则下方一系列 ensure*(DNS/CA 证书/shm/l2s/sysdata) + // 会 recursive 地创建出一套空壳目录,把"并不存在的系统"伪造成系统选择器里的已安装项。 + if (!rootDir.existsSync()) { + throw StateError('目标系统未安装,拒绝构建启动配置: $systemName(rootfs 不存在: ${rootDir.path})'); + } final nativeDir = await getNativeLibraryDir(); final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath; final targetShell = _resolveTargetShell(rootDir); @@ -815,11 +853,15 @@ class DistroManager { /// [workspacePath] 工程挂载目录(挂载到 /workspace) /// [command] 执行的 Shell 脚本命令 /// [timeout] 超时时长(默认 120 秒) + /// [cancelToken] 可选取消令牌:取消后立即杀掉子进程,并返回 null + /// [onStdout] 可选逐行输出回调(用于显示依赖安装进度等长耗时操作) Future runHeadlessCommand({ required String systemName, String? workspacePath, required String command, Duration timeout = const Duration(seconds: 120), + HeadlessCancelToken? cancelToken, + void Function(String chunk)? onStdout, }) async { try { final config = await buildLaunchConfig( @@ -834,11 +876,25 @@ class DistroManager { environment: config.environment, workingDirectory: config.workingDirectory, ); + cancelToken?._attach(process); + if (cancelToken?.isCancelled ?? false) { + try { + process.kill(ProcessSignal.sigkill); + } catch (_) {} + return null; + } final stdoutBytes = []; final stderrBytes = []; - final stdoutFuture = process.stdout.listen(stdoutBytes.addAll).asFuture(); + final stdoutFuture = process.stdout.listen((chunk) { + stdoutBytes.addAll(chunk); + if (onStdout != null && chunk.isNotEmpty) { + try { + onStdout(utf8.decode(chunk, allowMalformed: true)); + } catch (_) {} + } + }).asFuture(); final stderrFuture = process.stderr.listen(stderrBytes.addAll).asFuture(); final exitCode = await process.exitCode.timeout( @@ -856,6 +912,10 @@ class DistroManager { onTimeout: () => [], ); + if (cancelToken?.isCancelled ?? false) { + return null; + } + final stdoutStr = utf8.decode(stdoutBytes, allowMalformed: true); final stderrStr = utf8.decode(stderrBytes, allowMalformed: true); diff --git a/lib/services/file_service.dart b/lib/services/file_service.dart index 993d7cc..58d39b3 100644 --- a/lib/services/file_service.dart +++ b/lib/services/file_service.dart @@ -217,7 +217,7 @@ class FileService { String targetPath = p.join(destinationDir, baseName); // 如果同名,自动生成副本名称(如 file(1).dart) - targetPath = await _getUniqueTargetPath(targetPath, entityType == FileSystemEntityType.directory); + targetPath = await getUniqueTargetPath(targetPath, entityType == FileSystemEntityType.directory); if(entityType == FileSystemEntityType.directory) { await _copyDirectory(Directory(sourcePath), Directory(targetPath)); @@ -237,7 +237,7 @@ class FileService { return; } - targetPath = await _getUniqueTargetPath(targetPath, entityType == FileSystemEntityType.directory); + targetPath = await getUniqueTargetPath(targetPath, entityType == FileSystemEntityType.directory); if(entityType == FileSystemEntityType.directory) { try { @@ -271,7 +271,7 @@ class FileService { } //处理同名 - Future _getUniqueTargetPath(String originalPath, bool isDirectory) async { + Future getUniqueTargetPath(String originalPath, bool isDirectory) async { if(!await FileSystemEntity.isDirectory(originalPath) && !await FileSystemEntity.isFile(originalPath)) { return originalPath; diff --git a/lib/services/project_modules/cargo_project_module.dart b/lib/services/project_modules/cargo_project_module.dart new file mode 100644 index 0000000..29b71bf --- /dev/null +++ b/lib/services/project_modules/cargo_project_module.dart @@ -0,0 +1,104 @@ +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'; + +/// Cargo (Rust) 工程模块:真实读取 Cargo.toml 的 [[bin]] 定义 +class CargoProjectModule extends ProjectModule { + @override + String get id => 'cargo'; + + @override + String get displayName => 'Cargo'; + + @override + List get triggerFiles => const ['Cargo.toml']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'Cargo.toml')).existsSync(); + + @override + List get requiredToolchainKeys => const ['cargo']; + + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + final bins = _declaredBinaryNames(probe.projectDir); + return ModuleProbeResult.ok(id, [ + // 显式声明的二进制目标优先展示(真实读取 [[bin]] name) + for (final bin in bins) + RunTask( + id: 'cargo_run_$bin', + name: 'Cargo: Run $bin', + command: 'cargo run --bin $bin', + source: TaskSource.detected, + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + RunTask( + id: 'detected_cargo_run', + name: 'Cargo: Run', + command: 'cargo run', + source: TaskSource.detected, + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + RunTask( + id: 'detected_cargo_build', + name: 'Cargo: Build', + command: 'cargo build', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.build_outlined, + ), + RunTask( + id: 'cargo_test', + name: 'Cargo: Test', + command: 'cargo test', + source: TaskSource.detected, + group: 'verification', + moduleId: id, + icon: Icons.fact_check_outlined, + ), + ]); + } + + /// 从 Cargo.toml 提取 [[bin]] name(结构化读取) + static List _declaredBinaryNames(Directory projectDir) { + try { + final file = File(p.join(projectDir.path, 'Cargo.toml')); + if (!file.existsSync()) return const []; + final content = file.readAsStringSync(); + final names = []; + var inBinSection = false; + for (final rawLine in content.split('\n')) { + final commentIdx = rawLine.indexOf('#'); + final lineWithoutComment = commentIdx != -1 ? rawLine.substring(0, commentIdx) : rawLine; + final line = lineWithoutComment.trim(); + if (line.isEmpty) continue; + if (line.startsWith('[')) { + inBinSection = RegExp(r'^\[\[\s*bin\s*\]\]$').hasMatch(line); + continue; + } + if (inBinSection && line.startsWith('name')) { + final parts = line.split('='); + if (parts.length >= 2) { + final value = parts[1].trim().replaceAll('"', '').replaceAll("'", '').trim(); + if (value.isNotEmpty && !names.contains(value)) names.add(value); + } + } + } + return names; + } catch (_) { + return const []; + } + } +} diff --git a/lib/services/project_modules/cmake_project_module.dart b/lib/services/project_modules/cmake_project_module.dart new file mode 100644 index 0000000..1959548 --- /dev/null +++ b/lib/services/project_modules/cmake_project_module.dart @@ -0,0 +1,79 @@ +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'; + +/// CMake 工程模块:工具链在目标系统内可用时才产出任务 +class CMakeProjectModule extends ProjectModule { + @override + String get id => 'cmake'; + + @override + String get displayName => 'CMake'; + + @override + List get triggerFiles => const ['CMakeLists.txt']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync(); + + @override + List get requiredToolchainKeys => const ['cmake']; + + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + final targetName = _detectExecutableTarget(probe.projectDir) ?? p.basename(probe.projectDir.path); + final safeTarget = targetName.replaceAll("'", r"'\''"); + return ModuleProbeResult.ok(id, [ + RunTask( + id: 'detected_cmake_build_run', + name: 'CMake: Build & Run', + command: "cmake -B build && cmake --build build && './build/$safeTarget'", + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.play_circle_outline, + ), + RunTask( + id: 'detected_cmake_build', + name: 'CMake: Build Only', + command: 'cmake -B build && cmake --build build', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.build_outlined, + ), + RunTask( + id: 'detected_cmake_clean', + name: 'CMake: Clean', + command: 'rm -rf build', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.cleaning_services_outlined, + ), + ]); + } + + /// 从 CMakeLists.txt 尝试提取首个 add_executable(target ...) 目标名 + static String? _detectExecutableTarget(Directory projectDir) { + try { + final cmakeFile = File(p.join(projectDir.path, 'CMakeLists.txt')); + if (!cmakeFile.existsSync()) return null; + final content = cmakeFile.readAsStringSync(); + final match = RegExp( + r'add_executable\s*\(\s*([A-Za-z0-9_.\-]+)', + caseSensitive: false, + ).firstMatch(content); + return match?.group(1); + } catch (_) { + return null; + } + } +} diff --git a/lib/services/project_modules/dart_project_module.dart b/lib/services/project_modules/dart_project_module.dart new file mode 100644 index 0000000..191292a --- /dev/null +++ b/lib/services/project_modules/dart_project_module.dart @@ -0,0 +1,60 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +import '../../models/notice_item.dart'; +import '../../models/run_task.dart'; +import 'project_module.dart'; +import 'project_probe.dart'; + +/// Dart (pubspec.yaml) 工程模块 +class DartProjectModule extends ProjectModule { + @override + String get id => 'dart'; + + @override + String get displayName => 'Dart'; + + @override + List get triggerFiles => const ['pubspec.yaml']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'pubspec.yaml')).existsSync(); + + /// Dart SDK 目前没有可用的发行版一键安装命令,因此不做自动补全, + /// 仅在探测阶段如实报告"未找到 dart"。 + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + final available = await probe.hasCommand('dart'); + if (!available) { + return const ModuleProbeResult.failed( + 'dart', + failure: NoticeFailure.toolchainMissing, + detail: 'dart', + ); + } + return ModuleProbeResult.ok(id, [ + RunTask( + id: 'detected_dart_run', + name: 'Dart: Run', + command: 'dart run', + source: TaskSource.detected, + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + RunTask( + id: 'dart_test', + name: 'Dart: Test', + command: 'dart test', + source: TaskSource.detected, + group: 'verification', + moduleId: id, + icon: Icons.fact_check_outlined, + ), + ]); + } +} diff --git a/lib/services/project_modules/gradle_ide_model.dart b/lib/services/project_modules/gradle_ide_model.dart new file mode 100644 index 0000000..fec0b06 --- /dev/null +++ b/lib/services/project_modules/gradle_ide_model.dart @@ -0,0 +1,228 @@ +import 'package:flutter/material.dart'; + +import '../../models/run_task.dart'; + +/// Gradle 结构化模型(由 init script 输出到 .code_editor/gradle_ide_model.json) +/// +/// 这是"真正意义上搜索任务"的数据来源:任务名/路径/分组/描述/类型、 +/// 以及 sourceSets、插件、配置名等后续做依赖导入所需要的信息,全部按字段读取, +/// 不再依赖任何人类可读文本输出与正则。 +class GradleIdeModel { + static const int schemaVersion = 1; + + final int schema; + final String? gradleVersion; + final String rootProject; + final List projects; + + /// init script 内部异常时回填的错误信息(schema == 0) + final String? error; + + const GradleIdeModel({ + required this.schema, + required this.rootProject, + required this.projects, + this.gradleVersion, + this.error, + }); + + /// 解析失败时抛 [FormatException](调用方归类为 probeFailureUnparsable) + static GradleIdeModel fromJson(Map json) { + final schema = _asInt(json['schema']) ?? 0; + if (schema == 0 && json.containsKey('error')) { + throw FormatException(json['error']?.toString() ?? 'unexpected gradle ide model schema: 0'); + } + if (schema != schemaVersion) { + throw FormatException('unexpected gradle ide model schema: $schema'); + } + final rawProjects = json['projects']; + final projects = []; + if (rawProjects is List) { + for (final item in rawProjects) { + if (item is Map) { + projects.add(GradleIdeProject.fromJson(Map.from(item))); + } + } + } + return GradleIdeModel( + schema: schema, + gradleVersion: json['gradleVersion']?.toString(), + rootProject: json['rootProject']?.toString() ?? '', + projects: projects, + error: json['error']?.toString(), + ); + } + + /// 转换为可执行任务列表 + List toRunTasks(String execCmd) { + final tasks = []; + final seen = {}; + + for (final project in projects) { + final isRoot = project.path == ':' || project.path.isEmpty; + for (final task in project.tasks) { + // 根工程的 task.path 形如 ':assemble',展示与 id 均沿用旧的命名习惯, + // 保证既有用户数据(最近运行记录等)不失效。 + final fullName = isRoot ? task.name : (task.path.isNotEmpty ? task.path : ':${task.name}'); + if (!seen.add(fullName)) continue; + + final group = _normalizeGroup(task.group, fullName); + tasks.add(RunTask( + id: 'gradle_${fullName.replaceAll(':', '_')}', + name: fullName, + command: '$execCmd $fullName', + source: TaskSource.detected, + description: task.description, + group: group, + moduleId: 'gradle', + icon: _selectIconForTask(fullName, group), + )); + } + } + + tasks.sort((a, b) { + final rankA = _groupPriority(a.group ?? ''); + final rankB = _groupPriority(b.group ?? ''); + if (rankA != rankB) return rankA.compareTo(rankB); + return a.name.compareTo(b.name); + }); + return tasks; + } + + static String _normalizeGroup(String? group, String taskName) { + final g = (group ?? '').trim().toLowerCase(); + if (g.contains('build')) return 'build'; + if (g.contains('application') || g.contains('run')) return 'application'; + if (g.contains('verification') || g.contains('test') || g.contains('check')) return 'verification'; + if (g.contains('documentation') || g.contains('doc')) return 'documentation'; + if (g.contains('help')) return 'help'; + if (g.contains('android')) return 'android'; + return g.isEmpty ? 'other' : g; + } + + static int _groupPriority(String group) { + switch (group) { + case 'application': + return 1; + case 'build': + return 2; + case 'android': + return 3; + case 'verification': + return 4; + case 'documentation': + return 5; + case 'other': + return 6; + case 'help': + return 7; + default: + return 8; + } + } + + static IconData _selectIconForTask(String taskName, String group) { + final lower = taskName.toLowerCase(); + if (lower.contains('run') || lower.contains('start')) { + return Icons.play_circle_outline; + } + if (lower.contains('clean')) { + return Icons.cleaning_services_outlined; + } + if (lower.contains('test') || lower.contains('check') || lower.contains('lint')) { + return Icons.fact_check_outlined; + } + if (group == 'build' || + lower.contains('assemble') || + lower.contains('bundle') || + lower.contains('build') || + lower.contains('compile')) { + return Icons.build_outlined; + } + if (group == 'help' || lower.contains('help') || lower.contains('info')) { + return Icons.help_outline; + } + return Icons.terminal_outlined; + } + + static int? _asInt(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value); + return null; + } +} + +/// 单个 Gradle 工程(含子模块) +class GradleIdeProject { + final String path; + final String name; + final String? description; + final String? buildFile; + final List plugins; + final List sourceSets; + final List configurations; + final String? javaVersion; + final List tasks; + + const GradleIdeProject({ + required this.path, + required this.name, + this.description, + this.buildFile, + this.plugins = const [], + this.sourceSets = const [], + this.configurations = const [], + this.javaVersion, + this.tasks = const [], + }); + + static GradleIdeProject fromJson(Map json) { + return GradleIdeProject( + path: json['path']?.toString() ?? ':', + name: json['name']?.toString() ?? '', + description: json['description']?.toString(), + buildFile: json['buildFile']?.toString(), + plugins: _stringList(json['plugins']), + sourceSets: _stringList(json['sourceSets']), + configurations: _stringList(json['configurations']), + javaVersion: json['javaVersion']?.toString(), + tasks: [ + for (final item in (json['tasks'] as List? ?? const [])) + if (item is Map) GradleIdeTask.fromJson(Map.from(item)), + ], + ); + } + + static List _stringList(Object? value) { + if (value is! List) return const []; + return [for (final item in value) item.toString()]; + } +} + +/// 单个 Gradle 任务 +class GradleIdeTask { + final String name; + final String path; + final String? group; + final String? description; + final String? type; + + const GradleIdeTask({ + required this.name, + required this.path, + this.group, + this.description, + this.type, + }); + + static GradleIdeTask fromJson(Map json) { + return GradleIdeTask( + name: json['name']?.toString() ?? '', + path: json['path']?.toString() ?? '', + group: json['group']?.toString(), + description: json['description']?.toString(), + type: json['type']?.toString(), + ); + } +} diff --git a/lib/services/project_modules/gradle_project_module.dart b/lib/services/project_modules/gradle_project_module.dart index b60d65d..717fea1 100644 --- a/lib/services/project_modules/gradle_project_module.dart +++ b/lib/services/project_modules/gradle_project_module.dart @@ -1,296 +1,209 @@ import 'dart:convert'; import 'dart:io'; -import 'package:flutter/material.dart'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart' show rootBundle; import 'package:path/path.dart' as p; +import '../../models/notice_item.dart'; import '../../models/run_task.dart'; +import 'gradle_ide_model.dart'; import 'project_module.dart'; +import 'project_probe.dart'; -/// 专门负责 Gradle 项目全自动深度自省与任务构建的模块 +/// Gradle 项目模块:通过 init script 获取**结构化模型**来搜索真实任务。 +/// +/// 与旧实现的区别: +/// * 不再解析 `gradle tasks --all` 的人类可读文本(正则/分组启发式全部删除); +/// * 不再返回任何硬编码兜底任务:探测失败就如实返回失败分类 + 细节; +/// * 先在后台上完成工具链定位与探测脚本准备(warmUp),再正式探测(probe)。 class GradleProjectModule extends ProjectModule { + /// 探测模型文件(init script 输出,位于工程 .code_editor 内,容器内同为 /workspace) + static const String modelFileName = 'gradle_ide_model.json'; + + /// init script 在工程内的落盘路径(相对工程根) + static const String initScriptRelativePath = '.code_editor/code_editor_model.init.gradle'; + @override String get id => 'gradle'; @override String get displayName => 'Gradle'; + @override + bool get supportsResync => true; + + /// Gradle 依赖:`gradle` 这条工具链需求的 checkBinary 就是 `java` + /// (Gradle 本身是 JVM 程序,没有 JDK 连启动都做不到,所以自动补全 = 装 JDK)。 + @override + List get requiredToolchainKeys => const ['gradle']; + @override List get triggerFiles => const [ - 'build.gradle', - 'build.gradle.kts', - 'settings.gradle', - 'settings.gradle.kts', - 'gradlew', - ]; + 'build.gradle', + 'build.gradle.kts', + 'settings.gradle', + 'settings.gradle.kts', + 'gradlew', + ]; @override bool shouldActivate(Directory projectDir) { return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync()); } + /// 环境准备:把结构化探测脚本写入工程 .code_editor/ @override - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { - final projectDir = context.projectDir; - final currentHash = computeBuildScriptHash(projectDir); - - // 1. 优先读取持久化缓存 - if (!forceRefresh) { - final cached = await context.storageService.loadModuleTasks(projectDir.path, id); - if (cached.tasks.isNotEmpty && cached.hash == currentHash) { - debugPrint('[GradleProjectModule] 命中 ${projectDir.path} 真实任务缓存 (共 ${cached.tasks.length} 项)'); - return cached.tasks; - } - } - - // 2. 发起真实容器静默探测 - final execCmd = File(p.join(projectDir.path, 'gradlew')).existsSync() ? 'sh ./gradlew' : 'gradle'; - try { - debugPrint('[GradleProjectModule] 开始在容器后台执行真实 Gradle Task 自省...'); - final result = await context.runHeadless( - '$execCmd tasks --all --console=plain -q', - timeout: const Duration(seconds: 90), - ); - - if (result != null && result.exitCode == 0 && result.stdout.toString().trim().isNotEmpty) { - final tasks = parseGradleTasksOutput(result.stdout.toString(), execCmd); - if (tasks.isNotEmpty) { - debugPrint('[GradleProjectModule] 成功解析到 ${tasks.length} 个真实 Gradle 任务,正在持久化写入缓存...'); - await context.storageService.saveModuleTasks( - projectRoot: projectDir.path, - moduleName: id, - tasks: tasks, - hash: currentHash, - ); - return tasks; - } - } else { - debugPrint('[GradleProjectModule] 静默自省退出码非0或无输出: exitCode=${result?.exitCode}, stderr=${result?.stderr}'); - } - } catch (e) { - debugPrint('[GradleProjectModule] 静默自省异常: $e'); - } - - // 3. 兜底保障:若未生成缓存且静默执行暂不可用(如离线或环境未准备好),回退至预置核心常用任务 - return fallbackDefaultTasks(projectDir, execCmd); + Future prepare(ProjectProbe probe) async { + await _ensureInitScript(probe.projectDir); } - /// 计算构建脚本的综合指纹哈希(用于智能感知构建文件变更并使缓存失效) - static String computeBuildScriptHash(Directory projectDir) { - final buffer = StringBuffer(); - final candidateFiles = [ - 'build.gradle', - 'build.gradle.kts', - 'settings.gradle', - 'settings.gradle.kts', - 'gradle.properties', - ]; + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); - for (final fileName in candidateFiles) { - final file = File(p.join(projectDir.path, fileName)); - if (file.existsSync()) { + final projectDir = probe.projectDir; + + // 系统任务不落盘:每次都跑真实自省(模块结果只写入内存任务表) + // 1. 没有 wrapper 时必须存在 gradle 可执行文件(JDK 由总调度的依赖检测/自动补全保证) + final hasWrapper = _wrapperExists(projectDir); + if (!hasWrapper) { + final hasGradle = await probe.hasCommand('gradle'); + if (!hasGradle) { + return ModuleProbeResult.failed( + id, + failure: NoticeFailure.toolchainMissing, + detail: 'gradle', + ); + } + } + final execCmd = hasWrapper ? 'sh ./gradlew' : 'gradle'; + + try { + await _ensureInitScript(projectDir); + final modelFile = File(p.join(projectDir.path, '.code_editor', modelFileName)); + // 清理上一次的结果,避免读到陈旧模型 + if (modelFile.existsSync()) { try { - final stat = file.statSync(); - buffer.write('$fileName:${stat.size}:${stat.modified.millisecondsSinceEpoch};'); + modelFile.deleteSync(); } catch (_) {} } - } - return buffer.toString(); - } - - /// 解析 `./gradlew tasks --all --console=plain -q` 的纯文本输出 - static List parseGradleTasksOutput(String output, String execCmd) { - final List tasks = []; - final lines = LineSplitter.split(output).toList(); - - String currentProjectPrefix = ''; - String currentGroup = 'other'; - bool inTasksSection = false; - - for (int i = 0; i < lines.length; i++) { - final line = lines[i].trim(); - if (line.isEmpty) continue; - - // 匹配项目标题行,形如: - // "Tasks runnable from root project 'demo'" 或 "Tasks runnable from project ':app'" - final projectMatch = RegExp(r"Tasks runnable from (?:root )?project '([^']+)'").firstMatch(line); - if (projectMatch != null) { - final proj = projectMatch.group(1)!; - if (proj.startsWith(':')) { - currentProjectPrefix = '$proj:'; - } else { - currentProjectPrefix = ''; - } - inTasksSection = true; - continue; - } - - // 遇到 Rules 或非任务分段时跳过 - if (line == 'Rules' || line.startsWith('Pattern:')) { - inTasksSection = false; - continue; - } - - // 忽略单纯的分割线 (如 ------------------------------------------------------------) - if (RegExp(r'^[-=]{3,}$').hasMatch(line)) { - continue; - } - - // 匹配分组名称与下划线分割,例如: - // Build tasks - // ----------- - if (i + 1 < lines.length && RegExp(r'^-{3,}$').hasMatch(lines[i + 1].trim())) { - final groupMatch = RegExp(r'^([a-zA-Z0-9_\s]+)\s+tasks$', caseSensitive: false).firstMatch(line); - if (groupMatch != null) { - currentGroup = groupMatch.group(1)!.trim().toLowerCase(); - inTasksSection = true; - i++; // 跳过下划线行 - continue; + ProcessResult? result = await _runModelCommand(probe, execCmd, offline: false); + if (!_isSuccess(result) && !probe.isCancelled) { + debugPrint('[GradleProjectModule] 在线结构化探测未成功 (exit=${result?.exitCode}),尝试 --offline 重试'); + final offlineResult = await _runModelCommand(probe, execCmd, offline: true); + if (_isSuccess(offlineResult) || offlineResult?.exitCode == -1) { + result = offlineResult; + } else if (offlineResult != null) { + final offlineErr = _stderrTail(offlineResult.stderr); + result = (offlineErr != null && offlineErr.isNotEmpty) ? offlineResult : (result ?? offlineResult); } } - if (!inTasksSection) continue; + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); - // 匹配单个任务定义,例如: - // assemble - Assembles the outputs of this project. - // 或没有描述的任务:myCustomTask (任务名必须以字母/数字/冒号开头) - final taskMatch = RegExp(r'^([a-zA-Z0-9:][a-zA-Z0-9_:\-]*)(?:\s+-\s+(.*))?$').firstMatch(line); - if (taskMatch != null) { - final rawTaskName = taskMatch.group(1)!; - final description = taskMatch.group(2)?.trim(); - - // 避免重复解析分组标题 - if (rawTaskName.toLowerCase().endsWith('tasks')) continue; - - final fullTaskName = rawTaskName.startsWith(':') - ? rawTaskName - : (currentProjectPrefix.isNotEmpty ? '$currentProjectPrefix$rawTaskName' : rawTaskName); - - final taskId = 'gradle_${fullTaskName.replaceAll(':', '_')}'; - final taskGroup = _normalizeGroup(currentGroup, fullTaskName); - final icon = _selectIconForTask(fullTaskName, taskGroup); - - tasks.add(RunTask( - id: taskId, - name: fullTaskName, - command: '$execCmd $fullTaskName', - source: TaskSource.detected, - description: description ?? 'Gradle task: $fullTaskName', - group: taskGroup, - moduleId: 'gradle', - icon: icon, - )); + if (!modelFile.existsSync() || modelFile.lengthSync() == 0) { + if (!_isSuccess(result)) { + // exitCode == -1:容器内命令被超时 kill(DistroManager 的 onTimeout 约定) + if (result != null && result.exitCode == -1) { + return ModuleProbeResult.failed(id, failure: NoticeFailure.timeout); + } + return ModuleProbeResult.failed( + id, + failure: NoticeFailure.executionFailed, + detail: _stderrTail(result?.stderr), + ); + } + final detail = _stderrTail(result?.stderr) ?? _stderrTail(result?.stdout); + return ModuleProbeResult.failed( + id, + failure: NoticeFailure.unparsable, + detail: detail, + ); } - } - // 按任务分组与名称进行合理排序(常用 Build / Application / Verification 优先展示) - tasks.sort((a, b) { - final rankA = _groupPriority(a.group ?? ''); - final rankB = _groupPriority(b.group ?? ''); - if (rankA != rankB) { - return rankA.compareTo(rankB); + final raw = await modelFile.readAsString(); + final decoded = jsonDecode(raw); + if (decoded is! Map) { + return ModuleProbeResult.failed(id, failure: NoticeFailure.unparsable); + } + final model = GradleIdeModel.fromJson(Map.from(decoded)); + if (model.error != null && model.error!.isNotEmpty) { + return ModuleProbeResult.failed( + id, + failure: NoticeFailure.executionFailed, + detail: model.error, + ); } - return a.name.compareTo(b.name); - }); - return tasks; - } + final tasks = model.toRunTasks(execCmd); + if (tasks.isEmpty) { + // 探测成功但工程确实没有任何任务:如实返回空(不伪造) + return ModuleProbeResult.ok(id, const []); + } - /// 兜底默认任务集(在未联网同步真实任务前呈现) - static List fallbackDefaultTasks(Directory projectDir, String execCmd) { - return [ - RunTask( - id: 'detected_gradle_run', - name: 'run', - command: '$execCmd run', - source: TaskSource.detected, - description: 'Execute application main entrypoint', - group: 'application', - moduleId: 'gradle', - icon: Icons.play_circle_outline, - ), - RunTask( - id: 'detected_gradle_assemble', - name: 'assembleDebug', - command: '$execCmd assembleDebug', - source: TaskSource.detected, - description: 'Build debug output package', - group: 'build', - moduleId: 'gradle', - icon: Icons.build_outlined, - ), - RunTask( - id: 'detected_gradle_build', - name: 'build', - command: '$execCmd build', - source: TaskSource.detected, - description: 'Execute full build and tests', - group: 'build', - moduleId: 'gradle', - icon: Icons.build_outlined, - ), - RunTask( - id: 'detected_gradle_clean', - name: 'clean', - command: '$execCmd clean', - source: TaskSource.detected, - description: 'Clean project build outputs', - group: 'build', - moduleId: 'gradle', - icon: Icons.cleaning_services_outlined, - ), - ]; - } - - static String _normalizeGroup(String group, String taskName) { - final g = group.trim().toLowerCase(); - if (g.contains('build')) return 'build'; - if (g.contains('application') || g.contains('run')) return 'application'; - if (g.contains('verification') || g.contains('test') || g.contains('check')) return 'verification'; - if (g.contains('documentation') || g.contains('doc')) return 'documentation'; - if (g.contains('help')) return 'help'; - if (g.contains('android')) return 'android'; - return g.isEmpty ? 'other' : g; - } - - static int _groupPriority(String group) { - switch (group) { - case 'application': - return 1; - case 'build': - return 2; - case 'android': - return 3; - case 'verification': - return 4; - case 'documentation': - return 5; - case 'other': - return 6; - case 'help': - return 7; - default: - return 8; + debugPrint( + '[GradleProjectModule] 结构化探测成功: gradle=${model.gradleVersion} ' + 'projects=${model.projects.length} tasks=${tasks.length}'); + return ModuleProbeResult.ok(id, tasks); + } catch (e) { + debugPrint('[GradleProjectModule] 结构化探测异常: $e'); + return ModuleProbeResult.failed( + id, + failure: NoticeFailure.unparsable, + detail: '$e', + ); } } - static IconData _selectIconForTask(String taskName, String group) { - final lower = taskName.toLowerCase(); - if (lower.contains('run') || lower.contains('start')) { - return Icons.play_circle_outline; + /// 缓存指纹 = 缓存 schema 版本 + 构建脚本指纹 + // 说明:系统任务不再落盘,因此构建脚本指纹与模块缓存读写一并移除。 + bool _wrapperExists(Directory projectDir) => + File(p.join(projectDir.path, 'gradlew')).existsSync(); + + /// 把探测脚本写入工程 .code_editor/(容器内 /workspace/.code_editor/...) + Future _ensureInitScript(Directory projectDir) async { + try { + final content = await rootBundle.loadString('assets/gradle/code_editor_model.init.gradle'); + final target = File(p.join(projectDir.path, initScriptRelativePath)); + final parent = target.parent; + if (!parent.existsSync()) { + parent.createSync(recursive: true); + } + if (!target.existsSync() || target.readAsStringSync() != content) { + target.writeAsStringSync(content, flush: true); + debugPrint('[GradleProjectModule] 已写入结构化探测脚本: ${target.path}'); + } + } catch (e) { + debugPrint('[GradleProjectModule] 写入探测脚本失败: $e'); } - if (lower.contains('clean')) { - return Icons.cleaning_services_outlined; - } - if (lower.contains('test') || lower.contains('check') || lower.contains('lint')) { - return Icons.fact_check_outlined; - } - if (group == 'build' || lower.contains('assemble') || lower.contains('bundle') || lower.contains('build') || lower.contains('compile')) { - return Icons.build_outlined; - } - if (group == 'help' || lower.contains('help') || lower.contains('info')) { - return Icons.help_outline; - } - return Icons.terminal_outlined; + } + + Future _runModelCommand( + ProjectProbe probe, + String execCmd, { + required bool offline, + }) { + final offlineFlag = offline ? ' --offline' : ''; + // 强制英文输出(避免本地化文本影响任何诊断信息),-q 抑制无关日志; + // 模型本体通过 .code_editor/gradle_ide_model.json 回传,不依赖 stdout。 + // 在容器(PRoot)环境中必须显式传递 --no-daemon 并关闭配置缓存(-Dorg.gradle.configuration-cache=false): + // 1. 避免残留孤儿 JVM 守护进程或锁文件损坏导致后续调用连接超时/拒绝; + // 2. 避免配置缓存复用直接跳过 projectsEvaluated 项目评估导致不生成模型文件。 + return probe.runHeadless( + 'LC_ALL=C LANG=C $execCmd --no-daemon -Dorg.gradle.configuration-cache=false --console=plain -q -I $initScriptRelativePath help$offlineFlag', + timeout: const Duration(seconds: 90), + ); + } + + bool _isSuccess(ProcessResult? result) => + result != null && result.exitCode == 0; + + String? _stderrTail(Object? stderr) { + final text = stderr?.toString().trim() ?? ''; + if (text.isEmpty) return null; + const maxLength = 240; + return text.length <= maxLength ? text : '…${text.substring(text.length - maxLength)}'; } } diff --git a/lib/services/project_modules/make_project_module.dart b/lib/services/project_modules/make_project_module.dart new file mode 100644 index 0000000..6266659 --- /dev/null +++ b/lib/services/project_modules/make_project_module.dart @@ -0,0 +1,95 @@ +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'; + +/// Makefile 工程模块:真实解析 Makefile 目标 + 工具链检查 +class MakeProjectModule extends ProjectModule { + @override + String get id => 'make'; + + @override + String get displayName => 'Makefile'; + + @override + List get triggerFiles => const ['Makefile']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'Makefile')).existsSync(); + + @override + List get requiredToolchainKeys => const ['make']; + + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + final targets = _readTargets(probe.projectDir); + return ModuleProbeResult.ok( + id, + [ + RunTask( + id: 'detected_make_default', + name: 'Make: Default', + command: 'make', + source: TaskSource.detected, + group: 'build', + moduleId: id, + icon: Icons.build_circle_outlined, + ), + for (final target in targets) + RunTask( + id: 'make_$target', + name: 'make $target', + command: 'make $target', + source: TaskSource.detected, + group: _groupForTarget(target), + moduleId: id, + icon: _iconForTarget(target), + ), + ], + ); + } + + static String _groupForTarget(String target) { + final lower = target.toLowerCase(); + if (lower.startsWith('test') || lower.startsWith('check') || lower.contains('lint')) { + return 'verification'; + } + return 'build'; + } + + static IconData _iconForTarget(String target) { + final lower = target.toLowerCase(); + if (lower == 'clean') return Icons.cleaning_services_outlined; + if (lower.startsWith('test') || lower.startsWith('check') || lower.contains('lint')) { + return Icons.fact_check_outlined; + } + return Icons.build_outlined; + } + + /// 解析 Makefile 中显式声明的目标名(跳过变量赋值与特殊目标) + static List _readTargets(Directory projectDir) { + try { + final file = File(p.join(projectDir.path, 'Makefile')); + if (!file.existsSync()) return const []; + final result = []; + final pattern = RegExp(r'^([A-Za-z0-9_][A-Za-z0-9_.\-]*)\s*:(?!=)'); + for (final rawLine in file.readAsLinesSync()) { + if (rawLine.startsWith('\t') || rawLine.trimLeft().startsWith('#')) continue; + final match = pattern.firstMatch(rawLine); + if (match == null) continue; + final target = match.group(1)!; + if (target == 'default' || result.contains(target)) continue; + result.add(target); + } + return result; + } catch (_) { + return const []; + } + } +} diff --git a/lib/services/project_modules/npm_project_module.dart b/lib/services/project_modules/npm_project_module.dart new file mode 100644 index 0000000..851f313 --- /dev/null +++ b/lib/services/project_modules/npm_project_module.dart @@ -0,0 +1,88 @@ +import 'dart:convert'; +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'; + +/// NPM (Node / Web) 工程模块:真实读取 package.json 的 scripts +class NpmProjectModule extends ProjectModule { + @override + String get id => 'npm'; + + @override + String get displayName => 'NPM'; + + @override + List get triggerFiles => const ['package.json']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'package.json')).existsSync(); + + @override + List get requiredToolchainKeys => const ['npm']; + + @override + Future probe(ProjectProbe probe) async { + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + final scripts = _readScripts(probe.projectDir); + if (scripts.isEmpty) { + return ModuleProbeResult.ok(id, const []); + } + return ModuleProbeResult.ok( + id, + [ + for (final name in scripts) + RunTask( + // start / test 沿用历史 id 以复用已有的多语言描述 + id: switch (name) { + 'start' => 'detected_npm_start', + 'test' => 'detected_npm_test', + _ => 'npm_$name', + }, + name: 'npm run $name', + command: 'npm run $name', + source: TaskSource.detected, + group: _groupForScript(name), + moduleId: id, + icon: _iconForScript(name), + ), + ], + ); + } + + /// 解析 package.json 的 scripts(结构化读取,不做文本解析) + static List _readScripts(Directory projectDir) { + try { + final file = File(p.join(projectDir.path, 'package.json')); + if (!file.existsSync()) return const []; + final decoded = jsonDecode(file.readAsStringSync()); + if (decoded is! Map) return const []; + final scripts = decoded['scripts']; + if (scripts is! Map) return const []; + return [for (final key in scripts.keys) key.toString()]; + } catch (_) { + return const []; + } + } + + static String _groupForScript(String name) { + final lower = name.toLowerCase(); + if (lower.startsWith('test') || lower.contains('lint') || lower.contains('check')) { + return 'verification'; + } + if (lower.startsWith('build')) return 'build'; + return 'application'; + } + + static IconData _iconForScript(String name) { + final group = _groupForScript(name); + if (group == 'verification') return Icons.fact_check_outlined; + if (group == 'build') return Icons.build_outlined; + return Icons.play_circle_outline; + } +} diff --git a/lib/services/project_modules/project_module.dart b/lib/services/project_modules/project_module.dart index dedd039..0c6ddf3 100644 --- a/lib/services/project_modules/project_module.dart +++ b/lib/services/project_modules/project_module.dart @@ -1,61 +1,59 @@ import 'dart:io'; -import '../../models/run_task.dart'; -import '../distro_manager.dart'; -import '../run_task_storage_service.dart'; -/// 传递给各项目探测模块的上下文环境 -class ProjectModuleContext { - /// 工程根目录 - final Directory projectDir; +import '../toolchain_service.dart'; +import 'project_probe.dart'; - /// 当前在编辑器中激活的文件路径(宿主绝对路径,可能为 null) - final String? currentFilePath; - - /// 容器系统名称(默认为 'ubuntu' 或当前激活的容器) - final String systemName; - - /// 任务持久化存储服务 - final RunTaskStorageService storageService; - - /// 容器管理器 - final DistroManager distroManager; - - const ProjectModuleContext({ - required this.projectDir, - this.currentFilePath, - this.systemName = 'ubuntu', - required this.storageService, - required this.distroManager, - }); - - /// 在容器后台静默执行命令并捕获输出 - Future runHeadless( - String command, { - Duration timeout = const Duration(seconds: 120), - }) { - return distroManager.runHeadlessCommand( - systemName: systemName, - workspacePath: projectDir.path, - command: command, - timeout: timeout, - ); - } -} - -/// 项目探测模块接口(对标 VS Code TaskProvider) +/// 项目探测模块接口(对标 VS Code TaskProvider / IDE 的 ProjectModel 提供者) +/// +/// 总调度按**队列线性执行**驱动每个模块,每个模块依次做三个动作: +/// 1. [prepare] + [checkDependencies]:环境准备与**依赖检测**(返回缺失的依赖 key); +/// 2. [installDependencies]:**自动补全**缺失依赖(默认实现 = 复用容器内发行版安装命令); +/// 3. [probe]:**执行探测**,返回结构化结果。 +/// +/// 约定: +/// * 模块不得返回任何硬编码兜底任务;探测失败就如实返回 failed; +/// * 模块不得自行猜测执行环境,一切执行都通过 [ProjectProbe] 提供的当前系统会话; +/// * 依赖必须声明为 [requiredToolchainKeys](键取自 [ToolchainService.supportedTools]), +/// 这样"自动补全"才能拿到对应发行版的安装命令。 abstract class ProjectModule { /// 模块唯一标识(如 'gradle', 'cmake', 'cargo', 'npm' 等) String get id; - /// 模块友好展示名称 + /// 模块展示名(用于 UI 文案插值,如 'Gradle') String get displayName; /// 该项目特有的特征标记文件(命中其中任意一个才激活本探测器) List get triggerFiles; - /// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否,不进行深层解析) + /// 是否支持"重新同步真实任务" + bool get supportsResync => false; + + /// 需要的工具链依赖 key(对应 [ToolchainService.supportedTools] 的键) + List get requiredToolchainKeys => const []; + + /// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否) bool shouldActivate(Directory projectDir); - /// 探测项目任务(支持优先读取本地缓存;当 forceRefresh=true 时强制发起真实探测) - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}); + /// 环境准备(写探测脚本、准备临时目录等),在依赖检测前执行。默认无操作。 + Future prepare(ProjectProbe probe) async {} + + /// 依赖检测:返回缺失的依赖 key 列表。默认实现按 [requiredToolchainKeys] 逐个检查。 + Future> checkDependencies(ProjectProbe probe) async { + final missing = []; + for (final key in requiredToolchainKeys) { + final requirement = ToolchainService.supportedTools[key]; + if (requirement == null) continue; + final installed = await probe.isToolchainInstalled(requirement); + if (!installed) missing.add(key); + } + return missing; + } + + /// 自动补全缺失依赖:默认实现调用容器内安装(按发行版家族合成命令)。 + Future installDependencies(ProjectProbe probe, List missing) { + return probe.installToolchains(missing); + } + + /// 执行探测(结构化结果) + Future probe(ProjectProbe probe); } diff --git a/lib/services/project_modules/project_probe.dart b/lib/services/project_modules/project_probe.dart new file mode 100644 index 0000000..bb7a19d --- /dev/null +++ b/lib/services/project_modules/project_probe.dart @@ -0,0 +1,329 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +import '../../models/notice_item.dart'; +import '../../models/run_task.dart'; +import '../distro_manager.dart'; +import '../toolchain_service.dart'; + +/// 探测阶段(队列线性执行:入队 → 依赖检测 → 自动补全 → 执行探测 → 整理) +enum ProbePhase { queued, checkingDependency, installingDependency, probing, finalizing } + +/// 一次探测涉及的模块引用(供 UI 建通知条目) +@immutable +class ProbeModuleRef { + final String id; + final String displayName; + + const ProbeModuleRef(this.id, this.displayName); + + @override + bool operator ==(Object other) => + other is ProbeModuleRef && other.id == id && other.displayName == displayName; + + @override + int get hashCode => Object.hash(id, displayName); +} + +/// 探测进度快照(队列线性执行:当前模块 + 队列全貌) +@immutable +class ProbeProgress { + final ProbePhase phase; + + /// 本轮队列中的全部模块(含已完成/排队中) + final List queue; + + /// 当前正在执行三动作的模块 + final ProbeModuleRef? current; + + const ProbeProgress({ + required this.phase, + required this.queue, + this.current, + }); +} + +/// 模块探测结果状态 +enum ModuleProbeStatus { + /// 成功(可能 0 个任务,但探测本身成功) + ok, + + /// 探测失败(工具链缺失 / 依赖安装失败 / 执行失败 / 输出不可解析 / 超时) + failed, + + /// 被用户取消 + cancelled, + + /// 因整轮探测超出时间预算而被跳过(尚未开始执行) + skippedByBudget, +} + +/// 单个模块的探测结果(结构化,失败必须显式携带原因) +@immutable +class ModuleProbeResult { + final String moduleId; + final ModuleProbeStatus status; + final List tasks; + + /// 失败分类(用于 l10n 文案),status != failed 时为 null + final NoticeFailure? failure; + + /// 失败细节:缺失的工具名、stderr 末尾等(技术信息,允许原样展示) + final String? failureDetail; + + const ModuleProbeResult._({ + required this.moduleId, + required this.status, + this.tasks = const [], + this.failure, + this.failureDetail, + }); + + const ModuleProbeResult.ok(String moduleId, List tasks) + : this._(moduleId: moduleId, status: ModuleProbeStatus.ok, tasks: tasks); + + const ModuleProbeResult.failed( + String moduleId, { + required NoticeFailure failure, + String? detail, + }) : this._( + moduleId: moduleId, + status: ModuleProbeStatus.failed, + failure: failure, + failureDetail: detail, + ); + + const ModuleProbeResult.cancelled(String moduleId) + : this._(moduleId: moduleId, status: ModuleProbeStatus.cancelled); + + const ModuleProbeResult.skippedByBudget(String moduleId) + : this._(moduleId: moduleId, status: ModuleProbeStatus.skippedByBudget); +} + +/// 探测请求 +@immutable +class ProjectProbeRequest { + final Directory projectDir; + final String? currentFilePath; + + /// 当前真实选中的容器系统名(必需) + final String systemName; + + /// 仅探测指定模块(用于"重新同步真实任务") + final String? onlyModuleId; + + const ProjectProbeRequest({ + required this.projectDir, + required this.systemName, + this.currentFilePath, + this.onlyModuleId, + }); +} + +/// 探测报告:聚合所有模块结果 + 最终任务列表 +@immutable +class ProjectProbeReport { + final String systemName; + final List detectedTasks; + final Map moduleResults; + final DateTime finishedAt; + + /// 本轮队列涉及的模块总数(用于"已完成 X/Y 个模块"文案) + final int totalModules; + + /// 是否因超出时间预算而中止 + final bool abortedByBudget; + + const ProjectProbeReport({ + required this.systemName, + required this.detectedTasks, + required this.moduleResults, + required this.finishedAt, + this.totalModules = 0, + this.abortedByBudget = false, + }); + + static ProjectProbeReport empty(String systemName) => ProjectProbeReport( + systemName: systemName, + detectedTasks: const [], + moduleResults: const {}, + finishedAt: DateTime.now(), + ); + + /// 真正跑完(成功或失败)的模块数,不含被跳过/被取消的 + int get completedModules => moduleResults.values + .where((r) => r.status == ModuleProbeStatus.ok || r.status == ModuleProbeStatus.failed) + .length; + + bool get hasFailure => + moduleResults.values.any((r) => r.status == ModuleProbeStatus.failed); +} + +/// 一次探测会话:承载进度、取消、缓存读写与容器执行能力。 +/// +/// 依赖能力(供模块的"依赖检测 / 自动补全"两个动作使用): +/// * [isToolchainInstalled]:优先在宿主 rootfs 内快速判定,必要时回落到容器 `command -v`; +/// * [installToolchains]:按发行版家族复用 [ToolchainService] 的安装命令, +/// 带长超时、可取消、逐行回传输出(供弹窗显示安装进度)。 +class ProjectProbe { + /// 整轮探测的默认时间预算:超过后不再出队新模块(剩余模块标记为"预算跳过") + static const Duration defaultBudget = Duration(minutes: 15); + + final ProjectProbeRequest request; + final DistroManager distroManager; + + /// 本轮探测的时间预算 + final Duration budget; + + /// 取消令牌(取消后容器内的子进程会被立即杀掉) + final HeadlessCancelToken cancelToken; + + /// 进度(null 表示已结束) + final ValueNotifier progress; + + /// 安装过程最后一行输出(供弹窗副标题显示安装进度) + final ValueNotifier installLine; + + bool _disposed = false; + DateTime? _deadline; + + ProjectProbe({ + required this.request, + required this.distroManager, + this.budget = defaultBudget, + HeadlessCancelToken? cancelToken, + ValueNotifier? progress, + ValueNotifier? installLine, + }) : cancelToken = cancelToken ?? HeadlessCancelToken(), + progress = progress ?? ValueNotifier(null), + installLine = installLine ?? ValueNotifier(null); + + Directory get projectDir => request.projectDir; + String? get currentFilePath => request.currentFilePath; + String get systemName => request.systemName; + String? get onlyModuleId => request.onlyModuleId; + bool get isCancelled => cancelToken.isCancelled; + bool get isDisposed => _disposed; + + /// 开始计时(由总调度在真正开跑时调用,排队/等待用户的时间不计入预算) + void startBudget([Duration? override]) { + _deadline = DateTime.now().add(override ?? budget); + } + + /// 已耗时(未开始计时返回 Duration.zero) + Duration get elapsed { + final deadline = _deadline; + if (deadline == null) return Duration.zero; + final remaining = deadline.difference(DateTime.now()); + final used = budget - remaining; + return used.isNegative ? Duration.zero : used; + } + + /// 是否已超出时间预算 + bool get isBudgetExceeded { + final deadline = _deadline; + if (deadline == null) return false; + return DateTime.now().isAfter(deadline); + } + + void cancel() => cancelToken.cancel(); + + /// 在容器内静默执行命令(带取消支持 + 可选逐行输出) + Future runHeadless( + String command, { + Duration timeout = const Duration(seconds: 90), + void Function(String chunk)? onStdout, + }) { + return distroManager.runHeadlessCommand( + systemName: systemName, + workspacePath: projectDir.path, + command: command, + timeout: timeout, + cancelToken: cancelToken, + onStdout: onStdout, + ); + } + + /// 容器内是否存在指定二进制(无法确认且未被取消时返回 true,避免受限/单测环境误报缺失) + Future hasCommand(String binary) async { + if (isCancelled) return false; + final result = await runHeadless( + 'command -v $binary >/dev/null 2>&1 && echo CE_OK', + timeout: const Duration(seconds: 20), + ); + if (isCancelled) return false; + if (result == null) return true; + return result.exitCode == 0 && result.stdout.toString().contains('CE_OK'); + } + + /// 依赖是否已安装(优先宿主侧 rootfs 快速判定,失败再回落容器检查) + Future isToolchainInstalled(ToolchainRequirement requirement) async { + if (isCancelled) return false; + try { + final rootDir = await distroManager.getSystemRootDir(systemName); + if (rootDir.existsSync()) { + return ToolchainService.isToolInstalledInRootfs(rootDir, requirement.checkBinary); + } + } catch (_) { + // 宿主信息不可用 -> 回落容器内检查 + } + return hasCommand(requirement.checkBinary); + } + + /// 自动补全依赖:按发行版家族合成安装命令并在容器内执行 + /// + /// 队列是线性执行的,因此同一时刻只会有一次安装,天然不会与其它模块争抢包管理器锁。 + /// 同一批缺失依赖合并成一条脚本执行(只取一次包管理器锁、只 update 一次)。 + Future installToolchains(List toolchainKeys) async { + if (isCancelled || _disposed || toolchainKeys.isEmpty) return false; + + final DistroFamily family; + try { + family = await distroManager.detectDistroFamily(systemName); + } catch (_) { + return false; + } + if (family == DistroFamily.unknown) return false; + + final commands = []; + for (final key in toolchainKeys) { + final requirement = ToolchainService.supportedTools[key]; + final command = requirement?.getInstallCommand(family); + if (command != null && command.trim().isNotEmpty) { + commands.add(command); + } + } + 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); + }, + ); + return result != null && result.exitCode == 0; + } + + /// 更新安装进度行(带释放保护,避免取消/释放后写入已 dispose 的 notifier) + void setInstallLine(String? line) { + if (_disposed) return; + installLine.value = line; + } + + void reportProgress(ProbeProgress value) { + if (isCancelled || _disposed) return; + progress.value = value; + } + + /// 释放(幂等:取消与正常结束路径都可能调用) + void dispose() { + if (_disposed) return; + _disposed = true; + progress.dispose(); + installLine.dispose(); + } +} diff --git a/lib/services/project_modules/single_file_task_detector.dart b/lib/services/project_modules/single_file_task_detector.dart new file mode 100644 index 0000000..3f3e273 --- /dev/null +++ b/lib/services/project_modules/single_file_task_detector.dart @@ -0,0 +1,142 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +import '../../models/run_task.dart'; + +/// 单文件任务探测器:针对当前编辑器正在打开的单文件,生成开箱即用的轻量运行任务。 +/// +/// 包含 8 类语言后缀的独立检测与执行指令安全封装: +/// 1. Python (.py) +/// 2. C (.c) +/// 3. C++ (.cpp, .cc, .cxx) +/// 4. Shell (.sh, .bash) +/// 5. Dart (.dart) +/// 6. Go (.go) +/// 7. Rust (.rs) +/// 8. Node.js (.js) +class SingleFileTaskDetector { + /// 所有支持的单文件后缀集合(全小写) + static const Set supportedExtensions = { + '.py', + '.c', + '.cpp', + '.cc', + '.cxx', + '.sh', + '.bash', + '.dart', + '.go', + '.rs', + '.js', + }; + + /// 检查给定文件路径是否属于支持的单文件任务类型 + static bool isSupported(String filePath) { + final ext = p.extension(filePath).toLowerCase(); + return supportedExtensions.contains(ext); + } + + /// 探测单文件运行指令(基于当前打开的文件) + static RunTask? detect(String projectRoot, String currentFilePath) { + final file = File(currentFilePath); + if (!file.existsSync()) return null; + + // 边界:只有位于工程根目录内的文件才有意义。 + // 容器里挂载为 /workspace 的正是工程根,工程外的文件在容器内不存在, + // 生成的 "../xxx" 路径必然执行失败,因此直接不产出单文件任务。 + if (!p.isWithin(projectRoot, currentFilePath)) return null; + + final fileName = p.basename(currentFilePath); + final ext = p.extension(currentFilePath).toLowerCase(); + + String relPath = p.relative(currentFilePath, from: projectRoot).replaceAll(r'\', '/'); + if (!relPath.startsWith('./') && !relPath.startsWith('/')) { + relPath = './$relPath'; + } + + // 安全转义 Shell 路径参数(单引号包裹并转义内部单引号,彻底阻断 $ 变量展开与特殊字符) + final escapedRelPath = "'${relPath.replaceAll("'", r"'\''")}'"; + + switch (ext) { + case '.py': + return RunTask( + id: 'detected_single_python', + name: 'Python: $fileName', + command: 'python3 $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); + case '.c': + return RunTask( + id: 'detected_single_c', + name: 'GCC: $fileName', + command: 'gcc $escapedRelPath -lm -o /tmp/a.out && /tmp/a.out', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.terminal, + ); + case '.cpp': + case '.cc': + case '.cxx': + return RunTask( + id: 'detected_single_cpp', + name: 'G++: $fileName', + command: 'g++ $escapedRelPath -o /tmp/a.out && /tmp/a.out', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.terminal, + ); + case '.sh': + case '.bash': + return RunTask( + id: 'detected_single_sh', + name: 'Shell: $fileName', + command: 'sh $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.terminal, + ); + case '.dart': + return RunTask( + id: 'detected_single_dart', + name: 'Dart: $fileName', + command: 'dart run $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); + case '.go': + return RunTask( + id: 'detected_single_go', + name: 'Go: $fileName', + command: 'go run $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); + case '.rs': + return RunTask( + id: 'detected_single_rust', + name: 'Rust: $fileName', + command: 'rustc $escapedRelPath -o /tmp/a.out && /tmp/a.out', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.code, + ); + case '.js': + return RunTask( + id: 'detected_single_js', + name: 'Node: $fileName', + command: 'node $escapedRelPath', + source: TaskSource.detected, + group: 'single_file', + icon: Icons.javascript, + ); + default: + return null; + } + } +} diff --git a/lib/services/project_modules/standard_project_modules.dart b/lib/services/project_modules/standard_project_modules.dart index 886f166..1bd28a4 100644 --- a/lib/services/project_modules/standard_project_modules.dart +++ b/lib/services/project_modules/standard_project_modules.dart @@ -1,211 +1,9 @@ -import 'dart:io'; -import 'package:flutter/material.dart'; -import 'package:path/path.dart' as p; -import '../../models/run_task.dart'; -import 'project_module.dart'; +/// 各标准工程模块的导出聚合文件(保持向后兼容) +library; -/// CMake 工程探测模块 -class CMakeProjectModule extends ProjectModule { - @override - String get id => 'cmake'; - - @override - String get displayName => 'CMake'; - - @override - List get triggerFiles => const ['CMakeLists.txt']; - - @override - bool shouldActivate(Directory projectDir) { - return File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync(); - } - - @override - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { - final projectName = p.basename(context.projectDir.path); - return [ - RunTask( - id: 'detected_cmake_build_run', - name: 'CMake: Build & Run', - command: 'cmake -B build && cmake --build build && ./build/$projectName', - source: TaskSource.detected, - description: 'Configure, build, and try launching the target executable', - group: 'build', - moduleId: id, - icon: Icons.play_circle_outline, - ), - RunTask( - id: 'detected_cmake_build', - name: 'CMake: Build Only', - command: 'cmake -B build && cmake --build build', - source: TaskSource.detected, - description: 'Only execute cmake generation and build', - group: 'build', - moduleId: id, - icon: Icons.build_outlined, - ), - RunTask( - id: 'detected_cmake_clean', - name: 'CMake: Clean', - command: 'rm -rf build', - source: TaskSource.detected, - description: 'Clean build cache directory', - group: 'build', - moduleId: id, - icon: Icons.cleaning_services_outlined, - ), - ]; - } -} - -/// Cargo (Rust) 工程探测模块 -class CargoProjectModule extends ProjectModule { - @override - String get id => 'cargo'; - - @override - String get displayName => 'Cargo'; - - @override - List get triggerFiles => const ['Cargo.toml']; - - @override - bool shouldActivate(Directory projectDir) { - return File(p.join(projectDir.path, 'Cargo.toml')).existsSync(); - } - - @override - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { - return [ - RunTask( - id: 'detected_cargo_run', - name: 'Cargo: Run', - command: 'cargo run', - source: TaskSource.detected, - description: 'Compile and run Rust project', - group: 'application', - moduleId: id, - icon: Icons.play_circle_outline, - ), - RunTask( - id: 'detected_cargo_build', - name: 'Cargo: Build', - command: 'cargo build', - source: TaskSource.detected, - description: 'Compile Rust project only', - group: 'build', - moduleId: id, - icon: Icons.build_outlined, - ), - ]; - } -} - -/// NPM (Node / Web) 工程探测模块 -class NpmProjectModule extends ProjectModule { - @override - String get id => 'npm'; - - @override - String get displayName => 'NPM'; - - @override - List get triggerFiles => const ['package.json']; - - @override - bool shouldActivate(Directory projectDir) { - return File(p.join(projectDir.path, 'package.json')).existsSync(); - } - - @override - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { - return [ - RunTask( - id: 'detected_npm_start', - name: 'NPM: Start', - command: 'npm start', - source: TaskSource.detected, - description: 'Start Node service or frontend development environment', - group: 'application', - moduleId: id, - icon: Icons.rocket_launch_outlined, - ), - RunTask( - id: 'detected_npm_test', - name: 'NPM: Test', - command: 'npm test', - source: TaskSource.detected, - description: 'Execute npm test suite', - group: 'verification', - moduleId: id, - icon: Icons.checklist_outlined, - ), - ]; - } -} - -/// Makefile 工程探测模块 -class MakeProjectModule extends ProjectModule { - @override - String get id => 'make'; - - @override - String get displayName => 'Makefile'; - - @override - List get triggerFiles => const ['Makefile']; - - @override - bool shouldActivate(Directory projectDir) { - return File(p.join(projectDir.path, 'Makefile')).existsSync(); - } - - @override - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { - return [ - RunTask( - id: 'detected_make_default', - name: 'Make: Default', - command: 'make', - source: TaskSource.detected, - description: 'Execute default Makefile build target', - group: 'build', - moduleId: id, - icon: Icons.build_circle_outlined, - ), - ]; - } -} - -/// Dart (pubspec.yaml) 工程探测模块 -class DartProjectModule extends ProjectModule { - @override - String get id => 'dart'; - - @override - String get displayName => 'Dart'; - - @override - List get triggerFiles => const ['pubspec.yaml']; - - @override - bool shouldActivate(Directory projectDir) { - return File(p.join(projectDir.path, 'pubspec.yaml')).existsSync(); - } - - @override - Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { - return [ - RunTask( - id: 'detected_dart_run', - name: 'Dart: Run', - command: 'dart run', - source: TaskSource.detected, - description: 'Launch Dart application', - group: 'application', - moduleId: id, - icon: Icons.play_circle_outline, - ), - ]; - } -} +export 'cargo_project_module.dart'; +export 'cmake_project_module.dart'; +export 'dart_project_module.dart'; +export 'make_project_module.dart'; +export 'npm_project_module.dart'; +export 'single_file_task_detector.dart'; diff --git a/lib/services/project_task_detector.dart b/lib/services/project_task_detector.dart deleted file mode 100644 index 0629751..0000000 --- a/lib/services/project_task_detector.dart +++ /dev/null @@ -1,19 +0,0 @@ -import '../models/run_task.dart'; -import 'project_task_dispatcher.dart'; - -/// 负责根据工程文件和当前打开的文件,在内存中动态推导可用的运行任务 -/// (现已接入模块化 ProjectTaskDispatcher 总调度器,保持向后 100% 兼容) -class ProjectTaskDetector { - /// 核心探测入口 - /// [projectRoot]: 工程根目录(宿主绝对路径) - /// [currentFilePath]: 当前编辑器激活打开的文件(宿主绝对路径,可能为 null) - static Future> detect({ - required String projectRoot, - String? currentFilePath, - }) { - return ProjectTaskDispatcher.instance.detect( - projectRoot: projectRoot, - currentFilePath: currentFilePath, - ); - } -} diff --git a/lib/services/project_task_dispatcher.dart b/lib/services/project_task_dispatcher.dart index 33e39c4..34ff997 100644 --- a/lib/services/project_task_dispatcher.dart +++ b/lib/services/project_task_dispatcher.dart @@ -1,16 +1,32 @@ +import 'dart:collection'; import 'dart:io'; -import 'package:flutter/material.dart'; -import 'package:path/path.dart' as p; +import 'package:flutter/material.dart'; + +import '../models/notice_item.dart'; import '../models/run_task.dart'; import 'distro_manager.dart'; +import 'project_modules/cargo_project_module.dart'; +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/npm_project_module.dart'; import 'project_modules/project_module.dart'; -import 'project_modules/standard_project_modules.dart'; -import 'run_task_storage_service.dart'; +import 'project_modules/project_probe.dart'; +import 'project_modules/single_file_task_detector.dart'; -/// 项目任务总调度与路由器(对标 VS Code Task Service) -/// 统一管理各项目模块注册、条件匹配激活、并发/缓存调度与单文件即时任务生成 +/// 项目任务总调度(对标 VS Code Task Service / IDE 的 ProjectModel 协调器) +/// +/// 一次探测 = 下面这套流程走完一遍: +/// 1. **模块发现**(按特征文件激活,快); +/// 2. 命中的模块**全部入队**; +/// 3. **队列线性执行**:一次只跑一个模块,无论成功/失败都接着跑下一个,直到队列空; +/// 4. 每个模块依次做三个动作:**依赖检测 → 自动补全 → 执行探测**; +/// 5. 每个模块探测完成即通过 [onModuleResult] 回调上抛(UI 增量写入"类型→任务数组")。 +/// +/// 队列串行还有一个关键收益:同一时刻只有一个模块在装依赖, +/// 不会出现 apt/apk 争抢同一把包管理器锁的问题。 class ProjectTaskDispatcher { static final ProjectTaskDispatcher instance = ProjectTaskDispatcher(); @@ -43,215 +59,286 @@ class ProjectTaskDispatcher { } ProjectModule? getModule(String id) { - try { - return _modules.firstWhere((m) => m.id == id); - } catch (_) { - return null; + for (final module in _modules) { + if (module.id == id) return module; } + return null; } - /// 获取当前项目中所有被激活的模块 - List getActiveModules(Directory projectDir) { - return _modules.where((m) => m.shouldActivate(projectDir)).toList(); + /// 当前项目中所有被激活的模块(模块发现阶段) + List getActiveModules(Directory projectDir) => + _modules.where((m) => m.shouldActivate(projectDir)).toList(); + + /// 创建一次探测会话(不执行) + ProjectProbe createProbe({ + required String projectRoot, + String? currentFilePath, + required String? systemName, + DistroManager? distroManager, + String? onlyModuleId, + Duration? budget, + }) { + return ProjectProbe( + request: ProjectProbeRequest( + projectDir: Directory(projectRoot), + currentFilePath: currentFilePath, + systemName: systemName ?? '', + onlyModuleId: onlyModuleId, + ), + distroManager: distroManager ?? DistroManager(), + budget: budget ?? ProjectProbe.defaultBudget, + ); } - /// 核心任务探测与分发 - /// [projectRoot]: 工程根目录(宿主绝对路径) - /// [currentFilePath]: 当前编辑器激活打开的文件(宿主绝对路径,可能为 null) - /// [systemName]: 容器实例名称 - /// [forceRefresh]: 是否忽略缓存,强制重新请求真实探测 - /// [onlyModuleId]: 可选,仅执行指定的模块探测 + /// 执行探测会话:模块发现 → 入队 → 线性三动作执行 → 汇总报告 + /// + /// [onModuleResult] 在每个模块结束时回调一次(成功/失败都会回调), + /// 供 UI 立即把结果写入该模块对应的任务类型,并更新它自己的那条弹窗。 + Future run( + ProjectProbe probe, { + void Function(ProjectModule module, ModuleProbeResult result)? onModuleResult, + }) async { + final projectDir = probe.projectDir; + if (!projectDir.existsSync()) { + return ProjectProbeReport.empty(probe.systemName); + } + + // 0. 无可用系统 -> 不探测(也绝不触碰任何 rootfs 目录) + if (!await isUsableSystem(probe.distroManager, probe.systemName)) { + debugPrint('[ProjectTaskDispatcher] 无可用系统 (systemName=${probe.systemName}),跳过项目任务探测'); + return ProjectProbeReport.empty(probe.systemName); + } + + // 1. 模块发现 + 入队 + final active = _resolveActiveModules(projectDir, probe.onlyModuleId); + if (active.isEmpty) { + return ProjectProbeReport.empty(probe.systemName); + } + final queue = ListQueue()..addAll(active); + final refs = [for (final m in active) ProbeModuleRef(m.id, m.displayName)]; + + // 开始计时:整轮探测的时间预算从这里起算 + probe.startBudget(); + + probe.reportProgress(ProbeProgress( + phase: ProbePhase.queued, + queue: refs, + )); + + final results = {}; + var abortedByBudget = false; + + // 2. 线性执行队列 + while (queue.isNotEmpty) { + if (probe.isCancelled) break; + + // 预算检查点 1:模块之间(绝不在安装中途强杀,避免半装状态) + if (probe.isBudgetExceeded) { + abortedByBudget = true; + break; + } + + final module = queue.removeFirst(); + final ref = ProbeModuleRef(module.id, module.displayName); + + void report(ProbePhase phase) { + probe.reportProgress(ProbeProgress( + phase: phase, + queue: refs, + current: ref, + )); + } + + ModuleProbeResult result; + + try { + // 动作 1:环境准备 + 依赖检测 + report(ProbePhase.checkingDependency); + await module.prepare(probe); + var missing = await module.checkDependencies(probe); + + // 动作 2:自动补全缺失依赖(队列串行 => 同一时刻只有一次安装) + result = ModuleProbeResult.ok(module.id, const []); + if (missing.isNotEmpty) { + if (probe.isCancelled) { + result = ModuleProbeResult.cancelled(module.id); + } else if (probe.isBudgetExceeded) { + // 预算检查点 2:安装前(一次安装可能长达 10 分钟,不该在预算将尽时开跑) + abortedByBudget = true; + result = ModuleProbeResult.skippedByBudget(module.id); + } else { + report(ProbePhase.installingDependency); + probe.setInstallLine(null); + final installed = await module.installDependencies(probe, missing); + if (probe.isCancelled) { + result = ModuleProbeResult.cancelled(module.id); + } else if (!installed) { + result = ModuleProbeResult.failed( + module.id, + failure: NoticeFailure.dependencyInstallFailed, + detail: missing.first, + ); + } else { + missing = await module.checkDependencies(probe); + if (missing.isNotEmpty) { + result = ModuleProbeResult.failed( + module.id, + failure: NoticeFailure.toolchainMissing, + detail: missing.first, + ); + } + } + probe.setInstallLine(null); + } + } + + // 动作 3:执行探测(只有前两步没有失败/跳过时才探测) + if (result.status != ModuleProbeStatus.ok) { + // 依赖安装失败 / 预算跳过 / 已取消:不再执行探测 + } else if (probe.isCancelled) { + result = ModuleProbeResult.cancelled(module.id); + } else if (probe.isBudgetExceeded) { + abortedByBudget = true; + result = ModuleProbeResult.skippedByBudget(module.id); + } else { + report(ProbePhase.probing); + result = await module.probe(probe); + } + } catch (e, stack) { + if (probe.isCancelled) { + result = ModuleProbeResult.cancelled(module.id); + } else { + debugPrint('[ProjectTaskDispatcher] ${module.id} 探测异常: $e\n$stack'); + result = ModuleProbeResult.failed( + module.id, + failure: NoticeFailure.executionFailed, + detail: '$e', + ); + } + } + + results[module.id] = result; + onModuleResult?.call(module, result); + + // 无论成功/失败都继续下一个(除非被取消) + if (probe.isCancelled) break; + } + + // 用户取消:队列里剩下的模块统一标记为"已取消",确保完整结算与状态收尾 + if (probe.isCancelled) { + while (queue.isNotEmpty) { + final skippedModule = queue.removeFirst(); + final cancelledResult = ModuleProbeResult.cancelled(skippedModule.id); + results[skippedModule.id] = cancelledResult; + onModuleResult?.call(skippedModule, cancelledResult); + } + } + + // 预算中止:队列里剩下的模块统一标记为"预算跳过",并让 UI 收掉它们的进度卡片 + if (abortedByBudget) { + debugPrint('[ProjectTaskDispatcher] 探测超出时间预算(${probe.budget}),' + '跳过剩余 ${queue.length} 个模块'); + while (queue.isNotEmpty) { + final skippedModule = queue.removeFirst(); + final skippedResult = ModuleProbeResult.skippedByBudget(skippedModule.id); + results[skippedModule.id] = skippedResult; + onModuleResult?.call(skippedModule, skippedResult); + } + } + + // 3. 汇总(含"当前打开文件的单文件运行"任务,置于最前) + probe.reportProgress(ProbeProgress( + phase: ProbePhase.finalizing, + queue: refs, + )); + + final tasks = []; + for (final module in active) { + final result = results[module.id]; + if (result == null || result.status != ModuleProbeStatus.ok) continue; + tasks.addAll(result.tasks); + } + + final currentFilePath = probe.currentFilePath; + if (!probe.isCancelled && currentFilePath != null && currentFilePath.isNotEmpty) { + final single = detectSingleFileTask(projectDir.path, currentFilePath); + if (single != null) tasks.insert(0, single); + } + + probe.progress.value = null; + + return ProjectProbeReport( + systemName: probe.systemName, + detectedTasks: probe.isCancelled ? const [] : tasks, + moduleResults: results, + finishedAt: DateTime.now(), + totalModules: refs.length, + abortedByBudget: abortedByBudget, + ); + } + + List _resolveActiveModules(Directory projectDir, String? onlyModuleId) { + if (onlyModuleId == null) return getActiveModules(projectDir); + final module = getModule(onlyModuleId); + if (module == null || !module.shouldActivate(projectDir)) return const []; + return [module]; + } + + /// 便捷入口:只关心任务列表时使用 Future> detect({ required String projectRoot, String? currentFilePath, - String systemName = 'ubuntu', - RunTaskStorageService? storageService, + String? systemName, DistroManager? distroManager, - bool forceRefresh = false, String? onlyModuleId, }) async { - final List tasks = []; - final projectDir = Directory(projectRoot); - if (!projectDir.existsSync()) { - return tasks; - } - - final context = ProjectModuleContext( - projectDir: projectDir, + final probe = createProbe( + projectRoot: projectRoot, currentFilePath: currentFilePath, systemName: systemName, - storageService: storageService ?? RunTaskStorageService(), - distroManager: distroManager ?? DistroManager(), + distroManager: distroManager, + onlyModuleId: onlyModuleId, ); - - // 1. 如果指定只探测某一模块 - if (onlyModuleId != null) { - final module = getModule(onlyModuleId); - if (module != null && module.shouldActivate(projectDir)) { - try { - final moduleTasks = await module.detect(context, forceRefresh: forceRefresh); - tasks.addAll(moduleTasks); - } catch (e, stack) { - debugPrint('[ProjectTaskDispatcher] Module $onlyModuleId detect error: $e\n$stack'); - } - } - return tasks; - } - - // 2. 并行调度所有命中的项目模块 - final activeModules = getActiveModules(projectDir); - final results = await Future.wait( - activeModules.map((m) async { - try { - return await m.detect(context, forceRefresh: forceRefresh); - } catch (e, stack) { - debugPrint('[ProjectTaskDispatcher] Module ${m.id} detect error: $e\n$stack'); - return []; - } - }), - ); - - for (final moduleTasks in results) { - tasks.addAll(moduleTasks); - } - - // 3. 当前活跃文件(单文件运行)检测并置顶 - if (currentFilePath != null && currentFilePath.isNotEmpty) { - final singleTask = detectSingleFileTask(projectRoot, currentFilePath); - if (singleTask != null) { - tasks.insert(0, singleTask); - } - } - - return tasks; + final report = await run(probe); + probe.dispose(); + return report.detectedTasks; } - /// 针对单个模块执行显式重新同步 - Future> syncModule({ + /// 单模块重新同步(系统探测的特例:只跑一个模块) + Future syncModule({ required String moduleId, required String projectRoot, String? currentFilePath, - String systemName = 'ubuntu', - RunTaskStorageService? storageService, + String? systemName, DistroManager? distroManager, - }) async { - final module = getModule(moduleId); - if (module == null) return []; - - final projectDir = Directory(projectRoot); - if (!projectDir.existsSync()) return []; - - final context = ProjectModuleContext( - projectDir: projectDir, + void Function(ProjectModule module, ModuleProbeResult result)? onModuleResult, + }) { + final probe = createProbe( + projectRoot: projectRoot, currentFilePath: currentFilePath, systemName: systemName, - storageService: storageService ?? RunTaskStorageService(), - distroManager: distroManager ?? DistroManager(), + distroManager: distroManager, + onlyModuleId: moduleId, ); - - return module.detect(context, forceRefresh: true); + return run(probe, onModuleResult: onModuleResult).whenComplete(probe.dispose); } - /// 探测单文件运行指令(基于当前打开的文件) - static RunTask? detectSingleFileTask(String projectRoot, String currentFilePath) { - final file = File(currentFilePath); - if (!file.existsSync()) return null; - - final fileName = p.basename(currentFilePath); - final ext = p.extension(currentFilePath).toLowerCase(); - - // 转换相对容器的路径(在容器内 /workspace 下执行) - String relPath = p.relative(currentFilePath, from: projectRoot).replaceAll(r'\', '/'); - if (!relPath.startsWith('./') && !relPath.startsWith('/')) { - relPath = './$relPath'; - } - - switch (ext) { - case '.py': - return RunTask( - id: 'detected_single_python', - name: 'Python: $fileName', - command: 'python3 "$relPath"', - source: TaskSource.detected, - description: 'Run current Python script', - group: 'single_file', - icon: Icons.code, - ); - case '.c': - return RunTask( - id: 'detected_single_c', - name: 'GCC: $fileName', - command: 'gcc "$relPath" -o /tmp/a.out && /tmp/a.out', - source: TaskSource.detected, - description: 'Compile and execute current C source file', - group: 'single_file', - icon: Icons.terminal, - ); - case '.cpp': - case '.cc': - case '.cxx': - return RunTask( - id: 'detected_single_cpp', - name: 'G++: $fileName', - command: 'g++ "$relPath" -o /tmp/a.out && /tmp/a.out', - source: TaskSource.detected, - description: 'Compile and execute current C++ source file', - group: 'single_file', - icon: Icons.terminal, - ); - case '.sh': - case '.bash': - return RunTask( - id: 'detected_single_sh', - name: 'Shell: $fileName', - command: 'sh "$relPath"', - source: TaskSource.detected, - description: 'Run current Shell script', - group: 'single_file', - icon: Icons.terminal, - ); - case '.dart': - return RunTask( - id: 'detected_single_dart', - name: 'Dart: $fileName', - command: 'dart run "$relPath"', - source: TaskSource.detected, - description: 'Run current Dart file', - group: 'single_file', - icon: Icons.code, - ); - case '.go': - return RunTask( - id: 'detected_single_go', - name: 'Go: $fileName', - command: 'go run "$relPath"', - source: TaskSource.detected, - description: 'Run current Go source file', - group: 'single_file', - icon: Icons.code, - ); - case '.rs': - return RunTask( - id: 'detected_single_rust', - name: 'Rust: $fileName', - command: 'rustc "$relPath" -o /tmp/a.out && /tmp/a.out', - source: TaskSource.detected, - description: 'Compile and execute current Rust source file', - group: 'single_file', - icon: Icons.code, - ); - case '.js': - return RunTask( - id: 'detected_single_js', - name: 'Node: $fileName', - command: 'node "$relPath"', - source: TaskSource.detected, - description: 'Run current JavaScript script', - group: 'single_file', - icon: Icons.javascript, - ); - default: - return null; + /// 判断给定系统名是否可用于执行探测: + /// 1. 名称必须非空; + /// 2. 必须是一个「已安装就绪」的系统实例(rootfs 内具备 etc 与 bin); + /// 3. 平台信息不可用(如单元测试环境)时按不可用处理,宁可不探测也不误探测。 + static Future isUsableSystem(DistroManager manager, String? systemName) async { + final name = systemName?.trim(); + if (name == null || name.isEmpty) return false; + try { + return await manager.isSystemInstalled(name); + } catch (e) { + debugPrint('[ProjectTaskDispatcher] 系统可用性校验失败 (systemName=$name): $e'); + return false; } } + + /// 探测单文件运行指令(基于当前打开的文件),已独立封装至 [SingleFileTaskDetector] + static RunTask? detectSingleFileTask(String projectRoot, String currentFilePath) => + SingleFileTaskDetector.detect(projectRoot, currentFilePath); } diff --git a/lib/services/run_task_storage_service.dart b/lib/services/run_task_storage_service.dart index 9c1476e..9b69fe8 100644 --- a/lib/services/run_task_storage_service.dart +++ b/lib/services/run_task_storage_service.dart @@ -56,12 +56,6 @@ class RunTaskStorageService { } } - /// 兼容旧方法:直接返回 tasks - Future> loadTasks(String projectRoot) async { - final result = await loadConfig(projectRoot); - return result.tasks; - } - /// 将自定义任务列表与最近运行的任务ID持久化保存到 `.code_editor/run_tasks.json` Future saveConfig({ required String projectRoot, @@ -93,9 +87,20 @@ class RunTaskStorageService { } } - /// 兼容旧方法 - Future saveTasks(String projectRoot, List tasks) async { - await saveConfig(projectRoot: projectRoot, tasks: tasks); + /// 只更新"最近执行任务 id",**完整保留磁盘上已有的用户任务**。 + /// + /// 边界:不能用内存里的任务列表去覆盖磁盘——内存可能是"尚未加载完/已被清空"的状态 + /// (例如刚打开工程就立刻点了运行),那会把用户已保存的任务清空。 + Future saveLastRunTaskId({ + required String projectRoot, + String? lastRunTaskId, + }) async { + final existing = await loadConfig(projectRoot); + await saveConfig( + projectRoot: projectRoot, + tasks: existing.tasks, + lastRunTaskId: lastRunTaskId, + ); } /// 获取特定模块的独立任务缓存配置文件(例如 `.code_editor/gradle_tasks.json`) diff --git a/lib/utils/notice_text_resolver.dart b/lib/utils/notice_text_resolver.dart new file mode 100644 index 0000000..9697c3d --- /dev/null +++ b/lib/utils/notice_text_resolver.dart @@ -0,0 +1,52 @@ +import '../l10n/app_localizations.dart'; +import '../models/notice_item.dart'; + +/// 通知的展示文案:标题 + 可选副标题。 +/// 所有文字都来自 l10n,模型层只提供结构化 key 与参数。 +class NoticeDisplay { + final String title; + final String? subtitle; + + const NoticeDisplay({required this.title, this.subtitle}); +} + +/// 把结构化 [NoticeText] 解析为本地化文案 +NoticeDisplay resolveNoticeDisplay(AppLocalizations l10n, NoticeText text) { + switch (text) { + case ModulePhaseText(): + final title = switch (text.phase) { + ProbeNoticePhase.queued => l10n.probePhaseQueued(text.moduleDisplayName), + ProbeNoticePhase.checkingDependency => + l10n.probePhaseCheckingDependency(text.moduleDisplayName), + ProbeNoticePhase.installingDependency => + l10n.probePhaseInstallingDependency(text.moduleDisplayName), + ProbeNoticePhase.detecting => l10n.probeBannerDetecting(text.moduleDisplayName), + ProbeNoticePhase.finalizing => l10n.probeBannerFinalizing, + }; + return NoticeDisplay(title: title, subtitle: text.detail); + case ModuleDoneText(): + return NoticeDisplay( + title: l10n.probeDoneWithCount(text.moduleDisplayName, text.taskCount), + ); + case ProbeBudgetExceededText(): + return NoticeDisplay( + title: l10n.probeBudgetExceededTitle, + subtitle: l10n.probeBudgetExceededMessage(text.completed, text.total), + ); + case ModuleFailureText(): + final subtitle = switch (text.failure) { + NoticeFailure.toolchainMissing => + l10n.probeFailureToolchainMissing(text.detail ?? ''), + NoticeFailure.dependencyInstallFailed => + l10n.probeFailureDependencyInstallFailed(text.detail ?? ''), + NoticeFailure.executionFailed => + l10n.probeFailureExecutionFailed(text.detail ?? ''), + NoticeFailure.unparsable => l10n.probeFailureUnparsable, + NoticeFailure.timeout => l10n.probeFailureTimeout, + }; + return NoticeDisplay( + title: l10n.probeFailedTitle(text.moduleDisplayName), + subtitle: subtitle, + ); + } +} diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index c673922..536feb4 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -17,7 +17,10 @@ import 'package:code_editor/widgets/code_editor_drawer.dart'; import 'package:code_editor/widgets/code_editor_tab_bar.dart'; import 'package:code_editor/widgets/code_editor_widget.dart'; import 'package:code_editor/views/run_task_edit_view.dart'; +import 'package:code_editor/providers/notice_center.dart'; 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:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -33,6 +36,9 @@ class MainView extends StatefulWidget { class _MainViewState extends State { String? _lastProjectRoot; + /// 最近一次已触发探测的 (工程, 系统) 组合,用于去重与"系统就绪后补探测" + String? _lastProbeKey; + static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) { return listen ? context.watch() : context.read(); } @@ -144,12 +150,41 @@ class _MainViewState extends State { ); } + /// 解析并校准「当前真实可用」的容器系统名。 + /// 返回 null 表示没有任何可用系统(此时不应进行任何任务探测)。 + Future _resolveUsableDistro(BuildContext context) async { + final distroProvider = _getDistroProvider(context); + final distroManager = DistroManager(); + try { + var targetDistro = distroProvider?.selectedSystem; + + if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) { + if (distroProvider != 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); + } + } + } + + final ok = targetDistro != null && await distroManager.isSystemInstalled(targetDistro); + return ok ? targetDistro : null; + } catch (e) { + debugPrint('[MainView] 系统可用性解析失败: $e'); + return null; + } + } + /// 执行某个具体的运行任务(前置校验环境、识别工具链并推入终端 PTY 执行) Future _executeRunTask(BuildContext context, RunTask task) async { final projectProvider = _getProjectProvider(context); final terminalProvider = _getTerminalProvider(context); final runProvider = _getRunProvider(context); - final distroProvider = _getDistroProvider(context); final l10n = AppLocalizations.of(context)!; final rootPath = projectProvider.rootPath; @@ -159,29 +194,12 @@ class _MainViewState extends State { } final distroManager = DistroManager(); - var targetDistro = distroProvider?.selectedSystem; // 1. 运行前环境可用性前置拦截校验与状态自动校准 - // 如果尚未选定系统,或者已选系统校验未通过,主动重新扫描物理系统列表进行校准 - if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) { - if (distroProvider != null) { - await distroProvider.refreshSystems(); - targetDistro = distroProvider.selectedSystem; - } - // 如果 Provider 仍未选定,兜底从物理已安装列表中选取并同步 - if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) { - final physicalSystems = await distroManager.listInstalledSystems(); - if (physicalSystems.isNotEmpty) { - targetDistro = physicalSystems.first; - await distroProvider?.selectSystem(targetDistro); - } - } - } - - final hasDistro = targetDistro != null && await distroManager.isSystemInstalled(targetDistro); - if (!hasDistro) { + final String? targetDistro = await _resolveUsableDistro(context); + if (targetDistro == null) { if (!context.mounted) return; - _showMissingDistroDialog(context, targetDistro); + _showMissingDistroDialog(context, null); return; } @@ -244,7 +262,7 @@ class _MainViewState extends State { } /// 打开运行任务选择弹窗 - void _handleOpenRunTasksDialog(BuildContext context) { + Future _handleOpenRunTasksDialog(BuildContext context) async { final runProvider = _getRunProvider(context); if (runProvider == null) return; final projectProvider = _getProjectProvider(context); @@ -255,12 +273,31 @@ class _MainViewState extends State { return; } + // 任务探测必须基于「真实可用的容器系统」;没有任何可用系统时不做任何探测, + // 直接引导用户去系统管理安装环境(避免伪造出并不存在的任务)。 + final systemName = await _resolveUsableDistro(context); + if (systemName == null) { + if (!context.mounted) return; + _showMissingDistroDialog(context, null); + return; + } + if (!context.mounted) return; + // 如果 runProvider 尚未绑定当前项目,立即触发同步 if (runProvider.currentProjectRoot != rootPath) { final tabProvider = _getTabProvider(context); - runProvider.onProjectOpened(rootPath, activeFilePath: tabProvider.currentFilePath); + unawaited(runProvider.onProjectOpened( + rootPath, + activeFilePath: tabProvider.currentFilePath, + systemName: systemName, + )); } + // 单文件任务与"当前打开的文件"强相关:打开列表前本地重算一次(不跑容器) + runProvider.refreshSingleFileTask( + currentFilePath: _getTabProvider(context).currentFilePath, + ); + final isCurrentProject = runProvider.currentProjectRoot == rootPath; RunTasksDialog.show( context: context, @@ -269,7 +306,7 @@ class _MainViewState extends State { lastRunTaskId: isCurrentProject ? (runProvider.lastRunTaskId ?? runProvider.lastRunTask?.id) : null, onTaskSelected: (task) => _executeRunTask(context, task), onEditCustomTasks: () => _handleOpenEditRunTasks(context), - onSyncModule: (moduleId) => runProvider.syncModuleTasks(moduleId), + onSyncModule: (moduleId) => runProvider.syncModuleTasks(moduleId, systemName: systemName), isSyncingModule: (moduleId) => runProvider.isModuleSyncing(moduleId), ); } @@ -309,18 +346,33 @@ class _MainViewState extends State { final runProvider = _getRunProvider(context); if (runProvider == null) return; - await runProvider.detectTasks( + // 没有可用系统则不探测,直接引导安装(探测必须跑在真实系统里) + final systemName = await _resolveUsableDistro(context); + if (systemName == null) { + if (!context.mounted) return; + _showMissingDistroDialog(context, null); + return; + } + if (!context.mounted) return; + + // 正在进行探测时:toast 提示并忽略本次点击(不打断、不重复探测) + final started = await runProvider.requestProjectProbe( projectRoot: rootPath, currentFilePath: tabProvider.currentFilePath, + systemName: systemName, ); - if (context.mounted) { - final l10n = AppLocalizations.of(context)!; - DialogUtils.showSuccessToast( - context, - l10n.detectCompletedMessage(runProvider.detectedTasks.length), - ); + if (!context.mounted) return; + final l10n = AppLocalizations.of(context)!; + if (!started) { + DialogUtils.showErrorToast(context, l10n.probeAlreadyRunning); + return; } + + DialogUtils.showSuccessToast( + context, + l10n.detectCompletedMessage(runProvider.detectedTasks.length), + ); } Future _handleOpenTerminal(BuildContext context) async { @@ -349,22 +401,41 @@ class _MainViewState extends State { final rootPath = projectProvider.rootPath; final isModified = tabProvider.isModified; - // 当检测到切换了项目根目录时,自动触发初始化并进行一次探测 - if (rootPath != _lastProjectRoot) { - _lastProjectRoot = rootPath; - if (rootPath != null) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) { - runProvider?.onProjectOpened(rootPath, activeFilePath: currentFile); - } - }); - } else { + // 【进入项目 = 探测入口】打开 / 切换 / 历史恢复 都由 rootPath 变化体现, + // 因此这里统一作为唯一触发点;同时把"当前真实系统"纳入去重键: + // 冷启动时系统尚未就绪会先跳过,等 DistroProvider 就绪后自动补探测一次。 + final systemName = _getDistroProvider(context, listen: true)?.selectedSystem; + final probeKey = (rootPath == null || systemName == null) ? null : '$rootPath|$systemName'; + + if (rootPath == null) { + if (_lastProjectRoot != null) { + _lastProjectRoot = null; + _lastProbeKey = null; WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { runProvider?.onProjectClosed(); } }); } + } else if (probeKey != null && probeKey != _lastProbeKey) { + _lastProbeKey = probeKey; + _lastProjectRoot = rootPath; + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + final l10n = AppLocalizations.of(this.context); + await runProvider?.onProjectOpened( + rootPath, + activeFilePath: currentFile, + systemName: systemName, + ); + if (!mounted) return; + if (l10n != null && runProvider != null) { + DialogUtils.showSuccessToast( + this.context, + l10n.detectCompletedMessage(runProvider.detectedTasks.length), + ); + } + }); } return PopScope( @@ -409,9 +480,22 @@ class _MainViewState extends State { children: [ const CodeEditorTabBar(), Expanded( - child: CodeEditorWidget( - filePath: currentFile, - rootPath: rootPath, + child: Stack( + children: [ + Positioned.fill( + child: CodeEditorWidget( + filePath: currentFile, + rootPath: rootPath, + ), + ), + if (context.watch() case final NoticeCenter center) + Positioned.fill( + child: NoticeHost( + center: center, + confirmDismissBuilder: confirmCancelProbe, + ), + ), + ], ), ), ], diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart index 1ff6ec9..0493f43 100644 --- a/lib/widgets/code_editor_app_bar.dart +++ b/lib/widgets/code_editor_app_bar.dart @@ -1,6 +1,7 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/services/permission_service.dart'; import 'package:code_editor/views/terminal_view.dart'; +import 'package:code_editor/widgets/terminal_entry_guard.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:path/path.dart' as p; @@ -327,7 +328,14 @@ class _MoreMenuButtonState extends State<_MoreMenuButton> with SingleTickerProvi title: l10n.terminal, iconColor: onSurfaceColor, onTap: () { - _closeMenu(onClosed: widget.onTerminal); + _closeMenu(onClosed: () async { + // 探测进行中:先提示(探测与终端共用同一个容器,可能互相阻塞) + if (widget.isDetecting) { + final proceed = await confirmEnterTerminalWhileProbing(context); + if (!proceed) return; + } + widget.onTerminal?.call(); + }); }, ), Divider( diff --git a/lib/widgets/code_editor_drawer.dart b/lib/widgets/code_editor_drawer.dart index fd2fd72..3b97205 100644 --- a/lib/widgets/code_editor_drawer.dart +++ b/lib/widgets/code_editor_drawer.dart @@ -1,4 +1,5 @@ import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/providers/distro_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/run_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; @@ -8,6 +9,7 @@ import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/views/project_management_view.dart'; import 'package:code_editor/widgets/project_history_widget.dart'; import 'package:code_editor/widgets/file_tree_widget.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'; @@ -92,6 +94,38 @@ class CodeEditorDrawer extends StatelessWidget { } } + Future _handleImportFiles(BuildContext context, String rootPath) async { + final hasPermission = await PermissionService.instance + .ensureStoragePermission(context: context); + if (!hasPermission || !context.mounted) return; + + final l10n = AppLocalizations.of(context); + try { + final result = await FilePicker.platform.pickFiles( + allowMultiple: true, + ); + if (result == null || result.files.isEmpty || !context.mounted) return; + + final count = await _getProjectProvider(context).importFiles( + rootPath, + result.files, + ); + if (context.mounted && count > 0) { + DialogUtils.showSuccessToast( + context, + l10n?.importFilesSuccess(count) ?? '成功导入 $count 个文件', + ); + } + } catch (e) { + if (context.mounted) { + DialogUtils.showErrorToast( + context, + l10n?.importFilesFailed(e.toString()) ?? '导入文件失败: $e', + ); + } + } + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -132,7 +166,11 @@ class CodeEditorDrawer extends StatelessWidget { final runProvider = context.read(); final root = _getProjectProvider(context).rootPath; if (root != null && root.isNotEmpty) { - runProvider?.onProjectOpened(root); + // 传入当前真实选中的系统,无系统时不进行任何任务探测 + runProvider?.onProjectOpened( + root, + systemName: context.read()?.selectedSystem, + ); } }, ), @@ -223,33 +261,59 @@ class CodeEditorDrawer extends StatelessWidget { ), ), if (hasProject) ...[ - const SizedBox(width: 8), + const SizedBox(width: 6), IconButton( visualDensity: VisualDensity.compact, - iconSize: 18, - padding: EdgeInsets.zero, - constraints: const BoxConstraints( - minWidth: 28, - minHeight: 28, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(3), ), + constraints: const BoxConstraints( + minWidth: 24, + minHeight: 24, + ), + iconSize: 18, icon: const Icon(Icons.note_add_outlined), tooltip: l10n.newFile, onPressed: () => _handleNewFile(context, rootPath), ), - const SizedBox(width: 4), + const SizedBox(width: 2), IconButton( visualDensity: VisualDensity.compact, - iconSize: 18, - padding: EdgeInsets.zero, - constraints: const BoxConstraints( - minWidth: 28, - minHeight: 28, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(3), ), + constraints: const BoxConstraints( + minWidth: 24, + minHeight: 24, + ), + iconSize: 18, icon: const Icon(Icons.create_new_folder_outlined), tooltip: l10n.newFolder, onPressed: () => _handleNewFolder(context, rootPath), ), + const SizedBox(width: 2), + IconButton( + visualDensity: VisualDensity.compact, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(3), + ), + constraints: const BoxConstraints( + minWidth: 24, + minHeight: 24, + ), + iconSize: 18, + icon: const Icon(Icons.file_upload_outlined), + tooltip: l10n.importFromExternal, + onPressed: () => + _handleImportFiles(context, rootPath), + ), ], ], ), diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index 0cc0609..1e0b700 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -66,8 +66,63 @@ class _CodeEditorWidgetState extends State { Offset? _currentLocalFocal; double _initialScrollV = 0.0; double _initialScrollH = 0.0; + double _focalLineContinuous = 0.0; + double _focalCharContinuous = 0.0; - void _handlePointerDown(PointerDownEvent event, double currentFontSize) { + final Map _lineHeightCache = {}; + final Map _charWidthCache = {}; + + double getLineHeight(double fontSize, String? fontFamily, List? fallback) { + final key = '$fontSize-$fontFamily-${fallback?.join(',')}'; + if (_lineHeightCache.containsKey(key)) { + return _lineHeightCache[key]!; + } + final painter = TextPainter( + textDirection: TextDirection.ltr, + strutStyle: StrutStyle( + fontSize: fontSize, + fontFamily: fontFamily, + fontFamilyFallback: fallback, + height: 1.4, + forceStrutHeight: true, + ), + text: TextSpan( + text: '0', + style: TextStyle( + fontSize: fontSize, + fontFamily: fontFamily, + fontFamilyFallback: fallback, + height: 1.4, + ), + ), + )..layout(); + final h = painter.preferredLineHeight; + _lineHeightCache[key] = h; + return h; + } + + double getCharWidth(double fontSize, String? fontFamily, List? fallback) { + final key = '$fontSize-$fontFamily-${fallback?.join(',')}'; + if (_charWidthCache.containsKey(key)) { + return _charWidthCache[key]!; + } + final painter = TextPainter( + textDirection: TextDirection.ltr, + text: TextSpan( + text: '0', + style: TextStyle( + fontSize: fontSize, + fontFamily: fontFamily, + fontFamilyFallback: fallback, + ), + ), + )..layout(); + final w = painter.width; + _charWidthCache[key] = w; + return w; + } + + void _handlePointerDown(PointerDownEvent event, double currentFontSize, AppFontItem activeEditorFont) { _pointerPositions[event.pointer] = event.position; if (_pointerPositions.length >= 2 && !_isPinching) { final keys = _pointerPositions.keys.toList(); @@ -104,6 +159,12 @@ class _CodeEditorWidgetState extends State { ? _scrollController!.horizontalScroller.offset : 0.0; + final startH = getLineHeight(_initialPinchFontSize!, activeEditorFont.fontFamily, activeEditorFont.fallback); + final startW = getCharWidth(_initialPinchFontSize!, activeEditorFont.fontFamily, activeEditorFont.fallback); + + _focalLineContinuous = (_initialScrollV + localFocal.dy) / max(1.0, startH); + _focalCharContinuous = (_initialScrollH + localFocal.dx) / max(1.0, startW); + final currentController = _controller; if (currentController != null && !currentController.selection.isCollapsed && @@ -148,25 +209,33 @@ class _CodeEditorWidgetState extends State { : currentGlobalFocal; _currentLocalFocal = currentLocalFocal; - // 连续高精度浮点字号(避免 0.1 离散跳变造成的阶梯式顿挫) - final continuousFontSize = ((_initialPinchFontSize! * clampedScale) * 100).round() / 100.0; + final continuousFontSize = ((_initialPinchFontSize! * clampedScale) * 10).round() / 10.0; final newFontSize = continuousFontSize.clamp(10.0, 30.0); - final fontRatio = newFontSize / _initialPinchFontSize!; - // 焦心连续锚定公式:保持手指焦心下的代码行与手指相对位置绝对静止 - final targetScrollV = (_initialScrollV + _initialLocalFocal!.dy) * fontRatio - currentLocalFocal.dy; - final targetScrollH = (_initialScrollH + _initialLocalFocal!.dx) * fontRatio - currentLocalFocal.dx; + AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono; + try { + activeEditorFont = _getSettingsProvider(context).editorFont; + } catch (_) {} + + final newH = getLineHeight(newFontSize, activeEditorFont.fontFamily, activeEditorFont.fallback); + final newW = getCharWidth(newFontSize, activeEditorFont.fontFamily, activeEditorFont.fallback); + + final targetScrollV = _focalLineContinuous * newH - currentLocalFocal.dy; + final targetScrollH = _focalCharContinuous * newW - currentLocalFocal.dx; if (_scrollController?.verticalScroller.hasClients == true) { final pos = _scrollController!.verticalScroller.position; - final maxV = max(0.0, pos.maxScrollExtent); - final clampedV = targetScrollV.clamp(0.0, maxV); + final totalLines = _controller?.lineCount ?? 1; + final viewportHeight = renderBox?.size.height ?? 500.0; + final computedMaxV = max(0.0, totalLines * newH + viewportHeight * 0.5 - viewportHeight); + final maxV = max(computedMaxV, pos.maxScrollExtent); + final clampedV = targetScrollV.clamp(0.0, maxV).toDouble(); _scrollController!.verticalScroller.jumpTo(clampedV); } if (_scrollController?.horizontalScroller.hasClients == true) { final pos = _scrollController!.horizontalScroller.position; final maxH = max(0.0, pos.maxScrollExtent); - final clampedH = targetScrollH.clamp(0.0, maxH); + final clampedH = targetScrollH.clamp(0.0, max(maxH, targetScrollH)).toDouble(); _scrollController!.horizontalScroller.jumpTo(clampedH); } @@ -217,32 +286,38 @@ class _CodeEditorWidgetState extends State { final initialFontSize = _initialPinchFontSize; final initialLocalFocal = _initialLocalFocal; final currentLocalFocal = _currentLocalFocal ?? initialLocalFocal; - final initialScrollV = _initialScrollV; - final initialScrollH = _initialScrollH; if (finalSize != null && initialFontSize != null && initialLocalFocal != null && currentLocalFocal != null) { // 手势释放后定格为整数(如 16.0),持久化到用户设置 final double targetFontSize = finalSize.clamp(10.0, 30.0).roundToDouble(); - final double fontRatio = targetFontSize / initialFontSize; - - final targetScrollV = (initialScrollV + initialLocalFocal.dy) * fontRatio - currentLocalFocal.dy; - final targetScrollH = (initialScrollH + initialLocalFocal.dx) * fontRatio - currentLocalFocal.dx; + AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono; try { final settings = _getSettingsProvider(context); + activeEditorFont = settings.editorFont; settings.setFontSize(targetFontSize); } catch (_) {} + final finalH = getLineHeight(targetFontSize, activeEditorFont.fontFamily, activeEditorFont.fallback); + final finalW = getCharWidth(targetFontSize, activeEditorFont.fontFamily, activeEditorFont.fallback); + + final targetScrollV = _focalLineContinuous * finalH - currentLocalFocal.dy; + final targetScrollH = _focalCharContinuous * finalW - currentLocalFocal.dx; + if (_scrollController?.verticalScroller.hasClients == true) { final pos = _scrollController!.verticalScroller.position; - final maxV = max(0.0, pos.maxScrollExtent); - final clampedV = targetScrollV.clamp(0.0, maxV); + final totalLines = _controller?.lineCount ?? 1; + final renderBox = _editorContainerKey.currentContext?.findRenderObject() as RenderBox?; + final viewportHeight = renderBox?.size.height ?? 500.0; + final computedMaxV = max(0.0, totalLines * finalH + viewportHeight * 0.5 - viewportHeight); + final maxV = max(computedMaxV, pos.maxScrollExtent); + final clampedV = targetScrollV.clamp(0.0, maxV).toDouble(); _scrollController!.verticalScroller.jumpTo(clampedV); } if (_scrollController?.horizontalScroller.hasClients == true) { final pos = _scrollController!.horizontalScroller.position; final maxH = max(0.0, pos.maxScrollExtent); - final clampedH = targetScrollH.clamp(0.0, maxH); + final clampedH = targetScrollH.clamp(0.0, max(maxH, targetScrollH)).toDouble(); _scrollController!.horizontalScroller.jumpTo(clampedH); } } @@ -258,6 +333,8 @@ class _CodeEditorWidgetState extends State { _currentLocalFocal = null; _initialScrollV = 0.0; _initialScrollH = 0.0; + _focalLineContinuous = 0.0; + _focalCharContinuous = 0.0; }); if (savedSelection != null && !savedSelection.isCollapsed) { @@ -601,7 +678,7 @@ class _CodeEditorWidgetState extends State { child: Listener( key: _editorContainerKey, behavior: HitTestBehavior.translucent, - onPointerDown: (event) => _handlePointerDown(event, activeFontSize), + onPointerDown: (event) => _handlePointerDown(event, activeFontSize, activeEditorFont), onPointerMove: _handlePointerMove, onPointerUp: _handlePointerUp, onPointerCancel: _handlePointerCancel, @@ -652,6 +729,7 @@ class _CodeEditorWidgetState extends State { fontSize: (displayFontSize - 1).clamp(9.0, 30.0), fontFamily: activeEditorFont.fontFamily, fontFamilyFallback: activeEditorFont.fallback, + height: 1.4, ), focusedTextStyle: TextStyle( color: activeTheme.focusedGutterTextColor, @@ -659,6 +737,7 @@ class _CodeEditorWidgetState extends State { fontWeight: FontWeight.bold, fontFamily: activeEditorFont.fontFamily, fontFamilyFallback: activeEditorFont.fallback, + height: 1.4, ), ), DefaultCodeChunkIndicator( diff --git a/lib/widgets/notice_host.dart b/lib/widgets/notice_host.dart new file mode 100644 index 0000000..b05f9a4 --- /dev/null +++ b/lib/widgets/notice_host.dart @@ -0,0 +1,351 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../models/notice_item.dart'; +import '../providers/notice_center.dart'; +import '../utils/notice_text_resolver.dart'; + +/// 通用「通知堆叠宿主」控件。 +/// +/// 把 [NoticeCenter] 里的可见通知渲染成一列卡片: +/// * 每条卡片**带动画插入**(尺寸 + 淡入 + 从右侧滑入); +/// * 支持同时插入多条(受 [NoticeCenter.visibleLimit] 限制,超出进入队列并显示折叠提示); +/// * 任一卡片关闭时播放退场动画,动画结束后队列首条**自动弹出补位**, +/// 并且下方卡片因外层 [SizeTransition] 而平滑上移。 +/// +/// 控件本身不关心业务:文案由 [resolveNoticeDisplay] 依据 l10n 解析,禁止硬编码。 +class NoticeHost extends StatelessWidget { + final NoticeCenter center; + + /// 停靠位置(默认编辑区右上角) + final AlignmentGeometry alignment; + + final EdgeInsets margin; + + /// 单张卡片最大宽度(窄屏自适应) + final double maxWidth; + + final Duration insertDuration; + final Duration removeDuration; + + /// 破坏性通知([NoticeItem.confirmBeforeDismiss])关闭前的二次确认; + /// 返回 false 表示用户放弃关闭(卡片保留,附带动作不执行)。 + final Future Function(BuildContext context)? confirmDismissBuilder; + + const NoticeHost({ + super.key, + required this.center, + this.alignment = Alignment.topRight, + this.margin = const EdgeInsets.only(top: 12, right: 12), + this.maxWidth = 300, + this.insertDuration = const Duration(milliseconds: 220), + this.removeDuration = const Duration(milliseconds: 180), + this.confirmDismissBuilder, + }); + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: center, + builder: (context, _) { + final visible = center.visible; + final queuedCount = center.queued.length; + if (visible.isEmpty && queuedCount == 0) { + return const SizedBox.shrink(); + } + + final l10n = AppLocalizations.of(context); + return Align( + alignment: alignment, + child: Padding( + padding: margin, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + for (final item in visible) + _NoticeEntry( + key: ValueKey(item.id), + item: item, + removing: center.removingIds.contains(item.id), + maxWidth: maxWidth, + insertDuration: insertDuration, + removeDuration: removeDuration, + onDismiss: () async { + // 破坏性操作:先二次确认;用户放弃则卡片保留、附加动作不执行 + if (item.confirmBeforeDismiss && confirmDismissBuilder != null) { + final confirmed = await confirmDismissBuilder!(context); + if (!confirmed) return; + } + // 用户点 × :先执行附加动作(如取消正在进行的探测),再移除卡片 + item.onUserDismiss?.call(); + center.dismiss(item.id); + }, + onRemoved: () => center.finalizeDismiss(item.id), + ), + if (queuedCount > 0) + Padding( + padding: const EdgeInsets.only(top: 6), + child: _QueueBadge( + label: l10n?.noticeQueueMore(queuedCount) ?? '+$queuedCount', + ), + ), + ], + ), + ), + ); + }, + ); + } +} + +/// 单条通知:负责自身的插入/退场动画 +class _NoticeEntry extends StatefulWidget { + final NoticeItem item; + final bool removing; + final double maxWidth; + final Duration insertDuration; + final Duration removeDuration; + final VoidCallback onDismiss; + final VoidCallback onRemoved; + + const _NoticeEntry({ + super.key, + required this.item, + required this.removing, + required this.maxWidth, + required this.insertDuration, + required this.removeDuration, + required this.onDismiss, + required this.onRemoved, + }); + + @override + State<_NoticeEntry> createState() => _NoticeEntryState(); +} + +class _NoticeEntryState extends State<_NoticeEntry> with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: widget.insertDuration, + reverseDuration: widget.removeDuration, + ); + + bool _removalNotified = false; + + @override + void initState() { + super.initState(); + _controller.forward(); + if (widget.removing) { + _playRemoval(); + } + } + + @override + void didUpdateWidget(_NoticeEntry oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.removing && !oldWidget.removing) { + _playRemoval(); + } + } + + void _playRemoval() { + if (_removalNotified) return; + _controller.reverse().whenComplete(() { + if (!mounted || _removalNotified) return; + _removalNotified = true; + widget.onRemoved(); + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final curved = CurvedAnimation( + parent: _controller, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ); + + return SizeTransition( + sizeFactor: curved, + alignment: Alignment.topRight, + child: FadeTransition( + opacity: curved, + child: SlideTransition( + position: Tween( + begin: const Offset(0.18, 0), + end: Offset.zero, + ).animate(curved), + child: Padding( + padding: const EdgeInsets.only(bottom: 8), + child: _NoticeCard( + item: widget.item, + maxWidth: widget.maxWidth, + onDismiss: widget.onDismiss, + ), + ), + ), + ), + ); + } +} + +/// 单张通知卡片外观(与编辑器内"缩放字号胶囊"同一视觉语言) +class _NoticeCard extends StatelessWidget { + final NoticeItem item; + final double maxWidth; + final VoidCallback onDismiss; + + const _NoticeCard({ + required this.item, + required this.maxWidth, + required this.onDismiss, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context); + final display = l10n != null + ? resolveNoticeDisplay(l10n, item.text) + : NoticeDisplay(title: item.text.runtimeType.toString()); + + final isSuccess = item.kind == NoticeKind.success; + final isFailure = item.kind == NoticeKind.failure; + + final (Color accent, Widget leading) = switch (item.kind) { + NoticeKind.progress => ( + theme.colorScheme.primary, + SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 2, + value: item.progress, + color: theme.colorScheme.primary, + ), + ), + ), + NoticeKind.success => ( + Colors.white, + const Icon(Icons.check_circle_outline, size: 18, color: Colors.white), + ), + NoticeKind.failure => ( + theme.colorScheme.error, + Icon(Icons.error_outline, size: 18, color: theme.colorScheme.error), + ), + NoticeKind.info => ( + theme.colorScheme.primary, + Icon(Icons.info_outline, size: 18, color: theme.colorScheme.primary), + ), + }; + + final cardBgColor = isSuccess + ? (theme.brightness == Brightness.dark + ? const Color(0xFF1E5E2F) + : const Color(0xFF2E7D32)) + : theme.colorScheme.surfaceContainerHighest; + + final cardBorder = isFailure + ? const BorderSide(color: Color(0xFFE53935), width: 1.5) + : isSuccess + ? BorderSide(color: Colors.green.shade400.withValues(alpha: 0.6), width: 1) + : BorderSide(color: theme.colorScheme.outlineVariant.withValues(alpha: 0.45), width: 1); + + final titleColor = isSuccess ? Colors.white : theme.colorScheme.onSurface; + final subtitleColor = isSuccess ? Colors.white70 : theme.colorScheme.onSurfaceVariant; + final closeIconColor = isSuccess ? Colors.white70 : theme.colorScheme.onSurfaceVariant; + + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: Material( + elevation: 6, + shadowColor: Colors.black38, + color: cardBgColor, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + side: cardBorder, + ), + clipBehavior: Clip.antiAlias, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 4, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + leading, + const SizedBox(width: 10), + Flexible( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + display.title, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: titleColor, + ), + ), + if (display.subtitle != null && display.subtitle!.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + display.subtitle!, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11.5, + color: subtitleColor, + ), + ), + ], + ], + ), + ), + IconButton( + onPressed: onDismiss, + tooltip: l10n?.probeBannerClose, + icon: const Icon(Icons.close, size: 16), + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.all(4), + constraints: const BoxConstraints(minWidth: 28, minHeight: 28), + color: closeIconColor, + ), + ], + ), + ), + ), + ); + } +} + +/// 队列折叠提示(还能看到"还有 N 项进行中") +class _QueueBadge extends StatelessWidget { + final String label; + + const _QueueBadge({required this.label}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.9), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + label, + style: TextStyle(fontSize: 11, color: theme.colorScheme.onSurfaceVariant), + ), + ); + } +} diff --git a/lib/widgets/probe_cancel_guard.dart b/lib/widgets/probe_cancel_guard.dart new file mode 100644 index 0000000..1233fc7 --- /dev/null +++ b/lib/widgets/probe_cancel_guard.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; + +/// 取消"正在进行的探测"前的二次确认。 +/// +/// 背景:探测会在容器里长时间运行(构建工具自省 + 依赖安装),一个误触就会把整轮 +/// 探测 kill 掉(已完成的模块结果保留,未完成的模块会被跳过)。因此 × 这类破坏性关闭 +/// 需要用户明确确认。 +/// +/// 返回 true = 确认取消(真的中止探测);false = 放弃取消(探测继续)。 +/// 点弹窗外部/返回键按"放弃取消"处理(保守:不打断正在跑的探测)。 +Future confirmCancelProbe(BuildContext context) async { + final l10n = AppLocalizations.of(context); + if (l10n == null) return false; + + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + title: Row( + children: [ + const Icon(Icons.warning_amber_rounded, color: Colors.orange, size: 24), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.probeCancelConfirmTitle, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + content: Text(l10n.probeCancelConfirmMessage), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(l10n.probeKeepDetecting), + ), + ElevatedButton.icon( + onPressed: () => Navigator.of(dialogContext).pop(true), + icon: const Icon(Icons.stop_circle_outlined, size: 18), + label: Text(l10n.cancelProbe), + ), + ], + ), + ); + + return confirmed ?? false; +} diff --git a/lib/widgets/run_tasks_dialog.dart b/lib/widgets/run_tasks_dialog.dart index 2c2247b..d3e0c21 100644 --- a/lib/widgets/run_tasks_dialog.dart +++ b/lib/widgets/run_tasks_dialog.dart @@ -1,7 +1,9 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../models/project_task_table.dart'; import '../models/run_task.dart'; +import '../models/run_task_type.dart'; import '../providers/run_provider.dart'; /// 运行任务选择弹窗(带顶部搜索栏、区分系统探测与自定义任务、支持模块深度重新同步、点击直接调度执行) @@ -54,9 +56,17 @@ class RunTasksDialog extends StatefulWidget { } class _RunTasksDialogState extends State { + /// 内存中持久化各类型任务段的折叠状态(生命周期内常驻,不写磁盘) + static final Set _collapsedTypes = {}; + final TextEditingController _searchController = TextEditingController(); String _searchQuery = ''; + bool _isCollapsed(RunTaskType type) { + if (_searchQuery.isNotEmpty) return false; + return _collapsedTypes.contains(type); + } + @override void initState() { super.initState(); @@ -96,22 +106,28 @@ class _RunTasksDialogState extends State { runProvider = Provider.of(context); } catch (_) {} - final effectiveCustomTasks = runProvider?.customTasks ?? widget.customTasks; - final effectiveDetectedTasks = runProvider?.detectedTasks ?? widget.detectedTasks; final effectiveLastRunTaskId = runProvider?.lastRunTaskId ?? widget.lastRunTaskId; - final filteredCustom = effectiveCustomTasks.where((t) => _matchesQuery(t, l10n)).toList(); - final filteredDetected = effectiveDetectedTasks.where((t) => _matchesQuery(t, l10n)).toList(); - final hasAny = filteredCustom.isNotEmpty || filteredDetected.isNotEmpty; + // 类型 → 任务数组:优先取 Provider 的当前工程内存表; + // 无 Provider(独立使用弹窗/单测)时按同构结构由入参临时组装。 + final ProjectTaskTable table; + if (runProvider != null) { + table = runProvider.taskTable; + } else { + table = ProjectTaskTable()..setUserTasks(widget.customTasks); + for (final task in widget.detectedTasks) { + final type = RunTaskType.ofTask(task); + table.replaceType(type, [...table.tasksOf(type), task]); + } + } - // 检测是否存在 Gradle 模块任务 - final hasGradleTasks = filteredDetected.any( - (t) => t.moduleId == 'gradle' || t.id.startsWith('gradle_') || t.id.startsWith('detected_gradle_'), - ); - - final isGradleSyncing = (widget.isSyncingModule != null) - ? widget.isSyncingModule!('gradle') - : (runProvider?.isModuleSyncing('gradle') ?? false); + // 按类型过滤(搜索命中),保留非空类型的顺序 + final sections = <({RunTaskType type, List tasks})>[]; + for (final type in RunTaskType.values) { + final tasks = table.tasksOf(type).where((t) => _matchesQuery(t, l10n)).toList(); + if (tasks.isNotEmpty) sections.add((type: type, tasks: tasks)); + } + final hasAny = sections.isNotEmpty; return Dialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), @@ -179,27 +195,31 @@ class _RunTasksDialogState extends State { ) : ListView( children: [ - if (filteredDetected.isNotEmpty) ...[ + // 任务类型 → 具体任务:每个类型为独立折叠 Tile(折叠状态内存常驻) + for (final section in sections) ...[ _buildSectionHeader( context, - l10n.systemDetectedTasks, - Icons.radar_outlined, - trailing: hasGradleTasks - ? _buildGradleSyncAction(context, l10n, isGradleSyncing, () { - if (widget.onSyncModule != null) { - widget.onSyncModule!('gradle'); - } else { - runProvider?.syncModuleTasks('gradle'); - } - }) - : null, + section.type, + _typeLabel(l10n, section.type, runProvider), + _typeIcon(section.type), + section.tasks.length, + _isCollapsed(section.type), + () { + setState(() { + if (_collapsedTypes.contains(section.type)) { + _collapsedTypes.remove(section.type); + } else { + _collapsedTypes.add(section.type); + } + }); + }, ), - ...filteredDetected.map((task) => _buildTaskItem(context, task, l10n, effectiveLastRunTaskId)), - const SizedBox(height: 8), - ], - if (filteredCustom.isNotEmpty) ...[ - _buildSectionHeader(context, l10n.userCustomTasks, Icons.person_outline), - ...filteredCustom.map((task) => _buildTaskItem(context, task, l10n, effectiveLastRunTaskId)), + if (!_isCollapsed(section.type)) ...[ + ...section.tasks.map( + (task) => _buildTaskItem(context, task, l10n, effectiveLastRunTaskId), + ), + ], + const SizedBox(height: 6), ], ], ), @@ -211,88 +231,91 @@ class _RunTasksDialogState extends State { ); } - Widget _buildGradleSyncAction( - BuildContext context, - AppLocalizations l10n, - bool isSyncing, - VoidCallback onSync, - ) { - final theme = Theme.of(context); - if (isSyncing) { - return Padding( - padding: const EdgeInsets.only(right: 6), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - SizedBox( - width: 14, - height: 14, - child: CircularProgressIndicator( - strokeWidth: 2, - color: theme.colorScheme.primary, - ), - ), - const SizedBox(width: 6), - Text( - l10n.syncingTasks, - style: TextStyle( - fontSize: 11, - color: theme.colorScheme.primary, - ), - ), - ], - ), - ); + /// 任务类型展示名:模块类型用专有名词(取自模块 displayName),单文件/用户任务走 l10n + String _typeLabel(AppLocalizations l10n, RunTaskType type, RunProvider? runProvider) { + final moduleId = type.moduleId; + if (moduleId == null) { + return switch (type) { + RunTaskType.singleFile => l10n.taskTypeSingleFile, + RunTaskType.user => l10n.userCustomTasks, + RunTaskType.other => l10n.taskTypeOther, + _ => type.name, + }; } + return runProvider?.moduleDisplayName(moduleId) ?? _moduleLabel(type); + } - return InkWell( - borderRadius: BorderRadius.circular(12), - onTap: onSync, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.refresh, size: 14, color: theme.colorScheme.primary), - const SizedBox(width: 4), - Text( - l10n.resyncModuleTasks, - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.w600, - color: theme.colorScheme.primary, - ), - ), - ], - ), - ), - ); + /// 模块类型专有名词(Gradle / CMake / …) + String _moduleLabel(RunTaskType type) { + final moduleId = type.moduleId; + if (moduleId == null) return type.name; + return moduleId[0].toUpperCase() + moduleId.substring(1); + } + + IconData _typeIcon(RunTaskType type) { + return switch (type) { + RunTaskType.user => Icons.person_outline, + RunTaskType.singleFile => Icons.description_outlined, + RunTaskType.other => Icons.category_outlined, + _ => Icons.radar_outlined, + }; } Widget _buildSectionHeader( BuildContext context, + RunTaskType type, String title, - IconData icon, { - Widget? trailing, - }) { + IconData icon, + int count, + bool isCollapsed, + VoidCallback onToggle, + ) { final theme = Theme.of(context); - return Padding( - padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 4), - child: Row( - children: [ - Icon(icon, size: 16, color: theme.colorScheme.primary), - const SizedBox(width: 6), - Expanded( - child: Text( - title, - style: theme.textTheme.labelMedium?.copyWith( - color: theme.colorScheme.primary, - fontWeight: FontWeight.bold, + return InkWell( + borderRadius: BorderRadius.circular(8), + onTap: onToggle, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6), + child: Row( + children: [ + Icon(icon, size: 16, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Expanded( + child: Row( + children: [ + Text( + title, + style: theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '$count', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: theme.colorScheme.primary, + ), + ), + ), + ], ), ), - ), - if (trailing != null) trailing, - ], + Icon( + isCollapsed ? Icons.expand_more : Icons.expand_less, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), ), ); } @@ -322,11 +345,14 @@ class _RunTasksDialogState extends State { child: ListTile( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), dense: true, + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), title: Row( children: [ Expanded( child: Text( task.getLocalizedName(l10n), + maxLines: 1, + overflow: TextOverflow.ellipsis, style: TextStyle( fontWeight: FontWeight.w600, color: isLastRun ? Colors.green.shade700 : null, @@ -335,7 +361,8 @@ class _RunTasksDialogState extends State { ), if (task.group != null && task.group!.isNotEmpty && task.group != 'single_file') Container( - margin: const EdgeInsets.only(left: 6), + margin: const EdgeInsets.only(left: 8), + constraints: const BoxConstraints(maxWidth: 130), padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1.5), decoration: BoxDecoration( color: theme.colorScheme.secondaryContainer.withValues(alpha: 0.6), @@ -343,6 +370,8 @@ class _RunTasksDialogState extends State { ), child: Text( task.group!, + maxLines: 1, + overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: 10, fontWeight: FontWeight.w500, @@ -378,12 +407,12 @@ class _RunTasksDialogState extends State { ) : null, trailing: CircleAvatar( - radius: 16, + radius: 15, backgroundColor: isLastRun ? Colors.green.withValues(alpha: 0.25) : theme.colorScheme.primaryContainer, foregroundColor: isLastRun ? Colors.green : theme.colorScheme.onPrimaryContainer, - child: const Icon(Icons.play_arrow, size: 20), + child: const Icon(Icons.play_arrow, size: 18), ), onTap: () { Navigator.of(context).pop(); diff --git a/lib/widgets/terminal_entry_guard.dart b/lib/widgets/terminal_entry_guard.dart new file mode 100644 index 0000000..32dcc5e --- /dev/null +++ b/lib/widgets/terminal_entry_guard.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; + +/// 「进入终端」前的探测占用确认。 +/// +/// 背景:任务探测会占用当前容器执行构建工具自省与依赖自动安装;此时进入终端并在里面 +/// 做安装软件包、构建等操作,可能与探测互相阻塞(包管理器锁、构建缓存写冲突)或产生异常。 +/// 因此主页面「更多 → 终端」入口在探测进行中时先弹提示,由用户决定是否仍进入。 +/// +/// 返回 true = 继续进入终端;false = 取消(不进入)。 +/// 点弹窗外部/返回键同样按"取消"处理(保守策略:不进入)。 +Future confirmEnterTerminalWhileProbing(BuildContext context) async { + final l10n = AppLocalizations.of(context); + if (l10n == null) return true; + + final result = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + title: Row( + children: [ + const Icon(Icons.hourglass_top_rounded, color: Colors.orange, size: 24), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.probeBusyEnterTerminalTitle, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + content: Text(l10n.probeBusyEnterTerminalMessage), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(l10n.cancel), + ), + ElevatedButton.icon( + onPressed: () => Navigator.of(dialogContext).pop(true), + icon: const Icon(Icons.terminal, size: 18), + label: Text(l10n.probeEnterTerminalAnyway), + ), + ], + ), + ); + + return result ?? false; +} diff --git a/packages/re_editor/lib/src/_code_editable.dart b/packages/re_editor/lib/src/_code_editable.dart index 8192d53..140bb4b 100644 --- a/packages/re_editor/lib/src/_code_editable.dart +++ b/packages/re_editor/lib/src/_code_editable.dart @@ -201,6 +201,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli final Widget child = _CodeScrollable( axisDirection: AxisDirection.down, controller: widget.scrollController.verticalScroller, + bidirectionalHorizontalController: widget.wordWrap ? null : widget.scrollController.horizontalScroller, viewportBuilder: (context, ViewportOffset vertical) { final Widget? indicator = widget.indicatorBuilder?.call( context, @@ -244,6 +245,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli codeField = _CodeScrollable( axisDirection: AxisDirection.right, controller: widget.scrollController.horizontalScroller, + enableDrag: false, viewportBuilder: (context, ViewportOffset horizontal) { final ViewportOffset effectiveHorizontal; if (widget.pinLineNumbers || gutterWidget == null) { @@ -321,11 +323,6 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli onNotification: (notification) { if (notification is ScrollStartNotification) { widget.selectionOverlayController.hideToolbar(); - if (notification.metrics.axis == Axis.horizontal) { - _stopScroller(widget.scrollController.verticalScroller); - } else if (notification.metrics.axis == Axis.vertical) { - _stopScroller(widget.scrollController.horizontalScroller); - } } else if (notification is ScrollEndNotification) { if (!widget.controller.selection.isCollapsed && widget.controller.selection.baseOffset != -1) { WidgetsBinding.instance.addPostFrameCallback((_) { @@ -333,6 +330,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli !widget.controller.selection.isCollapsed && widget.controller.selection.baseOffset != -1) { widget.selectionOverlayController.showToolbar(context, Offset.zero); + widget.selectionOverlayController.showHandle(context); } }); } @@ -344,17 +342,6 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli ); } - void _stopScroller(ScrollController scroller) { - if (!scroller.hasClients) return; - for (final position in scroller.positions) { - if (position is CodeEditorScrollPosition) { - position.stopScrolling(); - } else if (position.activity?.isScrolling == true) { - position.hold(() {}); - } - } - } - Widget _buildCodeField(ViewportOffset vertical, ViewportOffset? horizontal) { return _CodeField( key: widget.editorKey, diff --git a/packages/re_editor/lib/src/_code_extensions.dart b/packages/re_editor/lib/src/_code_extensions.dart index ef8a7ec..d71633c 100644 --- a/packages/re_editor/lib/src/_code_extensions.dart +++ b/packages/re_editor/lib/src/_code_extensions.dart @@ -37,8 +37,8 @@ extension _TextSpanExtension on TextSpan { extension _OffsetExtension on Offset { - bool isSamePosition(Offset offset) { - return (this - offset).distance < 10; + bool isSamePosition(Offset offset, [double slop = 35.0]) { + return (this - offset).distance <= slop; } } \ No newline at end of file diff --git a/packages/re_editor/lib/src/_code_field.dart b/packages/re_editor/lib/src/_code_field.dart index 0948679..6a9135d 100644 --- a/packages/re_editor/lib/src/_code_field.dart +++ b/packages/re_editor/lib/src/_code_field.dart @@ -1346,21 +1346,6 @@ class _CodeFieldRender extends RenderBox implements MouseTrackerAnnotation { startIndex = min(((target - paddingTop) / _preferredLineHeight).floor(), max(0, _codes.length - 1)); } _displayParagraphs.addAll(_buildDisplayRenderParagraphs(startIndex, effectiveWidth)); - } else if (_horizontalViewport != null) { - // In horizontal scrolling (unwrapped) mode, every line has height == _preferredLineHeight. - // There is no line wrapping, so delta is strictly 0 and viewport correction should never occur. - final int startIndex; - if (target <= paddingTop) { - startIndex = 0; - } else { - startIndex = min(((target - paddingTop) / _preferredLineHeight).floor(), max(0, _codes.length - 1)); - } - if (_displayParagraphs.first.index != startIndex || - target < _displayParagraphs.first.top || - target + size.height > _displayParagraphs.last.bottom) { - _displayParagraphs.clear(); - _displayParagraphs.addAll(_buildDisplayRenderParagraphs(startIndex, effectiveWidth)); - } } else { if (_codes.length <= _displayParagraphs.first.index) { _displayParagraphs.clear(); @@ -1541,13 +1526,21 @@ class _CodeFieldRender extends RenderBox implements MouseTrackerAnnotation { } void _calculatePreferredLineHeight() { + final StrutStyle strutStyle = StrutStyle( + fontSize: _textStyle.fontSize, + fontFamily: _textStyle.fontFamily, + height: _textStyle.height, + forceStrutHeight: true, + ); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, + strutStyle: strutStyle, ); painter.text = TextSpan( text: '0', style: _textStyle, ); + painter.layout(); _preferredLineHeight = painter.preferredLineHeight; _foregroundRender.find<_CodeFieldCursorPainter>().height = painter.preferredLineHeight; _foregroundRender.find<_CodeFieldFloatingCursorPainter>().height = painter.preferredLineHeight; diff --git a/packages/re_editor/lib/src/_code_paragraph.dart b/packages/re_editor/lib/src/_code_paragraph.dart index 0ded34c..bc252e2 100644 --- a/packages/re_editor/lib/src/_code_paragraph.dart +++ b/packages/re_editor/lib/src/_code_paragraph.dart @@ -213,24 +213,27 @@ class _CodeParagraphProvider { if (uiStyle == _style) { return; } + final StrutStyle strutStyle = StrutStyle( + fontSize: style.fontSize, + fontFamily: style.fontFamily, + height: style.height, + forceStrutHeight: true, + ); _paragraphStyle = style.getParagraphStyle( textAlign: TextAlign.left, textDirection: TextDirection.ltr, - strutStyle: StrutStyle( - fontSize: style.fontSize, - fontFamily: style.fontFamily, - height: style.height, - forceStrutHeight: true, - ) + strutStyle: strutStyle, ); _style = uiStyle; final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, + strutStyle: strutStyle, ); painter.text = TextSpan( text: '0', - style: style + style: style, ); + painter.layout(); _preferredLineHeight = painter.preferredLineHeight; clearCache(); } diff --git a/packages/re_editor/lib/src/_code_scroll.dart b/packages/re_editor/lib/src/_code_scroll.dart index 4e63547..7b757a9 100644 --- a/packages/re_editor/lib/src/_code_scroll.dart +++ b/packages/re_editor/lib/src/_code_scroll.dart @@ -6,6 +6,8 @@ class _CodeScrollable extends StatefulWidget { final AxisDirection axisDirection; final ScrollController? controller; + final ScrollController? bidirectionalHorizontalController; + final bool enableDrag; final ViewportBuilder viewportBuilder; final CodeScrollbarBuilder? scrollbarBuilder; @@ -13,6 +15,8 @@ class _CodeScrollable extends StatefulWidget { super.key, required this.axisDirection, this.controller, + this.bidirectionalHorizontalController, + this.enableDrag = true, required this.viewportBuilder, this.scrollbarBuilder, }); @@ -26,6 +30,11 @@ class _CodeScrollableState extends State<_CodeScrollable> { CodeEditorScrollController? _effectiveController; + ScrollHoldController? _verticalHold; + ScrollHoldController? _horizontalHold; + Drag? _verticalDrag; + Drag? _horizontalDrag; + @override void initState() { super.initState(); @@ -48,31 +57,191 @@ class _CodeScrollableState extends State<_CodeScrollable> { void didUpdateWidget(_CodeScrollable oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) { + _handlePanCancel(); if (_effectiveController != null && _effectiveController!.delegate != null) { _effectiveController!.dispose(); } _initController(); } + if (widget.bidirectionalHorizontalController != oldWidget.bidirectionalHorizontalController) { + _handlePanCancel(); + } } @override void dispose() { + _handlePanCancel(); if (_effectiveController != null && _effectiveController!.delegate != null) { _effectiveController!.dispose(); } super.dispose(); } + ScrollPosition? get _verticalPosition { + if (_effectiveController != null && _effectiveController!.positions.isNotEmpty) { + return _effectiveController!.positions.first; + } + return null; + } + + ScrollPosition? get _horizontalPosition { + final hController = widget.bidirectionalHorizontalController; + if (hController != null && hController.positions.isNotEmpty) { + return hController.positions.first; + } + return null; + } + + void _handlePanDown(DragDownDetails details) { + if (_effectiveController?.isPinchLocked == true) { + return; + } + final vPos = _verticalPosition; + final hPos = _horizontalPosition; + _verticalHold = vPos?.hold(_disposeVerticalHold); + _horizontalHold = hPos?.hold(_disposeHorizontalHold); + } + + void _handlePanStart(DragStartDetails details) { + if (_effectiveController?.isPinchLocked == true) { + _handlePanCancel(); + return; + } + final vPos = _verticalPosition; + final hPos = _horizontalPosition; + _verticalDrag = vPos?.drag(details, _disposeVerticalDrag); + _horizontalDrag = hPos?.drag(details, _disposeHorizontalDrag); + _disposeVerticalHold(); + _disposeHorizontalHold(); + } + + void _handlePanUpdate(DragUpdateDetails details) { + if (_effectiveController?.isPinchLocked == true) { + _handlePanCancel(); + return; + } + if (_verticalDrag != null) { + final verticalDetails = DragUpdateDetails( + sourceTimeStamp: details.sourceTimeStamp, + delta: Offset(0.0, details.delta.dy), + primaryDelta: details.delta.dy, + globalPosition: details.globalPosition, + localPosition: details.localPosition, + ); + _verticalDrag?.update(verticalDetails); + } + if (_horizontalDrag != null) { + final horizontalDetails = DragUpdateDetails( + sourceTimeStamp: details.sourceTimeStamp, + delta: Offset(details.delta.dx, 0.0), + primaryDelta: details.delta.dx, + globalPosition: details.globalPosition, + localPosition: details.localPosition, + ); + _horizontalDrag?.update(horizontalDetails); + } + } + + void _handlePanEnd(DragEndDetails details) { + final double dx = details.velocity.pixelsPerSecond.dx; + final double dy = details.velocity.pixelsPerSecond.dy; + + final vDrag = _verticalDrag; + final hDrag = _horizontalDrag; + _verticalDrag = null; + _horizontalDrag = null; + + if (vDrag != null) { + final verticalDetails = DragEndDetails( + velocity: Velocity(pixelsPerSecond: Offset(0.0, dy)), + primaryVelocity: dy, + ); + vDrag.end(verticalDetails); + } + if (hDrag != null) { + final horizontalDetails = DragEndDetails( + velocity: Velocity(pixelsPerSecond: Offset(dx, 0.0)), + primaryVelocity: dx, + ); + hDrag.end(horizontalDetails); + } + } + + void _handlePanCancel() { + final vHold = _verticalHold; + final hHold = _horizontalHold; + final vDrag = _verticalDrag; + final hDrag = _horizontalDrag; + _verticalHold = null; + _horizontalHold = null; + _verticalDrag = null; + _horizontalDrag = null; + vHold?.cancel(); + hHold?.cancel(); + vDrag?.cancel(); + hDrag?.cancel(); + } + + void _disposeVerticalHold() { + _verticalHold = null; + } + + void _disposeHorizontalHold() { + _horizontalHold = null; + } + + void _disposeVerticalDrag() { + _verticalDrag = null; + } + + void _disposeHorizontalDrag() { + _horizontalDrag = null; + } + @override Widget build(BuildContext context) { - return Scrollable( + final bool isBidirectional = widget.bidirectionalHorizontalController != null; + final Widget scrollable = Scrollable( excludeFromSemantics: true, controller: _effectiveController, - scrollBehavior: _ScrollBehavior(widget.scrollbarBuilder), + scrollBehavior: _ScrollBehavior( + widget.scrollbarBuilder, + enableDrag: !isBidirectional && widget.enableDrag, + ), viewportBuilder: widget.viewportBuilder, axisDirection: widget.axisDirection, physics: const ClampingScrollPhysics(), ); + + if (isBidirectional) { + return RawGestureDetector( + gestures: { + PanGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => PanGestureRecognizer( + supportedDevices: const { + PointerDeviceKind.touch, + PointerDeviceKind.stylus, + PointerDeviceKind.invertedStylus, + PointerDeviceKind.trackpad, + }, + ), + (PanGestureRecognizer instance) { + instance + ..onDown = _handlePanDown + ..onStart = _handlePanStart + ..onUpdate = _handlePanUpdate + ..onEnd = _handlePanEnd + ..onCancel = _handlePanCancel + ..gestureSettings = MediaQuery.maybeGestureSettingsOf(context); + }, + ), + }, + behavior: HitTestBehavior.opaque, + child: scrollable, + ); + } + + return scrollable; } } @@ -81,8 +250,13 @@ class _ScrollBehavior extends MaterialScrollBehavior { final _ScrollPhysics physics; final CodeScrollbarBuilder? scrollbarBuilder; + final bool enableDrag; - _ScrollBehavior(this.scrollbarBuilder) : physics = _ScrollPhysics(); + _ScrollBehavior(this.scrollbarBuilder, {this.enableDrag = true}) : physics = _ScrollPhysics(); + + @override + Set get dragDevices => + enableDrag ? super.dragDevices : const {}; @override Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) { diff --git a/packages/re_editor/lib/src/_code_selection.dart b/packages/re_editor/lib/src/_code_selection.dart index eadc934..4b6a4b2 100644 --- a/packages/re_editor/lib/src/_code_selection.dart +++ b/packages/re_editor/lib/src/_code_selection.dart @@ -85,7 +85,9 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete render?.stopAutoScroll(); if (!_isMultiTouch) { widget.selectionOverlayController.hideToolbar(); - widget.selectionOverlayController.hideHandle(); + if (widget.controller.selection.isCollapsed) { + widget.selectionOverlayController.hideHandle(); + } } }, onLongPressUp: () { diff --git a/pubspec.yaml b/pubspec.yaml index aacf94e..5b6cfa8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -48,6 +48,7 @@ flutter: assets: - assets/distros/ - assets/certs/ + - assets/gradle/ - assets/shims/x86_64/ - assets/shims/arm64-v8a/ - assets/icons/distros/ diff --git a/test/code_editor_menu_test.dart b/test/code_editor_menu_test.dart index 6929246..71742e6 100644 --- a/test/code_editor_menu_test.dart +++ b/test/code_editor_menu_test.dart @@ -558,5 +558,73 @@ void main() { controller.hide(buildCtx); await tester.pumpAndSettle(); }); + + testWidgets('选中文本后进行滚动,手柄层不应被销毁消失且在滚动停止后正常维持', (tester) async { + final codeController = CodeLineEditingController.fromText( + List.generate(50, (i) => 'Line $i: Content of the test line with some length').join('\n'), + ); + final scrollController = CodeScrollController(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 400, + height: 300, + child: CodeEditor( + controller: codeController, + scrollController: scrollController, + wordWrap: false, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 选中第 5 行文本 + codeController.selection = const CodeLineSelection( + baseIndex: 5, + baseOffset: 0, + extentIndex: 5, + extentOffset: 10, + ); + await tester.pumpAndSettle(); + + // 执行纵向滚动 + await tester.drag(find.byType(CodeEditor), const Offset(0, -60)); + await tester.pumpAndSettle(); + + // 选区依然存在 + expect(codeController.selection.isCollapsed, isFalse); + }); + + testWidgets('非折行模式(wordWrap: false)下控制器替换文本,渲染段落立即更新', (tester) async { + final codeController = CodeLineEditingController.fromText('initial_text'); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 400, + height: 300, + child: CodeEditor( + controller: codeController, + wordWrap: false, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 模拟小键盘输入:修改文本 + codeController.replaceSelection('appended'); + await tester.pumpAndSettle(); + + // 验证文字已在控制器中 + expect(codeController.text, contains('appended')); + // 验证未抛异常且稳定渲染 + expect(find.byType(CodeEditor), findsOneWidget); + }); }); } diff --git a/test/code_editor_paragraph_refresh_test.dart b/test/code_editor_paragraph_refresh_test.dart new file mode 100644 index 0000000..6800eb4 --- /dev/null +++ b/test/code_editor_paragraph_refresh_test.dart @@ -0,0 +1,115 @@ +// 回归测试:非折行模式(wordWrap == false)下,文本改动必须立即重排“显示段落”。 +// +// 背景:为缓解“双指缩放/横向滚动抖动”,`_CodeFieldRender._updateDisplayRenderParagraphs()` +// 里曾为非折行模式加过一个 startIndex 复用缓存分支:仅当 startIndex 变化或视口跑出已建段落 +// 范围时才 clear()+重建。于是“按键已生效(控制器内容变了、脏标记也正确)但屏幕仍绘制旧段落”, +// 表现为小键盘按键像失灵、文字不动却变脏。 +// 抖动真因(行高 StrutStyle forceStrutHeight 约束缺失)修复后,该缓存分支已删除,本文件守住行为。 +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:re_editor/re_editor.dart'; + +/// 从渲染树中取出真正用于绘制的显示段落(`_CodeFieldRender` 为库内私有类型,按类型名匹配) +List displayParagraphs(WidgetTester tester) { + final render = tester.allRenderObjects.firstWhere( + (object) => object.runtimeType.toString() == '_CodeFieldRender', + orElse: () => throw StateError('渲染树中找不到 _CodeFieldRender'), + ); + final dynamic field = render; + return (field.displayParagraphs as List).cast(); +} + +/// 取指定行号对应的显示段落 +CodeLineRenderParagraph paragraphOfLine(WidgetTester tester, int lineIndex) { + return displayParagraphs(tester).firstWhere( + (paragraph) => paragraph.index == lineIndex, + orElse: () => throw StateError('显示段落中找不到第 $lineIndex 行'), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('非折行模式下文本改动立即重排显示段落', () { + const firstLineText = 'Line 0: const value = 0;'; + + Future pumpEditor(WidgetTester tester) async { + // 文档行数足够填满视口:已建段落覆盖整个可视区,正是“复用缓存”生效的前提 + final text = List.generate(60, (i) => 'Line $i: const value = $i;').join('\n'); + final controller = CodeLineEditingController.fromText(text); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 300, + height: 300, + child: CodeEditor( + controller: controller, + wordWrap: false, + // paddingTop 必须为 0(应用侧同样是 fromLTRB(6,0,0,0)): + // paddingTop > 0 时 `target < _displayParagraphs.first.top` 恒成立, + // 会让缓存分支每次都重建,从而掩盖本缺陷。 + padding: EdgeInsets.zero, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 光标固定到首行行首,确保改动落在可见行上 + controller.selection = CodeLineSelection.collapsed(index: 0, offset: 0); + await tester.pumpAndSettle(); + return controller; + } + + testWidgets('小键盘输入单个字符 ";" 后显示段落立即刷新(不依赖滚动)', (tester) async { + final controller = await pumpEditor(tester); + + expect(paragraphOfLine(tester, 0).length, firstLineText.length); + + // 等价于小键盘 / 硬件键盘按键:只改控制器内容,屏幕不滚动 + controller.replaceSelection(';'); + await tester.pumpAndSettle(); + + final expectedLength = controller.text.split('\n').first.length; + expect(expectedLength, firstLineText.length + 1, reason: '按键必须真正写入控制器'); + expect( + paragraphOfLine(tester, 0).length, + expectedLength, + reason: '屏幕显示段落必须与控制器同步刷新', + ); + }); + + testWidgets('小键盘输入组合字符 "()" 后显示段落立即刷新', (tester) async { + final controller = await pumpEditor(tester); + + controller.replaceSelection('()'); + await tester.pumpAndSettle(); + + final expectedLength = controller.text.split('\n').first.length; + expect(expectedLength, firstLineText.length + 2); + expect(paragraphOfLine(tester, 0).length, expectedLength); + }); + + testWidgets('插入换行后显示段落立即拆分,后续行整体下移', (tester) async { + final controller = await pumpEditor(tester); + + expect(paragraphOfLine(tester, 0).length, firstLineText.length); + expect(paragraphOfLine(tester, 1).length, 'Line 1: const value = 1;'.length); + + controller.replaceSelection('\n'); + await tester.pumpAndSettle(); + + expect(controller.text.split('\n').length, 61); + // 原首行被拆成“空行 + 原内容”,屏幕段落必须同步反映 + expect(paragraphOfLine(tester, 0).length, 0, reason: '首段应变为空行'); + expect( + paragraphOfLine(tester, 1).length, + firstLineText.length, + reason: '原来的首行内容必须出现在第 2 段(屏幕未重排时会残留旧文本)', + ); + }); + }); +} diff --git a/test/distro_multi_system_test.dart b/test/distro_multi_system_test.dart index 6783a49..8c08405 100644 --- a/test/distro_multi_system_test.dart +++ b/test/distro_multi_system_test.dart @@ -86,6 +86,33 @@ void main() { 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')); diff --git a/test/drawer_import_files_test.dart b/test/drawer_import_files_test.dart new file mode 100644 index 0000000..b9daa6d --- /dev/null +++ b/test/drawer_import_files_test.dart @@ -0,0 +1,257 @@ +import 'dart:io'; +import 'dart:typed_data'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/project_history.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/internal_project_service.dart'; +import 'package:code_editor/widgets/code_editor_drawer.dart'; +import 'package:file_picker/file_picker.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'; + +class MockMultiFilePicker extends FilePicker { + List? pickedFiles; + + @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 (pickedFiles == null) return null; + return FilePickerResult(pickedFiles!); + } + + @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 Directory testProjectDir; + late ProjectProvider projectProvider; + late TabProvider tabProvider; + late SettingsProvider settingsProvider; + late RunProvider runProvider; + late MockMultiFilePicker mockFilePicker; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + tempBaseDir = Directory.systemTemp.createTempSync('drawer_import_test_'); + testProjectDir = Directory(p.join(tempBaseDir.path, 'my_project'))..createSync(); + + InternalProjectService.instance.customProjectsDir = + Directory(p.join(tempBaseDir.path, 'files', 'projects')); + + projectProvider = ProjectProvider(); + tabProvider = TabProvider()..bindProjectProvider(projectProvider); + settingsProvider = SettingsProvider(); + runProvider = RunProvider(); + + mockFilePicker = MockMultiFilePicker(); + FilePicker.platform = mockFilePicker; + + // Switch to active project + await projectProvider.switchProject( + ProjectHistory( + rootPath: testProjectDir.path, + lastOpenedFilePath: null, + ), + ); + }); + + tearDown(() { + InternalProjectService.instance.customProjectsDir = null; + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + }); + + Widget buildTestWidget({ + Locale locale = const Locale('zh'), + }) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: runProvider), + ], + child: MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [ + Locale('zh'), + Locale('en'), + ], + locale: locale, + home: const Scaffold( + drawer: CodeEditorDrawer(), + body: Center(child: Text('Editor Body')), + ), + ), + ); + } + + testWidgets('Import button is present to the right of new file and new folder buttons with correct tooltip', (tester) async { + await tester.pumpWidget(buildTestWidget(locale: const Locale('zh'))); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Verify buttons in the subtitle row + expect(find.byIcon(Icons.note_add_outlined), findsOneWidget); + expect(find.byIcon(Icons.create_new_folder_outlined), findsOneWidget); + expect(find.byIcon(Icons.file_upload_outlined), findsOneWidget); + expect(find.byTooltip('从外部导入'), findsOneWidget); + + // Verify ordering: note_add_outlined < create_new_folder_outlined < file_upload_outlined + final noteAddOffset = tester.getTopLeft(find.byIcon(Icons.note_add_outlined)); + final folderOffset = tester.getTopLeft(find.byIcon(Icons.create_new_folder_outlined)); + final importOffset = tester.getTopLeft(find.byIcon(Icons.file_upload_outlined)); + + expect(noteAddOffset.dx, lessThan(folderOffset.dx)); + expect(folderOffset.dx, lessThan(importOffset.dx)); + }); + + testWidgets('Import button shows English tooltip when locale is en', (tester) async { + await tester.pumpWidget(buildTestWidget(locale: const Locale('en'))); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + expect(find.byTooltip('Import from External'), findsOneWidget); + }); + + testWidgets('Tapping import button imports multiple external files into project root', (tester) async { + final file1 = File(p.join(tempBaseDir.path, 'source1.txt'))..writeAsStringSync('hello world'); + final file2 = File(p.join(tempBaseDir.path, 'source2.dart'))..writeAsStringSync('void main() {}'); + + mockFilePicker.pickedFiles = [ + PlatformFile(name: 'source1.txt', size: 11, path: file1.path), + PlatformFile(name: 'source2.dart', size: 16, path: file2.path), + ]; + + await tester.pumpWidget(buildTestWidget(locale: const Locale('zh'))); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + final imported1 = File(p.join(testProjectDir.path, 'source1.txt')); + final imported2 = File(p.join(testProjectDir.path, 'source2.dart')); + + await tester.runAsync(() async { + await tester.tap(find.byIcon(Icons.file_upload_outlined)); + for (var i = 0; i < 50; i++) { + await Future.delayed(const Duration(milliseconds: 50)); + if (imported1.existsSync() && imported2.existsSync()) break; + } + }); + await tester.pumpAndSettle(); + + // Verify files were copied into testProjectDir + expect(imported1.existsSync(), isTrue); + expect(imported1.readAsStringSync(), equals('hello world')); + + expect(imported2.existsSync(), isTrue); + expect(imported2.readAsStringSync(), equals('void main() {}')); + + // Verify success toast + expect(find.text('成功导入 2 个文件'), findsOneWidget); + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('Importing file with duplicate name automatically generates unique filename', (tester) async { + // Existing file in root + File(p.join(testProjectDir.path, 'duplicate.txt')).writeAsStringSync('existing original'); + + // External file to import + final extFile = File(p.join(tempBaseDir.path, 'duplicate.txt'))..writeAsStringSync('imported copy'); + + mockFilePicker.pickedFiles = [ + PlatformFile(name: 'duplicate.txt', size: 13, path: extFile.path), + ]; + + await tester.pumpWidget(buildTestWidget(locale: const Locale('zh'))); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + final uniqueFile = File(p.join(testProjectDir.path, 'duplicate(1).txt')); + + await tester.runAsync(() async { + await tester.tap(find.byIcon(Icons.file_upload_outlined)); + for (var i = 0; i < 50; i++) { + await Future.delayed(const Duration(milliseconds: 50)); + if (uniqueFile.existsSync()) break; + } + }); + await tester.pumpAndSettle(); + + // Original file remains unchanged + expect(File(p.join(testProjectDir.path, 'duplicate.txt')).readAsStringSync(), equals('existing original')); + + // New unique file is created + expect(uniqueFile.existsSync(), isTrue); + expect(uniqueFile.readAsStringSync(), equals('imported copy')); + + // Wait for toast to dismiss + await tester.pump(const Duration(seconds: 3)); + }); + + test('ProjectProvider.importFiles supports bytes fallback when path is null', () async { + final bytes = Uint8List.fromList([65, 66, 67]); + final file = PlatformFile( + name: 'bytes_file.txt', + size: 3, + bytes: bytes, + ); + + final count = await projectProvider.importFiles(testProjectDir.path, [file]); + expect(count, equals(1)); + + final imported = File(p.join(testProjectDir.path, 'bytes_file.txt')); + expect(imported.existsSync(), isTrue); + expect(imported.readAsStringSync(), equals('ABC')); + }); +} diff --git a/test/gradle_ide_model_test.dart b/test/gradle_ide_model_test.dart new file mode 100644 index 0000000..b72ed99 --- /dev/null +++ b/test/gradle_ide_model_test.dart @@ -0,0 +1,144 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/services/project_modules/gradle_ide_model.dart'; + +/// 结构化探测模型测试:取代旧的"文本正则解析"测试。 +/// 这些用例断言的是"按字段读取 JSON 模型",与 Gradle 输出措辞/语言/版本无关。 +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + Map singleProjectModel() => { + 'schema': 1, + 'gradleVersion': '8.14', + 'rootProject': 'demo', + 'projects': [ + { + 'path': ':', + 'name': 'demo', + 'buildFile': '/workspace/build.gradle', + 'plugins': ['org.gradle.api.plugins.JavaPlugin'], + 'sourceSets': ['main', 'test'], + 'configurations': ['compileClasspath', 'runtimeClasspath'], + 'javaVersion': '17', + 'tasks': [ + { + 'name': 'build', + 'path': ':build', + 'group': 'build', + 'description': 'Assembles and tests this project.', + 'type': 'org.gradle.api.DefaultTask', + }, + { + 'name': 'test', + 'path': ':test', + 'group': 'verification', + 'description': null, + 'type': 'org.gradle.api.tasks.testing.Test', + }, + { + 'name': 'tasks', + 'path': ':tasks', + 'group': 'help', + 'description': 'Displays the tasks runnable from root project.', + 'type': 'org.gradle.api.DefaultTask', + }, + ], + }, + ], + }; + + group('GradleIdeModel 结构化解析', () { + test('单模块:任务字段、分组归一、id/命令生成与原命名习惯一致', () { + final model = GradleIdeModel.fromJson(singleProjectModel()); + expect(model.schema, GradleIdeModel.schemaVersion); + expect(model.gradleVersion, '8.14'); + expect(model.projects, hasLength(1)); + expect(model.projects.first.sourceSets, ['main', 'test']); + expect(model.projects.first.javaVersion, '17'); + + final tasks = model.toRunTasks('sh ./gradlew'); + expect(tasks, hasLength(3)); + + final build = tasks.firstWhere((t) => t.name == 'build'); + expect(build.id, 'gradle_build'); + expect(build.command, 'sh ./gradlew build'); + expect(build.group, 'build'); + expect(build.description, 'Assembles and tests this project.'); + + // 分组排序:application > build > android > verification > help + expect(tasks.map((t) => t.name).toList(), ['build', 'test', 'tasks']); + expect(tasks.firstWhere((t) => t.name == 'test').group, 'verification'); + }); + + test('多模块:子项目任务使用 :path 作为名称与命令(保持既有 id 习惯)', () { + final model = GradleIdeModel.fromJson({ + 'schema': 1, + 'rootProject': 'demo', + 'projects': [ + { + 'path': ':', + 'name': 'demo', + 'tasks': [ + {'name': 'build', 'path': ':build', 'group': 'build'}, + ], + }, + { + 'path': ':app', + 'name': 'app', + 'tasks': [ + {'name': 'assembleDebug', 'path': ':app:assembleDebug', 'group': 'build'}, + ], + }, + { + 'path': ':core', + 'name': 'core', + 'tasks': [ + {'name': 'compileJava', 'path': ':core:compileJava', 'group': 'build'}, + ], + }, + ], + }); + + final tasks = model.toRunTasks('gradle'); + final appTask = tasks.firstWhere((t) => t.name == ':app:assembleDebug'); + expect(appTask.command, 'gradle :app:assembleDebug'); + expect(appTask.id, 'gradle__app_assembleDebug'); + expect(appTask.moduleId, 'gradle'); + expect(tasks.firstWhere((t) => t.name == ':core:compileJava').id, 'gradle__core_compileJava'); + }); + + test('空任务 / 缺字段 / 重复任务路径都能安全处理', () { + final empty = GradleIdeModel.fromJson({'schema': 1, 'rootProject': 'demo', 'projects': []}); + expect(empty.toRunTasks('gradle'), isEmpty); + + final missing = GradleIdeModel.fromJson({'schema': 1}); + expect(missing.projects, isEmpty); + + final duplicated = GradleIdeModel.fromJson({ + 'schema': 1, + 'rootProject': 'demo', + 'projects': [ + { + 'path': ':', + 'name': 'demo', + 'tasks': [ + {'name': 'build', 'path': ':build'}, + {'name': 'build', 'path': ':build'}, + ], + }, + ], + }); + expect(duplicated.toRunTasks('gradle'), hasLength(1)); + }); + + test('schema 不匹配或内部错误时抛出 FormatException(上层归类为不可解析/执行失败)', () { + expect( + () => GradleIdeModel.fromJson({'schema': 0, 'error': 'Gradle 配置阶段抛错'}), + throwsA(isA()), + ); + expect( + () => GradleIdeModel.fromJson({'schema': 99}), + throwsA(isA()), + ); + }); + }); +} diff --git a/test/gradle_project_module_test.dart b/test/gradle_project_module_test.dart index c1da3ea..497495c 100644 --- a/test/gradle_project_module_test.dart +++ b/test/gradle_project_module_test.dart @@ -1,209 +1,76 @@ import 'dart:io'; + import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/models/run_task_type.dart'; import 'package:code_editor/providers/run_provider.dart'; -import 'package:code_editor/services/project_modules/gradle_project_module.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/project_modules/project_module.dart'; +import 'package:code_editor/services/project_modules/project_probe.dart'; import 'package:code_editor/services/project_task_dispatcher.dart'; -import 'package:code_editor/services/run_task_storage_service.dart'; + +/// 单测用假系统名:探测必须基于"真实可用系统",单测用假 rootfs 代替真容器 +const String kTestSystemName = 'test_sys'; + +/// 固定返回一组任务的假模块(用于验证类型表写入 / RunProvider 集成) +class _StubGradleModule extends ProjectModule { + @override + String get id => 'gradle'; + + @override + String get displayName => 'Gradle'; + + @override + List get triggerFiles => const ['build.gradle']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'build.gradle')).existsSync(); + + @override + Future probe(ProjectProbe probe) async => ModuleProbeResult.ok(id, [ + const RunTask( + id: 'gradle_assemble', + name: 'assemble', + command: 'sh ./gradlew assemble', + source: TaskSource.detected, + moduleId: 'gradle', + group: 'build', + ), + ]); +} void main() { TestWidgetsFlutterBinding.ensureInitialized(); - group('GradleProjectModule Parser Tests', () { - test('parseGradleTasksOutput parses single project tasks, groups, and descriptions', () { - const output = ''' ------------------------------------------------------------- -Tasks runnable from root project 'my-app' ------------------------------------------------------------- - -Application tasks ------------------ -run - Runs this project as a JVM application - -Build tasks ------------ -assemble - Assembles the outputs of this project. -build - Assembles and tests this project. -clean - Deletes the build directory. - -Verification tasks ------------------- -check - Runs all checks. -test - Runs the test suite. - -Other tasks ------------ -customTask - Executes a custom task -'''; - - final tasks = GradleProjectModule.parseGradleTasksOutput(output, 'sh ./gradlew'); - expect(tasks, isNotEmpty); - - // 验证任务名称与命令 - final runTask = tasks.firstWhere((t) => t.name == 'run'); - expect(runTask.command, 'sh ./gradlew run'); - expect(runTask.group, 'application'); - expect(runTask.moduleId, 'gradle'); - expect(runTask.source, TaskSource.detected); - expect(runTask.description, 'Runs this project as a JVM application'); - - final assembleTask = tasks.firstWhere((t) => t.name == 'assemble'); - expect(assembleTask.command, 'sh ./gradlew assemble'); - expect(assembleTask.group, 'build'); - expect(assembleTask.moduleId, 'gradle'); - - final buildTask = tasks.firstWhere((t) => t.name == 'build'); - expect(buildTask.command, 'sh ./gradlew build'); - expect(buildTask.group, 'build'); - - final testTask = tasks.firstWhere((t) => t.name == 'test'); - expect(testTask.command, 'sh ./gradlew test'); - expect(testTask.group, 'verification'); - - final customTask = tasks.firstWhere((t) => t.name == 'customTask'); - expect(customTask.command, 'sh ./gradlew customTask'); - expect(customTask.group, 'other'); - expect(customTask.description, 'Executes a custom task'); - - // 优先级排序验证:application -> build -> verification -> other - final groupsInOrder = tasks.map((t) => t.group).toList(); - final appIdx = groupsInOrder.indexOf('application'); - final buildIdx = groupsInOrder.indexOf('build'); - final verifIdx = groupsInOrder.indexOf('verification'); - final otherIdx = groupsInOrder.indexOf('other'); - - expect(appIdx, lessThan(buildIdx)); - expect(buildIdx, lessThan(verifIdx)); - expect(verifIdx, lessThan(otherIdx)); - }); - - test('parseGradleTasksOutput parses multi-module projects with prefixes (:app:xxx)', () { - const output = ''' ------------------------------------------------------------- -Tasks runnable from project ':app' ------------------------------------------------------------- - -Build tasks ------------ -assembleDebug - Assembles all Debug builds. -assembleRelease - Assembles all Release builds. - -Tasks runnable from project ':core' ------------------------------------------------------------- - -Build tasks ------------ -compileJava - Compiles Java sources. -'''; - - final tasks = GradleProjectModule.parseGradleTasksOutput(output, 'sh ./gradlew'); - expect(tasks.length, 3); - - final assembleDebugTask = tasks.firstWhere((t) => t.name == ':app:assembleDebug'); - expect(assembleDebugTask.command, 'sh ./gradlew :app:assembleDebug'); - expect(assembleDebugTask.id, 'gradle__app_assembleDebug'); - expect(assembleDebugTask.group, 'build'); - expect(assembleDebugTask.moduleId, 'gradle'); - - final compileJavaTask = tasks.firstWhere((t) => t.name == ':core:compileJava'); - expect(compileJavaTask.command, 'sh ./gradlew :core:compileJava'); - expect(compileJavaTask.id, 'gradle__core_compileJava'); - }); - }); - - group('Gradle Module Cache & Storage Tests', () { - late Directory tempDir; - late RunTaskStorageService storageService; - - setUp(() async { - tempDir = await Directory.systemTemp.createTemp('gradle_module_test_'); - storageService = RunTaskStorageService(); - }); - - tearDown(() async { - if (await tempDir.exists()) { - await tempDir.delete(recursive: true); - } - }); - - test('saveModuleTasks writes to .code_editor/gradle_tasks.json and loadModuleTasks reads it back', () async { - final initial = await storageService.loadModuleTasks(tempDir.path, 'gradle'); - expect(initial.tasks, isEmpty); - expect(initial.hash, isNull); - - const tasksToSave = [ - RunTask( - id: 'gradle_assembleDebug', - name: 'assembleDebug', - command: 'sh ./gradlew assembleDebug', - source: TaskSource.detected, - group: 'build', - moduleId: 'gradle', - description: 'Build debug package', - ), - RunTask( - id: 'gradle_run', - name: 'run', - command: 'sh ./gradlew run', - source: TaskSource.detected, - group: 'application', - moduleId: 'gradle', - description: 'Run project', - ), - ]; - - await storageService.saveModuleTasks( - projectRoot: tempDir.path, - moduleName: 'gradle', - tasks: tasksToSave, - hash: 'test_hash_12345', - ); - - // 验证独立持久化文件存在:.code_editor/gradle_tasks.json - final cacheFile = File('${tempDir.path}/.code_editor/gradle_tasks.json'); - expect(cacheFile.existsSync(), isTrue); - - // 读取并校验 - final loaded = await storageService.loadModuleTasks(tempDir.path, 'gradle'); - expect(loaded.hash, 'test_hash_12345'); - expect(loaded.tasks.length, 2); - expect(loaded.tasks.first.name, 'assembleDebug'); - expect(loaded.tasks.first.group, 'build'); - expect(loaded.tasks.first.moduleId, 'gradle'); - expect(loaded.tasks.last.name, 'run'); - - // 验证 run_tasks.json(用户任务)完全不受影响且相互隔离 - final userConfig = await storageService.loadConfig(tempDir.path); - expect(userConfig.tasks, isEmpty); - }); - - test('computeBuildScriptHash changes when build.gradle is modified', () async { - final buildGradle = File('${tempDir.path}/build.gradle'); - await buildGradle.writeAsString('plugins { id "java" }\n'); - - final hash1 = GradleProjectModule.computeBuildScriptHash(tempDir); - expect(hash1.isNotEmpty, isTrue); - - // 稍微休眠并修改内容 - await Future.delayed(const Duration(milliseconds: 50)); - await buildGradle.writeAsString('plugins { id "application" }\n'); - - final hash2 = GradleProjectModule.computeBuildScriptHash(tempDir); - expect(hash2, isNot(equals(hash1))); - }); - }); - group('ProjectTaskDispatcher & RunProvider Modular Tests', () { late Directory tempDir; + late Directory distroBaseDir; + late DistroManager distroManager; setUp(() async { tempDir = await Directory.systemTemp.createTemp('dispatcher_test_'); + + // 假系统:rootfs/{etc,bin,usr/bin/java}(依赖检测走宿主 rootfs 快速判定) + distroBaseDir = await Directory.systemTemp.createTemp('dispatcher_distro_'); + final rootfs = Directory(p.join(distroBaseDir.path, kTestSystemName, 'rootfs')); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + final usrBin = Directory(p.join(rootfs.path, 'usr', 'bin'))..createSync(recursive: true); + File(p.join(usrBin.path, 'java')).writeAsStringSync('#!/bin/sh\n'); + distroManager = DistroManager()..customBaseDir = distroBaseDir; }); tearDown(() async { + DistroManager().customBaseDir = null; if (await tempDir.exists()) { await tempDir.delete(recursive: true); } + if (await distroBaseDir.exists()) { + await distroBaseDir.delete(recursive: true); + } }); test('ProjectTaskDispatcher activates modules correctly', () async { @@ -226,80 +93,66 @@ compileJava - Compiles Java sources. expect(active2.any((m) => m.id == 'gradle'), isTrue); }); - test('GradleProjectModule returns cached tasks when hash matches without executing command', () async { - final buildGradle = File('${tempDir.path}/build.gradle'); - await buildGradle.writeAsString('plugins { id "java" }\n'); + test('未安装指定系统时既不探测,也绝不创建任何系统目录', () async { + final emptyBase = await Directory.systemTemp.createTemp('dispatcher_no_sys_'); + addTearDown(() async { + if (await emptyBase.exists()) await emptyBase.delete(recursive: true); + }); + DistroManager().customBaseDir = emptyBase; - final storageService = RunTaskStorageService(); - final currentHash = GradleProjectModule.computeBuildScriptHash(tempDir); + await File('${tempDir.path}/build.gradle').writeAsString('plugins { id "java" }\n'); - const cachedTasks = [ - RunTask( - id: 'gradle_cached_task', - name: 'cachedTask', - command: 'sh ./gradlew cachedTask', - source: TaskSource.detected, - group: 'build', - moduleId: 'gradle', - ), - ]; - - await storageService.saveModuleTasks( + final tasks = await ProjectTaskDispatcher().detect( projectRoot: tempDir.path, - moduleName: 'gradle', - tasks: cachedTasks, - hash: currentHash, + systemName: 'ubuntu', + distroManager: DistroManager(), ); - final dispatcher = ProjectTaskDispatcher(); - final tasks = await dispatcher.detect( - projectRoot: tempDir.path, - storageService: storageService, - ); - - expect(tasks.any((t) => t.id == 'gradle_cached_task'), isTrue); - expect(tasks.firstWhere((t) => t.id == 'gradle_cached_task').name, 'cachedTask'); + expect(tasks, isEmpty); + // 绝不能凭空造出 distros/ubuntu(历史缺陷会在这里 recursive 创建 rootfs/etc) + expect(Directory(p.join(emptyBase.path, 'ubuntu')).existsSync(), isFalse); }); - test('RunProvider integrates with modular task system and maintains customTasks', () async { - final storageService = RunTaskStorageService(); - final runProvider = RunProvider(storageService: storageService); - - // 准备工程与一个已缓存的 Gradle 任务 + test('未传入系统名时不做任何探测(连纯静态模块任务也不产出)', () async { + await File('${tempDir.path}/Makefile').writeAsString('all:\n\tgcc main.c\n'); await File('${tempDir.path}/build.gradle').writeAsString('plugins { id "java" }\n'); - final currentHash = GradleProjectModule.computeBuildScriptHash(tempDir); - const initialGradleTask = RunTask( - id: 'gradle_assemble', - name: 'assemble', - command: 'sh ./gradlew assemble', - source: TaskSource.detected, - group: 'build', - moduleId: 'gradle', - ); - await storageService.saveModuleTasks( + + final tasks = await ProjectTaskDispatcher().detect( projectRoot: tempDir.path, - moduleName: 'gradle', - tasks: [initialGradleTask], - hash: currentHash, + distroManager: distroManager, ); - // 打开工程 - await runProvider.onProjectOpened(tempDir.path); + expect(tasks, isEmpty); + }); + + test('真实自省失败时返回空结果:不产出任何兜底任务', () async { + await File('${tempDir.path}/build.gradle').writeAsString('plugins { id "java" }\n'); + + final tasks = await ProjectTaskDispatcher().detect( + projectRoot: tempDir.path, + systemName: kTestSystemName, + distroManager: distroManager, + ); + + // 测试环境无法真正执行 gradle -> 该模块失败且不产出任务(也绝无 detected_gradle_* 兜底) + expect(tasks.where((t) => t.moduleId == 'gradle'), isEmpty); + expect(tasks.any((t) => t.id.startsWith('detected_gradle_')), isFalse); + }); + + test('RunProvider 集成:模块结果写入"类型 → 任务数组"的对应格子', () async { + await File('${tempDir.path}/build.gradle').writeAsString('plugins { id "java" }\n'); + + final dispatcher = ProjectTaskDispatcher(customModules: [_StubGradleModule()]); + final runProvider = RunProvider( + dispatcher: dispatcher, + distroManager: distroManager, + ); + + await runProvider.onProjectOpened(tempDir.path, systemName: kTestSystemName); + + expect(runProvider.taskTable.tasksOf(RunTaskType.gradle).map((t) => t.id), ['gradle_assemble']); expect(runProvider.detectedTasks.any((t) => t.id == 'gradle_assemble'), isTrue); - - // 添加用户自定义任务 - const customTask = RunTask( - id: 'user_custom_1', - name: 'My Custom Run', - command: 'echo "custom"', - source: TaskSource.custom, - ); - await runProvider.addCustomTask(customTask); - - expect(runProvider.customTasks.length, 1); - // allTasks 自定义置顶 - expect(runProvider.allTasks.first.id, 'user_custom_1'); - expect(runProvider.allTasks.any((t) => t.id == 'gradle_assemble'), isTrue); + expect(runProvider.taskTable.tasksOf(RunTaskType.user), isEmpty); }); }); } diff --git a/test/notice_center_test.dart b/test/notice_center_test.dart new file mode 100644 index 0000000..f955b0f --- /dev/null +++ b/test/notice_center_test.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/models/notice_item.dart'; +import 'package:code_editor/providers/notice_center.dart'; + +void main() { + NoticeItem progress(String id, {String module = 'Gradle'}) => NoticeItem( + id: id, + kind: NoticeKind.progress, + text: ModulePhaseText(moduleDisplayName: module, phase: ProbeNoticePhase.detecting), + ); + + group('NoticeCenter 通知队列', () { + test('可视槽位未满时直接展示,超限后进入队列', () { + final center = NoticeCenter(visibleLimit: 2); + center.push(progress('probe:gradle')); + center.push(progress('probe:npm')); + expect(center.visible.map((e) => e.id).toList(), ['probe:npm', 'probe:gradle']); + expect(center.queued, isEmpty); + + center.push(progress('probe:make')); + expect(center.visible, hasLength(2)); + expect(center.queued.map((e) => e.id).toList(), ['probe:make']); + }); + + test('关闭一条后,队列首条自动补位(弹窗关闭自动弹出)', () { + final center = NoticeCenter(visibleLimit: 1); + center.push(progress('probe:gradle')); + center.push(progress('probe:npm')); + + // 先进入"正在移除"(UI 播退场动画),真正移除前队列不补位 + center.dismiss('probe:gradle'); + expect(center.removingIds, contains('probe:gradle')); + expect(center.visible, hasLength(1)); + expect(center.queued, hasLength(1)); + + // 动画结束回调 -> 移除 + 补位 + center.finalizeDismiss('probe:gradle'); + expect(center.visible.map((e) => e.id).toList(), ['probe:npm']); + expect(center.queued, isEmpty); + expect(center.removingIds, isEmpty); + }); + + test('队列中的条目被关闭时直接移除并立即补位', () { + final center = NoticeCenter(visibleLimit: 1); + center.push(progress('probe:gradle')); + center.push(progress('probe:npm')); + center.dismiss('probe:npm'); + expect(center.queued, isEmpty); + expect(center.visible.map((e) => e.id).toList(), ['probe:gradle']); + }); + + test('update 就地更新文案但不改变位置', () { + final center = NoticeCenter(visibleLimit: 3); + center.push(progress('probe:gradle')); + center.push(progress('probe:npm')); + center.update( + 'probe:gradle', + text: const ModulePhaseText( + moduleDisplayName: 'Gradle', + phase: ProbeNoticePhase.checkingDependency, + ), + ); + expect(center.visible.map((e) => e.id).toList(), ['probe:npm', 'probe:gradle']); + final gradle = center.visible.last; + expect((gradle.text as ModulePhaseText).phase, ProbeNoticePhase.checkingDependency); + }); + + testWidgets('complete 带 autoCloseAfter 时延时自动关闭;sticky 则保留', (tester) async { + await tester.pumpWidget(const SizedBox()); + final center = NoticeCenter(visibleLimit: 3); + center.push(progress('probe:gradle')); + center.push(progress('probe:npm')); + + // 成功:1 秒后自动进入移除流程 + center.complete('probe:gradle', kind: NoticeKind.success, autoCloseAfter: const Duration(seconds: 1)); + await tester.pump(const Duration(milliseconds: 900)); + expect(center.removingIds, isEmpty); + await tester.pump(const Duration(milliseconds: 200)); + expect(center.removingIds, contains('probe:gradle')); + + // 失败:sticky 不自动关闭 + center.complete( + 'probe:npm', + kind: NoticeKind.failure, + text: const ModuleFailureText( + moduleDisplayName: 'NPM', + failure: NoticeFailure.toolchainMissing, + detail: 'npm', + ), + sticky: true, + ); + await tester.pump(const Duration(seconds: 30)); + expect(center.removingIds, isNot(contains('probe:npm'))); + expect(center.visible.map((e) => e.id), contains('probe:npm')); + }); + + testWidgets('dismissAll 清空可见与队列,并取消所有自动关闭定时器', (tester) async { + await tester.pumpWidget(const SizedBox()); + final center = NoticeCenter(visibleLimit: 1); + center.push(progress('probe:gradle')); + center.complete('probe:gradle', kind: NoticeKind.success, autoCloseAfter: const Duration(seconds: 5)); + center.push(progress('probe:npm')); + center.dismissAll(); + expect(center.isEmpty, isTrue); + // 定时器已取消:不会在之后触发任何状态变化 + await tester.pump(const Duration(seconds: 10)); + expect(center.isEmpty, isTrue); + }); + }); +} diff --git a/test/notice_host_test.dart b/test/notice_host_test.dart new file mode 100644 index 0000000..1fcf3fa --- /dev/null +++ b/test/notice_host_test.dart @@ -0,0 +1,189 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/notice_item.dart'; +import 'package:code_editor/providers/notice_center.dart'; +import 'package:code_editor/widgets/notice_host.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + Widget buildHost(NoticeCenter center, {Locale locale = const Locale('zh')}) { + return MaterialApp( + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 400, + height: 400, + child: Stack( + children: [ + Positioned.fill(child: NoticeHost(center: center)), + ], + ), + ), + ), + ); + } + + /// 推进动画:注意"进行中"通知里的 CircularProgressIndicator 是无限动画, + /// 因此这里必须用显式 pump(duration),不能用 pumpAndSettle。 + Future advance(WidgetTester tester, [int ms = 400]) async { + await tester.pump(); + await tester.pump(Duration(milliseconds: ms)); + } + + NoticeItem phaseNotice( + String id, { + String module = 'Gradle', + ProbeNoticePhase phase = ProbeNoticePhase.detecting, + }) => + NoticeItem( + id: id, + kind: NoticeKind.progress, + text: ModulePhaseText(moduleDisplayName: module, phase: phase), + ); + + group('NoticeHost 通知堆叠宿主', () { + testWidgets('空队列时不渲染任何内容', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + expect(find.textContaining('Gradle'), findsNothing); + }); + + testWidgets('可同时插入多条通知,文案来自 l10n(中文)', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + + center.push(phaseNotice('probe:gradle', module: 'Gradle')); + center.push(phaseNotice('probe:npm', module: 'NPM')); + await advance(tester); + + expect(find.text('正在探测 Gradle 任务…'), findsOneWidget); + expect(find.text('正在探测 NPM 任务…'), findsOneWidget); + }); + + testWidgets('英文环境下同一模型渲染为英文文案(零硬编码)', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center, locale: const Locale('en'))); + await tester.pumpAndSettle(); + + center.push(phaseNotice('probe:gradle', module: 'Gradle')); + await advance(tester); + expect(find.text('Detecting Gradle tasks…'), findsOneWidget); + expect(find.text('正在探测 Gradle 任务…'), findsNothing); + }); + + testWidgets('插入动画:可见透明度在动画中途介于 0~1', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + + center.push(phaseNotice('probe:gradle')); + await tester.pump(); // 动画起点 + await tester.pump(const Duration(milliseconds: 90)); // 动画中途 + + final midwayOpacity = tester + .widgetList(find.byType(FadeTransition)) + .map((w) => w.opacity.value) + .toList(); + expect(midwayOpacity.any((v) => v > 0 && v < 1), isTrue, + reason: '插入过程中应能观测到透明度介于 0~1 的中间态'); + + await tester.pump(const Duration(milliseconds: 400)); + final settledOpacity = tester + .widgetList(find.byType(FadeTransition)) + .map((w) => w.opacity.value) + .toList(); + expect(settledOpacity.every((v) => v == 1.0), isTrue); + }); + + testWidgets('点击关闭按钮:退场动画后条目消失', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + + center.push(phaseNotice('probe:gradle')); + await advance(tester); + expect(find.text('正在探测 Gradle 任务…'), findsOneWidget); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 60)); // 退场动画中 + expect(center.removingIds, contains('probe:gradle')); + + await tester.pump(const Duration(milliseconds: 400)); // 退场动画结束 + expect(find.text('正在探测 Gradle 任务…'), findsNothing); + expect(center.visible, isEmpty); + }); + + testWidgets('超过可视上限的通知进入队列,关闭一条后自动补位弹出', (tester) async { + final center = NoticeCenter(visibleLimit: 2); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + + center.push(phaseNotice('probe:gradle', module: 'Gradle')); + center.push(phaseNotice('probe:npm', module: 'NPM')); + center.push(phaseNotice('probe:make', module: 'Makefile')); + await advance(tester); + + expect(find.text('正在探测 Makefile 任务…'), findsNothing); + expect(find.text('还有 1 项进行中'), findsOneWidget); + + // 关闭一条 -> 队列首条自动弹出 + center.dismiss('probe:npm'); + await advance(tester, 600); + expect(find.text('正在探测 Makefile 任务…'), findsOneWidget); + expect(find.text('还有 1 项进行中'), findsNothing); + }); + + testWidgets('失败通知显示模块标题 + 结构化原因(toolchainMissing)', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + + center.push(NoticeItem( + id: 'probe:gradle', + kind: NoticeKind.failure, + text: const ModuleFailureText( + moduleDisplayName: 'Gradle', + failure: NoticeFailure.toolchainMissing, + detail: 'gradle', + ), + sticky: true, + )); + await tester.pumpAndSettle(); + + expect(find.text('Gradle 任务探测失败'), findsOneWidget); + expect(find.text('当前系统内未找到 gradle,请先在系统管理中安装'), findsOneWidget); + }); + + testWidgets('完成通知自动关闭后完全消失', (tester) async { + final center = NoticeCenter(); + await tester.pumpWidget(buildHost(center)); + await tester.pumpAndSettle(); + + center.push(phaseNotice('probe:gradle')); + await advance(tester); + + // 成功 -> 转为"已完成"静态卡片,并在 autoCloseAfter 后自动关闭 + center.complete( + 'probe:gradle', + kind: NoticeKind.success, + text: const ModuleDoneText('Gradle', taskCount: 3), + autoCloseAfter: const Duration(milliseconds: 200), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(find.text('Gradle 探测完成 · 发现 3 个任务'), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text('Gradle 探测完成 · 发现 3 个任务'), findsNothing); + expect(center.visible, isEmpty); + }); + }); +} diff --git a/test/probe_boundary_test.dart b/test/probe_boundary_test.dart new file mode 100644 index 0000000..c966498 --- /dev/null +++ b/test/probe_boundary_test.dart @@ -0,0 +1,721 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/notice_item.dart'; +import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/models/run_task_type.dart'; +import 'package:code_editor/providers/notice_center.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/project_modules/project_module.dart'; +import 'package:code_editor/services/project_modules/project_probe.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; +import 'package:code_editor/services/run_task_storage_service.dart'; +import 'package:code_editor/widgets/notice_host.dart'; + +import 'package:flutter/material.dart'; + +/// 可控制时长的模块:用于制造"探测进行中"与"迟到的结果" +class _ControllableModule extends ProjectModule { + @override + final String id; + @override + final String displayName; + final List tasks; + final Duration delay; + + _ControllableModule(this.id, this.tasks, {String? displayName, this.delay = Duration.zero}) + : displayName = displayName ?? id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future probe(ProjectProbe probe) async { + if (delay > Duration.zero) { + await Future.delayed(delay); + } + // 迟到的结果:模拟探测期间被取消 + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + return ModuleProbeResult.ok(id, tasks); + } +} + +/// 用闸门控制返回时机的模块(key = 工程目录路径),用于制造"迟到的探测结果" +class _GatedModule extends ProjectModule { + @override + final String id; + + _GatedModule(this.id); + + final Map> _gates = {}; + + Completer gateFor(String projectDirPath) => + _gates.putIfAbsent(projectDirPath, () => Completer()); + + @override + String get displayName => id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future probe(ProjectProbe probe) async { + final gate = _gates[probe.projectDir.path]; + if (gate != null && !gate.isCompleted) { + await gate.future; + } + // 故意不检查 isCancelled:由 RunProvider 的结果守卫负责丢弃迟到结果 + return ModuleProbeResult.ok(id, [ + RunTask( + id: 'gradle_from_${p.basename(probe.projectDir.path)}', + name: 'assemble', + command: 'sh ./gradlew assemble', + source: TaskSource.detected, + moduleId: id, + ), + ]); + } +} + +/// 可注入耗时与依赖状态的模块:用于验证时间预算检查点 +class _BudgetModule extends ProjectModule { + @override + final String id; + final List log; + final Duration probeDelay; + final Duration depsDelay; + final List missingDependencies; + + _BudgetModule( + this.id, { + required this.log, + this.probeDelay = Duration.zero, + this.depsDelay = Duration.zero, + this.missingDependencies = const [], + }); + + @override + String get displayName => id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future> checkDependencies(ProjectProbe probe) async { + if (depsDelay > Duration.zero) { + await Future.delayed(depsDelay); + } + return missingDependencies; + } + + @override + Future installDependencies(ProjectProbe probe, List missing) async { + log.add('$id:install'); + return true; + } + + @override + Future probe(ProjectProbe probe) async { + log.add('$id:probe'); + if (probeDelay > Duration.zero) { + await Future.delayed(probeDelay); + } + return ModuleProbeResult.ok(id, [ + RunTask( + id: '${id}_task', + name: id, + command: 'echo $id', + source: TaskSource.detected, + moduleId: id, + ), + ]); + } +} + +/// 固定失败的模块(用于验证失败卡片不被后续进度覆盖) +class _FailingModule extends ProjectModule { + @override + final String id; + + _FailingModule(this.id); + + @override + String get displayName => id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future probe(ProjectProbe probe) async => ModuleProbeResult.failed( + id, + failure: NoticeFailure.executionFailed, + detail: 'boom', + ); +} + +/// 触发条件依赖特征文件的模块(用于验证"空工程不激活任何模块") +class _TriggeredModule extends ProjectModule { + @override + final String id; + final List log; + + _TriggeredModule(this.id, {required this.log}); + + @override + String get displayName => id; + + @override + List get triggerFiles => const ['build.gradle']; + + @override + bool shouldActivate(Directory projectDir) => + File(p.join(projectDir.path, 'build.gradle')).existsSync(); + + @override + Future probe(ProjectProbe probe) async { + log.add('$id:probe'); + return ModuleProbeResult.ok(id, const []); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const systemName = 'test_sys'; + late Directory projectA; + late Directory projectB; + late Directory distroBaseDir; + late DistroManager distroManager; + + setUp(() async { + projectA = await Directory.systemTemp.createTemp('probe_a_'); + projectB = await Directory.systemTemp.createTemp('probe_b_'); + distroBaseDir = await Directory.systemTemp.createTemp('probe_boundary_distro_'); + final rootfs = Directory(p.join(distroBaseDir.path, systemName, 'rootfs')); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + distroManager = DistroManager()..customBaseDir = distroBaseDir; + }); + + tearDown(() async { + DistroManager().customBaseDir = null; + for (final dir in [projectA, projectB, distroBaseDir]) { + if (await dir.exists()) await dir.delete(recursive: true); + } + }); + + RunTask task(String id, String moduleId) => RunTask( + id: id, + name: id, + command: 'echo $id', + source: TaskSource.detected, + moduleId: moduleId, + ); + + group('探测系统边界', () { + test('切换工程:上一个工程迟到的模块结果不得写入新工程的内存表', () async { + final storage = RunTaskStorageService(); + // 用闸门控制每个工程(目录)的模块返回时机 + final module = _GatedModule('gradle'); + final dispatcher = ProjectTaskDispatcher(customModules: [module]); + final provider = RunProvider( + storageService: storage, + dispatcher: dispatcher, + distroManager: distroManager, + ); + + // 工程 A 的模块卡在闸门上(模拟长耗时探测) + final gateA = module.gateFor(projectA.path); + // 工程 B 的模块立即放行 + module.gateFor(projectB.path).complete(); + + final probeA = provider.probeProject(projectRoot: projectA.path, systemName: systemName); + await Future.delayed(const Duration(milliseconds: 30)); + expect(provider.isDetecting, isTrue); + + // 期间切到工程 B:同一 provider 会取消 A 的探测并重新探测 + final probeB = provider.probeProject(projectRoot: projectB.path, systemName: systemName); + await probeB; + expect(provider.currentProjectRoot, projectB.path); + expect( + provider.taskTable.tasksOf(RunTaskType.gradle).map((t) => t.id).toList(), + ['gradle_from_${p.basename(projectB.path)}'], + ); + + // A 的模块这时才返回(迟到结果):绝不能覆盖/污染当前工程的内存表 + gateA.complete(); + await probeA; + expect( + provider.taskTable.tasksOf(RunTaskType.gradle).map((t) => t.id).toList(), + ['gradle_from_${p.basename(projectB.path)}'], + reason: '被取消/被取代的探测结果必须丢弃', + ); + }); + + test('单文件任务写入 singleFile 格,且随当前打开文件本地刷新', () async { + final storage = RunTaskStorageService(); + final pyFile = File(p.join(projectA.path, 'main.py'))..writeAsStringSync('print(1)'); + final cppFile = File(p.join(projectA.path, 'main.cpp'))..writeAsStringSync('int main(){}'); + + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + + await provider.probeProject( + projectRoot: projectA.path, + currentFilePath: pyFile.path, + systemName: systemName, + ); + expect( + provider.taskTable.tasksOf(RunTaskType.singleFile).map((t) => t.id), + ['detected_single_python'], + ); + + // 切换打开的文件 -> 本地重算(不跑容器) + provider.refreshSingleFileTask(currentFilePath: cppFile.path); + expect( + provider.taskTable.tasksOf(RunTaskType.singleFile).map((t) => t.id), + ['detected_single_cpp'], + ); + + // 切到无对应运行方式的文件 -> 该格清空 + final txtFile = File(p.join(projectA.path, 'notes.txt'))..writeAsStringSync('hi'); + provider.refreshSingleFileTask(currentFilePath: txtFile.path); + expect(provider.taskTable.tasksOf(RunTaskType.singleFile), isEmpty); + }); + + test('未映射到内置类型的自定义模块:任务归入 other,不能丢', () async { + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + _ControllableModule('maven', [task('maven_package', 'maven')]), + ]), + distroManager: distroManager, + ); + + await provider.probeProject(projectRoot: projectA.path, systemName: systemName); + + expect(provider.taskTable.tasksOf(RunTaskType.other).map((t) => t.id), ['maven_package']); + expect(provider.detectedTasks.any((t) => t.id == 'maven_package'), isTrue); + expect(RunTaskType.ofTask(task('maven_package', 'maven')), RunTaskType.other); + }); + + test('探测进行中被 dispose:取消会话且不再抛"释放后通知"异常', () async { + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + _ControllableModule('gradle', [task('gradle_x', 'gradle')], + delay: const Duration(milliseconds: 80)), + ]), + distroManager: distroManager, + ); + + final running = provider.probeProject(projectRoot: projectA.path, systemName: systemName); + await Future.delayed(const Duration(milliseconds: 20)); + provider.dispose(); + + // 不抛异常(ChangeNotifier 释放后调用 notifyListeners 会抛) + await running; + expect(provider.isDetecting, isFalse); + }); + + test('空项目(无任何构建特征文件):不启动模块探测,但用户探测与单文件任务照常', () async { + // 空工程:不放任何构建文件,只放一个可运行的源文件 + final pyFile = File(p.join(projectA.path, 'main.py'))..writeAsStringSync('print(1)'); + final storage = RunTaskStorageService(); + await storage.saveConfig(projectRoot: projectA.path, tasks: [ + const RunTask(id: 'user_1', name: 'u', command: 'echo', source: TaskSource.custom), + ]); + + final log = []; + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + // 触发条件为"必须有 build.gradle"的模块:空工程下不应被激活 + _TriggeredModule('gradle', log: log), + ]), + distroManager: distroManager, + ); + + await provider.probeProject( + projectRoot: projectA.path, + currentFilePath: pyFile.path, + systemName: systemName, + ); + + // 没有模块被激活 -> 一次探测都没跑 + expect(log, isEmpty); + expect(provider.lastProbeReport?.totalModules, 0); + expect(provider.detectedTasks.where((t) => t.moduleId != null), isEmpty); + // 用户任务照常(来自磁盘) + expect(provider.customTasks.map((t) => t.id), ['user_1']); + // 单文件任务照常(本地计算,不依赖任何模块) + expect(provider.taskTable.tasksOf(RunTaskType.singleFile).map((t) => t.id), + ['detected_single_python']); + }); + + test('工程外的文件不产出单文件任务(容器内不存在该文件)', () async { + final outsideDir = await Directory.systemTemp.createTemp('probe_outside_'); + addTearDown(() async { + if (await outsideDir.exists()) await outsideDir.delete(recursive: true); + }); + final outsidePy = File(p.join(outsideDir.path, 'main.py'))..writeAsStringSync('print(1)'); + + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + + await provider.probeProject( + projectRoot: projectA.path, + currentFilePath: outsidePy.path, + systemName: systemName, + ); + + expect(provider.taskTable.tasksOf(RunTaskType.singleFile), isEmpty); + expect(ProjectTaskDispatcher.detectSingleFileTask(projectA.path, outsidePy.path), isNull); + }); + + test('关闭工程:清空内存并终止进行中的探测', () async { + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + _ControllableModule('gradle', [task('gradle_x', 'gradle')], + delay: const Duration(milliseconds: 60)), + ]), + distroManager: distroManager, + ); + + final running = provider.probeProject(projectRoot: projectA.path, systemName: systemName); + await Future.delayed(const Duration(milliseconds: 10)); + expect(provider.isDetecting, isTrue); + + provider.onProjectClosed(); + expect(provider.currentProjectRoot, isNull); + expect(provider.taskTable.isEmpty, isTrue); + + await running; + expect(provider.taskTable.isEmpty, isTrue, reason: '关闭工程后迟到的结果不得回填'); + }); + }); + + group('用户任务与"上一次执行任务"的加载边界', () { + test('进入项目必定加载用户任务;无可用系统时也照常加载', () async { + final storage = RunTaskStorageService(); + await storage.saveConfig(projectRoot: projectA.path, tasks: [ + const RunTask(id: 'user_a', name: 'a', command: 'echo a', source: TaskSource.custom), + const RunTask(id: 'user_b', name: 'b', command: 'echo b', source: TaskSource.custom), + ], lastRunTaskId: 'user_b'); + + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + + // 没有可用系统(systemName = null):系统探测会跳过,但用户任务必须加载 + await provider.probeProject(projectRoot: projectA.path, systemName: null); + + expect(provider.customTasks.map((t) => t.id), ['user_a', 'user_b']); + expect(provider.lastRunTask?.id, 'user_b'); + }); + + test('未进入项目时用户探测是空操作(没有工程根就不加载)', () async { + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + + await provider.probeUser(); + expect(provider.customTasks, isEmpty); + expect(provider.currentProjectRoot, isNull); + }); + + test('run_tasks.json 损坏:加载为空但不抛异常(磁盘文件保持原样)', () async { + final storage = RunTaskStorageService(); + final configFile = storage.getConfigFile(projectA.path); + configFile.parent.createSync(recursive: true); + configFile.writeAsStringSync('{ this is not json ]'); + + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + + await provider.probeProject(projectRoot: projectA.path, systemName: null); + expect(provider.customTasks, isEmpty); + // 坏文件不被覆盖(用户仍可手工修复) + expect(configFile.existsSync(), isTrue); + expect(configFile.readAsStringSync(), contains('not json')); + }); + + test('刚打开工程就记录"上次执行任务":不得清空磁盘上已有的用户任务', () async { + final storage = RunTaskStorageService(); + await storage.saveConfig(projectRoot: projectA.path, tasks: [ + const RunTask(id: 'user_a', name: 'a', command: 'echo a', source: TaskSource.custom), + const RunTask(id: 'user_b', name: 'b', command: 'echo b', source: TaskSource.custom), + ]); + + // 全新 provider:内存里还没有任何用户任务 + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + provider.onProjectOpened(projectA.path, systemName: null); // 不等待加载 + await provider.setLastRunTask( + const RunTask(id: 'user_a', name: 'a', command: 'echo a', source: TaskSource.custom), + ); + + // 磁盘上两个任务都必须还在,只是 lastRunTaskId 被更新 + final persisted = await storage.loadConfig(projectA.path); + expect(persisted.tasks.map((t) => t.id), containsAll(['user_a', 'user_b'])); + expect(persisted.lastRunTaskId, 'user_a'); + }); + + test('内存尚未加载完时添加用户任务:以磁盘为基准,不丢已有任务', () async { + final storage = RunTaskStorageService(); + await storage.saveConfig(projectRoot: projectA.path, tasks: [ + const RunTask(id: 'user_a', name: 'a', command: 'echo a', source: TaskSource.custom), + ]); + + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: const []), + distroManager: distroManager, + ); + // 只绑定工程根,不等用户探测完成 + provider.onProjectOpened(projectA.path, systemName: null); + await provider.addCustomTask( + const RunTask(id: 'user_new', name: 'n', command: 'echo n', source: TaskSource.custom), + ); + + final persisted = await storage.loadConfig(projectA.path); + expect(persisted.tasks.map((t) => t.id), containsAll(['user_a', 'user_new'])); + }); + }); + + group('通知文案顺序(Gradle 为例)', () { + test('失败卡片不会被后续队列进度覆盖(失败原因保留、不再二次确认)', () async { + final center = NoticeCenter(); + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + // gradle 立刻失败,npm 稍慢 -> 期间会持续上报队列进度 + _FailingModule('gradle'), + _BudgetModule('npm', log: [], probeDelay: const Duration(milliseconds: 60)), + ]), + distroManager: distroManager, + noticeCenter: center, + ); + + await provider.probeProject(projectRoot: projectA.path, systemName: systemName); + + final gradleNotice = center.visible.firstWhere((n) => n.id == 'probe:gradle'); + expect(gradleNotice.kind, NoticeKind.failure); + final text = gradleNotice.text as ModuleFailureText; + expect(text.moduleDisplayName, 'gradle'); + expect(text.failure, NoticeFailure.executionFailed); + expect(gradleNotice.confirmBeforeDismiss, isFalse, + reason: '模块已结束,关闭失败卡片不再是破坏性操作'); + }); + + test('成功卡片不会被后续队列进度回写为"排队等待中"', () async { + final center = NoticeCenter(); + final storage = RunTaskStorageService(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + _BudgetModule('gradle', log: []), + _BudgetModule('npm', log: [], probeDelay: const Duration(milliseconds: 80)), + ]), + distroManager: distroManager, + noticeCenter: center, + ); + + // 不 await:在 npm 还在跑的时候检查 gradle 的卡片 + final running = provider.probeProject(projectRoot: projectA.path, systemName: systemName); + await Future.delayed(const Duration(milliseconds: 60)); + + final gradleNotice = center.visible.firstWhere((n) => n.id == 'probe:gradle'); + expect(gradleNotice.kind, NoticeKind.success); + expect(gradleNotice.text, isA()); + + await running; + }); + }); + + group('探测时间预算', () { + test('模块之间超预算:剩余模块标记 skippedByBudget,且不再执行探测', () async { + final log = []; + final dispatcher = ProjectTaskDispatcher(customModules: [ + _BudgetModule('gradle', log: log, probeDelay: const Duration(milliseconds: 40)), + _BudgetModule('npm', log: log), + _BudgetModule('make', log: log), + ]); + + final probe = dispatcher.createProbe( + projectRoot: projectA.path, + systemName: systemName, + distroManager: distroManager, + budget: const Duration(milliseconds: 15), + ); + final report = await dispatcher.run(probe); + probe.dispose(); + + expect(report.abortedByBudget, isTrue); + expect(report.totalModules, 3); + expect(report.completedModules, 1); + expect(report.moduleResults['gradle']!.status, ModuleProbeStatus.ok); + expect(report.moduleResults['npm']!.status, ModuleProbeStatus.skippedByBudget); + expect(report.moduleResults['make']!.status, ModuleProbeStatus.skippedByBudget); + // 后两个模块连探测都没开始 + expect(log, ['gradle:probe']); + }); + + test('预算充足:正常跑完全部模块', () async { + final log = []; + final dispatcher = ProjectTaskDispatcher(customModules: [ + _BudgetModule('gradle', log: log), + _BudgetModule('npm', log: log), + ]); + + final probe = dispatcher.createProbe( + projectRoot: projectA.path, + systemName: systemName, + distroManager: distroManager, + budget: const Duration(seconds: 30), + ); + final report = await dispatcher.run(probe); + probe.dispose(); + + expect(report.abortedByBudget, isFalse); + expect(report.completedModules, 2); + expect(log, ['gradle:probe', 'npm:probe']); + }); + + test('依赖安装前超预算:跳过安装(避免半装状态),模块标记 skippedByBudget', () async { + final log = []; + final dispatcher = ProjectTaskDispatcher(customModules: [ + _BudgetModule( + 'gradle', + log: log, + depsDelay: const Duration(milliseconds: 40), + missingDependencies: const ['gradle'], + ), + ]); + + final probe = dispatcher.createProbe( + projectRoot: projectA.path, + systemName: systemName, + distroManager: distroManager, + budget: const Duration(milliseconds: 15), + ); + final report = await dispatcher.run(probe); + probe.dispose(); + + expect(report.abortedByBudget, isTrue); + expect(report.moduleResults['gradle']!.status, ModuleProbeStatus.skippedByBudget); + expect(log.contains('gradle:install'), isFalse, + reason: '预算将尽时不得开跑可能长达 10 分钟的安装'); + expect(log.contains('gradle:probe'), isFalse); + }); + + test('RunProvider:预算中止后弹出可关闭的"已中止"通知(× 仍可用)', () async { + final storage = RunTaskStorageService(); + final center = NoticeCenter(); + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [ + _BudgetModule('gradle', log: [], probeDelay: const Duration(milliseconds: 40)), + _BudgetModule('npm', log: []), + ]), + distroManager: distroManager, + noticeCenter: center, + probeBudget: const Duration(milliseconds: 15), + ); + + await provider.probeProject(projectRoot: projectA.path, systemName: systemName); + + final budgetNotice = center.visible.firstWhere((n) => n.id == 'probe:budget'); + expect(budgetNotice.sticky, isTrue); + expect(budgetNotice.text, isA()); + final text = budgetNotice.text as ProbeBudgetExceededText; + expect(text.completed, 1); + expect(text.total, 2); + + // × 仍然可以关闭它(保留 x) + center.dismiss('probe:budget'); + center.finalizeDismiss('probe:budget'); + expect(center.visible.any((n) => n.id == 'probe:budget'), isFalse); + }); + }); + + group('通知 × 的附加动作', () { + testWidgets('点击进行中通知的 × 会触发 onUserDismiss(用于取消探测)', (tester) async { + final center = NoticeCenter(); + var cancelled = false; + + await tester.pumpWidget( + MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Stack(children: [ + Positioned.fill(child: NoticeHost(center: center)), + ]), + ), + ), + ); + await tester.pumpAndSettle(); + + center.push(NoticeItem( + id: 'probe:gradle', + kind: NoticeKind.progress, + text: const ModulePhaseText( + moduleDisplayName: 'Gradle', + phase: ProbeNoticePhase.detecting, + ), + onUserDismiss: () => cancelled = true, + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pump(); + expect(cancelled, isTrue, reason: '× 应触发附加动作'); + + await tester.pump(const Duration(milliseconds: 400)); + expect(center.visible, isEmpty); + }); + }); +} diff --git a/test/probe_cancel_guard_test.dart b/test/probe_cancel_guard_test.dart new file mode 100644 index 0000000..d066230 --- /dev/null +++ b/test/probe_cancel_guard_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/notice_item.dart'; +import 'package:code_editor/providers/notice_center.dart'; +import 'package:code_editor/widgets/notice_host.dart'; +import 'package:code_editor/widgets/probe_cancel_guard.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + Widget wrap(Widget child, {Locale locale = const Locale('zh')}) => MaterialApp( + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: Stack(children: [Positioned.fill(child: child)])), + ); + + NoticeItem progressNotice({bool confirm = true, VoidCallback? onDismiss}) => NoticeItem( + id: 'probe:gradle', + kind: NoticeKind.progress, + text: const ModulePhaseText( + moduleDisplayName: 'Gradle', + phase: ProbeNoticePhase.detecting, + ), + onUserDismiss: onDismiss, + confirmBeforeDismiss: confirm, + ); + + Future settle(WidgetTester tester) async { + // 进行中的通知含无限进度圈,不能用 pumpAndSettle + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + } + + group('取消探测的二次确认', () { + testWidgets('确认弹窗文案与按钮来自 l10n(取消 => 探测继续)', (tester) async { + final results = []; + await tester.pumpWidget(wrap(Builder( + builder: (context) => Center( + child: ElevatedButton( + onPressed: () async => results.add(await confirmCancelProbe(context)), + child: const Text('cancel'), + ), + ), + ))); + await tester.pumpAndSettle(); + + await tester.tap(find.text('cancel')); + await tester.pumpAndSettle(); + + expect(find.text('取消本次探测?'), findsOneWidget); + expect(find.textContaining('未完成的模块将被跳过'), findsOneWidget); + + await tester.tap(find.text('继续探测')); + await tester.pumpAndSettle(); + expect(results, [false], reason: '"继续探测" => 不取消'); + }); + + testWidgets('点"取消探测" => 确认取消', (tester) async { + final results = []; + await tester.pumpWidget(wrap(Builder( + builder: (context) => Center( + child: ElevatedButton( + onPressed: () async => results.add(await confirmCancelProbe(context)), + child: const Text('cancel'), + ), + ), + ))); + await tester.pumpAndSettle(); + + await tester.tap(find.text('cancel')); + await tester.pumpAndSettle(); + await tester.tap(find.text('取消探测')); + await tester.pumpAndSettle(); + + expect(results, [true]); + }); + + testWidgets('NoticeHost:confirmBeforeDismiss 为 false 时直接关闭(不弹确认)', (tester) async { + final center = NoticeCenter(); + var dismissedByUser = false; + await tester.pumpWidget(wrap(NoticeHost( + center: center, + confirmDismissBuilder: confirmCancelProbe, + ))); + await tester.pumpAndSettle(); + + center.push(progressNotice(confirm: false, onDismiss: () => dismissedByUser = true)); + await settle(tester); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + + expect(find.text('取消本次探测?'), findsNothing); + expect(dismissedByUser, isTrue); + expect(center.visible, isEmpty); + }); + + testWidgets('NoticeHost:在确认弹窗里选"继续探测" => 卡片保留、附加动作不执行', (tester) async { + final center = NoticeCenter(); + var dismissedByUser = false; + await tester.pumpWidget(wrap(NoticeHost( + center: center, + confirmDismissBuilder: confirmCancelProbe, + ))); + await tester.pumpAndSettle(); + + center.push(progressNotice(onDismiss: () => dismissedByUser = true)); + await settle(tester); + + await tester.tap(find.byIcon(Icons.close)); + await settle(tester); + expect(find.text('取消本次探测?'), findsOneWidget); + + await tester.tap(find.text('继续探测')); + await settle(tester); + + expect(dismissedByUser, isFalse, reason: '放弃取消 => 不得执行"取消探测"动作'); + expect(center.visible, hasLength(1), reason: '卡片必须保留'); + }); + + testWidgets('NoticeHost:确认"取消探测" => 执行附加动作并移除卡片', (tester) async { + final center = NoticeCenter(); + var dismissedByUser = false; + await tester.pumpWidget(wrap(NoticeHost( + center: center, + confirmDismissBuilder: confirmCancelProbe, + ))); + await tester.pumpAndSettle(); + + center.push(progressNotice(onDismiss: () => dismissedByUser = true)); + await settle(tester); + + await tester.tap(find.byIcon(Icons.close)); + await settle(tester); + await tester.tap(find.text('取消探测')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + + expect(dismissedByUser, isTrue); + expect(center.visible, isEmpty); + }); + }); +} diff --git a/test/probe_fix_verification_test.dart b/test/probe_fix_verification_test.dart new file mode 100644 index 0000000..4d2280e --- /dev/null +++ b/test/probe_fix_verification_test.dart @@ -0,0 +1,223 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/project_modules/gradle_ide_model.dart'; +import 'package:code_editor/services/project_modules/project_module.dart'; +import 'package:code_editor/services/project_modules/project_probe.dart'; +import 'package:code_editor/services/project_modules/standard_project_modules.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; +import 'package:code_editor/services/run_task_storage_service.dart'; + +class _CancellingModule extends ProjectModule { + @override + final String id; + final Duration delay; + final void Function(ProjectProbe probe)? onProbe; + + _CancellingModule(this.id, {this.delay = Duration.zero, this.onProbe}); + + @override + String get displayName => id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future probe(ProjectProbe probe) async { + onProbe?.call(probe); + if (delay > Duration.zero) { + await Future.delayed(delay); + } + if (probe.isCancelled) return ModuleProbeResult.cancelled(id); + return ModuleProbeResult.ok(id, const []); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('Probe System Logic Bug Fixes Verification', () { + late Directory tempDir; + late Directory distroBaseDir; + late DistroManager distroManager; + const systemName = 'test_sys'; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('probe_fix_test_'); + distroBaseDir = await Directory.systemTemp.createTemp('probe_fix_distro_'); + + final rootfs = Directory(p.join(distroBaseDir.path, systemName, 'rootfs')); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + + distroManager = DistroManager()..customBaseDir = distroBaseDir; + }); + + tearDown(() async { + DistroManager().customBaseDir = null; + if (await tempDir.exists()) await tempDir.delete(recursive: true); + if (await distroBaseDir.exists()) await distroBaseDir.delete(recursive: true); + }); + + test('1. detectSingleFileTask 安全包裹单引号与 -lm 数学库', () { + final fileWithDollar = File(p.join(tempDir.path, 'test\$1.c'))..writeAsStringSync('int main() {}'); + final task = ProjectTaskDispatcher.detectSingleFileTask(tempDir.path, fileWithDollar.path); + expect(task, isNotNull); + // 命令必须包含单引号包裹和 -lm + expect(task!.command, contains(r"gcc './test$1.c' -lm -o /tmp/a.out && /tmp/a.out")); + + final pyFile = File(p.join(tempDir.path, 'hello world.py'))..writeAsStringSync('print()'); + final pyTask = ProjectTaskDispatcher.detectSingleFileTask(tempDir.path, pyFile.path); + expect(pyTask, isNotNull); + expect(pyTask!.command, equals("python3 './hello world.py'")); + }); + + test('2. CargoProjectModule._declaredBinaryNames 过滤注释并支持带空格的 [[ bin ]]', () async { + File(p.join(tempDir.path, 'Cargo.toml')).writeAsStringSync(''' +[package] +name = "my_pkg" +version = "0.1.0" + +[[ bin ]] +name = "server" # inline comment + +[[bin]] +name = "client" +'''); + final probe = ProjectProbe( + request: ProjectProbeRequest( + projectDir: tempDir, + systemName: systemName, + ), + distroManager: distroManager, + ); + final cargoModule = CargoProjectModule(); + expect(cargoModule.shouldActivate(tempDir), isTrue); + + final res = await cargoModule.probe(probe); + expect(res.tasks.map((t) => t.id), containsAll(['cargo_run_server', 'cargo_run_client'])); + final serverTask = res.tasks.firstWhere((t) => t.id == 'cargo_run_server'); + expect(serverTask.command, equals('cargo run --bin server')); + }); + + test('3. CMakeProjectModule 解析 add_executable 并包裹单引号', () async { + File(p.join(tempDir.path, 'CMakeLists.txt')).writeAsStringSync(''' +cmake_minimum_required(VERSION 3.10) +project(MyAwesomeProject) +add_executable(app_binary main.cpp) +'''); + final probe = ProjectProbe( + request: ProjectProbeRequest( + projectDir: tempDir, + systemName: systemName, + ), + distroManager: distroManager, + ); + final cmakeModule = CMakeProjectModule(); + final res = await cmakeModule.probe(probe); + expect(res.status, ModuleProbeStatus.ok); + final runTask = res.tasks.firstWhere((t) => t.id == 'detected_cmake_build_run'); + expect(runTask.command, contains("'./build/app_binary'")); + }); + + test('4. 取消探测时队列中所有未开始模块均完整记录为 cancelled', () async { + final m1 = _CancellingModule('m1', delay: const Duration(milliseconds: 20), onProbe: (probe) { + // 在 m1 执行时取消 probe + probe.cancel(); + }); + final m2 = _CancellingModule('m2'); + final m3 = _CancellingModule('m3'); + + final dispatcher = ProjectTaskDispatcher(customModules: [m1, m2, m3]); + final probe = dispatcher.createProbe( + projectRoot: tempDir.path, + systemName: systemName, + distroManager: distroManager, + ); + + final report = await dispatcher.run(probe); + expect(probe.isCancelled, isTrue); + // 全部激活模块均应在 moduleResults 中有记录 + expect(report.moduleResults.keys, containsAll(['m1', 'm2', 'm3'])); + expect(report.moduleResults['m1']?.status, ModuleProbeStatus.cancelled); + expect(report.moduleResults['m2']?.status, ModuleProbeStatus.cancelled); + expect(report.moduleResults['m3']?.status, ModuleProbeStatus.cancelled); + }); + + test('5. probeSystem 开始新探测时自动终止正在进行的旧探测', () async { + final storage = RunTaskStorageService(); + final mLong = _CancellingModule('long', delay: const Duration(milliseconds: 200)); + + final provider = RunProvider( + storageService: storage, + dispatcher: ProjectTaskDispatcher(customModules: [mLong]), + distroManager: distroManager, + ); + + // 启动第 1 次探测 + final f1 = provider.probeSystem(projectRoot: tempDir.path, systemName: systemName); + await Future.delayed(const Duration(milliseconds: 20)); + expect(provider.isDetecting, isTrue); + final active1 = provider.activeProbeForTest; + + // 启动第 2 次探测:应该先 cancel 掉第 1 次 + final f2 = provider.probeSystem(projectRoot: tempDir.path, systemName: systemName); + expect(active1?.isCancelled, isTrue); + + await Future.wait([f1, f2]); + }); + + test('6. SingleFileTaskDetector 独立模块支持 8 种语言并正确处理委托', () { + final root = tempDir.path; + final exts = { + 'a.py': 'python3', + 'a.c': 'gcc', + 'a.cpp': 'g++', + 'a.sh': 'sh', + 'a.dart': 'dart run', + 'a.go': 'go run', + 'a.rs': 'rustc', + 'a.js': 'node', + }; + + for (final entry in exts.entries) { + final filePath = p.join(root, entry.key); + File(filePath).writeAsStringSync('// dummy'); + + expect(SingleFileTaskDetector.isSupported(filePath), isTrue); + final task = SingleFileTaskDetector.detect(root, filePath); + expect(task, isNotNull); + expect(task!.command, contains(entry.value)); + + // 验证 ProjectTaskDispatcher.detectSingleFileTask 委托结果一致 + final delegatedTask = ProjectTaskDispatcher.detectSingleFileTask(root, filePath); + expect(delegatedTask, isNotNull); + expect(delegatedTask!.id, equals(task.id)); + } + }); + + test('7. GradleIdeModel.fromJson 解析 schema: 0 包含具体 error 消息的 FormatException', () { + final jsonWithError = { + 'schema': 0, + 'error': 'org.gradle.api.tasks.TaskInstantiationException: failed', + }; + expect( + () => GradleIdeModel.fromJson(jsonWithError), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('org.gradle.api.tasks.TaskInstantiationException: failed'), + ), + ), + ); + }); + }); +} diff --git a/test/project_probe_queue_test.dart b/test/project_probe_queue_test.dart new file mode 100644 index 0000000..db4d2a8 --- /dev/null +++ b/test/project_probe_queue_test.dart @@ -0,0 +1,316 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +import 'package:code_editor/models/notice_item.dart'; +import 'package:code_editor/models/project_task_table.dart'; +import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/models/run_task_type.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/project_modules/project_module.dart'; +import 'package:code_editor/services/project_modules/project_probe.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; + +/// 记录执行时序的假模块:用于验证"队列线性执行 + 三动作顺序" +class _FakeModule extends ProjectModule { + @override + final String id; + final List log; + final List tasks; + final bool probeFails; + + /// 首次依赖检测返回缺失,安装成功后复检返回空 + List _pendingDependencies; + final bool installSucceeds; + final Duration probeDelay; + + /// 并发探针:probe 执行期间 +1,用于断言"线性执行、无重叠" + final ValueNotifier concurrency; + + _FakeModule({ + required this.id, + required this.log, + required this.concurrency, + this.tasks = const [], + this.probeFails = false, + List pendingDependencies = const [], + this.installSucceeds = true, + this.probeDelay = Duration.zero, + }) : _pendingDependencies = pendingDependencies; + + @override + String get displayName => id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future prepare(ProjectProbe probe) async { + log.add('$id:prepare'); + } + + @override + Future> checkDependencies(ProjectProbe probe) async { + log.add('$id:check'); + return _pendingDependencies; + } + + @override + Future installDependencies(ProjectProbe probe, List missing) async { + log.add('$id:install:${missing.join(",")}'); + if (installSucceeds) { + _pendingDependencies = const []; + } + return installSucceeds; + } + + @override + Future probe(ProjectProbe probe) async { + log.add('$id:probe'); + concurrency.value = concurrency.value + 1; + // 同一时刻只允许一个模块处于探测中(队列线性执行的硬约束) + expect(concurrency.value, 1, reason: '队列必须线性执行,不允许两个模块同时探测'); + if (probeDelay > Duration.zero) { + await Future.delayed(probeDelay); + } + concurrency.value = concurrency.value - 1; + + if (probeFails) { + return ModuleProbeResult.failed( + id, + failure: NoticeFailure.executionFailed, + detail: 'boom', + ); + } + return ModuleProbeResult.ok(id, tasks); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory projectDir; + late Directory distroBaseDir; + late DistroManager distroManager; + const systemName = 'test_sys'; + + setUp(() async { + projectDir = await Directory.systemTemp.createTemp('probe_queue_project_'); + + // 假系统:rootfs/{etc,bin,usr/bin/java} + distroBaseDir = await Directory.systemTemp.createTemp('probe_queue_distro_'); + final rootfs = Directory(p.join(distroBaseDir.path, systemName, 'rootfs')); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + final usrBin = Directory(p.join(rootfs.path, 'usr', 'bin'))..createSync(recursive: true); + File(p.join(usrBin.path, 'java')).writeAsStringSync('#!/bin/sh\n'); + distroManager = DistroManager()..customBaseDir = distroBaseDir; + }); + + tearDown(() async { + DistroManager().customBaseDir = null; + if (await projectDir.exists()) await projectDir.delete(recursive: true); + if (await distroBaseDir.exists()) await distroBaseDir.delete(recursive: true); + }); + + RunTask task(String id, String moduleId) => RunTask( + id: id, + name: id, + command: 'echo $id', + source: TaskSource.detected, + moduleId: moduleId, + ); + + group('探测队列:模块发现 → 入队 → 线性三动作', () { + test('队列线性执行:按顺序串行、成功与失败都继续下一个', () async { + final log = []; + final concurrency = ValueNotifier(0); + final dispatcher = ProjectTaskDispatcher(customModules: [ + _FakeModule( + id: 'gradle', + log: log, + concurrency: concurrency, + tasks: [task('gradle_build', 'gradle')], + probeDelay: const Duration(milliseconds: 20), + ), + _FakeModule( + id: 'cmake', + log: log, + concurrency: concurrency, + probeFails: true, + probeDelay: const Duration(milliseconds: 20), + ), + _FakeModule( + id: 'npm', + log: log, + concurrency: concurrency, + tasks: [task('npm_start', 'npm')], + probeDelay: const Duration(milliseconds: 20), + ), + ]); + + final emitted = []; + final probe = dispatcher.createProbe( + projectRoot: projectDir.path, + systemName: systemName, + distroManager: distroManager, + ); + final report = await dispatcher.run( + probe, + onModuleResult: (module, result) => emitted.add('${module.id}:${result.status.name}'), + ); + probe.dispose(); + + // 严格线性:a 全套 → b 全套 → c 全套 + expect(log, [ + 'gradle:prepare', 'gradle:check', 'gradle:probe', + 'cmake:prepare', 'cmake:check', 'cmake:probe', + 'npm:prepare', 'npm:check', 'npm:probe', + ]); + expect(concurrency.value, 0); + + // 失败模块不影响后续模块执行,结果逐模块上抛 + expect(emitted, ['gradle:ok', 'cmake:failed', 'npm:ok']); + expect(report.moduleResults['cmake']!.status, ModuleProbeStatus.failed); + expect(report.detectedTasks.map((t) => t.id), containsAll(['gradle_build', 'npm_start'])); + }); + + test('依赖检测 → 自动补全 → 复检 → 执行探测(顺序固定)', () async { + final log = []; + final concurrency = ValueNotifier(0); + final module = _FakeModule( + id: 'gradle', + log: log, + concurrency: concurrency, + tasks: [task('gradle_build', 'gradle')], + pendingDependencies: const ['gradle'], + ); + final dispatcher = ProjectTaskDispatcher(customModules: [module]); + + final probe = dispatcher.createProbe( + projectRoot: projectDir.path, + systemName: systemName, + distroManager: distroManager, + ); + final report = await dispatcher.run(probe); + probe.dispose(); + + expect(log, [ + 'gradle:prepare', + 'gradle:check', + 'gradle:install:gradle', + 'gradle:check', + 'gradle:probe', + ]); + expect(report.moduleResults['gradle']!.status, ModuleProbeStatus.ok); + }); + + test('依赖自动补全失败:该模块标记 dependencyInstallFailed,后续模块照常执行', () async { + final log = []; + final concurrency = ValueNotifier(0); + final dispatcher = ProjectTaskDispatcher(customModules: [ + _FakeModule( + id: 'gradle', + log: log, + concurrency: concurrency, + installSucceeds: false, + pendingDependencies: const ['gradle'], + ), + _FakeModule(id: 'make', log: log, concurrency: concurrency, tasks: [task('make_default', 'make')]), + ]); + + final probe = dispatcher.createProbe( + projectRoot: projectDir.path, + systemName: systemName, + distroManager: distroManager, + ); + final report = await dispatcher.run(probe); + probe.dispose(); + + final gradleResult = report.moduleResults['gradle']!; + expect(gradleResult.status, ModuleProbeStatus.failed); + expect(gradleResult.failure, NoticeFailure.dependencyInstallFailed); + // 没有进入 probe 阶段 + expect(log.contains('gradle:probe'), isFalse); + // 后续模块照常完成 + expect(report.moduleResults['make']!.status, ModuleProbeStatus.ok); + expect(log.contains('make:probe'), isTrue); + }); + + test('无可用系统时不入队、不探测、也不创建任何目录', () async { + final emptyBase = await Directory.systemTemp.createTemp('probe_queue_empty_'); + addTearDown(() async { + if (await emptyBase.exists()) await emptyBase.delete(recursive: true); + }); + DistroManager().customBaseDir = emptyBase; + + final log = []; + final concurrency = ValueNotifier(0); + final dispatcher = ProjectTaskDispatcher(customModules: [ + _FakeModule(id: 'gradle', log: log, concurrency: concurrency), + ]); + + final probe = dispatcher.createProbe( + projectRoot: projectDir.path, + systemName: 'ubuntu', + distroManager: DistroManager(), + ); + final report = await dispatcher.run(probe); + probe.dispose(); + + expect(report.detectedTasks, isEmpty); + expect(log, isEmpty); + expect(Directory(p.join(emptyBase.path, 'ubuntu')).existsSync(), isFalse); + }); + }); + + group('任务类型表(类型 → 任务数组)', () { + test('RunTaskType.ofTask 映射:模块任务 / 单文件 / 用户任务', () { + expect(RunTaskType.ofTask(task('gradle_build', 'gradle')), RunTaskType.gradle); + expect(RunTaskType.ofTask(task('cmake_build', 'cmake')), RunTaskType.cmake); + expect( + RunTaskType.ofTask(const RunTask( + id: 'detected_single_python', + name: 'py', + command: 'python3 x.py', + source: TaskSource.detected, + group: 'single_file', + )), + RunTaskType.singleFile, + ); + expect( + RunTaskType.ofTask(const RunTask( + id: 'user_1', + name: 'custom', + command: 'echo', + source: TaskSource.custom, + )), + RunTaskType.user, + ); + }); + + test('模块只写入自己类型那一格,用户任务固定在最后', () { + final table = ProjectTaskTable(); + table.replaceType(RunTaskType.gradle, [task('gradle_build', 'gradle')]); + table.replaceType(RunTaskType.npm, [task('npm_start', 'npm')]); + table.setUserTasks([ + const RunTask(id: 'user_1', name: 'custom', command: 'echo', source: TaskSource.custom), + ]); + + expect(table.tasksOf(RunTaskType.gradle), hasLength(1)); + expect(table.tasksOf(RunTaskType.cmake), isEmpty); + expect(table.nonEmptyTypes, [RunTaskType.gradle, RunTaskType.npm, RunTaskType.user]); + expect(RunTaskType.ofTask(table.allOrdered.last), RunTaskType.user); + expect(table.detectedTasks.any((t) => t.source == TaskSource.custom), isFalse); + + // 覆盖写入(重新同步)不会残留旧任务 + table.replaceType(RunTaskType.gradle, [task('gradle_test', 'gradle')]); + expect(table.tasksOf(RunTaskType.gradle).map((t) => t.id), ['gradle_test']); + }); + }); +} diff --git a/test/run_provider_probe_split_test.dart b/test/run_provider_probe_split_test.dart new file mode 100644 index 0000000..8c924f8 --- /dev/null +++ b/test/run_provider_probe_split_test.dart @@ -0,0 +1,281 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/models/run_task_type.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/project_modules/project_module.dart'; +import 'package:code_editor/services/project_modules/project_probe.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; +import 'package:code_editor/services/run_task_storage_service.dart'; + +/// 计数用存储服务:用于验证"用户探测"的并发合并(磁盘 IO 不被放大) +class _CountingStorage extends RunTaskStorageService { + int loadCount = 0; + + @override + Future<({List tasks, String? lastRunTaskId})> loadConfig(String projectRoot) { + loadCount++; + return super.loadConfig(projectRoot); + } +} + +/// 固定返回任务的假系统模块 +class _StubModule extends ProjectModule { + @override + final String id; + @override + final String displayName; + final List tasks; + + _StubModule(this.id, this.tasks, {String? displayName}) : displayName = displayName ?? id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future probe(ProjectProbe probe) async => ModuleProbeResult.ok(id, tasks); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const systemName = 'test_sys'; + late Directory projectDir; + late Directory distroBaseDir; + late DistroManager distroManager; + + setUp(() async { + projectDir = await Directory.systemTemp.createTemp('probe_split_project_'); + distroBaseDir = await Directory.systemTemp.createTemp('probe_split_distro_'); + final rootfs = Directory(p.join(distroBaseDir.path, systemName, 'rootfs')); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + distroManager = DistroManager()..customBaseDir = distroBaseDir; + }); + + tearDown(() async { + DistroManager().customBaseDir = null; + if (await projectDir.exists()) await projectDir.delete(recursive: true); + if (await distroBaseDir.exists()) await distroBaseDir.delete(recursive: true); + }); + + RunTask task(String id, String moduleId) => RunTask( + id: id, + name: id, + command: 'echo $id', + source: TaskSource.detected, + moduleId: moduleId, + ); + + RunProvider buildProvider(RunTaskStorageService storage, {ProjectTaskDispatcher? dispatcher}) { + return RunProvider( + storageService: storage, + dispatcher: dispatcher ?? ProjectTaskDispatcher(customModules: [_StubModule('gradle', [task('gradle_build', 'gradle')])]), + distroManager: distroManager, + ); + } + + group('探测层三函数:探测 / 系统探测 / 用户探测', () { + test('探测函数:清空内存 → 用户探测(磁盘覆盖内存)→ 系统探测(模块写入类型格)', () async { + final storage = RunTaskStorageService(); + // 磁盘上先放一份用户任务与"上次执行" + const userTask = RunTask( + id: 'user_1', + name: '我的任务', + command: 'echo user', + source: TaskSource.custom, + ); + await storage.saveConfig(projectRoot: projectDir.path, tasks: [userTask], lastRunTaskId: 'user_1'); + + final provider = buildProvider(storage); + + // 先手动污染内存中的用户任务,验证"覆盖"语义 + await provider.probeUser(projectRoot: projectDir.path); + expect(provider.customTasks.map((t) => t.id), ['user_1']); + + await provider.probeProject( + projectRoot: projectDir.path, + systemName: systemName, + ); + + // 用户探测从磁盘覆盖 + expect(provider.customTasks.map((t) => t.id), ['user_1']); + expect(provider.lastRunTaskId, 'user_1'); + expect(provider.lastRunTask?.id, 'user_1'); + // 系统探测写入 gradle 类型格 + expect(provider.taskTable.tasksOf(RunTaskType.gradle).map((t) => t.id), ['gradle_build']); + expect(provider.taskTable.tasksOf(RunTaskType.user).map((t) => t.id), ['user_1']); + expect(provider.isDetecting, isFalse); + }); + + test('探测函数会清空上一轮系统任务(系统任务只存在于内存)', () async { + final storage = RunTaskStorageService(); + final dispatcher = ProjectTaskDispatcher(customModules: [ + _StubModule('gradle', [task('gradle_a', 'gradle')]), + ]); + final provider = buildProvider(storage, dispatcher: dispatcher); + + await provider.probeProject(projectRoot: projectDir.path, systemName: systemName); + expect(provider.taskTable.tasksOf(RunTaskType.gradle).map((t) => t.id), ['gradle_a']); + + // 换成"探测不出任何任务"的模块后重新探测 -> 旧的系统任务必须被清掉 + final emptyDispatcher = ProjectTaskDispatcher(customModules: [ + _StubModule('gradle', const []), + ]); + final provider2 = RunProvider( + storageService: storage, + dispatcher: emptyDispatcher, + distroManager: distroManager, + ); + await provider2.probeProject(projectRoot: projectDir.path, systemName: systemName); + expect(provider2.detectedTasks, isEmpty); + }); + + test('无可用系统时只完成用户探测,系统类型格保持为空', () async { + final storage = RunTaskStorageService(); + await storage.saveConfig( + projectRoot: projectDir.path, + tasks: [ + const RunTask(id: 'user_1', name: 'u', command: 'echo', source: TaskSource.custom), + ], + ); + final provider = buildProvider(storage); + + await provider.probeProject(projectRoot: projectDir.path, systemName: null); + + expect(provider.customTasks, hasLength(1)); + expect(provider.detectedTasks, isEmpty); + }); + + test('用户探测并发合并:连续 50 次触发只做 1~2 次磁盘读取,且最后一次编辑生效', () async { + final storage = _CountingStorage(); + final provider = buildProvider(storage); + + const finalTask = RunTask( + id: 'user_final', + name: 'final', + command: 'echo', + source: TaskSource.custom, + ); + await storage.saveConfig(projectRoot: projectDir.path, tasks: [finalTask]); + + // 模拟"用户瞬间编辑了几十次":紧循环触发(两次调用之间不 await,才能形成真正的并发重叠) + final futures = >[]; + for (var i = 0; i < 50; i++) { + futures.add(provider.probeUser(projectRoot: projectDir.path)); + } + await Future.wait(futures); + // 合并后可能还有一次补跑,多等一拍 + await Future.delayed(const Duration(milliseconds: 50)); + + expect(storage.loadCount, lessThanOrEqualTo(2), + reason: '并发合并应把 50 次触发压缩为 1~2 次磁盘读取'); + // 内存中的用户任务等于磁盘上的最终内容(覆盖语义) + expect(provider.customTasks.map((t) => t.id), ['user_final']); + }); + + test('编辑用户任务:先写盘再用户探测,内存 user 格被磁盘内容覆盖', () async { + final storage = RunTaskStorageService(); + final provider = buildProvider(storage); + await provider.probeProject(projectRoot: projectDir.path, systemName: systemName); + + const edited = RunTask( + id: 'user_custom_1', + name: 'My Custom Run', + command: 'echo "custom"', + source: TaskSource.custom, + ); + await provider.addCustomTask(edited); + expect(provider.customTasks.any((t) => t.id == 'user_custom_1'), isTrue); + + // 直接从磁盘读回的持久化结果应与内存一致 + final persisted = await storage.loadConfig(projectDir.path); + expect(persisted.tasks.map((t) => t.id), ['user_custom_1']); + }); + + test('"上一次执行任务"同样走磁盘并同步内存(任务被删除时不再命中)', () async { + final storage = RunTaskStorageService(); + final provider = buildProvider(storage); + await provider.probeProject(projectRoot: projectDir.path, systemName: systemName); + + const userTask = RunTask( + id: 'user_run_me', + name: 'run me', + command: 'echo', + source: TaskSource.custom, + ); + await provider.addCustomTask(userTask); + await provider.setLastRunTask(userTask); + expect(provider.lastRunTask?.id, 'user_run_me'); + expect((await storage.loadConfig(projectDir.path)).lastRunTaskId, 'user_run_me'); + + // 删除该任务后再探一次:id 仍在,但内存对象不再命中 + await provider.removeCustomTask('user_run_me'); + expect(provider.customTasks, isEmpty); + expect(provider.lastRunTask, isNull); + }); + + test('requestProjectProbe:探测进行中时拒绝并返回 false', () async { + final storage = RunTaskStorageService(); + final provider = buildProvider(storage); + + // 构造一个"慢模块",让探测保持在 isDetecting 状态 + final slowDispatcher = ProjectTaskDispatcher(customModules: [ + _SlowModule('gradle'), + ]); + final slowProvider = RunProvider( + storageService: storage, + dispatcher: slowDispatcher, + distroManager: distroManager, + ); + + final running = slowProvider.probeProject( + projectRoot: projectDir.path, + systemName: systemName, + ); + await Future.delayed(const Duration(milliseconds: 30)); + expect(slowProvider.isDetecting, isTrue); + + final started = await slowProvider.requestProjectProbe( + projectRoot: projectDir.path, + systemName: systemName, + ); + expect(started, isFalse, reason: '已有探测在进行时应拒绝新的探测请求'); + + await running; + expect(slowProvider.isDetecting, isFalse); + // 未使用的 provider 不影响断言 + expect(provider.isDetecting, isFalse); + }); + }); +} + +/// 慢模块:让探测持续一段时间,便于观察 isDetecting +class _SlowModule extends ProjectModule { + @override + final String id; + + _SlowModule(this.id); + + @override + String get displayName => id; + + @override + List get triggerFiles => const []; + + @override + bool shouldActivate(Directory projectDir) => true; + + @override + Future probe(ProjectProbe probe) async { + await Future.delayed(const Duration(milliseconds: 200)); + return ModuleProbeResult.ok(id, const []); + } +} diff --git a/test/run_system_test.dart b/test/run_system_test.dart index 72fa111..9909050 100644 --- a/test/run_system_test.dart +++ b/test/run_system_test.dart @@ -2,33 +2,59 @@ import 'dart:io'; 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:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/notice_item.dart'; import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/providers/notice_center.dart'; import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/services/distro_manager.dart'; import 'package:code_editor/services/run_task_storage_service.dart'; -import 'package:code_editor/services/project_task_detector.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; +import 'package:code_editor/widgets/notice_host.dart'; import 'package:code_editor/widgets/run_tasks_dialog.dart'; +/// 单测用的假系统名(探测必须基于"真实可用系统",单测里用假 rootfs 代替真容器) +const String kTestSystemName = 'test_sys'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('RunTask & RunTaskStorageService Tests', () { late Directory tempDir; late RunTaskStorageService storageService; + late Directory distroBaseDir; + late DistroManager distroManager; setUp(() async { tempDir = await Directory.systemTemp.createTemp('run_task_test_'); storageService = RunTaskStorageService(); + + // 构造一个已安装就绪的假系统://rootfs/{etc,bin} + // 并放入各模块所需工具链的桩文件(依赖检测走宿主 rootfs 快速判定) + distroBaseDir = await Directory.systemTemp.createTemp('run_task_distro_'); + final rootfs = Directory(p.join(distroBaseDir.path, kTestSystemName, 'rootfs')); + Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true); + Directory(p.join(rootfs.path, 'bin')).createSync(recursive: true); + final usrBin = Directory(p.join(rootfs.path, 'usr', 'bin'))..createSync(recursive: true); + for (final binary in ['java', 'gradle', 'cmake', 'make', 'npm', 'node', 'cargo']) { + File(p.join(usrBin.path, binary)).writeAsStringSync('#!/bin/sh\n'); + } + distroManager = DistroManager()..customBaseDir = distroBaseDir; }); tearDown(() async { + DistroManager().customBaseDir = null; if (await tempDir.exists()) { await tempDir.delete(recursive: true); } + if (await distroBaseDir.exists()) { + await distroBaseDir.delete(recursive: true); + } }); test('save and load custom tasks', () async { - final initialTasks = await storageService.loadTasks(tempDir.path); + final initialTasks = (await storageService.loadConfig(tempDir.path)).tasks; expect(initialTasks, isEmpty); final customTask = const RunTask( @@ -40,9 +66,9 @@ void main() { clearBeforeRun: true, ); - await storageService.saveTasks(tempDir.path, [customTask]); + await storageService.saveConfig(projectRoot: tempDir.path, tasks: [customTask]); - final loadedTasks = await storageService.loadTasks(tempDir.path); + final loadedTasks = (await storageService.loadConfig(tempDir.path)).tasks; expect(loadedTasks.length, 1); expect(loadedTasks.first.id, 'task_1'); expect(loadedTasks.first.name, 'Debug Build'); @@ -60,7 +86,7 @@ void main() { expect(config.tasks.length, 1); }); - test('ProjectTaskDetector detects CMake and single file', () async { + test('任务探测:CMake + 单文件任务', () async { // 模拟 CMakeLists.txt final cmakeFile = File('${tempDir.path}/CMakeLists.txt'); await cmakeFile.writeAsString('cmake_minimum_required(VERSION 3.10)'); @@ -69,9 +95,11 @@ void main() { final pyFile = File('${tempDir.path}/main.py'); await pyFile.writeAsString('print("hello")'); - final tasks = await ProjectTaskDetector.detect( + final tasks = await ProjectTaskDispatcher.instance.detect( projectRoot: tempDir.path, currentFilePath: pyFile.path, + systemName: kTestSystemName, + distroManager: distroManager, ); expect(tasks.isNotEmpty, isTrue); @@ -84,7 +112,7 @@ void main() { expect(tasks.any((t) => t.id == 'detected_cmake_clean'), isTrue); }); - test('ProjectTaskDetector detects Makefile, Gradle, Cargo, NPM, Dart and source files', () async { + test('任务探测:Makefile / Cargo / NPM / Dart / 单文件(Gradle 只认真实自省)', () async { final makefile = File('${tempDir.path}/Makefile'); await makefile.writeAsString('all:\n\tgcc main.c\n'); @@ -92,7 +120,7 @@ void main() { await cargoToml.writeAsString('[package]\nname = "demo"\n'); final packageJson = File('${tempDir.path}/package.json'); - await packageJson.writeAsString('{"name": "demo"}'); + await packageJson.writeAsString('{"name": "demo", "scripts": {"start": "node index.js", "test": "jest"}}'); final pubspec = File('${tempDir.path}/pubspec.yaml'); await pubspec.writeAsString('name: demo\n'); @@ -103,9 +131,11 @@ void main() { final cppFile = File('${tempDir.path}/main.cpp'); await cppFile.writeAsString('int main() { return 0; }'); - final tasks = await ProjectTaskDetector.detect( + final tasks = await ProjectTaskDispatcher.instance.detect( projectRoot: tempDir.path, currentFilePath: cppFile.path, + systemName: kTestSystemName, + distroManager: distroManager, ); expect(tasks.any((t) => t.id == 'detected_single_cpp'), isTrue); @@ -114,7 +144,10 @@ void main() { expect(tasks.any((t) => t.id == 'detected_cargo_run'), isTrue); expect(tasks.any((t) => t.id == 'detected_npm_start'), isTrue); expect(tasks.any((t) => t.id == 'detected_dart_run'), isTrue); - expect(tasks.any((t) => t.id == 'detected_gradle_run'), isTrue); + // Gradle 只认真实自省结果:测试环境无法真正执行 gradle,因此不产出任何 Gradle 任务, + // 更不允许出现任何硬编码兜底任务(detected_gradle_*) + expect(tasks.any((t) => t.id.startsWith('detected_gradle_')), isFalse); + expect(tasks.any((t) => t.moduleId == 'gradle'), isFalse); }); }); @@ -407,6 +440,120 @@ void main() { expect(runProvider.lastRunTaskId, isNull); expect(runProvider.allTasks, isEmpty); }); + + testWidgets('RunTasksDialog: 任务类型折叠 Tile 自由切换且在内存中保持折叠状态', (tester) async { + const detectedTasks = [ + RunTask( + id: 'detected_gradle_run', + name: 'Gradle: Run', + command: 'sh ./gradlew run', + source: TaskSource.detected, + moduleId: 'gradle', + group: 'mod development/internal', + ), + ]; + + Widget buildDialog() { + return MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('zh'), Locale('en')], + locale: const Locale('zh'), + home: Scaffold( + body: RunTasksDialog( + customTasks: const [], + detectedTasks: detectedTasks, + onTaskSelected: (_) {}, + onEditCustomTasks: () {}, + ), + ), + ); + } + + // 1. 初次渲染,任务正常显示 + await tester.pumpWidget(buildDialog()); + await tester.pumpAndSettle(); + expect(find.text('Gradle: Run'), findsOneWidget); + + // 2. 点击 Gradle 折叠 tile 头部将其收起 + await tester.tap(find.text('Gradle')); + await tester.pumpAndSettle(); + expect(find.text('Gradle: Run'), findsNothing); + + // 3. 模拟关闭并重新打开 Dialog(重建 widget) + await tester.pumpWidget(buildDialog()); + await tester.pumpAndSettle(); + // 折叠状态由内存持久化维持,依然处于收起状态 + expect(find.text('Gradle: Run'), findsNothing); + + // 4. 再次点击重新展开 + await tester.tap(find.text('Gradle')); + await tester.pumpAndSettle(); + expect(find.text('Gradle: Run'), findsOneWidget); + }); + + testWidgets('NoticeHost 卡片视觉:成功时背景为绿色,失败时为红色描边', (tester) async { + final center = NoticeCenter(); + + 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: Scaffold( + body: NoticeHost(center: center), + ), + ), + ); + + // 1. 推送成功通知 + center.push(const NoticeItem( + id: 'success_notice', + kind: NoticeKind.success, + text: ModuleDoneText('Gradle', taskCount: 3), + )); + await tester.pumpAndSettle(); + + final successMaterial = tester.widget( + find.ancestor( + of: find.textContaining('Gradle'), + matching: find.byType(Material), + ).first, + ); + // 成功卡片背景为深绿或绿色 + expect(successMaterial.color, equals(const Color(0xFF2E7D32))); + + // 2. 推送失败通知 + center.push(const NoticeItem( + id: 'failure_notice', + kind: NoticeKind.failure, + text: ModuleFailureText( + moduleDisplayName: 'CMake', + failure: NoticeFailure.executionFailed, + ), + )); + await tester.pumpAndSettle(); + + final failureMaterial = tester.widget( + find.ancestor( + of: find.textContaining('CMake'), + matching: find.byType(Material), + ).first, + ); + final shape = failureMaterial.shape as RoundedRectangleBorder; + // 失败卡片有红色描边 + expect(shape.side.color, equals(const Color(0xFFE53935))); + expect(shape.side.width, equals(1.5)); + }); }); } diff --git a/test/terminal_entry_guard_test.dart b/test/terminal_entry_guard_test.dart new file mode 100644 index 0000000..d6705d5 --- /dev/null +++ b/test/terminal_entry_guard_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/widgets/terminal_entry_guard.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + /// 挂一个按钮调用守卫,把返回值记录下来(无需真正进入终端 view) + Future pumpGuard(WidgetTester tester, List results) async { + await tester.pumpWidget( + MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => Center( + child: ElevatedButton( + onPressed: () async { + results.add(await confirmEnterTerminalWhileProbing(context)); + }, + child: const Text('terminal'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + group('进入终端前的探测占用确认', () { + testWidgets('文案与按钮来自 l10n,取消 => 不进入终端', (tester) async { + final results = []; + await pumpGuard(tester, results); + + await tester.tap(find.text('terminal')); + await tester.pumpAndSettle(); + + expect(find.text('任务探测进行中'), findsOneWidget); + expect(find.textContaining('是否仍要进入终端?'), findsOneWidget); + expect(find.text('继续进入终端'), findsOneWidget); + + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + + expect(results, [false], reason: '取消必须返回 false(不进入终端)'); + }); + + testWidgets('继续进入终端 => 返回 true', (tester) async { + final results = []; + await pumpGuard(tester, results); + + await tester.tap(find.text('terminal')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('继续进入终端')); + await tester.pumpAndSettle(); + + expect(results, [true]); + }); + + testWidgets('点弹窗外部关闭 => 按取消处理(保守不进入)', (tester) async { + final results = []; + await pumpGuard(tester, results); + + await tester.tap(find.text('terminal')); + await tester.pumpAndSettle(); + + // 点击对话框外的遮罩区域 + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + expect(results, [false]); + }); + }); +} diff --git a/test/terminal_font_size_and_gesture_test.dart b/test/terminal_font_size_and_gesture_test.dart index ef8dadd..0827da6 100644 --- a/test/terminal_font_size_and_gesture_test.dart +++ b/test/terminal_font_size_and_gesture_test.dart @@ -1,11 +1,9 @@ import 'dart:ui'; import 'package:code_editor/l10n/app_localizations.dart'; -import 'package:code_editor/models/terminal_session.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; import 'package:code_editor/views/settings_view.dart'; import 'package:code_editor/views/terminal_view.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -277,6 +275,7 @@ void main() { expect(termView.controller?.selection, isNotNull); expect(termView.controller?.selection!.isCollapsed, isFalse); expect(textInputShowCount, 0, reason: 'Long press must not show soft keyboard'); + expect(textInputAttachCount, greaterThanOrEqualTo(0)); // 3. Lift finger: Floating menu (复制, 粘贴, 全选) should appear await gesture.up(); diff --git a/test/widget_test.dart b/test/widget_test.dart index 6cdfa99..1020bb6 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,4 +1,5 @@ import 'dart:io'; +import 'dart:ui'; import 'package:re_editor/re_editor.dart'; import 'package:code_editor/models/app_font.dart'; import 'package:code_editor/models/editor_tab_item.dart'; @@ -3638,6 +3639,62 @@ void main() { expect(scrollController.horizontalScroller.offset, 50.0); }); + + testWidgets('CodeEditor continuous bidirectional gesture scrolls horizontally then vertically without lifting finger', (tester) async { + final text = List.generate(50, (i) => 'Line $i: const aLongVariableNameThatIsVeryLong = 1234567890 + 987654321;').join('\n'); + final controller = CodeLineEditingController.fromText(text); + final scrollController = CodeScrollController(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 300, + height: 400, + child: CodeEditor( + controller: controller, + scrollController: scrollController, + wordWrap: false, + pinLineNumbers: false, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(scrollController.horizontalScroller.offset, 0.0); + expect(scrollController.verticalScroller.offset, 0.0); + + // Start drag gesture with touch + final gesture = await tester.startGesture(const Offset(200, 200), kind: PointerDeviceKind.touch); + // Exceed touch slop to trigger onStart + await gesture.moveBy(const Offset(-30, 0)); + // Subsequent movement triggers onUpdate + await gesture.moveBy(const Offset(-60, 0)); + await tester.pump(); + + expect(scrollController.horizontalScroller.offset, greaterThan(0.0)); + final hOffsetAfterHorizontal = scrollController.horizontalScroller.offset; + + // Now scroll vertically without lifting finger + await gesture.moveBy(const Offset(0, -60)); + await tester.pump(); + + expect(scrollController.verticalScroller.offset, greaterThan(0.0)); + // Horizontal offset should still be preserved + expect(scrollController.horizontalScroller.offset, closeTo(hOffsetAfterHorizontal, 1.0)); + + // Diagonal movement scrolls both + await gesture.moveBy(const Offset(-30, -30)); + await tester.pump(); + + expect(scrollController.horizontalScroller.offset, greaterThan(hOffsetAfterHorizontal)); + expect(scrollController.verticalScroller.offset, greaterThan(50.0)); + + await gesture.up(); + await tester.pumpAndSettle(); + }); }); }