diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index f2c9227..3a04e56 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -513,6 +513,8 @@ "noMatchingTasks": "No matching tasks found", "userCustomTasks": "User Custom Tasks", "systemDetectedTasks": "System Detected Tasks", + "resyncModuleTasks": "Resync Real Tasks", + "syncingTasks": "Introspecting tasks in background...", "editCustomTasksTooltip": "Edit Custom Tasks", "runTasksConfig": "Run Tasks Configuration", "editTask": "Edit Task", @@ -646,5 +648,34 @@ } }, "unsupportedProjectArchiveFormat": "Unsupported file format. Only archive files (.zip, .tar.gz, .tar.xz, .tar, etc.) are supported", - "unsupportedDistroArchiveFormat": "Unsupported file format. Only system archives (.tar.gz, .tar.xz, .tar) are supported" + "unsupportedDistroArchiveFormat": "Unsupported file format. Only system archives (.tar.gz, .tar.xz, .tar) are supported", + "exportProject": "Export Project", + "exportProjectTooltip": "Export as ZIP archive", + "exportingProject": "Compressing and exporting project...", + "projectExported": "Project exported successfully", + "exportProjectFailed": "Failed to export project: {error}", + "@exportProjectFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "selectExportDirectory": "Select Export Destination Folder", + "targetFileAlreadyExists": "Target file \"{name}\" already exists. Overwrite?", + "@targetFileAlreadyExists": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "overwrite": "Overwrite", + "batteryOptimizationTitle": "Background Running & Battery Optimization", + "batteryOptimizationMessage": "To prevent terminal sessions from being killed by the system in the background, it is recommended to disable battery optimization or set it to 'Unrestricted'.\n\nWould you like to go to settings to configure it?", + "copy": "Copy", + "cut": "Cut", + "paste": "Paste", + "selectAll": "Select All", + "copiedToClipboard": "Copied to clipboard" } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 916447c..6fd3d37 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1772,6 +1772,18 @@ abstract class AppLocalizations { /// **'系统动态探测任务'** String get systemDetectedTasks; + /// No description provided for @resyncModuleTasks. + /// + /// In zh, this message translates to: + /// **'重新同步真实任务'** + String get resyncModuleTasks; + + /// No description provided for @syncingTasks. + /// + /// In zh, this message translates to: + /// **'正在后台自省任务...'** + String get syncingTasks; + /// No description provided for @editCustomTasksTooltip. /// /// In zh, this message translates to: @@ -2239,6 +2251,72 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)'** String get unsupportedDistroArchiveFormat; + + /// No description provided for @exportProject. + /// + /// In zh, this message translates to: + /// **'导出项目'** + String get exportProject; + + /// No description provided for @exportProjectTooltip. + /// + /// In zh, this message translates to: + /// **'导出为 ZIP 压缩包'** + String get exportProjectTooltip; + + /// No description provided for @exportingProject. + /// + /// In zh, this message translates to: + /// **'正在压缩并导出项目...'** + String get exportingProject; + + /// No description provided for @projectExported. + /// + /// In zh, this message translates to: + /// **'项目导出成功'** + String get projectExported; + + /// No description provided for @exportProjectFailed. + /// + /// In zh, this message translates to: + /// **'导出项目失败: {error}'** + String exportProjectFailed(String error); + + /// No description provided for @selectExportDirectory. + /// + /// In zh, this message translates to: + /// **'选择导出目标文件夹'** + String get selectExportDirectory; + + /// No description provided for @targetFileAlreadyExists. + /// + /// In zh, this message translates to: + /// **'目标文件 \"{name}\" 已存在,是否覆盖?'** + String targetFileAlreadyExists(String name); + + /// No description provided for @overwrite. + /// + /// In zh, this message translates to: + /// **'覆盖'** + String get overwrite; + + /// No description provided for @batteryOptimizationTitle. + /// + /// In zh, this message translates to: + /// **'后台运行与电池优化'** + String get batteryOptimizationTitle; + + /// No description provided for @batteryOptimizationMessage. + /// + /// In zh, this message translates to: + /// **'为了保证终端会话在后台不被系统强行终止,建议将本应用的电池优化设置为“无限制”或关闭电池优化。\n\n是否前往系统设置进行配置?'** + String get batteryOptimizationMessage; + + /// No description provided for @copiedToClipboard. + /// + /// In zh, this message translates to: + /// **'已复制到剪贴板'** + String get copiedToClipboard; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 9826bcf..0977a7e 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1074,6 +1074,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get systemDetectedTasks => 'System Detected Tasks'; + @override + String get resyncModuleTasks => 'Resync Real Tasks'; + + @override + String get syncingTasks => 'Introspecting tasks in background...'; + @override String get editCustomTasksTooltip => 'Edit Custom Tasks'; @@ -1344,4 +1350,43 @@ class AppLocalizationsEn extends AppLocalizations { @override String get unsupportedDistroArchiveFormat => 'Unsupported file format. Only system archives (.tar.gz, .tar.xz, .tar) are supported'; + + @override + String get exportProject => 'Export Project'; + + @override + String get exportProjectTooltip => 'Export as ZIP archive'; + + @override + String get exportingProject => 'Compressing and exporting project...'; + + @override + String get projectExported => 'Project exported successfully'; + + @override + String exportProjectFailed(String error) { + return 'Failed to export project: $error'; + } + + @override + String get selectExportDirectory => 'Select Export Destination Folder'; + + @override + String targetFileAlreadyExists(String name) { + return 'Target file \"$name\" already exists. Overwrite?'; + } + + @override + String get overwrite => 'Overwrite'; + + @override + String get batteryOptimizationTitle => + 'Background Running & Battery Optimization'; + + @override + String get batteryOptimizationMessage => + 'To prevent terminal sessions from being killed by the system in the background, it is recommended to disable battery optimization or set it to \'Unrestricted\'.\n\nWould you like to go to settings to configure it?'; + + @override + String get copiedToClipboard => 'Copied to clipboard'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 8c3a7d0..10f7b6c 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1047,6 +1047,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get systemDetectedTasks => '系统动态探测任务'; + @override + String get resyncModuleTasks => '重新同步真实任务'; + + @override + String get syncingTasks => '正在后台自省任务...'; + @override String get editCustomTasksTooltip => '编辑自定义任务'; @@ -1307,4 +1313,42 @@ class AppLocalizationsZh extends AppLocalizations { @override String get unsupportedDistroArchiveFormat => '不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)'; + + @override + String get exportProject => '导出项目'; + + @override + String get exportProjectTooltip => '导出为 ZIP 压缩包'; + + @override + String get exportingProject => '正在压缩并导出项目...'; + + @override + String get projectExported => '项目导出成功'; + + @override + String exportProjectFailed(String error) { + return '导出项目失败: $error'; + } + + @override + String get selectExportDirectory => '选择导出目标文件夹'; + + @override + String targetFileAlreadyExists(String name) { + return '目标文件 \"$name\" 已存在,是否覆盖?'; + } + + @override + String get overwrite => '覆盖'; + + @override + String get batteryOptimizationTitle => '后台运行与电池优化'; + + @override + String get batteryOptimizationMessage => + '为了保证终端会话在后台不被系统强行终止,建议将本应用的电池优化设置为“无限制”或关闭电池优化。\n\n是否前往系统设置进行配置?'; + + @override + String get copiedToClipboard => '已复制到剪贴板'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index b3a8c44..1aca5b1 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -513,6 +513,8 @@ "noMatchingTasks": "无匹配的任务", "userCustomTasks": "用户自定义任务", "systemDetectedTasks": "系统动态探测任务", + "resyncModuleTasks": "重新同步真实任务", + "syncingTasks": "正在后台自省任务...", "editCustomTasksTooltip": "编辑自定义任务", "runTasksConfig": "运行任务配置", "editTask": "编辑任务", @@ -646,5 +648,34 @@ } }, "unsupportedProjectArchiveFormat": "不支持的文件格式,仅支持压缩包格式 (.zip, .tar.gz, .tar.xz, .tar 等)", - "unsupportedDistroArchiveFormat": "不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)" + "unsupportedDistroArchiveFormat": "不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)", + "exportProject": "导出项目", + "exportProjectTooltip": "导出为 ZIP 压缩包", + "exportingProject": "正在压缩并导出项目...", + "projectExported": "项目导出成功", + "exportProjectFailed": "导出项目失败: {error}", + "@exportProjectFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "selectExportDirectory": "选择导出目标文件夹", + "targetFileAlreadyExists": "目标文件 \"{name}\" 已存在,是否覆盖?", + "@targetFileAlreadyExists": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "overwrite": "覆盖", + "batteryOptimizationTitle": "后台运行与电池优化", + "batteryOptimizationMessage": "为了保证终端会话在后台不被系统强行终止,建议将本应用的电池优化设置为“无限制”或关闭电池优化。\n\n是否前往系统设置进行配置?", + "copy": "复制", + "cut": "剪切", + "paste": "粘贴", + "selectAll": "全选", + "copiedToClipboard": "已复制到剪贴板" } \ No newline at end of file diff --git a/lib/models/run_task.dart b/lib/models/run_task.dart index 870a2ee..4756263 100644 --- a/lib/models/run_task.dart +++ b/lib/models/run_task.dart @@ -33,6 +33,12 @@ class RunTask { /// 是否在执行该命令前清屏(发送 clear) final bool clearBeforeRun; + /// 任务所属分组(如 Gradle 的 'build', 'verification', 'application', 'other' 等) + final String? group; + + /// 归属的项目探测模块ID(如 'gradle', 'cmake' 等) + final String? moduleId; + /// UI 展示图标(可选) final IconData? icon; @@ -44,35 +50,45 @@ class RunTask { this.description, this.workingDir, this.clearBeforeRun = false, + this.group, + this.moduleId, this.icon, }); - /// 从持久化的 JSON Map 构建自定义运行任务 + /// 从持久化的 JSON Map 构建运行任务 factory RunTask.fromJson(Map json) { final rawClear = json['clearBeforeRun']; final bool clearVal = (rawClear is bool) ? rawClear : (rawClear is num ? rawClear != 0 : (rawClear?.toString().toLowerCase() == 'true')); + final rawSource = json['source']?.toString(); + final TaskSource source = rawSource == 'detected' ? TaskSource.detected : TaskSource.custom; + return RunTask( id: json['id']?.toString() ?? 'custom_${DateTime.now().microsecondsSinceEpoch}', name: json['name']?.toString() ?? '未命名任务', command: json['command']?.toString() ?? '', - source: TaskSource.custom, + source: source, description: json['description']?.toString(), workingDir: json['workingDir']?.toString(), clearBeforeRun: clearVal, + group: json['group']?.toString(), + moduleId: json['moduleId']?.toString(), ); } - /// 序列化为持久化 JSON Map(仅针对用户自定义任务保存) + /// 序列化为持久化 JSON Map Map toJson() { return { 'id': id, 'name': name, 'command': command, + 'source': source.name, if (description != null && description!.isNotEmpty) 'description': description, if (workingDir != null && workingDir!.isNotEmpty) 'workingDir': workingDir, + if (group != null && group!.isNotEmpty) 'group': group, + if (moduleId != null && moduleId!.isNotEmpty) 'moduleId': moduleId, 'clearBeforeRun': clearBeforeRun, }; } @@ -87,10 +103,13 @@ class RunTask { case 'detected_cmake_clean': return l10n.detectedTaskCmakeCleanDesc; case 'detected_gradle_run': + case 'gradle_run': return l10n.detectedTaskGradleRunDesc; case 'detected_gradle_assemble': + case 'gradle_assembleDebug': return l10n.detectedTaskGradleAssembleDesc; case 'detected_gradle_build': + case 'gradle_build': return l10n.detectedTaskGradleBuildDesc; case 'detected_make_default': return l10n.detectedTaskMakeDefaultDesc; @@ -141,6 +160,8 @@ class RunTask { String? description, String? workingDir, bool? clearBeforeRun, + String? group, + String? moduleId, IconData? icon, }) { return RunTask( @@ -151,6 +172,8 @@ class RunTask { description: description ?? this.description, workingDir: workingDir ?? this.workingDir, clearBeforeRun: clearBeforeRun ?? this.clearBeforeRun, + group: group ?? this.group, + moduleId: moduleId ?? this.moduleId, icon: icon ?? this.icon, ); } diff --git a/lib/providers/run_provider.dart b/lib/providers/run_provider.dart index 0a23f46..37d8360 100644 --- a/lib/providers/run_provider.dart +++ b/lib/providers/run_provider.dart @@ -1,14 +1,22 @@ import 'package:flutter/material.dart'; import '../models/run_task.dart'; -import '../services/project_task_detector.dart'; +import '../services/distro_manager.dart'; +import '../services/project_task_dispatcher.dart'; import '../services/run_task_storage_service.dart'; /// 运行任务状态管理 Provider class RunProvider extends ChangeNotifier { final RunTaskStorageService _storageService; + final ProjectTaskDispatcher _dispatcher; + final DistroManager _distroManager; - RunProvider({RunTaskStorageService? storageService}) - : _storageService = storageService ?? RunTaskStorageService(); + RunProvider({ + RunTaskStorageService? storageService, + ProjectTaskDispatcher? dispatcher, + DistroManager? distroManager, + }) : _storageService = storageService ?? RunTaskStorageService(), + _dispatcher = dispatcher ?? ProjectTaskDispatcher.instance, + _distroManager = distroManager ?? DistroManager(); /// 内存中保存的系统动态探测任务列表(不落盘) List _detectedTasks = []; @@ -22,18 +30,25 @@ class RunProvider extends ChangeNotifier { /// 最近一次运行的任务(如果有) RunTask? _lastRunTask; - /// 是否正在探测中(探测期间互斥,防止并发与按钮连点) + /// 是否正在总体探测中(探测期间互斥,防止并发与按钮连点) bool _isDetecting = false; /// 当前绑定的工程根路径 String? _currentProjectRoot; + /// 正在后台执行深度同步自省的模块集合(如 'gradle') + final Set _syncingModules = {}; + List get detectedTasks => List.unmodifiable(_detectedTasks); List get customTasks => List.unmodifiable(_customTasks); RunTask? get lastRunTask => _lastRunTask; String? get lastRunTaskId => _lastRunTaskId; bool get isDetecting => _isDetecting; String? get currentProjectRoot => _currentProjectRoot; + Set get syncingModules => Set.unmodifiable(_syncingModules); + + bool isModuleSyncing(String moduleId) => _syncingModules.contains(moduleId); + bool get isAnyModuleSyncing => _syncingModules.isNotEmpty; /// 获取当前合并后的所有可用任务列表(自定义任务置顶,随后为探测任务) List get allTasks => [..._customTasks, ..._detectedTasks]; @@ -66,13 +81,14 @@ class RunProvider extends ChangeNotifier { } /// 当打开或切换工程时初始化任务(读取持久化任务 + 首次自动探测系统任务) - Future onProjectOpened(String projectRoot, {String? activeFilePath}) async { + Future onProjectOpened(String projectRoot, {String? activeFilePath, String systemName = 'ubuntu'}) async { _currentProjectRoot = projectRoot; // 切换工程时首先立即清空上一工程的内存任务状态,防止跨项目污染 _detectedTasks = []; _customTasks = []; _lastRunTaskId = null; _lastRunTask = null; + _syncingModules.clear(); notifyListeners(); // 1. 加载持久化的自定义任务与最近运行任务ID @@ -84,8 +100,12 @@ class RunProvider extends ChangeNotifier { _resolveLastRunTask(); notifyListeners(); - // 2. 自动触发一次系统探测 - await detectTasks(projectRoot: projectRoot, currentFilePath: activeFilePath); + // 2. 自动触发一次系统探测(优先读模块本地持久化缓存,秒开无感) + await detectTasks( + projectRoot: projectRoot, + currentFilePath: activeFilePath, + systemName: systemName, + ); } /// 关闭工程时清理状态 @@ -96,28 +116,35 @@ class RunProvider extends ChangeNotifier { _lastRunTaskId = null; _lastRunTask = null; _isDetecting = false; + _syncingModules.clear(); notifyListeners(); } /// 手动或自动触发项目探测 /// [projectRoot] 目标工程路径 /// [currentFilePath] 当前激活的编辑器文件路径 + /// [forceRefresh] 是否强制重新自省探测 Future detectTasks({ required String projectRoot, String? currentFilePath, + String systemName = 'ubuntu', + bool forceRefresh = false, }) async { if (_isDetecting) return; _isDetecting = true; - // 清空内存中的旧探测结果 _detectedTasks = []; _resolveLastRunTask(); notifyListeners(); try { - final detected = await ProjectTaskDetector.detect( + final detected = await _dispatcher.detect( projectRoot: projectRoot, currentFilePath: currentFilePath, + systemName: systemName, + storageService: _storageService, + distroManager: _distroManager, + forceRefresh: forceRefresh, ); if (_currentProjectRoot == projectRoot) { _detectedTasks = detected; @@ -131,6 +158,67 @@ class RunProvider extends ChangeNotifier { } } + /// 异步重新同步/深度自省某个特定模块的任务(如 Gradle) + /// 在后台静默运行,并无缝将结果合并入当前 detectedTasks + Future syncModuleTasks( + String moduleId, { + String systemName = 'ubuntu', + }) async { + if (_currentProjectRoot == null) return; + if (_syncingModules.contains(moduleId)) return; + + final projectRoot = _currentProjectRoot!; + _syncingModules.add(moduleId); + notifyListeners(); + + try { + final moduleTasks = await _dispatcher.syncModule( + moduleId: moduleId, + projectRoot: projectRoot, + systemName: systemName, + storageService: _storageService, + distroManager: _distroManager, + ); + + if (_currentProjectRoot == projectRoot && moduleTasks.isNotEmpty) { + _detectedTasks = _mergeModuleTasks(_detectedTasks, moduleId, moduleTasks); + _resolveLastRunTask(); + } + } catch (e) { + debugPrint('[RunProvider] 模块 $moduleId 深度自省失败: $e'); + } finally { + _syncingModules.remove(moduleId); + notifyListeners(); + } + } + + /// 合并替换指定模块在 detectedTasks 中的条目,保持原有相对排布 + List _mergeModuleTasks(List current, String moduleId, List updated) { + final result = []; + bool inserted = false; + + for (final task in current) { + final isThisModule = task.moduleId == moduleId || + task.id.startsWith('${moduleId}_') || + task.id.startsWith('detected_${moduleId}_'); + + if (isThisModule) { + if (!inserted) { + result.addAll(updated); + inserted = true; + } + } else { + result.add(task); + } + } + + if (!inserted) { + result.addAll(updated); + } + + return result; + } + /// 保存并更新用户自定义任务 Future updateCustomTasks(List updatedTasks) async { if (_currentProjectRoot == null) return; diff --git a/lib/services/archive_compressor.dart b/lib/services/archive_compressor.dart new file mode 100644 index 0000000..0f8ccb6 --- /dev/null +++ b/lib/services/archive_compressor.dart @@ -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 _crcTable = List.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 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> { + final RandomAccessFile raf; + int bytesWritten = 0; + + _RafChunkSink(this.raf); + + @override + void add(List 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 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(); + 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 _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 = []; + 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 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()); + } +} diff --git a/lib/services/archive_extractor.dart b/lib/services/archive_extractor.dart new file mode 100644 index 0000000..5c656a8 --- /dev/null +++ b/lib/services/archive_extractor.dart @@ -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 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>>(); + 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>(); + 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 _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, >{}]); + 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>> _streamExtractTarFile({ + required File tarFile, + required String targetDirPath, + required SendPort sendPort, + required double progressStart, + required double progressEnd, + }) async { + final input = InputFileStream(tarFile.path); + final byMode = >{}; + 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, () => []).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 _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 _restoreModes(Map> 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 则静默跳过 + } + } + } + } +} diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index abb0d67..b272b67 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -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; + /// 获取发行版存储基础目录: `/distros` Future 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 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 = []; + final stderrBytes = []; + + final stdoutFuture = process.stdout.listen(stdoutBytes.addAll).asFuture(); + final stderrFuture = process.stderr.listen(stderrBytes.addAll).asFuture(); + + 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: diff --git a/lib/services/internal_project_service.dart b/lib/services/internal_project_service.dart index 3e94bd6..01df0d6 100644 --- a/lib/services/internal_project_service.dart +++ b/lib/services/internal_project_service.dart @@ -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/`) - Future importProjectFromArchive(String archivePath, String projectName) async { + /// (采用底层 Isolate 流式分块直写落盘引擎,避免大项目解压内存溢出 OOM) + Future 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 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; + } } diff --git a/lib/services/permission_service.dart b/lib/services/permission_service.dart index 28cb76c..98f3d86 100644 --- a/lib/services/permission_service.dart +++ b/lib/services/permission_service.dart @@ -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 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 resetBatteryOptimizationPrompt() async { + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_keyBatteryOptimizationPrompted); + } catch (_) {} + } } diff --git a/lib/services/project_modules/gradle_project_module.dart b/lib/services/project_modules/gradle_project_module.dart new file mode 100644 index 0000000..b60d65d --- /dev/null +++ b/lib/services/project_modules/gradle_project_module.dart @@ -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 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> 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 parseGradleTasksOutput(String output, String execCmd) { + final List tasks = []; + final lines = LineSplitter.split(output).toList(); + + String currentProjectPrefix = ''; + String currentGroup = 'other'; + bool inTasksSection = false; + + for (int i = 0; i < lines.length; i++) { + final line = lines[i].trim(); + if (line.isEmpty) continue; + + // 匹配项目标题行,形如: + // "Tasks runnable from root project 'demo'" 或 "Tasks runnable from project ':app'" + final projectMatch = RegExp(r"Tasks runnable from (?:root )?project '([^']+)'").firstMatch(line); + if (projectMatch != null) { + final proj = projectMatch.group(1)!; + if (proj.startsWith(':')) { + currentProjectPrefix = '$proj:'; + } else { + currentProjectPrefix = ''; + } + inTasksSection = true; + continue; + } + + // 遇到 Rules 或非任务分段时跳过 + if (line == 'Rules' || line.startsWith('Pattern:')) { + inTasksSection = false; + continue; + } + + // 忽略单纯的分割线 (如 ------------------------------------------------------------) + if (RegExp(r'^[-=]{3,}$').hasMatch(line)) { + continue; + } + + // 匹配分组名称与下划线分割,例如: + // Build tasks + // ----------- + if (i + 1 < lines.length && RegExp(r'^-{3,}$').hasMatch(lines[i + 1].trim())) { + final groupMatch = RegExp(r'^([a-zA-Z0-9_\s]+)\s+tasks$', caseSensitive: false).firstMatch(line); + if (groupMatch != null) { + currentGroup = groupMatch.group(1)!.trim().toLowerCase(); + inTasksSection = true; + i++; // 跳过下划线行 + continue; + } + } + + 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 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; + } +} diff --git a/lib/services/project_modules/project_module.dart b/lib/services/project_modules/project_module.dart new file mode 100644 index 0000000..dedd039 --- /dev/null +++ b/lib/services/project_modules/project_module.dart @@ -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 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 get triggerFiles; + + /// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否,不进行深层解析) + bool shouldActivate(Directory projectDir); + + /// 探测项目任务(支持优先读取本地缓存;当 forceRefresh=true 时强制发起真实探测) + Future> detect(ProjectModuleContext context, {bool forceRefresh = false}); +} diff --git a/lib/services/project_modules/standard_project_modules.dart b/lib/services/project_modules/standard_project_modules.dart new file mode 100644 index 0000000..886f166 --- /dev/null +++ b/lib/services/project_modules/standard_project_modules.dart @@ -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 get triggerFiles => const ['CMakeLists.txt']; + + @override + bool shouldActivate(Directory projectDir) { + return File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync(); + } + + @override + Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { + final projectName = p.basename(context.projectDir.path); + return [ + RunTask( + id: 'detected_cmake_build_run', + name: 'CMake: Build & Run', + command: 'cmake -B build && cmake --build build && ./build/$projectName', + source: TaskSource.detected, + description: 'Configure, build, and try launching the target executable', + group: 'build', + moduleId: id, + icon: Icons.play_circle_outline, + ), + RunTask( + id: 'detected_cmake_build', + name: 'CMake: Build Only', + command: 'cmake -B build && cmake --build build', + source: TaskSource.detected, + description: 'Only execute cmake generation and build', + group: 'build', + moduleId: id, + icon: Icons.build_outlined, + ), + RunTask( + id: 'detected_cmake_clean', + name: 'CMake: Clean', + command: 'rm -rf build', + source: TaskSource.detected, + description: 'Clean build cache directory', + group: 'build', + moduleId: id, + icon: Icons.cleaning_services_outlined, + ), + ]; + } +} + +/// Cargo (Rust) 工程探测模块 +class CargoProjectModule extends ProjectModule { + @override + String get id => 'cargo'; + + @override + String get displayName => 'Cargo'; + + @override + List get triggerFiles => const ['Cargo.toml']; + + @override + bool shouldActivate(Directory projectDir) { + return File(p.join(projectDir.path, 'Cargo.toml')).existsSync(); + } + + @override + Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { + return [ + RunTask( + id: 'detected_cargo_run', + name: 'Cargo: Run', + command: 'cargo run', + source: TaskSource.detected, + description: 'Compile and run Rust project', + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + RunTask( + id: 'detected_cargo_build', + name: 'Cargo: Build', + command: 'cargo build', + source: TaskSource.detected, + description: 'Compile Rust project only', + group: 'build', + moduleId: id, + icon: Icons.build_outlined, + ), + ]; + } +} + +/// NPM (Node / Web) 工程探测模块 +class NpmProjectModule extends ProjectModule { + @override + String get id => 'npm'; + + @override + String get displayName => 'NPM'; + + @override + List get triggerFiles => const ['package.json']; + + @override + bool shouldActivate(Directory projectDir) { + return File(p.join(projectDir.path, 'package.json')).existsSync(); + } + + @override + Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { + return [ + RunTask( + id: 'detected_npm_start', + name: 'NPM: Start', + command: 'npm start', + source: TaskSource.detected, + description: 'Start Node service or frontend development environment', + group: 'application', + moduleId: id, + icon: Icons.rocket_launch_outlined, + ), + RunTask( + id: 'detected_npm_test', + name: 'NPM: Test', + command: 'npm test', + source: TaskSource.detected, + description: 'Execute npm test suite', + group: 'verification', + moduleId: id, + icon: Icons.checklist_outlined, + ), + ]; + } +} + +/// Makefile 工程探测模块 +class MakeProjectModule extends ProjectModule { + @override + String get id => 'make'; + + @override + String get displayName => 'Makefile'; + + @override + List get triggerFiles => const ['Makefile']; + + @override + bool shouldActivate(Directory projectDir) { + return File(p.join(projectDir.path, 'Makefile')).existsSync(); + } + + @override + Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { + return [ + RunTask( + id: 'detected_make_default', + name: 'Make: Default', + command: 'make', + source: TaskSource.detected, + description: 'Execute default Makefile build target', + group: 'build', + moduleId: id, + icon: Icons.build_circle_outlined, + ), + ]; + } +} + +/// Dart (pubspec.yaml) 工程探测模块 +class DartProjectModule extends ProjectModule { + @override + String get id => 'dart'; + + @override + String get displayName => 'Dart'; + + @override + List get triggerFiles => const ['pubspec.yaml']; + + @override + bool shouldActivate(Directory projectDir) { + return File(p.join(projectDir.path, 'pubspec.yaml')).existsSync(); + } + + @override + Future> detect(ProjectModuleContext context, {bool forceRefresh = false}) async { + return [ + RunTask( + id: 'detected_dart_run', + name: 'Dart: Run', + command: 'dart run', + source: TaskSource.detected, + description: 'Launch Dart application', + group: 'application', + moduleId: id, + icon: Icons.play_circle_outline, + ), + ]; + } +} diff --git a/lib/services/project_task_detector.dart b/lib/services/project_task_detector.dart index c99515f..0629751 100644 --- a/lib/services/project_task_detector.dart +++ b/lib/services/project_task_detector.dart @@ -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> detect({ required String projectRoot, String? currentFilePath, - }) async { - final List 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> _detectProjectBuildTasks(String projectRoot) async { - final List 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, + ); } } diff --git a/lib/services/project_task_dispatcher.dart b/lib/services/project_task_dispatcher.dart new file mode 100644 index 0000000..33e39c4 --- /dev/null +++ b/lib/services/project_task_dispatcher.dart @@ -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 _modules = []; + + ProjectTaskDispatcher({List? customModules}) { + if (customModules != null) { + _modules.addAll(customModules); + } else { + _registerDefaultModules(); + } + } + + void _registerDefaultModules() { + _modules.addAll([ + GradleProjectModule(), + CMakeProjectModule(), + CargoProjectModule(), + NpmProjectModule(), + MakeProjectModule(), + DartProjectModule(), + ]); + } + + List 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 getActiveModules(Directory projectDir) { + return _modules.where((m) => m.shouldActivate(projectDir)).toList(); + } + + /// 核心任务探测与分发 + /// [projectRoot]: 工程根目录(宿主绝对路径) + /// [currentFilePath]: 当前编辑器激活打开的文件(宿主绝对路径,可能为 null) + /// [systemName]: 容器实例名称 + /// [forceRefresh]: 是否忽略缓存,强制重新请求真实探测 + /// [onlyModuleId]: 可选,仅执行指定的模块探测 + Future> detect({ + required String projectRoot, + String? currentFilePath, + String systemName = 'ubuntu', + RunTaskStorageService? storageService, + DistroManager? distroManager, + bool forceRefresh = false, + String? onlyModuleId, + }) async { + final List tasks = []; + final projectDir = Directory(projectRoot); + if (!projectDir.existsSync()) { + return tasks; + } + + final context = ProjectModuleContext( + projectDir: projectDir, + 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 []; + } + }), + ); + + 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> 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; + } + } +} diff --git a/lib/services/run_task_storage_service.dart b/lib/services/run_task_storage_service.dart index 808d257..9c1476e 100644 --- a/lib/services/run_task_storage_service.dart +++ b/lib/services/run_task_storage_service.dart @@ -97,4 +97,78 @@ class RunTaskStorageService { Future saveTasks(String projectRoot, List 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/_tasks.json` 中读取模块探测出的任务与缓存元信息 + Future<({List tasks, String? hash, DateTime? updatedAt})> loadModuleTasks( + String projectRoot, + String moduleName, + ) async { + try { + final file = getModuleConfigFile(projectRoot, moduleName); + if (!await file.exists()) { + return (tasks: [], hash: null, updatedAt: null); + } + + final content = await file.readAsString(); + if (content.trim().isEmpty) { + return (tasks: [], 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 list = []; + if (tasksRaw is List) { + for (final item in tasksRaw) { + if (item is Map) { + list.add(RunTask.fromJson(Map.from(item))); + } + } + } + return (tasks: list, hash: hash, updatedAt: updatedAt); + } + return (tasks: [], hash: null, updatedAt: null); + } catch (e) { + debugPrint('[RunTaskStorageService] 读取 ${moduleName}_tasks.json 失败: $e'); + return (tasks: [], hash: null, updatedAt: null); + } + } + + /// 将特定模块探测所得任务与缓存哈希持久化保存到 `.code_editor/_tasks.json` + Future saveModuleTasks({ + required String projectRoot, + required String moduleName, + required List 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'); + } + } } diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index 6a90fdf..c673922 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -7,6 +7,7 @@ import 'package:code_editor/providers/run_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/permission_service.dart'; import 'package:code_editor/services/toolchain_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/views/settings_view.dart'; @@ -268,6 +269,8 @@ class _MainViewState extends State { lastRunTaskId: isCurrentProject ? (runProvider.lastRunTaskId ?? runProvider.lastRunTask?.id) : null, onTaskSelected: (task) => _executeRunTask(context, task), onEditCustomTasks: () => _handleOpenEditRunTasks(context), + onSyncModule: (moduleId) => runProvider.syncModuleTasks(moduleId), + isSyncingModule: (moduleId) => runProvider.isModuleSyncing(moduleId), ); } @@ -320,6 +323,18 @@ class _MainViewState extends State { } } + Future _handleOpenTerminal(BuildContext context) async { + final wentToSettings = await PermissionService.instance.promptBatteryOptimizationIfNeeded(context); + if (wentToSettings) return; + if (context.mounted) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => const TerminalView(), + ), + ); + } + } + @override Widget build(BuildContext context) { final projectProvider = _getProjectProvider(context, listen: true); @@ -377,6 +392,7 @@ class _MainViewState extends State { onCloseProject: () => _handleCloseProject(context), onRun: () => _handleRun(context), onRunTasks: () => _handleOpenRunTasksDialog(context), + onTerminal: () => _handleOpenTerminal(context), onProjectDetect: () => _handleProjectDetect(context), onEditRunTasks: () => _handleOpenEditRunTasks(context), isDetecting: runProvider?.isDetecting ?? false, diff --git a/lib/views/project_management_view.dart b/lib/views/project_management_view.dart index 016080d..fa6605d 100644 --- a/lib/views/project_management_view.dart +++ b/lib/views/project_management_view.dart @@ -235,6 +235,59 @@ class _ProjectManagementViewState extends State { } } + Future _onExportProject(Directory dir, String projectName) async { + final l10n = AppLocalizations.of(context)!; + + // 打开系统文件管理选择导出目标文件夹 + final selectedDir = await FilePicker.platform.getDirectoryPath( + dialogTitle: l10n.selectExportDirectory, + ); + + if (selectedDir == null || selectedDir.trim().isEmpty || !mounted) { + return; + } + + final targetFileName = '$projectName.zip'; + final targetFilePath = p.join(selectedDir, targetFileName); + final targetFile = File(targetFilePath); + + // 若目标文件已存在,弹出覆盖确认 + if (targetFile.existsSync()) { + final confirmOverwrite = await DialogUtils.showDestructiveConfirmDialog( + context, + title: l10n.exportProject, + message: l10n.targetFileAlreadyExists(targetFileName), + confirmText: l10n.overwrite, + cancelText: l10n.cancel, + ); + if (!confirmOverwrite || !mounted) { + return; + } + } + + // 执行流式压缩导出任务 + try { + await DialogUtils.showSyncLoadingDialog( + context, + message: l10n.exportingProject, + task: () async { + await _projectService.exportProjectToZip(dir, targetFilePath); + }, + ); + + if (mounted) { + DialogUtils.showSuccessToast(context, l10n.projectExported); + } + } catch (e) { + if (mounted) { + DialogUtils.showErrorToast( + context, + l10n.exportProjectFailed(e.toString()), + ); + } + } + } + Future _onDeleteProject(Directory dir, String projectName) async { final l10n = AppLocalizations.of(context)!; final confirmed = await DialogUtils.showDestructiveConfirmDialog( @@ -360,6 +413,11 @@ class _ProjectManagementViewState extends State { tooltip: l10n.renameProject, onPressed: () => _onRenameProject(dir, projectName), ), + IconButton( + icon: const Icon(Icons.drive_folder_upload_outlined), + tooltip: l10n.exportProjectTooltip, + onPressed: () => _onExportProject(dir, projectName), + ), IconButton( icon: const Icon(Icons.delete_outline), tooltip: l10n.deleteProject, diff --git a/lib/views/terminal_view.dart b/lib/views/terminal_view.dart index 2337d54..f80f717 100644 --- a/lib/views/terminal_view.dart +++ b/lib/views/terminal_view.dart @@ -13,8 +13,11 @@ import 'package:code_editor/widgets/distro_selector_dialog.dart'; import 'package:code_editor/widgets/terminal_drawer.dart'; import 'package:code_editor/widgets/terminal_keyboard_sink.dart'; import 'package:code_editor/widgets/terminal_modifier_state.dart'; +import 'package:code_editor/services/internal_project_service.dart'; import 'package:code_editor/widgets/virtual_keyboard_widget.dart'; +import 'package:code_editor/widgets/terminal_selection_overlay.dart'; import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; import 'package:xterm/xterm.dart' as xterm; import 'package:xterm/xterm.dart' show TerminalInputHandler, defaultInputHandler; @@ -105,10 +108,12 @@ class _TerminalViewState extends State { final activeIndex = provider.activeIndex; final titleText = activeSession?.name ?? l10n.sessionDefaultName; - // 副标题严格取自当前会话绑定的工作目录根路径 - final sessionWorkspace = activeSession?.workspacePath; - final String? subtitleText = (sessionWorkspace != null && sessionWorkspace.trim().isNotEmpty) - ? sessionWorkspace.trim() + // 副标题取自当前会话绑定的工作目录:若是内部项目则展示项目名,外部项目展示完整绝对路径 + final sessionWorkspace = activeSession?.workspacePath?.trim(); + final String? subtitleText = (sessionWorkspace != null && sessionWorkspace.isNotEmpty) + ? (InternalProjectService.instance.isInternalProject(sessionWorkspace) + ? p.basename(sessionWorkspace) + : sessionWorkspace) : null; return Scaffold( @@ -201,6 +206,10 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> { /// 小键盘修饰键的运行时状态:键盘组件与终端共用同一份 late final TerminalModifierState _modifiers = TerminalModifierState(); + /// 终端控制器与 View GlobalKey(用于选区、手柄与上下文菜单定位) + late final xterm.TerminalController _terminalController = xterm.TerminalController(); + final GlobalKey _terminalViewKey = GlobalKey(); + /// 终端原有的输入处理器与输出出口(用于串联,而不是替换) TerminalInputHandler? _delegateInputHandler; void Function(String)? _delegateOnOutput; @@ -235,6 +244,7 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> { } terminal.onOutput = _delegateOnOutput; _modifiers.dispose(); + _terminalController.dispose(); super.dispose(); } @@ -264,14 +274,22 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> { child: Column( children: [ Expanded( - child: xterm.TerminalView( - session.terminal, + child: TerminalSelectionOverlay( + terminal: session.terminal, + controller: _terminalController, + terminalViewKey: _terminalViewKey, focusNode: session.focusNode, - autofocus: true, - theme: terminalThemeWithBackground(backgroundColor), - textStyle: terminalStyle, - cursorType: xterm.TerminalCursorType.block, - padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0), + child: xterm.TerminalView( + session.terminal, + key: _terminalViewKey, + controller: _terminalController, + focusNode: session.focusNode, + autofocus: true, + theme: terminalThemeWithBackground(backgroundColor), + textStyle: terminalStyle, + cursorType: xterm.TerminalCursorType.block, + padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0), + ), ), ), if (keyboardEnabled && keyboardConfig != null && keyboardConfig.hasKeys) diff --git a/lib/widgets/code_editor_app_bar.dart b/lib/widgets/code_editor_app_bar.dart index abdb389..1ff6ec9 100644 --- a/lib/widgets/code_editor_app_bar.dart +++ b/lib/widgets/code_editor_app_bar.dart @@ -1,4 +1,5 @@ import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/services/permission_service.dart'; import 'package:code_editor/views/terminal_view.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -133,12 +134,16 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget { onSaveAll: onSaveAll, onRunTasks: onRunTasks, onTerminal: onTerminal ?? - () { - Navigator.of(context).push( - MaterialPageRoute( - builder: (context) => const TerminalView(), - ), - ); + () async { + final wentToSettings = await PermissionService.instance.promptBatteryOptimizationIfNeeded(context); + if (wentToSettings) return; + if (context.mounted) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => const TerminalView(), + ), + ); + } }, onProjectDetect: onProjectDetect, onEditRunTasks: onEditRunTasks, diff --git a/lib/widgets/code_editor_menu.dart b/lib/widgets/code_editor_menu.dart index e5d48de..e57210b 100644 --- a/lib/widgets/code_editor_menu.dart +++ b/lib/widgets/code_editor_menu.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:code_editor/l10n/app_localizations.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -34,18 +35,130 @@ class _EditorContextMenuItem extends PopupMenuItem implements PreferredSiz Size get preferredSize => const Size(140, 36); } +/// 移动端选区悬浮工具栏布局代理: +/// 负责根据 EditorToolbarPlacement 与 safeEditorRect(精准剔除 AppBar/TabBar/虚拟小键盘/软键盘)精确定位 +class _MobileToolbarLayoutDelegate extends SingleChildLayoutDelegate { + final TextSelectionToolbarAnchors anchors; + final Rect? renderRect; + final MediaQueryData mediaQuery; + + _MobileToolbarLayoutDelegate({ + required this.anchors, + required this.renderRect, + required this.mediaQuery, + }); + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + return constraints.loosen(); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + // 1. 计算受保护的可视安全编辑区 safeEditorRect + // 顶部:排除 AppBar, TabBar (renderRect.top) 以及系统状态栏 + final double safeTop = max(renderRect?.top ?? 0.0, mediaQuery.padding.top) + 6.0; + // 底部:排除软键盘 (viewInsets.bottom)、虚拟小键盘 (renderRect.bottom) 以及底部安全区 + final double screenBottomWithoutKeyboard = mediaQuery.size.height - mediaQuery.viewInsets.bottom - mediaQuery.padding.bottom; + final double safeBottom = min(renderRect?.bottom ?? screenBottomWithoutKeyboard, screenBottomWithoutKeyboard) - 6.0; + // 左右:留出安全内边距 + final double safeLeft = max(renderRect?.left ?? 0.0, mediaQuery.padding.left) + 8.0; + final double safeRight = min(renderRect?.right ?? mediaQuery.size.width, mediaQuery.size.width - mediaQuery.padding.right) - 8.0; + + final double availableWidth = max(0.0, safeRight - safeLeft); + final double availableHeight = max(0.0, safeBottom - safeTop); + + // 2. 根据 anchors 中的 EditorToolbarPlacement 或传统 anchors 计算位置 + EditorToolbarPlacement placement = EditorToolbarPlacement.aboveStart; + Offset targetOffset = anchors.primaryAnchor; + + if (anchors is EditorSelectionToolbarAnchors) { + final customAnchors = anchors as EditorSelectionToolbarAnchors; + placement = customAnchors.placement; + targetOffset = customAnchors.targetOffset; + } + + double x; + double y; + + switch (placement) { + case EditorToolbarPlacement.center: + // 框选文本完全占据当前屏幕:在中间显示 + x = safeLeft + (availableWidth - childSize.width) / 2.0; + y = safeTop + (availableHeight - childSize.height) / 2.0; + break; + + case EditorToolbarPlacement.top: + // 选区整体在视口上方:在视口顶部贴边显示 + x = safeLeft + (availableWidth - childSize.width) / 2.0; + y = safeTop + 4.0; + break; + + case EditorToolbarPlacement.bottom: + // 选区整体在视口下方:在视口底部贴边显示(紧贴软键盘/小键盘上方) + x = safeLeft + (availableWidth - childSize.width) / 2.0; + y = max(safeTop, safeBottom - childSize.height - 4.0); + break; + + case EditorToolbarPlacement.aboveStart: + // 在左端点上方弹出,若上方空间不足则翻转至下方 + x = targetOffset.dx - childSize.width / 2.0; + final double yAbove = targetOffset.dy - childSize.height - 8.0; + if (yAbove >= safeTop) { + y = yAbove; + } else { + // 上方空间不足,翻转到左端点下方(行高约为 24) + y = targetOffset.dy + 24.0 + 8.0; + } + break; + + case EditorToolbarPlacement.belowEnd: + // 在右端点下方弹出,若下方空间不足则翻转至上方 + x = targetOffset.dx - childSize.width / 2.0; + // 右端点手柄下挂高度约 28px,避免遮挡光标水滴手柄 + final double yBelow = targetOffset.dy + 24.0 + 26.0; + if (yBelow + childSize.height <= safeBottom) { + y = yBelow; + } else { + // 下方空间不足(被软键盘或小键盘限制),翻转到右端点上方 + y = targetOffset.dy - childSize.height - 8.0; + } + break; + } + + // 3. 水平与垂直安全夹紧,防止任何溢出 + final double clampedX = (availableWidth >= childSize.width) + ? x.clamp(safeLeft, safeRight - childSize.width) + : safeLeft; + final double clampedY = (availableHeight >= childSize.height) + ? y.clamp(safeTop, safeBottom - childSize.height) + : safeTop; + + return Offset(clampedX, clampedY); + } + + @override + bool shouldRelayout(covariant _MobileToolbarLayoutDelegate oldDelegate) { + return anchors != oldDelegate.anchors || + renderRect != oldDelegate.renderRect || + mediaQuery != oldDelegate.mediaQuery; + } +} + /// 移动端选区悬浮工具栏(基于 OverlayEntry,绝不压入 Route,软键盘保持弹起) class _MobileSelectionToolbarWidget extends StatefulWidget { final TextSelectionToolbarAnchors anchors; final CodeLineEditingController controller; final VoidCallback onDismiss; final FocusNode? focusNode; + final Rect? renderRect; const _MobileSelectionToolbarWidget({ required this.anchors, required this.controller, required this.onDismiss, this.focusNode, + this.renderRect, }); @override @@ -79,76 +192,130 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi widget.controller.selection.extentOffset != -1 && !widget.controller.selection.isCollapsed; - final mediaQuery = MediaQuery.of(context); - final availableBottom = mediaQuery.size.height - mediaQuery.viewInsets.bottom; - TextSelectionToolbarAnchors effectiveAnchors = widget.anchors; + final cutLabel = l10n?.cut ?? 'Cut'; + final copyLabel = l10n?.copy ?? 'Copy'; + final pasteLabel = l10n?.paste ?? 'Paste'; + final selectAllLabel = l10n?.selectAll ?? 'Select All'; - final primary = effectiveAnchors.primaryAnchor; - final secondary = effectiveAnchors.secondaryAnchor; + final theme = Theme.of(context); - // 针对虚拟键盘或底栏的全局安全高度校准: - if (secondary != null && secondary.dy + 65.0 > availableBottom) { - effectiveAnchors = TextSelectionToolbarAnchors( - primaryAnchor: Offset( - secondary.dx.clamp(120.0, max(120.0, mediaQuery.size.width - 120.0)), - (availableBottom - 12.0).clamp(mediaQuery.padding.top + 48.0, availableBottom), + final toolbarContent = Material( + elevation: 6.0, + shadowColor: Colors.black45, + color: theme.colorScheme.surfaceContainerHighest, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8.0), + side: BorderSide( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.6), + width: 0.8, ), - secondaryAnchor: null, - ); - } else if (primary.dy + 60.0 > availableBottom && primary.dx >= 0) { - effectiveAnchors = TextSelectionToolbarAnchors( - primaryAnchor: Offset( - primary.dx.clamp(120.0, max(120.0, mediaQuery.size.width - 120.0)), - (availableBottom - 12.0).clamp(mediaQuery.padding.top + 48.0, availableBottom), + ), + clipBehavior: Clip.antiAlias, + child: IntrinsicHeight( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (hasSelection) ...[ + _buildItem( + context, + icon: Icons.content_cut, + label: cutLabel, + onTap: () { + widget.controller.cut(); + widget.onDismiss(); + widget.focusNode?.requestFocus(); + }, + ), + _buildDivider(context), + _buildItem( + context, + icon: Icons.copy, + label: copyLabel, + onTap: () { + widget.controller.copy(); + widget.onDismiss(); + widget.focusNode?.requestFocus(); + }, + ), + ], + if (_canPaste) ...[ + if (hasSelection) _buildDivider(context), + _buildItem( + context, + icon: Icons.paste, + label: pasteLabel, + onTap: () { + widget.controller.paste(); + widget.onDismiss(); + widget.focusNode?.requestFocus(); + }, + ), + ], + if (!widget.controller.isEmpty) ...[ + _buildDivider(context), + _buildItem( + context, + icon: Icons.select_all, + label: selectAllLabel, + onTap: () { + widget.controller.selectAll(); + widget.onDismiss(); + widget.focusNode?.requestFocus(); + }, + ), + ], + ], ), - secondaryAnchor: null, - ); - } + ), + ); - return AdaptiveTextSelectionToolbar.buttonItems( - anchors: effectiveAnchors, - buttonItems: [ - if (hasSelection) - ContextMenuButtonItem( - label: l10n?.cut ?? '剪切', - type: ContextMenuButtonType.cut, - onPressed: () { - widget.controller.cut(); - widget.onDismiss(); - widget.focusNode?.requestFocus(); - }, - ), - if (hasSelection) - ContextMenuButtonItem( - label: l10n?.copy ?? '复制', - type: ContextMenuButtonType.copy, - onPressed: () { - widget.controller.copy(); - widget.onDismiss(); - widget.focusNode?.requestFocus(); - }, - ), - if (_canPaste) - ContextMenuButtonItem( - label: l10n?.paste ?? '粘贴', - type: ContextMenuButtonType.paste, - onPressed: () { - widget.controller.paste(); - widget.onDismiss(); - widget.focusNode?.requestFocus(); - }, - ), - if (!widget.controller.isEmpty) - ContextMenuButtonItem( - label: l10n?.selectAll ?? '全选', - type: ContextMenuButtonType.selectAll, - onPressed: () { - widget.controller.selectAll(); - widget.onDismiss(); - widget.focusNode?.requestFocus(); - }, - ), - ], + return CustomSingleChildLayout( + delegate: _MobileToolbarLayoutDelegate( + anchors: widget.anchors, + renderRect: widget.renderRect, + mediaQuery: MediaQuery.of(context), + ), + child: toolbarContent, + ); + } + + Widget _buildItem( + BuildContext context, { + required IconData icon, + required String label, + required VoidCallback onTap, + }) { + final colorScheme = Theme.of(context).colorScheme; + return InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: colorScheme.onSurface), + const SizedBox(width: 4), + Text( + label, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: colorScheme.onSurface, + ), + ), + ], + ), + ), + ); + } + + Widget _buildDivider(BuildContext context) { + return VerticalDivider( + width: 1, + thickness: 0.8, + indent: 6, + endIndent: 6, + color: Theme.of(context).colorScheme.outlineVariant.withValues(alpha: 0.5), ); } } @@ -158,6 +325,12 @@ class CodeEditorToolbarController implements SelectionToolbarController { final FocusNode? focusNode; late final SelectionToolbarController _mobileController; + CodeLineEditingController? _lastController; + TextSelectionToolbarAnchors? _lastAnchors; + Rect? _lastRenderRect; + LayerLink? _lastLayerLink; + ValueNotifier? _lastVisibility; + CodeEditorToolbarController({this.focusNode}) { _mobileController = MobileSelectionToolbarController( builder: ({ @@ -166,12 +339,14 @@ class CodeEditorToolbarController implements SelectionToolbarController { required CodeLineEditingController controller, required VoidCallback onDismiss, required VoidCallback onRefresh, + Rect? renderRect, }) { return _MobileSelectionToolbarWidget( anchors: anchors, controller: controller, onDismiss: onDismiss, focusNode: focusNode, + renderRect: renderRect, ); }, ); @@ -191,6 +366,12 @@ class CodeEditorToolbarController implements SelectionToolbarController { required LayerLink layerLink, required ValueNotifier visibility, }) { + _lastController = controller; + _lastAnchors = anchors; + _lastRenderRect = renderRect; + _lastLayerLink = layerLink; + _lastVisibility = visibility; + if (renderRect == null) { _showDesktopMenu( context: context, @@ -198,11 +379,10 @@ class CodeEditorToolbarController implements SelectionToolbarController { anchors: anchors, ); } else { - final safeAnchors = _sanitizeMobileAnchors(anchors, renderRect); _mobileController.show( context: context, controller: controller, - anchors: safeAnchors, + anchors: anchors, renderRect: renderRect, layerLink: layerLink, visibility: visibility, @@ -210,56 +390,22 @@ class CodeEditorToolbarController implements SelectionToolbarController { } } - /// 智能校准移动端选区工具栏锚点: - /// 1. 优先展示在选区上方(primaryAnchor),避免遮挡当前选中的代码内容及下方代码; - /// 2. 当选区位于视口顶部(上方空间不足 54px 时),智能翻转至选区下方(secondaryAnchor); - /// 3. 当选区靠近视口底部或键盘时,保护次锚点不落入键盘/底栏区域,坚决保持在上方; - /// 4. 水平坐标智能居中并进行安全边缘约束(左右各留出 120px 缓冲),防止菜单按钮溢出屏幕。 - static TextSelectionToolbarAnchors _sanitizeMobileAnchors( - TextSelectionToolbarAnchors anchors, - Rect renderRect, - ) { - final primary = anchors.primaryAnchor; - final secondary = anchors.secondaryAnchor; - - // 确定水平基准坐标并进行安全边距夹取(左右两端预留充足空间以保证多个操作按钮完整可见) - final double rawX = (primary.dx > 0) ? primary.dx : (secondary?.dx ?? renderRect.center.dx); - final double safeX = (renderRect.width > 240.0) - ? rawX.clamp(renderRect.left + 120.0, renderRect.right - 120.0) - : renderRect.center.dx; - - // 计算选区上方与下方的垂直可用净空间 - final double topY = (primary.dy > 0) ? primary.dy : (secondary?.dy ?? renderRect.top + 60.0); - final double bottomY = (secondary != null && secondary.dy > 0) ? secondary.dy : (topY + 30.0); - - final double spaceAbove = topY - renderRect.top; - final double spaceBelow = renderRect.bottom - bottomY; - - // 规则 1:选区上方空间充足(>= 54.0px,足够容纳工具栏),置于选区上方! - // 选区本身与下方的代码行将保持 100% 清晰可见,绝不遮挡。 - if (spaceAbove >= 54.0) { - return TextSelectionToolbarAnchors( - primaryAnchor: Offset(safeX, topY), - secondaryAnchor: spaceBelow >= 64.0 ? Offset(safeX, bottomY) : null, - ); + /// 重新唤起上一次的选区悬浮工具栏(常用于滚动结束时自动恢复) + void reshowLastToolbar(BuildContext context) { + final controller = _lastController; + if (controller == null || controller.selection.isCollapsed || controller.selection.baseOffset == -1) { + return; } - - // 规则 2:选区位于第一行/第二行(上方空间不足 54px),但下方空间充足(>= 64px) - // 智能翻转至选区下方,保证不超出屏幕顶部也不遮挡第一行 - if (spaceBelow >= 64.0) { - return TextSelectionToolbarAnchors( - primaryAnchor: const Offset(-10000, -10000), - secondaryAnchor: Offset(safeX, bottomY), - ); + if (_lastAnchors == null || _lastLayerLink == null || _lastVisibility == null) { + return; } - - // 规则 3:选区跨越很大或上下空间均受限时,安全悬浮于可视区域上边缘内侧 - return TextSelectionToolbarAnchors( - primaryAnchor: Offset( - safeX, - (renderRect.top + 56.0).clamp(renderRect.top + 10.0, renderRect.bottom - 10.0), - ), - secondaryAnchor: null, + show( + context: context, + controller: controller, + anchors: _lastAnchors!, + renderRect: _lastRenderRect, + layerLink: _lastLayerLink!, + visibility: _lastVisibility!, ); } @@ -300,7 +446,7 @@ class CodeEditorToolbarController implements SelectionToolbarController { ), items: [ _EditorContextMenuItem( - text: l10n?.cut ?? '剪切', + text: l10n?.cut ?? 'Cut', icon: Icons.content_cut, enabled: hasSelection, onTap: () { @@ -308,7 +454,7 @@ class CodeEditorToolbarController implements SelectionToolbarController { }, ), _EditorContextMenuItem( - text: l10n?.copy ?? '复制', + text: l10n?.copy ?? 'Copy', icon: Icons.copy, enabled: hasSelection, onTap: () { @@ -316,7 +462,7 @@ class CodeEditorToolbarController implements SelectionToolbarController { }, ), _EditorContextMenuItem( - text: l10n?.paste ?? '粘贴', + text: l10n?.paste ?? 'Paste', icon: Icons.paste, enabled: hasClipboard, onTap: () { @@ -325,7 +471,7 @@ class CodeEditorToolbarController implements SelectionToolbarController { ), const PopupMenuDivider(height: 1), _EditorContextMenuItem( - text: l10n?.selectAll ?? '全选', + text: l10n?.selectAll ?? 'Select All', icon: Icons.select_all, enabled: !controller.isEmpty, onTap: () { diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index 765a23d..f9843f4 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -457,56 +457,56 @@ class _CodeEditorWidgetState extends State { controller: controller, focusNode: _focusNode, scrollController: _scrollController, - wordWrap: activeWordWrap, - toolbarController: _toolbarController, - margin: const EdgeInsets.only(left: 2.0, top: 4.0, right: 8, bottom: 8.0), - padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - style: CodeEditorStyle( - fontSize: displayFontSize, - textColor: activeTheme.textColor, - backgroundColor: activeTheme.backgroundColor, - cursorColor: activeTheme.cursorColor, - cursorLineColor: activeTheme.cursorLineColor, - selectionColor: activeTheme.selectionColor, - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - codeTheme: CodeHighlightTheme( - languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath), - theme: activeTheme.highlightTheme, + wordWrap: activeWordWrap, + toolbarController: _toolbarController, + margin: const EdgeInsets.only(left: 2.0, top: 4.0, right: 8, bottom: 8.0), + padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), + style: CodeEditorStyle( + fontSize: displayFontSize, + textColor: activeTheme.textColor, + backgroundColor: activeTheme.backgroundColor, + cursorColor: activeTheme.cursorColor, + cursorLineColor: activeTheme.cursorLineColor, + selectionColor: activeTheme.selectionColor, + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + codeTheme: CodeHighlightTheme( + languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath), + theme: activeTheme.highlightTheme, + ), ), + indicatorBuilder: (context, editingController, chunkController, notifier) { + return Row( + children: [ + DefaultCodeLineNumber( + controller: editingController, + notifier: notifier, + textStyle: TextStyle( + color: activeTheme.gutterTextColor, + fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + ), + focusedTextStyle: TextStyle( + color: activeTheme.focusedGutterTextColor, + fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontWeight: FontWeight.bold, + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + ), + ), + DefaultCodeChunkIndicator( + width: 20, + controller: chunkController, + notifier: notifier, + painter: DefaultCodeChunkIndicatorPainter( + color: activeTheme.gutterTextColor, + ), + ), + ], + ); + }, ), - indicatorBuilder: (context, editingController, chunkController, notifier) { - return Row( - children: [ - DefaultCodeLineNumber( - controller: editingController, - notifier: notifier, - textStyle: TextStyle( - color: activeTheme.gutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - ), - focusedTextStyle: TextStyle( - color: activeTheme.focusedGutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), - fontWeight: FontWeight.bold, - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - ), - ), - DefaultCodeChunkIndicator( - width: 20, - controller: chunkController, - notifier: notifier, - painter: DefaultCodeChunkIndicatorPainter( - color: activeTheme.gutterTextColor, - ), - ), - ], - ); - }, - ), if (_isPinching && _activeZoomFontSize != null) Center( child: IgnorePointer( diff --git a/lib/widgets/project_history_widget.dart b/lib/widgets/project_history_widget.dart index 6f92470..d275040 100644 --- a/lib/widgets/project_history_widget.dart +++ b/lib/widgets/project_history_widget.dart @@ -2,6 +2,7 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/project_history.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/internal_project_service.dart'; import 'package:code_editor/services/project_history_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:flutter/material.dart'; @@ -196,7 +197,12 @@ class _ProjectHistoryWidgetState lastFile.trim().isNotEmpty) ? p.basename(lastFile) : l10n.noOpenFile; - final rootDir = item.rootPath ?? l10n.unknownDirectory; + final rawRoot = item.rootPath; + final displayRoot = (rawRoot != null && rawRoot.trim().isNotEmpty) + ? (InternalProjectService.instance.isInternalProject(rawRoot) + ? p.basename(rawRoot) + : rawRoot) + : l10n.unknownDirectory; return InkWell( onTap: () { @@ -235,9 +241,9 @@ class _ProjectHistoryWidgetState overflow: TextOverflow.ellipsis, ), const SizedBox(height: 4), - // 下面:一行小字表示根目录 + // 下面:一行小字表示根目录或内部项目名 Text( - rootDir, + displayRoot, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), diff --git a/lib/widgets/run_tasks_dialog.dart b/lib/widgets/run_tasks_dialog.dart index e57eac1..2c2247b 100644 --- a/lib/widgets/run_tasks_dialog.dart +++ b/lib/widgets/run_tasks_dialog.dart @@ -1,14 +1,18 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import '../models/run_task.dart'; +import '../providers/run_provider.dart'; -/// 运行任务选择弹窗(带顶部搜索栏、区分系统探测与自定义任务,点击直接调度执行) +/// 运行任务选择弹窗(带顶部搜索栏、区分系统探测与自定义任务、支持模块深度重新同步、点击直接调度执行) class RunTasksDialog extends StatefulWidget { final List customTasks; final List detectedTasks; final String? lastRunTaskId; final ValueChanged onTaskSelected; final VoidCallback onEditCustomTasks; + final void Function(String moduleId)? onSyncModule; + final bool Function(String moduleId)? isSyncingModule; const RunTasksDialog({ super.key, @@ -17,6 +21,8 @@ class RunTasksDialog extends StatefulWidget { this.lastRunTaskId, required this.onTaskSelected, required this.onEditCustomTasks, + this.onSyncModule, + this.isSyncingModule, }); static Future show({ @@ -26,6 +32,8 @@ class RunTasksDialog extends StatefulWidget { String? lastRunTaskId, required ValueChanged onTaskSelected, required VoidCallback onEditCustomTasks, + void Function(String moduleId)? onSyncModule, + bool Function(String moduleId)? isSyncingModule, }) { return showDialog( context: context, @@ -35,6 +43,8 @@ class RunTasksDialog extends StatefulWidget { lastRunTaskId: lastRunTaskId, onTaskSelected: onTaskSelected, onEditCustomTasks: onEditCustomTasks, + onSyncModule: onSyncModule, + isSyncingModule: isSyncingModule, ), ); } @@ -67,9 +77,11 @@ class _RunTasksDialogState extends State { if (_searchQuery.isEmpty) return true; final name = task.getLocalizedName(l10n); final desc = task.getLocalizedDescription(l10n); + final group = task.group ?? ''; return name.toLowerCase().contains(_searchQuery) || task.command.toLowerCase().contains(_searchQuery) || desc.toLowerCase().contains(_searchQuery) || + group.toLowerCase().contains(_searchQuery) || (task.description?.toLowerCase().contains(_searchQuery) ?? false); } @@ -77,10 +89,30 @@ class _RunTasksDialogState extends State { Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = AppLocalizations.of(context)!; - final filteredCustom = widget.customTasks.where((t) => _matchesQuery(t, l10n)).toList(); - final filteredDetected = widget.detectedTasks.where((t) => _matchesQuery(t, l10n)).toList(); + + // 优先响应父级 Provider 数据变化,保证静默后台自省完成后对话框无感自动刷新 + RunProvider? runProvider; + try { + runProvider = Provider.of(context); + } catch (_) {} + + final effectiveCustomTasks = runProvider?.customTasks ?? widget.customTasks; + final effectiveDetectedTasks = runProvider?.detectedTasks ?? widget.detectedTasks; + final effectiveLastRunTaskId = runProvider?.lastRunTaskId ?? widget.lastRunTaskId; + + final filteredCustom = effectiveCustomTasks.where((t) => _matchesQuery(t, l10n)).toList(); + final filteredDetected = effectiveDetectedTasks.where((t) => _matchesQuery(t, l10n)).toList(); final hasAny = filteredCustom.isNotEmpty || filteredDetected.isNotEmpty; + // 检测是否存在 Gradle 模块任务 + final hasGradleTasks = filteredDetected.any( + (t) => t.moduleId == 'gradle' || t.id.startsWith('gradle_') || t.id.startsWith('detected_gradle_'), + ); + + final isGradleSyncing = (widget.isSyncingModule != null) + ? widget.isSyncingModule!('gradle') + : (runProvider?.isModuleSyncing('gradle') ?? false); + return Dialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), child: ConstrainedBox( @@ -148,13 +180,26 @@ class _RunTasksDialogState extends State { : ListView( children: [ if (filteredDetected.isNotEmpty) ...[ - _buildSectionHeader(context, l10n.systemDetectedTasks, Icons.radar_outlined), - ...filteredDetected.map((task) => _buildTaskItem(context, task, l10n)), + _buildSectionHeader( + context, + l10n.systemDetectedTasks, + Icons.radar_outlined, + trailing: hasGradleTasks + ? _buildGradleSyncAction(context, l10n, isGradleSyncing, () { + if (widget.onSyncModule != null) { + widget.onSyncModule!('gradle'); + } else { + runProvider?.syncModuleTasks('gradle'); + } + }) + : null, + ), + ...filteredDetected.map((task) => _buildTaskItem(context, task, l10n, effectiveLastRunTaskId)), const SizedBox(height: 8), ], if (filteredCustom.isNotEmpty) ...[ _buildSectionHeader(context, l10n.userCustomTasks, Icons.person_outline), - ...filteredCustom.map((task) => _buildTaskItem(context, task, l10n)), + ...filteredCustom.map((task) => _buildTaskItem(context, task, l10n, effectiveLastRunTaskId)), ], ], ), @@ -166,7 +211,70 @@ class _RunTasksDialogState extends State { ); } - Widget _buildSectionHeader(BuildContext context, String title, IconData icon) { + Widget _buildGradleSyncAction( + BuildContext context, + AppLocalizations l10n, + bool isSyncing, + VoidCallback onSync, + ) { + final theme = Theme.of(context); + if (isSyncing) { + return Padding( + padding: const EdgeInsets.only(right: 6), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 6), + Text( + l10n.syncingTasks, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.primary, + ), + ), + ], + ), + ); + } + + return InkWell( + borderRadius: BorderRadius.circular(12), + onTap: onSync, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.refresh, size: 14, color: theme.colorScheme.primary), + const SizedBox(width: 4), + Text( + l10n.resyncModuleTasks, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: theme.colorScheme.primary, + ), + ), + ], + ), + ), + ); + } + + Widget _buildSectionHeader( + BuildContext context, + String title, + IconData icon, { + Widget? trailing, + }) { final theme = Theme.of(context); return Padding( padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 4), @@ -174,21 +282,24 @@ class _RunTasksDialogState extends State { children: [ Icon(icon, size: 16, color: theme.colorScheme.primary), const SizedBox(width: 6), - Text( - title, - style: theme.textTheme.labelMedium?.copyWith( - color: theme.colorScheme.primary, - fontWeight: FontWeight.bold, + Expanded( + child: Text( + title, + style: theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ), + if (trailing != null) trailing, ], ), ); } - Widget _buildTaskItem(BuildContext context, RunTask task, AppLocalizations l10n) { + Widget _buildTaskItem(BuildContext context, RunTask task, AppLocalizations l10n, String? lastRunTaskId) { final theme = Theme.of(context); - final isLastRun = widget.lastRunTaskId != null && widget.lastRunTaskId == task.id; + final isLastRun = lastRunTaskId != null && lastRunTaskId == task.id; final cardColor = isLastRun ? Colors.green.withValues(alpha: 0.15) @@ -222,6 +333,23 @@ class _RunTasksDialogState extends State { ), ), ), + if (task.group != null && task.group!.isNotEmpty && task.group != 'single_file') + Container( + margin: const EdgeInsets.only(left: 6), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1.5), + decoration: BoxDecoration( + color: theme.colorScheme.secondaryContainer.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + task.group!, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w500, + color: theme.colorScheme.onSecondaryContainer, + ), + ), + ), if (isLastRun) Container( margin: const EdgeInsets.only(left: 6), diff --git a/lib/widgets/terminal_selection_overlay.dart b/lib/widgets/terminal_selection_overlay.dart new file mode 100644 index 0000000..6c7d983 --- /dev/null +++ b/lib/widgets/terminal_selection_overlay.dart @@ -0,0 +1,524 @@ +// ignore_for_file: implementation_imports +import 'dart:math'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:xterm/src/ui/render.dart'; +import 'package:xterm/xterm.dart' as xterm; + +enum _DraggingHandle { none, start, end } + +/// 终端文字框选交互叠加层 +/// 包含双端拖动手柄(Start/End Handle)与高层级浮动上下文操作菜单(复制、粘贴、全选) +class TerminalSelectionOverlay extends StatefulWidget { + final xterm.Terminal terminal; + final xterm.TerminalController controller; + final GlobalKey terminalViewKey; + final FocusNode focusNode; + final Widget child; + + const TerminalSelectionOverlay({ + super.key, + required this.terminal, + required this.controller, + required this.terminalViewKey, + required this.focusNode, + required this.child, + }); + + @override + State createState() => _TerminalSelectionOverlayState(); +} + +class _TerminalSelectionOverlayState extends State { + OverlayEntry? _menuOverlayEntry; + _DraggingHandle _dragging = _DraggingHandle.none; + bool _isScrolling = false; + bool _isPointerSelecting = false; + Offset? _lastActiveAnchor; + + @override + void initState() { + super.initState(); + widget.controller.addListener(_onSelectionChanged); + } + + @override + void didUpdateWidget(TerminalSelectionOverlay oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + oldWidget.controller.removeListener(_onSelectionChanged); + widget.controller.addListener(_onSelectionChanged); + } + } + + @override + void dispose() { + widget.controller.removeListener(_onSelectionChanged); + _hideMenu(); + super.dispose(); + } + + RenderTerminal? get _renderTerminal { + return widget.terminalViewKey.currentState?.renderTerminal; + } + + void _onSelectionChanged() { + if (!mounted) return; + final selection = widget.controller.selection; + if (selection == null || selection.isCollapsed) { + _hideMenu(); + setState(() {}); + return; + } + + // 若非正在拖动手柄或滑动,展示菜单 + if (_dragging == _DraggingHandle.none && !_isScrolling && !_isPointerSelecting) { + _updateLastActiveAnchorDefault(); + _showMenu(); + } + setState(() {}); + } + + void _updateLastActiveAnchorDefault() { + final render = _renderTerminal; + final selection = widget.controller.selection; + if (render == null || selection == null || selection.isCollapsed) return; + + final range = selection.normalized; + final endOffset = render.getOffset(range.end); + final globalEnd = render.localToGlobal( + endOffset + Offset(render.cellSize.width, render.cellSize.height), + ); + _lastActiveAnchor = globalEnd; + } + + void _hideMenu() { + _menuOverlayEntry?.remove(); + _menuOverlayEntry = null; + } + + void _showMenu([Offset? targetAnchor]) { + _hideMenu(); + if (!mounted) return; + + final selection = widget.controller.selection; + if (selection == null || selection.isCollapsed) return; + + final anchor = targetAnchor ?? _lastActiveAnchor; + if (anchor == null) return; + _lastActiveAnchor = anchor; + + final overlayState = Overlay.of(context, rootOverlay: true); + + _menuOverlayEntry = OverlayEntry( + builder: (context) { + return _TerminalContextMenuWidget( + anchor: anchor, + onCopy: _handleCopy, + onPaste: _handlePaste, + onSelectAll: _handleSelectAll, + onDismiss: _hideMenu, + ); + }, + ); + + overlayState.insert(_menuOverlayEntry!); + } + + Future _handleCopy() async { + final selection = widget.controller.selection; + if (selection == null || selection.isCollapsed) { + _hideMenu(); + return; + } + final text = widget.terminal.buffer.getText(selection); + await Clipboard.setData(ClipboardData(text: text)); + _hideMenu(); + widget.controller.clearSelection(); + if (mounted) { + final l10n = AppLocalizations.of(context); + if (l10n != null) { + DialogUtils.showSuccessToast(context, l10n.copiedToClipboard); + } + } + } + + Future _handlePaste() async { + _hideMenu(); + final data = await Clipboard.getData(Clipboard.kTextPlain); + final text = data?.text; + if (text != null && text.isNotEmpty) { + widget.terminal.paste(text); + widget.controller.clearSelection(); + } + } + + void _handleSelectAll() { + final width = widget.terminal.viewWidth; + final height = widget.terminal.buffer.height; + widget.controller.setSelection( + widget.terminal.buffer.createAnchor(0, 0), + widget.terminal.buffer.createAnchor(max(0, width - 1), max(0, height - 1)), + mode: xterm.SelectionMode.line, + ); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _updateLastActiveAnchorDefault(); + _showMenu(); + } + }); + } + + // --- 手柄拖拽逻辑 --- + + void _onStartHandlePanStart(DragStartDetails details) { + _dragging = _DraggingHandle.start; + _hideMenu(); + } + + void _onStartHandlePanUpdate(DragUpdateDetails details) { + final render = _renderTerminal; + final selection = widget.controller.selection; + if (render == null || selection == null) return; + + final range = selection.normalized; + final localPos = render.globalToLocal(details.globalPosition); + final adjusted = Offset(localPos.dx, localPos.dy - render.cellSize.height / 2); + final cell = render.getCellOffset(adjusted); + + // 约束:起始手柄不能越过结束手柄 + if (cell.isBefore(range.end) || cell.isEqual(range.end)) { + widget.controller.setSelection( + widget.terminal.buffer.createAnchorFromOffset(cell), + widget.terminal.buffer.createAnchorFromOffset(range.end), + ); + final newLocal = render.getOffset(cell); + _lastActiveAnchor = render.localToGlobal(newLocal + Offset(0, render.cellSize.height)); + } + } + + void _onStartHandlePanEnd(DragEndDetails details) { + _dragging = _DraggingHandle.none; + if (mounted && widget.controller.selection != null && !widget.controller.selection!.isCollapsed) { + _showMenu(_lastActiveAnchor); + } + } + + void _onEndHandlePanStart(DragStartDetails details) { + _dragging = _DraggingHandle.end; + _hideMenu(); + } + + void _onEndHandlePanUpdate(DragUpdateDetails details) { + final render = _renderTerminal; + final selection = widget.controller.selection; + if (render == null || selection == null) return; + + final range = selection.normalized; + final localPos = render.globalToLocal(details.globalPosition); + final adjusted = Offset(localPos.dx, localPos.dy - render.cellSize.height / 2); + final cell = render.getCellOffset(adjusted); + + // 约束:结束手柄不能移到起始手柄之前 + if (cell.isAfter(range.begin) || cell.isEqual(range.begin)) { + widget.controller.setSelection( + widget.terminal.buffer.createAnchorFromOffset(range.begin), + widget.terminal.buffer.createAnchorFromOffset(cell), + ); + final newLocal = render.getOffset(cell); + _lastActiveAnchor = render.localToGlobal( + newLocal + Offset(render.cellSize.width, render.cellSize.height), + ); + } + } + + void _onEndHandlePanEnd(DragEndDetails details) { + _dragging = _DraggingHandle.none; + if (mounted && widget.controller.selection != null && !widget.controller.selection!.isCollapsed) { + _showMenu(_lastActiveAnchor); + } + } + + @override + Widget build(BuildContext context) { + final selection = widget.controller.selection; + final hasSelection = selection != null && !selection.isCollapsed; + final render = _renderTerminal; + + Offset? startHandleLocal; + Offset? endHandleLocal; + + if (hasSelection && render != null && render.hasSize) { + final range = selection.normalized; + final startCellOffset = render.getOffset(range.begin); + final endCellOffset = render.getOffset(range.end); + + final viewportHeight = render.size.height; + final viewportWidth = render.size.width; + + // 起始手柄锚点(字符底部左侧) + final rawStartY = startCellOffset.dy + render.cellSize.height; + final clampedStartY = rawStartY.clamp(0.0, viewportHeight - 10.0); + final clampedStartX = startCellOffset.dx.clamp(0.0, viewportWidth - 20.0); + startHandleLocal = Offset(clampedStartX, clampedStartY); + + // 结束手柄锚点(字符底部右侧) + final rawEndY = endCellOffset.dy + render.cellSize.height; + final clampedEndY = rawEndY.clamp(0.0, viewportHeight - 10.0); + final clampedEndX = (endCellOffset.dx + render.cellSize.width).clamp(0.0, viewportWidth - 20.0); + endHandleLocal = Offset(clampedEndX, clampedEndY); + } + + return NotificationListener( + onNotification: (notification) { + if (notification is ScrollStartNotification) { + _isScrolling = true; + _hideMenu(); + } else if (notification is ScrollUpdateNotification) { + if (mounted) setState(() {}); + } else if (notification is ScrollEndNotification) { + _isScrolling = false; + if (hasSelection && mounted && _dragging == _DraggingHandle.none) { + _showMenu(_lastActiveAnchor); + } + } + return false; + }, + child: Listener( + onPointerDown: (event) { + _isPointerSelecting = true; + }, + onPointerMove: (event) { + if (_isPointerSelecting) { + _hideMenu(); + } + }, + onPointerUp: (event) { + _isPointerSelecting = false; + if (widget.controller.selection != null && !widget.controller.selection!.isCollapsed) { + _lastActiveAnchor = event.position; + if (_dragging == _DraggingHandle.none && !_isScrolling) { + _showMenu(_lastActiveAnchor); + } + } + setState(() {}); + }, + child: Stack( + children: [ + widget.child, + if (hasSelection && startHandleLocal != null) + Positioned( + left: startHandleLocal.dx - 32.0, + top: startHandleLocal.dy - 10.0, + child: _TerminalSelectionHandle( + isStart: true, + lineHeight: render?.cellSize.height ?? 20.0, + onPanStart: _onStartHandlePanStart, + onPanUpdate: _onStartHandlePanUpdate, + onPanEnd: _onStartHandlePanEnd, + ), + ), + if (hasSelection && endHandleLocal != null) + Positioned( + left: endHandleLocal.dx - 10.0, + top: endHandleLocal.dy - 10.0, + child: _TerminalSelectionHandle( + isStart: false, + lineHeight: render?.cellSize.height ?? 20.0, + onPanStart: _onEndHandlePanStart, + onPanUpdate: _onEndHandlePanUpdate, + onPanEnd: _onEndHandlePanEnd, + ), + ), + ], + ), + ), + ); + } +} + +/// 终端选区端点拖动手柄组件(采用与编辑区一致的 Material 水滴造型手柄,兼顾触屏大热区与鼠标拖拽) +class _TerminalSelectionHandle extends StatelessWidget { + final bool isStart; + final double lineHeight; + final GestureDragStartCallback onPanStart; + final GestureDragUpdateCallback onPanUpdate; + final GestureDragEndCallback onPanEnd; + + const _TerminalSelectionHandle({ + required this.isStart, + required this.lineHeight, + required this.onPanStart, + required this.onPanUpdate, + required this.onPanEnd, + }); + + @override + Widget build(BuildContext context) { + final type = isStart ? TextSelectionHandleType.left : TextSelectionHandleType.right; + + return MouseRegion( + cursor: SystemMouseCursors.grab, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onPanStart: onPanStart, + onPanUpdate: onPanUpdate, + onPanEnd: onPanEnd, + child: Padding( + padding: const EdgeInsets.all(10.0), + child: materialTextSelectionControls.buildHandle( + context, + type, + lineHeight, + ), + ), + ), + ); + } +} + +/// 终端高层级浮动上下文菜单(挂载于 Root Overlay) +class _TerminalContextMenuWidget extends StatelessWidget { + final Offset anchor; + final VoidCallback onCopy; + final VoidCallback onPaste; + final VoidCallback onSelectAll; + final VoidCallback onDismiss; + + const _TerminalContextMenuWidget({ + required this.anchor, + required this.onCopy, + required this.onPaste, + required this.onSelectAll, + required this.onDismiss, + }); + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final theme = Theme.of(context); + final mediaQuery = MediaQuery.of(context); + + const menuWidth = 210.0; + const menuHeight = 44.0; + + // 水平居中并限制在屏幕内 + final screenWidth = mediaQuery.size.width; + final double left = (anchor.dx - menuWidth / 2).clamp(12.0, max(12.0, screenWidth - menuWidth - 12.0)); + + // 垂直计算:优先位于锚点上方,若贴近屏幕顶端则悬浮于锚点下方 + final topThreshold = mediaQuery.padding.top + 48.0; + final double top; + if (anchor.dy - menuHeight - 12.0 >= topThreshold) { + top = anchor.dy - menuHeight - 12.0; + } else { + top = (anchor.dy + 14.0).clamp(topThreshold, mediaQuery.size.height - menuHeight - 12.0); + } + + return Stack( + children: [ + // 点击外部空白区域关闭菜单 + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: onDismiss, + ), + ), + Positioned( + left: left, + top: top, + child: Material( + elevation: 8.0, + borderRadius: BorderRadius.circular(10.0), + color: theme.colorScheme.surfaceContainerHighest, + surfaceTintColor: theme.colorScheme.surfaceTint, + clipBehavior: Clip.antiAlias, + child: Container( + height: menuHeight, + padding: const EdgeInsets.symmetric(horizontal: 4.0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10.0), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 0.8, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _MenuItemButton( + label: l10n.copy, + icon: Icons.copy_rounded, + onPressed: onCopy, + ), + _buildDivider(theme), + _MenuItemButton( + label: l10n.paste, + icon: Icons.paste_rounded, + onPressed: onPaste, + ), + _buildDivider(theme), + _MenuItemButton( + label: l10n.selectAll, + icon: Icons.select_all_rounded, + onPressed: onSelectAll, + ), + ], + ), + ), + ), + ), + ], + ); + } + + Widget _buildDivider(ThemeData theme) { + return Container( + width: 1.0, + height: 20.0, + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.6), + ); + } +} + +class _MenuItemButton extends StatelessWidget { + final String label; + final IconData icon; + final VoidCallback onPressed; + + const _MenuItemButton({ + required this.label, + required this.icon, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(8.0), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16.0, color: theme.colorScheme.primary), + const SizedBox(width: 4.0), + Text( + label, + style: TextStyle( + fontSize: 13.0, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurface, + ), + ), + ], + ), + ), + ); + } +} diff --git a/packages/re_editor/analysis_options.yaml b/packages/re_editor/analysis_options.yaml index a5744c1..e46654b 100644 --- a/packages/re_editor/analysis_options.yaml +++ b/packages/re_editor/analysis_options.yaml @@ -1,3 +1,6 @@ +analyzer: + exclude: + - build/** include: package:flutter_lints/flutter.yaml # Additional information about this file can be found at diff --git a/packages/re_editor/build/native_assets/windows/native_assets.json b/packages/re_editor/build/native_assets/windows/native_assets.json new file mode 100644 index 0000000..523bfc7 --- /dev/null +++ b/packages/re_editor/build/native_assets/windows/native_assets.json @@ -0,0 +1 @@ +{"format-version":[1,0,0],"native-assets":{}} \ No newline at end of file diff --git a/packages/re_editor/build/test_cache/build/f29338658ca85c93a5dc5db6ef50c64f.cache.dill.track.dill b/packages/re_editor/build/test_cache/build/f29338658ca85c93a5dc5db6ef50c64f.cache.dill.track.dill new file mode 100644 index 0000000..9fc1ddb Binary files /dev/null and b/packages/re_editor/build/test_cache/build/f29338658ca85c93a5dc5db6ef50c64f.cache.dill.track.dill differ diff --git a/packages/re_editor/build/unit_test_assets/AssetManifest.bin b/packages/re_editor/build/unit_test_assets/AssetManifest.bin new file mode 100644 index 0000000..86d111f Binary files /dev/null and b/packages/re_editor/build/unit_test_assets/AssetManifest.bin differ diff --git a/packages/re_editor/build/unit_test_assets/FontManifest.json b/packages/re_editor/build/unit_test_assets/FontManifest.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/packages/re_editor/build/unit_test_assets/FontManifest.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/packages/re_editor/build/unit_test_assets/NOTICES.Z b/packages/re_editor/build/unit_test_assets/NOTICES.Z new file mode 100644 index 0000000..a7744a3 Binary files /dev/null and b/packages/re_editor/build/unit_test_assets/NOTICES.Z differ diff --git a/packages/re_editor/build/unit_test_assets/NativeAssetsManifest.json b/packages/re_editor/build/unit_test_assets/NativeAssetsManifest.json new file mode 100644 index 0000000..523bfc7 --- /dev/null +++ b/packages/re_editor/build/unit_test_assets/NativeAssetsManifest.json @@ -0,0 +1 @@ +{"format-version":[1,0,0],"native-assets":{}} \ No newline at end of file diff --git a/packages/re_editor/build/unit_test_assets/shaders/ink_sparkle.frag b/packages/re_editor/build/unit_test_assets/shaders/ink_sparkle.frag new file mode 100644 index 0000000..ebd8066 Binary files /dev/null and b/packages/re_editor/build/unit_test_assets/shaders/ink_sparkle.frag differ diff --git a/packages/re_editor/build/unit_test_assets/shaders/stretch_effect.frag b/packages/re_editor/build/unit_test_assets/shaders/stretch_effect.frag new file mode 100644 index 0000000..3c938de Binary files /dev/null and b/packages/re_editor/build/unit_test_assets/shaders/stretch_effect.frag differ diff --git a/packages/re_editor/lib/src/_code_editable.dart b/packages/re_editor/lib/src/_code_editable.dart index 365f6d7..e65a19b 100644 --- a/packages/re_editor/lib/src/_code_editable.dart +++ b/packages/re_editor/lib/src/_code_editable.dart @@ -271,6 +271,16 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli onNotification: (notification) { if (notification is ScrollStartNotification) { widget.selectionOverlayController.hideToolbar(); + } else if (notification is ScrollEndNotification) { + if (!widget.controller.selection.isCollapsed && widget.controller.selection.baseOffset != -1) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (widget.focusNode.hasFocus && + !widget.controller.selection.isCollapsed && + widget.controller.selection.baseOffset != -1) { + widget.selectionOverlayController.showToolbar(context, Offset.zero); + } + }); + } } return false; }, diff --git a/packages/re_editor/lib/src/_code_selection.dart b/packages/re_editor/lib/src/_code_selection.dart index 7d963b9..987ca7c 100644 --- a/packages/re_editor/lib/src/_code_selection.dart +++ b/packages/re_editor/lib/src/_code_selection.dart @@ -178,6 +178,9 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete }.contains); void _onMobileTapDown(Offset position) { + if (!widget.controller.selection.isCollapsed && _isPositionOnSelection(position)) { + return; + } _selectPosition(position, _SelectionChangedCause.tapDown); widget.selectionOverlayController.hideHandle(); widget.selectionOverlayController.hideToolbar(); @@ -193,9 +196,15 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete } else { _pointerTapTimestamp = now; _pointerTapPosition = position; - _selectPosition(position, _SelectionChangedCause.tapUp); - widget.selectionOverlayController.hideHandle(); - widget.selectionOverlayController.hideToolbar(); + if (!widget.controller.selection.isCollapsed && _isPositionOnSelection(position)) { + // 存在框选区域时,点击框选区域不再取消框选区域,而是弹出菜单 + widget.selectionOverlayController.showHandle(context); + widget.selectionOverlayController.showToolbar(context, position); + } else { + _selectPosition(position, _SelectionChangedCause.tapUp); + widget.selectionOverlayController.hideHandle(); + widget.selectionOverlayController.hideToolbar(); + } } widget.inputController.ensureInput(); } @@ -432,7 +441,7 @@ abstract class _SelectionOverlayController { void hideHandle(); - void showToolbar(BuildContext context, Offset position); + void showToolbar(BuildContext context, Offset position, [TextSelectionHandleType? targetHandle]); void hideToolbar(); @@ -466,7 +475,7 @@ class _DesktopSelectionOverlayController implements _SelectionOverlayController } @override - void showToolbar(BuildContext context, Offset? position) { + void showToolbar(BuildContext context, Offset? position, [TextSelectionHandleType? targetHandle]) { if (position == null) { return; } @@ -575,7 +584,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController { } @override - void showToolbar(BuildContext context, Offset globalPosition) { + void showToolbar(BuildContext context, Offset globalPosition, [TextSelectionHandleType? targetHandle]) { globalPosition = _clampPosition(globalPosition); final Rect editingRegion = Rect.fromPoints( ensureRender.localToGlobal(Offset.zero), @@ -588,28 +597,84 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController { primaryAnchor: ensureRender.calculateTextPositionScreenOffset(selection.start, false) ?? globalPosition, ); } else { - final Rect? bounds = ensureRender.calculateSelectionBoundingRect(selection); - final double midX; - final double topY; - final double bottomY; - if (bounds != null) { - midX = bounds.center.dx; - topY = bounds.top.clamp(editingRegion.top, editingRegion.bottom); - bottomY = bounds.bottom.clamp(editingRegion.top, editingRegion.bottom); + final Offset? startScreenOffset = ensureRender.calculateTextPositionScreenOffset(selection.start, false); + final Offset? endScreenOffset = ensureRender.calculateTextPositionScreenOffset(selection.end, false); + final double lineHeight = ensureRender.lineHeight; + + // 判断左端点是否完全在屏幕编辑区内(留有微小容差) + final bool isStartOnScreen = startScreenOffset != null && + startScreenOffset.dy >= (editingRegion.top - 1.0) && + (startScreenOffset.dy + lineHeight) <= (editingRegion.bottom + 1.0) && + startScreenOffset.dx >= (editingRegion.left - 1.0) && + startScreenOffset.dx <= (editingRegion.right + 1.0); + + // 判断右端点是否完全在屏幕编辑区内(留有微小容差) + final bool isEndOnScreen = endScreenOffset != null && + endScreenOffset.dy >= (editingRegion.top - 1.0) && + (endScreenOffset.dy + lineHeight) <= (editingRegion.bottom + 1.0) && + endScreenOffset.dx >= (editingRegion.left - 1.0) && + endScreenOffset.dx <= (editingRegion.right + 1.0); + + final EditorToolbarPlacement placement; + final Offset targetOffset; + + if (targetHandle == TextSelectionHandleType.left) { + // 用户刚才拖动或点击了左端点手柄:在左端点位置上方弹出 + placement = EditorToolbarPlacement.aboveStart; + targetOffset = startScreenOffset ?? globalPosition; + } else if (targetHandle == TextSelectionHandleType.right) { + // 用户刚才拖动或点击了右端点手柄:在右端点位置下方弹出 + placement = EditorToolbarPlacement.belowEnd; + targetOffset = endScreenOffset ?? globalPosition; } else { - Offset startPosition = ensureRender.calculateTextPositionScreenOffset(selection.start, false) ?? editingRegion.topLeft; - Offset endPosition = ensureRender.calculateTextPositionScreenOffset(selection.end, true) ?? editingRegion.bottomRight; - topY = min(startPosition.dy, endPosition.dy).clamp(editingRegion.top, editingRegion.bottom); - bottomY = max(startPosition.dy, endPosition.dy).clamp(editingRegion.top, editingRegion.bottom); - if ((endPosition.dy - startPosition.dy).abs() <= ensureRender.lineHeight * 1.5) { - midX = (startPosition.dx + endPosition.dx) / 2.0; + // 通用智能定位逻辑(点击选区/滑动结束/双击长按初始框选) + if (isStartOnScreen && isEndOnScreen) { + // 都在,以左边为基,在左端点上方弹出 + placement = EditorToolbarPlacement.aboveStart; + targetOffset = startScreenOffset!; + } else if (isStartOnScreen) { + // 仅左端点在屏幕内:在左端点上方弹出 + placement = EditorToolbarPlacement.aboveStart; + targetOffset = startScreenOffset!; + } else if (isEndOnScreen) { + // 仅右端点在屏幕内:在右端点下方弹出 + placement = EditorToolbarPlacement.belowEnd; + targetOffset = endScreenOffset!; } else { - midX = globalPosition.dx; + // 都不在屏幕内 + final int firstVisibleLine = ensureRender.displayParagraphs.isNotEmpty + ? ensureRender.displayParagraphs.first.index + : 0; + final int lastVisibleLine = ensureRender.displayParagraphs.isNotEmpty + ? ensureRender.displayParagraphs.last.index + : 0; + + if (selection.startIndex <= firstVisibleLine && selection.endIndex >= lastVisibleLine) { + // 框选文本完全占据当前屏幕:在中间显示 + placement = EditorToolbarPlacement.center; + targetOffset = editingRegion.center; + } else if (selection.endIndex < firstVisibleLine) { + // 选区整体在屏幕上方:在上面显示 + placement = EditorToolbarPlacement.top; + targetOffset = Offset(editingRegion.center.dx, editingRegion.top); + } else if (selection.startIndex > lastVisibleLine) { + // 选区整体在屏幕下方:在下方显示 + placement = EditorToolbarPlacement.bottom; + targetOffset = Offset(editingRegion.center.dx, editingRegion.bottom); + } else { + // 兜底(水平滚动偏离等异常情况):在中间显示 + placement = EditorToolbarPlacement.center; + targetOffset = editingRegion.center; + } } } - anchors = TextSelectionToolbarAnchors( - primaryAnchor: Offset(midX, topY), - secondaryAnchor: Offset(midX, bottomY), + + anchors = EditorSelectionToolbarAnchors( + primaryAnchor: targetOffset, + secondaryAnchor: Offset(targetOffset.dx, targetOffset.dy + lineHeight), + placement: placement, + targetOffset: targetOffset, + visibleEditorRect: editingRegion, ); } onShowToolbar(context, anchors, editingRegion); @@ -704,10 +769,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController { handleLayerLink: startHandleLayerLink, onSelectionHandleTapped: () { final Offset? position = ensureRender.calculateTextPositionScreenOffset(controller.selection.start, false); - if (position == null) { - return; - } - showToolbar(_context, position); + showToolbar(_context, position ?? Offset.zero, TextSelectionHandleType.left); }, onSelectionHandleDragStart: _handleStartHandleDragStart, onSelectionHandleDragUpdate: (details) { @@ -736,10 +798,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController { handleLayerLink: endHandleLayerLink, onSelectionHandleTapped: () { final Offset? position = ensureRender.calculateTextPositionScreenOffset(controller.selection.end, false); - if (position == null) { - return; - } - showToolbar(_context, position); + showToolbar(_context, position ?? Offset.zero, TextSelectionHandleType.right); }, onSelectionHandleDragStart: _handleEndHandleDragStart, onSelectionHandleDragUpdate: (details) { @@ -835,7 +894,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController { _isStartHandleAutoScrolling = false; ensureRender.stopAutoScroll(); toolbarVisibility.value = true; - showToolbar(_context, _startHandleDragLastPosition); + showToolbar(_context, _startHandleDragLastPosition, TextSelectionHandleType.left); } void _handleEndHandleDragStart(DragStartDetails details) { @@ -916,7 +975,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController { _isEndHandleAutoScrolling = false; ensureRender.stopAutoScroll(); toolbarVisibility.value = true; - showToolbar(_context, _endHandleDragLastPosition); + showToolbar(_context, _endHandleDragLastPosition, TextSelectionHandleType.right); } void _autoScrollWhenStartHandleDragging() { @@ -1089,41 +1148,46 @@ class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with S alignment: Alignment.topLeft, width: interactiveRect.width, height: interactiveRect.height, - child: RawGestureDetector( - behavior: HitTestBehavior.translucent, - gestures: { - PanGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => PanGestureRecognizer( - debugOwner: this, - // Mouse events select the text and do not drag the cursor. - supportedDevices: { - PointerDeviceKind.touch, - PointerDeviceKind.stylus, - PointerDeviceKind.unknown, + child: MouseRegion( + cursor: SystemMouseCursors.grab, + child: RawGestureDetector( + behavior: HitTestBehavior.translucent, + gestures: { + PanGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => PanGestureRecognizer( + debugOwner: this, + supportedDevices: { + PointerDeviceKind.touch, + PointerDeviceKind.stylus, + PointerDeviceKind.invertedStylus, + PointerDeviceKind.mouse, + PointerDeviceKind.trackpad, + PointerDeviceKind.unknown, + }, + ), + (PanGestureRecognizer instance) { + instance + ..dragStartBehavior = DragStartBehavior.start + ..onStart = widget.onSelectionHandleDragStart + ..onUpdate = widget.onSelectionHandleDragUpdate + ..onCancel = widget.onSelectionHandleDragCancel + ..onEnd = widget.onSelectionHandleDragEnd; }, ), - (PanGestureRecognizer instance) { - instance - ..dragStartBehavior = DragStartBehavior.start - ..onStart = widget.onSelectionHandleDragStart - ..onUpdate = widget.onSelectionHandleDragUpdate - ..onCancel = widget.onSelectionHandleDragCancel - ..onEnd = widget.onSelectionHandleDragEnd; - }, - ), - }, - child: Padding( - padding: EdgeInsets.only( - left: padding.left, - top: padding.top, - right: padding.right, - bottom: padding.bottom, - ), - child: widget.selectionControls.buildHandle( - context, - widget.type, - widget.preferredLineHeight, - widget.onSelectionHandleTapped, + }, + child: Padding( + padding: EdgeInsets.only( + left: padding.left, + top: padding.top, + right: padding.right, + bottom: padding.bottom, + ), + child: widget.selectionControls.buildHandle( + context, + widget.type, + widget.preferredLineHeight, + widget.onSelectionHandleTapped, + ), ), ), ), @@ -1184,6 +1248,7 @@ class _MobileSelectionToolbarController implements MobileSelectionToolbarControl visibility: visibility ); }, + renderRect: renderRect, ) ) ); diff --git a/packages/re_editor/lib/src/code_toolbar.dart b/packages/re_editor/lib/src/code_toolbar.dart index 5b2948f..067da6f 100644 --- a/packages/re_editor/lib/src/code_toolbar.dart +++ b/packages/re_editor/lib/src/code_toolbar.dart @@ -1,11 +1,44 @@ part of re_editor; +/// 选区弹出菜单的位置策略类型 +enum EditorToolbarPlacement { + /// 在起始端点(左端点)上方弹出,若上方空间不足则翻转至下方 + aboveStart, + /// 在结束端点(右端点)下方弹出,若下方空间不足则翻转至上方 + belowEnd, + /// 选区文本完全贯穿/占据视口时,在可视屏幕正中间弹出 + center, + /// 选区整体在视口上方时,在视口顶部贴边弹出 + top, + /// 选区整体在视口下方时,在视口底部贴边弹出 + bottom, +} + +/// 携带智能定位策略与可视边界信息的扩展锚点 +class EditorSelectionToolbarAnchors extends TextSelectionToolbarAnchors { + /// 定位策略分支 + final EditorToolbarPlacement placement; + /// 目标锚点位置(绝对屏幕坐标) + final Offset targetOffset; + /// 当前编辑器的有效可视区域边界(绝对屏幕坐标) + final Rect visibleEditorRect; + + const EditorSelectionToolbarAnchors({ + required super.primaryAnchor, + super.secondaryAnchor, + required this.placement, + required this.targetOffset, + required this.visibleEditorRect, + }); +} + typedef ToolbarMenuBuilder = Widget Function({ required BuildContext context, required TextSelectionToolbarAnchors anchors, required CodeLineEditingController controller, required VoidCallback onDismiss, required VoidCallback onRefresh, + Rect? renderRect, }); abstract class SelectionToolbarController { diff --git a/packages/re_editor/pubspec.lock b/packages/re_editor/pubspec.lock new file mode 100644 index 0000000..3ade0ab --- /dev/null +++ b/packages/re_editor/pubspec.lock @@ -0,0 +1,237 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04 + url: "https://pub.dev" + source: hosted + version: "2.0.3" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + isolate_contactor: + dependency: transitive + description: + name: isolate_contactor + sha256: f1be0a90f91e4309ef37cc45280b2a84e769e848aae378318dd3dd263cfc482a + url: "https://pub.dev" + source: hosted + version: "4.2.0" + isolate_manager: + dependency: "direct main" + description: + name: isolate_manager + sha256: "8fb916c4444fd408f089448f904f083ac3e169ea1789fd4d987b25809af92188" + url: "https://pub.dev" + source: hosted + version: "4.3.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + path: + dependency: "direct dev" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + re_highlight: + dependency: "direct main" + description: + name: re_highlight + sha256: "6c4ac3f76f939fb7ca9df013df98526634e17d8f7460e028bd23a035870024f2" + url: "https://pub.dev" + source: hosted + version: "0.0.3" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + url: "https://pub.dev" + source: hosted + version: "15.3.0" + web: + dependency: transitive + description: + name: web + sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" + url: "https://pub.dev" + source: hosted + version: "0.5.1" +sdks: + dart: ">=3.11.0-0 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/test/archive_compressor_test.dart b/test/archive_compressor_test.dart new file mode 100644 index 0000000..a767959 --- /dev/null +++ b/test/archive_compressor_test.dart @@ -0,0 +1,186 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:code_editor/services/archive_compressor.dart'; +import 'package:code_editor/services/archive_extractor.dart'; +import 'package:code_editor/services/internal_project_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + late Directory tempTestDir; + + setUp(() { + tempTestDir = Directory.systemTemp.createTempSync('archive_compressor_test_'); + }); + + tearDown(() { + if (tempTestDir.existsSync()) { + try { + tempTestDir.deleteSync(recursive: true); + } catch (_) {} + } + }); + + group('ArchiveCompressor CRC-32 Tests', () { + test('standard test vector "123456789" produces 0xCBF43926', () { + final input = utf8.encode('123456789'); + final crc = computeCrc32(input); + expect(crc, equals(0xCBF43926)); + }); + + test('empty byte array produces 0', () { + final crc = computeCrc32([]); + expect(crc, equals(0)); + }); + + test('incremental chunked calculation matches one-shot calculation', () { + final data = Uint8List.fromList(List.generate(20000, (i) => i % 256)); + final oneShotCrc = computeCrc32(data); + + var chunkedCrc = 0; + const chunkSize = 1024; + for (var i = 0; i < data.length; i += chunkSize) { + final end = (i + chunkSize < data.length) ? i + chunkSize : data.length; + chunkedCrc = computeCrc32(data.sublist(i, end), chunkedCrc); + } + + expect(chunkedCrc, equals(oneShotCrc)); + }); + }); + + group('ArchiveCompressor Streaming ZIP Compression Tests', () { + test('compresses nested files, empty files, empty dirs and utf-8 names cleanly', () async { + final srcDir = Directory(p.join(tempTestDir.path, 'source_project'))..createSync(); + + // 1. 普通文件 + final fileA = File(p.join(srcDir.path, 'main.dart'))..writeAsStringSync('void main() => print("hello");'); + + // 2. 多级子目录与文件 + final subDir = Directory(p.join(srcDir.path, 'src', 'utils'))..createSync(recursive: true); + final fileB = File(p.join(subDir.path, 'helper.dart'))..writeAsStringSync('class Helper {}'); + + // 3. 空目录 + Directory(p.join(srcDir.path, 'assets', 'empty_folder')).createSync(recursive: true); + + // 4. 空文件 + File(p.join(srcDir.path, 'EMPTY.txt')).writeAsStringSync(''); + + // 5. 中文与表情等 UTF-8 文件名 + final fileUtf8 = File(p.join(srcDir.path, '测试项目_说明.md'))..writeAsStringSync('# 中文测试文档\n内容丰富'); + + // 6. 大文件 (> 128KB 验证 64KB 多分块流式压缩与 CRC 回填) + final largeContent = 'Line of large content for streaming test 1234567890\n' * 3000; + final fileLarge = File(p.join(srcDir.path, 'large_file.txt'))..writeAsStringSync(largeContent); + + final zipFile = File(p.join(tempTestDir.path, 'output.zip')); + final progressList = []; + + await ArchiveCompressor.zipDirectory( + sourceDir: srcDir, + targetZipFile: zipFile, + onProgress: (p, msg) { + progressList.add(p); + }, + ); + + expect(zipFile.existsSync(), isTrue); + expect(zipFile.lengthSync(), greaterThan(100)); + expect(progressList, isNotEmpty); + expect(progressList.last, equals(1.0)); + + // 使用 ArchiveExtractor 解压验证 ZIP 完整性与正确性 + final extractDir = Directory(p.join(tempTestDir.path, 'extracted'))..createSync(); + await ArchiveExtractor.extract( + archiveFile: zipFile, + targetDir: extractDir, + ); + + // 校验解压出的各个文件及内容 + expect(File(p.join(extractDir.path, 'main.dart')).existsSync(), isTrue); + expect(File(p.join(extractDir.path, 'main.dart')).readAsStringSync(), equals(fileA.readAsStringSync())); + + expect(File(p.join(extractDir.path, 'src', 'utils', 'helper.dart')).existsSync(), isTrue); + expect(File(p.join(extractDir.path, 'src', 'utils', 'helper.dart')).readAsStringSync(), equals(fileB.readAsStringSync())); + + expect(Directory(p.join(extractDir.path, 'assets', 'empty_folder')).existsSync(), isTrue); + + expect(File(p.join(extractDir.path, 'EMPTY.txt')).existsSync(), isTrue); + expect(File(p.join(extractDir.path, 'EMPTY.txt')).readAsStringSync(), isEmpty); + + expect(File(p.join(extractDir.path, '测试项目_说明.md')).existsSync(), isTrue); + expect(File(p.join(extractDir.path, '测试项目_说明.md')).readAsStringSync(), equals(fileUtf8.readAsStringSync())); + + expect(File(p.join(extractDir.path, 'large_file.txt')).existsSync(), isTrue); + expect(File(p.join(extractDir.path, 'large_file.txt')).readAsStringSync(), equals(fileLarge.readAsStringSync())); + }); + + test('cancellation aborts compression and cleans up target zip file', () async { + final srcDir = Directory(p.join(tempTestDir.path, 'cancel_src'))..createSync(); + for (var i = 0; i < 50; i++) { + File(p.join(srcDir.path, 'file_$i.txt')).writeAsStringSync('Content $i ' * 500); + } + + final zipFile = File(p.join(tempTestDir.path, 'cancel_target.zip')); + + expect( + () async { + await ArchiveCompressor.zipDirectory( + sourceDir: srcDir, + targetZipFile: zipFile, + isCancelled: () => true, + ); + }, + throwsA(isA()), + ); + + // 验证未完成的临时或目标 zip 文件被及时清理 + expect(zipFile.existsSync(), isFalse); + }); + }); + + group('InternalProjectService Export & Import End-to-End Tests', () { + test('exports project to zip and re-imports back with perfect fidelity', () async { + final service = InternalProjectService.instance; + final customProjectsDir = Directory(p.join(tempTestDir.path, 'projects'))..createSync(recursive: true); + service.customProjectsDir = customProjectsDir; + + // 1. 创建待导出的项目 + final projectDir = await service.createProject('MyExportApp'); + File(p.join(projectDir.path, 'pubspec.yaml')).writeAsStringSync('name: my_export_app\nversion: 1.0.0\n'); + final libDir = Directory(p.join(projectDir.path, 'lib'))..createSync(); + File(p.join(libDir.path, 'main.dart')).writeAsStringSync('void main() {}'); + File(p.join(libDir.path, 'calc.dart')).writeAsStringSync('int add(int a, int b) => a + b;'); + + // 2. 导出到外部目标目录 + final exportDir = Directory(p.join(tempTestDir.path, 'user_exports'))..createSync(recursive: true); + final targetZipPath = p.join(exportDir.path, 'MyExportApp.zip'); + + final exportedFile = await service.exportProjectToZip(projectDir, targetZipPath); + expect(exportedFile.existsSync(), isTrue); + expect(exportedFile.path, equals(targetZipPath)); + + // 3. 从导出的 ZIP 重新导入为新项目 + final importedProjectDir = await service.importProjectFromArchive( + targetZipPath, + 'MyExportApp_Restored', + ); + + expect(importedProjectDir.existsSync(), isTrue); + expect(p.basename(importedProjectDir.path), equals('MyExportApp_Restored')); + + // 4. 校验所有导入的文件及内容无损还原 + final pubspec = File(p.join(importedProjectDir.path, 'pubspec.yaml')); + expect(pubspec.existsSync(), isTrue); + expect(pubspec.readAsStringSync(), contains('name: my_export_app')); + + final restoredMain = File(p.join(importedProjectDir.path, 'lib', 'main.dart')); + expect(restoredMain.existsSync(), isTrue); + expect(restoredMain.readAsStringSync(), equals('void main() {}')); + + final restoredCalc = File(p.join(importedProjectDir.path, 'lib', 'calc.dart')); + expect(restoredCalc.existsSync(), isTrue); + expect(restoredCalc.readAsStringSync(), equals('int add(int a, int b) => a + b;')); + }); + }); +} diff --git a/test/archive_extractor_test.dart b/test/archive_extractor_test.dart new file mode 100644 index 0000000..fea1eb9 --- /dev/null +++ b/test/archive_extractor_test.dart @@ -0,0 +1,171 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:archive/archive_io.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:code_editor/services/archive_extractor.dart'; +import 'package:code_editor/services/internal_project_service.dart'; + +import 'distro_image_resolver_test.dart'; // 借用 encodeValidXz + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + + setUp(() { + tempBaseDir = Directory.systemTemp.createTempSync('archive_extractor_test_'); + }); + + tearDown(() { + try { + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + } catch (_) {} + }); + + group('ArchiveExtractor Format Detection Tests', () { + test('detectFormat correctly identifies format from magic bytes or extension', () { + final zipFile = File(p.join(tempBaseDir.path, 'test.zip')); + zipFile.writeAsBytesSync(ZipEncoder().encode(Archive()..addFile(ArchiveFile('a.txt', 1, [65])))!); + expect(ArchiveExtractor.detectFormat(zipFile), ArchiveFormat.zip); + + final tarGzFile = File(p.join(tempBaseDir.path, 'test.tar.gz')); + final tarBytes = TarEncoder().encode(Archive()..addFile(ArchiveFile('b.txt', 1, [66]))); + tarGzFile.writeAsBytesSync(GZipEncoder().encode(tarBytes)!); + expect(ArchiveExtractor.detectFormat(tarGzFile), ArchiveFormat.tarGz); + + final xzBytes = encodeValidXz(tarBytes); + final tarXzFile = File(p.join(tempBaseDir.path, 'test.tar.xz')); + tarXzFile.writeAsBytesSync(xzBytes); + expect(ArchiveExtractor.detectFormat(tarXzFile), ArchiveFormat.tarXz); + }); + }); + + group('ArchiveExtractor Extraction Tests', () { + test('extracts ZIP archive with subdirectories and verifies content', () async { + final zipFile = File(p.join(tempBaseDir.path, 'project.zip')); + final encoder = ZipFileEncoder(); + encoder.create(zipFile.path); + + final file1 = File(p.join(tempBaseDir.path, 'pubspec.yaml')); + file1.writeAsStringSync('name: test_project\nversion: 1.0.0\n'); + encoder.addFile(file1); + + final file2 = File(p.join(tempBaseDir.path, 'main.dart')); + file2.writeAsStringSync('void main() { print("hello world"); }'); + encoder.addFile(file2); + + encoder.close(); + + final targetDir = Directory(p.join(tempBaseDir.path, 'extracted_zip')); + final progressList = []; + + await ArchiveExtractor.extract( + archiveFile: zipFile, + targetDir: targetDir, + onProgress: (prog, msg) { + progressList.add(prog); + }, + ); + + expect(targetDir.existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'pubspec.yaml')).existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'pubspec.yaml')).readAsStringSync(), contains('name: test_project')); + expect(File(p.join(targetDir.path, 'main.dart')).existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'main.dart')).readAsStringSync(), contains('hello world')); + expect(progressList.isNotEmpty, isTrue); + expect(progressList.last, 1.0); + }); + + test('extracts TAR.GZ archive with low-memory streaming', () async { + final archive = Archive(); + archive.addFile(ArchiveFile('src/index.js', 25, utf8.encode('console.log("hello node");'))); + archive.addFile(ArchiveFile('package.json', 16, utf8.encode('{"name":"demo"}'))); + final tarBytes = TarEncoder().encode(archive); + final gzBytes = GZipEncoder().encode(tarBytes)!; + + final gzFile = File(p.join(tempBaseDir.path, 'project.tar.gz')); + gzFile.writeAsBytesSync(gzBytes); + + final targetDir = Directory(p.join(tempBaseDir.path, 'extracted_targz')); + await ArchiveExtractor.extract( + archiveFile: gzFile, + targetDir: targetDir, + ); + + expect(targetDir.existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'src', 'index.js')).existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'src', 'index.js')).readAsStringSync(), contains('hello node')); + expect(File(p.join(targetDir.path, 'package.json')).existsSync(), isTrue); + }); + + test('extracts TAR.XZ archive using LowMemoryXZDecoder', () async { + final archive = Archive(); + archive.addFile(ArchiveFile('CMakeLists.txt', 25, utf8.encode('cmake_minimum_required()'))); + archive.addFile(ArchiveFile('main.cpp', 20, utf8.encode('int main(){return 0;}'))); + final tarBytes = TarEncoder().encode(archive); + final xzBytes = encodeValidXz(tarBytes); + + final xzFile = File(p.join(tempBaseDir.path, 'project.tar.xz')); + xzFile.writeAsBytesSync(xzBytes); + + final targetDir = Directory(p.join(tempBaseDir.path, 'extracted_tarxz')); + await ArchiveExtractor.extract( + archiveFile: xzFile, + targetDir: targetDir, + ); + + expect(targetDir.existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'CMakeLists.txt')).existsSync(), isTrue); + expect(File(p.join(targetDir.path, 'CMakeLists.txt')).readAsStringSync(), 'cmake_minimum_required()'); + expect(File(p.join(targetDir.path, 'main.cpp')).existsSync(), isTrue); + }); + + test('cancellation aborts extraction and cleans up target directory', () async { + final archive = Archive(); + archive.addFile(ArchiveFile('file1.txt', 10, utf8.encode('1234567890'))); + final tarBytes = TarEncoder().encode(archive); + final gzBytes = GZipEncoder().encode(tarBytes)!; + + final gzFile = File(p.join(tempBaseDir.path, 'cancel_test.tar.gz')); + gzFile.writeAsBytesSync(gzBytes); + + final targetDir = Directory(p.join(tempBaseDir.path, 'cancelled_target')); + + expect( + () => ArchiveExtractor.extract( + archiveFile: gzFile, + targetDir: targetDir, + isCancelled: () => true, + ), + throwsA(isA()), + ); + + expect(targetDir.existsSync(), isFalse); + }); + }); + + group('InternalProjectService with ArchiveExtractor Tests', () { + test('importProjectFromArchive uses ArchiveExtractor and imports project successfully', () async { + final service = InternalProjectService.instance; + service.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects')); + + final zipFile = File(p.join(tempBaseDir.path, 'sample_repo.zip')); + final encoder = ZipFileEncoder(); + encoder.create(zipFile.path); + final dummyFile = File(p.join(tempBaseDir.path, 'app.py')); + dummyFile.writeAsStringSync('print("python app")'); + encoder.addFile(dummyFile); + encoder.close(); + + final importedDir = await service.importProjectFromArchive(zipFile.path, 'sample_repo'); + expect(importedDir.existsSync(), isTrue); + expect(File(p.join(importedDir.path, 'app.py')).existsSync(), isTrue); + expect(File(p.join(importedDir.path, 'app.py')).readAsStringSync(), 'print("python app")'); + + service.customProjectsDir = null; + }); + }); +} diff --git a/test/code_editor_menu_test.dart b/test/code_editor_menu_test.dart new file mode 100644 index 0000000..7fa230e --- /dev/null +++ b/test/code_editor_menu_test.dart @@ -0,0 +1,391 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/widgets/code_editor_menu.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:re_editor/re_editor.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('CodeEditorToolbarController 选区菜单定位与恢复测试', () { + test('拖动 End Handle 时,锚点严格位于末尾手柄位置,绝不跳跃至顶端', () { + // 模拟 re_editor 传递的 End Handle 拖拽锚点:primary 为 -10000,secondary 为末尾坐标 (180, 450) + const inputAnchors = TextSelectionToolbarAnchors( + primaryAnchor: Offset(-10000, -10000), + secondaryAnchor: Offset(180, 450), + ); + + // 验证 End Handle 拖拽锚点规则 + final target = inputAnchors.primaryAnchor.dx < 0 && inputAnchors.secondaryAnchor != null + ? inputAnchors.secondaryAnchor! + : inputAnchors.primaryAnchor; + + expect(target.dy, equals(450)); + expect(target.dx, equals(180)); + }); + + test('拖动 Start Handle 时,锚点严格位于起始手柄位置', () { + const inputAnchors = TextSelectionToolbarAnchors( + primaryAnchor: Offset(150, 120), + secondaryAnchor: Offset(180, 450), + ); + + final target = inputAnchors.primaryAnchor.dx < 0 && inputAnchors.secondaryAnchor != null + ? inputAnchors.secondaryAnchor! + : inputAnchors.primaryAnchor; + + expect(target.dy, equals(120)); + expect(target.dx, equals(150)); + }); + + testWidgets('reshowLastToolbar 在选区折叠时安全跳过,在有选区时可重新唤起', (tester) async { + final controller = CodeEditorToolbarController(); + final codeController = CodeLineEditingController.fromText('Hello World\nSecond Line\nThird Line'); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) { + return ElevatedButton( + onPressed: () { + controller.reshowLastToolbar(context); + }, + child: const Text('Reshow'), + ); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 无选区(折叠)时点击 Reshow 不抛异常且无崩溃 + await tester.tap(find.text('Reshow')); + await tester.pumpAndSettle(); + + // 设置选区 + codeController.selection = const CodeLineSelection( + baseIndex: 0, + baseOffset: 0, + extentIndex: 0, + extentOffset: 5, + ); + + // 模拟 show 记录上下文 + final layerLink = LayerLink(); + final visibility = ValueNotifier(true); + final element = tester.element(find.text('Reshow')); + + controller.show( + context: element, + controller: codeController, + anchors: const TextSelectionToolbarAnchors( + primaryAnchor: Offset(100, 200), + ), + renderRect: const Rect.fromLTWH(0, 0, 400, 600), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + + // 隐藏后再 reshow + controller.hide(element); + await tester.pumpAndSettle(); + + controller.reshowLastToolbar(element); + await tester.pumpAndSettle(); + + // 验证无异常并正常处理 + expect(codeController.selection.isCollapsed, isFalse); + }); + + testWidgets('验证中英文本地化字符串正确无硬编码', (tester) async { + late AppLocalizations zhL10n; + late AppLocalizations enL10n; + + await tester.pumpWidget( + MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) { + zhL10n = AppLocalizations.of(context)!; + return const SizedBox.shrink(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(zhL10n.copy, equals('复制')); + expect(zhL10n.cut, equals('剪切')); + expect(zhL10n.paste, equals('粘贴')); + expect(zhL10n.selectAll, equals('全选')); + expect(zhL10n.copiedToClipboard, equals('已复制到剪贴板')); + + await tester.pumpWidget( + MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) { + enL10n = AppLocalizations.of(context)!; + return const SizedBox.shrink(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(enL10n.copy, equals('Copy')); + expect(enL10n.cut, equals('Cut')); + expect(enL10n.paste, equals('Paste')); + expect(enL10n.selectAll, equals('Select All')); + expect(enL10n.copiedToClipboard, equals('Copied to clipboard')); + }); + + testWidgets('CodeEditor 选区手柄在有选区时正常展现并支持鼠标交互', (tester) async { + final codeController = CodeLineEditingController.fromText('Hello Flutter Code Editor\nSecond line text'); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 500, + height: 400, + child: CodeEditor( + controller: codeController, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + codeController.selection = const CodeLineSelection( + baseIndex: 0, + baseOffset: 0, + extentIndex: 0, + extentOffset: 5, + ); + await tester.pumpAndSettle(); + + expect(codeController.selection.isCollapsed, isFalse); + }); + + testWidgets('智能定位算法测试: aboveStart/belowEnd/center/top/bottom 与空间避让翻转', (tester) async { + final controller = CodeEditorToolbarController(); + final codeController = CodeLineEditingController.fromText('Test line 1\nTest line 2\nTest line 3'); + codeController.selection = const CodeLineSelection( + baseIndex: 0, + baseOffset: 0, + extentIndex: 0, + extentOffset: 4, + ); + + late BuildContext buildCtx; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) { + buildCtx = context; + return const SizedBox(width: 400, height: 600); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final layerLink = LayerLink(); + final visibility = ValueNotifier(true); + + // 1. aboveStart: 空间充裕时显示在目标上方 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 300), + placement: EditorToolbarPlacement.aboveStart, + targetOffset: Offset(200, 300), + visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500), + ), + renderRect: const Rect.fromLTWH(0, 50, 400, 500), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final abovePos = tester.getTopLeft(find.byType(Material).last); + expect(abovePos.dy, lessThan(300)); + + // 2. aboveStart: 空间狭小(靠近顶部)时翻转到下方 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 60), + placement: EditorToolbarPlacement.aboveStart, + targetOffset: Offset(200, 60), + visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500), + ), + renderRect: const Rect.fromLTWH(0, 50, 400, 500), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final flippedBelowPos = tester.getTopLeft(find.byType(Material).last); + expect(flippedBelowPos.dy, greaterThan(60)); + + // 3. belowEnd: 空间充裕时显示在目标下方 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 200), + placement: EditorToolbarPlacement.belowEnd, + targetOffset: Offset(200, 200), + visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500), + ), + renderRect: const Rect.fromLTWH(0, 50, 400, 500), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final belowPos = tester.getTopLeft(find.byType(Material).last); + expect(belowPos.dy, greaterThan(200)); + + // 4. belowEnd: 空间狭小(靠近底部)时翻转到上方 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 530), + placement: EditorToolbarPlacement.belowEnd, + targetOffset: Offset(200, 530), + visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500), + ), + renderRect: const Rect.fromLTWH(0, 50, 400, 500), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final flippedAbovePos = tester.getTopLeft(find.byType(Material).last); + expect(flippedAbovePos.dy, lessThan(530)); + + // 5. center: 居中显示 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 300), + placement: EditorToolbarPlacement.center, + targetOffset: Offset(200, 300), + visibleEditorRect: Rect.fromLTWH(0, 100, 400, 400), + ), + renderRect: const Rect.fromLTWH(0, 100, 400, 400), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final centerPos = tester.getCenter(find.byType(Material).last); + expect((centerPos.dy - 300).abs(), lessThan(30)); + + // 6. top: 顶部贴边 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 100), + placement: EditorToolbarPlacement.top, + targetOffset: Offset(200, 100), + visibleEditorRect: Rect.fromLTWH(0, 100, 400, 400), + ), + renderRect: const Rect.fromLTWH(0, 100, 400, 400), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final topPos = tester.getTopLeft(find.byType(Material).last); + expect(topPos.dy, closeTo(110, 10)); + + // 7. bottom: 底部贴边 + controller.show( + context: buildCtx, + controller: codeController, + anchors: const EditorSelectionToolbarAnchors( + primaryAnchor: Offset(200, 500), + placement: EditorToolbarPlacement.bottom, + targetOffset: Offset(200, 500), + visibleEditorRect: Rect.fromLTWH(0, 100, 400, 400), + ), + renderRect: const Rect.fromLTWH(0, 100, 400, 400), + layerLink: layerLink, + visibility: visibility, + ); + await tester.pumpAndSettle(); + final bottomPos = tester.getBottomLeft(find.byType(Material).last); + expect(bottomPos.dy, closeTo(490, 20)); + + controller.hide(buildCtx); + await tester.pumpAndSettle(); + }); + + testWidgets('存在框选区域时,点击框选区域不取消框选,点击外部则取消框选', (tester) async { + final codeController = CodeLineEditingController.fromText('Hello Flutter Code Editor\nSecond line text'); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 500, + height: 400, + child: CodeEditor( + controller: codeController, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 设置选区为 "Hello" (offset 0 到 5) + codeController.selection = const CodeLineSelection( + baseIndex: 0, + baseOffset: 0, + extentIndex: 0, + extentOffset: 5, + ); + await tester.pumpAndSettle(); + expect(codeController.selection.isCollapsed, isFalse); + + // 点击首行 "Hello" 内部 + final editorFinder = find.byType(CodeEditor); + final editorTopLeft = tester.getTopLeft(editorFinder); + await tester.tapAt(editorTopLeft + const Offset(20, 10)); + await tester.pumpAndSettle(); + + // 选区不被取消! + expect(codeController.selection.isCollapsed, isFalse); + + // 点击第 2 行(选区外部) + await tester.tapAt(editorTopLeft + const Offset(20, 60)); + await tester.pumpAndSettle(); + + // 选区在点击外部后被取消 + expect(codeController.selection.isCollapsed, isTrue); + }); + }); +} diff --git a/test/distro_multi_system_test.dart b/test/distro_multi_system_test.dart index 05fbb6b..6783a49 100644 --- a/test/distro_multi_system_test.dart +++ b/test/distro_multi_system_test.dart @@ -62,9 +62,12 @@ void main() { }); tearDown(() { - if (tempBaseDir.existsSync()) { - tempBaseDir.deleteSync(recursive: true); - } + manager.customSdcardPath = null; + try { + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + } catch (_) {} }); Uint8List createMockRootfsTarGz() { @@ -246,6 +249,28 @@ void main() { expect(hushFile.existsSync(), isTrue); }); + test('buildLaunchConfig 自动挂载 sdcard 目录到 /sdcard 与 /root/sdcard', () async { + final gzBytes = createMockRootfsTarGz(); + final tempGzFile = File(p.join(tempBaseDir.path, 'sdcard_cfg.tar.gz'))..writeAsBytesSync(gzBytes); + + await manager.importFromCustomTarGz(systemName: 'sdcard_env', tarGzFile: tempGzFile); + + final fakeSdcard = Directory(p.join(tempBaseDir.path, 'fake_sdcard'))..createSync(); + manager.customSdcardPath = fakeSdcard.path; + + final launchConfig = await manager.buildLaunchConfig( + systemName: 'sdcard_env', + workspacePath: tempBaseDir.path, + ); + + expect(launchConfig.arguments, contains('${fakeSdcard.path}:/sdcard')); + expect(launchConfig.arguments, contains('${fakeSdcard.path}:/root/sdcard')); + + final rootDir = await manager.getSystemRootDir('sdcard_env'); + expect(Directory(p.join(rootDir.path, 'sdcard')).existsSync(), isTrue); + expect(Directory(p.join(rootDir.path, 'root', 'sdcard')).existsSync(), isTrue); + }); + test('buildLaunchConfig 针对不同发行版(Alpine ash vs passwd 自定义 shell)自适应启动参数', () async { final gzBytes = createMockRootfsTarGz(); final tempGzFile = File(p.join(tempBaseDir.path, 'alpine_cfg.tar.gz'))..writeAsBytesSync(gzBytes); diff --git a/test/gradle_project_module_test.dart b/test/gradle_project_module_test.dart new file mode 100644 index 0000000..c1da3ea --- /dev/null +++ b/test/gradle_project_module_test.dart @@ -0,0 +1,305 @@ +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/models/run_task.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/services/project_modules/gradle_project_module.dart'; +import 'package:code_editor/services/project_task_dispatcher.dart'; +import 'package:code_editor/services/run_task_storage_service.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('GradleProjectModule Parser Tests', () { + test('parseGradleTasksOutput parses single project tasks, groups, and descriptions', () { + const output = ''' +------------------------------------------------------------ +Tasks runnable from root project 'my-app' +------------------------------------------------------------ + +Application tasks +----------------- +run - Runs this project as a JVM application + +Build tasks +----------- +assemble - Assembles the outputs of this project. +build - Assembles and tests this project. +clean - Deletes the build directory. + +Verification tasks +------------------ +check - Runs all checks. +test - Runs the test suite. + +Other tasks +----------- +customTask - Executes a custom task +'''; + + final tasks = GradleProjectModule.parseGradleTasksOutput(output, 'sh ./gradlew'); + expect(tasks, isNotEmpty); + + // 验证任务名称与命令 + final runTask = tasks.firstWhere((t) => t.name == 'run'); + expect(runTask.command, 'sh ./gradlew run'); + expect(runTask.group, 'application'); + expect(runTask.moduleId, 'gradle'); + expect(runTask.source, TaskSource.detected); + expect(runTask.description, 'Runs this project as a JVM application'); + + final assembleTask = tasks.firstWhere((t) => t.name == 'assemble'); + expect(assembleTask.command, 'sh ./gradlew assemble'); + expect(assembleTask.group, 'build'); + expect(assembleTask.moduleId, 'gradle'); + + final buildTask = tasks.firstWhere((t) => t.name == 'build'); + expect(buildTask.command, 'sh ./gradlew build'); + expect(buildTask.group, 'build'); + + final testTask = tasks.firstWhere((t) => t.name == 'test'); + expect(testTask.command, 'sh ./gradlew test'); + expect(testTask.group, 'verification'); + + final customTask = tasks.firstWhere((t) => t.name == 'customTask'); + expect(customTask.command, 'sh ./gradlew customTask'); + expect(customTask.group, 'other'); + expect(customTask.description, 'Executes a custom task'); + + // 优先级排序验证:application -> build -> verification -> other + final groupsInOrder = tasks.map((t) => t.group).toList(); + final appIdx = groupsInOrder.indexOf('application'); + final buildIdx = groupsInOrder.indexOf('build'); + final verifIdx = groupsInOrder.indexOf('verification'); + final otherIdx = groupsInOrder.indexOf('other'); + + expect(appIdx, lessThan(buildIdx)); + expect(buildIdx, lessThan(verifIdx)); + expect(verifIdx, lessThan(otherIdx)); + }); + + test('parseGradleTasksOutput parses multi-module projects with prefixes (:app:xxx)', () { + const output = ''' +------------------------------------------------------------ +Tasks runnable from project ':app' +------------------------------------------------------------ + +Build tasks +----------- +assembleDebug - Assembles all Debug builds. +assembleRelease - Assembles all Release builds. + +Tasks runnable from project ':core' +------------------------------------------------------------ + +Build tasks +----------- +compileJava - Compiles Java sources. +'''; + + final tasks = GradleProjectModule.parseGradleTasksOutput(output, 'sh ./gradlew'); + expect(tasks.length, 3); + + final assembleDebugTask = tasks.firstWhere((t) => t.name == ':app:assembleDebug'); + expect(assembleDebugTask.command, 'sh ./gradlew :app:assembleDebug'); + expect(assembleDebugTask.id, 'gradle__app_assembleDebug'); + expect(assembleDebugTask.group, 'build'); + expect(assembleDebugTask.moduleId, 'gradle'); + + final compileJavaTask = tasks.firstWhere((t) => t.name == ':core:compileJava'); + expect(compileJavaTask.command, 'sh ./gradlew :core:compileJava'); + expect(compileJavaTask.id, 'gradle__core_compileJava'); + }); + }); + + group('Gradle Module Cache & Storage Tests', () { + late Directory tempDir; + late RunTaskStorageService storageService; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('gradle_module_test_'); + storageService = RunTaskStorageService(); + }); + + tearDown(() async { + if (await tempDir.exists()) { + await tempDir.delete(recursive: true); + } + }); + + test('saveModuleTasks writes to .code_editor/gradle_tasks.json and loadModuleTasks reads it back', () async { + final initial = await storageService.loadModuleTasks(tempDir.path, 'gradle'); + expect(initial.tasks, isEmpty); + expect(initial.hash, isNull); + + const tasksToSave = [ + RunTask( + id: 'gradle_assembleDebug', + name: 'assembleDebug', + command: 'sh ./gradlew assembleDebug', + source: TaskSource.detected, + group: 'build', + moduleId: 'gradle', + description: 'Build debug package', + ), + RunTask( + id: 'gradle_run', + name: 'run', + command: 'sh ./gradlew run', + source: TaskSource.detected, + group: 'application', + moduleId: 'gradle', + description: 'Run project', + ), + ]; + + await storageService.saveModuleTasks( + projectRoot: tempDir.path, + moduleName: 'gradle', + tasks: tasksToSave, + hash: 'test_hash_12345', + ); + + // 验证独立持久化文件存在:.code_editor/gradle_tasks.json + final cacheFile = File('${tempDir.path}/.code_editor/gradle_tasks.json'); + expect(cacheFile.existsSync(), isTrue); + + // 读取并校验 + final loaded = await storageService.loadModuleTasks(tempDir.path, 'gradle'); + expect(loaded.hash, 'test_hash_12345'); + expect(loaded.tasks.length, 2); + expect(loaded.tasks.first.name, 'assembleDebug'); + expect(loaded.tasks.first.group, 'build'); + expect(loaded.tasks.first.moduleId, 'gradle'); + expect(loaded.tasks.last.name, 'run'); + + // 验证 run_tasks.json(用户任务)完全不受影响且相互隔离 + final userConfig = await storageService.loadConfig(tempDir.path); + expect(userConfig.tasks, isEmpty); + }); + + test('computeBuildScriptHash changes when build.gradle is modified', () async { + final buildGradle = File('${tempDir.path}/build.gradle'); + await buildGradle.writeAsString('plugins { id "java" }\n'); + + final hash1 = GradleProjectModule.computeBuildScriptHash(tempDir); + expect(hash1.isNotEmpty, isTrue); + + // 稍微休眠并修改内容 + await Future.delayed(const Duration(milliseconds: 50)); + await buildGradle.writeAsString('plugins { id "application" }\n'); + + final hash2 = GradleProjectModule.computeBuildScriptHash(tempDir); + expect(hash2, isNot(equals(hash1))); + }); + }); + + group('ProjectTaskDispatcher & RunProvider Modular Tests', () { + late Directory tempDir; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('dispatcher_test_'); + }); + + tearDown(() async { + if (await tempDir.exists()) { + await tempDir.delete(recursive: true); + } + }); + + test('ProjectTaskDispatcher activates modules correctly', () async { + final dispatcher = ProjectTaskDispatcher(); + + // 空目录,不激活任何模块 + expect(dispatcher.getActiveModules(tempDir), isEmpty); + + // 写入 build.gradle + await File('${tempDir.path}/build.gradle').writeAsString('// gradle build'); + final active = dispatcher.getActiveModules(tempDir); + expect(active.length, 1); + expect(active.first.id, 'gradle'); + + // 再写入 CMakeLists.txt + await File('${tempDir.path}/CMakeLists.txt').writeAsString('project(test)'); + final active2 = dispatcher.getActiveModules(tempDir); + expect(active2.length, 2); + expect(active2.any((m) => m.id == 'cmake'), isTrue); + expect(active2.any((m) => m.id == 'gradle'), isTrue); + }); + + test('GradleProjectModule returns cached tasks when hash matches without executing command', () async { + final buildGradle = File('${tempDir.path}/build.gradle'); + await buildGradle.writeAsString('plugins { id "java" }\n'); + + final storageService = RunTaskStorageService(); + final currentHash = GradleProjectModule.computeBuildScriptHash(tempDir); + + const cachedTasks = [ + RunTask( + id: 'gradle_cached_task', + name: 'cachedTask', + command: 'sh ./gradlew cachedTask', + source: TaskSource.detected, + group: 'build', + moduleId: 'gradle', + ), + ]; + + await storageService.saveModuleTasks( + projectRoot: tempDir.path, + moduleName: 'gradle', + tasks: cachedTasks, + hash: currentHash, + ); + + final dispatcher = ProjectTaskDispatcher(); + final tasks = await dispatcher.detect( + projectRoot: tempDir.path, + storageService: storageService, + ); + + expect(tasks.any((t) => t.id == 'gradle_cached_task'), isTrue); + expect(tasks.firstWhere((t) => t.id == 'gradle_cached_task').name, 'cachedTask'); + }); + + test('RunProvider integrates with modular task system and maintains customTasks', () async { + final storageService = RunTaskStorageService(); + final runProvider = RunProvider(storageService: storageService); + + // 准备工程与一个已缓存的 Gradle 任务 + await File('${tempDir.path}/build.gradle').writeAsString('plugins { id "java" }\n'); + final currentHash = GradleProjectModule.computeBuildScriptHash(tempDir); + const initialGradleTask = RunTask( + id: 'gradle_assemble', + name: 'assemble', + command: 'sh ./gradlew assemble', + source: TaskSource.detected, + group: 'build', + moduleId: 'gradle', + ); + await storageService.saveModuleTasks( + projectRoot: tempDir.path, + moduleName: 'gradle', + tasks: [initialGradleTask], + hash: currentHash, + ); + + // 打开工程 + await runProvider.onProjectOpened(tempDir.path); + expect(runProvider.detectedTasks.any((t) => t.id == 'gradle_assemble'), isTrue); + + // 添加用户自定义任务 + const customTask = RunTask( + id: 'user_custom_1', + name: 'My Custom Run', + command: 'echo "custom"', + source: TaskSource.custom, + ); + await runProvider.addCustomTask(customTask); + + expect(runProvider.customTasks.length, 1); + // allTasks 自定义置顶 + expect(runProvider.allTasks.first.id, 'user_custom_1'); + expect(runProvider.allTasks.any((t) => t.id == 'gradle_assemble'), isTrue); + }); + }); +} diff --git a/test/project_management_test.dart b/test/project_management_test.dart index 73649b0..53eb83e 100644 --- a/test/project_management_test.dart +++ b/test/project_management_test.dart @@ -20,6 +20,7 @@ import 'package:shared_preferences/shared_preferences.dart'; class MockFilePicker extends FilePicker { String? pickedPath; + String? pickedDirectory; @override Future pickFiles({ @@ -50,7 +51,7 @@ class MockFilePicker extends FilePicker { String? dialogTitle, bool lockParentWindow = false, String? initialDirectory, - }) async => null; + }) async => pickedDirectory; @override Future saveFile({ @@ -529,5 +530,109 @@ void main() { final projects = await projectService.listProjects(); expect(projects, isEmpty); }); + + testWidgets('Export button is placed next to edit button and exports project as zip', (tester) async { + final projDir = await projectService.createProject('my_export_app'); + File(p.join(projDir.path, 'main.dart')).writeAsStringSync('void main() {}'); + + final exportDir = Directory(p.join(tempBaseDir.path, 'exports'))..createSync(); + mockFilePicker.pickedDirectory = exportDir.path; + + await tester.pumpWidget(buildTestWidget( + child: const ProjectManagementView(), + locale: const Locale('zh'), + )); + await tester.pumpAndSettle(); + + expect(find.text('my_export_app'), findsOneWidget); + + // Verify buttons in order: Edit, Export, Delete + expect(find.byIcon(Icons.edit_outlined), findsOneWidget); + expect(find.byIcon(Icons.drive_folder_upload_outlined), findsOneWidget); + expect(find.byTooltip('导出为 ZIP 压缩包'), findsOneWidget); + expect(find.byIcon(Icons.delete_outline), findsOneWidget); + + final targetZip = File(p.join(exportDir.path, 'my_export_app.zip')); + + // Tap export button inside runAsync so Isolate compression can complete + await tester.runAsync(() async { + await tester.tap(find.byIcon(Icons.drive_folder_upload_outlined)); + for (var i = 0; i < 50; i++) { + await Future.delayed(const Duration(milliseconds: 100)); + if (targetZip.existsSync()) break; + } + }); + await tester.pump(); + await tester.pump(const Duration(seconds: 4)); + + // Verify exported file exists on disk + expect(targetZip.existsSync(), isTrue); + expect(targetZip.lengthSync(), greaterThan(0)); + }); + + testWidgets('Exporting when target zip exists prompts for overwrite confirmation', (tester) async { + final projDir = await projectService.createProject('app_conflict'); + File(p.join(projDir.path, 'code.dart')).writeAsStringSync('int a = 1;'); + + final exportDir = Directory(p.join(tempBaseDir.path, 'exports_conflict'))..createSync(); + final existingZip = File(p.join(exportDir.path, 'app_conflict.zip'))..writeAsStringSync('old zip content'); + mockFilePicker.pickedDirectory = exportDir.path; + + await tester.pumpWidget(buildTestWidget( + child: const ProjectManagementView(), + locale: const Locale('zh'), + )); + await tester.pumpAndSettle(); + + // Tap export button + await tester.tap(find.byIcon(Icons.drive_folder_upload_outlined)); + await tester.pumpAndSettle(); + + // Overwrite confirmation dialog should appear + expect(find.text('目标文件 "app_conflict.zip" 已存在,是否覆盖?'), findsOneWidget); + expect(find.text('覆盖'), findsOneWidget); + expect(find.text('取消'), findsOneWidget); + + // Cancel first + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(existingZip.readAsStringSync(), equals('old zip content')); + + // Tap export again and confirm overwrite + await tester.tap(find.byIcon(Icons.drive_folder_upload_outlined)); + await tester.pumpAndSettle(); + + await tester.runAsync(() async { + await tester.tap(find.text('覆盖')); + for (var i = 0; i < 50; i++) { + await Future.delayed(const Duration(milliseconds: 100)); + if (existingZip.existsSync() && existingZip.lengthSync() > 15) { + break; + } + } + }); + await tester.pump(); + await tester.pump(const Duration(seconds: 4)); + + expect(existingZip.existsSync(), isTrue); + expect(existingZip.lengthSync(), greaterThan(15)); + final bytes = existingZip.readAsBytesSync(); + expect(bytes[0], equals(0x50)); + expect(bytes[1], equals(0x4B)); + }); + + testWidgets('Export button tooltips follow English locale', (tester) async { + await projectService.createProject('en_project'); + + await tester.pumpWidget(buildTestWidget( + child: const ProjectManagementView(), + locale: const Locale('en'), + )); + await tester.pumpAndSettle(); + + expect(find.byTooltip('Export as ZIP archive'), findsOneWidget); + expect(find.byTooltip('Rename Project'), findsOneWidget); + expect(find.byTooltip('Delete Project'), findsOneWidget); + }); }); } diff --git a/test/terminal_battery_and_history_test.dart b/test/terminal_battery_and_history_test.dart new file mode 100644 index 0000000..3edbf13 --- /dev/null +++ b/test/terminal_battery_and_history_test.dart @@ -0,0 +1,209 @@ +import 'dart:io'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/providers/distro_provider.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/services/internal_project_service.dart'; +import 'package:code_editor/services/permission_service.dart'; +import 'package:code_editor/services/project_history_service.dart'; +import 'package:code_editor/views/terminal_view.dart'; +import 'package:code_editor/widgets/code_editor_app_bar.dart'; +import 'package:code_editor/widgets/project_history_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + late InternalProjectService projectService; + late ProjectProvider projectProvider; + late TabProvider tabProvider; + late SettingsProvider settingsProvider; + late TerminalProvider terminalProvider; + late DistroProvider distroProvider; + late RunProvider runProvider; + + setUp(() { + SharedPreferences.setMockInitialValues({}); + tempBaseDir = Directory.systemTemp.createTempSync('term_batt_test_'); + projectService = InternalProjectService.instance; + projectService.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects')); + + projectProvider = ProjectProvider(); + tabProvider = TabProvider()..bindProjectProvider(projectProvider); + settingsProvider = SettingsProvider(); + terminalProvider = TerminalProvider(); + distroProvider = DistroProvider(); + runProvider = RunProvider(); + }); + + tearDown(() { + projectService.customProjectsDir = null; + if (tempBaseDir.existsSync()) { + try { + tempBaseDir.deleteSync(recursive: true); + } catch (_) {} + } + }); + + Widget buildTestApp({required Widget child, Locale locale = const Locale('zh')}) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: terminalProvider), + ChangeNotifierProvider.value(value: distroProvider), + ChangeNotifierProvider.value(value: runProvider), + ], + child: MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [ + Locale('zh'), + Locale('en'), + ], + locale: locale, + home: child, + ), + ); + } + + group('ProjectHistoryWidget 内部与外部项目展示测试', () { + testWidgets('内部项目副标题显示项目名称,外部项目副标题显示绝对路径', (tester) async { + // 创建一个内部项目路径 + final internalProjectsDir = projectService.customProjectsDir!; + final internalDir = Directory(p.join(internalProjectsDir.path, 'my_internal_app'))..createSync(recursive: true); + final internalFile = File(p.join(internalDir.path, 'lib', 'main.dart'))..createSync(recursive: true); + + // 创建一个外部项目路径 + final externalDir = Directory(p.join(tempBaseDir.path, 'outside', 'external_proj'))..createSync(recursive: true); + final externalFile = File(p.join(externalDir.path, 'app.py'))..createSync(recursive: true); + + // 录入历史 + await ProjectHistoryService.instance.recordHistory( + rootPath: internalDir.path, + lastOpenedFilePath: internalFile.path, + ); + await ProjectHistoryService.instance.recordHistory( + rootPath: externalDir.path, + lastOpenedFilePath: externalFile.path, + ); + + await tester.pumpWidget(buildTestApp( + child: const Scaffold( + body: ProjectHistoryWidget(), + ), + )); + await tester.pumpAndSettle(); + + // 验证内部项目:显示项目名 "my_internal_app",而不显示绝对路径 + expect(find.text('my_internal_app'), findsOneWidget); + expect(find.text(internalDir.path), findsNothing); + + // 验证外部项目:显示完整绝对路径 + expect(find.text(externalDir.path), findsOneWidget); + }); + }); + + group('TerminalView AppBar 副标题展示测试', () { + testWidgets('内部项目工作区副标题显示项目名,外部项目工作区副标题显示完整路径', (tester) async { + final internalProjectsDir = projectService.customProjectsDir!; + final internalDir = Directory(p.join(internalProjectsDir.path, 'term_internal_proj'))..createSync(recursive: true); + + // 会话 1:绑定内部项目工作区 + terminalProvider.createSession( + name: '会话1', + distroId: 'ubuntu', + workspacePath: internalDir.path, + activate: true, + ); + + await tester.pumpWidget(buildTestApp( + child: const TerminalView(), + )); + await tester.pumpAndSettle(); + + // AppBar 标题与副标题 + expect(find.text('会话1'), findsOneWidget); + // 内部项目:副标题应为项目名称 "term_internal_proj",而不是绝对路径 + expect(find.text('term_internal_proj'), findsOneWidget); + expect(find.text(internalDir.path), findsNothing); + + // 切换为外部项目工作区会话 + final externalPath = p.normalize('C:/workspace/my_ext_work'); + terminalProvider.createSession( + name: '会话2', + distroId: 'ubuntu', + workspacePath: externalPath, + activate: true, + ); + await tester.pumpAndSettle(); + + expect(find.text('会话2'), findsOneWidget); + // 外部项目:副标题应为完整路径 + expect(find.text(externalPath), findsOneWidget); + }); + }); + + group('进入终端前的电池优化检测与导航测试', () { + testWidgets('点击 AppBar 更多菜单中的终端按钮触发进入终端', (tester) async { + await tester.pumpWidget(buildTestApp( + child: const Scaffold( + appBar: CodeEditorAppBar(filePath: null), + body: Center(child: Text('Editor')), + ), + )); + await tester.pumpAndSettle(); + + // 点击右上角更多按钮 + final moreButton = find.byIcon(Icons.more_vert); + expect(moreButton, findsOneWidget); + await tester.tap(moreButton); + await tester.pumpAndSettle(); + + // 菜单弹出,找到“终端”选项 + final terminalItem = find.text('终端'); + expect(terminalItem, findsOneWidget); + + // 点击终端 + await tester.tap(terminalItem); + await tester.pumpAndSettle(); + + // 验证进入终端视图 TerminalView + expect(find.byType(TerminalView), findsOneWidget); + }); + + testWidgets('非 Android 平台下 promptBatteryOptimizationIfNeeded 静默返回 false 且无弹窗', (tester) async { + await tester.pumpWidget(buildTestApp( + child: Builder( + builder: (context) => ElevatedButton( + onPressed: () async { + final res = await PermissionService.instance.promptBatteryOptimizationIfNeeded(context); + expect(res, isFalse); + }, + child: const Text('Test'), + ), + ), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Test')); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + }); + }); +} diff --git a/test/terminal_selection_and_menu_test.dart b/test/terminal_selection_and_menu_test.dart new file mode 100644 index 0000000..8ccf899 --- /dev/null +++ b/test/terminal_selection_and_menu_test.dart @@ -0,0 +1,261 @@ +import 'dart:ui'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/widgets/terminal_selection_overlay.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart' as xterm; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('TerminalSelectionOverlay 终端框选与菜单测试', () { + late xterm.Terminal terminal; + late xterm.TerminalController controller; + late FocusNode focusNode; + late GlobalKey terminalViewKey; + + String? clipboardContent; + + setUp(() { + terminal = xterm.Terminal(maxLines: 100); + controller = xterm.TerminalController(); + focusNode = FocusNode(); + terminalViewKey = GlobalKey(); + clipboardContent = null; + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + if (methodCall.method == 'Clipboard.setData') { + clipboardContent = (methodCall.arguments as Map)['text'] as String?; + return null; + } + if (methodCall.method == 'Clipboard.getData') { + return {'text': clipboardContent}; + } + return null; + }, + ); + }); + + tearDown(() { + controller.dispose(); + focusNode.dispose(); + }); + + Widget buildTestWidget({Locale locale = const Locale('zh')}) { + return MaterialApp( + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 400, + height: 600, + child: TerminalSelectionOverlay( + terminal: terminal, + controller: controller, + terminalViewKey: terminalViewKey, + focusNode: focusNode, + child: xterm.TerminalView( + terminal, + key: terminalViewKey, + controller: controller, + focusNode: focusNode, + ), + ), + ), + ), + ); + } + + testWidgets('无选区时不显示拖动手柄与弹出菜单', (tester) async { + terminal.write('Hello Terminal\r\n'); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + expect(find.byType(CustomPaint), findsWidgets); + // 没有任何选区手柄或菜单 + expect(find.text('复制'), findsNothing); + expect(find.text('粘贴'), findsNothing); + expect(find.text('全选'), findsNothing); + }); + + testWidgets('选中文本后自动展示两个拖动手柄以及浮动菜单', (tester) async { + terminal.write('Hello Terminal World\r\n'); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + // 设置选区覆盖 "Hello" + controller.setSelection( + terminal.buffer.createAnchor(0, 0), + terminal.buffer.createAnchor(5, 0), + ); + await tester.pumpAndSettle(); + + // 菜单弹出:包含复制、粘贴、全选 + expect(find.text('复制'), findsOneWidget); + expect(find.text('粘贴'), findsOneWidget); + expect(find.text('全选'), findsOneWidget); + + // 选区存在手柄 + expect(controller.selection, isNotNull); + expect(controller.selection!.isCollapsed, isFalse); + }); + + testWidgets('英文环境下菜单显示 Copy, Paste, Select All', (tester) async { + terminal.write('Hello Terminal World\r\n'); + await tester.pumpWidget(buildTestWidget(locale: const Locale('en'))); + await tester.pumpAndSettle(); + + controller.setSelection( + terminal.buffer.createAnchor(0, 0), + terminal.buffer.createAnchor(5, 0), + ); + await tester.pumpAndSettle(); + + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Paste'), findsOneWidget); + expect(find.text('Select All'), findsOneWidget); + }); + + testWidgets('点击菜单中的“复制”将选区文本写入剪贴板并清空选区与关闭菜单', (tester) async { + terminal.write('TestText\r\n'); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + // 清空初始系统剪贴板 + await Clipboard.setData(const ClipboardData(text: '')); + + controller.setSelection( + terminal.buffer.createAnchor(0, 0), + terminal.buffer.createAnchor(8, 0), + ); + await tester.pumpAndSettle(); + + expect(find.text('复制'), findsOneWidget); + await tester.tap(find.text('复制')); + await tester.pump(); + await tester.pump(const Duration(seconds: 3)); + await tester.pumpAndSettle(); + + // 验证剪贴板 + final clipData = await Clipboard.getData(Clipboard.kTextPlain); + expect(clipData?.text, equals('TestText')); + + // 选区已清空,菜单已隐藏 + expect(controller.selection, isNull); + expect(find.text('复制'), findsNothing); + }); + + testWidgets('点击菜单中的“粘贴”将剪贴板内容输入到终端', (tester) async { + String? outputData; + terminal.onOutput = (data) { + outputData = data; + terminal.write(data); + }; + + terminal.write('Prompt\$ '); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + clipboardContent = 'ls -la'; + + controller.setSelection( + terminal.buffer.createAnchor(0, 0), + terminal.buffer.createAnchor(6, 0), + ); + await tester.pumpAndSettle(); + + expect(find.text('粘贴'), findsOneWidget); + await tester.tap(find.text('粘贴')); + await tester.pumpAndSettle(); + + // 验证终端输出被粘贴 + expect(outputData, equals('ls -la')); + expect(terminal.buffer.getText(), contains('ls -la')); + expect(controller.selection, isNull); + expect(find.text('粘贴'), findsNothing); + }); + + testWidgets('点击菜单中的“全选”选择终端所有可见字符', (tester) async { + terminal.write('Line 1\r\nLine 2\r\nLine 3\r\n'); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + controller.setSelection( + terminal.buffer.createAnchor(0, 0), + terminal.buffer.createAnchor(4, 0), + ); + await tester.pumpAndSettle(); + + expect(find.text('全选'), findsOneWidget); + await tester.tap(find.text('全选')); + await tester.pumpAndSettle(); + + // 选区扩展 + expect(controller.selection, isNotNull); + expect(controller.selection!.begin.x, equals(0)); + expect(controller.selection!.begin.y, equals(0)); + }); + + testWidgets('拖动手柄时隐藏弹出菜单,拖动结束后重新展示', (tester) async { + terminal.write('Hello World from Terminal\r\n'); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + controller.setSelection( + terminal.buffer.createAnchor(0, 0), + terminal.buffer.createAnchor(11, 0), + ); + await tester.pumpAndSettle(); + expect(find.text('复制'), findsOneWidget); + + final handleFinder = find.byWidgetPredicate( + (w) => w.runtimeType.toString() == '_TerminalSelectionHandle', + ); + expect(handleFinder, findsNWidgets(2)); + + // 模拟拖拽结束手柄 + final handleCenter = tester.getCenter(handleFinder.last); + final gesture = await tester.startGesture(handleCenter); + await tester.pump(); + await gesture.moveBy(const Offset(30, 0)); + await tester.pump(); + + // 移动过程中菜单隐藏 + expect(find.text('复制'), findsNothing); + + await gesture.up(); + await tester.pumpAndSettle(); + + // 松手后菜单恢复 + expect(find.text('复制'), findsOneWidget); + }); + + testWidgets('鼠标直接拖动框选文本后松开弹出菜单', (tester) async { + terminal.write('Hello Terminal World\r\n'); + await tester.pumpWidget(buildTestWidget()); + await tester.pumpAndSettle(); + + final terminalTopLeft = tester.getTopLeft(find.byType(xterm.TerminalView)); + // 在文本区域内拖动 + final gesture = await tester.startGesture( + terminalTopLeft + const Offset(15, 15), + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + await gesture.moveBy(const Offset(60, 0)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // 验证是否已选中文本 + expect(controller.selection, isNotNull); + expect(controller.selection!.isCollapsed, isFalse); + // 验证菜单是否弹出 + expect(find.text('复制'), findsOneWidget); + }); + }); +}