This commit is contained in:
LZX committed 2026-09-15 16:59:50 +08:00
1 parent b49e096355
commit 63e1fe3861
48 files changed
+5817 -556

No files matched your search

+541
View File
@@ -0,0 +1,541 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:path/path.dart' as p;
import 'archive_extractor.dart';
/// 用户或外部取消压缩异常
class ArchiveCompressCancelledException implements Exception {
final String message;
ArchiveCompressCancelledException([this.message = '压缩操作已取消']);
@override
String toString() => message;
}
/// 内部 CRC-32 表(IEEE 802.3 标准多项式 0xEDB88320)
final List<int> _crcTable = List<int>.generate(256, (i) {
var c = i;
for (var k = 0; k < 8; k++) {
c = (c & 1) != 0 ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
}
return c;
});
/// 高性能增量 CRC-32 校验和计算
int computeCrc32(List<int> bytes, [int crc = 0]) {
crc = crc ^ 0xffffffff;
for (var i = 0; i < bytes.length; i++) {
crc = _crcTable[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
}
return crc ^ 0xffffffff;
}
int _dosTime(DateTime dt) {
return ((dt.hour & 0x1f) << 11) |
((dt.minute & 0x3f) << 5) |
((dt.second ~/ 2) & 0x1f);
}
int _dosDate(DateTime dt) {
final year = dt.year < 1980 ? 1980 : (dt.year > 2107 ? 2107 : dt.year);
return (((year - 1980) & 0x7f) << 9) |
((dt.month & 0x0f) << 5) |
(dt.day & 0x1f);
}
class _ZipEntryRecord {
final String name;
final int time;
final int date;
final int crc32;
final int compressedSize;
final int uncompressedSize;
final int method;
final int localHeaderOffset;
final bool isDirectory;
const _ZipEntryRecord({
required this.name,
required this.time,
required this.date,
required this.crc32,
required this.compressedSize,
required this.uncompressedSize,
required this.method,
required this.localHeaderOffset,
required this.isDirectory,
});
}
class _CompressIsolateParams {
final String sourceDirPath;
final String targetZipPath;
final SendPort sendPort;
const _CompressIsolateParams({
required this.sourceDirPath,
required this.targetZipPath,
required this.sendPort,
});
}
class _RafChunkSink implements Sink<List<int>> {
final RandomAccessFile raf;
int bytesWritten = 0;
_RafChunkSink(this.raf);
@override
void add(List<int> chunk) {
if (chunk.isNotEmpty) {
raf.writeFromSync(chunk);
bytesWritten += chunk.length;
}
}
@override
void close() {}
}
/// 通用自研低内存流式 ZIP 压缩引擎
///
/// 解决原生 package:archive/ZipFileEncoder 在大项目或海量小文件时
/// 触发并发读取与全量大内存缓冲导致的 OOM (Out Of Memory) 崩溃。
///
/// 特性:
/// 1. 严格遵循 PKZIP 标准;
/// 2. 64KB 分块流式直写落盘,内存恒定在 < 15MB;
/// 3. 支持 Local File Header 占位与精确尺寸/CRC-32 回填;
/// 4. 独立后台 Worker Isolate 运行,零 UI 冻结;
/// 5. 支持实时进度回调与安全取消(清理残余半成品文件)。
class ArchiveCompressor {
/// 将 [sourceDir] 目录下的所有文件和文件夹打包流式压缩为 ZIP 文件 [targetZipFile]
static Future<void> zipDirectory({
required Directory sourceDir,
required File targetZipFile,
ArchiveProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
if (isCancelled?.call() == true) {
throw ArchiveCompressCancelledException();
}
if (!sourceDir.existsSync()) {
throw ArgumentError('源目录不存在: ${sourceDir.path}');
}
onProgress?.call(0.01, '正在准备压缩...');
// 确保目标父目录存在
final parentDir = targetZipFile.parent;
if (!parentDir.existsSync()) {
parentDir.createSync(recursive: true);
}
// 若目标文件已存在先删除旧文件
if (targetZipFile.existsSync()) {
try {
targetZipFile.deleteSync();
} catch (_) {}
}
final receivePort = ReceivePort();
final exitPort = ReceivePort();
final completer = Completer<void>();
Isolate? isolate;
Timer? cancelTimer;
try {
isolate = await Isolate.spawn<_CompressIsolateParams>(
_compressIsolateEntry,
_CompressIsolateParams(
sourceDirPath: sourceDir.path,
targetZipPath: targetZipFile.path,
sendPort: receivePort.sendPort,
),
);
isolate.addOnExitListener(exitPort.sendPort);
exitPort.listen((_) {
if (!completer.isCompleted) {
completer.completeError(Exception('压缩 Worker Isolate 意外退出'));
}
});
cancelTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {
if (isCancelled?.call() == true) {
isolate?.kill(priority: Isolate.immediate);
if (!completer.isCompleted) {
completer.completeError(ArchiveCompressCancelledException());
}
}
});
receivePort.listen((message) {
if (message is List) {
final type = message[0] as int;
if (type == 0) {
// 进度通知: [0, progress(0.0~1.0), message]
final prog = message[1] as double;
final msg = message[2] as String;
onProgress?.call(prog, msg);
} else if (type == 1) {
// 成功完成: [1]
if (!completer.isCompleted) {
completer.complete();
}
} else if (type == 3) {
// 失败错误: [3, errorMessage]
if (!completer.isCompleted) {
completer.completeError(Exception(message[1].toString()));
}
}
}
});
await completer.future;
} catch (e) {
if (targetZipFile.existsSync()) {
try {
targetZipFile.deleteSync();
} catch (_) {}
}
rethrow;
} finally {
cancelTimer?.cancel();
receivePort.close();
exitPort.close();
isolate?.kill(priority: Isolate.immediate);
}
}
/// 后台 Worker Isolate 执行入口
static Future<void> _compressIsolateEntry(_CompressIsolateParams params) async {
final sendPort = params.sendPort;
final sourceDir = Directory(params.sourceDirPath);
final targetFile = File(params.targetZipPath);
RandomAccessFile? raf;
try {
sendPort.send([0, 0.05, '正在扫描工程文件列表...']);
final targetCanonical = p.canonicalize(targetFile.path);
final sourceCanonical = p.canonicalize(sourceDir.path);
// 递归收集所有实体,按目录结构排布
final entities = <FileSystemEntity>[];
for (final entity in sourceDir.listSync(recursive: true, followLinks: false)) {
// 避免把正在写入的 zip 文件自身扫描进去
if (p.canonicalize(entity.path) == targetCanonical) {
continue;
}
entities.add(entity);
}
// 按字典序排序保持构建一致性
entities.sort((a, b) => a.path.compareTo(b.path));
final total = entities.length;
sendPort.send([0, 0.10, '开始流式压缩...']);
raf = targetFile.openSync(mode: FileMode.write);
final entries = <_ZipEntryRecord>[];
final readBuffer = Uint8List(64 * 1024);
for (var i = 0; i < total; i++) {
final entity = entities[i];
var relPath = p.relative(entity.path, from: sourceCanonical).replaceAll('\\', '/');
if (relPath.startsWith('./')) {
relPath = relPath.substring(2);
}
final stat = entity.statSync();
final modTime = stat.modified;
final dosT = _dosTime(modTime);
final dosD = _dosDate(modTime);
if (entity is Directory) {
if (!relPath.endsWith('/')) {
relPath = '$relPath/';
}
final nameBytes = utf8.encode(relPath);
final localHeaderOffset = raf.positionSync();
// 写入 Local File Header(目录使用 Store,0 字节内容)
_writeLocalHeader(
raf: raf,
method: 0,
dosTime: dosT,
dosDate: dosD,
crc32: 0,
compressedSize: 0,
uncompressedSize: 0,
nameBytes: nameBytes,
);
entries.add(_ZipEntryRecord(
name: relPath,
time: dosT,
date: dosD,
crc32: 0,
compressedSize: 0,
uncompressedSize: 0,
method: 0,
localHeaderOffset: localHeaderOffset,
isDirectory: true,
));
} else if (entity is File) {
final fileSize = stat.size;
final nameBytes = utf8.encode(relPath);
final localHeaderOffset = raf.positionSync();
if (fileSize == 0) {
// 空文件无需压缩,使用 Store 模式
_writeLocalHeader(
raf: raf,
method: 0,
dosTime: dosT,
dosDate: dosD,
crc32: 0,
compressedSize: 0,
uncompressedSize: 0,
nameBytes: nameBytes,
);
entries.add(_ZipEntryRecord(
name: relPath,
time: dosT,
date: dosD,
crc32: 0,
compressedSize: 0,
uncompressedSize: 0,
method: 0,
localHeaderOffset: localHeaderOffset,
isDirectory: false,
));
} else {
// 写入占位 Local File Header (待压缩完成后回填 CRC 和压缩后大小)
_writeLocalHeader(
raf: raf,
method: 8, // Deflate
dosTime: dosT,
dosDate: dosD,
crc32: 0,
compressedSize: 0,
uncompressedSize: fileSize,
nameBytes: nameBytes,
);
// 流式分块压缩直写
final fileRaf = entity.openSync(mode: FileMode.read);
var crc = 0;
var uncompressedBytes = 0;
final chunkSink = _RafChunkSink(raf);
final deflateSink = ZLibEncoder(raw: true, level: 6).startChunkedConversion(chunkSink);
try {
while (true) {
final bytesRead = fileRaf.readIntoSync(readBuffer);
if (bytesRead <= 0) break;
final view = Uint8List.sublistView(readBuffer, 0, bytesRead);
crc = computeCrc32(view, crc);
uncompressedBytes += bytesRead;
deflateSink.add(view);
}
} finally {
deflateSink.close();
fileRaf.closeSync();
}
final compressedBytes = chunkSink.bytesWritten;
final endPos = raf.positionSync();
// 回退到 Local Header 的 crc32 位置 (localHeaderOffset + 14) 回填元数据
raf.setPositionSync(localHeaderOffset + 14);
final fixHeader = ByteData(12);
fixHeader.setUint32(0, crc, Endian.little);
fixHeader.setUint32(4, compressedBytes, Endian.little);
fixHeader.setUint32(8, uncompressedBytes, Endian.little);
raf.writeFromSync(fixHeader.buffer.asUint8List());
// 恢复指针到写入末尾
raf.setPositionSync(endPos);
entries.add(_ZipEntryRecord(
name: relPath,
time: dosT,
date: dosD,
crc32: crc,
compressedSize: compressedBytes,
uncompressedSize: uncompressedBytes,
method: 8,
localHeaderOffset: localHeaderOffset,
isDirectory: false,
));
}
}
if ((i + 1) % 20 == 0 || (i + 1) == total) {
final fraction = total > 0 ? (i + 1) / total : 1.0;
final prog = 0.10 + fraction * 0.85;
sendPort.send([0, prog, '正在压缩 (${i + 1}/$total)...']);
}
}
// 写入 Central Directory 和 End of Central Directory (EOCD)
sendPort.send([0, 0.96, '正在封装压缩文件索引...']);
final cdStartOffset = raf.positionSync();
for (final entry in entries) {
_writeCentralDirectoryHeader(raf: raf, entry: entry);
}
final cdEndOffset = raf.positionSync();
final cdSize = cdEndOffset - cdStartOffset;
// 写入 End of Central Directory Record
_writeEOCD(
raf: raf,
entryCount: entries.length,
cdSize: cdSize,
cdStartOffset: cdStartOffset,
);
raf.flushSync();
raf.closeSync();
raf = null;
sendPort.send([0, 1.0, '压缩导出完成']);
sendPort.send([1]);
} catch (e, stack) {
if (raf != null) {
try {
raf.closeSync();
} catch (_) {}
}
sendPort.send([3, '$e\n$stack']);
}
}
/// 写入 30 字节 Local File Header + 文件名
static void _writeLocalHeader({
required RandomAccessFile raf,
required int method,
required int dosTime,
required int dosDate,
required int crc32,
required int compressedSize,
required int uncompressedSize,
required List<int> nameBytes,
}) {
final header = ByteData(30);
// Signature: 0x04034b50
header.setUint32(0, 0x04034b50, Endian.little);
// Version needed: 20 (2.0)
header.setUint16(4, 20, Endian.little);
// General purpose flag: bit 11 (UTF-8) = 0x0800
header.setUint16(6, 0x0800, Endian.little);
// Compression method: 8 (Deflate) or 0 (Store)
header.setUint16(8, method, Endian.little);
// Last mod file time
header.setUint16(10, dosTime, Endian.little);
// Last mod file date
header.setUint16(12, dosDate, Endian.little);
// CRC-32
header.setUint32(14, crc32, Endian.little);
// Compressed size
header.setUint32(18, compressedSize, Endian.little);
// Uncompressed size
header.setUint32(22, uncompressedSize, Endian.little);
// File name length
header.setUint16(26, nameBytes.length, Endian.little);
// Extra field length: 0
header.setUint16(28, 0, Endian.little);
raf.writeFromSync(header.buffer.asUint8List());
raf.writeFromSync(nameBytes);
}
/// 写入 46 字节 Central Directory Header + 文件名
static void _writeCentralDirectoryHeader({
required RandomAccessFile raf,
required _ZipEntryRecord entry,
}) {
final nameBytes = utf8.encode(entry.name);
final header = ByteData(46);
// Signature: 0x02014b50
header.setUint32(0, 0x02014b50, Endian.little);
// Version made by: 0x0314 (Unix 2.0)
header.setUint16(4, 0x0314, Endian.little);
// Version needed to extract: 20 (2.0)
header.setUint16(6, 20, Endian.little);
// General purpose flag: bit 11 (UTF-8) = 0x0800
header.setUint16(8, 0x0800, Endian.little);
// Compression method
header.setUint16(10, entry.method, Endian.little);
// Last mod time
header.setUint16(12, entry.time, Endian.little);
// Last mod date
header.setUint16(14, entry.date, Endian.little);
// CRC-32
header.setUint32(16, entry.crc32, Endian.little);
// Compressed size
header.setUint32(20, entry.compressedSize, Endian.little);
// Uncompressed size
header.setUint32(24, entry.uncompressedSize, Endian.little);
// File name length
header.setUint16(28, nameBytes.length, Endian.little);
// Extra field length: 0
header.setUint16(30, 0, Endian.little);
// File comment length: 0
header.setUint16(32, 0, Endian.little);
// Disk number start: 0
header.setUint16(34, 0, Endian.little);
// Internal file attributes: 0
header.setUint16(36, 0, Endian.little);
// External file attributes:
// 目录: Unix 0755 (0x41ED0000) | MS-DOS directory flag (0x10) = 0x41ED0010
// 普通文件: Unix 0644 (0x81A40000)
final extAttr = entry.isDirectory ? 0x41ED0010 : 0x81A40000;
header.setUint32(38, extAttr, Endian.little);
// Relative offset of local header
header.setUint32(42, entry.localHeaderOffset, Endian.little);
raf.writeFromSync(header.buffer.asUint8List());
raf.writeFromSync(nameBytes);
}
/// 写入 22 字节 End of Central Directory Record (EOCD)
static void _writeEOCD({
required RandomAccessFile raf,
required int entryCount,
required int cdSize,
required int cdStartOffset,
}) {
final eocd = ByteData(22);
// Signature: 0x06054b50
eocd.setUint32(0, 0x06054b50, Endian.little);
// Number of this disk: 0
eocd.setUint16(4, 0, Endian.little);
// Disk where central directory starts: 0
eocd.setUint16(6, 0, Endian.little);
// Number of central directory records on this disk
eocd.setUint16(8, entryCount.clamp(0, 0xFFFF), Endian.little);
// Total number of central directory records
eocd.setUint16(10, entryCount.clamp(0, 0xFFFF), Endian.little);
// Size of central directory
eocd.setUint32(12, cdSize, Endian.little);
// Offset of start of central directory
eocd.setUint32(16, cdStartOffset, Endian.little);
// ZIP file comment length: 0
eocd.setUint16(20, 0, Endian.little);
raf.writeFromSync(eocd.buffer.asUint8List());
}
}
+643
View File
@@ -0,0 +1,643 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'package:archive/archive_io.dart';
import 'package:path/path.dart' as p;
import 'low_memory_xz_decoder.dart';
final RegExp _paxRecordRegexp = RegExp(r"(\d+) (\w+)=(.*)");
/// 压缩包格式枚举
enum ArchiveFormat {
zip,
tarGz,
tarXz,
tarBz2,
tar,
unknown,
}
/// 解压进度回调
/// [progress] 0.0 ~ 1.0
/// [message] 当前阶段文字说明
typedef ArchiveProgressCallback = void Function(double progress, String message);
/// 用户或外部取消解压异常
class ArchiveExtractCancelledException implements Exception {
final String message;
ArchiveExtractCancelledException([this.message = '解压操作已取消']);
@override
String toString() => message;
}
class _ExtractIsolateParams {
final String archivePath;
final String targetDirPath;
final SendPort sendPort;
final bool restorePermissions;
const _ExtractIsolateParams({
required this.archivePath,
required this.targetDirPath,
required this.sendPort,
this.restorePermissions = false,
});
}
/// 流式 TAR 块头部结构解析器
class _TarHeader {
final String filename;
final int mode;
final int fileSize;
final String typeFlag;
final String? nameOfLinkedFile;
_TarHeader({
required this.filename,
required this.mode,
required this.fileSize,
required this.typeFlag,
this.nameOfLinkedFile,
});
static _TarHeader? read(InputStreamBase input) {
if (input.isEOS) return null;
final header = input.readBytes(512);
if (header.length < 512) return null;
final bytes = header.toUint8List();
var allZero = true;
for (var i = 0; i < 512; i++) {
if (bytes[i] != 0) {
allZero = false;
break;
}
}
if (allZero) return null;
String parseString(int offset, int length) {
var end = offset;
final max = offset + length;
while (end < max && bytes[end] != 0) {
end++;
}
return utf8.decode(bytes.sublist(offset, end), allowMalformed: true);
}
int parseInt(int offset, int length) {
final s = parseString(offset, length).trim();
if (s.isEmpty) return 0;
return int.tryParse(s, radix: 8) ?? 0;
}
var filename = parseString(0, 100);
final mode = parseInt(100, 8);
final fileSize = parseInt(124, 12);
final typeFlag = parseString(156, 1);
String? nameOfLinkedFile = parseString(157, 100);
if (nameOfLinkedFile.isEmpty) nameOfLinkedFile = null;
final ustarIndicator = parseString(257, 6);
if (ustarIndicator == 'ustar') {
final filenamePrefix = parseString(345, 155);
if (filenamePrefix.isNotEmpty) {
filename = '$filenamePrefix/$filename';
}
}
return _TarHeader(
filename: filename,
mode: mode,
fileSize: fileSize,
typeFlag: typeFlag,
nameOfLinkedFile: nameOfLinkedFile,
);
}
}
/// 通用高性能、低内存流式解压引擎
///
/// 解决原生 package:archive 全量读入内存导致的 OOM (Out Of Memory) 崩溃,
/// 并将高负载解压迁移到独立的后台 Worker Isolate,保证主 UI 线程持续 120fps 流畅。
/// 支持全格式解压:.zip, .tar.gz, .tgz, .tar.xz, .txz, .tar.bz2, .tbz, .tar。
class ArchiveExtractor {
/// 根据文件头部魔数与文件后缀综合识别压缩包格式
static ArchiveFormat detectFormat(File file) {
if (!file.existsSync()) return ArchiveFormat.unknown;
try {
final raf = file.openSync(mode: FileMode.read);
final bytes = raf.readSync(6);
raf.closeSync();
// XZ 魔数: FD 37 7A 58 5A 00
if (bytes.length >= 6 &&
bytes[0] == 0xFD &&
bytes[1] == 0x37 &&
bytes[2] == 0x7A &&
bytes[3] == 0x58 &&
bytes[4] == 0x5A &&
bytes[5] == 0x00) {
return ArchiveFormat.tarXz;
}
// GZ 魔数: 1F 8B
if (bytes.length >= 2 && bytes[0] == 0x1F && bytes[1] == 0x8B) {
return ArchiveFormat.tarGz;
}
// BZ2 魔数: 42 5A 68 ('BZh')
if (bytes.length >= 3 && bytes[0] == 0x42 && bytes[1] == 0x5A && bytes[2] == 0x68) {
return ArchiveFormat.tarBz2;
}
// ZIP 魔数: 50 4B 03 04 ('PK\x03\x04')
if (bytes.length >= 4 &&
bytes[0] == 0x50 &&
bytes[1] == 0x4B &&
bytes[2] == 0x03 &&
bytes[3] == 0x04) {
return ArchiveFormat.zip;
}
} catch (_) {}
final lower = file.path.toLowerCase();
if (lower.endsWith('.zip')) return ArchiveFormat.zip;
if (lower.endsWith('.tar.xz') || lower.endsWith('.txz') || lower.endsWith('.xz')) {
return ArchiveFormat.tarXz;
}
if (lower.endsWith('.tar.gz') || lower.endsWith('.tgz') || lower.endsWith('.gz')) {
return ArchiveFormat.tarGz;
}
if (lower.endsWith('.tar.bz2') ||
lower.endsWith('.tbz') ||
lower.endsWith('.tbz2') ||
lower.endsWith('.bz2')) {
return ArchiveFormat.tarBz2;
}
if (lower.endsWith('.tar')) return ArchiveFormat.tar;
return ArchiveFormat.unknown;
}
/// 在独立后台 Isolate 中低内存流式解压压缩包到目标目录
///
/// [archiveFile] 输入压缩包文件
/// [targetDir] 目标解压目录
/// [onProgress] 进度与状态说明回调(0.0 ~ 1.0)
/// [isCancelled] 外部取消检查函数
/// [restorePermissions] 是否恢复 Unix 权限位(Linux/Android 系统 Rootfs 解压需要)
static Future<void> extract({
required File archiveFile,
required Directory targetDir,
ArchiveProgressCallback? onProgress,
bool Function()? isCancelled,
bool restorePermissions = false,
}) async {
if (isCancelled?.call() == true) {
throw ArchiveExtractCancelledException();
}
if (!archiveFile.existsSync()) {
throw ArgumentError('压缩包文件不存在: ${archiveFile.path}');
}
onProgress?.call(0.02, '正在准备解压目录...');
if (!targetDir.existsSync()) {
targetDir.createSync(recursive: true);
}
final receivePort = ReceivePort();
final exitPort = ReceivePort();
final completer = Completer<Map<int, List<String>>>();
Isolate? isolate;
Timer? cancelTimer;
try {
isolate = await Isolate.spawn<_ExtractIsolateParams>(
_extractIsolateEntry,
_ExtractIsolateParams(
archivePath: archiveFile.path,
targetDirPath: targetDir.path,
sendPort: receivePort.sendPort,
restorePermissions: restorePermissions,
),
);
isolate.addOnExitListener(exitPort.sendPort);
exitPort.listen((_) {
if (!completer.isCompleted) {
completer.completeError(Exception('解压 Worker 意外退出'));
}
});
cancelTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {
if (isCancelled?.call() == true) {
isolate?.kill(priority: Isolate.immediate);
if (!completer.isCompleted) {
completer.completeError(ArchiveExtractCancelledException());
}
}
});
receivePort.listen((message) {
if (message is List) {
final type = message[0] as int;
if (type == 0) {
final prog = message[1] as double;
final msg = message[2] as String;
onProgress?.call(prog, msg);
} else if (type == 1) {
final byMode = (message[1] as Map).cast<int, List<String>>();
if (!completer.isCompleted) {
completer.complete(byMode);
}
} else if (type == 3) {
if (!completer.isCompleted) {
completer.completeError(Exception(message[1].toString()));
}
}
}
});
final byMode = await completer.future;
if (restorePermissions && !Platform.isWindows && byMode.isNotEmpty) {
await _restoreModes(byMode);
}
onProgress?.call(1.0, '解压完成!');
} catch (e) {
// 若中途失败或取消,清理不完整的目标目录
try {
if (targetDir.existsSync()) {
targetDir.deleteSync(recursive: true);
}
} catch (_) {}
rethrow;
} finally {
cancelTimer?.cancel();
receivePort.close();
exitPort.close();
isolate?.kill(priority: Isolate.immediate);
}
}
/// Worker Isolate 入口:低内存流式解码与单文件即刻落盘
static Future<void> _extractIsolateEntry(_ExtractIsolateParams params) async {
File? tempTarFile;
try {
params.sendPort.send([0, 0.05, '正在分析压缩文件结构...']);
final archiveFile = File(params.archivePath);
if (!archiveFile.existsSync()) {
params.sendPort.send([3, '压缩包文件不存在: ${params.archivePath}']);
return;
}
final format = detectFormat(archiveFile);
final targetDir = Directory(params.targetDirPath);
final tempDir = targetDir.parent.existsSync() ? targetDir.parent : Directory.systemTemp;
if (format == ArchiveFormat.zip) {
// ZIP 流式解压(单文件解压并立即清除内存对象)
params.sendPort.send([0, 0.10, '正在读取 ZIP 目录索引...']);
await _streamExtractZipFile(
zipFile: archiveFile,
targetDirPath: params.targetDirPath,
sendPort: params.sendPort,
progressStart: 0.10,
progressEnd: 0.98,
);
params.sendPort.send([1, <int, List<String>>{}]);
return;
}
File tarToExtract;
if (format == ArchiveFormat.tarXz) {
params.sendPort.send([0, 0.10, '正在通过环形缓冲流式解压 XZ 格式...']);
tempTarFile = File(p.join(
tempDir.path,
'temp_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
));
if (tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
final tarSink = tempTarFile.openWrite();
final inputStream = InputFileStream(archiveFile.path);
final archiveSize = archiveFile.lengthSync();
try {
final decoder = LowMemoryXZDecoder();
decoder.decodeToSink(
inputStream,
tarSink,
onProgress: (decompressed, compPos) {
final frac = archiveSize > 0 ? (compPos / archiveSize).clamp(0.0, 1.0) : 0.0;
final prog = 0.10 + frac * 0.40; // 0.10 ~ 0.50
final mb = (decompressed / (1024 * 1024)).toStringAsFixed(1);
params.sendPort.send([0, prog, '正在解码流 ($mb MB)...']);
},
);
} finally {
await tarSink.flush();
await tarSink.close();
await inputStream.close();
}
tarToExtract = tempTarFile;
} else if (format == ArchiveFormat.tarGz) {
params.sendPort.send([0, 0.10, '正在流式解压 GZip 压缩流...']);
tempTarFile = File(p.join(
tempDir.path,
'temp_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
));
if (tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
final tarSink = tempTarFile.openWrite();
try {
await archiveFile.openRead().transform(gzip.decoder).pipe(tarSink);
} finally {
await tarSink.close();
}
tarToExtract = tempTarFile;
} else if (format == ArchiveFormat.tarBz2) {
params.sendPort.send([0, 0.10, '正在流式解压 BZip2 压缩流...']);
tempTarFile = File(p.join(
tempDir.path,
'temp_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
));
if (tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
final tarSink = OutputFileStream(tempTarFile.path);
final inputStream = InputFileStream(archiveFile.path);
try {
BZip2Decoder().decodeStream(inputStream, tarSink);
} finally {
await inputStream.close();
await tarSink.close();
}
tarToExtract = tempTarFile;
} else {
tarToExtract = archiveFile;
}
// TAR 块流式释放到目标根目录
params.sendPort.send([0, 0.50, '正在释放文件与构建目录结构...']);
final byMode = await _streamExtractTarFile(
tarFile: tarToExtract,
targetDirPath: params.targetDirPath,
sendPort: params.sendPort,
progressStart: 0.50,
progressEnd: 0.98,
);
params.sendPort.send([1, byMode]);
} catch (e, stack) {
params.sendPort.send([3, '$e\n$stack']);
} finally {
if (tempTarFile != null && tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
}
}
/// 流式逐条解析 TAR 文件并直接落盘(不缓存大对象,单块 64KB 直写)
static Future<Map<int, List<String>>> _streamExtractTarFile({
required File tarFile,
required String targetDirPath,
required SendPort sendPort,
required double progressStart,
required double progressEnd,
}) async {
final input = InputFileStream(tarFile.path);
final byMode = <int, List<String>>{};
final totalLen = tarFile.lengthSync();
String? nextName;
String? nextLinkName;
int processed = 0;
try {
while (!input.isEOS) {
final th = _TarHeader.read(input);
if (th == null) break;
if (th.filename == '././@LongLink' || th.filename == '././@LongSymLink') {
final contentBytes = input.readBytes(th.fileSize).toUint8List();
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
final text = utf8.decode(contentBytes, allowMalformed: true).split('\x00').first;
if (th.typeFlag == 'K') {
nextLinkName = text;
} else {
nextName = text;
}
continue;
}
if (th.typeFlag == 'g' || th.typeFlag == 'x') {
// PAX Header
try {
final paxBytes = input.readBytes(th.fileSize).toUint8List();
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
final headerContent = utf8.decode(paxBytes, allowMalformed: true);
for (final line in headerContent.split('\n')) {
final match = _paxRecordRegexp.firstMatch(line);
if (match != null) {
final k = match.group(2);
final v = match.group(3);
if (k == 'path' && v != null) nextName = v;
if (k == 'linkpath' && v != null) nextLinkName = v;
}
}
} catch (_) {}
continue;
}
final filename = nextName ?? th.filename;
nextName = null;
final linkName = nextLinkName ?? th.nameOfLinkedFile;
nextLinkName = null;
// 路径穿越校验 (TarSlip 防护)
if (filename.contains('..') || filename.startsWith('/') || filename.contains(':')) {
if (th.fileSize > 0) {
input.skip(th.fileSize);
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
}
continue;
}
final cleanRel = p.normalize(filename);
if (cleanRel.startsWith('..') || p.isAbsolute(cleanRel)) {
if (th.fileSize > 0) {
input.skip(th.fileSize);
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
}
continue;
}
final outPath = p.join(targetDirPath, cleanRel);
if (!p.isWithin(p.canonicalize(targetDirPath), p.canonicalize(outPath)) &&
p.canonicalize(targetDirPath) != p.canonicalize(outPath)) {
if (th.fileSize > 0) {
input.skip(th.fileSize);
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
}
continue;
}
if (th.typeFlag == '5' || th.filename.endsWith('/')) {
final d = Directory(outPath);
if (!d.existsSync()) d.createSync(recursive: true);
} else if ((th.typeFlag == '2' || th.typeFlag == '1') && linkName != null) {
try {
final parent = Directory(p.dirname(outPath));
if (!parent.existsSync()) parent.createSync(recursive: true);
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(linkName);
} catch (_) {}
} else {
final parent = Directory(p.dirname(outPath));
if (!parent.existsSync()) parent.createSync(recursive: true);
final f = File(outPath);
final sink = f.openWrite();
var remaining = th.fileSize;
while (remaining > 0) {
final chunk = remaining < 65536 ? remaining : 65536;
sink.add(input.readBytes(chunk).toUint8List());
remaining -= chunk;
}
await sink.flush();
await sink.close();
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
}
final mode = th.mode & 0xFFF;
if (mode != 0 && th.typeFlag != '2') {
byMode.putIfAbsent(mode, () => <String>[]).add(outPath);
}
processed++;
if (processed % 100 == 0) {
final fraction = totalLen > 0 ? (input.position / totalLen).clamp(0.0, 1.0) : 0.0;
final prog = progressStart + fraction * (progressEnd - progressStart);
sendPort.send([0, prog, '正在释放文件 ($processed)...']);
}
}
} finally {
await input.close();
}
return byMode;
}
/// 流式逐条解析 ZIP 文件并直接落盘(单文件即解即清,内存严格平稳)
static Future<void> _streamExtractZipFile({
required File zipFile,
required String targetDirPath,
required SendPort sendPort,
required double progressStart,
required double progressEnd,
}) async {
final input = InputFileStream(zipFile.path);
try {
final zip = ZipDecoder().decodeBuffer(input);
final total = zip.files.length;
var count = 0;
for (final file in zip.files) {
final rawName = file.name.replaceAll('\\', '/');
// 路径穿越校验 (ZipSlip 防护)
if (rawName.contains('..') || rawName.startsWith('/') || rawName.contains(':')) {
count++;
continue;
}
final cleanRel = p.normalize(rawName);
if (cleanRel.startsWith('..') || p.isAbsolute(cleanRel)) {
count++;
continue;
}
final outPath = p.join(targetDirPath, cleanRel);
if (!p.isWithin(p.canonicalize(targetDirPath), p.canonicalize(outPath)) &&
p.canonicalize(targetDirPath) != p.canonicalize(outPath)) {
count++;
continue;
}
if (!file.isFile || rawName.endsWith('/')) {
final d = Directory(outPath);
if (!d.existsSync()) d.createSync(recursive: true);
} else if (file.isSymbolicLink) {
try {
final parent = Directory(p.dirname(outPath));
if (!parent.existsSync()) parent.createSync(recursive: true);
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(p.normalize(file.nameOfLinkedFile));
} catch (_) {}
} else {
final parent = Directory(p.dirname(outPath));
if (!parent.existsSync()) parent.createSync(recursive: true);
final outStream = OutputFileStream(outPath);
try {
file.writeContent(outStream, freeMemory: true);
} finally {
await outStream.close();
file.clear();
}
}
count++;
if (count % 25 == 0 || count == total) {
final fraction = total > 0 ? (count / total).clamp(0.0, 1.0) : 1.0;
final prog = progressStart + fraction * (progressEnd - progressStart);
sendPort.send([0, prog, '正在解压文件 ($count/$total)...']);
}
}
} finally {
await input.close();
}
}
/// 按 tar 头部恢复 POSIX 文件权限位
static Future<void> _restoreModes(Map<int, List<String>> byMode) async {
for (final entry in byMode.entries) {
final octal = entry.key.toRadixString(8).padLeft(4, '0');
final paths = entry.value;
const batchSize = 100;
for (var i = 0; i < paths.length; i += batchSize) {
final batch = paths.sublist(i, (i + batchSize).clamp(0, paths.length));
try {
await Process.run('chmod', [octal, ...batch]);
} catch (_) {
break; // 若系统无 chmod 则静默跳过
}
}
}
}
}
+93
View File
@@ -1,3 +1,4 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
@@ -55,6 +56,10 @@ class DistroManager {
@visibleForTesting
Directory? customBaseDir;
/// 自定义手机外部存储 sdcard 路径(主要用于测试)
@visibleForTesting
String? customSdcardPath;
/// 获取发行版存储基础目录: `<app_dir>/distros`
Future<Directory> getBaseDistrosDir() async {
if (customBaseDir != null) {
@@ -418,6 +423,38 @@ class DistroManager {
args.addAll(['-b', '$tmpPath:/tmp']);
}
// 挂载手机外部存储 (sdcard) 到容器 /sdcard 与 root 主目录 (/root/sdcard)
final effectiveSdcard = customSdcardPath ?? '/sdcard';
if (Directory(effectiveSdcard).existsSync()) {
// 1. 确保目标挂载目录存在,挂载到 /sdcard
final guestSdcard = Directory(p.join(rootDir.path, 'sdcard'));
if (!guestSdcard.existsSync()) {
try {
guestSdcard.createSync(recursive: true);
} catch (_) {}
}
args.addAll(['-b', '$effectiveSdcard:/sdcard']);
// 2. 挂载到容器内 root 用户主目录 (/root/sdcard),方便在主目录直接访问
final guestRootSdcard = Directory(p.join(rootDir.path, 'root', 'sdcard'));
if (!guestRootSdcard.existsSync()) {
try {
guestRootSdcard.createSync(recursive: true);
} catch (_) {}
}
args.addAll(['-b', '$effectiveSdcard:/root/sdcard']);
}
if (Directory('/storage').existsSync()) {
final guestStorage = Directory(p.join(rootDir.path, 'storage'));
if (!guestStorage.existsSync()) {
try {
guestStorage.createSync(recursive: true);
} catch (_) {}
}
args.addAll(['-b', '/storage']);
}
// 挂载工作区
String containerWorkDir = '/root';
if (workspacePath != null && Directory(workspacePath).existsSync()) {
@@ -773,6 +810,62 @@ class DistroManager {
}
}
/// 在容器(或宿主)后台静默执行指定命令(不打开终端、不绑定 PTY、纯管道捕获输出)
/// [systemName] 运行的系统名称(如 'ubuntu' 或 'host')
/// [workspacePath] 工程挂载目录(挂载到 /workspace)
/// [command] 执行的 Shell 脚本命令
/// [timeout] 超时时长(默认 120 秒)
Future<ProcessResult?> runHeadlessCommand({
required String systemName,
String? workspacePath,
required String command,
Duration timeout = const Duration(seconds: 120),
}) async {
try {
final config = await buildLaunchConfig(
systemName: systemName,
workspacePath: workspacePath,
customCommand: command,
);
final process = await Process.start(
config.executable,
config.arguments,
environment: config.environment,
workingDirectory: config.workingDirectory,
);
final stdoutBytes = <int>[];
final stderrBytes = <int>[];
final stdoutFuture = process.stdout.listen(stdoutBytes.addAll).asFuture<void>();
final stderrFuture = process.stderr.listen(stderrBytes.addAll).asFuture<void>();
final exitCode = await process.exitCode.timeout(
timeout,
onTimeout: () {
try {
process.kill(ProcessSignal.sigkill);
} catch (_) {}
return -1;
},
);
await Future.wait([stdoutFuture, stderrFuture]).timeout(
const Duration(seconds: 2),
onTimeout: () => [],
);
final stdoutStr = utf8.decode(stdoutBytes, allowMalformed: true);
final stderrStr = utf8.decode(stderrBytes, allowMalformed: true);
return ProcessResult(process.pid, exitCode, stdoutStr, stderrStr);
} catch (e) {
debugPrint('[DistroManager] runHeadlessCommand 异常: $e');
return null;
}
}
static String _androidAidGroupName(int gid) {
switch (gid) {
case 1015:
+37 -3
View File
@@ -1,8 +1,9 @@
import 'dart:io';
import 'package:archive/archive_io.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'archive_compressor.dart';
import 'archive_extractor.dart';
/// 软件内部私有存储项目管理服务 (files/projects)
class InternalProjectService {
@@ -146,7 +147,13 @@ class InternalProjectService {
}
/// 从外部压缩文件解压导入为内部项目 (`files/projects/<projectName>`)
Future<Directory> importProjectFromArchive(String archivePath, String projectName) async {
/// (采用底层 Isolate 流式分块直写落盘引擎,避免大项目解压内存溢出 OOM)
Future<Directory> importProjectFromArchive(
String archivePath,
String projectName, {
ArchiveProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final trimmedName = projectName.trim();
if (trimmedName.isEmpty) {
throw const FileSystemException('项目名称不能为空');
@@ -165,7 +172,12 @@ class InternalProjectService {
projectDir.createSync(recursive: true);
try {
await extractFileToDisk(archivePath, projectDir.path);
await ArchiveExtractor.extract(
archiveFile: archiveFile,
targetDir: projectDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
return projectDir;
} catch (e) {
if (projectDir.existsSync()) {
@@ -176,4 +188,26 @@ class InternalProjectService {
rethrow;
}
}
/// 将内部项目文件夹流式打包压缩为 ZIP 文件并导出到指定路径
/// (采用自研后台 Isolate 流式分块直写引擎,避免大项目压缩 OOM)
Future<File> exportProjectToZip(
Directory projectDir,
String targetZipPath, {
ArchiveProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
if (!projectDir.existsSync()) {
throw FileSystemException('项目目录不存在', projectDir.path);
}
final targetFile = File(targetZipPath);
await ArchiveCompressor.zipDirectory(
sourceDir: projectDir,
targetZipFile: targetFile,
onProgress: onProgress,
isCancelled: isCancelled,
);
return targetFile;
}
}
+66
View File
@@ -4,12 +4,15 @@ import 'package:code_editor/utils/dialog_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// 文件存储权限管理服务
class PermissionService {
static final PermissionService instance = PermissionService._();
PermissionService._();
static const String _keyBatteryOptimizationPrompted = 'battery_optimization_prompted';
/// 检查并确保拥有存储/工作区访问权限
///
/// 如果未授权且传入了 [context],会弹出友好说明对话框,引导用户前往系统设置开启“所有文件访问权限”。
@@ -90,4 +93,67 @@ class PermissionService {
return false;
}
}
/// 检查电池优化状态(是否已忽略后台电池优化)。
/// 若未关闭后台优化且尚未提示过,弹出提示对话框引导前往设置。
/// [forcePrompt] 为 true 时忽略已提示过的记录强制检查。
/// 返回 true 表示用户点击了“去设置”并触发了跳转;
/// 返回 false 表示无需配置或用户点击了“取消”或已提示过。
Future<bool> promptBatteryOptimizationIfNeeded(
BuildContext context, {
bool forcePrompt = false,
}) async {
if (kIsWeb || !Platform.isAndroid) return false;
try {
final prefs = await SharedPreferences.getInstance();
final hasPrompted = prefs.getBool(_keyBatteryOptimizationPrompted) ?? false;
if (!forcePrompt && hasPrompted) {
return false;
}
final isIgnored = await Permission.ignoreBatteryOptimizations.isGranted;
if (isIgnored) return false;
if (!context.mounted) return false;
final l10n = AppLocalizations.of(context);
final title = l10n?.batteryOptimizationTitle ?? '后台运行与电池优化';
final message = l10n?.batteryOptimizationMessage ??
'为了保证终端会话在后台不被系统强行终止,建议将本应用的电池优化设置为“无限制”或关闭电池优化。\n\n是否前往系统设置进行配置?';
final confirmText = l10n?.goToSettings ?? '去设置';
final cancelText = l10n?.cancel ?? '取消';
final shouldGoToSettings = await DialogUtils.showConfirmDialog(
context,
title: title,
message: message,
confirmText: confirmText,
cancelText: cancelText,
icon: const Icon(Icons.battery_alert_outlined, size: 28),
);
// 用户选择“去设置”或“取消”后,记录已提示,避免每次进入终端重复弹窗
await prefs.setBool(_keyBatteryOptimizationPrompted, true);
if (shouldGoToSettings) {
final status = await Permission.ignoreBatteryOptimizations.request();
if (!status.isGranted) {
await openAppSettings();
}
return true;
}
return false;
} catch (e) {
debugPrint('电池优化检测发生异常: $e');
return false;
}
}
/// 重置电池优化提示状态(供设置界面重新触发检测使用)
Future<void> resetBatteryOptimizationPrompt() async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyBatteryOptimizationPrompted);
} catch (_) {}
}
}
@@ -0,0 +1,296 @@
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';
/// 专门负责 Gradle 项目全自动深度自省与任务构建的模块
class GradleProjectModule extends ProjectModule {
@override
String get id => 'gradle';
@override
String get displayName => 'Gradle';
@override
List<String> get triggerFiles => const [
'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());
}
@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);
}
/// 计算构建脚本的综合指纹哈希(用于智能感知构建文件变更并使缓存失效)
static String computeBuildScriptHash(Directory projectDir) {
final buffer = StringBuffer();
final candidateFiles = [
'build.gradle',
'build.gradle.kts',
'settings.gradle',
'settings.gradle.kts',
'gradle.properties',
];
for (final fileName in candidateFiles) {
final file = File(p.join(projectDir.path, fileName));
if (file.existsSync()) {
try {
final stat = file.statSync();
buffer.write('$fileName:${stat.size}:${stat.modified.millisecondsSinceEpoch};');
} 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;
}
}
if (!inTasksSection) continue;
// 匹配单个任务定义,例如:
// 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,
));
}
}
// 按任务分组与名称进行合理排序(常用 Build / Application / Verification 优先展示)
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 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;
}
}
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;
}
}
@@ -0,0 +1,61 @@
import 'dart:io';
import '../../models/run_task.dart';
import '../distro_manager.dart';
import '../run_task_storage_service.dart';
/// 传递给各项目探测模块的上下文环境
class ProjectModuleContext {
/// 工程根目录
final Directory projectDir;
/// 当前在编辑器中激活的文件路径(宿主绝对路径,可能为 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)
abstract class ProjectModule {
/// 模块唯一标识(如 'gradle', 'cmake', 'cargo', 'npm' 等)
String get id;
/// 模块友好展示名称
String get displayName;
/// 该项目特有的特征标记文件(命中其中任意一个才激活本探测器)
List<String> get triggerFiles;
/// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否,不进行深层解析)
bool shouldActivate(Directory projectDir);
/// 探测项目任务(支持优先读取本地缓存;当 forceRefresh=true 时强制发起真实探测)
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false});
}
@@ -0,0 +1,211 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../../models/run_task.dart';
import 'project_module.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) {
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,
),
];
}
}
+7 -267
View File
@@ -1,9 +1,8 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../models/run_task.dart';
import 'project_task_dispatcher.dart';
/// 负责根据工程文件和当前打开的文件,在内存中动态推导可用的运行任务
/// (现已接入模块化 ProjectTaskDispatcher 总调度器,保持向后 100% 兼容)
class ProjectTaskDetector {
/// 核心探测入口
/// [projectRoot]: 工程根目录(宿主绝对路径)
@@ -11,269 +10,10 @@ class ProjectTaskDetector {
static Future<List<RunTask>> detect({
required String projectRoot,
String? currentFilePath,
}) async {
final List<RunTask> tasks = [];
final projectDir = Directory(projectRoot);
if (!projectDir.existsSync()) {
return tasks;
}
// 1. 工程级特征文件检测
tasks.addAll(await _detectProjectBuildTasks(projectRoot));
// 2. 当前活跃文件(单文件运行)检测
if (currentFilePath != null && currentFilePath.isNotEmpty) {
final singleTask = _detectSingleFileTask(projectRoot, currentFilePath);
if (singleTask != null) {
// 单文件即时运行置于首位,方便用户直接点击运行
tasks.insert(0, singleTask);
}
}
return tasks;
}
/// 探测构建工程任务(CMake / Gradle / Makefile / npm / Cargo / Dart 等)
static Future<List<RunTask>> _detectProjectBuildTasks(String projectRoot) async {
final List<RunTask> buildTasks = [];
// 1. CMakeLists.txt
final cmakeFile = File(p.join(projectRoot, 'CMakeLists.txt'));
if (cmakeFile.existsSync()) {
final projectName = p.basename(projectRoot);
buildTasks.addAll([
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',
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',
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_cmake_clean',
name: 'CMake: Clean',
command: 'rm -rf build',
source: TaskSource.detected,
description: 'Clean build cache directory',
icon: Icons.cleaning_services_outlined,
),
]);
}
// 2. Gradle (build.gradle / gradlew)
final gradlewFile = File(p.join(projectRoot, 'gradlew'));
final gradleFile = File(p.join(projectRoot, 'build.gradle'));
final gradleKtsFile = File(p.join(projectRoot, 'build.gradle.kts'));
if (gradlewFile.existsSync() || gradleFile.existsSync() || gradleKtsFile.existsSync()) {
final exec = gradlewFile.existsSync() ? 'sh ./gradlew' : 'gradle';
buildTasks.addAll([
RunTask(
id: 'detected_gradle_run',
name: 'Gradle: Run',
command: '$exec run',
source: TaskSource.detected,
description: 'Execute application main entrypoint',
icon: Icons.play_circle_outline,
),
RunTask(
id: 'detected_gradle_assemble',
name: 'Gradle: Assemble Debug',
command: '$exec assembleDebug',
source: TaskSource.detected,
description: 'Build debug output package',
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_gradle_build',
name: 'Gradle: Build',
command: '$exec build',
source: TaskSource.detected,
description: 'Execute full build and tests',
icon: Icons.done_all_outlined,
),
]);
}
// 3. Makefile
final makeFile = File(p.join(projectRoot, 'Makefile'));
if (makeFile.existsSync()) {
buildTasks.add(
const RunTask(
id: 'detected_make_default',
name: 'Make: Default',
command: 'make',
source: TaskSource.detected,
description: 'Execute default Makefile build target',
icon: Icons.build_circle_outlined,
),
);
}
// 4. package.json (Node/Web)
final packageJsonFile = File(p.join(projectRoot, 'package.json'));
if (packageJsonFile.existsSync()) {
buildTasks.addAll([
const RunTask(
id: 'detected_npm_start',
name: 'NPM: Start',
command: 'npm start',
source: TaskSource.detected,
description: 'Start Node service or frontend development environment',
icon: Icons.rocket_launch_outlined,
),
const RunTask(
id: 'detected_npm_test',
name: 'NPM: Test',
command: 'npm test',
source: TaskSource.detected,
description: 'Execute npm test suite',
icon: Icons.checklist_outlined,
),
]);
}
// 5. Cargo.toml (Rust)
final cargoFile = File(p.join(projectRoot, 'Cargo.toml'));
if (cargoFile.existsSync()) {
buildTasks.addAll([
const RunTask(
id: 'detected_cargo_run',
name: 'Cargo: Run',
command: 'cargo run',
source: TaskSource.detected,
description: 'Compile and run Rust project',
icon: Icons.play_circle_outline,
),
const RunTask(
id: 'detected_cargo_build',
name: 'Cargo: Build',
command: 'cargo build',
source: TaskSource.detected,
description: 'Compile Rust project only',
icon: Icons.build_outlined,
),
]);
}
// 6. pubspec.yaml (Dart)
final pubspecFile = File(p.join(projectRoot, 'pubspec.yaml'));
if (pubspecFile.existsSync()) {
buildTasks.add(
const RunTask(
id: 'detected_dart_run',
name: 'Dart: Run',
command: 'dart run',
source: TaskSource.detected,
description: 'Launch Dart application',
icon: Icons.play_circle_outline,
),
);
}
return buildTasks;
}
/// 探测单文件运行指令(基于当前打开的文件)
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',
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',
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',
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',
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',
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',
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',
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',
icon: Icons.javascript,
);
default:
return null;
}
}) {
return ProjectTaskDispatcher.instance.detect(
projectRoot: projectRoot,
currentFilePath: currentFilePath,
);
}
}
+257
View File
@@ -0,0 +1,257 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../models/run_task.dart';
import 'distro_manager.dart';
import 'project_modules/gradle_project_module.dart';
import 'project_modules/project_module.dart';
import 'project_modules/standard_project_modules.dart';
import 'run_task_storage_service.dart';
/// 项目任务总调度与路由器(对标 VS Code Task Service)
/// 统一管理各项目模块注册、条件匹配激活、并发/缓存调度与单文件即时任务生成
class ProjectTaskDispatcher {
static final ProjectTaskDispatcher instance = ProjectTaskDispatcher();
final List<ProjectModule> _modules = [];
ProjectTaskDispatcher({List<ProjectModule>? customModules}) {
if (customModules != null) {
_modules.addAll(customModules);
} else {
_registerDefaultModules();
}
}
void _registerDefaultModules() {
_modules.addAll([
GradleProjectModule(),
CMakeProjectModule(),
CargoProjectModule(),
NpmProjectModule(),
MakeProjectModule(),
DartProjectModule(),
]);
}
List<ProjectModule> get modules => List.unmodifiable(_modules);
void registerModule(ProjectModule module) {
_modules.removeWhere((m) => m.id == module.id);
_modules.add(module);
}
ProjectModule? getModule(String id) {
try {
return _modules.firstWhere((m) => m.id == id);
} catch (_) {
return null;
}
}
/// 获取当前项目中所有被激活的模块
List<ProjectModule> getActiveModules(Directory projectDir) {
return _modules.where((m) => m.shouldActivate(projectDir)).toList();
}
/// 核心任务探测与分发
/// [projectRoot]: 工程根目录(宿主绝对路径)
/// [currentFilePath]: 当前编辑器激活打开的文件(宿主绝对路径,可能为 null)
/// [systemName]: 容器实例名称
/// [forceRefresh]: 是否忽略缓存,强制重新请求真实探测
/// [onlyModuleId]: 可选,仅执行指定的模块探测
Future<List<RunTask>> detect({
required String projectRoot,
String? currentFilePath,
String systemName = 'ubuntu',
RunTaskStorageService? storageService,
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,
currentFilePath: currentFilePath,
systemName: systemName,
storageService: storageService ?? RunTaskStorageService(),
distroManager: distroManager ?? DistroManager(),
);
// 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;
}
/// 针对单个模块执行显式重新同步
Future<List<RunTask>> syncModule({
required String moduleId,
required String projectRoot,
String? currentFilePath,
String systemName = 'ubuntu',
RunTaskStorageService? storageService,
DistroManager? distroManager,
}) async {
final module = getModule(moduleId);
if (module == null) return [];
final projectDir = Directory(projectRoot);
if (!projectDir.existsSync()) return [];
final context = ProjectModuleContext(
projectDir: projectDir,
currentFilePath: currentFilePath,
systemName: systemName,
storageService: storageService ?? RunTaskStorageService(),
distroManager: distroManager ?? DistroManager(),
);
return module.detect(context, forceRefresh: true);
}
/// 探测单文件运行指令(基于当前打开的文件)
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;
}
}
}
@@ -97,4 +97,78 @@ class RunTaskStorageService {
Future<void> saveTasks(String projectRoot, List<RunTask> tasks) async {
await saveConfig(projectRoot: projectRoot, tasks: tasks);
}
/// 获取特定模块的独立任务缓存配置文件(例如 `.code_editor/gradle_tasks.json`)
File getModuleConfigFile(String projectRoot, String moduleName) {
return File(p.join(projectRoot, configDirName, '${moduleName}_tasks.json'));
}
/// 从工程的 `.code_editor/<module>_tasks.json` 中读取模块探测出的任务与缓存元信息
Future<({List<RunTask> tasks, String? hash, DateTime? updatedAt})> loadModuleTasks(
String projectRoot,
String moduleName,
) async {
try {
final file = getModuleConfigFile(projectRoot, moduleName);
if (!await file.exists()) {
return (tasks: <RunTask>[], hash: null, updatedAt: null);
}
final content = await file.readAsString();
if (content.trim().isEmpty) {
return (tasks: <RunTask>[], hash: null, updatedAt: null);
}
final dynamic decoded = jsonDecode(content);
if (decoded is Map) {
final hash = decoded['buildScriptHash']?.toString();
final rawUpdated = decoded['updatedAt']?.toString();
final updatedAt = rawUpdated != null ? DateTime.tryParse(rawUpdated) : null;
final tasksRaw = decoded['tasks'];
final List<RunTask> list = [];
if (tasksRaw is List) {
for (final item in tasksRaw) {
if (item is Map) {
list.add(RunTask.fromJson(Map<String, dynamic>.from(item)));
}
}
}
return (tasks: list, hash: hash, updatedAt: updatedAt);
}
return (tasks: <RunTask>[], hash: null, updatedAt: null);
} catch (e) {
debugPrint('[RunTaskStorageService] 读取 ${moduleName}_tasks.json 失败: $e');
return (tasks: <RunTask>[], hash: null, updatedAt: null);
}
}
/// 将特定模块探测所得任务与缓存哈希持久化保存到 `.code_editor/<module>_tasks.json`
Future<void> saveModuleTasks({
required String projectRoot,
required String moduleName,
required List<RunTask> tasks,
String? hash,
}) async {
try {
final file = getModuleConfigFile(projectRoot, moduleName);
final dir = file.parent;
if (!await dir.exists()) {
await dir.create(recursive: true);
}
final data = {
'version': '1.0',
'module': moduleName,
'updatedAt': DateTime.now().toIso8601String(),
if (hash != null && hash.isNotEmpty) 'buildScriptHash': hash,
'tasks': tasks.map((t) => t.toJson()).toList(),
};
const encoder = JsonEncoder.withIndent(' ');
final jsonStr = encoder.convert(data);
await file.writeAsString(jsonStr, flush: true);
} catch (e) {
debugPrint('[RunTaskStorageService] 保存 ${moduleName}_tasks.json 失败: $e');
}
}
}