This commit is contained in:
LZX committed 2026-09-16 20:43:39 +08:00
1 parent 5efc778165
commit 59125d185c
64 files changed
+7912 -1393

No files matched your search

+63 -3
View File
@@ -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<List<String>> 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<ProcessResult?> 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 = <int>[];
final stderrBytes = <int>[];
final stdoutFuture = process.stdout.listen(stdoutBytes.addAll).asFuture<void>();
final stdoutFuture = process.stdout.listen((chunk) {
stdoutBytes.addAll(chunk);
if (onStdout != null && chunk.isNotEmpty) {
try {
onStdout(utf8.decode(chunk, allowMalformed: true));
} catch (_) {}
}
}).asFuture<void>();
final stderrFuture = process.stderr.listen(stderrBytes.addAll).asFuture<void>();
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);
+3 -3
View File
@@ -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<String> _getUniqueTargetPath(String originalPath, bool isDirectory) async {
Future<String> getUniqueTargetPath(String originalPath, bool isDirectory) async {
if(!await FileSystemEntity.isDirectory(originalPath) &&
!await FileSystemEntity.isFile(originalPath)) {
return originalPath;
@@ -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<String> get triggerFiles => const ['Cargo.toml'];
@override
bool shouldActivate(Directory projectDir) =>
File(p.join(projectDir.path, 'Cargo.toml')).existsSync();
@override
List<String> get requiredToolchainKeys => const ['cargo'];
@override
Future<ModuleProbeResult> 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<String> _declaredBinaryNames(Directory projectDir) {
try {
final file = File(p.join(projectDir.path, 'Cargo.toml'));
if (!file.existsSync()) return const [];
final content = file.readAsStringSync();
final names = <String>[];
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 [];
}
}
}
@@ -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<String> get triggerFiles => const ['CMakeLists.txt'];
@override
bool shouldActivate(Directory projectDir) =>
File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync();
@override
List<String> get requiredToolchainKeys => const ['cmake'];
@override
Future<ModuleProbeResult> 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;
}
}
}
@@ -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<String> get triggerFiles => const ['pubspec.yaml'];
@override
bool shouldActivate(Directory projectDir) =>
File(p.join(projectDir.path, 'pubspec.yaml')).existsSync();
/// Dart SDK 目前没有可用的发行版一键安装命令,因此不做自动补全,
/// 仅在探测阶段如实报告"未找到 dart"。
@override
Future<ModuleProbeResult> 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,
),
]);
}
}
@@ -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<GradleIdeProject> 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<String, dynamic> 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 = <GradleIdeProject>[];
if (rawProjects is List) {
for (final item in rawProjects) {
if (item is Map) {
projects.add(GradleIdeProject.fromJson(Map<String, dynamic>.from(item)));
}
}
}
return GradleIdeModel(
schema: schema,
gradleVersion: json['gradleVersion']?.toString(),
rootProject: json['rootProject']?.toString() ?? '',
projects: projects,
error: json['error']?.toString(),
);
}
/// 转换为可执行任务列表
List<RunTask> toRunTasks(String execCmd) {
final tasks = <RunTask>[];
final seen = <String>{};
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<String> plugins;
final List<String> sourceSets;
final List<String> configurations;
final String? javaVersion;
final List<GradleIdeTask> 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<String, dynamic> 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<String, dynamic>.from(item)),
],
);
}
static List<String> _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<String, dynamic> json) {
return GradleIdeTask(
name: json['name']?.toString() ?? '',
path: json['path']?.toString() ?? '',
group: json['group']?.toString(),
description: json['description']?.toString(),
type: json['type']?.toString(),
);
}
}
@@ -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<String> get requiredToolchainKeys => const ['gradle'];
@override
List<String> 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<List<RunTask>> 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<void> 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<ModuleProbeResult> 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<RunTask> parseGradleTasksOutput(String output, String execCmd) {
final List<RunTask> 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<String, dynamic>.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 <RunTask>[]);
}
/// 兜底默认任务集(在未联网同步真实任务前呈现)
static List<RunTask> 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<void> _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<ProcessResult?> _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)}';
}
}
@@ -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<String> get triggerFiles => const ['Makefile'];
@override
bool shouldActivate(Directory projectDir) =>
File(p.join(projectDir.path, 'Makefile')).existsSync();
@override
List<String> get requiredToolchainKeys => const ['make'];
@override
Future<ModuleProbeResult> 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<String> _readTargets(Directory projectDir) {
try {
final file = File(p.join(projectDir.path, 'Makefile'));
if (!file.existsSync()) return const [];
final result = <String>[];
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 [];
}
}
}
@@ -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<String> get triggerFiles => const ['package.json'];
@override
bool shouldActivate(Directory projectDir) =>
File(p.join(projectDir.path, 'package.json')).existsSync();
@override
List<String> get requiredToolchainKeys => const ['npm'];
@override
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
final scripts = _readScripts(probe.projectDir);
if (scripts.isEmpty) {
return ModuleProbeResult.ok(id, const <RunTask>[]);
}
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<String> _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;
}
}
@@ -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<ProcessResult?> 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<String> get triggerFiles;
/// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否,不进行深层解析)
/// 是否支持"重新同步真实任务"
bool get supportsResync => false;
/// 需要的工具链依赖 key(对应 [ToolchainService.supportedTools] 的键)
List<String> get requiredToolchainKeys => const [];
/// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否)
bool shouldActivate(Directory projectDir);
/// 探测项目任务(支持优先读取本地缓存;当 forceRefresh=true 时强制发起真实探测)
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false});
/// 环境准备(写探测脚本、准备临时目录等),在依赖检测前执行。默认无操作。
Future<void> prepare(ProjectProbe probe) async {}
/// 依赖检测:返回缺失的依赖 key 列表。默认实现按 [requiredToolchainKeys] 逐个检查。
Future<List<String>> checkDependencies(ProjectProbe probe) async {
final missing = <String>[];
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<bool> installDependencies(ProjectProbe probe, List<String> missing) {
return probe.installToolchains(missing);
}
/// 执行探测(结构化结果)
Future<ModuleProbeResult> probe(ProjectProbe probe);
}
@@ -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<ProbeModuleRef> 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<RunTask> tasks;
/// 失败分类(用于 l10n 文案),status != failed 时为 null
final NoticeFailure? failure;
/// 失败细节:缺失的工具名、stderr 末尾等(技术信息,允许原样展示)
final String? failureDetail;
const ModuleProbeResult._({
required this.moduleId,
required this.status,
this.tasks = const <RunTask>[],
this.failure,
this.failureDetail,
});
const ModuleProbeResult.ok(String moduleId, List<RunTask> 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<RunTask> detectedTasks;
final Map<String, ModuleProbeResult> 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 <RunTask>[],
moduleResults: const <String, ModuleProbeResult>{},
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<ProbeProgress?> progress;
/// 安装过程最后一行输出(供弹窗副标题显示安装进度)
final ValueNotifier<String?> installLine;
bool _disposed = false;
DateTime? _deadline;
ProjectProbe({
required this.request,
required this.distroManager,
this.budget = defaultBudget,
HeadlessCancelToken? cancelToken,
ValueNotifier<ProbeProgress?>? progress,
ValueNotifier<String?>? installLine,
}) : cancelToken = cancelToken ?? HeadlessCancelToken(),
progress = progress ?? ValueNotifier<ProbeProgress?>(null),
installLine = installLine ?? ValueNotifier<String?>(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<ProcessResult?> 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<bool> 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<bool> 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<bool> installToolchains(List<String> 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 = <String>[];
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();
}
}
@@ -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<String> 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;
}
}
}
@@ -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<String> get triggerFiles => const ['CMakeLists.txt'];
@override
bool shouldActivate(Directory projectDir) {
return File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync();
}
@override
Future<List<RunTask>> 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<String> get triggerFiles => const ['Cargo.toml'];
@override
bool shouldActivate(Directory projectDir) {
return File(p.join(projectDir.path, 'Cargo.toml')).existsSync();
}
@override
Future<List<RunTask>> 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<String> get triggerFiles => const ['package.json'];
@override
bool shouldActivate(Directory projectDir) {
return File(p.join(projectDir.path, 'package.json')).existsSync();
}
@override
Future<List<RunTask>> 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<String> get triggerFiles => const ['Makefile'];
@override
bool shouldActivate(Directory projectDir) {
return File(p.join(projectDir.path, 'Makefile')).existsSync();
}
@override
Future<List<RunTask>> 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<String> get triggerFiles => const ['pubspec.yaml'];
@override
bool shouldActivate(Directory projectDir) {
return File(p.join(projectDir.path, 'pubspec.yaml')).existsSync();
}
@override
Future<List<RunTask>> 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';
-19
View File
@@ -1,19 +0,0 @@
import '../models/run_task.dart';
import 'project_task_dispatcher.dart';
/// 负责根据工程文件和当前打开的文件,在内存中动态推导可用的运行任务
/// (现已接入模块化 ProjectTaskDispatcher 总调度器,保持向后 100% 兼容)
class ProjectTaskDetector {
/// 核心探测入口
/// [projectRoot]: 工程根目录(宿主绝对路径)
/// [currentFilePath]: 当前编辑器激活打开的文件(宿主绝对路径,可能为 null)
static Future<List<RunTask>> detect({
required String projectRoot,
String? currentFilePath,
}) {
return ProjectTaskDispatcher.instance.detect(
projectRoot: projectRoot,
currentFilePath: currentFilePath,
);
}
}
+277 -190
View File
@@ -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<ProjectModule> getActiveModules(Directory projectDir) {
return _modules.where((m) => m.shouldActivate(projectDir)).toList();
/// 当前项目中所有被激活的模块(模块发现阶段)
List<ProjectModule> 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<ProjectProbeReport> 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<ProjectModule>()..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 = <String, ModuleProbeResult>{};
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 <RunTask>[]);
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 = <RunTask>[];
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 <RunTask>[] : tasks,
moduleResults: results,
finishedAt: DateTime.now(),
totalModules: refs.length,
abortedByBudget: abortedByBudget,
);
}
List<ProjectModule> _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<List<RunTask>> detect({
required String projectRoot,
String? currentFilePath,
String systemName = 'ubuntu',
RunTaskStorageService? storageService,
String? systemName,
DistroManager? distroManager,
bool forceRefresh = false,
String? onlyModuleId,
}) async {
final List<RunTask> 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 <RunTask>[];
}
}),
);
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<List<RunTask>> syncModule({
/// 单模块重新同步(系统探测的特例:只跑一个模块)
Future<ProjectProbeReport> 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<bool> 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);
}
+14 -9
View File
@@ -56,12 +56,6 @@ class RunTaskStorageService {
}
}
/// 兼容旧方法:直接返回 tasks
Future<List<RunTask>> loadTasks(String projectRoot) async {
final result = await loadConfig(projectRoot);
return result.tasks;
}
/// 将自定义任务列表与最近运行的任务ID持久化保存到 `.code_editor/run_tasks.json`
Future<void> saveConfig({
required String projectRoot,
@@ -93,9 +87,20 @@ class RunTaskStorageService {
}
}
/// 兼容旧方法
Future<void> saveTasks(String projectRoot, List<RunTask> tasks) async {
await saveConfig(projectRoot: projectRoot, tasks: tasks);
/// 只更新"最近执行任务 id",**完整保留磁盘上已有的用户任务**。
///
/// 边界:不能用内存里的任务列表去覆盖磁盘——内存可能是"尚未加载完/已被清空"的状态
/// (例如刚打开工程就立刻点了运行),那会把用户已保存的任务清空。
Future<void> 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`)