2
This commit is contained in:
1 parent
5ac164b407
commit
f93f6095af
94 files changed
+7877
-4018
No files matched your search
@@ -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 (_) {}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user