This commit is contained in:
LZX committed 2026-09-17 16:32:27 +08:00
1 parent 5ac164b407
commit f93f6095af
94 files changed
+7877 -4018

No files matched your search

@@ -0,0 +1,123 @@
import '../../models/distro_manifest.dart';
import '../../models/notice_item.dart';
import '../distro_manager.dart';
import '../internal_engine_service.dart';
import 'background_task.dart';
/// Ubuntu APT 软件包安装与卸载任务
///
/// 运行在 [TaskExecutionScope.packageManager] 互斥域内,
/// 保证同一时刻全局只有一个 apt-get/dpkg 命令执行,杜绝锁冲突。
class AptPackageTask extends BackgroundTask<bool> {
final String packageName;
final String componentDisplayName;
final bool isUninstall;
@override
final TaskPriority priority;
AptPackageTask({
required this.packageName,
required this.componentDisplayName,
this.isUninstall = false,
this.priority = TaskPriority.userInitiated,
});
@override
String get id => 'pkg:${isUninstall ? 'remove' : 'install'}:$packageName';
@override
TaskExecutionScope get scope => TaskExecutionScope.packageManager;
@override
NoticeText? createNoticeText(
BackgroundTaskState state, {
String? detail,
String? error,
}) {
switch (state) {
case BackgroundTaskState.queued:
return ComponentInstallPhaseText(
componentName: componentDisplayName,
isUninstall: isUninstall,
isQueued: true,
);
case BackgroundTaskState.running:
return ComponentInstallPhaseText(
componentName: componentDisplayName,
isUninstall: isUninstall,
isQueued: false,
detail: detail,
);
case BackgroundTaskState.completed:
return ComponentInstallDoneText(
componentName: componentDisplayName,
isUninstall: isUninstall,
);
case BackgroundTaskState.failed:
return ComponentInstallFailureText(
componentName: componentDisplayName,
isUninstall: isUninstall,
error: error,
);
case BackgroundTaskState.cancelled:
return null;
}
}
@override
Future<bool> execute(TaskExecutionContext context) async {
final engine = InternalEngineService.instance;
if (!await engine.isEngineInstalled() || packageName.trim().isEmpty) {
return false;
}
final rootfs = await engine.getRootfsDir();
final cmd = isUninstall
? 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; '
'dpkg --configure -a 2>/dev/null || true; '
'apt-get remove --purge -y ${packageName.trim()} && '
'apt-get autoremove -y'
: 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; '
'dpkg --configure -a 2>/dev/null || true; '
'apt-get update && '
'apt-get install -y --no-install-recommends ${packageName.trim()}';
final res = await DistroManager().runHeadlessCommand(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: cmd,
timeout: isUninstall ? const Duration(minutes: 5) : const Duration(minutes: 10),
cancelToken: context.cancelToken,
onStdout: (chunk) {
final line = chunk.trim();
if (line.isNotEmpty) {
context.updateDetail(line);
}
},
);
if (context.isCancelled) {
// 被取消后,进行一次后台锁自愈
_healDpkgLock(rootfs);
return false;
}
final success = res != null && res.exitCode == 0;
if (!success) {
throw Exception(
'apt process exited with code ${res?.exitCode ?? -1}: ${res?.stderr}',
);
}
return true;
}
void _healDpkgLock(dynamic rootfs) {
DistroManager().runHeadlessCommand(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: 'dpkg --configure -a 2>/dev/null || true',
timeout: const Duration(seconds: 30),
);
}
}
@@ -0,0 +1,91 @@
import '../../models/notice_item.dart';
import '../distro_manager.dart';
/// 任务执行范围(互斥域)
enum TaskExecutionScope {
/// 包管理器域:严格单线程串行(Ubuntu 下 apt-get / dpkg 独占锁保护)
packageManager,
/// 独占域:暂停所有其它任务,独自运行
exclusive,
/// 共享只读域:允许与其他非 exclusive 任务并发运行(如无副作用的检查、扫描)
shared,
}
/// 任务优先级(值越大越靠前出队)
enum TaskPriority implements Comparable<TaskPriority> {
/// 用户主动触发(如用户点击安装/卸载组件):最高优先
userInitiated(100),
/// 项目生命周期触发(如打开工程后的模块依赖探测):标准优先级
projectLifecycle(50),
/// 静默预热/后台空闲:低优先级
backgroundIdle(10);
final int value;
const TaskPriority(this.value);
@override
int compareTo(TaskPriority other) => other.value.compareTo(value);
}
/// 任务执行状态
enum BackgroundTaskState {
queued,
running,
completed,
failed,
cancelled,
}
/// 任务执行上下文
class TaskExecutionContext {
/// 用于中断底层进程的取消令牌
final HeadlessCancelToken cancelToken;
/// 实时输出行/副标题更新
final void Function(String line) updateDetail;
/// 进度百分比更新(0.0 ~ 1.0)
final void Function(double? progress) updateProgress;
const TaskExecutionContext({
required this.cancelToken,
required this.updateDetail,
required this.updateProgress,
});
bool get isCancelled => cancelToken.isCancelled;
}
/// 全局后台任务抽象接口
abstract class BackgroundTask<T> {
/// 全局唯一任务 ID(同时作为右上角通知 NoticeItem 的 id)
String get id;
/// 互斥作用域
TaskExecutionScope get scope;
/// 优先级
TaskPriority get priority => TaskPriority.projectLifecycle;
/// 是否在 NoticeCenter 中展示右上角悬浮通知
bool get showNotice => true;
/// 根据状态生成对应的结构化通知文案(无硬编码)
NoticeText? createNoticeText(BackgroundTaskState state, {String? detail, String? error});
/// 核心执行体
Future<T> execute(TaskExecutionContext context);
/// 取消回调
void onCancelled() {}
/// 失败回调
void onFailure(Object error, StackTrace stackTrace) {}
/// 成功回调
void onSuccess(T result) {}
}
@@ -0,0 +1,302 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../models/notice_item.dart';
import '../../providers/notice_center.dart';
import '../distro_manager.dart';
import 'background_task.dart';
/// 待执行任务包装条目
class _QueuedTaskEntry<T> {
final BackgroundTask<T> task;
final Completer<T> completer;
final HeadlessCancelToken cancelToken;
_QueuedTaskEntry({
required this.task,
required this.completer,
required this.cancelToken,
});
}
/// 统一后台任务调度中心
///
/// 核心职责:
/// 1. 任务排队与优先级排序;
/// 2. [TaskExecutionScope] 资源互斥域管控(针对 Ubuntu 单底座 apt/dpkg 独占锁,严格串行 packageManager 域);
/// 3. 与 [NoticeCenter] 双向联动(反映入队、执行中、成功淡出、失败驻留,UI 取消联动底层进程中断);
/// 4. 任务取消与失败时的环境自愈保护。
class BackgroundTaskScheduler {
BackgroundTaskScheduler._();
static final BackgroundTaskScheduler instance = BackgroundTaskScheduler._();
NoticeCenter? _noticeCenter;
/// 待执行任务队列
final List<_QueuedTaskEntry> _queue = [];
/// 正在运行的任务集合
final Map<String, _QueuedTaskEntry> _runningTasks = {};
/// 绑定全局通知中心
void attachNoticeCenter(NoticeCenter noticeCenter) {
_noticeCenter = noticeCenter;
}
/// 提交一个后台任务
Future<T> submit<T>(BackgroundTask<T> task) {
final completer = Completer<T>();
final cancelToken = HeadlessCancelToken();
final entry = _QueuedTaskEntry<T>(
task: task,
completer: completer,
cancelToken: cancelToken,
);
// 插入并按优先级降序排序(优先级高在先)
_queue.add(entry);
_queue.sort((a, b) => a.task.priority.compareTo(b.task.priority));
// 通知中心同步:若任务配置了通知,则先发入队卡片
if (task.showNotice && _noticeCenter != null) {
final text = task.createNoticeText(BackgroundTaskState.queued);
if (text != null) {
_noticeCenter!.push(
NoticeItem(
id: task.id,
kind: NoticeKind.progress,
text: text,
onUserDismiss: () => cancel(task.id),
),
);
}
}
_scheduleNext();
return completer.future;
}
/// 取消指定 ID 的任务(若在队列中则移除,若在运行中则触发 cancelToken)
void cancel(String taskId) {
// 1. 检查队列中尚未启动的任务
final qIndex = _queue.indexWhere((e) => e.task.id == taskId);
if (qIndex != -1) {
final entry = _queue.removeAt(qIndex);
entry.cancelToken.cancel();
try {
entry.task.onCancelled();
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
if (!entry.completer.isCompleted) {
entry.completer.completeError(
const CancellationException('Task cancelled before start'),
);
}
_noticeCenter?.dismiss(taskId);
return;
}
// 2. 检查正在运行的任务
final running = _runningTasks[taskId];
if (running != null) {
running.cancelToken.cancel();
try {
running.task.onCancelled();
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
// 不直接 dismiss,等待执行体退出抛出/退出时自然结算
}
}
/// 是否有任务正在占用 packageManager 锁
bool get isPackageManagerBusy {
return _runningTasks.values
.any((e) => e.task.scope == TaskExecutionScope.packageManager);
}
/// 是否有独占任务正在运行
bool get isExclusiveBusy {
return _runningTasks.values
.any((e) => e.task.scope == TaskExecutionScope.exclusive);
}
/// 正在运行的任务总数
int get runningCount => _runningTasks.length;
/// 等待队列中的任务总数
int get queuedCount => _queue.length;
/// 核心调度分配逻辑
void _scheduleNext() {
if (_queue.isEmpty) return;
// 若当前有 exclusive 任务正在运行,阻塞一切新任务
if (isExclusiveBusy) return;
for (int i = 0; i < _queue.length; i++) {
final candidate = _queue[i];
final scope = candidate.task.scope;
if (scope == TaskExecutionScope.exclusive) {
// 独占任务必须等待当前所有运行中的任务全部结束才能起跑
if (_runningTasks.isEmpty) {
_queue.removeAt(i);
_executeTask(candidate);
}
return;
} else if (scope == TaskExecutionScope.packageManager) {
// 包管理器任务要求单线排他
if (!isPackageManagerBusy) {
_queue.removeAt(i);
_executeTask(candidate);
// 继续检查后续队列中是否有可以并发执行的 shared 任务
_scheduleNext();
return;
}
} else if (scope == TaskExecutionScope.shared) {
// 共享任务可以并发运行(受最大并发限制,如 4)
if (_runningTasks.length < 4) {
_queue.removeAt(i);
_executeTask(candidate);
_scheduleNext();
return;
}
}
}
}
Future<void> _executeTask(_QueuedTaskEntry entry) async {
final task = entry.task;
_runningTasks[task.id] = entry;
// 更新为运行中通知
if (task.showNotice && _noticeCenter != null) {
final text = task.createNoticeText(BackgroundTaskState.running);
if (text != null) {
_noticeCenter!.update(
task.id,
kind: NoticeKind.progress,
text: text,
);
}
}
final context = TaskExecutionContext(
cancelToken: entry.cancelToken,
updateDetail: (detail) {
if (!entry.cancelToken.isCancelled && task.showNotice && _noticeCenter != null) {
final text = task.createNoticeText(BackgroundTaskState.running, detail: detail);
if (text != null) {
_noticeCenter!.update(task.id, text: text);
}
}
},
updateProgress: (progress) {
if (!entry.cancelToken.isCancelled && task.showNotice && _noticeCenter != null) {
_noticeCenter!.update(task.id, progress: progress);
}
},
);
try {
final result = await task.execute(context);
_runningTasks.remove(task.id);
if (entry.cancelToken.isCancelled) {
try {
task.onCancelled();
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
_noticeCenter?.dismiss(task.id);
if (!entry.completer.isCompleted) {
entry.completer.completeError(
const CancellationException('Task was cancelled during execution'),
);
}
} else {
try {
task.onSuccess(result);
} catch (e) {
debugPrint('[BackgroundTaskScheduler] onSuccess 异常: ');
}
if (task.showNotice && _noticeCenter != null) {
final doneText = task.createNoticeText(BackgroundTaskState.completed);
if (doneText != null) {
_noticeCenter!.complete(
task.id,
kind: NoticeKind.success,
text: doneText,
autoCloseAfter: const Duration(seconds: 3),
);
} else {
_noticeCenter!.dismiss(task.id);
}
}
if (!entry.completer.isCompleted) {
entry.completer.complete(result);
}
}
} catch (e, stack) {
_runningTasks.remove(task.id);
if (entry.cancelToken.isCancelled) {
try {
task.onCancelled();
} catch (err) {
debugPrint('[BackgroundTaskScheduler] onCancelled 异常: ');
}
_noticeCenter?.dismiss(task.id);
if (!entry.completer.isCompleted) {
entry.completer.completeError(
const CancellationException('Task was cancelled'),
);
}
} else {
try {
task.onFailure(e, stack);
} catch (err) {
debugPrint('[BackgroundTaskScheduler] onFailure 异常: ');
}
if (task.showNotice && _noticeCenter != null) {
final failText = task.createNoticeText(
BackgroundTaskState.failed,
error: e.toString(),
);
if (failText != null) {
_noticeCenter!.complete(
task.id,
kind: NoticeKind.failure,
text: failText,
sticky: true,
);
} else {
_noticeCenter!.dismiss(task.id);
}
}
if (!entry.completer.isCompleted) {
entry.completer.completeError(e, stack);
}
}
} finally {
// 触发后续调度
_scheduleNext();
}
}
}
/// 取消异常定义
class CancellationException implements Exception {
final String message;
const CancellationException([this.message = 'Operation was cancelled']);
@override
String toString() => 'CancellationException: ';
}
@@ -0,0 +1,36 @@
import '../../models/notice_item.dart';
import 'background_task.dart';
/// 包装一个函数执行体到后台调度系统(如探测中的依赖自动安装等)
class GenericBackgroundTask<T> extends BackgroundTask<T> {
@override
final String id;
@override
final TaskExecutionScope scope;
@override
final TaskPriority priority;
@override
final bool showNotice;
final Future<T> Function(TaskExecutionContext context) runner;
final NoticeText? Function(BackgroundTaskState state, {String? detail, String? error})? noticeTextBuilder;
GenericBackgroundTask({
required this.id,
required this.scope,
this.priority = TaskPriority.projectLifecycle,
this.showNotice = false,
required this.runner,
this.noticeTextBuilder,
});
@override
NoticeText? createNoticeText(BackgroundTaskState state, {String? detail, String? error}) {
return noticeTextBuilder?.call(state, detail: detail, error: error);
}
@override
Future<T> execute(TaskExecutionContext context) {
return runner(context);
}
}
@@ -0,0 +1,136 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:re_editor/re_editor.dart';
import '../fuzzy_matcher.dart';
import '../providers/completion_provider.dart';
import 'completion_types.dart';
/// 补全调度引擎 (Completion Engine)
///
/// 核心职责:
/// 1. 0ms 同步聚合本地所有同步 Provider(关键字、词法启发提取),保证首帧流畅弹出;
/// 2. 异步发起 LSP 或远程 Provider 请求;
/// 3. 基于 requestId 与版本号防抖校验,杜绝陈旧回包覆盖;
/// 4. 统一执行 Fuzzy 模糊匹配打分、sortText 权重排序与截断;
/// 5. 动态向绑定的 ValueNotifier 推流更新,实现平滑渐进增强。
class CompletionEngine {
CompletionEngine({
required this.providers,
this.maxSuggestions = 40,
});
final List<CompletionProvider> providers;
final int maxSuggestions;
int _lastRequestId = 0;
/// 异步直接请求补全(专为 LSP 异步语义流优化设计)
Future<CodeAutocompleteEditingValue?> requestCompletionsAsync(
CompletionContext context,
) async {
final currentRequestId = ++_lastRequestId;
final currentInput = context.input;
try {
final results = await Future.wait(
providers.map((p) async {
try {
final res = await p.provideCompletions(context);
return res;
} catch (_) {
return <SmartPrompt>[];
}
}),
);
// 请求过期(用户已键入新内容或已移动光标),直接废弃
if (currentRequestId != _lastRequestId) return null;
final allPrompts = <SmartPrompt>[];
final seenWords = <String>{};
for (final list in results) {
for (final p in list) {
if (seenWords.add(p.word)) {
allPrompts.add(p);
}
}
}
if (allPrompts.isEmpty) return null;
return scoreAndFilter(allPrompts, currentInput);
} catch (_) {
return null;
}
}
/// 兼容推流式调用
CodeAutocompleteEditingValue? requestCompletions(
CompletionContext context, {
ValueNotifier<CodeAutocompleteEditingValue>? notifier,
}) {
if (notifier != null) {
requestCompletionsAsync(context).then((value) {
if (value != null) {
notifier.value = value;
}
});
}
return null;
}
/// 模糊匹配打分、权重排序与截取
CodeAutocompleteEditingValue? scoreAndFilter(List<SmartPrompt> candidates, String input) {
if (candidates.isEmpty) {
return null;
}
final List<SmartPrompt> matchedPrompts = [];
for (final candidate in candidates) {
if (input.isEmpty) {
matchedPrompts.add(candidate.copyWithScore(
score: 100,
matchedIndices: const [],
));
} else {
final result = FuzzyMatcher.match(input, candidate.word);
if (result.isMatch) {
matchedPrompts.add(candidate.copyWithScore(
score: result.score,
matchedIndices: result.matchedIndices,
));
}
}
}
if (matchedPrompts.isEmpty) {
return null;
}
// 按照得分降序排序,相同得分若有 LSP sortText 则依据 sortText 升序,否则按字典序升序
matchedPrompts.sort((a, b) {
final scoreCompare = b.score.compareTo(a.score);
if (scoreCompare != 0) return scoreCompare;
if (a.sortText != null && b.sortText != null) {
final sortCompare = a.sortText!.compareTo(b.sortText!);
if (sortCompare != 0) return sortCompare;
}
return a.word.compareTo(b.word);
});
// 截取前 maxSuggestions 条最佳结果,保证 60fps 流畅渲染
final limitedPrompts = matchedPrompts.take(maxSuggestions).toList();
return CodeAutocompleteEditingValue(
input: input,
prompts: limitedPrompts,
index: 0,
);
}
void dispose() {
_lastRequestId++;
for (final provider in providers) {
provider.dispose();
}
}
}
@@ -0,0 +1,112 @@
import 'package:flutter/widgets.dart';
import 'package:re_editor/re_editor.dart';
import '../fuzzy_matcher.dart';
/// 补全候选词类别
enum SmartPromptKind {
keyword,
function,
field,
type,
constant,
word,
}
/// 具有模糊匹配打分与高亮索引的工业级智能补全 Prompt
class SmartPrompt extends CodePrompt {
SmartPrompt({
required super.word,
this.type,
this.kind = SmartPromptKind.word,
this.customAutocomplete,
this.parameters = const {},
this.score = 0,
this.matchedIndices = const [],
this.detail,
this.documentation,
this.sortText,
});
final String? type;
final SmartPromptKind kind;
final CodeAutocompleteResult? customAutocomplete;
final Map<String, String> parameters;
final String? detail;
final String? documentation;
final String? sortText;
int score;
List<int> matchedIndices;
@override
CodeAutocompleteResult get autocomplete {
if (customAutocomplete != null) {
return customAutocomplete!;
}
if (kind == SmartPromptKind.function && parameters.isNotEmpty) {
final paramStr = parameters.keys.join(', ');
return CodeAutocompleteResult(
input: '',
word: '$word($paramStr)',
selection: TextSelection.collapsed(offset: word.length + 1),
);
}
return CodeAutocompleteResult.fromWord(word);
}
@override
bool match(String input) {
if (input.isEmpty) return true;
final res = FuzzyMatcher.match(input, word);
if (res.isMatch) {
score = res.score;
matchedIndices = res.matchedIndices;
return true;
}
return false;
}
SmartPrompt copyWithScore({
required int score,
required List<int> matchedIndices,
}) {
return SmartPrompt(
word: word,
type: type,
kind: kind,
customAutocomplete: customAutocomplete,
parameters: parameters,
score: score,
matchedIndices: matchedIndices,
detail: detail,
documentation: documentation,
sortText: sortText,
);
}
}
/// 代码补全上下文请求参数
class CompletionContext {
final String input;
final String? triggerCharacter;
final String? target;
final String? filePath;
final int lineIndex;
final int characterOffset;
final CodeLine codeLine;
final CodeLines? codeLines;
final CodeLineSelection selection;
const CompletionContext({
required this.input,
this.triggerCharacter,
this.target,
this.filePath,
required this.lineIndex,
required this.characterOffset,
required this.codeLine,
this.codeLines,
required this.selection,
});
bool get isDotTrigger => triggerCharacter == '.';
}
@@ -0,0 +1,247 @@
import 'dart:math';
/// 模糊匹配与打字纠错结果
class FuzzyMatchResult {
const FuzzyMatchResult({
required this.isMatch,
required this.score,
this.matchedIndices = const [],
});
static const notMatched = FuzzyMatchResult(isMatch: false, score: -1);
final bool isMatch;
final int score;
final List<int> matchedIndices;
}
/// 工业级代码模糊匹配与容错纠错打分器
class FuzzyMatcher {
const FuzzyMatcher();
/// 对 [pattern](用户输入)与 [target](候选词)进行匹配打分
///
/// 支持:
/// 1. 精确匹配 / 精确前缀匹配 (Prefix Match)
/// 2. 忽略大小写前缀匹配 (Case-insensitive Prefix)
/// 3. 驼峰与下划线缩写匹配 (CamelCase / Snake_case)
/// 4. 连续子序列匹配 (Subsequence Match with Consecutive Bonus)
/// 5. 打字手误纠错 (Typo Tolerance / Levenshtein Distance)
static FuzzyMatchResult match(String pattern, String target) {
if (pattern.isEmpty) {
return const FuzzyMatchResult(isMatch: true, score: 100);
}
if (target.isEmpty) {
return FuzzyMatchResult.notMatched;
}
// 1. 完全相同
if (pattern == target) {
return FuzzyMatchResult(
isMatch: true,
score: 3000,
matchedIndices: List.generate(pattern.length, (i) => i),
);
}
// 2. 严格区分大小写的前缀匹配 (最高优先级)
if (target.startsWith(pattern)) {
final score = 2000 - (target.length - pattern.length);
return FuzzyMatchResult(
isMatch: true,
score: score,
matchedIndices: List.generate(pattern.length, (i) => i),
);
}
final lowerPattern = pattern.toLowerCase();
final lowerTarget = target.toLowerCase();
// 3. 忽略大小写的前缀匹配
if (lowerTarget.startsWith(lowerPattern)) {
final score = 1500 - (target.length - pattern.length);
return FuzzyMatchResult(
isMatch: true,
score: score,
matchedIndices: List.generate(pattern.length, (i) => i),
);
}
// 4. 驼峰与下划线缩写匹配 (例如 "fb" 匹配 "FloatingActionButton", "tv" 匹配 "text_view")
final camelMatch = _matchCamelOrSeparator(lowerPattern, target);
if (camelMatch.isMatch) {
return camelMatch;
}
// 5. 字符子序列匹配 (Subsequence Match)
final subseqMatch = _matchSubsequence(lowerPattern, lowerTarget, target);
if (subseqMatch.isMatch) {
return subseqMatch;
}
// 6. 拼写手误纠错 (Typo Tolerance / Levenshtein Distance)
// 当输入字符长度 >= 3 时,允许前缀 1 处编辑距离错误(如 prnt -> print, lenght -> length)
// 当输入字符长度 >= 6 时,允许前缀 2 处编辑距离错误
if (pattern.length >= 3) {
final typoMatch = _matchTypo(lowerPattern, lowerTarget, target);
if (typoMatch.isMatch) {
return typoMatch;
}
}
return FuzzyMatchResult.notMatched;
}
/// 驼峰与分隔符匹配
static FuzzyMatchResult _matchCamelOrSeparator(String lowerPattern, String target) {
final List<int> wordStartIndices = [];
for (int i = 0; i < target.length; i++) {
final char = target[i];
if (i == 0) {
wordStartIndices.add(i);
} else if (char == '_' || char == '-' || char == '.') {
if (i + 1 < target.length) {
wordStartIndices.add(i + 1);
}
} else {
final isUpper = char.toUpperCase() == char && char.toLowerCase() != char;
final prevChar = target[i - 1];
final isPrevLower = prevChar.toLowerCase() == prevChar && prevChar.toUpperCase() != prevChar;
if (isUpper && isPrevLower) {
wordStartIndices.add(i);
}
}
}
if (lowerPattern.length <= wordStartIndices.length) {
int pIdx = 0;
final List<int> matched = [];
for (final sIdx in wordStartIndices) {
if (pIdx < lowerPattern.length &&
target[sIdx].toLowerCase() == lowerPattern[pIdx]) {
matched.add(sIdx);
pIdx++;
}
}
if (pIdx == lowerPattern.length) {
final score = 1000 - (target.length - lowerPattern.length) * 2;
return FuzzyMatchResult(
isMatch: true,
score: max(score, 600),
matchedIndices: matched,
);
}
}
return FuzzyMatchResult.notMatched;
}
/// 子序列匹配(考虑连续命中加分)
static FuzzyMatchResult _matchSubsequence(
String lowerPattern,
String lowerTarget,
String target,
) {
int pIdx = 0;
int tIdx = 0;
final List<int> matched = [];
int consecutiveCount = 0;
int score = 700;
while (pIdx < lowerPattern.length && tIdx < lowerTarget.length) {
if (lowerPattern[pIdx] == lowerTarget[tIdx]) {
matched.add(tIdx);
// 大小写一致加分
if (pIdx < target.length && target[tIdx] == lowerPattern[pIdx]) {
score += 10;
}
// 连续匹配加分
if (matched.length > 1 && matched.last == matched[matched.length - 2] + 1) {
consecutiveCount++;
score += consecutiveCount * 25;
} else {
consecutiveCount = 0;
}
pIdx++;
}
tIdx++;
}
if (pIdx == lowerPattern.length) {
score -= matched.first * 15;
score -= (target.length - lowerPattern.length) * 2;
return FuzzyMatchResult(
isMatch: true,
score: max(score, 450),
matchedIndices: matched,
);
}
return FuzzyMatchResult.notMatched;
}
/// 打字手误纠错(基于编辑距离对比前缀)
static FuzzyMatchResult _matchTypo(
String lowerPattern,
String lowerTarget,
String target,
) {
final int pLen = lowerPattern.length;
final int minLen = max(1, pLen - 1);
final int maxLen = min(lowerTarget.length, pLen + 1);
int bestDistance = 999;
int bestPrefixLen = pLen;
for (int len = minLen; len <= maxLen; len++) {
final prefix = lowerTarget.substring(0, len);
final dist = _levenshteinDistance(lowerPattern, prefix);
if (dist < bestDistance) {
bestDistance = dist;
bestPrefixLen = len;
}
}
final int maxAllowedDist = pLen >= 6 ? 2 : 1;
if (bestDistance <= maxAllowedDist) {
final score = 380 - (bestDistance * 80) - (target.length - pLen);
return FuzzyMatchResult(
isMatch: true,
score: max(score, 150),
matchedIndices: List.generate(min(bestPrefixLen, target.length), (i) => i),
);
}
return FuzzyMatchResult.notMatched;
}
/// 计算两个字符串的 Levenshtein 编辑距离
static int _levenshteinDistance(String s1, String s2) {
if (s1 == s2) return 0;
if (s1.isEmpty) return s2.length;
if (s2.isEmpty) return s1.length;
List<int> prev = List<int>.generate(s2.length + 1, (i) => i);
List<int> curr = List<int>.filled(s2.length + 1, 0);
for (int i = 0; i < s1.length; i++) {
curr[0] = i + 1;
for (int j = 0; j < s2.length; j++) {
final cost = (s1[i] == s2[j]) ? 0 : 1;
curr[j + 1] = min(
curr[j] + 1,
min(
prev[j + 1] + 1,
prev[j] + cost,
),
);
}
final temp = prev;
prev = curr;
curr = temp;
}
return prev[s2.length];
}
}
@@ -0,0 +1,17 @@
import 'dart:async';
import '../core/completion_types.dart';
/// 补全数据源提供者抽象契约
abstract class CompletionProvider {
/// 提供者唯一标识
String get id;
/// 是否为异步远程数据源(如 LSP)
bool get isAsync => false;
/// 依据上下文提供补全候选项
FutureOr<List<SmartPrompt>> provideCompletions(CompletionContext context);
/// 释放资源
void dispose() {}
}
@@ -0,0 +1,96 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:re_editor/re_editor.dart';
import '../../lsp/lsp_manager.dart';
import '../../lsp/lsp_protocol.dart';
import '../core/completion_types.dart';
import 'completion_provider.dart';
/// 远程 LSP 语言服务补全数据源提供者
class LspCompletionProvider implements CompletionProvider {
const LspCompletionProvider();
@override
String get id => 'lsp';
@override
bool get isAsync => true;
@override
Future<List<SmartPrompt>> provideCompletions(CompletionContext context) async {
final filePath = context.filePath;
if (filePath == null || filePath.isEmpty) {
return const [];
}
final session = LspManager.instance.getExistingSession(filePath);
if (session == null || !session.isInitialized) {
return const [];
}
final lspItems = await session.getCompletions(
filePath,
context.lineIndex,
context.characterOffset,
);
return lspItems.map(fromLspItem).toList();
}
/// 将 LSP 原始协议的 LspCompletionItem 转换为统一领域模型 SmartPrompt
static SmartPrompt fromLspItem(LspCompletionItem item) {
SmartPromptKind kind;
switch (item.kind) {
case 2: // Method
case 3: // Function
case 4: // Constructor
kind = SmartPromptKind.function;
break;
case 5: // Field
case 6: // Variable
case 10: // Property
kind = SmartPromptKind.field;
break;
case 7: // Class
case 8: // Interface
case 13: // Enum
case 22: // Struct
case 25: // TypeParameter
kind = SmartPromptKind.type;
break;
case 14: // Keyword
kind = SmartPromptKind.keyword;
break;
case 21: // Constant
kind = SmartPromptKind.constant;
break;
default:
kind = SmartPromptKind.word;
}
final insert = item.effectiveInsertText;
final word = item.label.isNotEmpty ? item.label : insert;
CodeAutocompleteResult? customAuto;
if (insert != word) {
customAuto = CodeAutocompleteResult(
input: '',
word: insert,
selection: TextSelection.collapsed(offset: insert.length),
);
}
return SmartPrompt(
word: word,
kind: kind,
type: item.detail,
detail: item.detail,
documentation: item.documentation,
sortText: item.sortText,
customAutocomplete: customAuto,
);
}
@override
void dispose() {}
}
@@ -0,0 +1,144 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:re_editor/re_editor.dart';
import 'core/completion_engine.dart';
import 'core/completion_types.dart';
import 'providers/completion_provider.dart';
import 'providers/lsp_completion_provider.dart';
export 'core/completion_engine.dart';
export 'core/completion_types.dart';
export 'providers/completion_provider.dart';
export 'providers/lsp_completion_provider.dart';
/// 工业级智能代码补全构建器适配器
///
/// 实现 re_editor 的 CodeAutocompletePromptsBuilder 协议,
/// 将编辑器的输入上下文规范化后,转派给 LSP CompletionEngine 异步调度处理。
class SmartCodeAutocompletePromptsBuilder implements CodeAutocompletePromptsBuilder {
SmartCodeAutocompletePromptsBuilder({
this.controller,
this.filePath,
this.enableLspCompletion = true,
@Deprecated('本地补全已完全移除,此参数无效') bool enableLocalCompletion = false,
@Deprecated('本地补全已完全移除,此参数无效') dynamic language,
@Deprecated('本地补全已完全移除,此参数无效') List<CodePrompt> keywordPrompts = const [],
@Deprecated('本地补全已完全移除,此参数无效') List<CodePrompt> directPrompts = const [],
@Deprecated('本地补全已完全移除,此参数无效') Map<String, List<CodePrompt>> relatedPrompts = const {},
List<CompletionProvider>? customProviders,
}) {
final providers = <CompletionProvider>[
if (customProviders != null)
...customProviders
else if (enableLspCompletion)
const LspCompletionProvider(),
];
engine = CompletionEngine(providers: providers);
}
final CodeLineEditingController? controller;
final String? filePath;
final bool enableLspCompletion;
late final CompletionEngine engine;
/// 当前活跃的悬浮面板 ValueNotifier(由 CodeAutocompleteView 动态注入绑定)
ValueNotifier<CodeAutocompleteEditingValue>? activeNotifier;
@override
FutureOr<CodeAutocompleteEditingValue?> build(
BuildContext context,
CodeLine codeLine,
CodeLineSelection selection,
) {
if (!enableLspCompletion || engine.providers.isEmpty) {
return null;
}
final String text = codeLine.text;
if (selection.extentOffset > text.length) {
return null;
}
final Characters charactersBefore = text.substring(0, selection.extentOffset).characters;
if (charactersBefore.isEmpty) {
return null;
}
// 检查是否在普通闭合双引号或单引号字符串中(简易校验)
final String linePrefix = text.substring(0, selection.extentOffset);
final int singleQuoteCount = "'".allMatches(linePrefix).length;
final int doubleQuoteCount = '"'.allMatches(linePrefix).length;
if (singleQuoteCount % 2 == 1 || doubleQuoteCount % 2 == 1) {
// 位于字符串字面量内部,不触发代码智能补全
return null;
}
final String input;
String? triggerCharacter;
String? target;
if (charactersBefore.takeLast(1).string == '.') {
triggerCharacter = '.';
input = '';
int start = charactersBefore.length - 2;
for (; start >= 0; start--) {
final char = charactersBefore.elementAt(start);
if (!_isValidIdentifierChar(char)) {
break;
}
}
target = charactersBefore.getRange(start + 1, charactersBefore.length - 1).string;
} else {
int start = charactersBefore.length - 1;
for (; start >= 0; start--) {
final char = charactersBefore.elementAt(start);
if (!_isValidIdentifierChar(char)) {
break;
}
}
input = charactersBefore.getRange(start + 1, charactersBefore.length).string;
if (input.isEmpty) {
return null;
}
if (start > 0 && charactersBefore.elementAt(start) == '.') {
triggerCharacter = '.';
final int mark = start;
for (start = start - 1; start >= 0; start--) {
final char = charactersBefore.elementAt(start);
if (!_isValidIdentifierChar(char)) {
break;
}
}
target = charactersBefore.getRange(start + 1, mark).string;
}
}
final completionContext = CompletionContext(
input: input,
triggerCharacter: triggerCharacter,
target: target,
filePath: filePath,
lineIndex: selection.extentIndex,
characterOffset: selection.extentOffset,
codeLine: codeLine,
codeLines: controller?.codeLines,
selection: selection,
);
// 原生异步发起 LSP 智能语义补全请求
return engine.requestCompletionsAsync(completionContext);
}
static bool _isValidIdentifierChar(String char) {
if (char.isEmpty) return false;
final code = char.codeUnitAt(0);
return (code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) || // a-z
(code >= 48 && code <= 57) || // 0-9
code == 95; // _
}
}
-448
View File
@@ -1,448 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../models/distro_manifest.dart';
import 'distro_image_resolver.dart';
/// 系统包下载状态枚举
enum DistroDownloadState {
notStarted,
downloading,
completed,
cancelled,
failed,
}
/// 单个系统的下载状态快照
class DistroDownloadProgress {
final String distroId;
final DistroDownloadState state;
final double progress; // 0.0 ~ 1.0
final int receivedBytes;
final int totalBytes;
final String? errorMessage;
final File? targetFile;
const DistroDownloadProgress({
required this.distroId,
required this.state,
this.progress = 0.0,
this.receivedBytes = 0,
this.totalBytes = -1,
this.errorMessage,
this.targetFile,
});
DistroDownloadProgress copyWith({
DistroDownloadState? state,
double? progress,
int? receivedBytes,
int? totalBytes,
String? errorMessage,
File? targetFile,
}) {
return DistroDownloadProgress(
distroId: distroId,
state: state ?? this.state,
progress: progress ?? this.progress,
receivedBytes: receivedBytes ?? this.receivedBytes,
totalBytes: totalBytes ?? this.totalBytes,
errorMessage: errorMessage ?? this.errorMessage,
targetFile: targetFile ?? this.targetFile,
);
}
}
/// 下载被取消异常
class DistroDownloadCancelledException implements Exception {
final String message;
const DistroDownloadCancelledException([this.message = 'Download cancelled']);
@override
String toString() => message;
}
/// 全局异步系统镜像下载管理器(单例模式)
class DistroDownloadManager extends ChangeNotifier {
static final DistroDownloadManager _instance = DistroDownloadManager._internal();
factory DistroDownloadManager() => _instance;
DistroDownloadManager._internal();
final Map<String, DistroDownloadProgress> _progressMap = {};
final Map<String, HttpClientRequest> _activeRequests = {};
final Map<String, HttpClient> _activeClients = {};
final Map<String, StreamSubscription<List<int>>> _activeSubscriptions = {};
final Map<String, IOSink> _activeSinks = {};
final Map<String, Completer<void>> _activeCompleters = {};
final Set<String> _cancelledDistroIds = {};
@visibleForTesting
Directory? customPackagesDir;
/// 获取系统安装包持久化存储目录: `<app_dir>/distro_packages`
Future<Directory> getPackagesDir() async {
if (customPackagesDir != null) return customPackagesDir!;
final appDir = await getApplicationSupportDirectory();
final dir = Directory(p.join(appDir.path, 'distro_packages'));
if (!dir.existsSync()) {
dir.createSync(recursive: true);
}
return dir;
}
/// 获取指定系统的安装包文件对象
Future<File> getPackageFile(String distroId, [String? downloadUrl]) async {
final dir = await getPackagesDir();
final ext = (downloadUrl?.endsWith('.tar.gz') ?? false) ? '.tar.gz' : '.tar.xz';
final targetFile = File(p.join(dir.path, '${distroId}_rootfs$ext'));
if (targetFile.existsSync()) return targetFile;
final altExt = ext == '.tar.xz' ? '.tar.gz' : '.tar.xz';
final altFile = File(p.join(dir.path, '${distroId}_rootfs$altExt'));
if (altFile.existsSync()) return altFile;
return targetFile;
}
/// 检测指定系统的离线安装包是否已下载完备
Future<bool> isPackageDownloaded(String distroId, [String? downloadUrl]) async {
final dir = await getPackagesDir();
final xzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.xz'));
final gzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.gz'));
return (xzFile.existsSync() && xzFile.lengthSync() > 0) ||
(gzFile.existsSync() && gzFile.lengthSync() > 0);
}
/// 物理删除已下载的系统安装包
Future<void> deletePackage(String distroId, [String? downloadUrl]) async {
if (isDownloading(distroId)) {
await cancelDownload(distroId);
}
final dir = await getPackagesDir();
final files = [
File(p.join(dir.path, '${distroId}_rootfs.tar.xz')),
File(p.join(dir.path, '${distroId}_rootfs.tar.gz')),
];
for (final f in files) {
if (f.existsSync()) {
try {
f.deleteSync();
} catch (_) {}
}
}
_progressMap.remove(distroId);
notifyListeners();
}
/// 获取所有正在跟踪的下载任务快照
Map<String, DistroDownloadProgress> get allProgress => Map.unmodifiable(_progressMap);
/// 查询指定系统的下载状态
DistroDownloadProgress? getProgress(String distroId) => _progressMap[distroId];
/// 是否正在下载
bool isDownloading(String distroId) {
final status = _progressMap[distroId];
return status != null && status.state == DistroDownloadState.downloading;
}
/// 启动异步流式下载
Future<File?> startDownload({
required String distroId,
required String downloadUrl,
DistroMirror? mirror,
DistroManifestItem? manifestItem,
}) async {
if (isDownloading(distroId)) return null;
// 资源检测:若本地已存在完整的离线镜像包,拒绝重复下载并直接返回已有文件
if (await isPackageDownloaded(distroId, downloadUrl)) {
final existingFile = await getPackageFile(distroId, downloadUrl);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
targetFile: existingFile,
);
notifyListeners();
return existingFile;
}
// 清除历史取消标记
_cancelledDistroIds.remove(distroId);
// 状态更新为 downloading
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.downloading,
progress: 0.0,
);
notifyListeners();
String actualDownloadUrl = downloadUrl;
if (manifestItem != null && manifestItem.lxcSpec != null) {
try {
final activeMirror = mirror ?? DistroRepository.defaultMirror;
actualDownloadUrl = await DistroImageResolver().resolveDownloadUrl(
item: manifestItem,
arch: DistroManifestItem.currentArch,
mirror: activeMirror,
);
} catch (e) {
if (_cancelledDistroIds.contains(distroId)) {
_cleanupCancelledState(distroId);
return null;
}
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.failed,
errorMessage: e.toString(),
);
notifyListeners();
return null;
}
}
if (_cancelledDistroIds.contains(distroId)) {
_cleanupCancelledState(distroId);
return null;
}
// 二次资源检测:解析目标 URL 后再次检测文件是否完备
if (await isPackageDownloaded(distroId, actualDownloadUrl)) {
final existingFile = await getPackageFile(distroId, actualDownloadUrl);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
targetFile: existingFile,
);
notifyListeners();
return existingFile;
}
final targetFile = await getPackageFile(distroId, actualDownloadUrl);
final partFilePath = '${targetFile.path}.part';
final partFile = File(partFilePath);
HttpClient? client;
IOSink? sink;
StreamSubscription<List<int>>? subscription;
final completer = Completer<void>();
_activeCompleters[distroId] = completer;
try {
if (partFile.existsSync()) {
try {
partFile.deleteSync();
} catch (_) {}
}
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
client = HttpClient()
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
_activeClients[distroId] = client;
final uri = Uri.parse(actualDownloadUrl);
final request = await client.getUrl(uri);
_activeRequests[distroId] = request;
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
final response = await request.close();
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
if (response.statusCode != HttpStatus.ok) {
throw HttpException('HTTP Error: ${response.statusCode} ${response.reasonPhrase}');
}
final total = response.contentLength;
int received = 0;
sink = partFile.openWrite();
_activeSinks[distroId] = sink;
subscription = response.listen(
(chunk) {
if (_cancelledDistroIds.contains(distroId)) {
subscription?.cancel();
return;
}
sink?.add(chunk);
received += chunk.length;
final prog = total > 0 ? (received / total).clamp(0.0, 1.0) : 0.0;
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.downloading,
progress: prog,
receivedBytes: received,
totalBytes: total,
);
notifyListeners();
},
onDone: () async {
if (_cancelledDistroIds.contains(distroId)) {
if (!completer.isCompleted) {
completer.completeError(const DistroDownloadCancelledException());
}
return;
}
try {
await sink?.flush();
await sink?.close();
sink = null;
} catch (_) {}
if (!completer.isCompleted) {
completer.complete();
}
},
onError: (e) {
if (!completer.isCompleted) {
completer.completeError(e);
}
},
cancelOnError: true,
);
_activeSubscriptions[distroId] = subscription;
await completer.future;
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
// 下载完成,原子重命名 .part -> targetFile
if (targetFile.existsSync()) {
targetFile.deleteSync();
}
partFile.renameSync(targetFile.path);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: received,
totalBytes: total,
targetFile: targetFile,
);
notifyListeners();
return targetFile;
} catch (e) {
final isCancelled = _cancelledDistroIds.contains(distroId) ||
e is DistroDownloadCancelledException;
// 无论如何先关闭写入流,确保文件句柄释放
try {
await sink?.close();
} catch (_) {}
// 清理临时文件
if (partFile.existsSync()) {
try {
partFile.deleteSync();
} catch (_) {}
}
if (isCancelled) {
_cleanupCancelledState(distroId);
} else {
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.failed,
errorMessage: e.toString(),
);
notifyListeners();
}
return null;
} finally {
_activeRequests.remove(distroId);
_activeSubscriptions.remove(distroId);
_activeSinks.remove(distroId);
_activeCompleters.remove(distroId);
final c = _activeClients.remove(distroId);
try {
c?.close(force: true);
} catch (_) {}
_cancelledDistroIds.remove(distroId);
}
}
/// 取消下载并清理已下载的临时缓存资源
Future<void> cancelDownload(String distroId) async {
_cancelledDistroIds.add(distroId);
// 1. 中断活跃 Completer
final completer = _activeCompleters.remove(distroId);
if (completer != null && !completer.isCompleted) {
completer.completeError(const DistroDownloadCancelledException());
}
// 2. 中断 Request 并强力关闭 HttpClient(立即熔断底层 TCP Socket,避免 sub.cancel() 陷入 socket 耗尽等待)
final request = _activeRequests.remove(distroId);
if (request != null) {
try {
request.abort();
} catch (_) {}
}
final client = _activeClients.remove(distroId);
if (client != null) {
try {
client.close(force: true);
} catch (_) {}
}
// 3. 取消活跃 Stream 订阅以停止接收数据包(不阻塞等待 drain)
final sub = _activeSubscriptions.remove(distroId);
if (sub != null) {
try {
unawaited(sub.cancel());
} catch (_) {}
}
// 4. 关闭文件写入流以释放文件句柄(Windows 平台必须关闭方可删除)
final sink = _activeSinks.remove(distroId);
if (sink != null) {
try {
await sink.close();
} catch (_) {}
}
// 5. 立即清除临时 .part 文件
try {
final dir = await getPackagesDir();
final partFiles = [
File(p.join(dir.path, '${distroId}_rootfs.tar.gz.part')),
File(p.join(dir.path, '${distroId}_rootfs.tar.xz.part')),
];
for (final f in partFiles) {
if (f.existsSync()) {
f.deleteSync();
}
}
} catch (_) {}
// 6. 重置状态并通知刷新
_cleanupCancelledState(distroId);
}
void _cleanupCancelledState(String distroId) {
_progressMap.remove(distroId);
notifyListeners();
}
/// 重置已完成或失败的状态
void resetState(String distroId) {
_progressMap.remove(distroId);
notifyListeners();
}
}
-183
View File
@@ -1,183 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import '../models/distro_manifest.dart';
/// LXC 镜像源索引行条目
class DistroIndexEntry {
final String distribution;
final String release;
final String arch;
final String variant;
final String buildDate;
final String path;
const DistroIndexEntry({
required this.distribution,
required this.release,
required this.arch,
required this.variant,
required this.buildDate,
required this.path,
});
factory DistroIndexEntry.fromLine(String line) {
final parts = line.trim().split(';');
if (parts.length < 6) {
throw FormatException('Invalid index line: $line');
}
return DistroIndexEntry(
distribution: parts[0],
release: parts[1],
arch: parts[2],
variant: parts[3],
buildDate: parts[4],
path: parts[5],
);
}
}
/// 发行版镜像真实下载链接解析器(遵循 LinuxContainers 标准 index-system 规范)
class DistroImageResolver {
static final DistroImageResolver _instance = DistroImageResolver._internal();
factory DistroImageResolver() => _instance;
DistroImageResolver._internal();
/// 缓存的解析结果 (key: "mirrorId:distroId:arch", value: url)
final Map<String, String> _resolvedUrlCache = {};
/// 缓存的 index-system 纯文本内容 (key: mirrorId, value: (cachedTime, content))
final Map<String, (DateTime, String)> _indexContentCache = {};
/// 索引缓存有效期 (1 小时)
static const Duration cacheTtl = Duration(hours: 1);
@visibleForTesting
String? customIndexContent;
/// 清空指定系统或所有缓存
void invalidateCache({String? distroId}) {
if (distroId != null) {
_resolvedUrlCache.removeWhere((key, _) => key.contains(':$distroId:'));
} else {
_resolvedUrlCache.clear();
_indexContentCache.clear();
}
}
/// 将系统架构枚举映射为 LXC 索引架构命名(arm64 -> arm64, x86_64 -> amd64)
static String toLxcArch(DistroArch arch) {
switch (arch) {
case DistroArch.arm64:
return 'arm64';
case DistroArch.x86_64:
return 'amd64';
}
}
/// 动态解析指定发行版在指定镜像源上的最新真实下载 URL
Future<String> resolveDownloadUrl({
required DistroManifestItem item,
required DistroArch arch,
required DistroMirror mirror,
bool forceRefresh = false,
}) async {
// 内置系统直接返回静态资源路径
if (item.isBuiltin) {
return item.packages[arch] ?? '';
}
final spec = item.lxcSpec;
if (spec == null) {
return item.packages[arch] ?? '';
}
final cacheKey = '${mirror.id}:${item.id}:${arch.name}';
if (!forceRefresh && _resolvedUrlCache.containsKey(cacheKey)) {
return _resolvedUrlCache[cacheKey]!;
}
// 1. 获取对应镜像源的 meta/1.0/index-system 索引
final indexContent = await _fetchIndexContent(mirror, forceRefresh: forceRefresh);
// 2. 解析为条目列表
final entries = parseIndex(indexContent);
final targetArch = toLxcArch(arch);
// 3. 匹配符合发行版、版本、变体及 CPU 架构的条目
final matching = entries.where((e) =>
e.distribution.toLowerCase() == spec.distribution.toLowerCase() &&
e.release.toLowerCase() == spec.release.toLowerCase() &&
e.arch.toLowerCase() == targetArch.toLowerCase() &&
e.variant.toLowerCase() == spec.variant.toLowerCase(),
).toList();
if (matching.isEmpty) {
throw HttpException(
'Image not found in mirror ${mirror.name}: ${spec.distribution}/${spec.release}/$targetArch',
);
}
// 4. 按 buildDate 降序排序,取最新一次构建
matching.sort((a, b) => b.buildDate.compareTo(a.buildDate));
final latestEntry = matching.first;
// 5. 组合目标真实 URL
final base = mirror.baseUrl.replaceAll(RegExp(r'/+$'), '');
final relPath = latestEntry.path.replaceAll(RegExp(r'^/+'), '');
final fullUrl = '$base/$relPath' 'rootfs.tar.xz';
_resolvedUrlCache[cacheKey] = fullUrl;
return fullUrl;
}
/// 解析 index-system 纯文本内容为条目列表
static List<DistroIndexEntry> parseIndex(String content) {
final lines = content.split('\n');
final List<DistroIndexEntry> list = [];
for (final line in lines) {
final trimmed = line.trim();
if (trimmed.isEmpty || trimmed.startsWith('#')) continue;
try {
list.add(DistroIndexEntry.fromLine(trimmed));
} catch (_) {}
}
return list;
}
/// 从网络拉取镜像源的 meta/1.0/index-system
Future<String> _fetchIndexContent(DistroMirror mirror, {bool forceRefresh = false}) async {
if (customIndexContent != null) {
return customIndexContent!;
}
final now = DateTime.now();
if (!forceRefresh && _indexContentCache.containsKey(mirror.id)) {
final (cachedAt, text) = _indexContentCache[mirror.id]!;
if (now.difference(cachedAt) < cacheTtl) {
return text;
}
}
HttpClient? client;
try {
client = HttpClient()
..connectionTimeout = const Duration(seconds: 15)
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
final indexUrl = '${mirror.baseUrl.replaceAll(RegExp(r'/+$'), '')}/meta/1.0/index-system';
final request = await client.getUrl(Uri.parse(indexUrl));
final response = await request.close().timeout(const Duration(seconds: 20));
if (response.statusCode != HttpStatus.ok) {
throw HttpException('Failed to fetch mirror index from ${mirror.name}: HTTP ${response.statusCode}');
}
final body = await response.transform(utf8.decoder).join();
_indexContentCache[mirror.id] = (now, body);
return body;
} finally {
client?.close();
}
}
}
+93
View File
@@ -687,6 +687,99 @@ class DistroInstaller {
// 8. 自动配置 Java 运行时动态链接路径
await ensureJavaConfiguration(rootfsDir);
// 9. 自动配置 Debian/Ubuntu 容器环境策略(policy-rc.d 屏蔽守护进程启动,解决 dpkg error code 1)
await ensureAptPolicyAndDiversions(rootfsDir);
// 10. 自动配置 Debian/Ubuntu dpkg 优化(force-unsafe-io 解决硬链接解包与 I/O 阻塞异常)
await ensureDpkgConfiguration(rootfsDir);
}
/// 自动配置 Debian / Ubuntu 容器环境 dpkg 优化配置(解决 fsync/I/O 阻塞与权限死锁)
/// 对标 proot-distro:
/// 写入 `/etc/dpkg/dpkg.cfg.d/01_proot`,包含 `force-unsafe-io`
static Future<void> ensureDpkgConfiguration(Directory rootfsDir) async {
try {
final etcDpkgDir = Directory(p.join(rootfsDir.path, 'etc', 'dpkg'));
if (!etcDpkgDir.existsSync()) return;
final dpkgCfgD = Directory(p.join(etcDpkgDir.path, 'dpkg.cfg.d'));
if (!dpkgCfgD.existsSync()) {
dpkgCfgD.createSync(recursive: true);
}
final prootCfg = File(p.join(dpkgCfgD.path, '01_proot'));
const prootCfgContent = 'force-unsafe-io\n';
if (!prootCfg.existsSync() || prootCfg.readAsStringSync() != prootCfgContent) {
prootCfg.writeAsStringSync(prootCfgContent, flush: true);
debugPrint('[DistroInstaller] 成功配置 /etc/dpkg/dpkg.cfg.d/01_proot (force-unsafe-io)');
}
} catch (e) {
debugPrint('[DistroInstaller] 配置 dpkg 优化策略异常 (非阻塞): $e');
}
}
/// 自动适配 Debian/Ubuntu 容器环境的包管理器策略与服务屏蔽
/// 对标 proot-distro:
/// 1. 注入 `/usr/sbin/policy-rc.d` 返回 101,禁止包安装过程启动 systemd/init 服务;
/// 2. 伪装 `start-stop-daemon`,避免 postinst 脚本因守护进程调用失败导致 dpkg 退出码 1;
/// 3. 设置 APT 默认静默与非交互模式,避免缺少 apt-utils 时 debconf 异常。
static Future<void> ensureAptPolicyAndDiversions(Directory rootfsDir) async {
try {
final etcAptDir = Directory(p.join(rootfsDir.path, 'etc', 'apt'));
if (!etcAptDir.existsSync()) return;
// 同步检查并配置 dpkg 选项
await ensureDpkgConfiguration(rootfsDir);
// 1. /usr/sbin/policy-rc.d (exit 101)
final sbinDir = Directory(p.join(rootfsDir.path, 'usr', 'sbin'));
if (!sbinDir.existsSync()) {
sbinDir.createSync(recursive: true);
}
final policyRcD = File(p.join(sbinDir.path, 'policy-rc.d'));
const policyContent = '#!/bin/sh\nexit 101\n';
if (!policyRcD.existsSync() || policyRcD.readAsStringSync() != policyContent) {
policyRcD.writeAsStringSync(policyContent, flush: true);
if (!Platform.isWindows) {
try {
await Process.run('chmod', ['755', policyRcD.path]);
} catch (_) {}
}
debugPrint('[DistroInstaller] 成功注入 /usr/sbin/policy-rc.d');
}
// 2. /usr/sbin/start-stop-daemon (exit 0 伪装,避免无 init 守护进程报错)
final startStopDaemon = File(p.join(sbinDir.path, 'start-stop-daemon'));
const daemonStubContent = '#!/bin/sh\nexit 0\n';
if (!startStopDaemon.existsSync()) {
startStopDaemon.writeAsStringSync(daemonStubContent, flush: true);
if (!Platform.isWindows) {
try {
await Process.run('chmod', ['755', startStopDaemon.path]);
} catch (_) {}
}
debugPrint('[DistroInstaller] 成功伪装 /usr/sbin/start-stop-daemon');
}
// 3. /etc/apt/apt.conf.d/99no-install-recommends 与 debconf 配置
final aptConfD = Directory(p.join(etcAptDir.path, 'apt.conf.d'));
if (!aptConfD.existsSync()) {
aptConfD.createSync(recursive: true);
}
final aptSettings = File(p.join(aptConfD.path, '99proot-container'));
const aptSettingsContent =
'APT::Install-Recommends "false";\n'
'APT::Install-Suggests "false";\n'
'APT::Get::Assume-Yes "true";\n'
'Dpkg::Use-Pty "0";\n';
if (!aptSettings.existsSync() || aptSettings.readAsStringSync() != aptSettingsContent) {
aptSettings.writeAsStringSync(aptSettingsContent, flush: true);
debugPrint('[DistroInstaller] 成功配置 /etc/apt/apt.conf.d/99proot-container');
}
} catch (e) {
debugPrint('[DistroInstaller] 配置 APT policy-rc.d 策略异常 (非阻塞): $e');
}
}
/// 自动部署标准 SSL CA 证书链(让 APT / Curl / Git 默认支持 HTTPS)
+30 -52
View File
@@ -257,53 +257,7 @@ class DistroManager {
);
}
/// 从应用内置资源导入 Alpine Linux 系统实例(保留备用)
///
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
final assetPath = DistroRepository.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置 Alpine 系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 从用户本地指定的 .tar.gz / .tar.xz 压缩包导入外部系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
if (!tarGzFile.existsSync()) {
throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}');
}
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromFile(
archiveFile: tarGzFile,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 高危操作:彻底删除指定系统实例及其所有存储数据
Future<void> deleteSystem(String systemName) async {
@@ -432,11 +386,14 @@ class DistroManager {
// 确保 Java 运行时动态链接配置就绪(解决 /usr/bin/java 符号链接找不到 libjli.so)
await DistroInstaller.ensureJavaConfiguration(rootDir);
// 确保 Debian/Ubuntu 容器环境策略就绪(policy-rc.d 屏蔽守护进程自启,解决 dpkg error code 1)
await DistroInstaller.ensureAptPolicyAndDiversions(rootDir);
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
final shmDir = await _ensureShmDir(systemName, customBaseDir: customRootDir?.parent);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范)
final l2sDir = await _ensureL2sDir(systemName, customBaseDir: customRootDir?.parent);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范,位于 rootfs/.l2s)
final l2sDir = await _ensureL2sDir(systemName, rootDir, customBaseDir: customRootDir?.parent);
// 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据)
final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: customRootDir?.parent);
@@ -555,6 +512,7 @@ class DistroManager {
'TERM=xterm-256color',
'COLORTERM=truecolor',
'LANG=C.UTF-8',
'PROOT_L2S_DIR=/.l2s',
if (guestJavaHome != null) 'JAVA_HOME=$guestJavaHome',
if (guestJavaHome != null)
'PATH=$guestJavaHome/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
@@ -638,14 +596,34 @@ class DistroManager {
}
}
/// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro login/__init__.py)
Future<Directory?> _ensureL2sDir(String systemName, {Directory? customBaseDir}) async {
/// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro l2s.py,位于 rootfs/.l2s)
Future<Directory?> _ensureL2sDir(String systemName, Directory rootDir, {Directory? customBaseDir}) async {
try {
final baseDir = customBaseDir ?? await getBaseDistrosDir();
final l2sDir = Directory(p.join(baseDir.path, systemName, '.l2s'));
final l2sDir = Directory(p.join(rootDir.path, '.l2s'));
if (!l2sDir.existsSync()) {
l2sDir.createSync(recursive: true);
}
// 自动迁移旧版本放置在 rootfs 外部的 .l2s 目录 (<rootDir.parent>/.l2s)
try {
final legacyL2sDir = Directory(p.join(rootDir.parent.path, '.l2s'));
if (legacyL2sDir.existsSync() && legacyL2sDir.path != l2sDir.path) {
final entries = legacyL2sDir.listSync();
for (final entry in entries) {
final targetPath = p.join(l2sDir.path, p.basename(entry.path));
if (!File(targetPath).existsSync() && !Directory(targetPath).existsSync()) {
entry.renameSync(targetPath);
}
}
try {
legacyL2sDir.deleteSync(recursive: true);
} catch (_) {}
debugPrint('[DistroManager] 已平滑迁移旧版本外部 .l2s 目录至 rootfs/.l2s');
}
} catch (e) {
debugPrint('[DistroManager] 迁移旧 .l2s 异常 (非阻塞): $e');
}
return l2sDir;
} catch (e) {
debugPrint('创建容器 .l2s 目录失败 (非阻塞): $e');
+124 -61
View File
@@ -1,9 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../l10n/app_localizations.dart';
import '../models/distro_manifest.dart';
@@ -11,7 +9,7 @@ import '../widgets/distro_extract_dialog.dart';
import 'distro_installer.dart';
import 'distro_manager.dart';
/// 内部私有代码智能引擎服务 (files/internal_engine/alpine)
/// 代码智能与运行时引擎服务(基于统一主系统 Ubuntu 24.04)
class InternalEngineService extends ChangeNotifier {
static final InternalEngineService instance = InternalEngineService._();
InternalEngineService._();
@@ -23,48 +21,36 @@ class InternalEngineService extends ChangeNotifier {
bool _isChecking = false;
bool get isChecking => _isChecking;
/// 获取引擎主目录: `<files>/internal_engine/alpine`
Future<Directory> getEngineDir() async {
/// 获取主系统 Ubuntu rootfs 目录
Future<Directory> getRootfsDir() async {
if (customEngineDir != null) {
return customEngineDir!;
}
final appDir = await getApplicationSupportDirectory();
final rootPath = p.basename(appDir.path) == 'files'
? appDir.path
: p.join(appDir.path, 'files');
final engineDir = Directory(p.join(rootPath, 'internal_engine', 'alpine'));
if (!engineDir.existsSync()) {
engineDir.createSync(recursive: true);
}
return engineDir;
return DistroManager().getSystemRootDir(DistroRepository.defaultSystemName);
}
/// 获取 rootfs 目录: `<files>/internal_engine/alpine/rootfs`
Future<Directory> getRootfsDir() async {
final engineDir = await getEngineDir();
return Directory(p.join(engineDir.path, 'rootfs'));
}
/// 兼容旧方法命名
Future<Directory> getEngineDir() => getRootfsDir();
/// 检查内置 Alpine 引擎是否已完整安装
/// 检查主系统 Ubuntu 是否已完整安装
Future<bool> isEngineInstalled() async {
try {
final engineDir = await getEngineDir();
final marker = File(p.join(engineDir.path, '.installed'));
if (!marker.existsSync()) return false;
if (customEngineDir != null) {
final marker = File(p.join(customEngineDir!.path, '.installed'));
if (marker.existsSync()) return true;
final binDir = Directory(p.join(customEngineDir!.path, 'bin'));
final etcDir = Directory(p.join(customEngineDir!.path, 'etc'));
return binDir.existsSync() && etcDir.existsSync();
}
final rootfs = await getRootfsDir();
if (!rootfs.existsSync()) return false;
final binDir = Directory(p.join(rootfs.path, 'bin'));
final etcDir = Directory(p.join(rootfs.path, 'etc'));
return binDir.existsSync() && etcDir.existsSync();
return await DistroManager().isSystemInstalled(DistroRepository.defaultSystemName);
} catch (e) {
debugPrint('检查内置引擎异常: $e');
debugPrint('检查代码智能运行引擎异常: $e');
return false;
}
}
/// 确保内置引擎已准备完毕;若未安装,弹出模态解压弹窗进行解压
/// 确保内置 Ubuntu 引擎已准备完毕;若未安装,弹出模态解压弹窗进行解压
Future<bool> ensureEngineReady(BuildContext context) async {
if (await isEngineInstalled()) {
return true;
@@ -79,7 +65,7 @@ class InternalEngineService extends ChangeNotifier {
try {
final success = await DistroExtractDialog.show(
context: context,
systemName: l10n?.internalEngineTitle ?? '内部代码智能引擎 (Alpine)',
systemName: l10n?.internalEngineTitle ?? '代码运行与智能补全引擎 (Ubuntu)',
task: (onProgress, isCancelled) async {
await extractEngine(
onProgress: onProgress,
@@ -94,41 +80,31 @@ class InternalEngineService extends ChangeNotifier {
} catch (e) {
_isChecking = false;
notifyListeners();
debugPrint('解压内部引擎失败: $e');
debugPrint('解压 Ubuntu 引擎失败: $e');
return false;
}
}
/// 解压 Asset 中的 Alpine minirootfs 到私有引擎目录
/// 解压 Asset 中的 Ubuntu 到主系统目录
Future<void> extractEngine({
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final assetPath = DistroRepository.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置 Alpine 系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final rootfsDir = await getRootfsDir();
if (!rootfsDir.existsSync()) {
rootfsDir.createSync(recursive: true);
if (customEngineDir != null) {
// 测试模式下解压或标记
final marker = File(p.join(customEngineDir!.path, '.installed'));
await marker.writeAsString('ready');
return;
}
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: rootfsDir,
await DistroManager().importBuiltinUbuntu(
systemName: DistroRepository.defaultSystemName,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 写入安装完成标记文件
final engineDir = await getEngineDir();
final marker = File(p.join(engineDir.path, '.installed'));
await marker.writeAsString('ready');
}
/// 检查某命令(如 clangd, rust-analyzer)是否在内置 Alpine 中已安装
/// 检查某命令(如 clangd, rust-analyzer, pylsp)是否在系统已安装
Future<bool> isCommandInstalled(String command) async {
if (!await isEngineInstalled() || command.trim().isEmpty) {
return false;
@@ -137,39 +113,126 @@ class InternalEngineService extends ChangeNotifier {
try {
final rootfs = await getRootfsDir();
final res = await DistroManager().runHeadlessCommand(
systemName: 'alpine_internal',
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: 'command -v ${command.trim()} >/dev/null 2>&1 && echo CE_OK',
timeout: const Duration(seconds: 15),
);
return res?.stdout.toString().contains('CE_OK') ?? false;
} catch (e) {
debugPrint('检查内置引擎命令异常: $e');
debugPrint('检查引擎命令异常: $e');
return false;
}
}
/// 在内置 Alpine 中安装指定 apk 软件包
/// 在 Ubuntu 系统中安装指定 apt 软件包
Future<bool> installPackage(
String apkPackage, {
String packageName, {
void Function(String chunk)? onOutput,
}) async {
if (!await isEngineInstalled() || apkPackage.trim().isEmpty) {
if (!await isEngineInstalled() || packageName.trim().isEmpty) {
return false;
}
try {
final rootfs = await getRootfsDir();
final installCmd =
'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; '
'dpkg --configure -a 2>/dev/null || true; '
'apt-get update && '
'apt-get install -y --no-install-recommends ${packageName.trim()}';
final res = await DistroManager().runHeadlessCommand(
systemName: 'alpine_internal',
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: 'apk add --no-cache ${apkPackage.trim()}',
timeout: const Duration(minutes: 5),
command: installCmd,
timeout: const Duration(minutes: 10),
onStdout: onOutput,
);
return res != null && res.exitCode == 0;
} catch (e) {
debugPrint('安装内置引擎软件包异常: $e');
debugPrint('安装引擎软件包异常: $e');
return false;
}
}
/// 在 Ubuntu 系统中彻底卸载指定 apt 软件包及清理对应命令
Future<bool> uninstallPackage(
String packageName, {
String? serverCommand,
void Function(String chunk)? onOutput,
}) async {
final cleanPkg = packageName.trim();
if (!await isEngineInstalled() || cleanPkg.isEmpty) {
return false;
}
try {
final rootfs = await getRootfsDir();
final cleanCmd = serverCommand?.trim();
// 1. 若指定了服务命令,先在容器内强杀残留进程,避免文件占用导致卸载失败
final killSection = (cleanCmd != null && cleanCmd.isNotEmpty)
? 'pkill -9 -f "$cleanCmd" 2>/dev/null || true; '
: '';
// 2. 针对特定虚包/版本衍生包进行包名扩展 purge
// 例如 clangd 会衍生出 clangd-15, clang-tools-15 等
final String targetsToPurge;
if (cleanPkg == 'clangd') {
targetsToPurge = 'clangd clangd* clang-tools*';
} else {
targetsToPurge = cleanPkg;
}
// 3. 二次兜底检测:如果命令仍残留,尝试通过 dpkg -S 查询实际宿主包并 purge,或清理残留可执行文件
final cmdCleanupSection = (cleanCmd != null && cleanCmd.isNotEmpty)
? '''
BIN_PATH=\$(command -v "$cleanCmd" 2>/dev/null || true)
if [ -n "\$BIN_PATH" ]; then
OWNER_PKG=\$(dpkg -S "\$BIN_PATH" 2>/dev/null | cut -d: -f1 | head -n 1 || true)
if [ -n "\$OWNER_PKG" ]; then
apt-get remove --purge -y "\$OWNER_PKG" 2>/dev/null || true
fi
rm -f "\$BIN_PATH" 2>/dev/null || true
fi
'''
: '';
final uninstallCmd = '''
export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true
$killSection
dpkg --configure -a 2>/dev/null || true
apt-get remove --purge -y $targetsToPurge
apt-get autoremove --purge -y
$cmdCleanupSection
''';
final res = await DistroManager().runHeadlessCommand(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
command: uninstallCmd,
timeout: const Duration(minutes: 5),
onStdout: onOutput,
);
final success = res != null && res.exitCode == 0;
if (!success) {
return false;
}
// 4. 若提供了 serverCommand,确凿验证该命令在系统中是否已不存在
if (cleanCmd != null && cleanCmd.isNotEmpty) {
final stillExists = await isCommandInstalled(cleanCmd);
if (stillExists) {
debugPrint('[InternalEngineService] 警告: 卸载脚本完成后命令 $cleanCmd 仍残留');
return false;
}
}
return true;
} catch (e) {
debugPrint('卸载引擎软件包异常: $e');
return false;
}
}
+152
View File
@@ -0,0 +1,152 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
/// C/C++ 工程头文件搜索路径与编译数据库辅助器
///
/// 当用户打开 CMake 或普通 C/C++ 工程时,若缺少 compile_commands.json,
/// clangd 默认仅在单文件所在目录与系统库中搜索头文件,导致多目录项目(如 include/、src/、common/)
/// 中相互引用的头文件报错“file not found”。
/// 本类负责在启动 clangd 前:
/// 1. 检查是否存在 compile_commands.json、compile_flags.txt 或 .clangd,若存在则绝不覆盖;
/// 2. 检查 build/、out/ 等子构建目录下是否有 compile_commands.json,若有则自动生成 .clangd 配置指向该目录;
/// 3. 若均不存在,自动扫描项目下包含头文件的常见源码目录,推导并生成轻量合理的 compile_flags.txt。
class CppProjectHelper {
const CppProjectHelper._();
static const Set<String> _ignoredDirNames = {
'.git',
'.vscode',
'.idea',
'.dart_tool',
'build',
'out',
'dist',
'bin',
'obj',
'node_modules',
'cache',
'tmp',
};
static const Set<String> _headerExtensions = {
'.h',
'.hpp',
'.hxx',
'.hh',
'.inl',
};
/// 确保指定工作区根目录下具备 clangd 编译配置
static Future<void> ensureCompileFlags(String workspaceRoot) async {
if (workspaceRoot.isEmpty) return;
final rootDir = Directory(workspaceRoot);
if (!rootDir.existsSync()) return;
// 1. 若项目根目录已有配置,直接返回
final rootCompileCommands = File(p.join(workspaceRoot, 'compile_commands.json'));
final rootCompileFlags = File(p.join(workspaceRoot, 'compile_flags.txt'));
final rootClangd = File(p.join(workspaceRoot, '.clangd'));
if (rootCompileCommands.existsSync() ||
rootCompileFlags.existsSync() ||
rootClangd.existsSync()) {
return;
}
// 2. 检查常见构建输出子目录下是否存在 compile_commands.json
final candidateBuildDirs = ['build', 'out', 'cmake-build-debug', 'cmake-build-release'];
for (final buildDirName in candidateBuildDirs) {
final candidateFile = File(p.join(workspaceRoot, buildDirName, 'compile_commands.json'));
if (candidateFile.existsSync()) {
try {
final content = 'CompileFlags:\n CompilationDatabase: $buildDirName\n';
rootClangd.writeAsStringSync(content, flush: true);
debugPrint('[CppProjectHelper] 检测到 $buildDirName/compile_commands.json,已生成 .clangd 映射');
return;
} catch (e) {
debugPrint('[CppProjectHelper] 写入 .clangd 失败: $e');
}
}
}
// 3. 扫描项目目录,收集包含头文件的目录
final relativeIncludeDirs = <String>{};
_scanHeaderDirs(rootDir, rootDir, relativeIncludeDirs, currentDepth: 0, maxDepth: 3);
if (relativeIncludeDirs.isEmpty) return;
// 排序:常用顶级目录优先展示
final sortedDirs = relativeIncludeDirs.toList()
..sort((a, b) {
int score(String path) {
if (path == 'include') return 0;
if (path == 'src') return 1;
if (path == 'common') return 2;
if (path.endsWith('/include')) return 3;
if (path.endsWith('/src')) return 4;
return 5;
}
final scoreA = score(a);
final scoreB = score(b);
if (scoreA != scoreB) return scoreA.compareTo(scoreB);
return a.compareTo(b);
});
final buffer = StringBuffer();
for (final dir in sortedDirs) {
buffer.writeln('-I$dir');
}
buffer.writeln('-xc++');
buffer.writeln('-std=c++17');
try {
rootCompileFlags.writeAsStringSync(buffer.toString(), flush: true);
debugPrint('[CppProjectHelper] 已为工程自动生成 compile_flags.txt (${sortedDirs.length} 个头文件路径)');
} catch (e) {
debugPrint('[CppProjectHelper] 写入 compile_flags.txt 异常: $e');
}
}
static void _scanHeaderDirs(
Directory root,
Directory current,
Set<String> result, {
required int currentDepth,
required int maxDepth,
}) {
if (currentDepth > maxDepth) return;
try {
final entries = current.listSync(followLinks: false);
bool dirHasHeader = false;
final subDirs = <Directory>[];
for (final entry in entries) {
if (entry is File) {
final ext = p.extension(entry.path).toLowerCase();
if (_headerExtensions.contains(ext)) {
dirHasHeader = true;
}
} else if (entry is Directory) {
final dirName = p.basename(entry.path);
if (!dirName.startsWith('.') && !_ignoredDirNames.contains(dirName.toLowerCase())) {
subDirs.add(entry);
}
}
}
if (dirHasHeader) {
final rel = p.relative(current.path, from: root.path).replaceAll('\\', '/');
if (rel.isNotEmpty && rel != '.') {
result.add(rel);
}
}
for (final sub in subDirs) {
_scanHeaderDirs(root, sub, result, currentDepth: currentDepth + 1, maxDepth: maxDepth);
}
} catch (_) {}
}
}
+255
View File
@@ -0,0 +1,255 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
class LspException implements Exception {
final int code;
final String message;
final dynamic data;
const LspException(this.code, this.message, [this.data]);
@override
String toString() => 'LspException($code): $message';
}
/// 基于标准输入输出(stdio)的原生高性能 JSON-RPC 2.0 LSP 客户端
class LspClient {
final Process _process;
final StreamSubscription<List<int>> _stdoutSub;
final StreamSubscription<List<int>> _stderrSub;
int _nextId = 1;
final Map<int, Completer<dynamic>> _pendingRequests = {};
final Map<String, List<void Function(dynamic params)>> _notificationListeners = {};
final List<int> _buffer = [];
bool _isClosed = false;
bool get isClosed => _isClosed;
/// 串行异步写入链,杜绝并发写入 stdin 导致 StreamSink is bound to a stream 异常
Future<void> _writeQueue = Future.value();
LspClient(this._process)
: _stdoutSub = _process.stdout.listen(null),
_stderrSub = _process.stderr.listen(null) {
_stdoutSub.onData(_handleStdoutData);
_stderrSub.onData(_handleStderrData);
_process.exitCode.then((code) {
debugPrint('[LspClient] 语言服务进程退出: $code');
close();
});
}
/// 注册监听服务端的单向通知(如 textDocument/publishDiagnostics)
void onNotification(String method, void Function(dynamic params) handler) {
_notificationListeners.putIfAbsent(method, () => []).add(handler);
}
/// 发送 JSON-RPC 2.0 请求并等待响应结果
Future<T?> sendRequest<T>(String method, [dynamic params, Duration timeout = const Duration(seconds: 10)]) async {
if (_isClosed) {
throw StateError('LspClient 已关闭,无法发送请求: $method');
}
final id = _nextId++;
final completer = Completer<dynamic>();
_pendingRequests[id] = completer;
final payload = {
'jsonrpc': '2.0',
'id': id,
'method': method,
if (params != null) 'params': params,
};
_sendMessage(payload);
try {
final res = await completer.future.timeout(timeout);
return res as T?;
} on TimeoutException {
_pendingRequests.remove(id);
debugPrint('[LspClient] 请求超时: $method (id: $id)');
return null;
} catch (e) {
_pendingRequests.remove(id);
rethrow;
}
}
/// 发送单向通知(无需回复,如 textDocument/didChange, didOpen)
void sendNotification(String method, [dynamic params]) {
if (_isClosed) return;
final payload = {
'jsonrpc': '2.0',
'method': method,
if (params != null) 'params': params,
};
_sendMessage(payload);
}
void _sendMessage(Map<String, dynamic> payload) {
if (_isClosed) return;
_writeQueue = _writeQueue.then((_) async {
if (_isClosed) return;
try {
final jsonStr = jsonEncode(payload);
final bodyBytes = utf8.encode(jsonStr);
final headerStr = 'Content-Length: ${bodyBytes.length}\r\n\r\n';
final headerBytes = ascii.encode(headerStr);
_process.stdin.add(headerBytes);
_process.stdin.add(bodyBytes);
await _process.stdin.flush();
} catch (e) {
debugPrint('[LspClient] 发送消息异常: $e');
}
}).catchError((e) {
debugPrint('[LspClient] 消息写入队列异常: $e');
});
}
void _handleStdoutData(List<int> chunk) {
_buffer.addAll(chunk);
while (true) {
final headerEnd = _findHeaderEnd(_buffer);
if (headerEnd == -1) break;
final headerBytes = _buffer.sublist(0, headerEnd);
final headerStr = ascii.decode(headerBytes, allowInvalid: true);
final contentLength = _parseContentLength(headerStr);
if (contentLength == null) {
// 异常头部,跳过4字节分隔符
_buffer.removeRange(0, headerEnd + 4);
continue;
}
final totalMsgLength = headerEnd + 4 + contentLength;
if (_buffer.length < totalMsgLength) {
// 数据包尚未完整接收,等待下一个 chunk
break;
}
final bodyBytes = _buffer.sublist(headerEnd + 4, totalMsgLength);
_buffer.removeRange(0, totalMsgLength);
try {
final bodyStr = utf8.decode(bodyBytes, allowMalformed: true);
final dynamic msg = jsonDecode(bodyStr);
if (msg is Map<String, dynamic>) {
_dispatchMessage(msg);
}
} catch (e) {
debugPrint('[LspClient] 解析消息体异常: $e');
}
}
}
void _dispatchMessage(Map<String, dynamic> msg) {
final id = msg['id'];
final method = msg['method'] as String?;
// 1. 响应我们之前发送的 Request (id != null, 无 method)
if (id != null && method == null) {
final intId = id is int ? id : int.tryParse(id.toString());
if (intId != null && _pendingRequests.containsKey(intId)) {
final completer = _pendingRequests.remove(intId)!;
if (msg.containsKey('error')) {
final err = msg['error'];
if (err is Map) {
completer.completeError(LspException(
err['code'] as int? ?? -1,
err['message'] as String? ?? 'Unknown error',
err['data'],
));
} else {
completer.completeError(LspException(-1, err.toString()));
}
} else {
completer.complete(msg['result']);
}
}
return;
}
// 2. 服务端主动推送的单向通知 (id == null, 有 method)
if (method != null && id == null) {
final listeners = _notificationListeners[method];
if (listeners != null) {
for (final listener in listeners) {
try {
listener(msg['params']);
} catch (e) {
debugPrint('[LspClient] 通知监听执行异常 ($method): $e');
}
}
}
return;
}
// 3. 服务端向客户端发送的请求 (id != null, 有 method,如 workspace/configuration)
if (method != null && id != null) {
_handleServerRequest(id, method, msg['params']);
}
}
void _handleServerRequest(dynamic id, String method, dynamic params) {
// 基础应答:返回 null 或空配置,避免服务端挂起
final reply = {
'jsonrpc': '2.0',
'id': id,
'result': null,
};
_sendMessage(reply);
}
void _handleStderrData(List<int> chunk) {
// 记录语言服务器的 stderr 日志(调试信息)
final text = utf8.decode(chunk, allowMalformed: true);
if (kDebugMode) {
debugPrint('[LSP Stderr] $text');
}
}
int _findHeaderEnd(List<int> buf) {
// 匹配 \r\n\r\n (13, 10, 13, 10)
for (int i = 0; i <= buf.length - 4; i++) {
if (buf[i] == 13 && buf[i + 1] == 10 && buf[i + 2] == 13 && buf[i + 3] == 10) {
return i;
}
}
return -1;
}
int? _parseContentLength(String headerStr) {
for (final line in headerStr.split('\r\n')) {
final parts = line.split(':');
if (parts.length >= 2 && parts[0].trim().toLowerCase() == 'content-length') {
return int.tryParse(parts[1].trim());
}
}
return null;
}
void close() {
if (_isClosed) return;
_isClosed = true;
for (final completer in _pendingRequests.values) {
if (!completer.isCompleted) {
completer.completeError(const LspException(-32099, 'LspClient 已关闭'));
}
}
_pendingRequests.clear();
_notificationListeners.clear();
_stdoutSub.cancel();
_stderrSub.cancel();
try {
_process.kill();
} catch (_) {}
}
}
@@ -0,0 +1,87 @@
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'lsp_protocol.dart';
/// 全局代码错误诊断管理器(按文件 URI / 绝对路径存储报错区间与等级)
class LspDiagnosticsStore extends ChangeNotifier {
static final LspDiagnosticsStore instance = LspDiagnosticsStore._();
LspDiagnosticsStore._();
/// filePath -> `List<LspDiagnostic>`
final Map<String, List<LspDiagnostic>> _diagnosticsByFile = {};
/// 更新某个文件的诊断列表
void updateDiagnostics(String uriOrPath, List<LspDiagnostic> diagnostics) {
final normalized = _normalizePath(uriOrPath);
if (diagnostics.isEmpty) {
_diagnosticsByFile.remove(normalized);
} else {
// 按错误起始行号和字符列号升序排序
final sorted = List<LspDiagnostic>.from(diagnostics)
..sort((a, b) {
final lineComp = a.range.start.line.compareTo(b.range.start.line);
if (lineComp != 0) return lineComp;
return a.range.start.character.compareTo(b.range.start.character);
});
_diagnosticsByFile[normalized] = sorted;
}
notifyListeners();
}
/// 获取指定文件的全部诊断
List<LspDiagnostic> getDiagnosticsForFile(String? filePath) {
if (filePath == null || filePath.isEmpty) return const [];
return _diagnosticsByFile[_normalizePath(filePath)] ?? const [];
}
/// 获取指定文件在第 [line] 行(0-indexed)上的所有诊断
List<LspDiagnostic> getDiagnosticsForLine(String? filePath, int line) {
if (filePath == null || filePath.isEmpty) return const [];
final all = _diagnosticsByFile[_normalizePath(filePath)];
if (all == null || all.isEmpty) return const [];
return all.where((d) => d.range.overlapsLine(line)).toList();
}
/// 获取指定文件在第 [line] 行、第 [character] 列上的精确诊断项
LspDiagnostic? getDiagnosticAt(String? filePath, int line, int character) {
final list = getDiagnosticsForLine(filePath, line);
for (final d in list) {
if (d.range.contains(line, character)) {
return d;
}
}
// 若光标在该行但未精确在区间内,返回该行的第一个报错
return list.isNotEmpty ? list.first : null;
}
/// 清空所有诊断
void clear() {
_diagnosticsByFile.clear();
notifyListeners();
}
/// 移除指定文件的诊断
void removeForFile(String? filePath) {
if (filePath == null) return;
if (_diagnosticsByFile.remove(_normalizePath(filePath)) != null) {
notifyListeners();
}
}
String _normalizePath(String input) {
String path = input;
if (path.startsWith('file://')) {
final uri = Uri.tryParse(path);
if (uri != null && uri.hasAbsolutePath) {
path = uri.toFilePath();
} else {
path = path.substring(7);
}
}
path = p.normalize(path).replaceAll('\\', '/');
if (path.length >= 2 && path[1] == ':') {
path = path[0].toLowerCase() + path.substring(1);
}
return path;
}
}
+197
View File
@@ -0,0 +1,197 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import '../../models/distro_manifest.dart';
import '../distro_manager.dart';
import '../internal_engine_service.dart';
import '../lsp_config_service.dart';
import 'cpp_project_helper.dart';
import 'lsp_client.dart';
import 'lsp_session.dart';
/// 全局语言服务(LSP)调度管理中心
class LspManager extends ChangeNotifier {
static final LspManager instance = LspManager._();
LspManager._();
final Map<String, LspSession> _activeSessions = {};
final Map<String, Future<LspSession?>> _startingSessions = {};
/// 获取或拉起匹配当前文件的语言服务会话
Future<LspSession?> getOrCreateSession(String filePath, {String? workspaceRoot}) async {
final ext = p.extension(filePath);
if (ext.isEmpty) return null;
final config = LspConfigService.instance.findByExtension(ext);
if (config == null || !config.enabled) return null;
// 检查是否已有存活会话
final existing = _activeSessions[config.id];
if (existing != null && !existing.client.isClosed) {
return existing;
}
// 防止并发重复拉起同一个服务
if (_startingSessions.containsKey(config.id)) {
return _startingSessions[config.id];
}
final future = _startSession(config, filePath, workspaceRoot);
_startingSessions[config.id] = future;
try {
final session = await future;
if (session != null) {
_activeSessions[config.id] = session;
}
return session;
} finally {
_startingSessions.remove(config.id);
}
}
Future<LspSession?> _startSession(
dynamic config,
String filePath,
String? workspaceRoot,
) async {
try {
// 1. 检查 Ubuntu 引擎和命令是否就绪
final engineInstalled = await InternalEngineService.instance.isEngineInstalled();
if (!engineInstalled) return null;
final cmdInstalled = await InternalEngineService.instance.isCommandInstalled(config.serverCommand);
if (!cmdInstalled) {
debugPrint('[LspManager] 服务命令未安装: ${config.serverCommand}');
return null;
}
final effectiveRoot = workspaceRoot ?? p.dirname(filePath);
// 若为 C/C++ 项目,在启动 clangd 前确保推导并配置头文件与编译标志
if (config.id == 'c_cpp') {
try {
await CppProjectHelper.ensureCompileFlags(effectiveRoot);
} catch (e) {
debugPrint('[LspManager] 确保 C/C++ 编译标志失败: $e');
}
}
final rootfs = await InternalEngineService.instance.getRootfsDir();
final effectiveArgs = List<String>.from(config.serverArgs ?? const []);
if (config.id == 'c_cpp') {
if (!effectiveArgs.any((a) => a.startsWith('--query-driver'))) {
effectiveArgs.add('--query-driver=/usr/bin/*,/usr/local/bin/*');
}
if (!effectiveArgs.any((a) => a.startsWith('--header-insertion'))) {
effectiveArgs.add('--header-insertion=iwyu');
}
}
final cmdWithArgs = [
config.serverCommand,
...effectiveArgs,
].join(' ');
final launchConfig = await DistroManager().buildLaunchConfig(
systemName: DistroRepository.defaultSystemName,
customRootDir: rootfs,
workspacePath: effectiveRoot,
customCommand: cmdWithArgs,
);
debugPrint('[LspManager] 正在拉起语言服务进程: ${launchConfig.toCommandLine()}');
final process = await Process.start(
launchConfig.executable,
launchConfig.arguments,
environment: launchConfig.environment,
workingDirectory: launchConfig.workingDirectory,
);
final client = LspClient(process);
final session = LspSession(
client: client,
config: config,
workspaceRoot: effectiveRoot,
);
final success = await session.initialize();
if (success) {
notifyListeners();
return session;
} else {
await session.close();
return null;
}
} catch (e) {
debugPrint('[LspManager] 拉起语言服务异常: $e');
return null;
}
}
/// 获取当前已存活的会话(不触发异步拉起)
LspSession? getExistingSession(String filePath) {
final ext = p.extension(filePath);
if (ext.isEmpty) return null;
final config = LspConfigService.instance.findByExtension(ext);
if (config == null) return null;
final session = _activeSessions[config.id];
if (session != null && !session.client.isClosed) {
return session;
}
return null;
}
/// 响应文档打开
Future<void> onFileOpened(String filePath, String text, {String? workspaceRoot}) async {
final session = await getOrCreateSession(filePath, workspaceRoot: workspaceRoot);
session?.didOpen(filePath, text);
}
/// 响应文档编辑(带防抖通知)
void onFileChanged(String filePath, String fullText) {
final session = getExistingSession(filePath);
session?.didChange(filePath, fullText);
}
/// 响应文档关闭
void onFileClosed(String filePath) {
final session = getExistingSession(filePath);
session?.didClose(filePath);
}
/// 停用并释放指定语言配置的后台服务会话
Future<void> stopSession(String configId) async {
// 1. 若当前正在异步拉起中,等待启动完成后再关闭
if (_startingSessions.containsKey(configId)) {
try {
final session = await _startingSessions[configId];
await session?.close();
} catch (_) {}
_startingSessions.remove(configId);
}
// 2. 关闭并清理已存活的会话
final session = _activeSessions.remove(configId);
if (session != null) {
try {
await session.close();
} catch (e) {
debugPrint('[LspManager] 关闭语言会话异常 ($configId): $e');
}
notifyListeners();
}
}
/// 关闭并回收所有后台语言服务进程
Future<void> disposeAll() async {
for (final session in _activeSessions.values) {
await session.close();
}
_activeSessions.clear();
_startingSessions.clear();
notifyListeners();
}
}
+258
View File
@@ -0,0 +1,258 @@
/// LSP (Language Server Protocol) 核心协议数据模型
class LspPosition {
final int line;
final int character;
const LspPosition({required this.line, required this.character});
const LspPosition.pos(this.line, this.character);
factory LspPosition.fromJson(Map<String, dynamic> json) {
return LspPosition(
line: json['line'] as int? ?? 0,
character: json['character'] as int? ?? 0,
);
}
Map<String, dynamic> toJson() => {
'line': line,
'character': character,
};
@override
String toString() => '$line:$character';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LspPosition && line == other.line && character == other.character;
@override
int get hashCode => Object.hash(line, character);
}
class LspRange {
final LspPosition start;
final LspPosition end;
const LspRange({required this.start, required this.end});
factory LspRange.fromJson(Map<String, dynamic> json) {
return LspRange(
start: LspPosition.fromJson(json['start'] as Map<String, dynamic>? ?? const {}),
end: LspPosition.fromJson(json['end'] as Map<String, dynamic>? ?? const {}),
);
}
Map<String, dynamic> toJson() => {
'start': start.toJson(),
'end': end.toJson(),
};
/// 检查给定行列号是否处于当前区间内部(闭区间)
bool contains(int l, int c) {
if (l < start.line || l > end.line) return false;
if (l == start.line && c < start.character) return false;
if (l == end.line && c > end.character) return false;
return true;
}
/// 检查区间是否与某一行有交集
bool overlapsLine(int l) {
return l >= start.line && l <= end.line;
}
@override
String toString() => '$start-$end';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LspRange && start == other.start && end == other.end;
@override
int get hashCode => Object.hash(start, end);
}
/// 诊断等级常量定义(对齐 LSP 规范)
abstract class LspDiagnosticSeverity {
static const int error = 1;
static const int warning = 2;
static const int information = 3;
static const int hint = 4;
}
/// 编译器诊断错误与告警
class LspDiagnostic {
final LspRange range;
final int severity; // 1: Error, 2: Warning, 3: Information, 4: Hint
final dynamic code;
final String? source;
final String message;
final dynamic data;
const LspDiagnostic({
required this.range,
this.severity = 1,
this.code,
this.source,
required this.message,
this.data,
});
bool get isError => severity == 1;
bool get isWarning => severity == 2;
factory LspDiagnostic.fromJson(Map<String, dynamic> json) {
return LspDiagnostic(
range: LspRange.fromJson(json['range'] as Map<String, dynamic>? ?? const {}),
severity: json['severity'] as int? ?? 1,
code: json['code'],
source: json['source'] as String?,
message: json['message'] as String? ?? '',
data: json['data'],
);
}
Map<String, dynamic> toJson() => {
'range': range.toJson(),
'severity': severity,
if (code != null) 'code': code,
if (source != null) 'source': source,
'message': message,
if (data != null) 'data': data,
};
}
/// 语义补全项
class LspCompletionItem {
final String label;
final int? kind;
final String? detail;
final String? documentation;
final String? sortText;
final String? filterText;
final String? insertText;
final int? insertTextFormat; // 1: PlainText, 2: Snippet
final dynamic textEdit;
const LspCompletionItem({
required this.label,
this.kind,
this.detail,
this.documentation,
this.sortText,
this.filterText,
this.insertText,
this.insertTextFormat,
this.textEdit,
});
factory LspCompletionItem.fromJson(Map<String, dynamic> json) {
String? doc;
final rawDoc = json['documentation'];
if (rawDoc is String) {
doc = rawDoc;
} else if (rawDoc is Map && rawDoc['value'] is String) {
doc = rawDoc['value'] as String;
}
return LspCompletionItem(
label: json['label'] as String? ?? '',
kind: json['kind'] as int?,
detail: json['detail'] as String?,
documentation: doc,
sortText: json['sortText'] as String?,
filterText: json['filterText'] as String?,
insertText: json['insertText'] as String?,
insertTextFormat: json['insertTextFormat'] as int?,
textEdit: json['textEdit'],
);
}
/// 补全文本内容
String get effectiveInsertText {
if (textEdit is Map && textEdit['newText'] is String) {
return textEdit['newText'] as String;
}
return insertText ?? label;
}
}
/// 快速修复与代码动作
class LspCodeAction {
final String title;
final String? kind;
final List<LspDiagnostic> diagnostics;
final bool isPreferred;
final LspWorkspaceEdit? edit;
const LspCodeAction({
required this.title,
this.kind,
this.diagnostics = const [],
this.isPreferred = false,
this.edit,
});
factory LspCodeAction.fromJson(Map<String, dynamic> json) {
final diagsRaw = json['diagnostics'] as List? ?? const [];
final diags = diagsRaw
.whereType<Map<String, dynamic>>()
.map((d) => LspDiagnostic.fromJson(d))
.toList();
LspWorkspaceEdit? wsEdit;
if (json['edit'] is Map) {
wsEdit = LspWorkspaceEdit.fromJson(json['edit'] as Map<String, dynamic>);
}
return LspCodeAction(
title: json['title'] as String? ?? '',
kind: json['kind'] as String?,
diagnostics: diags,
isPreferred: json['isPreferred'] as bool? ?? false,
edit: wsEdit,
);
}
}
class LspWorkspaceEdit {
final Map<String, List<LspTextEdit>> changes;
const LspWorkspaceEdit({this.changes = const {}});
factory LspWorkspaceEdit.fromJson(Map<String, dynamic> json) {
final rawChanges = json['changes'];
final Map<String, List<LspTextEdit>> result = {};
if (rawChanges is Map) {
rawChanges.forEach((uri, edits) {
if (edits is List) {
result[uri.toString()] = edits
.whereType<Map<String, dynamic>>()
.map((e) => LspTextEdit.fromJson(e))
.toList();
}
});
}
return LspWorkspaceEdit(changes: result);
}
}
class LspTextEdit {
final LspRange range;
final String newText;
const LspTextEdit({required this.range, required this.newText});
factory LspTextEdit.fromJson(Map<String, dynamic> json) {
return LspTextEdit(
range: LspRange.fromJson(json['range'] as Map<String, dynamic>? ?? const {}),
newText: json['newText'] as String? ?? '',
);
}
Map<String, dynamic> toJson() => {
'range': range.toJson(),
'newText': newText,
};
}
+240
View File
@@ -0,0 +1,240 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../models/lsp_language_config.dart';
import 'lsp_client.dart';
import 'lsp_diagnostics_store.dart';
import 'lsp_protocol.dart';
import 'proot_path_mapper.dart';
/// 单个语言服务会话(管理与后台进程的文档增量同步、智能补全与诊断流)
class LspSession {
final LspClient client;
final LspLanguageConfig config;
final String workspaceRoot;
final Map<String, int> _fileVersions = {};
final Map<String, Timer> _debounceTimers = {};
bool _isInitialized = false;
bool get isInitialized => _isInitialized;
LspSession({
required this.client,
required this.config,
required this.workspaceRoot,
}) {
_registerNotificationHandlers();
}
void _registerNotificationHandlers() {
client.onNotification('textDocument/publishDiagnostics', (params) {
if (params is Map<String, dynamic>) {
final uri = params['uri'] as String? ?? '';
final diagsRaw = params['diagnostics'] as List? ?? const [];
final diags = diagsRaw
.whereType<Map<String, dynamic>>()
.map((d) => LspDiagnostic.fromJson(d))
.toList();
final hostPath = _fromGuestUriToHostPath(uri);
LspDiagnosticsStore.instance.updateDiagnostics(hostPath, diags);
if (hostPath != uri) {
LspDiagnosticsStore.instance.updateDiagnostics(uri, diags);
}
}
});
}
/// 发送 initialize 握手报文
Future<bool> initialize() async {
final rootUri = _toGuestUri(workspaceRoot);
final guestRootPath = PRootPathMapper.toGuestPath(workspaceRoot, workspaceRoot);
final initParams = {
'processId': null,
'rootUri': rootUri,
'rootPath': guestRootPath,
'capabilities': {
'textDocument': {
'synchronization': {
'dynamicRegistration': false,
'willSave': false,
'willSaveWaitUntil': false,
'didSave': true,
},
'completion': {
'dynamicRegistration': false,
'completionItem': {
'snippetSupport': true,
'documentationFormat': ['markdown', 'plaintext'],
},
},
'publishDiagnostics': {
'relatedInformation': true,
},
'codeAction': {
'codeActionLiteralSupport': {
'codeActionKind': {
'valueSet': ['quickfix', 'refactor'],
},
},
},
},
},
};
try {
final res = await client.sendRequest('initialize', initParams);
if (res != null) {
client.sendNotification('initialized', {});
_isInitialized = true;
debugPrint('[LspSession] 语言服务初始化成功: ${config.name} (${config.serverCommand})');
return true;
}
} catch (e) {
debugPrint('[LspSession] 初始化失败: $e');
}
return false;
}
/// 文档打开通知
void didOpen(String filePath, String text) {
final uri = _toGuestUri(filePath);
_fileVersions[filePath] = 1;
client.sendNotification('textDocument/didOpen', {
'textDocument': {
'uri': uri,
'languageId': config.languageId,
'version': 1,
'text': text,
},
});
}
/// 文档内容变更通知(带 250ms 智能防抖)
void didChange(String filePath, String fullText) {
if (!_fileVersions.containsKey(filePath)) {
didOpen(filePath, fullText);
return;
}
_debounceTimers[filePath]?.cancel();
_debounceTimers[filePath] = Timer(const Duration(milliseconds: 250), () {
if (client.isClosed) return;
final uri = _toGuestUri(filePath);
final newVersion = (_fileVersions[filePath] ?? 1) + 1;
_fileVersions[filePath] = newVersion;
client.sendNotification('textDocument/didChange', {
'textDocument': {
'uri': uri,
'version': newVersion,
},
'contentChanges': [
{'text': fullText},
],
});
});
}
/// 文档关闭通知
void didClose(String filePath) {
_debounceTimers[filePath]?.cancel();
_debounceTimers.remove(filePath);
_fileVersions.remove(filePath);
final uri = _toGuestUri(filePath);
client.sendNotification('textDocument/didClose', {
'textDocument': {
'uri': uri,
},
});
}
/// 获取光标处语义补全项列表
Future<List<LspCompletionItem>> getCompletions(
String filePath,
int line,
int character,
) async {
final guestUri = _toGuestUri(filePath);
if (!client.isClosed && _isInitialized) {
try {
final res = await client.sendRequest('textDocument/completion', {
'textDocument': {'uri': guestUri},
'position': {'line': line, 'character': character},
});
if (res is List) {
return res
.whereType<Map<String, dynamic>>()
.map((item) => LspCompletionItem.fromJson(item))
.toList();
} else if (res is Map && res['items'] is List) {
final items = res['items'] as List;
return items
.whereType<Map<String, dynamic>>()
.map((item) => LspCompletionItem.fromJson(item))
.toList();
}
} catch (e) {
debugPrint('[LspSession] 获取补全失败: $e');
}
}
return const [];
}
/// 获取指定错误或位置的代码修复操作(QuickFix)
Future<List<LspCodeAction>> getCodeActions(
String filePath,
LspRange range,
List<LspDiagnostic> diagnostics,
) async {
if (!client.isClosed && _isInitialized) {
try {
final res = await client.sendRequest('textDocument/codeAction', {
'textDocument': {'uri': _toGuestUri(filePath)},
'range': range.toJson(),
'context': {
'diagnostics': diagnostics.map((d) => d.toJson()).toList(),
'only': ['quickfix'],
},
});
if (res is List) {
return res
.whereType<Map<String, dynamic>>()
.map((a) => LspCodeAction.fromJson(a))
.toList();
}
} catch (e) {
debugPrint('[LspSession] 获取 CodeAction 失败: $e');
}
}
return const [];
}
/// 转换宿主文件路径为容器内部映射的 URI
String _toGuestUri(String hostFilePath) {
return PRootPathMapper.toGuestUri(hostFilePath, workspaceRoot);
}
/// 将容器内部的 URI 反向还原为宿主文件绝对路径
String _fromGuestUriToHostPath(String guestUri) {
return PRootPathMapper.fromGuestUriToHostPath(guestUri, workspaceRoot);
}
Future<void> close() async {
for (final timer in _debounceTimers.values) {
timer.cancel();
}
_debounceTimers.clear();
_fileVersions.clear();
try {
await client.sendRequest('shutdown', null, const Duration(seconds: 1));
client.sendNotification('exit');
} catch (_) {}
client.close();
}
}
@@ -0,0 +1,84 @@
import 'package:re_editor/re_editor.dart';
import 'lsp_protocol.dart';
/// 负责将 LSP 服务端返回的 WorkspaceEdit / TextEdit 序列安全、有序地应用到当前编辑器控制器中
class LspWorkspaceEditApplier {
/// 将 [edit] 应用至 [controller]
static void applyWorkspaceEdit(
CodeLineEditingController controller,
LspWorkspaceEdit edit, {
required String currentFilePath,
}) {
final normalizedTarget = _normalize(currentFilePath);
List<LspTextEdit>? targetEdits;
for (final entry in edit.changes.entries) {
final normalizedUri = _normalize(entry.key);
if (normalizedTarget.endsWith(normalizedUri) ||
normalizedUri.endsWith(normalizedTarget) ||
normalizedTarget.toLowerCase() == normalizedUri.toLowerCase()) {
targetEdits = entry.value;
break;
}
}
if (targetEdits == null || targetEdits.isEmpty) return;
applyTextEdits(controller, targetEdits);
}
/// 依据 LSP 规范,对逆向排序后的编辑操作逐一应用,防止前序编辑破坏后续行列偏移
static void applyTextEdits(
CodeLineEditingController controller,
List<LspTextEdit> edits,
) {
if (edits.isEmpty) return;
// 逆序排序:先按行号降序,同行按列号降序
final sortedEdits = List<LspTextEdit>.from(edits)
..sort((a, b) {
final lineComp = b.range.start.line.compareTo(a.range.start.line);
if (lineComp != 0) return lineComp;
return b.range.start.character.compareTo(a.range.start.character);
});
final totalLines = controller.lineCount;
for (final te in sortedEdits) {
final startLine = te.range.start.line.clamp(0, totalLines - 1);
final endLine = te.range.end.line.clamp(0, totalLines - 1);
final startLineLen = controller.codeLines[startLine].text.length;
final endLineLen = controller.codeLines[endLine].text.length;
final startCol = te.range.start.character.clamp(0, startLineLen);
final endCol = te.range.end.character.clamp(0, endLineLen);
final selection = CodeLineSelection(
baseIndex: startLine,
baseOffset: startCol,
extentIndex: endLine,
extentOffset: endCol,
);
controller.replaceSelection(te.newText, selection);
}
}
static String _normalize(String input) {
String path = input;
if (path.startsWith('file://')) {
final uri = Uri.tryParse(path);
if (uri != null && uri.hasAbsolutePath) {
path = uri.toFilePath();
} else {
path = path.substring(7);
}
}
path = path.replaceAll('\\', '/');
if (path.length >= 2 && path[1] == ':') {
path = path[0].toLowerCase() + path.substring(1);
}
return path;
}
}
+71
View File
@@ -0,0 +1,71 @@
import 'package:path/path.dart' as p;
/// PRoot 容器路径与宿主文件路径双向映射器
///
/// 在 Android 手机端 PRoot 架构中:
/// - 宿主端文件真实路径例如:`/data/data/com.example/files/workspace/main.c` 或 Windows 开发测试路径
/// - PRoot 启动参数将工作区绑定挂载至容器内部 `/workspace`
/// - 发送给 LSP 服务端(如 clangd)的文档 URI 需映射为 `file:///workspace/...`
/// - 接收 LSP 服务端诊断或引用返回的容器 URI 需反向还原为宿主绝对路径
class PRootPathMapper {
const PRootPathMapper();
/// 转换宿主文件路径为容器内部映射的 URI
static String toGuestUri(String hostFilePath, String workspaceRoot) {
if (workspaceRoot.isEmpty) {
return _toFileUri(hostFilePath);
}
final normHost = p.normalize(hostFilePath).replaceAll('\\', '/');
final normRoot = p.normalize(workspaceRoot).replaceAll('\\', '/');
if (normHost == normRoot) {
return 'file:///workspace';
}
if (normHost.startsWith('$normRoot/')) {
final relative = normHost.substring(normRoot.length + 1);
return 'file:///workspace/$relative';
}
if (normHost.startsWith(normRoot)) {
final relative = normHost.substring(normRoot.length).replaceFirst(RegExp(r'^/'), '');
return 'file:///workspace/$relative';
}
return _toFileUri(hostFilePath);
}
/// 转换宿主文件路径为容器内部真实绝对路径(例如 /workspace/src/main.c)
static String toGuestPath(String hostFilePath, String workspaceRoot) {
final uri = toGuestUri(hostFilePath, workspaceRoot);
if (uri.startsWith('file://')) {
return uri.substring('file://'.length);
}
return uri;
}
/// 将容器内部的 URI 反向还原为宿主文件绝对路径
static String fromGuestUriToHostPath(String guestUri, String workspaceRoot) {
final normUri = guestUri.replaceAll('\\', '/');
if (normUri.startsWith('file:///workspace/')) {
final relative = normUri.substring('file:///workspace/'.length);
return p.join(workspaceRoot, relative).replaceAll('\\', '/');
}
if (normUri == 'file:///workspace') {
return workspaceRoot.replaceAll('\\', '/');
}
if (normUri.startsWith('file:///')) {
// 普通 file:/// 协议,若未挂载至 /workspace 则直接去除 file:// 前缀
return normUri.substring('file://'.length);
}
return guestUri;
}
static String _toFileUri(String path) {
final normalized = p.normalize(path).replaceAll('\\', '/');
if (normalized.startsWith('file://')) return normalized;
if (normalized.startsWith('/')) return 'file://$normalized';
return 'file:///$normalized';
}
}
+42 -28
View File
@@ -20,7 +20,7 @@ class LspConfigService extends ChangeNotifier {
List<LspLanguageConfig> get configs => List.unmodifiable(_configs);
bool get isLoaded => _isLoaded;
/// 获取配置文件路径: `<files>/internal_engine/lsp_languages.json`
/// 获取配置文件路径: `<files>/config/lsp_languages.json`
Future<File> getConfigFile() async {
final Directory baseDir;
if (customBaseDir != null) {
@@ -30,7 +30,28 @@ class LspConfigService extends ChangeNotifier {
final rootPath = p.basename(appDir.path) == 'files'
? appDir.path
: p.join(appDir.path, 'files');
baseDir = Directory(p.join(rootPath, 'internal_engine'));
baseDir = Directory(p.join(rootPath, 'config'));
// 自动迁移旧版本放置在 internal_engine 的配置文件并清理旧目录
try {
final legacyDir = Directory(p.join(rootPath, 'internal_engine'));
final legacyFile = File(p.join(legacyDir.path, 'lsp_languages.json'));
final targetFile = File(p.join(baseDir.path, 'lsp_languages.json'));
if (legacyFile.existsSync() && !targetFile.existsSync()) {
if (!baseDir.existsSync()) {
baseDir.createSync(recursive: true);
}
legacyFile.copySync(targetFile.path);
}
if (legacyDir.existsSync()) {
legacyDir.deleteSync(recursive: true);
debugPrint('[LspConfigService] 已迁移并清理旧 internal_engine 目录');
}
} catch (e) {
debugPrint('[LspConfigService] 清理旧 internal_engine 异常: $e');
}
}
if (!baseDir.existsSync()) {
@@ -39,7 +60,7 @@ class LspConfigService extends ChangeNotifier {
return File(p.join(baseDir.path, 'lsp_languages.json'));
}
/// 加载配置,若缺失预设语言则自动增量追加合并并回写
/// 加载已安装的配置列表。初始为空数组 [],不存在未安装的占位项
Future<List<LspLanguageConfig>> loadConfigs({bool forceReload = false}) async {
if (_isLoaded && !forceReload) {
return _configs;
@@ -50,34 +71,28 @@ class LspConfigService extends ChangeNotifier {
bool needSave = false;
if (!file.existsSync()) {
loaded = List.from(LspLanguageConfig.defaultPresets);
// 初始为空数组,写入持久化文件
loaded = [];
needSave = true;
} else {
try {
final content = file.readAsStringSync();
final dynamic raw = jsonDecode(content);
if (raw is List) {
loaded = raw
.map((e) => e is Map<String, dynamic>
? LspLanguageConfig.fromJson(e)
: null)
.whereType<LspLanguageConfig>()
.toList();
final content = file.readAsStringSync().trim();
if (content.isNotEmpty) {
final dynamic raw = jsonDecode(content);
if (raw is List) {
loaded = raw
.map((e) => e is Map<String, dynamic>
? LspLanguageConfig.fromJson(e)
: null)
.whereType<LspLanguageConfig>()
.toList();
}
}
} catch (e) {
debugPrint('读取 lsp_languages.json 异常: $e,使用默认预设');
loaded = List.from(LspLanguageConfig.defaultPresets);
debugPrint('读取 lsp_languages.json 异常: $e');
loaded = [];
needSave = true;
}
// 动态增量合并:对比官方预设,若预设中某项 id 本地缺失,则追加进去,默认 enabled: true
final existingIds = loaded.map((e) => e.id).toSet();
for (final preset in LspLanguageConfig.defaultPresets) {
if (!existingIds.contains(preset.id)) {
loaded.add(preset.copyWith(enabled: true));
needSave = true;
}
}
}
_configs = loaded;
@@ -118,9 +133,9 @@ class LspConfigService extends ChangeNotifier {
notifyListeners();
}
/// 恢复官方默认预设
/// 清空所有已配置的语言项
Future<void> resetToDefaults() async {
_configs = List.from(LspLanguageConfig.defaultPresets);
_configs = [];
await _writeToDisk();
notifyListeners();
}
@@ -131,11 +146,10 @@ class LspConfigService extends ChangeNotifier {
final normalized = ext.startsWith('.') ? ext.toLowerCase() : '.$ext'.toLowerCase();
for (final config in _configs) {
if (!config.enabled) continue;
for (final item in config.fileExtensions) {
final itemNorm = item.startsWith('.') ? item.toLowerCase() : '.$item'.toLowerCase();
if (itemNorm == normalized) {
return config;
return config.enabled ? config : null;
}
}
}
@@ -0,0 +1,76 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../../models/run_task.dart';
import 'project_module.dart';
import 'project_probe.dart';
/// Maven (Java) 工程模块:识别 pom.xml 或 mvnw 包装脚本
class MavenProjectModule extends ProjectModule {
@override
String get id => 'maven';
@override
String get displayName => 'Maven';
@override
List<String> get triggerFiles => const ['pom.xml', 'mvnw'];
@override
bool shouldActivate(Directory projectDir) {
return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync());
}
@override
List<String> get requiredToolchainKeys => const ['maven'];
@override
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
final root = probe.projectDir;
final hasWrapper = File(p.join(root.path, 'mvnw')).existsSync();
final cmdPrefix = hasWrapper ? './mvnw' : 'mvn';
return ModuleProbeResult.ok(id, [
RunTask(
id: 'detected_maven_package',
name: 'Maven: Package',
command: '$cmdPrefix package',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.inventory_2_outlined,
),
RunTask(
id: 'detected_maven_compile',
name: 'Maven: Compile',
command: '$cmdPrefix compile',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_maven_test',
name: 'Maven: Test',
command: '$cmdPrefix test',
source: TaskSource.detected,
group: 'verification',
moduleId: id,
icon: Icons.fact_check_outlined,
),
RunTask(
id: 'detected_maven_clean',
name: 'Maven: Clean',
command: '$cmdPrefix clean',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.cleaning_services_outlined,
),
]);
}
}
@@ -4,6 +4,9 @@ import 'package:flutter/foundation.dart';
import '../../models/notice_item.dart';
import '../../models/run_task.dart';
import '../background_task/background_task.dart';
import '../background_task/background_task_scheduler.dart';
import '../background_task/generic_background_task.dart';
import '../distro_manager.dart';
import '../toolchain_service.dart';
@@ -297,15 +300,34 @@ class ProjectProbe {
if (commands.isEmpty) return false;
final script = commands.join(' && ');
final result = await runHeadless(
script,
timeout: const Duration(minutes: 10),
onStdout: (chunk) {
final line = chunk.trim();
if (line.isNotEmpty) setInstallLine(line);
// 接入统一调度器:通过 TaskExecutionScope.packageManager 保证独占排他锁,
// 不与用户同时触发的 LSP 组件安装/卸载冲突
final task = GenericBackgroundTask<bool>(
id: 'probe:toolchains:${toolchainKeys.join('+')}',
scope: TaskExecutionScope.packageManager,
priority: TaskPriority.projectLifecycle,
showNotice: false, // 模块探测自身已有专用的 ModulePhaseText 弹窗显示
runner: (taskContext) async {
if (isCancelled || _disposed) return false;
final result = await runHeadless(
script,
timeout: const Duration(minutes: 10),
onStdout: (chunk) {
final line = chunk.trim();
if (line.isNotEmpty) setInstallLine(line);
},
);
return result != null && result.exitCode == 0;
},
);
return result != null && result.exitCode == 0;
try {
return await BackgroundTaskScheduler.instance.submit(task);
} catch (_) {
return false;
}
}
/// 更新安装进度行(带释放保护,避免取消/释放后写入已 dispose 的 notifier)
@@ -0,0 +1,103 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import '../../models/run_task.dart';
import 'project_module.dart';
import 'project_probe.dart';
/// Python 工程模块:识别 requirements.txt、pyproject.toml 等特征
class PythonProjectModule extends ProjectModule {
@override
String get id => 'python';
@override
String get displayName => 'Python';
@override
List<String> get triggerFiles => const [
'requirements.txt',
'pyproject.toml',
'setup.py',
'Pipfile',
];
@override
bool shouldActivate(Directory projectDir) {
return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync());
}
@override
List<String> get requiredToolchainKeys => const ['python3'];
@override
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
final tasks = <RunTask>[];
final root = probe.projectDir;
// 1. 依赖安装任务
if (File(p.join(root.path, 'requirements.txt')).existsSync()) {
tasks.add(
RunTask(
id: 'detected_python_pip_install',
name: 'Pip: Install Requirements',
command: 'pip3 install -r requirements.txt',
source: TaskSource.detected,
group: 'build',
moduleId: id,
icon: Icons.download_outlined,
),
);
}
// 2. 主入口任务
if (File(p.join(root.path, 'main.py')).existsSync()) {
tasks.add(
RunTask(
id: 'detected_python_run_main',
name: 'Python: Run main.py',
command: 'python3 main.py',
source: TaskSource.detected,
group: 'application',
moduleId: id,
icon: Icons.play_circle_outline,
),
);
} else if (File(p.join(root.path, 'app.py')).existsSync()) {
tasks.add(
RunTask(
id: 'detected_python_run_app',
name: 'Python: Run app.py',
command: 'python3 app.py',
source: TaskSource.detected,
group: 'application',
moduleId: id,
icon: Icons.play_circle_outline,
),
);
}
// 3. 测试任务
final hasTestsDir = Directory(p.join(root.path, 'tests')).existsSync() ||
Directory(p.join(root.path, 'test')).existsSync();
final hasPytestIni = File(p.join(root.path, 'pytest.ini')).existsSync();
if (hasTestsDir || hasPytestIni) {
tasks.add(
RunTask(
id: 'detected_python_pytest',
name: 'Pytest: Run Tests',
command: 'pytest',
source: TaskSource.detected,
group: 'verification',
moduleId: id,
icon: Icons.fact_check_outlined,
),
);
}
return ModuleProbeResult.ok(id, tasks);
}
}
@@ -30,6 +30,12 @@ class SingleFileTaskDetector {
'.go',
'.rs',
'.js',
'.java',
'.ts',
'.mts',
'.lua',
'.pl',
'.php',
};
/// 检查给定文件路径是否属于支持的单文件任务类型
@@ -135,6 +141,52 @@ class SingleFileTaskDetector {
group: 'single_file',
icon: Icons.javascript,
);
case '.java':
return RunTask(
id: 'detected_single_java',
name: 'Java: $fileName',
command: 'java $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.code,
);
case '.ts':
case '.mts':
return RunTask(
id: 'detected_single_ts',
name: 'TypeScript: $fileName',
command: 'npx -y tsx $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.javascript,
);
case '.lua':
return RunTask(
id: 'detected_single_lua',
name: 'Lua: $fileName',
command: 'lua $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.code,
);
case '.pl':
return RunTask(
id: 'detected_single_perl',
name: 'Perl: $fileName',
command: 'perl $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.terminal,
);
case '.php':
return RunTask(
id: 'detected_single_php',
name: 'PHP: $fileName',
command: 'php $escapedRelPath',
source: TaskSource.detected,
group: 'single_file',
icon: Icons.code,
);
default:
return null;
}
@@ -4,6 +4,9 @@ library;
export 'cargo_project_module.dart';
export 'cmake_project_module.dart';
export 'dart_project_module.dart';
export 'gradle_project_module.dart';
export 'make_project_module.dart';
export 'maven_project_module.dart';
export 'npm_project_module.dart';
export 'python_project_module.dart';
export 'single_file_task_detector.dart';
@@ -11,9 +11,11 @@ import 'project_modules/cmake_project_module.dart';
import 'project_modules/dart_project_module.dart';
import 'project_modules/gradle_project_module.dart';
import 'project_modules/make_project_module.dart';
import 'project_modules/maven_project_module.dart';
import 'project_modules/npm_project_module.dart';
import 'project_modules/project_module.dart';
import 'project_modules/project_probe.dart';
import 'project_modules/python_project_module.dart';
import 'project_modules/single_file_task_detector.dart';
/// 项目任务总调度(对标 VS Code Task Service / IDE 的 ProjectModel 协调器)
@@ -43,11 +45,13 @@ class ProjectTaskDispatcher {
void _registerDefaultModules() {
_modules.addAll([
GradleProjectModule(),
MavenProjectModule(),
CMakeProjectModule(),
CargoProjectModule(),
NpmProjectModule(),
MakeProjectModule(),
DartProjectModule(),
PythonProjectModule(),
]);
}
+54 -96
View File
@@ -10,161 +10,119 @@ class ToolchainRequirement {
/// 用户可见的工具名称/描述
final String displayName;
/// 针对不同发行版家族的自动安装指令
final Map<DistroFamily, String> installCommands;
/// Ubuntu 下的自动安装指令
final String installCommand;
const ToolchainRequirement({
required this.checkBinary,
required this.displayName,
required this.installCommands,
required this.installCommand,
});
/// 获取指定发行版家族下的安装命令(对于 Ubuntu/Debian 自动前置 dpkg 自愈修复,防止前序中断报错)
String? getInstallCommand(DistroFamily family) {
final cmd = installCommands[family];
if (cmd == null) return null;
if (family == DistroFamily.ubuntu || family == DistroFamily.debian) {
return 'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $cmd';
}
return cmd;
/// 获取安装命令(带自动修复前缀)
String get effectiveInstallCommand =>
'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $installCommand';
/// 兼容接口
String? getInstallCommand([DistroFamily? family]) {
if (family == DistroFamily.unknown) return null;
return effectiveInstallCommand;
}
}
/// 预编译软件源与工具链检测/安装适配服务
/// 预编译软件源与工具链检测/安装适配服务(专为 Ubuntu 24.04 深度优化)
class ToolchainService {
/// 已注册的常用编译器与开发工具链元数据
static const Map<String, ToolchainRequirement> supportedTools = {
'make': ToolchainRequirement(
checkBinary: 'make',
displayName: 'make 编译构建工具',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache make build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y make gcc gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
),
'cmake': ToolchainRequirement(
checkBinary: 'cmake',
displayName: 'cmake 构建套件',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache cmake make build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm cmake base-devel',
DistroFamily.fedora: 'dnf install -y cmake make gcc gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
),
'gcc': ToolchainRequirement(
checkBinary: 'gcc',
displayName: 'GCC C 语言编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache gcc musl-dev build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y gcc gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
),
'g++': ToolchainRequirement(
checkBinary: 'g++',
displayName: 'G++ C++ 编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache g++ musl-dev build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y gcc-c++',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
),
'python3': ToolchainRequirement(
checkBinary: 'python3',
displayName: 'Python 3 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
),
'python': ToolchainRequirement(
checkBinary: 'python3',
displayName: 'Python 3 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
),
'npm': ToolchainRequirement(
checkBinary: 'npm',
displayName: 'Node.js 与 NPM 环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
DistroFamily.fedora: 'dnf install -y nodejs npm',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
),
'node': ToolchainRequirement(
checkBinary: 'node',
displayName: 'Node.js 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
DistroFamily.fedora: 'dnf install -y nodejs npm',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
),
'cargo': ToolchainRequirement(
checkBinary: 'cargo',
displayName: 'Rust 与 Cargo 工具链',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
DistroFamily.fedora: 'dnf install -y cargo rust',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
),
'rustc': ToolchainRequirement(
checkBinary: 'rustc',
displayName: 'Rust 编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
DistroFamily.fedora: 'dnf install -y cargo rust',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
),
'go': ToolchainRequirement(
checkBinary: 'go',
displayName: 'Go 语言环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache go',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
DistroFamily.arch: 'pacman -Sy --noconfirm go',
DistroFamily.fedora: 'dnf install -y golang',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
),
'gradle': ToolchainRequirement(
checkBinary: 'java',
displayName: 'Java / Gradle 运行时',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache openjdk17-jre-headless',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
DistroFamily.arch: 'pacman -Sy --noconfirm jdk-openjdk',
DistroFamily.fedora: 'dnf install -y java-latest-openjdk-devel',
},
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
),
'java': ToolchainRequirement(
checkBinary: 'java',
displayName: 'Java 运行环境 (JDK)',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
),
'maven': ToolchainRequirement(
checkBinary: 'mvn',
displayName: 'Maven 构建工具',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y maven default-jdk-headless',
),
'mvn': ToolchainRequirement(
checkBinary: 'mvn',
displayName: 'Maven 构建工具',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y maven default-jdk-headless',
),
'lua': ToolchainRequirement(
checkBinary: 'lua',
displayName: 'Lua 解释器',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y lua5.4',
),
'perl': ToolchainRequirement(
checkBinary: 'perl',
displayName: 'Perl 解释器',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y perl',
),
'php': ToolchainRequirement(
checkBinary: 'php',
displayName: 'PHP 命令行环境',
installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y php-cli',
),
};