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