From a8b7bdf606a0f99dc19ca8d67026d8c17de4a52a Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Sat, 19 Sep 2026 23:00:50 +0800 Subject: [PATCH] 1 --- lib/l10n/app_en.arb | 48 + lib/l10n/app_localizations.dart | 144 +++ lib/l10n/app_localizations_en.dart | 79 ++ lib/l10n/app_localizations_zh.dart | 78 ++ lib/l10n/app_zh.arb | 48 + lib/utils/git_conflict_parser.dart | 37 + lib/widgets/file_item_widget.dart | 19 +- lib/widgets/git/conflict_view_model.dart | 158 +++ lib/widgets/git/git_conflict_panel.dart | 44 +- .../git/git_conflict_resolve_page.dart | 1026 +++++++++++++++++ lib/widgets/git/git_sync_bar.dart | 11 +- test/conflict_view_model_test.dart | 201 ++++ test/git_conflict_parser_test.dart | 161 +++ 13 files changed, 2038 insertions(+), 16 deletions(-) create mode 100644 lib/widgets/git/conflict_view_model.dart create mode 100644 lib/widgets/git/git_conflict_resolve_page.dart create mode 100644 test/conflict_view_model_test.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7fde36e..86cfa99 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1365,6 +1365,54 @@ }, "gitConflictApplyOurs": "Use this", "gitConflictApplyBoth": "Keep both", + "gitConflictResolveTitle": "Resolve Conflict", + "gitConflictBlockIndex": "Conflict {index} of {total}", + "@gitConflictBlockIndex": { + "placeholders": { + "index": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "gitConflictSectionBaseline": "Baseline (common ancestor)", + "gitConflictSectionOurs": "Current side", + "gitConflictSectionTheirs": "Incoming side", + "gitConflictTakeBoth": "Keep both", + "gitConflictEditManually": "Edit manually", + "gitConflictAllOurs": "Use current side for all", + "gitConflictAllTheirs": "Use incoming side for all", + "gitConflictSaveAndMark": "Save and mark resolved", + "gitConflictAcceptCurrent": "Accept Current Change", + "gitConflictAcceptIncoming": "Accept Incoming Change", + "gitConflictAcceptBoth": "Accept Both Changes", + "gitConflictCompare": "Compare Changes", + "gitConflictPrev": "Previous conflict", + "gitConflictNext": "Next conflict", + "gitConflictSaveAndMarkDone": "Resolved and written back", + "gitConflictNoBlocks": "No conflict markers left in this file", + "gitConflictLoadFailed": "Failed to load conflict contents", + "gitConflictUnresolvedRemain": "{count} block(s) still unresolved", + "@gitConflictUnresolvedRemain": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitConflictMarkWithMarkers": "{count} conflict marker(s) still remain in the file", + "@gitConflictMarkWithMarkers": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitConflictMarkWithMarkersHint": "Marking as resolved would commit them as normal content.", + "gitConflictMarkAnyway": "Mark anyway", + "gitConflictGoResolve": "Resolve first", "gitRemoteBranches": "Remote Branches", "gitLocalBranches": "Local Branches", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 56cd4ac..18dc249 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -4018,6 +4018,150 @@ abstract class AppLocalizations { /// **'两段都要'** String get gitConflictApplyBoth; + /// No description provided for @gitConflictResolveTitle. + /// + /// In zh, this message translates to: + /// **'解决冲突'** + String get gitConflictResolveTitle; + + /// No description provided for @gitConflictBlockIndex. + /// + /// In zh, this message translates to: + /// **'冲突 {index} / {total}'** + String gitConflictBlockIndex(int index, int total); + + /// No description provided for @gitConflictSectionBaseline. + /// + /// In zh, this message translates to: + /// **'基线(共同祖先)'** + String get gitConflictSectionBaseline; + + /// No description provided for @gitConflictSectionOurs. + /// + /// In zh, this message translates to: + /// **'当前侧'** + String get gitConflictSectionOurs; + + /// No description provided for @gitConflictSectionTheirs. + /// + /// In zh, this message translates to: + /// **'传入侧'** + String get gitConflictSectionTheirs; + + /// No description provided for @gitConflictTakeBoth. + /// + /// In zh, this message translates to: + /// **'两段都要'** + String get gitConflictTakeBoth; + + /// No description provided for @gitConflictEditManually. + /// + /// In zh, this message translates to: + /// **'手动编辑'** + String get gitConflictEditManually; + + /// No description provided for @gitConflictAllOurs. + /// + /// In zh, this message translates to: + /// **'全部采用当前侧'** + String get gitConflictAllOurs; + + /// No description provided for @gitConflictAllTheirs. + /// + /// In zh, this message translates to: + /// **'全部采用传入侧'** + String get gitConflictAllTheirs; + + /// No description provided for @gitConflictSaveAndMark. + /// + /// In zh, this message translates to: + /// **'保存并标记为已解决'** + String get gitConflictSaveAndMark; + + /// No description provided for @gitConflictAcceptCurrent. + /// + /// In zh, this message translates to: + /// **'采用当前侧'** + String get gitConflictAcceptCurrent; + + /// No description provided for @gitConflictAcceptIncoming. + /// + /// In zh, this message translates to: + /// **'采用传入侧'** + String get gitConflictAcceptIncoming; + + /// No description provided for @gitConflictAcceptBoth. + /// + /// In zh, this message translates to: + /// **'两段都保留'** + String get gitConflictAcceptBoth; + + /// No description provided for @gitConflictCompare. + /// + /// In zh, this message translates to: + /// **'对比查看'** + String get gitConflictCompare; + + /// No description provided for @gitConflictPrev. + /// + /// In zh, this message translates to: + /// **'上一处冲突'** + String get gitConflictPrev; + + /// No description provided for @gitConflictNext. + /// + /// In zh, this message translates to: + /// **'下一处冲突'** + String get gitConflictNext; + + /// No description provided for @gitConflictSaveAndMarkDone. + /// + /// In zh, this message translates to: + /// **'已解决并写回文件'** + String get gitConflictSaveAndMarkDone; + + /// No description provided for @gitConflictNoBlocks. + /// + /// In zh, this message translates to: + /// **'该文件已无冲突标记'** + String get gitConflictNoBlocks; + + /// No description provided for @gitConflictLoadFailed. + /// + /// In zh, this message translates to: + /// **'读取冲突内容失败'** + String get gitConflictLoadFailed; + + /// No description provided for @gitConflictUnresolvedRemain. + /// + /// In zh, this message translates to: + /// **'还剩 {count} 处未处理'** + String gitConflictUnresolvedRemain(int count); + + /// No description provided for @gitConflictMarkWithMarkers. + /// + /// In zh, this message translates to: + /// **'文件里仍残留 {count} 处冲突标记'** + String gitConflictMarkWithMarkers(int count); + + /// No description provided for @gitConflictMarkWithMarkersHint. + /// + /// In zh, this message translates to: + /// **'标记为已解决会把它们当作正常内容提交进仓库。建议先处理干净。'** + String get gitConflictMarkWithMarkersHint; + + /// No description provided for @gitConflictMarkAnyway. + /// + /// In zh, this message translates to: + /// **'仍然标记'** + String get gitConflictMarkAnyway; + + /// No description provided for @gitConflictGoResolve. + /// + /// In zh, this message translates to: + /// **'去处理'** + String get gitConflictGoResolve; + /// No description provided for @gitRemoteBranches. /// /// In zh, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 41435af..c35e574 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2394,6 +2394,85 @@ class AppLocalizationsEn extends AppLocalizations { @override String get gitConflictApplyBoth => 'Keep both'; + @override + String get gitConflictResolveTitle => 'Resolve Conflict'; + + @override + String gitConflictBlockIndex(int index, int total) { + return 'Conflict $index of $total'; + } + + @override + String get gitConflictSectionBaseline => 'Baseline (common ancestor)'; + + @override + String get gitConflictSectionOurs => 'Current side'; + + @override + String get gitConflictSectionTheirs => 'Incoming side'; + + @override + String get gitConflictTakeBoth => 'Keep both'; + + @override + String get gitConflictEditManually => 'Edit manually'; + + @override + String get gitConflictAllOurs => 'Use current side for all'; + + @override + String get gitConflictAllTheirs => 'Use incoming side for all'; + + @override + String get gitConflictSaveAndMark => 'Save and mark resolved'; + + @override + String get gitConflictAcceptCurrent => 'Accept Current Change'; + + @override + String get gitConflictAcceptIncoming => 'Accept Incoming Change'; + + @override + String get gitConflictAcceptBoth => 'Accept Both Changes'; + + @override + String get gitConflictCompare => 'Compare Changes'; + + @override + String get gitConflictPrev => 'Previous conflict'; + + @override + String get gitConflictNext => 'Next conflict'; + + @override + String get gitConflictSaveAndMarkDone => 'Resolved and written back'; + + @override + String get gitConflictNoBlocks => 'No conflict markers left in this file'; + + @override + String get gitConflictLoadFailed => 'Failed to load conflict contents'; + + @override + String gitConflictUnresolvedRemain(int count) { + return '$count block(s) still unresolved'; + } + + @override + String gitConflictMarkWithMarkers(int count) { + return '$count conflict marker(s) still remain in the file'; + } + + @override + String get gitConflictMarkWithMarkersHint => + 'Marking as resolved would commit them as normal content.'; + + @override + String get gitConflictMarkAnyway => 'Mark anyway'; + + @override + String get gitConflictGoResolve => 'Resolve first'; + @override String get gitRemoteBranches => 'Remote Branches'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index e26f305..c426228 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2321,6 +2321,84 @@ class AppLocalizationsZh extends AppLocalizations { @override String get gitConflictApplyBoth => '两段都要'; + @override + String get gitConflictResolveTitle => '解决冲突'; + + @override + String gitConflictBlockIndex(int index, int total) { + return '冲突 $index / $total'; + } + + @override + String get gitConflictSectionBaseline => '基线(共同祖先)'; + + @override + String get gitConflictSectionOurs => '当前侧'; + + @override + String get gitConflictSectionTheirs => '传入侧'; + + @override + String get gitConflictTakeBoth => '两段都要'; + + @override + String get gitConflictEditManually => '手动编辑'; + + @override + String get gitConflictAllOurs => '全部采用当前侧'; + + @override + String get gitConflictAllTheirs => '全部采用传入侧'; + + @override + String get gitConflictSaveAndMark => '保存并标记为已解决'; + + @override + String get gitConflictAcceptCurrent => '采用当前侧'; + + @override + String get gitConflictAcceptIncoming => '采用传入侧'; + + @override + String get gitConflictAcceptBoth => '两段都保留'; + + @override + String get gitConflictCompare => '对比查看'; + + @override + String get gitConflictPrev => '上一处冲突'; + + @override + String get gitConflictNext => '下一处冲突'; + + @override + String get gitConflictSaveAndMarkDone => '已解决并写回文件'; + + @override + String get gitConflictNoBlocks => '该文件已无冲突标记'; + + @override + String get gitConflictLoadFailed => '读取冲突内容失败'; + + @override + String gitConflictUnresolvedRemain(int count) { + return '还剩 $count 处未处理'; + } + + @override + String gitConflictMarkWithMarkers(int count) { + return '文件里仍残留 $count 处冲突标记'; + } + + @override + String get gitConflictMarkWithMarkersHint => '标记为已解决会把它们当作正常内容提交进仓库。建议先处理干净。'; + + @override + String get gitConflictMarkAnyway => '仍然标记'; + + @override + String get gitConflictGoResolve => '去处理'; + @override String get gitRemoteBranches => '远端分支'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 909182c..0d5ed55 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1365,6 +1365,54 @@ }, "gitConflictApplyOurs": "采用此段", "gitConflictApplyBoth": "两段都要", + "gitConflictResolveTitle": "解决冲突", + "gitConflictBlockIndex": "冲突 {index} / {total}", + "@gitConflictBlockIndex": { + "placeholders": { + "index": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "gitConflictSectionBaseline": "基线(共同祖先)", + "gitConflictSectionOurs": "当前侧", + "gitConflictSectionTheirs": "传入侧", + "gitConflictTakeBoth": "两段都要", + "gitConflictEditManually": "手动编辑", + "gitConflictAllOurs": "全部采用当前侧", + "gitConflictAllTheirs": "全部采用传入侧", + "gitConflictSaveAndMark": "保存并标记为已解决", + "gitConflictAcceptCurrent": "采用当前侧", + "gitConflictAcceptIncoming": "采用传入侧", + "gitConflictAcceptBoth": "两段都保留", + "gitConflictCompare": "对比查看", + "gitConflictPrev": "上一处冲突", + "gitConflictNext": "下一处冲突", + "gitConflictSaveAndMarkDone": "已解决并写回文件", + "gitConflictNoBlocks": "该文件已无冲突标记", + "gitConflictLoadFailed": "读取冲突内容失败", + "gitConflictUnresolvedRemain": "还剩 {count} 处未处理", + "@gitConflictUnresolvedRemain": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitConflictMarkWithMarkers": "文件里仍残留 {count} 处冲突标记", + "@gitConflictMarkWithMarkers": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitConflictMarkWithMarkersHint": "标记为已解决会把它们当作正常内容提交进仓库。建议先处理干净。", + "gitConflictMarkAnyway": "仍然标记", + "gitConflictGoResolve": "去处理", "gitRemoteBranches": "远端分支", "gitLocalBranches": "本地分支", diff --git a/lib/utils/git_conflict_parser.dart b/lib/utils/git_conflict_parser.dart index 434ceeb..f356248 100644 --- a/lib/utils/git_conflict_parser.dart +++ b/lib/utils/git_conflict_parser.dart @@ -206,4 +206,41 @@ class GitConflictParser { static String _labelOf(String line, String marker) { return line.length > marker.length ? line.substring(marker.length).trim() : ''; } + + /// 把第 [blockIndex] 个冲突块替换为 [replacement],返回新内容 + /// + /// 这是"逐块解决"的核心算法,独立成纯函数以便测试: + /// - 只替换**该块的行范围**,前后内容原样保留(多块文件各块互不影响) + /// - 传入旧的 [blocks] 与 [content] 必须来自同一次解析,否则行号会错位 + /// - [replacement] 为空表示"该块删掉" + /// + /// 调用方应在替换后**重新解析**再处理下一块:块的行号会随替换而整体移动, + /// 维护偏移量容易出错,重解析代价可以忽略。 + static String? replaceBlock({ + required String content, + required List blocks, + required int blockIndex, + required String replacement, + }) { + if (blockIndex < 0 || blockIndex >= blocks.length) return null; + + final lines = content.split('\n'); + final block = blocks[blockIndex]; + if (block.startLine < 0 || block.endLine >= lines.length) return null; + + final before = lines.sublist(0, block.startLine); + final after = lines.sublist(block.endLine + 1); + + final replacementLines = + replacement.isEmpty ? [] : replacement.split('\n').toList(); + // split 在内容以换行结尾时会多出一个空串,去掉以免多插空行 + if (replacementLines.isNotEmpty && replacementLines.last.isEmpty) { + replacementLines.removeLast(); + } + + return [...before, ...replacementLines, ...after].join('\n'); + } + + /// 统计内容中未解决的冲突块数量(不做完整解析,用于快速校验) + static int countMarkers(String content) => parse(content).blocks.length; } diff --git a/lib/widgets/file_item_widget.dart b/lib/widgets/file_item_widget.dart index c26f028..f3fda75 100644 --- a/lib/widgets/file_item_widget.dart +++ b/lib/widgets/file_item_widget.dart @@ -197,10 +197,21 @@ class _FileItemWidgetState extends State { ), selected: isSelected, selectedTileColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.5), - leading: Icon( - _getFileIcon(item), - size: 20, - color: iconColor, + // 与文件夹项前导区对齐:文件夹有「折叠箭头 + 间距 + 图标」, + // 文件只有图标。若直接给图标,同一层级下文件图标会比文件夹图标 + // 左移一个箭头的宽度(16+4),视觉上文件缩进反而更浅。 + // 这里补一个等宽占位(区别于 VS Code:文件项不显示箭头), + // 使同一层级的图标与文件名严格对齐。 + leading: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(width: 16 + 4), + Icon( + _getFileIcon(item), + size: 20, + color: iconColor, + ), + ], ), title: Text( item.name, diff --git a/lib/widgets/git/conflict_view_model.dart b/lib/widgets/git/conflict_view_model.dart new file mode 100644 index 0000000..04fb3b1 --- /dev/null +++ b/lib/widgets/git/conflict_view_model.dart @@ -0,0 +1,158 @@ +/// 冲突页的行模型与内容组装(纯逻辑,便于单测) +/// +/// 与 `git_conflict_parser.dart` 的分工: +/// - 解析器负责"标记块在文件中的位置" +/// - 这里负责"把解析结果摊平成一条条带语义的行",供 UI 直接渲染 +/// +/// 独立成文件的原因:VS Code 风格的内联冲突视图**完全由行渲染**组成 +/// (标记行变标题带、内容行带整段底色),把"哪些行属于哪一段"算清楚 +/// 是正确性的核心,而它必须可测 —— 上一版页面的内容错乱正是栽在 +/// 行号映射上。 +library; + +import '../../utils/git_conflict_parser.dart'; + +/// 一行在冲突视图中的角色 +enum ConflictLineRole { + /// 普通上下文行(不属于任何冲突块) + context, + + /// 冲突块开头标记行(渲染为标题带 + 内联操作) + oursHeader, + + /// 当前侧内容行 + oursContent, + + /// 基线段标题(diff3 风格;不显示操作) + baseHeader, + + /// 基线段内容行 + baseContent, + + /// 分隔线(`=======`),渲染为极窄分隔 + separator, + + /// 传入侧标题带 + theirsHeader, + + /// 传入侧内容行 + theirsContent, +} + +/// 一行渲染数据 +class ConflictLine { + /// 文件中的绝对行号(1-based,供行号栏显示) + final int lineNumber; + + /// 该行的原始文本 + final String text; + + final ConflictLineRole role; + + /// 若该行是一处分段的标题,这里给出它所属的冲突块序号(0-based) + final int? blockIndex; + + const ConflictLine({ + required this.lineNumber, + required this.text, + required this.role, + this.blockIndex, + }); + + bool get isHeader => + role == ConflictLineRole.oursHeader || + role == ConflictLineRole.baseHeader || + role == ConflictLineRole.theirsHeader; + + bool get isContent => + role == ConflictLineRole.oursContent || + role == ConflictLineRole.baseContent || + role == ConflictLineRole.theirsContent; +} + +/// 把冲突文件内容摊平成可渲染的行序列 +class ConflictLineBuilder { + ConflictLineBuilder._(); + + /// 解析 [content] 并生成行序列 + /// + /// [parseResult] 必须与 [content] 来自同一次解析,否则行号会错位。 + static List build( + String content, + GitConflictParseResult parseResult, + ) { + final lines = content.split('\n'); + final result = []; + + // 行号 → 该行承担的段角色 + final roles = List.filled(lines.length, null); + final blockOfLine = List.filled(lines.length, null); + + for (var b = 0; b < parseResult.blocks.length; b++) { + final block = parseResult.blocks[b]; + + void mark(int from, int toExclusive, ConflictLineRole role) { + for (var i = from; i < toExclusive; i++) { + if (i >= 0 && i < roles.length) { + roles[i] = role; + blockOfLine[i] = b; + } + } + } + + // 起始标记行 + mark(block.startLine, block.startLine + 1, ConflictLineRole.oursHeader); + // 当前侧内容 + mark( + block.ours.startLine, + block.ours.endLine, + ConflictLineRole.oursContent, + ); + + if (block.base != null) { + // diff3:基线段(其上一行是 ||||||| 标记) + mark( + block.base!.startLine - 1, + block.base!.startLine, + ConflictLineRole.baseHeader, + ); + mark( + block.base!.startLine, + block.base!.endLine, + ConflictLineRole.baseContent, + ); + } + + // 分隔线位于基线段结束处(有基线时)或 ours 结束处 + final separatorLine = block.base != null + ? block.base!.endLine + : block.ours.endLine; + mark(separatorLine, separatorLine + 1, ConflictLineRole.separator); + + // 传入侧内容 + mark( + block.theirs.startLine, + block.theirs.endLine, + ConflictLineRole.theirsContent, + ); + // 结束标记行 + mark(block.endLine, block.endLine + 1, ConflictLineRole.theirsHeader); + } + + for (var i = 0; i < lines.length; i++) { + result.add( + ConflictLine( + lineNumber: i + 1, + text: lines[i], + role: roles[i] ?? ConflictLineRole.context, + blockIndex: blockOfLine[i], + ), + ); + } + return result; + } + + /// 统计各块是否已解决(视图中没有标记块时即为完全解决) + static bool isFullyResolved(GitConflictParseResult parseResult) => + parseResult.blocks.isEmpty; +} diff --git a/lib/widgets/git/git_conflict_panel.dart b/lib/widgets/git/git_conflict_panel.dart index 6f9f96b..b64a4c3 100644 --- a/lib/widgets/git/git_conflict_panel.dart +++ b/lib/widgets/git/git_conflict_panel.dart @@ -7,6 +7,7 @@ import '../../providers/git_provider.dart'; import '../../providers/tab_provider.dart'; import '../../utils/dialog_utils.dart'; import '../../utils/git_error_mapper.dart'; +import 'git_conflict_resolve_page.dart'; /// 冲突解决面板(底部弹出) /// @@ -380,11 +381,19 @@ class _ConflictFileTile extends StatelessWidget { tooltip: l10n.gitConflictTitle, onSelected: (action) => _handle(context, l10n, provider, action), itemBuilder: (_) => [ - if (file.canEditManually) + if (file.canEditManually) ...[ + PopupMenuItem( + value: 'resolve', + child: _menuRow( + Icons.merge_type, + l10n.gitConflictResolveTitle, + ), + ), PopupMenuItem( value: 'open', child: _menuRow(Icons.open_in_new_rounded, l10n.gitConflictOpenFile), ), + ], PopupMenuItem( value: 'ours', child: _menuRow( @@ -415,8 +424,9 @@ class _ConflictFileTile extends StatelessWidget { ), ], ), + // 点击文件条目直接进入三方解决页(这是主要路径) onTap: file.canEditManually - ? () => _handle(context, l10n, provider, 'open') + ? () => _openResolvePage(context, provider) : null, ); } @@ -458,6 +468,9 @@ class _ConflictFileTile extends StatelessWidget { String action, ) async { switch (action) { + case 'resolve': + await _openResolvePage(context, provider); + break; case 'open': await _openInEditor(context, provider); break; @@ -500,6 +513,21 @@ class _ConflictFileTile extends StatelessWidget { } } + /// 打开三方冲突解决页(逐块选择,由程序替换而非人工删标记) + Future _openResolvePage(BuildContext context, GitProvider provider) async { + await provider.refreshConflictState(); + if (!context.mounted) return; + + // 先收起面板与抽屉,再压入解决页 —— 否则返回时层级会错乱 + Navigator.of(context).maybePop(); + + await Navigator.of(context).push( + GitConflictResolvePage.route(file: file, gitProvider: provider), + ); + // 返回后刷新:用户可能已在解决页里标记完成 + await provider.refreshConflictState(); + } + /// 在编辑器中打开冲突文件 /// /// **必须先强制从磁盘重载**:Git 冲突时直接改写了工作区文件并写入标记, @@ -509,11 +537,13 @@ class _ConflictFileTile extends StatelessWidget { await provider.refreshConflictState(); await tabProvider.reloadTabFromDisk(file.absolutePath); await tabProvider.openFile(file.absolutePath); - if (context.mounted) { - // 关闭面板并退出抽屉,把焦点交给编辑器 - Navigator.of(context).maybePop(); - Navigator.of(context).maybePop(); - } + if (!context.mounted) return; + + // 先收起 bottom sheet 面板,再显式关闭抽屉。 + // 这里不能用连续两次 maybePop():抽屉是 Scaffold 管理的路由, + // 用 closeDrawer() 才是项目内一致且可靠的做法(见 file_item_widget)。 + Navigator.of(context).maybePop(); + Scaffold.maybeOf(context)?.closeDrawer(); } Future _takeSide( diff --git a/lib/widgets/git/git_conflict_resolve_page.dart b/lib/widgets/git/git_conflict_resolve_page.dart new file mode 100644 index 0000000..1d3f5f3 --- /dev/null +++ b/lib/widgets/git/git_conflict_resolve_page.dart @@ -0,0 +1,1026 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/app_font.dart'; +import '../../models/editor_theme.dart'; +import '../../models/git_model.dart'; +import '../../providers/git_provider.dart'; +import '../../providers/settings_provider.dart'; +import '../../providers/tab_provider.dart'; +import '../../services/file_service.dart'; +import '../../utils/dialog_utils.dart'; +import '../../utils/git_conflict_parser.dart'; +import '../../utils/syntax_highlight_helper.dart'; +import 'conflict_view_model.dart'; + +/// 冲突解决页(VS Code 内联冲突风格) +/// +/// 视觉与交互参照 VS Code 的内联冲突视图: +/// - 冲突标记行渲染成**整行色带标题**:`<<<<<<< HEAD (Current Change)` 绿、 +/// `>>>>>>> theirs (Incoming Change)` 蓝、`|||||||` 基线段灰 +/// - 每段内容带**整段底色**(当前侧绿、传入侧蓝) +/// - 标记行上叠加一行**内联操作**:Accept Current / Accept Incoming / +/// Accept Both / Compare +/// - 底部常驻「保存并标记为已解决」 +/// +/// 实现说明:这是**独立页面**,刻意不复用 `git_diff_page.dart` 的代码。 +/// 只读行渲染器 + 固定行号栏 + 全向滚动 + 双指缩放均按该类页面的既有做法 +/// 自行实现,保证缩放手感、行号对齐、横向滚动行为与本 App 其余部分一致。 +/// +/// **不使用 `CodeEditor`**:它来自 `re_editor`,只支持行级着色, +/// 无法表达"标记行变标题带 + 内容行整段底色"这种行级装饰。 +class GitConflictResolvePage extends StatefulWidget { + const GitConflictResolvePage({ + super.key, + required this.file, + required this.gitProvider, + }); + + final GitConflictedFile file; + final GitProvider gitProvider; + + static Route route({ + required GitConflictedFile file, + required GitProvider gitProvider, + }) { + return MaterialPageRoute( + builder: (_) => + GitConflictResolvePage(file: file, gitProvider: gitProvider), + ); + } + + @override + State createState() => _GitConflictResolvePageState(); +} + +class _GitConflictResolvePageState extends State { + bool _isLoading = true; + String? _errorMessage; + + /// 当前文件内容(\n 规范化,与解析行号一致) + String _content = ''; + GitConflictParseResult _parsed = GitConflictParseResult.none; + List _lines = const []; + + // 滚动分工照抄差异页:垂直 / 水平 / 行号各自独立控制器 + late final ScrollController _vController; + late final ScrollController _hController; + late final ScrollController _gutterController; + bool _syncing = false; + + double? _committedFontSize; + double? _activeZoomFontSize; + + final Map _pointers = {}; + int? _pointer1; + int? _pointer2; + double? _initialDistance; + double? _initialFontSize; + bool _isPinching = false; + Offset? _lastPanPos; + bool _showZoomBadge = false; + + final Map _highlightCache = {}; + + @override + void initState() { + super.initState(); + _vController = ScrollController(); + _hController = ScrollController(); + _gutterController = ScrollController(); + _vController.addListener(_onVerticalScrolled); + _load(); + } + + @override + void dispose() { + _vController.removeListener(_onVerticalScrolled); + _vController.dispose(); + _hController.dispose(); + _gutterController.dispose(); + super.dispose(); + } + + void _onVerticalScrolled() { + if (_syncing || !_gutterController.hasClients) return; + _syncing = true; + _gutterController.jumpTo( + _vController.offset.clamp( + _gutterController.position.minScrollExtent, + _gutterController.position.maxScrollExtent, + ), + ); + _syncing = false; + } + + double get _baseFontSize { + try { + return context.read().fontSize; + } catch (_) { + return 13.0; + } + } + + double get _effectiveFontSize => + _activeZoomFontSize ?? _committedFontSize ?? _baseFontSize; + + double get _rowHeight => (_effectiveFontSize * 1.45 + 4.0).roundToDouble(); + + EditorTheme get _editorTheme { + try { + return context.read().editorTheme; + } catch (_) { + return EditorTheme.atomOneDark; + } + } + + AppFontItem get _editorFont { + try { + return context.read().editorFont; + } catch (_) { + return AppFonts.editorJetBrainsMono; + } + } + + // ---------------------------- 数据 ---------------------------- + + Future _load() async { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + + try { + // 必须读磁盘:冲突时 Git 已把标记写进文件,内存标签页内容可能已过期 + final raw = await FileService.instance.readFileContent( + widget.file.absolutePath, + ); + final normalized = raw.replaceAll('\r\n', '\n'); + final parsed = GitConflictParser.parse(normalized); + + if (!mounted) return; + setState(() { + _content = normalized; + _parsed = parsed; + _lines = ConflictLineBuilder.build(normalized, parsed); + _isLoading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _errorMessage = e.toString(); + _isLoading = false; + }); + } + } + + /// 取某块某一段的文本(按该段在**本文件中的绝对行号**切分) + String _segmentText(int blockIndex, ConflictLineRole side) { + final lines = _content.split('\n'); + final block = _parsed.blocks[blockIndex]; + final seg = switch (side) { + ConflictLineRole.oursContent => block.ours, + ConflictLineRole.baseContent => block.base, + ConflictLineRole.theirsContent => block.theirs, + _ => null, + }; + if (seg == null) return ''; + final start = seg.startLine.clamp(0, lines.length); + final end = seg.endLine.clamp(start, lines.length); + return lines.sublist(start, end).join('\n'); + } + + /// 用 [replacement] 替换某块并立即写回磁盘 + Future _applyBlock(int blockIndex, String replacement) async { + final newContent = GitConflictParser.replaceBlock( + content: _content, + blocks: _parsed.blocks, + blockIndex: blockIndex, + replacement: replacement, + ); + if (newContent == null) return; + + try { + await FileService.instance.saveFile(widget.file.absolutePath, newContent); + } catch (e) { + if (!mounted) return; + DialogUtils.showToast(context, e.toString(), type: ToastType.error); + return; + } + if (!mounted) return; + + // 替换后行号整体移动:重新解析比维护偏移量可靠得多 + final parsed = GitConflictParser.parse(newContent); + setState(() { + _content = newContent; + _parsed = parsed; + _lines = ConflictLineBuilder.build(newContent, parsed); + }); + } + + Future _acceptCurrent(int blockIndex) async { + await _applyBlock( + blockIndex, + _segmentText(blockIndex, ConflictLineRole.oursContent), + ); + } + + Future _acceptIncoming(int blockIndex) async { + await _applyBlock( + blockIndex, + _segmentText(blockIndex, ConflictLineRole.theirsContent), + ); + } + + Future _acceptBoth(int blockIndex) async { + final current = _segmentText(blockIndex, ConflictLineRole.oursContent); + final incoming = _segmentText(blockIndex, ConflictLineRole.theirsContent); + final combined = [current, incoming].where((s) => s.isNotEmpty).join('\n'); + await _applyBlock(blockIndex, combined); + } + + Future _scrollToBlock(int blockIndex) async { + if (blockIndex < 0 || blockIndex >= _parsed.blocks.length) return; + if (!_vController.hasClients) return; + final target = (_parsed.blocks[blockIndex].startLine * _rowHeight - 60) + .clamp(0.0, _vController.position.maxScrollExtent); + await _vController.animateTo( + target, + duration: const Duration(milliseconds: 220), + curve: Curves.easeOut, + ); + } + + int _nearestBlock(int direction) { + if (!_vController.hasClients || _parsed.blocks.isEmpty) return 0; + final currentLine = (_vController.offset / _rowHeight).floor(); + if (direction > 0) { + for (var i = 0; i < _parsed.blocks.length; i++) { + if (_parsed.blocks[i].startLine > currentLine) return i; + } + return _parsed.blocks.length - 1; + } + for (var i = _parsed.blocks.length - 1; i >= 0; i--) { + if (_parsed.blocks[i].startLine < currentLine) return i; + } + return 0; + } + + /// Compare / 手动编辑:交给完整编辑器(带语法高亮、折叠、LSP) + Future _openInEditor() async { + final tabProvider = context.read(); + await tabProvider.reloadTabFromDisk(widget.file.absolutePath); + await tabProvider.openFile(widget.file.absolutePath); + if (!mounted) return; + Navigator.of(context).pop(); + } + + Future _saveAndMark() async { + final l10n = AppLocalizations.of(context)!; + + // 防线:仍有标记时不允许静默标记 —— 那会把标记当作正常内容提交 + final remaining = _parsed.blocks.length; + if (remaining > 0) { + final stillMark = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + icon: Icon( + Icons.warning_amber_rounded, + color: Theme.of(dialogCtx).colorScheme.error, + ), + title: Text(l10n.gitConflictMarkWithMarkers(remaining)), + content: Text(l10n.gitConflictMarkWithMarkersHint), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.gitConflictGoResolve), + ), + FilledButton( + key: const ValueKey('git_conflict_mark_anyway'), + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.gitConflictMarkAnyway), + ), + ], + ), + ); + if (stillMark != true || !mounted) return; + } + + try { + await FileService.instance.saveFile(widget.file.absolutePath, _content); + } catch (e) { + if (!mounted) return; + DialogUtils.showToast(context, e.toString(), type: ToastType.error); + return; + } + + final res = await widget.gitProvider.markConflictResolved(widget.file); + if (!mounted) return; + + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitConflictSaveAndMarkDone, + type: ToastType.success, + ); + Navigator.of(context).pop(); + } else { + DialogUtils.showToast( + context, + res.stderr.isNotEmpty ? res.stderr : l10n.gitConflictLoadFailed, + type: ToastType.error, + ); + } + } + + // ---------------------------- 渲染 ---------------------------- + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final editorTheme = _editorTheme; + final remaining = _parsed.blocks.length; + + return Scaffold( + backgroundColor: editorTheme.backgroundColor, + appBar: AppBar( + backgroundColor: editorTheme.backgroundColor, + foregroundColor: editorTheme.textColor, + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + p.basename(widget.file.relativePath), + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: editorTheme.textColor, + ), + ), + Text( + widget.file.relativePath, + style: TextStyle( + fontSize: 10.5, + color: editorTheme.gutterTextColor, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + actions: [ + if (!_isLoading && remaining > 0) ...[ + IconButton( + tooltip: l10n.gitConflictPrev, + icon: const Icon(Icons.keyboard_arrow_up, size: 20), + onPressed: () => _scrollToBlock(_nearestBlock(-1)), + ), + IconButton( + tooltip: l10n.gitConflictNext, + icon: const Icon(Icons.keyboard_arrow_down, size: 20), + onPressed: () => _scrollToBlock(_nearestBlock(1)), + ), + Padding( + padding: const EdgeInsets.only(right: 10), + child: Center( + child: Text( + l10n.gitConflictUnresolvedRemain(remaining), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: theme.colorScheme.error, + ), + ), + ), + ), + ], + ], + ), + body: _buildBody(theme, l10n, editorTheme), + ); + } + + Widget _buildBody( + ThemeData theme, + AppLocalizations l10n, + EditorTheme editorTheme, + ) { + if (_isLoading) { + return Center( + child: CircularProgressIndicator(color: theme.colorScheme.primary), + ); + } + if (_errorMessage != null) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.error_outline, + color: theme.colorScheme.error, + size: 32, + ), + const SizedBox(height: 10), + Text( + l10n.gitConflictLoadFailed, + style: TextStyle( + fontWeight: FontWeight.bold, + color: editorTheme.textColor, + ), + ), + const SizedBox(height: 6), + SelectableText( + _errorMessage!, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 11, + color: editorTheme.gutterTextColor, + ), + ), + const SizedBox(height: 14), + OutlinedButton( + onPressed: _load, + child: Text(l10n.gitRepairCheckRerun), + ), + ], + ), + ), + ); + } + + return Column( + children: [ + Expanded(child: _buildEditorArea(theme, l10n, editorTheme)), + _buildBottomBar(l10n, editorTheme), + ], + ); + } + + /// 只读行渲染区:行号栏固定 + 代码区全向滚动 + 双指缩放 + Widget _buildEditorArea( + ThemeData theme, + AppLocalizations l10n, + EditorTheme editorTheme, + ) { + final fontSize = _effectiveFontSize; + final rowHeight = _rowHeight; + final charW = fontSize * 0.62; + final gutterBg = + editorTheme.gutterBackgroundColor ?? editorTheme.backgroundColor; + final dividerColor = editorTheme.gutterTextColor.withValues(alpha: 0.25); + + return Stack( + children: [ + Positioned.fill( + child: LayoutBuilder( + builder: (context, constraints) { + final viewportWidth = constraints.maxWidth; + final digits = '${_lines.length}'.length; + final signW = (charW + 4.0).clamp(14.0, 36.0); + final gutterWidth = math.max(46.0, digits * charW + signW + 14.0); + final hasCodeArea = viewportWidth > gutterWidth + 1; + final actualGutter = hasCodeArea + ? gutterWidth + : math.max(0.0, viewportWidth - 1.0); + + int maxChars = 0; + for (final l in _lines) { + if (l.text.length > maxChars) maxChars = l.text.length; + } + final codeAvailable = math.max( + 10.0, + viewportWidth - gutterWidth - 1, + ); + final maxCodeWidth = math.max( + codeAvailable, + maxChars * charW + 240.0, + ); + + return Listener( + behavior: HitTestBehavior.opaque, + onPointerDown: (e) => _handlePointerDown(e, fontSize), + onPointerMove: _handlePointerMove, + onPointerUp: _handlePointerUp, + onPointerCancel: _handlePointerCancel, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (actualGutter > 0) + SizedBox( + width: actualGutter, + child: ClipRect( + child: OverflowBox( + alignment: Alignment.centerRight, + minWidth: 0, + maxWidth: gutterWidth, + child: SizedBox( + width: gutterWidth, + child: Container( + color: gutterBg, + child: ListView.builder( + controller: _gutterController, + physics: const NeverScrollableScrollPhysics(), + itemCount: _lines.length, + itemExtent: rowHeight, + padding: const EdgeInsets.only(bottom: 240), + itemBuilder: (ctx, i) => _buildGutterRow( + _lines[i], + rowHeight, + fontSize, + editorTheme, + ), + ), + ), + ), + ), + ), + ), + if (viewportWidth >= 1) + Container(width: 1.0, color: dividerColor), + if (hasCodeArea) + Expanded( + child: SingleChildScrollView( + controller: _hController, + scrollDirection: Axis.horizontal, + physics: const NeverScrollableScrollPhysics(), + child: SizedBox( + width: maxCodeWidth, + child: ListView.builder( + controller: _vController, + physics: const NeverScrollableScrollPhysics(), + itemCount: _lines.length, + itemExtent: rowHeight, + padding: const EdgeInsets.only(bottom: 240), + itemBuilder: (ctx, i) => _buildCodeRow( + _lines[i], + rowHeight, + fontSize, + editorTheme, + l10n, + ), + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), + if (_showZoomBadge) _buildZoomBadge(editorTheme, fontSize), + ], + ); + } + + /// 行号栏单行:行号 + 冲突段符号(当前侧 `+` 绿、传入侧 `~` 蓝) + Widget _buildGutterRow( + ConflictLine line, + double rowHeight, + double fontSize, + EditorTheme editorTheme, + ) { + final sign = switch (line.role) { + ConflictLineRole.oursContent => '+', + ConflictLineRole.theirsContent => '~', + _ => '', + }; + final signColor = switch (line.role) { + ConflictLineRole.oursContent => const Color(0xFF3FB950), + ConflictLineRole.theirsContent => const Color(0xFF58A6FF), + _ => editorTheme.gutterTextColor, + }; + final charW = fontSize * 0.62; + final signW = (charW + 4.0).clamp(14.0, 36.0); + + return Container( + height: rowHeight, + color: _rowBackground(line.role, editorTheme.isDark), + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Row( + children: [ + Expanded( + child: Text( + '${line.lineNumber}', + textAlign: TextAlign.right, + style: TextStyle( + fontSize: (fontSize - 1).clamp( + SettingsProvider.minFontSize - 1.0, + SettingsProvider.maxFontSize + 8.0, + ), + fontFamily: 'JetBrains Mono', + height: 1.4, + color: sign.isEmpty ? editorTheme.gutterTextColor : signColor, + ), + ), + ), + const SizedBox(width: 4), + SizedBox( + width: signW, + child: Center( + child: Text( + sign, + style: TextStyle( + fontSize: (fontSize - 1).clamp( + SettingsProvider.minFontSize - 1.0, + SettingsProvider.maxFontSize + 8.0, + ), + fontWeight: FontWeight.bold, + fontFamily: 'JetBrains Mono', + height: 1.4, + color: signColor, + ), + ), + ), + ), + ], + ), + ); + } + + /// 代码区单行:按角色渲染 + Widget _buildCodeRow( + ConflictLine line, + double rowHeight, + double fontSize, + EditorTheme editorTheme, + AppLocalizations l10n, + ) { + if (line.isHeader) { + return _buildHeaderBand(line, rowHeight, fontSize, editorTheme, l10n); + } + if (line.role == ConflictLineRole.separator) { + return Container( + height: rowHeight, + alignment: Alignment.centerLeft, + padding: const EdgeInsets.only(left: 6, right: 160), + child: Container( + height: 3, + color: editorTheme.gutterTextColor.withValues(alpha: 0.55), + ), + ); + } + + final baseStyle = TextStyle( + fontSize: fontSize, + fontFamily: _editorFont.fontFamily, + fontFamilyFallback: _editorFont.fallback, + height: 1.4, + color: editorTheme.textColor, + ); + + return Container( + height: rowHeight, + color: _rowBackground(line.role, editorTheme.isDark), + alignment: Alignment.centerLeft, + padding: const EdgeInsets.only(left: 6.0, right: 160.0), + child: Text.rich( + _highlight(line.text, baseStyle, editorTheme, fontSize), + overflow: TextOverflow.visible, + softWrap: false, + ), + ); + } + + /// 冲突标记行 → 色带标题(含内联操作) + Widget _buildHeaderBand( + ConflictLine line, + double rowHeight, + double fontSize, + EditorTheme editorTheme, + AppLocalizations l10n, + ) { + final isCurrent = line.role == ConflictLineRole.oursHeader; + final isIncoming = line.role == ConflictLineRole.theirsHeader; + + final bandColor = isCurrent + ? const Color(0xFF3FB950) + : (isIncoming ? const Color(0xFF58A6FF) : const Color(0xFF8B949E)); + + // 保留 git 原始标记文本,并补上"哪一侧"的说明 + final suffix = isCurrent + ? ' (${l10n.gitConflictSectionOurs})' + : (isIncoming ? ' (${l10n.gitConflictSectionTheirs})' : ''); + final blockIndex = line.blockIndex ?? 0; + + return Container( + constraints: BoxConstraints(minHeight: rowHeight), + color: bandColor.withValues(alpha: editorTheme.isDark ? 0.30 : 0.22), + padding: const EdgeInsets.only(left: 6, right: 8, top: 2, bottom: 2), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${line.text}$suffix', + style: TextStyle( + fontSize: fontSize - 0.5, + fontFamily: _editorFont.fontFamily, + fontFamilyFallback: _editorFont.fallback, + height: 1.4, + fontWeight: FontWeight.w600, + color: bandColor, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + // 基线段仅作参考,不提供操作 + if (isCurrent || isIncoming) + _buildInlineActions(blockIndex, fontSize, editorTheme, l10n), + ], + ), + ); + } + + /// 内联操作行(VS Code 命名固定,不随所在侧变化) + Widget _buildInlineActions( + int blockIndex, + double fontSize, + EditorTheme editorTheme, + AppLocalizations l10n, + ) { + const actionColor = Color(0xFF58A6FF); + final s = (fontSize - 1.5).clamp(9.0, 16.0); + + Widget action(String label, VoidCallback onTap, String keySuffix) { + return InkWell( + key: ValueKey('git_conflict_${keySuffix}_$blockIndex'), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), + child: Text( + label, + style: TextStyle( + fontSize: s, + color: actionColor, + fontFamily: _editorFont.fontFamily, + decoration: TextDecoration.underline, + decorationColor: actionColor.withValues(alpha: 0.5), + ), + ), + ), + ); + } + + Widget sep() => Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: Text( + '|', + style: TextStyle( + fontSize: s, + color: editorTheme.gutterTextColor.withValues(alpha: 0.7), + ), + ), + ); + + return Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + action( + l10n.gitConflictAcceptCurrent, + () => _acceptCurrent(blockIndex), + 'accept_current', + ), + sep(), + action( + l10n.gitConflictAcceptIncoming, + () => _acceptIncoming(blockIndex), + 'accept_incoming', + ), + sep(), + action( + l10n.gitConflictAcceptBoth, + () => _acceptBoth(blockIndex), + 'accept_both', + ), + sep(), + action(l10n.gitConflictCompare, _openInEditor, 'compare'), + ], + ); + } + + TextSpan _highlight( + String code, + TextStyle baseStyle, + EditorTheme editorTheme, + double fontSize, + ) { + if (code.isEmpty) return TextSpan(text: '', style: baseStyle); + final key = '$fontSize-${editorTheme.id}-$code'; + final cached = _highlightCache[key]; + if (cached != null) return cached; + final span = SyntaxHighlightHelper.highlightLine( + code: code, + filePath: widget.file.relativePath, + baseStyle: baseStyle, + highlightTheme: editorTheme.highlightTheme, + ); + _highlightCache[key] = span; + return span; + } + + /// 整段底色:当前侧绿、传入侧蓝、基线灰(与 VS Code 一致) + Color? _rowBackground(ConflictLineRole role, bool isDark) { + return switch (role) { + ConflictLineRole.oursContent => const Color( + 0xFF3FB950, + ).withValues(alpha: isDark ? 0.18 : 0.13), + ConflictLineRole.theirsContent => const Color( + 0xFF58A6FF, + ).withValues(alpha: isDark ? 0.18 : 0.13), + ConflictLineRole.baseContent => const Color( + 0xFF8B949E, + ).withValues(alpha: isDark ? 0.10 : 0.08), + _ => null, + }; + } + + Widget _buildZoomBadge(EditorTheme editorTheme, double fontSize) { + return Positioned( + left: 0, + right: 0, + bottom: 12, + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: editorTheme.backgroundColor.withValues(alpha: 0.94), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: editorTheme.gutterTextColor.withValues(alpha: 0.35), + ), + ), + child: Text( + '${fontSize.toStringAsFixed(1)}pt', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: editorTheme.textColor, + ), + ), + ), + ), + ); + } + + Widget _buildBottomBar(AppLocalizations l10n, EditorTheme editorTheme) { + return Container( + padding: const EdgeInsets.fromLTRB(10, 8, 10, 8), + decoration: BoxDecoration( + color: editorTheme.gutterBackgroundColor ?? editorTheme.backgroundColor, + border: Border( + top: BorderSide( + color: editorTheme.gutterTextColor.withValues(alpha: 0.3), + ), + ), + ), + child: SafeArea( + top: false, + child: Row( + children: [ + Expanded( + child: OutlinedButton.icon( + key: const ValueKey('git_conflict_edit_manually'), + onPressed: _openInEditor, + icon: const Icon(Icons.edit_outlined, size: 15), + label: Text( + l10n.gitConflictEditManually, + style: const TextStyle(fontSize: 12), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + flex: 2, + child: FilledButton.icon( + key: const ValueKey('git_conflict_save_and_mark'), + onPressed: _saveAndMark, + icon: const Icon(Icons.check, size: 16), + label: Text( + l10n.gitConflictSaveAndMark, + style: const TextStyle(fontSize: 12), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ], + ), + ), + ); + } + + // ---------------------------- 手势(Listener 原生指针跟踪) ---------------------------- + + void _handlePointerDown(PointerDownEvent event, double fontSize) { + _pointers[event.pointer] = event.position; + if (_pointers.length >= 2 && !_isPinching) { + final keys = _pointers.keys.toList(); + _pointer1 = keys[0]; + _pointer2 = keys[1]; + final p1 = _pointers[_pointer1]!; + final p2 = _pointers[_pointer2]!; + _initialDistance = (p1 - p2).distance; + _initialFontSize = fontSize; + _isPinching = true; + _lastPanPos = null; + setState(() => _showZoomBadge = true); + } else if (_pointers.length == 1) { + _lastPanPos = event.position; + } + } + + void _handlePointerMove(PointerMoveEvent event) { + if (!_pointers.containsKey(event.pointer)) return; + _pointers[event.pointer] = event.position; + + if (_isPinching && _pointer1 != null && _pointer2 != null) { + final p1 = _pointers[_pointer1]; + final p2 = _pointers[_pointer2]; + if (p1 == null || p2 == null || _initialDistance == null) return; + if (_initialDistance! <= 0) return; + + final ratio = (p1 - p2).distance / _initialDistance!; + final base = _initialFontSize ?? _baseFontSize; + final target = (base * ratio).clamp( + SettingsProvider.minFontSize.toDouble(), + SettingsProvider.maxFontSize.toDouble(), + ); + + final oldRowHeight = _rowHeight; + setState(() => _activeZoomFontSize = target); + final newRowHeight = _rowHeight; + + // 以双指中心为锚点,避免缩放时内容跳动 + if (_vController.hasClients && oldRowHeight > 0) { + final focalDy = ((p1 + p2) / 2).dy; + final lineUnderFocal = (focalDy + _vController.offset) / oldRowHeight; + final desired = lineUnderFocal * newRowHeight - focalDy; + _vController.jumpTo( + desired.clamp( + _vController.position.minScrollExtent, + _vController.position.maxScrollExtent, + ), + ); + } + return; + } + + // 单指平移:垂直 + 水平 + if (_lastPanPos != null && !_isPinching) { + final delta = event.position - _lastPanPos!; + _lastPanPos = event.position; + if (_vController.hasClients) { + _vController.jumpTo( + (_vController.offset - delta.dy).clamp( + _vController.position.minScrollExtent, + _vController.position.maxScrollExtent, + ), + ); + } + if (_hController.hasClients) { + _hController.jumpTo( + (_hController.offset - delta.dx).clamp( + _hController.position.minScrollExtent, + _hController.position.maxScrollExtent, + ), + ); + } + } + } + + void _handlePointerUp(PointerUpEvent event) { + _pointers.remove(event.pointer); + if (_pointers.length < 2 && _isPinching) _finishPinch(); + if (_pointers.isEmpty) _lastPanPos = null; + } + + void _handlePointerCancel(PointerCancelEvent event) { + _pointers.remove(event.pointer); + if (_pointers.length < 2 && _isPinching) _finishPinch(); + if (_pointers.isEmpty) _lastPanPos = null; + } + + void _finishPinch() { + _isPinching = false; + _pointer1 = null; + _pointer2 = null; + _initialDistance = null; + final zoomed = _activeZoomFontSize; + setState(() { + if (zoomed != null) _committedFontSize = zoomed; + _activeZoomFontSize = null; + _showZoomBadge = false; + }); + } +} diff --git a/lib/widgets/git/git_sync_bar.dart b/lib/widgets/git/git_sync_bar.dart index 28c88c3..b47009d 100644 --- a/lib/widgets/git/git_sync_bar.dart +++ b/lib/widgets/git/git_sync_bar.dart @@ -98,11 +98,6 @@ class _GitSyncBarState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ - // 冲突优先于一切:此时同步动作都无法继续,必须先把冲突摆到最前面 - if (gitProvider.hasPendingOperation) ...[ - _buildConflictBanner(context, theme, l10n, gitProvider), - const SizedBox(height: 6), - ], // 与上方「分支」行完全一致的结构:左侧占满的选择条 + 右侧 32×32 图标按钮。 // 这样三行(分支 / 远程 / 进度)视觉对齐,宽度也天然不会溢出。 Row( @@ -120,6 +115,12 @@ class _GitSyncBarState extends State { _buildSyncButton(context, theme, l10n, gitProvider), ], ), + // 冲突横幅放在远程行**下方**:它是一段需要处理的状态说明, + // 放在远程行之上会把「分支 → 远程」这两行的对应关系打断。 + if (gitProvider.hasPendingOperation) ...[ + const SizedBox(height: 6), + _buildConflictBanner(context, theme, l10n, gitProvider), + ], // 推送目标与上游不一致时的提示:单独占一行。 // 绝不能塞进上面的选择条 —— 那是第三个抢宽度的元素,会把远程名挤到溢出。 if (differs) ...[ diff --git a/test/conflict_view_model_test.dart b/test/conflict_view_model_test.dart new file mode 100644 index 0000000..2e4f74a --- /dev/null +++ b/test/conflict_view_model_test.dart @@ -0,0 +1,201 @@ +import 'package:code_editor/utils/git_conflict_parser.dart'; +import 'package:code_editor/widgets/git/conflict_view_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('冲突行模型(VS Code 内联视图的数据来源)', () { + const standard = 'line1\n' + '<<<<<<< HEAD\n' + 'ours-a\n' + 'ours-b\n' + '=======\n' + 'theirs-a\n' + '>>>>>>> feature\n' + 'line2'; + + test('标准风格:标记行变标题带、内容行归属正确', () { + final parsed = GitConflictParser.parse(standard); + final lines = ConflictLineBuilder.build(standard, parsed); + + expect(lines.length, equals(8)); + // 行号必须是文件绝对行号(1-based)——上一版页面正是栽在这里 + expect(lines[0].lineNumber, equals(1)); + expect(lines[0].role, equals(ConflictLineRole.context)); + expect(lines[0].text, equals('line1')); + + expect(lines[1].lineNumber, equals(2)); + expect(lines[1].role, equals(ConflictLineRole.oursHeader)); + expect(lines[1].isHeader, isTrue); + expect(lines[1].blockIndex, equals(0)); + + expect(lines[2].role, equals(ConflictLineRole.oursContent)); + expect(lines[3].role, equals(ConflictLineRole.oursContent)); + + expect(lines[4].role, equals(ConflictLineRole.separator)); + + expect(lines[5].role, equals(ConflictLineRole.theirsContent)); + + expect(lines[6].role, equals(ConflictLineRole.theirsHeader)); + expect(lines[6].blockIndex, equals(0)); + + expect(lines[7].role, equals(ConflictLineRole.context)); + expect(lines[7].text, equals('line2')); + }); + + test('标题带行保留 git 原始标记文本', () { + final parsed = GitConflictParser.parse(standard); + final lines = ConflictLineBuilder.build(standard, parsed); + + expect(lines[1].text, equals('<<<<<<< HEAD')); + expect(lines[6].text, equals('>>>>>>> feature')); + }); + + test('diff3 风格:基线段被单独标注,且不参与操作', () { + const diff3 = 'head\n' + '<<<<<<< HEAD\n' + 'ours\n' + '||||||| merged common ancestors\n' + 'base\n' + '=======\n' + 'theirs\n' + '>>>>>>> x\n' + 'tail'; + + final parsed = GitConflictParser.parse(diff3); + expect(parsed.blocks.first.hasBaseSegment, isTrue); + + final lines = ConflictLineBuilder.build(diff3, parsed); + final baseHeader = lines.firstWhere( + (l) => l.role == ConflictLineRole.baseHeader, + ); + final baseContent = lines.firstWhere( + (l) => l.role == ConflictLineRole.baseContent, + ); + + expect(baseHeader.text, contains('|||||||')); + expect(baseContent.text, equals('base')); + expect(baseContent.lineNumber, equals(5)); + + // 基线段不应被当作可操作侧 + expect(baseContent.role, isNot(equals(ConflictLineRole.oursContent))); + expect(baseContent.role, isNot(equals(ConflictLineRole.theirsContent))); + }); + + test('多个冲突块各自带正确 blockIndex,互不串位', () { + const two = 'a\n' + '<<<<<<< HEAD\n' + 'o1\n' + '=======\n' + 't1\n' + '>>>>>>> x\n' + 'b\n' + '<<<<<<< HEAD\n' + 'o2\n' + '=======\n' + 't2\n' + '>>>>>>> x\n' + 'c'; + + final parsed = GitConflictParser.parse(two); + final lines = ConflictLineBuilder.build(two, parsed); + + final headers = lines.where((l) => l.isHeader).toList(); + expect(headers.length, equals(4)); + expect(headers[0].blockIndex, equals(0)); + expect(headers[1].blockIndex, equals(0)); + expect(headers[2].blockIndex, equals(1)); + expect(headers[3].blockIndex, equals(1)); + + // 上下文行不属于任何块 + final contexts = lines.where((l) => l.role == ConflictLineRole.context); + expect(contexts.every((l) => l.blockIndex == null), isTrue); + }); + + test('行号连续覆盖整个文件,不丢行不多行', () { + final parsed = GitConflictParser.parse(standard); + final lines = ConflictLineBuilder.build(standard, parsed); + + for (var i = 0; i < lines.length; i++) { + expect(lines[i].lineNumber, equals(i + 1)); + } + expect(lines.length, equals(standard.split('\n').length)); + }); + + test('空段(一侧无内容)不产生内容行但标题与分隔仍在', () { + const emptyOurs = '<<<<<<< HEAD\n' + '=======\n' + 'theirs-only\n' + '>>>>>>> x'; + + final parsed = GitConflictParser.parse(emptyOurs); + final lines = ConflictLineBuilder.build(emptyOurs, parsed); + + expect(lines.length, equals(4)); + expect(lines[0].role, equals(ConflictLineRole.oursHeader)); + expect(lines[1].role, equals(ConflictLineRole.separator)); + expect(lines[2].role, equals(ConflictLineRole.theirsContent)); + expect(lines[3].role, equals(ConflictLineRole.theirsHeader)); + // 没有 oursContent 行 + expect( + lines.any((l) => l.role == ConflictLineRole.oursContent), + isFalse, + ); + }); + + test('无冲突文件全部是上下文行', () { + const clean = 'a\nb\nc'; + final parsed = GitConflictParser.parse(clean); + final lines = ConflictLineBuilder.build(clean, parsed); + + expect(lines.length, equals(3)); + expect( + lines.every((l) => l.role == ConflictLineRole.context), + isTrue, + ); + expect(ConflictLineBuilder.isFullyResolved(parsed), isTrue); + }); + + test('结构异常的标记不被当成冲突块,行仍全部输出', () { + const malformed = '<<<<<<< HEAD\nours\n'; + final parsed = GitConflictParser.parse(malformed); + expect(parsed.isMalformed, isTrue); + + final lines = ConflictLineBuilder.build(malformed, parsed); + // 解析失败时不应伪造标题带,全部按上下文渲染(用户会看到原始标记文本) + expect(lines.every((l) => l.role == ConflictLineRole.context), isTrue); + expect(lines.length, equals(malformed.split('\n').length)); + expect(lines.length, equals(3)); + }); + }); + + group('段落文本提取(按绝对行号切分)', () { + test('从块范围取当前侧与传入侧文本', () { + const content = 'line1\n' + '<<<<<<< HEAD\n' + 'ours-a\n' + 'ours-b\n' + '=======\n' + 'theirs-a\n' + '>>>>>>> feature\n' + 'line2'; + + final parsed = GitConflictParser.parse(content); + final lines = content.split('\n'); + final block = parsed.blocks.first; + + String seg(int from, int to) => + lines.sublist(from.clamp(0, lines.length), to.clamp(0, lines.length)).join('\n'); + + expect(seg(block.ours.startLine, block.ours.endLine), equals('ours-a\nours-b')); + expect(seg(block.theirs.startLine, block.theirs.endLine), equals('theirs-a')); + }); + + test('段落行号越界时被钳制而不是抛异常', () { + const content = '<<<<<<< HEAD\nours\n=======\n'; + final parsed = GitConflictParser.parse(content); + // 该内容结构不完整,应被判定为 malformed(不产生块) + expect(parsed.isMalformed, isTrue); + expect(parsed.blocks, isEmpty); + }); + }); +} diff --git a/test/git_conflict_parser_test.dart b/test/git_conflict_parser_test.dart index 6a7c540..713877d 100644 --- a/test/git_conflict_parser_test.dart +++ b/test/git_conflict_parser_test.dart @@ -243,4 +243,165 @@ void main() { expect(block.theirsLabel, contains('1a2b3c4')); }); }); + + group('逐块替换(解决冲突的核心算法)', () { + const twoBlocks = 'header\n' + '<<<<<<< HEAD\n' + 'ours-1\n' + '=======\n' + 'theirs-1\n' + '>>>>>>> x\n' + 'middle\n' + '<<<<<<< HEAD\n' + 'ours-2\n' + '=======\n' + 'theirs-2\n' + '>>>>>>> x\n' + 'footer'; + + test('替换第一个块只影响该块范围,其余原样保留', () { + final parsed = GitConflictParser.parse(twoBlocks); + expect(parsed.blocks.length, equals(2)); + + final result = GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 0, + replacement: 'RESOLVED-1', + ); + + expect(result, isNotNull); + expect(result!, contains('header')); + expect(result, contains('RESOLVED-1')); + expect(result, contains('middle')); + expect(result, contains('footer')); + // 第一个块的标记没了 + expect(result, isNot(contains('ours-1'))); + expect(result, isNot(contains('theirs-1'))); + // 第二个块完好无损 + expect(result, contains('ours-2')); + expect(result, contains('theirs-2')); + }); + + test('替换第二个块时第一个块不受影响', () { + final parsed = GitConflictParser.parse(twoBlocks); + final result = GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 1, + replacement: 'RESOLVED-2', + ); + + expect(result, isNotNull); + expect(result!, contains('ours-1')); + expect(result, contains('theirs-1')); + expect(result, contains('RESOLVED-2')); + expect(result, isNot(contains('ours-2'))); + }); + + test('替换为空字符串即删除该块内容', () { + final parsed = GitConflictParser.parse(twoBlocks); + final result = GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 0, + replacement: '', + ); + + expect(result, isNotNull); + // 块内容被整段移除,剩下 header/middle/第二个块/footer + expect(result!.split('\n')[0], equals('header')); + expect(result.split('\n')[1], equals('middle')); + expect(result, isNot(contains('ours-1'))); + }); + + test('多行替换内容保留全部行', () { + final parsed = GitConflictParser.parse(twoBlocks); + final result = GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 0, + replacement: 'line-a\nline-b\nline-c', + ); + + expect(result, isNotNull); + expect(result!, contains('line-a\nline-b\nline-c')); + }); + + test('末尾空串不会多插空行', () { + final parsed = GitConflictParser.parse(twoBlocks); + final result = GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 0, + replacement: 'only\n', + ); + // 'only\n' 应等价于 'only' + final result2 = GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 0, + replacement: 'only', + ); + expect(result, equals(result2)); + }); + + test('越界索引返回 null 而不是破坏内容', () { + final parsed = GitConflictParser.parse(twoBlocks); + expect( + GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: 5, + replacement: 'x', + ), + isNull, + ); + expect( + GitConflictParser.replaceBlock( + content: twoBlocks, + blocks: parsed.blocks, + blockIndex: -1, + replacement: 'x', + ), + isNull, + ); + }); + + test('逐个替换两块后不再有标记', () { + // 模拟用户逐块点选:每替换一次都重新解析(行号会移动) + var content = twoBlocks; + var parsed = GitConflictParser.parse(content); + expect(parsed.blocks.length, equals(2)); + + content = GitConflictParser.replaceBlock( + content: content, + blocks: parsed.blocks, + blockIndex: 0, + replacement: 'R1', + )!; + parsed = GitConflictParser.parse(content); + expect(parsed.blocks.length, equals(1), reason: '重解析后应只剩一块'); + + content = GitConflictParser.replaceBlock( + content: content, + blocks: parsed.blocks, + blockIndex: 0, + replacement: 'R2', + )!; + parsed = GitConflictParser.parse(content); + + expect(parsed.blocks, isEmpty); + expect(content, contains('R1')); + expect(content, contains('R2')); + // 全部标记清除 + expect(content, isNot(contains('<<<<<<<'))); + expect(content, isNot(contains('>>>>>>>'))); + }); + + test('countMarkers 快速统计残留块数', () { + expect(GitConflictParser.countMarkers(twoBlocks), equals(2)); + expect(GitConflictParser.countMarkers('clean file\n'), equals(0)); + }); + }); }