From 96358eae070595cf849b2d30795453aa7b65c0e7 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Fri, 18 Sep 2026 13:44:44 +0800 Subject: [PATCH] 1 --- lib/l10n/app_en.arb | 173 +- lib/l10n/app_localizations.dart | 672 ++++ lib/l10n/app_localizations_en.dart | 378 ++ lib/l10n/app_localizations_zh.dart | 373 ++ lib/l10n/app_zh.arb | 228 +- lib/main.dart | 18 +- lib/models/git_model.dart | 65 + lib/providers/git_provider.dart | 668 ++++ lib/providers/search_provider.dart | 16 + lib/providers/tab_provider.dart | 9 + .../background_task/apt_package_task.dart | 7 +- lib/services/git_service.dart | 1084 ++++++ lib/services/internal_engine_service.dart | 31 +- lib/services/toolchain_service.dart | 24 +- lib/utils/git_decoration_utils.dart | 83 + lib/utils/git_diff_helper.dart | 331 ++ lib/utils/syntax_highlight_helper.dart | 28 + lib/widgets/code_editor_drawer.dart | 136 +- lib/widgets/code_editor_widget.dart | 91 +- lib/widgets/file_item_widget.dart | 139 +- lib/widgets/file_tree_widget.dart | 19 +- lib/widgets/git/git_diff_page.dart | 1865 ++++++++++ lib/widgets/git/git_graph_painter.dart | 110 + lib/widgets/git/git_panel_widget.dart | 3112 +++++++++++++++++ lib/widgets/search/search_panel_widget.dart | 885 +++-- test/drawer_activity_bar_test.dart | 10 + test/git_file_tree_decoration_test.dart | 158 + test/git_repository_test.dart | 1322 +++++++ test/project_search_test.dart | 78 + 29 files changed, 11610 insertions(+), 503 deletions(-) create mode 100644 lib/providers/git_provider.dart create mode 100644 lib/services/git_service.dart create mode 100644 lib/utils/git_decoration_utils.dart create mode 100644 lib/utils/git_diff_helper.dart create mode 100644 lib/widgets/git/git_diff_page.dart create mode 100644 lib/widgets/git/git_graph_painter.dart create mode 100644 lib/widgets/git/git_panel_widget.dart create mode 100644 test/git_file_tree_decoration_test.dart create mode 100644 test/git_repository_test.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 798e4e6..fde8000 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1156,5 +1156,176 @@ "type": "int" } } - } + }, + "gitStageChange": "Stage Changes", + "gitUnstageChange": "Unstage Changes", + "gitStageAll": "Stage All Changes", + "gitUnstageAll": "Unstage All Changes", + "gitStageSuccess": "Staged", + "gitUnstageSuccess": "Unstaged", + "gitCommit": "Commit", + "gitCommitMessageHint": "Message", + "gitCommitSuccess": "Commit successful", + "gitCommitFailed": "Commit failed: {error}", + "@gitCommitFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "gitDiscardChange": "Discard Changes", + "gitDiscardConfirm": "Discard Changes?", + "gitDiscardConfirmDesc": "Are you sure you want to discard all unstaged changes in \"{fileName}\"? This cannot be undone.", + "@gitDiscardConfirmDesc": { + "placeholders": { + "fileName": { + "type": "String" + } + } + }, + "gitNoCommitMessage": "Please enter a commit message", + "gitNoStagedChangesToCommit": "There are no staged changes. Would you like to stage all changes and commit?", + "gitStageAllAndCommit": "Stage All and Commit", + "gitGraphTitle": "Graph", + "gitNoCommits": "No commit history", + "gitCommitDetails": "Commit Details", + "gitCommitAuthor": "Author", + "gitCommitDate": "Date", + "gitCommitHash": "Commit Hash", + "gitCopyHash": "Copy Hash", + "gitHashCopied": "Commit hash copied to clipboard", + "gitCommitParent": "Parent", + "gitDiscardAll": "Discard All Changes", + "gitDiscardAllChangesTitle": "Discard All Changes?", + "gitDiscardAllChangesConfirm": "Are you sure you want to discard all unstaged changes? Modified files will be restored and untracked files will be cleaned. This cannot be undone.", + "gitDiscardAllStagedTitle": "Discard All Staged Changes?", + "gitDiscardAllStagedConfirm": "Are you sure you want to discard all staged changes? This cannot be undone.", + "gitBranches": "Branches", + "gitCreateBranch": "Create Branch", + "gitBranchNameHint": "Enter branch name", + "gitSwitchBranchSuccess": "Switched to branch {branch}", + "@gitSwitchBranchSuccess": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitCreateBranchSuccess": "Created and switched to branch {branch}", + "@gitCreateBranchSuccess": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitDeleteBranch": "Delete Branch", + "gitDeleteBranchConfirm": "Are you sure you want to delete branch {branch}?", + "@gitDeleteBranchConfirm": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitDeleteBranchSuccess": "Deleted branch {branch}", + "@gitDeleteBranchSuccess": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitCannotDeleteCurrentBranch": "Cannot delete the current branch", + "gitUndoLastCommit": "Undo Last Commit", + "gitUndoLastCommitConfirm": "Are you sure you want to undo the last commit? Changes will be kept in the staging area.", + "gitUndoLastCommitSuccess": "Undid last commit", + "gitStash": "Stash", + "gitStashChanges": "Stash Changes", + "gitStashChangesSuccess": "Stashed current changes", + "gitStashPop": "Pop Latest Stash", + "gitStashPopSuccess": "Restored latest stash", + "gitNoStashFound": "No stashes found", + "gitAddToGitignore": "Add to .gitignore", + "gitAddedToGitignore": "Added to .gitignore", + "gitMoreActions": "More Actions", + "gitOpenFile": "Open File", + "gitTags": "Tags", + "gitCreateTag": "Create Tag", + "gitTagNameHint": "Enter tag name (e.g. v1.0.0)", + "gitTagMessageHint": "Tag message (optional)", + "gitDeleteTag": "Delete Tag", + "gitDeleteTagConfirm": "Are you sure you want to delete tag {tag}?", + "@gitDeleteTagConfirm": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitCreateTagSuccess": "Created tag {tag}", + "@gitCreateTagSuccess": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitDeleteTagSuccess": "Deleted tag {tag}", + "@gitDeleteTagSuccess": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitSwitchTagSuccess": "Checked out to tag {tag}", + "@gitSwitchTagSuccess": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitNoTags": "No tags", + "gitSelectBranchToDelete": "Select branch to delete", + "gitSelectTagToDelete": "Select tag to delete", + "gitSearchBranches": "Search branches...", + "gitSearchTags": "Search tags...", + "gitNoBranches": "No branches", + "gitDiff": "Diff", + "gitDiffOriginal": "Original", + "gitDiffModified": "Modified", + "gitDiffSplitView": "Split View", + "gitDiffUnifiedView": "Unified View", + "gitDiffPrevChange": "Previous Change", + "gitDiffNextChange": "Next Change", + "gitDiffBinaryOrEmpty": "Binary or unsupported file for comparison", + "gitDiffNoChanges": "This file is identical to the base version, no differences found", + "gitDiffStageTooltip": "Stage this file", + "gitDiffUnstageTooltip": "Unstage this file", + "gitDiffDiscardTooltip": "Discard changes in this file", + "gitExpandAll": "Expand All", + "gitLoadMoreCommits": "Load more commits ({count})", + "@gitLoadMoreCommits": { + "placeholders": { + "count": { "type": "int" } + } + }, + "gitLoadedCommitsCount": "Showing {loaded} of {total} commits", + "@gitLoadedCommitsCount": { + "placeholders": { + "loaded": { "type": "int" }, + "total": { "type": "int" } + } + }, + "gitAllCommitsLoaded": "All {count} commits loaded", + "@gitAllCommitsLoaded": { + "placeholders": { + "count": { "type": "int" } + } + }, + "gitLoadingMoreCommits": "Loading more commits...", + "searchExpandAllMatchesInFile": "Expand all matches" } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index da2f167..4a95da7 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3201,6 +3201,678 @@ abstract class AppLocalizations { int matchCount, String replaceText, ); + + /// No description provided for @gitNotInstalled. + /// + /// In zh, this message translates to: + /// **'未检测到 Git'** + String get gitNotInstalled; + + /// No description provided for @gitNotInstalledDesc. + /// + /// In zh, this message translates to: + /// **'系统中未检测到 Git 命令行工具。请在系统终端或 Linux 容器中安装 git(如执行 apt update && apt install -y git)。'** + String get gitNotInstalledDesc; + + /// No description provided for @gitNeedInstall. + /// + /// In zh, this message translates to: + /// **'需要安装 Git'** + String get gitNeedInstall; + + /// No description provided for @gitInstallAction. + /// + /// In zh, this message translates to: + /// **'安装 Git'** + String get gitInstallAction; + + /// No description provided for @gitInstallingProgress. + /// + /// In zh, this message translates to: + /// **'正在安装 Git...'** + String get gitInstallingProgress; + + /// No description provided for @gitInstallSuccess. + /// + /// In zh, this message translates to: + /// **'Git 安装成功'** + String get gitInstallSuccess; + + /// No description provided for @gitInstallFailed. + /// + /// In zh, this message translates to: + /// **'Git 安装失败: {error}'** + String gitInstallFailed(String error); + + /// No description provided for @gitNoRepoFound. + /// + /// In zh, this message translates to: + /// **'当前工程尚未初始化为 Git 仓库'** + String get gitNoRepoFound; + + /// No description provided for @gitNoRepoDesc. + /// + /// In zh, this message translates to: + /// **'初始化本地 Git 仓库后,即可使用版本控制、分支管理及变更追踪功能。'** + String get gitNoRepoDesc; + + /// No description provided for @gitInitRepo. + /// + /// In zh, this message translates to: + /// **'初始化 Git 仓库'** + String get gitInitRepo; + + /// No description provided for @gitInitializing. + /// + /// In zh, this message translates to: + /// **'正在初始化 Git 仓库...'** + String get gitInitializing; + + /// No description provided for @gitInitSuccess. + /// + /// In zh, this message translates to: + /// **'Git 仓库初始化成功'** + String get gitInitSuccess; + + /// No description provided for @gitInitFailed. + /// + /// In zh, this message translates to: + /// **'Git 仓库初始化失败: {error}'** + String gitInitFailed(String error); + + /// No description provided for @gitRepository. + /// + /// In zh, this message translates to: + /// **'仓库'** + String get gitRepository; + + /// No description provided for @gitCurrentBranch. + /// + /// In zh, this message translates to: + /// **'当前分支: {branch}'** + String gitCurrentBranch(String branch); + + /// No description provided for @gitSwitchRepo. + /// + /// In zh, this message translates to: + /// **'切换仓库'** + String get gitSwitchRepo; + + /// No description provided for @gitRefresh. + /// + /// In zh, this message translates to: + /// **'刷新 Git 状态'** + String get gitRefresh; + + /// No description provided for @gitChanges. + /// + /// In zh, this message translates to: + /// **'更改'** + String get gitChanges; + + /// No description provided for @gitStagedChanges. + /// + /// In zh, this message translates to: + /// **'暂存的更改'** + String get gitStagedChanges; + + /// No description provided for @gitNoChanges. + /// + /// In zh, this message translates to: + /// **'暂无任何文件更改'** + String get gitNoChanges; + + /// No description provided for @gitStatusUntracked. + /// + /// In zh, this message translates to: + /// **'未跟踪'** + String get gitStatusUntracked; + + /// No description provided for @gitStatusModified. + /// + /// In zh, this message translates to: + /// **'已修改'** + String get gitStatusModified; + + /// No description provided for @gitStatusAdded. + /// + /// In zh, this message translates to: + /// **'新增'** + String get gitStatusAdded; + + /// No description provided for @gitStatusDeleted. + /// + /// In zh, this message translates to: + /// **'已删除'** + String get gitStatusDeleted; + + /// No description provided for @gitStatusRenamed. + /// + /// In zh, this message translates to: + /// **'重命名'** + String get gitStatusRenamed; + + /// No description provided for @gitStatusConflict. + /// + /// In zh, this message translates to: + /// **'冲突'** + String get gitStatusConflict; + + /// No description provided for @gitMultipleReposDetected. + /// + /// In zh, this message translates to: + /// **'检测到多个 Git 仓库 ({count})'** + String gitMultipleReposDetected(int count); + + /// No description provided for @gitStageChange. + /// + /// In zh, this message translates to: + /// **'暂存更改'** + String get gitStageChange; + + /// No description provided for @gitUnstageChange. + /// + /// In zh, this message translates to: + /// **'取消暂存更改'** + String get gitUnstageChange; + + /// No description provided for @gitStageAll. + /// + /// In zh, this message translates to: + /// **'全部暂存更改'** + String get gitStageAll; + + /// No description provided for @gitUnstageAll. + /// + /// In zh, this message translates to: + /// **'全部取消暂存更改'** + String get gitUnstageAll; + + /// No description provided for @gitStageSuccess. + /// + /// In zh, this message translates to: + /// **'已暂存'** + String get gitStageSuccess; + + /// No description provided for @gitUnstageSuccess. + /// + /// In zh, this message translates to: + /// **'已取消暂存'** + String get gitUnstageSuccess; + + /// No description provided for @gitCommit. + /// + /// In zh, this message translates to: + /// **'提交'** + String get gitCommit; + + /// No description provided for @gitCommitMessageHint. + /// + /// In zh, this message translates to: + /// **'提交信息'** + String get gitCommitMessageHint; + + /// No description provided for @gitCommitSuccess. + /// + /// In zh, this message translates to: + /// **'提交成功'** + String get gitCommitSuccess; + + /// No description provided for @gitCommitFailed. + /// + /// In zh, this message translates to: + /// **'提交失败: {error}'** + String gitCommitFailed(String error); + + /// No description provided for @gitDiscardChange. + /// + /// In zh, this message translates to: + /// **'放弃更改'** + String get gitDiscardChange; + + /// No description provided for @gitDiscardConfirm. + /// + /// In zh, this message translates to: + /// **'放弃更改?'** + String get gitDiscardConfirm; + + /// No description provided for @gitDiscardConfirmDesc. + /// + /// In zh, this message translates to: + /// **'确定要放弃对 \"{fileName}\" 的所有未暂存更改吗?此操作无法撤销。'** + String gitDiscardConfirmDesc(String fileName); + + /// No description provided for @gitNoCommitMessage. + /// + /// In zh, this message translates to: + /// **'请输入提交信息'** + String get gitNoCommitMessage; + + /// No description provided for @gitNoStagedChangesToCommit. + /// + /// In zh, this message translates to: + /// **'暂存区没有已暂存的更改,是否全部暂存并直接提交?'** + String get gitNoStagedChangesToCommit; + + /// No description provided for @gitStageAllAndCommit. + /// + /// In zh, this message translates to: + /// **'全部暂存并提交'** + String get gitStageAllAndCommit; + + /// No description provided for @gitGraphTitle. + /// + /// In zh, this message translates to: + /// **'图表'** + String get gitGraphTitle; + + /// No description provided for @gitNoCommits. + /// + /// In zh, this message translates to: + /// **'暂无提交历史'** + String get gitNoCommits; + + /// No description provided for @gitCommitDetails. + /// + /// In zh, this message translates to: + /// **'提交详情'** + String get gitCommitDetails; + + /// No description provided for @gitCommitAuthor. + /// + /// In zh, this message translates to: + /// **'作者'** + String get gitCommitAuthor; + + /// No description provided for @gitCommitDate. + /// + /// In zh, this message translates to: + /// **'提交日期'** + String get gitCommitDate; + + /// No description provided for @gitCommitHash. + /// + /// In zh, this message translates to: + /// **'提交哈希'** + String get gitCommitHash; + + /// No description provided for @gitCopyHash. + /// + /// In zh, this message translates to: + /// **'复制哈希'** + String get gitCopyHash; + + /// No description provided for @gitHashCopied. + /// + /// In zh, this message translates to: + /// **'已复制提交哈希到剪贴板'** + String get gitHashCopied; + + /// No description provided for @gitCommitParent. + /// + /// In zh, this message translates to: + /// **'父提交'** + String get gitCommitParent; + + /// No description provided for @gitDiscardAll. + /// + /// In zh, this message translates to: + /// **'全部放弃更改'** + String get gitDiscardAll; + + /// No description provided for @gitDiscardAllChangesTitle. + /// + /// In zh, this message translates to: + /// **'放弃所有未暂存更改?'** + String get gitDiscardAllChangesTitle; + + /// No description provided for @gitDiscardAllChangesConfirm. + /// + /// In zh, this message translates to: + /// **'确定要放弃所有未暂存更改吗?所有已修改的文件将恢复,未跟踪的新文件将被清除,此操作无法撤销。'** + String get gitDiscardAllChangesConfirm; + + /// No description provided for @gitDiscardAllStagedTitle. + /// + /// In zh, this message translates to: + /// **'放弃所有已暂存更改?'** + String get gitDiscardAllStagedTitle; + + /// No description provided for @gitDiscardAllStagedConfirm. + /// + /// In zh, this message translates to: + /// **'确定要放弃所有已暂存的更改吗?所选文件的修改将被彻底恢复,此操作无法撤销。'** + String get gitDiscardAllStagedConfirm; + + /// No description provided for @gitBranches. + /// + /// In zh, this message translates to: + /// **'分支'** + String get gitBranches; + + /// No description provided for @gitCreateBranch. + /// + /// In zh, this message translates to: + /// **'创建新分支'** + String get gitCreateBranch; + + /// No description provided for @gitBranchNameHint. + /// + /// In zh, this message translates to: + /// **'输入新分支名称'** + String get gitBranchNameHint; + + /// No description provided for @gitSwitchBranchSuccess. + /// + /// In zh, this message translates to: + /// **'已切换至分支 {branch}'** + String gitSwitchBranchSuccess(String branch); + + /// No description provided for @gitCreateBranchSuccess. + /// + /// In zh, this message translates to: + /// **'已创建并切换至新分支 {branch}'** + String gitCreateBranchSuccess(String branch); + + /// No description provided for @gitDeleteBranch. + /// + /// In zh, this message translates to: + /// **'删除分支'** + String get gitDeleteBranch; + + /// No description provided for @gitDeleteBranchConfirm. + /// + /// In zh, this message translates to: + /// **'确定要删除本地分支 {branch} 吗?'** + String gitDeleteBranchConfirm(String branch); + + /// No description provided for @gitDeleteBranchSuccess. + /// + /// In zh, this message translates to: + /// **'已删除分支 {branch}'** + String gitDeleteBranchSuccess(String branch); + + /// No description provided for @gitCannotDeleteCurrentBranch. + /// + /// In zh, this message translates to: + /// **'无法删除当前所在分支'** + String get gitCannotDeleteCurrentBranch; + + /// No description provided for @gitUndoLastCommit. + /// + /// In zh, this message translates to: + /// **'撤销上次提交'** + String get gitUndoLastCommit; + + /// No description provided for @gitUndoLastCommitConfirm. + /// + /// In zh, this message translates to: + /// **'确定要撤销上一次提交吗?代码更改将保留在暂存区。'** + String get gitUndoLastCommitConfirm; + + /// No description provided for @gitUndoLastCommitSuccess. + /// + /// In zh, this message translates to: + /// **'已撤销上一次提交'** + String get gitUndoLastCommitSuccess; + + /// No description provided for @gitStash. + /// + /// In zh, this message translates to: + /// **'贮藏'** + String get gitStash; + + /// No description provided for @gitStashChanges. + /// + /// In zh, this message translates to: + /// **'贮藏当前更改'** + String get gitStashChanges; + + /// No description provided for @gitStashChangesSuccess. + /// + /// In zh, this message translates to: + /// **'已将当前更改暂存至贮藏栈'** + String get gitStashChangesSuccess; + + /// No description provided for @gitStashPop. + /// + /// In zh, this message translates to: + /// **'恢复最近贮藏 (Pop)'** + String get gitStashPop; + + /// No description provided for @gitStashPopSuccess. + /// + /// In zh, this message translates to: + /// **'已恢复最近的贮藏更改'** + String get gitStashPopSuccess; + + /// No description provided for @gitNoStashFound. + /// + /// In zh, this message translates to: + /// **'当前没有可恢复的贮藏记录'** + String get gitNoStashFound; + + /// No description provided for @gitAddToGitignore. + /// + /// In zh, this message translates to: + /// **'添加到 .gitignore'** + String get gitAddToGitignore; + + /// No description provided for @gitAddedToGitignore. + /// + /// In zh, this message translates to: + /// **'已添加至 .gitignore'** + String get gitAddedToGitignore; + + /// No description provided for @gitMoreActions. + /// + /// In zh, this message translates to: + /// **'更多操作'** + String get gitMoreActions; + + /// No description provided for @gitOpenFile. + /// + /// In zh, this message translates to: + /// **'打开文件'** + String get gitOpenFile; + + /// No description provided for @gitTags. + /// + /// In zh, this message translates to: + /// **'标签'** + String get gitTags; + + /// No description provided for @gitCreateTag. + /// + /// In zh, this message translates to: + /// **'创建新标签'** + String get gitCreateTag; + + /// No description provided for @gitTagNameHint. + /// + /// In zh, this message translates to: + /// **'输入标签名称 (例如 v1.0.0)'** + String get gitTagNameHint; + + /// No description provided for @gitTagMessageHint. + /// + /// In zh, this message translates to: + /// **'标签附注信息 (可选)'** + String get gitTagMessageHint; + + /// No description provided for @gitDeleteTag. + /// + /// In zh, this message translates to: + /// **'删除标签'** + String get gitDeleteTag; + + /// No description provided for @gitDeleteTagConfirm. + /// + /// In zh, this message translates to: + /// **'确定要删除本地标签 {tag} 吗?'** + String gitDeleteTagConfirm(String tag); + + /// No description provided for @gitCreateTagSuccess. + /// + /// In zh, this message translates to: + /// **'已创建标签 {tag}'** + String gitCreateTagSuccess(String tag); + + /// No description provided for @gitDeleteTagSuccess. + /// + /// In zh, this message translates to: + /// **'已删除标签 {tag}'** + String gitDeleteTagSuccess(String tag); + + /// No description provided for @gitSwitchTagSuccess. + /// + /// In zh, this message translates to: + /// **'已检出至标签 {tag}'** + String gitSwitchTagSuccess(String tag); + + /// No description provided for @gitNoTags. + /// + /// In zh, this message translates to: + /// **'暂无标签'** + String get gitNoTags; + + /// No description provided for @gitSelectBranchToDelete. + /// + /// In zh, this message translates to: + /// **'选择要删除的分支'** + String get gitSelectBranchToDelete; + + /// No description provided for @gitSelectTagToDelete. + /// + /// In zh, this message translates to: + /// **'选择要删除的标签'** + String get gitSelectTagToDelete; + + /// No description provided for @gitSearchBranches. + /// + /// In zh, this message translates to: + /// **'搜索分支...'** + String get gitSearchBranches; + + /// No description provided for @gitSearchTags. + /// + /// In zh, this message translates to: + /// **'搜索标签...'** + String get gitSearchTags; + + /// No description provided for @gitNoBranches. + /// + /// In zh, this message translates to: + /// **'暂无分支'** + String get gitNoBranches; + + /// No description provided for @gitDiff. + /// + /// In zh, this message translates to: + /// **'差异对比'** + String get gitDiff; + + /// No description provided for @gitDiffOriginal. + /// + /// In zh, this message translates to: + /// **'原始版本'** + String get gitDiffOriginal; + + /// No description provided for @gitDiffModified. + /// + /// In zh, this message translates to: + /// **'修改版本'** + String get gitDiffModified; + + /// No description provided for @gitDiffSplitView. + /// + /// In zh, this message translates to: + /// **'双屏分栏'** + String get gitDiffSplitView; + + /// No description provided for @gitDiffUnifiedView. + /// + /// In zh, this message translates to: + /// **'单屏内联'** + String get gitDiffUnifiedView; + + /// No description provided for @gitDiffPrevChange. + /// + /// In zh, this message translates to: + /// **'上一处更改'** + String get gitDiffPrevChange; + + /// No description provided for @gitDiffNextChange. + /// + /// In zh, this message translates to: + /// **'下一处更改'** + String get gitDiffNextChange; + + /// No description provided for @gitDiffBinaryOrEmpty. + /// + /// In zh, this message translates to: + /// **'二进制或不支持比较的文件'** + String get gitDiffBinaryOrEmpty; + + /// No description provided for @gitDiffNoChanges. + /// + /// In zh, this message translates to: + /// **'该文件与基准版本完全一致,暂无差异'** + String get gitDiffNoChanges; + + /// No description provided for @gitDiffStageTooltip. + /// + /// In zh, this message translates to: + /// **'暂存此文件更改'** + String get gitDiffStageTooltip; + + /// No description provided for @gitDiffUnstageTooltip. + /// + /// In zh, this message translates to: + /// **'取消暂存此文件'** + String get gitDiffUnstageTooltip; + + /// No description provided for @gitDiffDiscardTooltip. + /// + /// In zh, this message translates to: + /// **'放弃此文件更改'** + String get gitDiffDiscardTooltip; + + /// No description provided for @gitExpandAll. + /// + /// In zh, this message translates to: + /// **'全部展开'** + String get gitExpandAll; + + /// No description provided for @gitLoadMoreCommits. + /// + /// In zh, this message translates to: + /// **'加载更多提交 ({count})'** + String gitLoadMoreCommits(int count); + + /// No description provided for @gitLoadedCommitsCount. + /// + /// In zh, this message translates to: + /// **'已显示 {loaded} / {total} 个提交'** + String gitLoadedCommitsCount(int loaded, int total); + + /// No description provided for @gitAllCommitsLoaded. + /// + /// In zh, this message translates to: + /// **'已显示全部 {count} 个提交'** + String gitAllCommitsLoaded(int count); + + /// No description provided for @gitLoadingMoreCommits. + /// + /// In zh, this message translates to: + /// **'正在加载更多提交...'** + String get gitLoadingMoreCommits; + + /// No description provided for @searchExpandAllMatchesInFile. + /// + /// In zh, this message translates to: + /// **'展开全部匹配项'** + String get searchExpandAllMatchesInFile; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 7dfac17..4e34a29 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1933,4 +1933,382 @@ class AppLocalizationsEn extends AppLocalizations { ) { return 'Are you sure you want to replace all $matchCount occurrences in \"$fileName\" with \"$replaceText\"?'; } + + @override + String get gitNotInstalled => 'Git Not Found'; + + @override + String get gitNotInstalledDesc => + 'Git command-line tool was not found on your system. Please install git in your terminal or Linux container (e.g. apt update && apt install -y git).'; + + @override + String get gitNeedInstall => 'Git Installation Required'; + + @override + String get gitInstallAction => 'Install Git'; + + @override + String get gitInstallingProgress => 'Installing Git...'; + + @override + String get gitInstallSuccess => 'Git installed successfully'; + + @override + String gitInstallFailed(String error) { + return 'Failed to install Git: $error'; + } + + @override + String get gitNoRepoFound => 'No Git Repository'; + + @override + String get gitNoRepoDesc => + 'Initialize a Git repository to start version control, branch management, and tracking code changes.'; + + @override + String get gitInitRepo => 'Initialize Repository'; + + @override + String get gitInitializing => 'Initializing Git repository...'; + + @override + String get gitInitSuccess => 'Git repository initialized successfully'; + + @override + String gitInitFailed(String error) { + return 'Failed to initialize Git repository: $error'; + } + + @override + String get gitRepository => 'Repository'; + + @override + String gitCurrentBranch(String branch) { + return 'Branch: $branch'; + } + + @override + String get gitSwitchRepo => 'Switch Repository'; + + @override + String get gitRefresh => 'Refresh Git'; + + @override + String get gitChanges => 'Changes'; + + @override + String get gitStagedChanges => 'Staged Changes'; + + @override + String get gitNoChanges => 'No changes detected'; + + @override + String get gitStatusUntracked => 'Untracked'; + + @override + String get gitStatusModified => 'Modified'; + + @override + String get gitStatusAdded => 'Added'; + + @override + String get gitStatusDeleted => 'Deleted'; + + @override + String get gitStatusRenamed => 'Renamed'; + + @override + String get gitStatusConflict => 'Conflict'; + + @override + String gitMultipleReposDetected(int count) { + return 'Multiple Repositories ($count)'; + } + + @override + String get gitStageChange => 'Stage Changes'; + + @override + String get gitUnstageChange => 'Unstage Changes'; + + @override + String get gitStageAll => 'Stage All Changes'; + + @override + String get gitUnstageAll => 'Unstage All Changes'; + + @override + String get gitStageSuccess => 'Staged'; + + @override + String get gitUnstageSuccess => 'Unstaged'; + + @override + String get gitCommit => 'Commit'; + + @override + String get gitCommitMessageHint => 'Message'; + + @override + String get gitCommitSuccess => 'Commit successful'; + + @override + String gitCommitFailed(String error) { + return 'Commit failed: $error'; + } + + @override + String get gitDiscardChange => 'Discard Changes'; + + @override + String get gitDiscardConfirm => 'Discard Changes?'; + + @override + String gitDiscardConfirmDesc(String fileName) { + return 'Are you sure you want to discard all unstaged changes in \"$fileName\"? This cannot be undone.'; + } + + @override + String get gitNoCommitMessage => 'Please enter a commit message'; + + @override + String get gitNoStagedChangesToCommit => + 'There are no staged changes. Would you like to stage all changes and commit?'; + + @override + String get gitStageAllAndCommit => 'Stage All and Commit'; + + @override + String get gitGraphTitle => 'Graph'; + + @override + String get gitNoCommits => 'No commit history'; + + @override + String get gitCommitDetails => 'Commit Details'; + + @override + String get gitCommitAuthor => 'Author'; + + @override + String get gitCommitDate => 'Date'; + + @override + String get gitCommitHash => 'Commit Hash'; + + @override + String get gitCopyHash => 'Copy Hash'; + + @override + String get gitHashCopied => 'Commit hash copied to clipboard'; + + @override + String get gitCommitParent => 'Parent'; + + @override + String get gitDiscardAll => 'Discard All Changes'; + + @override + String get gitDiscardAllChangesTitle => 'Discard All Changes?'; + + @override + String get gitDiscardAllChangesConfirm => + 'Are you sure you want to discard all unstaged changes? Modified files will be restored and untracked files will be cleaned. This cannot be undone.'; + + @override + String get gitDiscardAllStagedTitle => 'Discard All Staged Changes?'; + + @override + String get gitDiscardAllStagedConfirm => + 'Are you sure you want to discard all staged changes? This cannot be undone.'; + + @override + String get gitBranches => 'Branches'; + + @override + String get gitCreateBranch => 'Create Branch'; + + @override + String get gitBranchNameHint => 'Enter branch name'; + + @override + String gitSwitchBranchSuccess(String branch) { + return 'Switched to branch $branch'; + } + + @override + String gitCreateBranchSuccess(String branch) { + return 'Created and switched to branch $branch'; + } + + @override + String get gitDeleteBranch => 'Delete Branch'; + + @override + String gitDeleteBranchConfirm(String branch) { + return 'Are you sure you want to delete branch $branch?'; + } + + @override + String gitDeleteBranchSuccess(String branch) { + return 'Deleted branch $branch'; + } + + @override + String get gitCannotDeleteCurrentBranch => 'Cannot delete the current branch'; + + @override + String get gitUndoLastCommit => 'Undo Last Commit'; + + @override + String get gitUndoLastCommitConfirm => + 'Are you sure you want to undo the last commit? Changes will be kept in the staging area.'; + + @override + String get gitUndoLastCommitSuccess => 'Undid last commit'; + + @override + String get gitStash => 'Stash'; + + @override + String get gitStashChanges => 'Stash Changes'; + + @override + String get gitStashChangesSuccess => 'Stashed current changes'; + + @override + String get gitStashPop => 'Pop Latest Stash'; + + @override + String get gitStashPopSuccess => 'Restored latest stash'; + + @override + String get gitNoStashFound => 'No stashes found'; + + @override + String get gitAddToGitignore => 'Add to .gitignore'; + + @override + String get gitAddedToGitignore => 'Added to .gitignore'; + + @override + String get gitMoreActions => 'More Actions'; + + @override + String get gitOpenFile => 'Open File'; + + @override + String get gitTags => 'Tags'; + + @override + String get gitCreateTag => 'Create Tag'; + + @override + String get gitTagNameHint => 'Enter tag name (e.g. v1.0.0)'; + + @override + String get gitTagMessageHint => 'Tag message (optional)'; + + @override + String get gitDeleteTag => 'Delete Tag'; + + @override + String gitDeleteTagConfirm(String tag) { + return 'Are you sure you want to delete tag $tag?'; + } + + @override + String gitCreateTagSuccess(String tag) { + return 'Created tag $tag'; + } + + @override + String gitDeleteTagSuccess(String tag) { + return 'Deleted tag $tag'; + } + + @override + String gitSwitchTagSuccess(String tag) { + return 'Checked out to tag $tag'; + } + + @override + String get gitNoTags => 'No tags'; + + @override + String get gitSelectBranchToDelete => 'Select branch to delete'; + + @override + String get gitSelectTagToDelete => 'Select tag to delete'; + + @override + String get gitSearchBranches => 'Search branches...'; + + @override + String get gitSearchTags => 'Search tags...'; + + @override + String get gitNoBranches => 'No branches'; + + @override + String get gitDiff => 'Diff'; + + @override + String get gitDiffOriginal => 'Original'; + + @override + String get gitDiffModified => 'Modified'; + + @override + String get gitDiffSplitView => 'Split View'; + + @override + String get gitDiffUnifiedView => 'Unified View'; + + @override + String get gitDiffPrevChange => 'Previous Change'; + + @override + String get gitDiffNextChange => 'Next Change'; + + @override + String get gitDiffBinaryOrEmpty => + 'Binary or unsupported file for comparison'; + + @override + String get gitDiffNoChanges => + 'This file is identical to the base version, no differences found'; + + @override + String get gitDiffStageTooltip => 'Stage this file'; + + @override + String get gitDiffUnstageTooltip => 'Unstage this file'; + + @override + String get gitDiffDiscardTooltip => 'Discard changes in this file'; + + @override + String get gitExpandAll => 'Expand All'; + + @override + String gitLoadMoreCommits(int count) { + return 'Load more commits ($count)'; + } + + @override + String gitLoadedCommitsCount(int loaded, int total) { + return 'Showing $loaded of $total commits'; + } + + @override + String gitAllCommitsLoaded(int count) { + return 'All $count commits loaded'; + } + + @override + String get gitLoadingMoreCommits => 'Loading more commits...'; + + @override + String get searchExpandAllMatchesInFile => 'Expand all matches'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 026ff45..0877a48 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1873,4 +1873,377 @@ class AppLocalizationsZh extends AppLocalizations { ) { return '确定要在 \"$fileName\" 中将全部 $matchCount 处匹配替换为 \"$replaceText\" 吗?'; } + + @override + String get gitNotInstalled => '未检测到 Git'; + + @override + String get gitNotInstalledDesc => + '系统中未检测到 Git 命令行工具。请在系统终端或 Linux 容器中安装 git(如执行 apt update && apt install -y git)。'; + + @override + String get gitNeedInstall => '需要安装 Git'; + + @override + String get gitInstallAction => '安装 Git'; + + @override + String get gitInstallingProgress => '正在安装 Git...'; + + @override + String get gitInstallSuccess => 'Git 安装成功'; + + @override + String gitInstallFailed(String error) { + return 'Git 安装失败: $error'; + } + + @override + String get gitNoRepoFound => '当前工程尚未初始化为 Git 仓库'; + + @override + String get gitNoRepoDesc => '初始化本地 Git 仓库后,即可使用版本控制、分支管理及变更追踪功能。'; + + @override + String get gitInitRepo => '初始化 Git 仓库'; + + @override + String get gitInitializing => '正在初始化 Git 仓库...'; + + @override + String get gitInitSuccess => 'Git 仓库初始化成功'; + + @override + String gitInitFailed(String error) { + return 'Git 仓库初始化失败: $error'; + } + + @override + String get gitRepository => '仓库'; + + @override + String gitCurrentBranch(String branch) { + return '当前分支: $branch'; + } + + @override + String get gitSwitchRepo => '切换仓库'; + + @override + String get gitRefresh => '刷新 Git 状态'; + + @override + String get gitChanges => '更改'; + + @override + String get gitStagedChanges => '暂存的更改'; + + @override + String get gitNoChanges => '暂无任何文件更改'; + + @override + String get gitStatusUntracked => '未跟踪'; + + @override + String get gitStatusModified => '已修改'; + + @override + String get gitStatusAdded => '新增'; + + @override + String get gitStatusDeleted => '已删除'; + + @override + String get gitStatusRenamed => '重命名'; + + @override + String get gitStatusConflict => '冲突'; + + @override + String gitMultipleReposDetected(int count) { + return '检测到多个 Git 仓库 ($count)'; + } + + @override + String get gitStageChange => '暂存更改'; + + @override + String get gitUnstageChange => '取消暂存更改'; + + @override + String get gitStageAll => '全部暂存更改'; + + @override + String get gitUnstageAll => '全部取消暂存更改'; + + @override + String get gitStageSuccess => '已暂存'; + + @override + String get gitUnstageSuccess => '已取消暂存'; + + @override + String get gitCommit => '提交'; + + @override + String get gitCommitMessageHint => '提交信息'; + + @override + String get gitCommitSuccess => '提交成功'; + + @override + String gitCommitFailed(String error) { + return '提交失败: $error'; + } + + @override + String get gitDiscardChange => '放弃更改'; + + @override + String get gitDiscardConfirm => '放弃更改?'; + + @override + String gitDiscardConfirmDesc(String fileName) { + return '确定要放弃对 \"$fileName\" 的所有未暂存更改吗?此操作无法撤销。'; + } + + @override + String get gitNoCommitMessage => '请输入提交信息'; + + @override + String get gitNoStagedChangesToCommit => '暂存区没有已暂存的更改,是否全部暂存并直接提交?'; + + @override + String get gitStageAllAndCommit => '全部暂存并提交'; + + @override + String get gitGraphTitle => '图表'; + + @override + String get gitNoCommits => '暂无提交历史'; + + @override + String get gitCommitDetails => '提交详情'; + + @override + String get gitCommitAuthor => '作者'; + + @override + String get gitCommitDate => '提交日期'; + + @override + String get gitCommitHash => '提交哈希'; + + @override + String get gitCopyHash => '复制哈希'; + + @override + String get gitHashCopied => '已复制提交哈希到剪贴板'; + + @override + String get gitCommitParent => '父提交'; + + @override + String get gitDiscardAll => '全部放弃更改'; + + @override + String get gitDiscardAllChangesTitle => '放弃所有未暂存更改?'; + + @override + String get gitDiscardAllChangesConfirm => + '确定要放弃所有未暂存更改吗?所有已修改的文件将恢复,未跟踪的新文件将被清除,此操作无法撤销。'; + + @override + String get gitDiscardAllStagedTitle => '放弃所有已暂存更改?'; + + @override + String get gitDiscardAllStagedConfirm => + '确定要放弃所有已暂存的更改吗?所选文件的修改将被彻底恢复,此操作无法撤销。'; + + @override + String get gitBranches => '分支'; + + @override + String get gitCreateBranch => '创建新分支'; + + @override + String get gitBranchNameHint => '输入新分支名称'; + + @override + String gitSwitchBranchSuccess(String branch) { + return '已切换至分支 $branch'; + } + + @override + String gitCreateBranchSuccess(String branch) { + return '已创建并切换至新分支 $branch'; + } + + @override + String get gitDeleteBranch => '删除分支'; + + @override + String gitDeleteBranchConfirm(String branch) { + return '确定要删除本地分支 $branch 吗?'; + } + + @override + String gitDeleteBranchSuccess(String branch) { + return '已删除分支 $branch'; + } + + @override + String get gitCannotDeleteCurrentBranch => '无法删除当前所在分支'; + + @override + String get gitUndoLastCommit => '撤销上次提交'; + + @override + String get gitUndoLastCommitConfirm => '确定要撤销上一次提交吗?代码更改将保留在暂存区。'; + + @override + String get gitUndoLastCommitSuccess => '已撤销上一次提交'; + + @override + String get gitStash => '贮藏'; + + @override + String get gitStashChanges => '贮藏当前更改'; + + @override + String get gitStashChangesSuccess => '已将当前更改暂存至贮藏栈'; + + @override + String get gitStashPop => '恢复最近贮藏 (Pop)'; + + @override + String get gitStashPopSuccess => '已恢复最近的贮藏更改'; + + @override + String get gitNoStashFound => '当前没有可恢复的贮藏记录'; + + @override + String get gitAddToGitignore => '添加到 .gitignore'; + + @override + String get gitAddedToGitignore => '已添加至 .gitignore'; + + @override + String get gitMoreActions => '更多操作'; + + @override + String get gitOpenFile => '打开文件'; + + @override + String get gitTags => '标签'; + + @override + String get gitCreateTag => '创建新标签'; + + @override + String get gitTagNameHint => '输入标签名称 (例如 v1.0.0)'; + + @override + String get gitTagMessageHint => '标签附注信息 (可选)'; + + @override + String get gitDeleteTag => '删除标签'; + + @override + String gitDeleteTagConfirm(String tag) { + return '确定要删除本地标签 $tag 吗?'; + } + + @override + String gitCreateTagSuccess(String tag) { + return '已创建标签 $tag'; + } + + @override + String gitDeleteTagSuccess(String tag) { + return '已删除标签 $tag'; + } + + @override + String gitSwitchTagSuccess(String tag) { + return '已检出至标签 $tag'; + } + + @override + String get gitNoTags => '暂无标签'; + + @override + String get gitSelectBranchToDelete => '选择要删除的分支'; + + @override + String get gitSelectTagToDelete => '选择要删除的标签'; + + @override + String get gitSearchBranches => '搜索分支...'; + + @override + String get gitSearchTags => '搜索标签...'; + + @override + String get gitNoBranches => '暂无分支'; + + @override + String get gitDiff => '差异对比'; + + @override + String get gitDiffOriginal => '原始版本'; + + @override + String get gitDiffModified => '修改版本'; + + @override + String get gitDiffSplitView => '双屏分栏'; + + @override + String get gitDiffUnifiedView => '单屏内联'; + + @override + String get gitDiffPrevChange => '上一处更改'; + + @override + String get gitDiffNextChange => '下一处更改'; + + @override + String get gitDiffBinaryOrEmpty => '二进制或不支持比较的文件'; + + @override + String get gitDiffNoChanges => '该文件与基准版本完全一致,暂无差异'; + + @override + String get gitDiffStageTooltip => '暂存此文件更改'; + + @override + String get gitDiffUnstageTooltip => '取消暂存此文件'; + + @override + String get gitDiffDiscardTooltip => '放弃此文件更改'; + + @override + String get gitExpandAll => '全部展开'; + + @override + String gitLoadMoreCommits(int count) { + return '加载更多提交 ($count)'; + } + + @override + String gitLoadedCommitsCount(int loaded, int total) { + return '已显示 $loaded / $total 个提交'; + } + + @override + String gitAllCommitsLoaded(int count) { + return '已显示全部 $count 个提交'; + } + + @override + String get gitLoadingMoreCommits => '正在加载更多提交...'; + + @override + String get searchExpandAllMatchesInFile => '展开全部匹配项'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 287f816..1b5e31c 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1101,5 +1101,231 @@ "type": "String" } } - } + }, + "gitNotInstalled": "未检测到 Git", + "gitNotInstalledDesc": "系统中未检测到 Git 命令行工具。请在系统终端或 Linux 容器中安装 git(如执行 apt update && apt install -y git)。", + "gitNeedInstall": "需要安装 Git", + "gitInstallAction": "安装 Git", + "gitInstallingProgress": "正在安装 Git...", + "gitInstallSuccess": "Git 安装成功", + "gitInstallFailed": "Git 安装失败: {error}", + "@gitInstallFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "gitNoRepoFound": "当前工程尚未初始化为 Git 仓库", + "gitNoRepoDesc": "初始化本地 Git 仓库后,即可使用版本控制、分支管理及变更追踪功能。", + "gitInitRepo": "初始化 Git 仓库", + "gitInitializing": "正在初始化 Git 仓库...", + "gitInitSuccess": "Git 仓库初始化成功", + "gitInitFailed": "Git 仓库初始化失败: {error}", + "@gitInitFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "gitRepository": "仓库", + "gitCurrentBranch": "当前分支: {branch}", + "@gitCurrentBranch": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitSwitchRepo": "切换仓库", + "gitRefresh": "刷新 Git 状态", + "gitChanges": "更改", + "gitStagedChanges": "暂存的更改", + "gitNoChanges": "暂无任何文件更改", + "gitStatusUntracked": "未跟踪", + "gitStatusModified": "已修改", + "gitStatusAdded": "新增", + "gitStatusDeleted": "已删除", + "gitStatusRenamed": "重命名", + "gitStatusConflict": "冲突", + "gitMultipleReposDetected": "检测到多个 Git 仓库 ({count})", + "@gitMultipleReposDetected": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitStageChange": "暂存更改", + "gitUnstageChange": "取消暂存更改", + "gitStageAll": "全部暂存更改", + "gitUnstageAll": "全部取消暂存更改", + "gitStageSuccess": "已暂存", + "gitUnstageSuccess": "已取消暂存", + "gitCommit": "提交", + "gitCommitMessageHint": "提交信息", + "gitCommitSuccess": "提交成功", + "gitCommitFailed": "提交失败: {error}", + "@gitCommitFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "gitDiscardChange": "放弃更改", + "gitDiscardConfirm": "放弃更改?", + "gitDiscardConfirmDesc": "确定要放弃对 \"{fileName}\" 的所有未暂存更改吗?此操作无法撤销。", + "@gitDiscardConfirmDesc": { + "placeholders": { + "fileName": { + "type": "String" + } + } + }, + "gitNoCommitMessage": "请输入提交信息", + "gitNoStagedChangesToCommit": "暂存区没有已暂存的更改,是否全部暂存并直接提交?", + "gitStageAllAndCommit": "全部暂存并提交", + "gitGraphTitle": "图表", + "gitNoCommits": "暂无提交历史", + "gitCommitDetails": "提交详情", + "gitCommitAuthor": "作者", + "gitCommitDate": "提交日期", + "gitCommitHash": "提交哈希", + "gitCopyHash": "复制哈希", + "gitHashCopied": "已复制提交哈希到剪贴板", + "gitCommitParent": "父提交", + "gitDiscardAll": "全部放弃更改", + "gitDiscardAllChangesTitle": "放弃所有未暂存更改?", + "gitDiscardAllChangesConfirm": "确定要放弃所有未暂存更改吗?所有已修改的文件将恢复,未跟踪的新文件将被清除,此操作无法撤销。", + "gitDiscardAllStagedTitle": "放弃所有已暂存更改?", + "gitDiscardAllStagedConfirm": "确定要放弃所有已暂存的更改吗?所选文件的修改将被彻底恢复,此操作无法撤销。", + "gitBranches": "分支", + "gitCreateBranch": "创建新分支", + "gitBranchNameHint": "输入新分支名称", + "gitSwitchBranchSuccess": "已切换至分支 {branch}", + "@gitSwitchBranchSuccess": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitCreateBranchSuccess": "已创建并切换至新分支 {branch}", + "@gitCreateBranchSuccess": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitDeleteBranch": "删除分支", + "gitDeleteBranchConfirm": "确定要删除本地分支 {branch} 吗?", + "@gitDeleteBranchConfirm": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitDeleteBranchSuccess": "已删除分支 {branch}", + "@gitDeleteBranchSuccess": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitCannotDeleteCurrentBranch": "无法删除当前所在分支", + "gitUndoLastCommit": "撤销上次提交", + "gitUndoLastCommitConfirm": "确定要撤销上一次提交吗?代码更改将保留在暂存区。", + "gitUndoLastCommitSuccess": "已撤销上一次提交", + "gitStash": "贮藏", + "gitStashChanges": "贮藏当前更改", + "gitStashChangesSuccess": "已将当前更改暂存至贮藏栈", + "gitStashPop": "恢复最近贮藏 (Pop)", + "gitStashPopSuccess": "已恢复最近的贮藏更改", + "gitNoStashFound": "当前没有可恢复的贮藏记录", + "gitAddToGitignore": "添加到 .gitignore", + "gitAddedToGitignore": "已添加至 .gitignore", + "gitMoreActions": "更多操作", + "gitOpenFile": "打开文件", + "gitTags": "标签", + "gitCreateTag": "创建新标签", + "gitTagNameHint": "输入标签名称 (例如 v1.0.0)", + "gitTagMessageHint": "标签附注信息 (可选)", + "gitDeleteTag": "删除标签", + "gitDeleteTagConfirm": "确定要删除本地标签 {tag} 吗?", + "@gitDeleteTagConfirm": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitCreateTagSuccess": "已创建标签 {tag}", + "@gitCreateTagSuccess": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitDeleteTagSuccess": "已删除标签 {tag}", + "@gitDeleteTagSuccess": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitSwitchTagSuccess": "已检出至标签 {tag}", + "@gitSwitchTagSuccess": { + "placeholders": { + "tag": { + "type": "String" + } + } + }, + "gitNoTags": "暂无标签", + "gitSelectBranchToDelete": "选择要删除的分支", + "gitSelectTagToDelete": "选择要删除的标签", + "gitSearchBranches": "搜索分支...", + "gitSearchTags": "搜索标签...", + "gitNoBranches": "暂无分支", + "gitDiff": "差异对比", + "gitDiffOriginal": "原始版本", + "gitDiffModified": "修改版本", + "gitDiffSplitView": "双屏分栏", + "gitDiffUnifiedView": "单屏内联", + "gitDiffPrevChange": "上一处更改", + "gitDiffNextChange": "下一处更改", + "gitDiffBinaryOrEmpty": "二进制或不支持比较的文件", + "gitDiffNoChanges": "该文件与基准版本完全一致,暂无差异", + "gitDiffStageTooltip": "暂存此文件更改", + "gitDiffUnstageTooltip": "取消暂存此文件", + "gitDiffDiscardTooltip": "放弃此文件更改", + "gitExpandAll": "全部展开", + "gitLoadMoreCommits": "加载更多提交 ({count})", + "@gitLoadMoreCommits": { + "placeholders": { + "count": { "type": "int" } + } + }, + "gitLoadedCommitsCount": "已显示 {loaded} / {total} 个提交", + "@gitLoadedCommitsCount": { + "placeholders": { + "loaded": { "type": "int" }, + "total": { "type": "int" } + } + }, + "gitAllCommitsLoaded": "已显示全部 {count} 个提交", + "@gitAllCommitsLoaded": { + "placeholders": { + "count": { "type": "int" } + } + }, + "gitLoadingMoreCommits": "正在加载更多提交...", + "searchExpandAllMatchesInFile": "展开全部匹配项" } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 32f8b75..3e7617b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -42,21 +42,23 @@ class MyApp extends StatelessWidget { return pp; }, ), - ChangeNotifierProxyProvider( + ChangeNotifierProxyProvider( + create: (_) => GitProvider(), + update: (_, project, git) => + (git ?? GitProvider())..bindRootPath(project.rootPath), + ), + ChangeNotifierProxyProvider2( create: (_) => TabProvider()..init(), - update: (_, project, tab) => - (tab ?? (TabProvider()..init()))..bindProjectProvider(project), + update: (_, project, git, tab) => + (tab ?? (TabProvider()..init())) + ..bindProjectProvider(project) + ..bindGitProvider(git), ), ChangeNotifierProxyProvider( create: (_) => SearchProvider(), update: (_, project, search) => (search ?? SearchProvider())..bindRootPath(project.rootPath), ), - ChangeNotifierProxyProvider( - create: (_) => GitProvider(), - update: (_, project, git) => - (git ?? GitProvider())..bindRootPath(project.rootPath), - ), ChangeNotifierProvider(create: (_) => TerminalProvider()), ChangeNotifierProvider( create: (_) { diff --git a/lib/models/git_model.dart b/lib/models/git_model.dart index 1af508a..bf10670 100644 --- a/lib/models/git_model.dart +++ b/lib/models/git_model.dart @@ -100,3 +100,68 @@ class GitCommandResult { ); } } + +/// Git 提交记录与图表节点模型 +class GitCommit { + final String hash; + final String shortHash; + final List parentHashes; + final String authorName; + final String authorEmail; + final DateTime authorDate; + final String relativeDate; + final String subject; + final List refs; // e.g. ["HEAD -> main", "origin/main", "tag: v1.0.0"] + + /// 线性图表拓扑布局字段 + final int lane; // 列通道索引 (0, 1, 2...) + final List activeLanes; // 经过当前行的活跃通道列表 + final List outgoingLanes; // 当前节点连接向父节点的通道列表 + + const GitCommit({ + required this.hash, + required this.shortHash, + required this.parentHashes, + required this.authorName, + required this.authorEmail, + required this.authorDate, + required this.relativeDate, + required this.subject, + this.refs = const [], + this.lane = 0, + this.activeLanes = const [], + this.outgoingLanes = const [], + }); + + bool get isHead => refs.any((r) => r.startsWith('HEAD')); + + GitCommit copyWith({ + String? hash, + String? shortHash, + List? parentHashes, + String? authorName, + String? authorEmail, + DateTime? authorDate, + String? relativeDate, + String? subject, + List? refs, + int? lane, + List? activeLanes, + List? outgoingLanes, + }) { + return GitCommit( + hash: hash ?? this.hash, + shortHash: shortHash ?? this.shortHash, + parentHashes: parentHashes ?? this.parentHashes, + authorName: authorName ?? this.authorName, + authorEmail: authorEmail ?? this.authorEmail, + authorDate: authorDate ?? this.authorDate, + relativeDate: relativeDate ?? this.relativeDate, + subject: subject ?? this.subject, + refs: refs ?? this.refs, + lane: lane ?? this.lane, + activeLanes: activeLanes ?? this.activeLanes, + outgoingLanes: outgoingLanes ?? this.outgoingLanes, + ); + } +} diff --git a/lib/providers/git_provider.dart b/lib/providers/git_provider.dart new file mode 100644 index 0000000..a4337b3 --- /dev/null +++ b/lib/providers/git_provider.dart @@ -0,0 +1,668 @@ +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; +import '../models/git_model.dart'; +import '../services/git_service.dart'; +import '../utils/git_decoration_utils.dart'; + +/// Git 状态管理 Provider +class GitProvider extends ChangeNotifier { + final GitService _gitService; + + GitProvider({GitService? gitService}) : _gitService = gitService ?? GitService.instance; + + String? _rootPath; + List _repositories = []; + String? _currentRepoPath; + bool _gitInstalled = true; + String? _gitVersion; + bool _isLoading = false; + bool _isInitializing = false; + bool _isInstallingGit = false; + String? _errorMessage; + List _changedFiles = []; + Map _fileStatusMap = {}; + Map _dirStatusMap = {}; + String? _currentBranch; + List _branches = []; + List _tags = []; + List _commits = []; + int _stashCount = 0; + int _totalCommitsCount = 0; + int _commitsLimit = 50; + bool _isLoadingMoreCommits = false; + + // UI 内存状态缓存(保留折叠状态、输入框草稿与滚动位置) + bool _stagedExpanded = true; + bool _unstagedExpanded = true; + bool _graphExpanded = true; + bool _showTagsInSelector = false; + String _commitMessage = ''; + double _scrollOffset = 0.0; + bool _isCurrentRefTag = false; + + // Getters + GitService get gitService => _gitService; + String? get rootPath => _rootPath; + List get repositories => List.unmodifiable(_repositories); + String? get currentRepoPath => _currentRepoPath; + bool get gitInstalled => _gitInstalled; + String? get gitVersion => _gitVersion; + bool get isLoading => _isLoading; + bool get isInitializing => _isInitializing; + bool get isInstallingGit => _isInstallingGit; + String? get errorMessage => _errorMessage; + List get changedFiles => List.unmodifiable(_changedFiles); + String? get currentBranch => _currentBranch; + bool get isCurrentRefTag => _isCurrentRefTag; + List get branches => List.unmodifiable(_branches); + List get tags => List.unmodifiable(_tags); + List get commits => List.unmodifiable(_commits); + int get stashCount => _stashCount; + int get totalCommitsCount => _totalCommitsCount; + int get commitsLimit => _commitsLimit; + bool get isLoadingMoreCommits => _isLoadingMoreCommits; + bool get hasMoreCommits => _totalCommitsCount > 0 ? _commits.length < _totalCommitsCount : false; + + bool get stagedExpanded => _stagedExpanded; + bool get unstagedExpanded => _unstagedExpanded; + bool get graphExpanded => _graphExpanded; + bool get showTagsInSelector => _showTagsInSelector; + String get commitMessage => _commitMessage; + double get scrollOffset => _scrollOffset; + + void setStagedExpanded(bool val) => _stagedExpanded = val; + void setUnstagedExpanded(bool val) => _unstagedExpanded = val; + void setGraphExpanded(bool val) => _graphExpanded = val; + void setShowTagsInSelector(bool val) => _showTagsInSelector = val; + void setCommitMessage(String val) => _commitMessage = val; + void setScrollOffset(double val) => _scrollOffset = val; + + bool get hasProject => _rootPath != null && _rootPath!.trim().isNotEmpty; + bool get hasRepository => _repositories.isNotEmpty; + bool get isGitRepo => hasRepository; + + GitRepositoryInfo? get currentRepo { + if (_currentRepoPath == null) return null; + return _repositories.where((r) => r.rootPath == _currentRepoPath).firstOrNull; + } + + /// 暂存区文件列表 + List get stagedFiles => _changedFiles.where((f) => f.isStaged).toList(); + + /// 未暂存文件列表(含修改与未跟踪) + List get unstagedFiles => _changedFiles.where((f) => !f.isStaged).toList(); + + /// 总变动文件数量(供活动栏与角标展示) + int get totalChangedCount => _changedFiles.length; + + /// 根据文件绝对路径或相对路径 O(1) 获取 Git 变更状态(用于文件树文件名染色与字母标识) + GitFileStatus? getFileStatus(String filePath) { + if (_fileStatusMap.isEmpty) return null; + final normalized = p.normalize(filePath); + final direct = _fileStatusMap[normalized]; + if (direct != null) return direct; + return _fileStatusMap[normalized.toLowerCase()]; + } + + /// 根据目录绝对路径 O(1) 获取最高优先级 Git 变更状态类别(用于文件夹名称染色与彩色圆点) + GitFileStatusType? getDirectoryStatus(String dirPath) { + if (_dirStatusMap.isEmpty) return null; + final normalized = p.normalize(dirPath); + final direct = _dirStatusMap[normalized]; + if (direct != null) return direct; + return _dirStatusMap[normalized.toLowerCase()]; + } + + /// 绑定项目根路径(响应 ProjectProvider 切换) + void bindRootPath(String? newRootPath) { + final normalized = newRootPath != null && newRootPath.trim().isNotEmpty + ? p.normalize(newRootPath.trim()) + : null; + + if (_rootPath != normalized) { + _rootPath = normalized; + _repositories = []; + _currentRepoPath = null; + _changedFiles = []; + _rebuildStatusMaps(); + _currentBranch = null; + _branches = []; + _tags = []; + _commits = []; + _stashCount = 0; + _errorMessage = null; + + if (_rootPath != null) { + refresh(); + } else { + notifyListeners(); + } + } + } + + int _refreshSeq = 0; + + /// 刷新 Git 状态与仓库信息 + Future refresh() async { + final seq = ++_refreshSeq; + + if (_rootPath == null || _rootPath!.isEmpty) { + _repositories = []; + _currentRepoPath = null; + _changedFiles = []; + _rebuildStatusMaps(); + _currentBranch = null; + _branches = []; + _tags = []; + _commits = []; + _stashCount = 0; + _isLoading = false; + notifyListeners(); + return; + } + + _isLoading = true; + _errorMessage = null; + notifyListeners(); + + try { + // 1. 校验 Git 命令行工具环境 + final env = await _gitService.checkGitInstalled(); + if (seq != _refreshSeq) return; + + _gitInstalled = env.isInstalled; + _gitVersion = env.version; + if (!env.isInstalled) { + _errorMessage = env.errorMessage ?? '未检测到 Git 命令行工具'; + _isLoading = false; + notifyListeners(); + return; + } + + // 2. 探测工程根目录及子目录下的仓库列表 + final detected = await _gitService.detectRepositories(_rootPath!); + if (seq != _refreshSeq) return; + + _repositories = detected; + + // 3. 确定当前活跃选中的仓库 + if (_repositories.isNotEmpty) { + // 如果当前没有选中或先前选中的已不存在,优先选根仓库,否则选第 1 个 + if (_currentRepoPath == null || !_repositories.any((r) => r.rootPath == _currentRepoPath)) { + final rootRepo = _repositories.where((r) => r.isRoot).firstOrNull; + _currentRepoPath = rootRepo != null ? rootRepo.rootPath : _repositories.first.rootPath; + } + + // 4. 加载当前活跃仓库的状态与分支 + await _loadCurrentRepoDetails(); + if (seq != _refreshSeq) return; + } else { + _currentRepoPath = null; + _changedFiles = []; + _rebuildStatusMaps(); + _currentBranch = null; + } + } catch (e) { + if (seq == _refreshSeq) { + _errorMessage = '加载 Git 状态异常: $e'; + } + } finally { + if (seq == _refreshSeq) { + _isLoading = false; + notifyListeners(); + } + } + } + + /// 切换当前选中的活跃仓库 + Future switchRepository(String repoPath) async { + final normalized = p.normalize(repoPath); + if (_currentRepoPath == normalized) return; + + if (_repositories.any((r) => r.rootPath == normalized)) { + _currentRepoPath = normalized; + _isLoading = true; + notifyListeners(); + + await _loadCurrentRepoDetails(); + + _isLoading = false; + notifyListeners(); + } + } + + /// 初始化本地 Git 仓库 + Future initRepository({ + String? targetPath, + String defaultBranch = 'main', + }) async { + final path = targetPath ?? _rootPath; + if (path == null || path.isEmpty) { + return GitCommandResult.error('未指定有效的仓库初始化路径'); + } + + _isInitializing = true; + _errorMessage = null; + notifyListeners(); + + try { + final result = await _gitService.initRepository( + path, + defaultBranch: defaultBranch, + ); + + if (result.success) { + // 初始化成功后自动重新扫描并选中该仓库 + await refresh(); + } else { + _errorMessage = result.stderr.isNotEmpty ? result.stderr : '初始化 Git 仓库失败'; + } + + return result; + } catch (e) { + _errorMessage = '初始化异常: $e'; + return GitCommandResult.error(e.toString()); + } finally { + _isInitializing = false; + notifyListeners(); + } + } + + /// 安装 Git + Future installGit({void Function(String output)? onProgress}) async { + _isInstallingGit = true; + _errorMessage = null; + notifyListeners(); + + try { + final result = await _gitService.installGit(onProgress: onProgress); + if (result.success) { + await refresh(); + } else { + _errorMessage = result.stderr.isNotEmpty ? result.stderr : '安装 Git 失败'; + } + return result; + } catch (e) { + _errorMessage = '安装 Git 异常: $e'; + return GitCommandResult.error(e.toString()); + } finally { + _isInstallingGit = false; + notifyListeners(); + } + } + + /// 暂存指定文件 + Future stageFile(String relativePath) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.stageFile(_currentRepoPath!, relativePath); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 取消暂存指定文件 + Future unstageFile(String relativePath) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.unstageFile(_currentRepoPath!, relativePath); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 全部暂存 + Future stageAll() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.stageAll(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 全部取消暂存 + Future unstageAll() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.unstageAll(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 放弃单个文件的更改 + Future discardFile(GitFileStatus file) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final isUntracked = file.statusType == GitFileStatusType.untracked; + final res = await _gitService.discardFile( + _currentRepoPath!, + file.relativePath, + isUntracked: isUntracked, + isStaged: file.isStaged, + ); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 全部放弃未暂存更改 + Future discardAllUnstaged() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.discardAllUnstaged(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 全部放弃已暂存更改 + Future discardAllStaged() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.discardAllStaged(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 提交当前暂存区的更改 + Future commit(String message, {bool amend = false}) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.commit(_currentRepoPath!, message, amend: amend); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 切换分支 + Future switchBranch(String branchName) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.checkoutBranch(_currentRepoPath!, branchName); + if (res.success) { + _currentBranch = branchName; + _isCurrentRefTag = false; + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 创建并可选检出新分支 + Future createBranch(String branchName, {bool checkout = true}) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.createBranch(_currentRepoPath!, branchName, checkout: checkout); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 删除本地分支 + Future deleteBranch(String branchName, {bool force = false}) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.deleteBranch(_currentRepoPath!, branchName, force: force); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 撤销上一次提交 + Future undoLastCommit() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.undoLastCommit(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 贮藏当前更改 + Future stash({String? message}) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.stash(_currentRepoPath!, message: message); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 恢复最近贮藏 + Future stashPop() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.stashPop(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 添加文件到 .gitignore + Future addToGitignore(String relativePath) async { + if (_currentRepoPath == null) return false; + final success = await _gitService.addToGitignore(_currentRepoPath!, relativePath); + if (success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return success; + } + + /// 创建新标签 + Future createTag(String tagName, {String? message}) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.createTag(_currentRepoPath!, tagName, message: message); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 删除本地标签 + Future deleteTag(String tagName) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.deleteTag(_currentRepoPath!, tagName); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 检出指定标签 + Future switchTag(String tagName) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.checkoutTag(_currentRepoPath!, tagName); + if (res.success) { + _currentBranch = tagName; + _isCurrentRefTag = true; + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 分页加载更多提交历史 + Future loadMoreCommits({int count = 50}) async { + if (_currentRepoPath == null || _isLoadingMoreCommits) return; + _isLoadingMoreCommits = true; + notifyListeners(); + try { + _commitsLimit += count; + _commits = await _gitService.getLog(_currentRepoPath!, maxCount: _commitsLimit); + if (_commits.length > _totalCommitsCount) { + _totalCommitsCount = _commits.length; + } + } catch (e) { + debugPrint('[GitProvider] 加载更多提交异常: $e'); + } finally { + _isLoadingMoreCommits = false; + notifyListeners(); + } + } + + /// 全量加载所有提交历史并解除分页限制 + Future loadAllCommits() async { + if (_currentRepoPath == null || _isLoadingMoreCommits) return; + _isLoadingMoreCommits = true; + notifyListeners(); + try { + final target = _totalCommitsCount > 0 ? _totalCommitsCount : 2000; + _commitsLimit = target; + _commits = await _gitService.getLog(_currentRepoPath!, maxCount: _commitsLimit); + _totalCommitsCount = _commits.length; + } catch (e) { + debugPrint('[GitProvider] 全量加载提交异常: $e'); + } finally { + _isLoadingMoreCommits = false; + notifyListeners(); + } + } + + /// 内部辅助:加载当前仓库的分支、提交历史与文件变更列表 + Future _loadCurrentRepoDetails() async { + if (_currentRepoPath == null) return; + try { + final refInfo = await _gitService.getCurrentRefInfo(_currentRepoPath!); + _currentBranch = refInfo.name; + _isCurrentRefTag = refInfo.isTag; + _branches = await _gitService.getLocalBranches(_currentRepoPath!); + _tags = await _gitService.getTags(_currentRepoPath!); + _changedFiles = await _gitService.getGitStatus(_currentRepoPath!); + _rebuildStatusMaps(); + _commitsLimit = 50; + _totalCommitsCount = await _gitService.getTotalCommitsCount(_currentRepoPath!); + _commits = await _gitService.getLog(_currentRepoPath!, maxCount: _commitsLimit); + if (_commits.length > _totalCommitsCount) { + _totalCommitsCount = _commits.length; + } + _stashCount = await _gitService.getStashCount(_currentRepoPath!); + + // 同步更新 repositories 列表中当前项的分支信息 + final idx = _repositories.indexWhere((r) => r.rootPath == _currentRepoPath); + if (idx != -1) { + _repositories[idx] = _repositories[idx].copyWith(currentBranch: _currentBranch); + } + } catch (e) { + debugPrint('[GitProvider] 加载仓库详情异常: $e'); + } + } + + /// 预先计算文件和目录的 Git 状态映射,将文件树每帧查询时间复杂度从 O(N*M) 降至 O(1) + void _rebuildStatusMaps() { + final fileMap = {}; + final dirMap = {}; + + for (final file in _changedFiles) { + final normalizedFilePath = p.normalize(file.path); + fileMap[normalizedFilePath] = file; + fileMap[normalizedFilePath.toLowerCase()] = file; + + // 自底向上聚合所有祖先目录状态(高优先级覆盖低优先级) + var currentDir = p.dirname(normalizedFilePath); + while (currentDir.isNotEmpty && currentDir != '.' && currentDir != p.dirname(currentDir)) { + final currentType = dirMap[currentDir]; + if (currentType == null || + GitDecorationUtils.getPriority(file.statusType) > + GitDecorationUtils.getPriority(currentType)) { + dirMap[currentDir] = file.statusType; + dirMap[currentDir.toLowerCase()] = file.statusType; + } + + // 避免向上越界超出仓库根目录或项目根目录 + if (_currentRepoPath != null && + (currentDir == p.normalize(_currentRepoPath!) || + currentDir.toLowerCase() == p.normalize(_currentRepoPath!).toLowerCase())) { + break; + } + if (_rootPath != null && + (currentDir == p.normalize(_rootPath!) || + currentDir.toLowerCase() == p.normalize(_rootPath!).toLowerCase())) { + break; + } + final parent = p.dirname(currentDir); + if (parent == currentDir) break; + currentDir = parent; + } + } + + _fileStatusMap = fileMap; + _dirStatusMap = dirMap; + } + + /// 测试辅助方法 + @visibleForTesting + void setStateForTesting({ + String? rootPath, + List? repositories, + String? currentRepoPath, + bool? gitInstalled, + bool? isLoading, + bool? isInitializing, + List? changedFiles, + String? currentBranch, + bool? isCurrentRefTag, + List? branches, + List? tags, + List? commits, + int? stashCount, + int? totalCommitsCount, + int? commitsLimit, + String? errorMessage, + bool? stagedExpanded, + bool? unstagedExpanded, + bool? graphExpanded, + bool? showTagsInSelector, + String? commitMessage, + double? scrollOffset, + }) { + if (rootPath != null) _rootPath = rootPath; + if (repositories != null) _repositories = repositories; + if (currentRepoPath != null) _currentRepoPath = currentRepoPath; + if (gitInstalled != null) _gitInstalled = gitInstalled; + if (isLoading != null) _isLoading = isLoading; + if (isInitializing != null) _isInitializing = isInitializing; + if (changedFiles != null) { + _changedFiles = changedFiles; + _rebuildStatusMaps(); + } + if (currentBranch != null) _currentBranch = currentBranch; + if (isCurrentRefTag != null) _isCurrentRefTag = isCurrentRefTag; + if (branches != null) _branches = branches; + if (tags != null) _tags = tags; + if (commits != null) { + _commits = commits; + if (totalCommitsCount == null) { + _totalCommitsCount = commits.length; + } + } + if (stashCount != null) _stashCount = stashCount; + if (totalCommitsCount != null) _totalCommitsCount = totalCommitsCount; + if (commitsLimit != null) _commitsLimit = commitsLimit; + if (errorMessage != null) _errorMessage = errorMessage; + if (stagedExpanded != null) _stagedExpanded = stagedExpanded; + if (unstagedExpanded != null) _unstagedExpanded = unstagedExpanded; + if (graphExpanded != null) _graphExpanded = graphExpanded; + if (showTagsInSelector != null) _showTagsInSelector = showTagsInSelector; + if (commitMessage != null) _commitMessage = commitMessage; + if (scrollOffset != null) _scrollOffset = scrollOffset; + notifyListeners(); + } +} diff --git a/lib/providers/search_provider.dart b/lib/providers/search_provider.dart index feb68c5..5f89d01 100644 --- a/lib/providers/search_provider.dart +++ b/lib/providers/search_provider.dart @@ -38,6 +38,22 @@ class SearchProvider extends ChangeNotifier { notifyListeners(); } + /// 一键解除分页限制,加载/展示全部匹配文件 + void loadAllFiles() { + if (_result.fileResults.isNotEmpty) { + _displayedFilesLimit = _result.fileResults.length; + notifyListeners(); + } + } + + /// 展开指定文件并加载展示其全部匹配行 + void expandAndLoadAllMatchesForFile(FileSearchResult fileResult) { + fileResult.isExpanded = true; + _fileExpandedStates[fileResult.filePath] = true; + _displayedMatchesLimits[fileResult.filePath] = fileResult.matches.length; + notifyListeners(); + } + int getFileMatchesLimit(String filePath, int defaultSize) { return _displayedMatchesLimits[filePath] ?? defaultSize; } diff --git a/lib/providers/tab_provider.dart b/lib/providers/tab_provider.dart index 23a9a43..54c2376 100644 --- a/lib/providers/tab_provider.dart +++ b/lib/providers/tab_provider.dart @@ -1,6 +1,7 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/editor_tab_item.dart'; import 'package:code_editor/models/file_item.dart'; +import 'package:code_editor/providers/git_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/services/project_history_service.dart'; import 'package:code_editor/services/file_service.dart'; @@ -74,6 +75,12 @@ class TabProvider extends ChangeNotifier { projectProvider.onExternalFileDeleted = handleExternalFileDeleted; } + GitProvider? _gitProvider; + + void bindGitProvider(GitProvider gitProvider) { + _gitProvider = gitProvider; + } + bool isFileSelected(String path) { if (_activeFilePath == null) return false; return p.equals(_activeFilePath!, path); @@ -451,6 +458,7 @@ class TabProvider extends ChangeNotifier { tab.originalContent = tab.content; tab.isModified = false; _isModified = false; + _gitProvider?.refresh(); notifyListeners(); } return ok; @@ -462,6 +470,7 @@ class TabProvider extends ChangeNotifier { if (_activeFilePath != null && p.equals(tab.path, _activeFilePath!)) { _isModified = false; } + _gitProvider?.refresh(); notifyListeners(); return true; } catch (e) { diff --git a/lib/services/background_task/apt_package_task.dart b/lib/services/background_task/apt_package_task.dart index 949d05c..0a3fda2 100644 --- a/lib/services/background_task/apt_package_task.dart +++ b/lib/services/background_task/apt_package_task.dart @@ -2,6 +2,7 @@ import '../../models/distro_manifest.dart'; import '../../models/notice_item.dart'; import '../distro_manager.dart'; import '../internal_engine_service.dart'; +import '../toolchain_service.dart'; import 'background_task.dart'; /// Ubuntu APT 软件包安装与卸载任务 @@ -74,12 +75,10 @@ class AptPackageTask extends BackgroundTask { final rootfs = await engine.getRootfsDir(); final cmd = isUninstall - ? 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; ' - 'dpkg --configure -a 2>/dev/null || true; ' + ? '${ToolchainService.dpkgAutoHealPrefix} ' 'apt-get remove --purge -y ${packageName.trim()} && ' 'apt-get autoremove -y' - : 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; ' - 'dpkg --configure -a 2>/dev/null || true; ' + : '${ToolchainService.dpkgAutoHealPrefix} ' 'apt-get update && ' 'apt-get install -y --no-install-recommends ${packageName.trim()}'; diff --git a/lib/services/git_service.dart b/lib/services/git_service.dart new file mode 100644 index 0000000..90db3e7 --- /dev/null +++ b/lib/services/git_service.dart @@ -0,0 +1,1084 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; +import '../models/distro_manifest.dart'; +import '../models/git_model.dart'; +import 'distro_manager.dart'; +import 'internal_engine_service.dart'; +import 'toolchain_service.dart'; + +/// Git 运行环境状态 +class GitEnvironmentStatus { + final bool isInstalled; + final String? version; + final String? errorMessage; + + const GitEnvironmentStatus({ + required this.isInstalled, + this.version, + this.errorMessage, + }); +} + +/// Git 核心服务层(单例模式,封装底层命令行交互与文件系统快速探测) +class GitService { + static final GitService instance = GitService._internal(); + GitService._internal(); + + /// 允许在测试环境下自定义或注入命令处理器 + @visibleForTesting + Future Function(String executable, List arguments, {String? workingDirectory})? + processRunner; + + /// 自定义 Git 可执行程序路径(默认从系统 PATH 查找 'git') + String gitExecutable = 'git'; + + /// 缓存的 Git 环境可用状态 + GitEnvironmentStatus? _cachedEnvStatus; + + /// 重置测试环境状态与进程注入 + void resetForTesting() { + processRunner = null; + _cachedEnvStatus = null; + } + + /// 快速检查系统或容器中是否存在 Git 命令行工具 + Future checkGitInstalled({bool forceRefresh = false}) async { + if (!forceRefresh && _cachedEnvStatus != null) { + return _cachedEnvStatus!; + } + + // 1. 如果测试环境注入了 processRunner,优先走注入的 runner + if (processRunner != null) { + try { + final res = await processRunner!(gitExecutable, ['--version']); + if (res.exitCode == 0) { + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: true, + version: res.stdout.toString().trim(), + ); + } else { + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: false, + errorMessage: res.stderr.toString().trim(), + ); + } + return _cachedEnvStatus!; + } catch (e) { + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: false, + errorMessage: e.toString(), + ); + return _cachedEnvStatus!; + } + } + + // 2. Android 真实设备环境:双重探测机制(优先探测内置 Ubuntu 容器环境) + if (Platform.isAndroid) { + final engine = InternalEngineService.instance; + if (await engine.isEngineInstalled()) { + final rootfs = await engine.getRootfsDir(); + // 物理根文件系统快速探测(毫秒级,直接检测 /usr/bin/git 等文件物理存在) + final physicallyInstalled = ToolchainService.isToolInstalledInRootfs(rootfs, 'git'); + if (!physicallyInstalled) { + _cachedEnvStatus = const GitEnvironmentStatus( + isInstalled: false, + errorMessage: '内置开发环境尚未安装 Git', + ); + return _cachedEnvStatus!; + } + + // 物理存在,进一步尝试在容器中执行 git --version 获取详细版本字符串 + try { + final res = await _runProcess(gitExecutable, ['--version']); + if (res.exitCode == 0) { + final versionStr = res.stdout.toString().trim(); + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: true, + version: versionStr.isNotEmpty ? versionStr : 'git (installed)', + ); + } else { + // 物理文件已在 rootfs 中,即便进程拉取临时异常也确凿判定为已安装 + _cachedEnvStatus = const GitEnvironmentStatus( + isInstalled: true, + version: 'git (installed in engine)', + ); + } + } catch (_) { + _cachedEnvStatus = const GitEnvironmentStatus( + isInstalled: true, + version: 'git (installed in engine)', + ); + } + + // 异步确保配置 safe.directory 与默认用户信息 + ensureGitUserConfigured(); + + return _cachedEnvStatus!; + } else { + _cachedEnvStatus = const GitEnvironmentStatus( + isInstalled: false, + errorMessage: '内置开发引擎尚未初始化', + ); + return _cachedEnvStatus!; + } + } + + // 3. 桌面平台 (Windows / macOS / Linux) 标准 PATH 检测 + try { + final res = await _runProcess(gitExecutable, ['--version']); + if (res.exitCode == 0) { + final versionStr = res.stdout.toString().trim(); + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: true, + version: versionStr, + ); + return _cachedEnvStatus!; + } else { + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: false, + errorMessage: res.stderr.toString().trim(), + ); + return _cachedEnvStatus!; + } + } on ProcessException catch (e) { + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: false, + errorMessage: e.message, + ); + return _cachedEnvStatus!; + } catch (e) { + _cachedEnvStatus = GitEnvironmentStatus( + isInstalled: false, + errorMessage: e.toString(), + ); + return _cachedEnvStatus!; + } + } + + /// 自动确保 Git 基础配置就绪(safe.directory 豁免 + 默认提交者占位符) + Future ensureGitUserConfigured() async { + try { + await _runProcess('git', ['config', '--global', '--add', 'safe.directory', '*']); + final nameCheck = await _runProcess('git', ['config', '--global', 'user.name']); + if (nameCheck.stdout.toString().trim().isEmpty) { + await _runProcess('git', ['config', '--global', 'user.name', 'CodeEditor User']); + } + final emailCheck = await _runProcess('git', ['config', '--global', 'user.email']); + if (emailCheck.stdout.toString().trim().isEmpty) { + await _runProcess('git', ['config', '--global', 'user.email', 'user@codeeditor.local']); + } + } catch (_) {} + } + + /// 统一安全的 Git 命令执行封装 + Future runGitCommand( + List args, { + required String workingDir, + Duration timeout = const Duration(seconds: 30), + }) async { + final env = await checkGitInstalled(); + if (!env.isInstalled) { + return GitCommandResult.error( + env.errorMessage ?? '未检测到 Git 命令行工具,请先在系统或容器中安装 git', + ); + } + + try { + final res = await _runProcess( + gitExecutable, + args, + workingDirectory: workingDir, + ).timeout(timeout, onTimeout: () { + throw ProcessException( + gitExecutable, + args, + 'Git 命令执行超时 (${timeout.inSeconds}s)', + -1, + ); + }); + + final stdout = res.stdout.toString(); + final stderr = res.stderr.toString(); + return GitCommandResult( + success: res.exitCode == 0, + exitCode: res.exitCode, + stdout: stdout, + stderr: stderr, + ); + } on ProcessException catch (e) { + return GitCommandResult.error(e.message, exitCode: e.errorCode); + } catch (e) { + return GitCommandResult.error(e.toString()); + } + } + + /// 快速检查指定目录是否为 Git 仓库(轻量级文件系统探测,无进程开销) + bool isGitRepository(String dirPath) { + try { + final dotGit = p.join(dirPath, '.git'); + return Directory(dotGit).existsSync() || File(dotGit).existsSync(); + } catch (_) { + return false; + } + } + + /// 探测工作区中存在的所有 Git 仓库(支持主仓库与子模块/嵌套仓库) + Future> detectRepositories( + String rootPath, { + int maxDepth = 2, + }) async { + final normalizedRoot = p.normalize(rootPath); + final List repos = []; + + // 1. 首先检查工程根目录自身是否是 Git 仓库 + if (isGitRepository(normalizedRoot)) { + final branch = await getCurrentBranch(normalizedRoot); + repos.add(GitRepositoryInfo( + rootPath: normalizedRoot, + name: p.basename(normalizedRoot).isEmpty ? normalizedRoot : p.basename(normalizedRoot), + isRoot: true, + currentBranch: branch, + )); + } + + // 2. 浅层递归扫描子目录中的嵌套仓库或子模块 (Submodules) + final rootDir = Directory(normalizedRoot); + if (rootDir.existsSync()) { + await _scanSubRepositories(rootDir, normalizedRoot, 1, maxDepth, repos); + } + + return repos; + } + + /// 递归扫描子仓库 + Future _scanSubRepositories( + Directory dir, + String rootPath, + int currentDepth, + int maxDepth, + List outRepos, + ) async { + if (currentDepth > maxDepth) return; + + try { + final entries = dir.listSync(followLinks: false); + for (final entry in entries) { + if (entry is! Directory) continue; + final name = p.basename(entry.path); + + // 跳过高频临时、依赖与隐藏目录 + if (name.startsWith('.') || + name == 'node_modules' || + name == 'build' || + name == '.dart_tool' || + name == 'Pods' || + name == 'DerivedData' || + name == 'target') { + continue; + } + + final subPath = p.normalize(entry.path); + if (isGitRepository(subPath)) { + final branch = await getCurrentBranch(subPath); + final relativeName = p.relative(subPath, from: rootPath); + final info = GitRepositoryInfo( + rootPath: subPath, + name: relativeName, + isRoot: false, + currentBranch: branch, + ); + if (!outRepos.contains(info)) { + outRepos.add(info); + } + } else { + // 未发现 .git 则继续向下探测一层 + await _scanSubRepositories(entry, rootPath, currentDepth + 1, maxDepth, outRepos); + } + } + } catch (_) {} + } + + /// 初始化本地 Git 仓库 + Future initRepository( + String path, { + String defaultBranch = 'main', + }) async { + final targetDir = Directory(path); + if (!targetDir.existsSync()) { + try { + targetDir.createSync(recursive: true); + } catch (e) { + return GitCommandResult.error('创建仓库目录失败: $e'); + } + } + + // 尝试带 -b 参数直接初始化默认分支名 + var result = await runGitCommand( + ['init', '-b', defaultBranch], + workingDir: path, + ); + + // 如果 Git 版本较老不支持 init -b,退化为普通 init 并重命名/创建分支 + if (!result.success && result.stderr.contains('unknown switch `b\'')) { + result = await runGitCommand(['init'], workingDir: path); + if (result.success) { + await runGitCommand(['checkout', '-b', defaultBranch], workingDir: path); + } + } + + return result; + } + + /// 安装 Git + Future installGit({ + void Function(String output)? onProgress, + }) async { + // 1. 如果设置了测试注入的 processRunner + if (processRunner != null) { + final res = await _runProcess(gitExecutable, ['install-git']); + if (res.exitCode == 0) { + _cachedEnvStatus = null; + await checkGitInstalled(forceRefresh: true); + return GitCommandResult( + success: true, + exitCode: 0, + stdout: res.stdout.toString(), + stderr: '', + ); + } else { + return GitCommandResult.error( + res.stderr.toString().isNotEmpty ? res.stderr.toString() : '安装 Git 失败', + exitCode: res.exitCode, + ); + } + } + + // 2. 内置引擎环境安装 (Ubuntu PRoot) + final engine = InternalEngineService.instance; + if (await engine.isEngineInstalled()) { + final success = await engine.installPackage('git', onOutput: onProgress); + if (success) { + _cachedEnvStatus = null; + final env = await checkGitInstalled(forceRefresh: true); + if (env.isInstalled) { + await ensureGitUserConfigured(); + return const GitCommandResult( + success: true, + exitCode: 0, + stdout: 'Git 安装成功', + stderr: '', + ); + } + } + return GitCommandResult.error('通过引擎安装 Git 失败'); + } + + // 3. 宿主 Linux / Termux 环境下尝试通过包管理器安装 + if (!Platform.isWindows && !Platform.isIOS) { + try { + final res = await Process.run( + 'apt-get', + ['install', '-y', 'git'], + runInShell: true, + ); + if (res.exitCode == 0) { + _cachedEnvStatus = null; + await checkGitInstalled(forceRefresh: true); + return GitCommandResult( + success: true, + exitCode: 0, + stdout: res.stdout.toString(), + stderr: '', + ); + } + } catch (_) {} + } + + return GitCommandResult.error('当前环境不支持自动安装 Git,请在内置引擎或终端中手动安装'); + } + + /// 获取仓库当前检出信息(分支名或标签名,以及是否为标签) + Future<({String name, bool isTag})> getCurrentRefInfo(String repoPath) async { + // 优先尝试从 git 命令行获取当前分支 + final res = await runGitCommand( + ['branch', '--show-current'], + workingDir: repoPath, + ); + if (res.success && res.stdout.trim().isNotEmpty) { + return (name: res.stdout.trim(), isTag: false); + } + + // 尝试检查 HEAD 是否精确匹配某个本地/远程标签 + final tagRes = await runGitCommand( + ['describe', '--tags', '--exact-match', 'HEAD'], + workingDir: repoPath, + ); + if (tagRes.success && tagRes.stdout.trim().isNotEmpty) { + return (name: tagRes.stdout.trim(), isTag: true); + } + + // 尝试 symbolic-ref + final symRes = await runGitCommand( + ['symbolic-ref', '--short', 'HEAD'], + workingDir: repoPath, + ); + if (symRes.success && symRes.stdout.trim().isNotEmpty) { + return (name: symRes.stdout.trim(), isTag: false); + } + + // 针对新初始化尚未进行任何 commit 的空仓库,命令行可能返回空,直接从 .git/HEAD 文件解析 + try { + final headFile = File(p.join(repoPath, '.git', 'HEAD')); + if (headFile.existsSync()) { + final content = headFile.readAsStringSync().trim(); + if (content.startsWith('ref: refs/heads/')) { + return (name: content.substring('ref: refs/heads/'.length).trim(), isTag: false); + } + } + } catch (_) {} + + // 尝试获取 Detached HEAD 哈希 + final revRes = await runGitCommand( + ['rev-parse', '--short', 'HEAD'], + workingDir: repoPath, + ); + if (revRes.success && revRes.stdout.trim().isNotEmpty) { + return (name: 'detached (${revRes.stdout.trim()})', isTag: false); + } + + return (name: 'main', isTag: false); + } + + /// 获取仓库当前分支名称(兼容新建未提交仓库从 .git/HEAD 兜底解析) + Future getCurrentBranch(String repoPath) async { + final info = await getCurrentRefInfo(repoPath); + return info.name; + } + + /// 获取本地分支列表 + Future> getLocalBranches(String repoPath) async { + final res = await runGitCommand( + ['branch', '--format=%(refname:short)'], + workingDir: repoPath, + ); + if (!res.success) { + final fbRes = await runGitCommand(['branch'], workingDir: repoPath); + if (!fbRes.success) return []; + return LineSplitter.split(fbRes.stdout) + .map((line) => line.replaceAll('*', '').trim()) + .where((name) => name.isNotEmpty) + .toList(); + } + return LineSplitter.split(res.stdout) + .map((s) => s.trim()) + .where((s) => s.isNotEmpty) + .toList(); + } + + /// 切换分支 (`git checkout `) + Future checkoutBranch(String repoPath, String branchName) async { + return runGitCommand(['checkout', branchName], workingDir: repoPath); + } + + /// 创建新分支 (`git checkout -b ` 或 `git branch `) + Future createBranch( + String repoPath, + String branchName, { + bool checkout = true, + }) async { + if (checkout) { + return runGitCommand(['checkout', '-b', branchName], workingDir: repoPath); + } else { + return runGitCommand(['branch', branchName], workingDir: repoPath); + } + } + + /// 删除本地分支 (`git branch -d` / `-D`) + Future deleteBranch( + String repoPath, + String branchName, { + bool force = false, + }) async { + return runGitCommand( + ['branch', force ? '-D' : '-d', branchName], + workingDir: repoPath, + ); + } + + /// 获取本地标签列表 (`git tag -l`) + Future> getTags(String repoPath) async { + final res = await runGitCommand(['tag', '-l'], workingDir: repoPath); + if (!res.success || res.stdout.trim().isEmpty) return []; + return LineSplitter.split(res.stdout) + .map((s) => s.trim()) + .where((s) => s.isNotEmpty) + .toList(); + } + + /// 创建标签 (`git tag ` 或 `git tag -a -m `) + Future createTag( + String repoPath, + String tagName, { + String? message, + }) async { + if (tagName.trim().isEmpty) { + return GitCommandResult.error('标签名称不能为空'); + } + final cleanName = tagName.trim(); + if (message != null && message.trim().isNotEmpty) { + return runGitCommand(['tag', '-a', cleanName, '-m', message.trim()], workingDir: repoPath); + } + return runGitCommand(['tag', cleanName], workingDir: repoPath); + } + + /// 删除本地标签 (`git tag -d `) + Future deleteTag(String repoPath, String tagName) async { + return runGitCommand(['tag', '-d', tagName.trim()], workingDir: repoPath); + } + + /// 检出指定标签 (`git checkout `) + Future checkoutTag(String repoPath, String tagName) async { + return runGitCommand(['checkout', tagName.trim()], workingDir: repoPath); + } + + /// 获取仓库当前工作区变更状态列表 (git status --porcelain -uall) + Future> getGitStatus(String repoPath) async { + final result = await runGitCommand( + ['status', '--porcelain', '-uall'], + workingDir: repoPath, + ); + + if (!result.success) { + return []; + } + + final lines = LineSplitter.split(result.stdout); + final List items = []; + + for (final line in lines) { + if (line.length < 4) continue; + final x = line[0]; + final y = line[1]; + final pathPart = line.substring(3).trim(); + + String rawPath = pathPart; + String? originalPath; + if (pathPart.contains(' -> ')) { + final parts = pathPart.split(' -> '); + originalPath = _unquote(parts[0].trim()); + rawPath = _unquote(parts[1].trim()); + } else { + rawPath = _unquote(rawPath); + } + + final fullPath = p.normalize(p.join(repoPath, rawPath)); + + // 暂存区状态 (Index / Staged) + if (x != ' ' && x != '?' && x != '!') { + items.add(GitFileStatus( + path: fullPath, + relativePath: rawPath, + statusType: _mapStatusCode(x), + isStaged: true, + originalPath: originalPath, + )); + } + + // 工作区未暂存状态 (Worktree / Unstaged) + if (y != ' ' && y != '?' && y != '!') { + items.add(GitFileStatus( + path: fullPath, + relativePath: rawPath, + statusType: _mapStatusCode(y), + isStaged: false, + originalPath: originalPath, + )); + } + + // 未跟踪文件 (Untracked ??) + if (x == '?' && y == '?') { + items.add(GitFileStatus( + path: fullPath, + relativePath: rawPath, + statusType: GitFileStatusType.untracked, + isStaged: false, + )); + } + } + + return items; + } + + /// 暂存单个文件的更改 (`git add -- `) + Future stageFile(String repoPath, String relativePath) async { + return runGitCommand(['add', '--', relativePath], workingDir: repoPath); + } + + /// 取消暂存单个文件的更改 (`git restore --staged` / `git reset HEAD`) + Future unstageFile(String repoPath, String relativePath) async { + final res = await runGitCommand( + ['restore', '--staged', '--', relativePath], + workingDir: repoPath, + ); + if (res.success) return res; + + // 针对老版本 Git 退化回退使用 reset HEAD + return runGitCommand(['reset', 'HEAD', '--', relativePath], workingDir: repoPath); + } + + /// 全部暂存所有更改 (`git add -A`) + Future stageAll(String repoPath) async { + return runGitCommand(['add', '-A'], workingDir: repoPath); + } + + /// 全部取消暂存所有更改 (`git restore --staged .` / `git reset HEAD`) + Future unstageAll(String repoPath) async { + final res = await runGitCommand(['restore', '--staged', '.'], workingDir: repoPath); + if (res.success) return res; + + // 针对老版本 Git 退化回退使用 reset HEAD + return runGitCommand(['reset', 'HEAD'], workingDir: repoPath); + } + + /// 放弃单个文件的更改 (`git restore` / `git checkout` 或未跟踪物理删除) + Future discardFile( + String repoPath, + String relativePath, { + required bool isUntracked, + bool isStaged = false, + }) async { + if (isUntracked) { + final fullPath = p.normalize(p.join(repoPath, relativePath)); + try { + final file = File(fullPath); + if (file.existsSync()) { + file.deleteSync(); + return const GitCommandResult(success: true, exitCode: 0, stdout: 'Deleted', stderr: ''); + } + final dir = Directory(fullPath); + if (dir.existsSync()) { + dir.deleteSync(recursive: true); + return const GitCommandResult(success: true, exitCode: 0, stdout: 'Deleted', stderr: ''); + } + return const GitCommandResult(success: true, exitCode: 0, stdout: '', stderr: ''); + } catch (e) { + return GitCommandResult.error('删除未跟踪文件失败: $e'); + } + } + + if (isStaged) { + var res = await runGitCommand(['restore', '--staged', '--worktree', '--', relativePath], workingDir: repoPath); + if (res.success) return res; + await runGitCommand(['restore', '--staged', '--', relativePath], workingDir: repoPath); + await runGitCommand(['reset', 'HEAD', '--', relativePath], workingDir: repoPath); + res = await runGitCommand(['restore', '--', relativePath], workingDir: repoPath); + if (res.success) return res; + return runGitCommand(['checkout', '--', relativePath], workingDir: repoPath); + } + + // 已跟踪未暂存文件执行 restore,回退 fallback 到 checkout + final res = await runGitCommand(['restore', '--', relativePath], workingDir: repoPath); + if (res.success) return res; + + return runGitCommand(['checkout', '--', relativePath], workingDir: repoPath); + } + + /// 放弃所有未暂存更改 (恢复工作区已跟踪文件修改并清理未跟踪新文件) + Future discardAllUnstaged(String repoPath) async { + var res = await runGitCommand(['restore', '.'], workingDir: repoPath); + if (!res.success) { + res = await runGitCommand(['checkout', '--', '.'], workingDir: repoPath); + } + await runGitCommand(['clean', '-fd'], workingDir: repoPath); + return res; + } + + /// 放弃所有已暂存更改 (取消暂存并还原至 HEAD) + Future discardAllStaged(String repoPath) async { + var res = await runGitCommand(['restore', '--staged', '--worktree', '.'], workingDir: repoPath); + if (!res.success) { + await runGitCommand(['restore', '--staged', '.'], workingDir: repoPath); + await runGitCommand(['reset', 'HEAD'], workingDir: repoPath); + res = await runGitCommand(['restore', '.'], workingDir: repoPath); + if (!res.success) { + res = await runGitCommand(['checkout', '--', '.'], workingDir: repoPath); + } + } + return res; + } + + /// 撤销上一次提交,保留暂存区与工作区更改 (`git reset --soft HEAD~1`) + Future undoLastCommit(String repoPath) async { + return runGitCommand(['reset', '--soft', 'HEAD~1'], workingDir: repoPath); + } + + /// 提交更改 (`git commit -m ` 或 `git commit --amend -m `) + Future commit( + String repoPath, + String message, { + bool amend = false, + }) async { + if (message.trim().isEmpty) { + return GitCommandResult.error('提交信息不能为空'); + } + final args = ['commit']; + if (amend) { + args.add('--amend'); + } + args.addAll(['-m', message.trim()]); + return runGitCommand(args, workingDir: repoPath); + } + + /// 贮藏当前工作区更改 (`git stash push` 或 `git stash push -m `) + Future stash(String repoPath, {String? message}) async { + final args = ['stash', 'push']; + if (message != null && message.trim().isNotEmpty) { + args.addAll(['-m', message.trim()]); + } + return runGitCommand(args, workingDir: repoPath); + } + + /// 恢复最近贮藏 (`git stash pop`) + Future stashPop(String repoPath) async { + return runGitCommand(['stash', 'pop'], workingDir: repoPath); + } + + /// 获取当前贮藏栈条目数量 (`git stash list`) + Future getStashCount(String repoPath) async { + final res = await runGitCommand(['stash', 'list'], workingDir: repoPath); + if (!res.success || res.stdout.trim().isEmpty) return 0; + return LineSplitter.split(res.stdout).where((l) => l.trim().isNotEmpty).length; + } + + /// 将相对路径添加到 .gitignore + Future addToGitignore(String repoPath, String relativePath) async { + try { + final gitignoreFile = File(p.join(repoPath, '.gitignore')); + final normalized = relativePath.replaceAll('\\', '/'); + String content = ''; + if (gitignoreFile.existsSync()) { + content = gitignoreFile.readAsStringSync(); + } + final lines = LineSplitter.split(content).map((l) => l.trim()).toList(); + if (lines.contains(normalized) || lines.contains('/$normalized')) { + return true; + } + final appendContent = content.endsWith('\n') || content.isEmpty + ? '$normalized\n' + : '\n$normalized\n'; + gitignoreFile.writeAsStringSync(appendContent, mode: FileMode.append); + return true; + } catch (e) { + debugPrint('[GitService] 添加到 .gitignore 异常: $e'); + return false; + } + } + + /// 获取指定引用或索引区中的文件历史内容 (如 `git show HEAD:file.txt` 或 `git show :0:file.txt`) + Future getFileContentAtRef( + String repoPath, + String ref, + String relativePath, + ) async { + final normalized = relativePath.replaceAll('\\', '/'); + final res = await runGitCommand( + ['show', '$ref:$normalized'], + workingDir: repoPath, + ); + if (!res.success) { + return null; + } + return res.stdout; + } + + /// 获取变更文件的基准版本内容 (用于 Diff 对比) + Future getFileBaseContent(String repoPath, GitFileStatus file) async { + // 1. 未跟踪文件没有基准内容 + if (file.statusType == GitFileStatusType.untracked) { + return ''; + } + + // 2. 如果是暂存区文件,对比的是 HEAD 上的内容 + if (file.isStaged) { + final content = await getFileContentAtRef(repoPath, 'HEAD', file.originalPath ?? file.relativePath); + return content ?? ''; + } + + // 3. 如果是未暂存文件,优先对比暂存区版本 (:0),若无则对比 HEAD + final stagedContent = await getFileContentAtRef(repoPath, ':0', file.originalPath ?? file.relativePath); + if (stagedContent != null) { + return stagedContent; + } + final headContent = await getFileContentAtRef(repoPath, 'HEAD', file.originalPath ?? file.relativePath); + return headContent ?? ''; + } + + /// 获取变更文件的当前修改内容 (用于 Diff 对比) + Future getFileModifiedContent(String repoPath, GitFileStatus file) async { + if (file.statusType == GitFileStatusType.deleted) { + return ''; + } + // 如果是暂存区文件,读取暂存区版本内容 (:0) + if (file.isStaged) { + final content = await getFileContentAtRef(repoPath, ':0', file.relativePath); + if (content != null) return content; + } + // 否则直接读取本地工作区磁盘文件 + try { + final f = File(file.path); + if (f.existsSync()) { + return f.readAsStringSync(); + } + } catch (_) {} + return ''; + } + + /// 获取当前分支/HEAD的提交总数 + Future getTotalCommitsCount(String repoPath) async { + try { + final res = await _runProcess( + gitExecutable, + ['rev-list', '--count', 'HEAD'], + workingDirectory: repoPath, + ); + if (res.exitCode == 0) { + final text = res.stdout.toString().trim(); + return int.tryParse(text) ?? 0; + } + } catch (e) { + debugPrint('[GitService] 获取提交总数失败: $e'); + } + return 0; + } + + /// 获取仓库提交历史记录并计算图表拓扑布局 + Future> getLog( + String repoPath, { + int maxCount = 50, + }) async { + try { + final res = await _runProcess( + gitExecutable, + [ + 'log', + '-n', + maxCount.toString(), + '--format=%H%x00%h%x00%P%x00%an%x00%ae%x00%at%x00%ar%x00%s%x00%D', + ], + workingDirectory: repoPath, + ); + + // 仓库尚无提交(如新建空分支/空仓库),git log 返回非 0,正常返回空列表 + if (res.exitCode != 0) { + return []; + } + + final raw = res.stdout.toString().trim(); + if (raw.isEmpty) return []; + + final lines = raw.split('\n'); + final rawCommits = []; + + for (final line in lines) { + final cleanLine = line.trim(); + if (cleanLine.isEmpty) continue; + + final parts = cleanLine.split('\x00'); + if (parts.length < 8) continue; + + final hash = parts[0].trim(); + final shortHash = parts[1].trim(); + final parentsRaw = parts[2].trim(); + final parentHashes = parentsRaw.isEmpty ? [] : parentsRaw.split(' ').where((p) => p.isNotEmpty).toList(); + final authorName = parts[3].trim(); + final authorEmail = parts[4].trim(); + final timestampSec = int.tryParse(parts[5].trim()) ?? 0; + final authorDate = DateTime.fromMillisecondsSinceEpoch(timestampSec * 1000); + final relativeDate = parts[6].trim(); + final subject = parts[7].trim(); + final refsRaw = parts.length > 8 ? parts[8].trim() : ''; + final refs = refsRaw.isEmpty + ? [] + : refsRaw + .split(',') + .map((r) => r.trim()) + .where((r) => r.isNotEmpty) + .toList(); + + rawCommits.add(GitCommit( + hash: hash, + shortHash: shortHash, + parentHashes: parentHashes, + authorName: authorName, + authorEmail: authorEmail, + authorDate: authorDate, + relativeDate: relativeDate, + subject: subject, + refs: refs, + )); + } + + return computeGraphLanes(rawCommits); + } catch (e) { + debugPrint('[GitService] 获取 Git 提交历史异常: $e'); + return []; + } + } + + /// 计算 Git 图表通道拓扑关系 (为每个提交分配 lane,计算 pass-through 和连线) + static List computeGraphLanes(List rawCommits) { + final List result = []; + final List activeLanes = []; + + for (final commit in rawCommits) { + // 1. 查找此 commit 是否已有分配的 lane + int lane = activeLanes.indexOf(commit.hash); + if (lane == -1) { + // 分配一个空闲 lane 或者追加新 lane + lane = activeLanes.indexOf(null); + if (lane == -1) { + lane = activeLanes.length; + activeLanes.add(commit.hash); + } else { + activeLanes[lane] = commit.hash; + } + } + + // 此时穿过这一行的活跃 lanes(不为 null 的通道) + final currentActive = []; + for (int i = 0; i < activeLanes.length; i++) { + if (activeLanes[i] != null) { + currentActive.add(i); + } + } + + // 2. 为此 commit 的父提交更新 activeLanes + final outgoing = []; + if (commit.parentHashes.isNotEmpty) { + // 第一个父提交继续占用当前 lane + activeLanes[lane] = commit.parentHashes.first; + outgoing.add(lane); + + // 其他父提交(如有 merge 节点) + for (int p = 1; p < commit.parentHashes.length; p++) { + final parentHash = commit.parentHashes[p]; + int pLane = activeLanes.indexOf(parentHash); + if (pLane == -1) { + pLane = activeLanes.indexOf(null); + if (pLane == -1) { + pLane = activeLanes.length; + activeLanes.add(parentHash); + } else { + activeLanes[pLane] = parentHash; + } + } + outgoing.add(pLane); + } + } else { + // 根提交(没有父提交),释放该 lane + activeLanes[lane] = null; + } + + // 清理尾部连续为 null 的通道 + while (activeLanes.isNotEmpty && activeLanes.last == null) { + activeLanes.removeLast(); + } + + result.add(commit.copyWith( + lane: lane, + activeLanes: currentActive, + outgoingLanes: outgoing, + )); + } + return result; + } + + /// 状态码映射 + GitFileStatusType _mapStatusCode(String code) { + switch (code) { + case 'M': + return GitFileStatusType.modified; + case 'A': + return GitFileStatusType.added; + case 'D': + return GitFileStatusType.deleted; + case 'R': + return GitFileStatusType.renamed; + case 'C': + return GitFileStatusType.copied; + case 'T': + return GitFileStatusType.typeChange; + case 'U': + return GitFileStatusType.unmerged; + case '!': + return GitFileStatusType.ignored; + case '?': + return GitFileStatusType.untracked; + default: + return GitFileStatusType.unknown; + } + } + + String _unquote(String s) { + if (s.startsWith('"') && s.endsWith('"') && s.length >= 2) { + return s.substring(1, s.length - 1); + } + return s; + } + + String _escapeShellArg(String arg) { + if (RegExp(r'^[a-zA-Z0-9_\.\-\/=:]+$').hasMatch(arg)) { + return arg; + } + return "'${arg.replaceAll("'", r"'\''")}'"; + } + + Future _runProcess( + String executable, + List arguments, { + String? workingDirectory, + Duration timeout = const Duration(seconds: 30), + }) async { + if (processRunner != null) { + return processRunner!(executable, arguments, workingDirectory: workingDirectory); + } + + // 1. Android 真实设备环境下,优先在内置 Ubuntu PRoot / Chroot 容器中执行 + if (Platform.isAndroid) { + final engine = InternalEngineService.instance; + if (await engine.isEngineInstalled()) { + final rootfs = await engine.getRootfsDir(); + final escapedArgs = arguments.map(_escapeShellArg).join(' '); + // 自动注入 safe.directory 避免 Android/PRoot 跨 UID 权限所有权检查报错 + final fullCmd = (executable == 'git' || executable.endsWith('/git')) + ? 'git -c safe.directory=* $escapedArgs'.trim() + : '$executable $escapedArgs'.trim(); + + try { + final res = await DistroManager().runHeadlessCommand( + systemName: DistroRepository.defaultSystemName, + customRootDir: rootfs, + workspacePath: workingDirectory, + command: fullCmd, + timeout: timeout, + ); + if (res != null) { + return res; + } + } catch (e) { + debugPrint('[GitService] 容器引擎命令执行异常: $e'); + } + } + } + + // 2. 桌面平台 (Windows / macOS / Linux) 或 Android 降级回退 + return Process.run( + executable, + arguments, + workingDirectory: workingDirectory, + runInShell: Platform.isWindows, + ); + } +} diff --git a/lib/services/internal_engine_service.dart b/lib/services/internal_engine_service.dart index 5ebead8..4c86ad6 100644 --- a/lib/services/internal_engine_service.dart +++ b/lib/services/internal_engine_service.dart @@ -11,6 +11,7 @@ import '../widgets/distro_extract_dialog.dart'; import 'distro_installer.dart'; import 'distro_manager.dart'; import 'lsp/lsp_manager.dart'; +import 'toolchain_service.dart'; /// 代码智能与运行时引擎服务(基于统一主系统 Ubuntu 24.04) class InternalEngineService extends ChangeNotifier { @@ -197,8 +198,7 @@ class InternalEngineService extends ChangeNotifier { try { final rootfs = await getRootfsDir(); final installCmd = - 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; ' - 'dpkg --configure -a 2>/dev/null || true; ' + '${ToolchainService.dpkgAutoHealPrefix} ' 'apt-get update && ' 'apt-get install -y --no-install-recommends ${packageName.trim()}'; @@ -216,6 +216,30 @@ class InternalEngineService extends ChangeNotifier { } } + /// 自动诊断与修复 dpkg 锁及半安装 (reinstreq/half-installed) 死锁状态 + Future repairDpkgStatus({void Function(String chunk)? onOutput}) async { + if (!await isEngineInstalled()) return false; + try { + final rootfs = await getRootfsDir(); + final repairCmd = + '${ToolchainService.dpkgAutoHealPrefix} ' + 'apt-get update && ' + 'apt-get -f install -y 2>/dev/null || true;'; + + final res = await DistroManager().runHeadlessCommand( + systemName: DistroRepository.defaultSystemName, + customRootDir: rootfs, + command: repairCmd, + timeout: const Duration(minutes: 3), + onStdout: onOutput, + ); + return res != null && res.exitCode == 0; + } catch (e) { + debugPrint('修复 dpkg 状态异常: $e'); + return false; + } + } + /// 在 Ubuntu 系统中彻底卸载指定 apt 软件包及清理对应命令 Future uninstallPackage( String packageName, { @@ -260,9 +284,8 @@ fi : ''; final uninstallCmd = ''' -export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true +${ToolchainService.dpkgAutoHealPrefix} $killSection -dpkg --configure -a 2>/dev/null || true apt-get remove --purge -y $targetsToPurge apt-get autoremove --purge -y $cmdCleanupSection diff --git a/lib/services/toolchain_service.dart b/lib/services/toolchain_service.dart index 0449e3a..3ee209d 100644 --- a/lib/services/toolchain_service.dart +++ b/lib/services/toolchain_service.dart @@ -19,9 +19,9 @@ class ToolchainRequirement { required this.installCommand, }); - /// 获取安装命令(带自动修复前缀) + /// 获取安装命令(带自动修复与防死锁前缀) String get effectiveInstallCommand => - 'DEBIAN_FRONTEND=noninteractive dpkg --configure -a 2>/dev/null || true; $installCommand'; + '${ToolchainService.dpkgAutoHealPrefix} $installCommand'; /// 兼容接口 String? getInstallCommand([DistroFamily? family]) { @@ -32,8 +32,28 @@ class ToolchainRequirement { /// 预编译软件源与工具链检测/安装适配服务(专为 Ubuntu 24.04 深度优化) class ToolchainService { + /// 全局 Dpkg 自动修复与防死锁前置指令: + /// 1. 设置非交互式环境变量,防止无终端卡死; + /// 2. 清除残留的 lock 锁文件(防止异常中断遗留死锁); + /// 3. 自动扫描并强制清理处于 reinstreq 或半安装 (half-installed/half-configured) 状态的损坏包, + /// 防止其导致后续 dpkg --configure 及 apt-get 陷入死锁; + /// 4. 自动执行 dpkg --configure -a 恢复环境。 + static const String dpkgAutoHealPrefix = + 'export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true; ' + 'rm -f /var/lib/dpkg/lock* /var/lib/apt/lists/lock* /var/cache/apt/archives/lock* 2>/dev/null || true; ' + 'for p in \$(dpkg-query -W -f=\'\${Package} \${Status}\\n\' 2>/dev/null | grep -E \'reinstreq|half-\' | cut -d\' \' -f1); do ' + ' rm -f /var/lib/dpkg/info/\$p.* 2>/dev/null || true; ' + ' dpkg --remove --force-all --force-remove-reinstreq "\$p" 2>/dev/null || true; ' + 'done; ' + 'dpkg --configure -a 2>/dev/null || true;'; + /// 已注册的常用编译器与开发工具链元数据 static const Map supportedTools = { + 'git': ToolchainRequirement( + checkBinary: 'git', + displayName: 'Git 版本控制工具', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y git', + ), 'make': ToolchainRequirement( checkBinary: 'make', displayName: 'make 编译构建工具', diff --git a/lib/utils/git_decoration_utils.dart b/lib/utils/git_decoration_utils.dart new file mode 100644 index 0000000..dd627ab --- /dev/null +++ b/lib/utils/git_decoration_utils.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import '../models/git_model.dart'; + +/// VS Code 风格的 Git 状态装饰工具类 +class GitDecorationUtils { + /// 获取状态对应的文字/圆点颜色(自适应暗黑与明亮主题) + static Color getStatusColor(GitFileStatusType type, {required bool isDark}) { + switch (type) { + case GitFileStatusType.modified: + // VS Code Modified 经典暖沙金/琥珀色 + return isDark ? const Color(0xFFE2C08D) : const Color(0xFFB58900); + case GitFileStatusType.untracked: + case GitFileStatusType.added: + // VS Code Untracked / Added 浅草绿 + return isDark ? const Color(0xFF73C991) : const Color(0xFF2E7D32); + case GitFileStatusType.deleted: + // VS Code Deleted 砖红 + return isDark ? const Color(0xFFE06C75) : const Color(0xFFC62828); + case GitFileStatusType.unmerged: + // VS Code Merge Conflict 醒目亮红 + return isDark ? const Color(0xFFFF5370) : const Color(0xFFD32F2F); + case GitFileStatusType.renamed: + case GitFileStatusType.copied: + // 青色 + return isDark ? const Color(0xFF56B6C2) : const Color(0xFF00838F); + case GitFileStatusType.typeChange: + return isDark ? const Color(0xFFE5C07B) : const Color(0xFF8A6D3B); + case GitFileStatusType.ignored: + return isDark ? const Color(0xFF7F848E) : const Color(0xFF9E9E9E); + case GitFileStatusType.unknown: + return isDark ? const Color(0xFFABB2BF) : const Color(0xFF616161); + } + } + + /// 获取文件在右侧显示的状态缩写字母(如 M, U, A, D, !) + static String? getStatusLetter(GitFileStatusType type) { + switch (type) { + case GitFileStatusType.modified: + return 'M'; + case GitFileStatusType.untracked: + return 'U'; + case GitFileStatusType.added: + return 'A'; + case GitFileStatusType.deleted: + return 'D'; + case GitFileStatusType.unmerged: + return '!'; + case GitFileStatusType.renamed: + return 'R'; + case GitFileStatusType.copied: + return 'C'; + case GitFileStatusType.typeChange: + return 'T'; + case GitFileStatusType.ignored: + case GitFileStatusType.unknown: + return null; + } + } + + /// 状态优先级(用于目录层级聚合:冲突 > 删除 > 修改 > 新增 > 未跟踪 > 其他) + static int getPriority(GitFileStatusType type) { + switch (type) { + case GitFileStatusType.unmerged: + return 50; + case GitFileStatusType.deleted: + return 40; + case GitFileStatusType.modified: + return 30; + case GitFileStatusType.added: + return 20; + case GitFileStatusType.untracked: + return 15; + case GitFileStatusType.renamed: + case GitFileStatusType.copied: + case GitFileStatusType.typeChange: + return 10; + case GitFileStatusType.ignored: + return 5; + case GitFileStatusType.unknown: + return 0; + } + } +} diff --git a/lib/utils/git_diff_helper.dart b/lib/utils/git_diff_helper.dart new file mode 100644 index 0000000..5899bec --- /dev/null +++ b/lib/utils/git_diff_helper.dart @@ -0,0 +1,331 @@ +import 'dart:convert'; +import 'dart:math' as math; + +/// 差异行类型 +enum DiffLineType { + /// 未更改 + unchanged, + + /// 新增 + added, + + /// 删除 + deleted, + + /// 空占位行 (在双屏对齐模式下用于填充高度保持两侧对齐) + empty, +} + +/// 单侧差异行模型 +class DiffLine { + final DiffLineType type; + final String text; + final int? lineNumber; + + const DiffLine({ + required this.type, + required this.text, + this.lineNumber, + }); + + bool get isEmptyPlaceholder => type == DiffLineType.empty; +} + +/// 单屏内联差异行模型 +class UnifiedDiffLine { + final DiffLineType type; + final String text; + final int? oldLineNumber; + final int? newLineNumber; + + const UnifiedDiffLine({ + required this.type, + required this.text, + this.oldLineNumber, + this.newLineNumber, + }); +} + +/// 双屏差异对比计算结果 +class SplitDiffResult { + final List leftLines; + final List rightLines; + final List changeRowIndices; + final int additionsCount; + final int deletionsCount; + + const SplitDiffResult({ + required this.leftLines, + required this.rightLines, + required this.changeRowIndices, + required this.additionsCount, + required this.deletionsCount, + }); +} + +/// Git Diff 算法与行对齐计算工具类 +class GitDiffHelper { + /// 计算双屏并排对齐结果 + static SplitDiffResult computeSplitDiff(String originalText, String modifiedText) { + final originalLines = _splitLines(originalText); + final modifiedLines = _splitLines(modifiedText); + + // 1. 公共前后缀快速收缩剪枝 (大幅提升常见文件差异计算性能) + int prefixCount = 0; + while (prefixCount < originalLines.length && + prefixCount < modifiedLines.length && + originalLines[prefixCount] == modifiedLines[prefixCount]) { + prefixCount++; + } + + int suffixCount = 0; + while (suffixCount < (originalLines.length - prefixCount) && + suffixCount < (modifiedLines.length - prefixCount) && + originalLines[originalLines.length - 1 - suffixCount] == + modifiedLines[modifiedLines.length - 1 - suffixCount]) { + suffixCount++; + } + + final leftResult = []; + final rightResult = []; + final changeRowIndices = []; + int additions = 0; + int deletions = 0; + + // 前缀相同部分 + for (int i = 0; i < prefixCount; i++) { + final line = originalLines[i]; + leftResult.add(DiffLine( + type: DiffLineType.unchanged, + text: line, + lineNumber: i + 1, + )); + rightResult.add(DiffLine( + type: DiffLineType.unchanged, + text: line, + lineNumber: i + 1, + )); + } + + // 中间变化部分 + final middleOrig = originalLines.sublist( + prefixCount, + originalLines.length - suffixCount, + ); + final middleMod = modifiedLines.sublist( + prefixCount, + modifiedLines.length - suffixCount, + ); + + int origLineNo = prefixCount + 1; + int modLineNo = prefixCount + 1; + + final diffOps = _computeDiffOperations(middleOrig, middleMod); + + // 将 diff 操作块分组合并以构建双屏对齐 + int opIndex = 0; + while (opIndex < diffOps.length) { + final op = diffOps[opIndex]; + + if (op.type == _DiffOpType.equal) { + leftResult.add(DiffLine( + type: DiffLineType.unchanged, + text: op.text, + lineNumber: origLineNo++, + )); + rightResult.add(DiffLine( + type: DiffLineType.unchanged, + text: op.text, + lineNumber: modLineNo++, + )); + opIndex++; + } else { + // 遇到变更块 (连续的 delete 与 insert) + final delBlock = []; + final addBlock = []; + + while (opIndex < diffOps.length && diffOps[opIndex].type != _DiffOpType.equal) { + if (diffOps[opIndex].type == _DiffOpType.delete) { + delBlock.add(diffOps[opIndex].text); + deletions++; + } else if (diffOps[opIndex].type == _DiffOpType.insert) { + addBlock.add(diffOps[opIndex].text); + additions++; + } + opIndex++; + } + + // 记录差异起点行索引 + changeRowIndices.add(leftResult.length); + + final maxLen = math.max(delBlock.length, addBlock.length); + for (int i = 0; i < maxLen; i++) { + if (i < delBlock.length) { + leftResult.add(DiffLine( + type: DiffLineType.deleted, + text: delBlock[i], + lineNumber: origLineNo++, + )); + } else { + leftResult.add(const DiffLine( + type: DiffLineType.empty, + text: '', + lineNumber: null, + )); + } + + if (i < addBlock.length) { + rightResult.add(DiffLine( + type: DiffLineType.added, + text: addBlock[i], + lineNumber: modLineNo++, + )); + } else { + rightResult.add(const DiffLine( + type: DiffLineType.empty, + text: '', + lineNumber: null, + )); + } + } + } + } + + // 后缀相同部分 + final origSuffixStart = originalLines.length - suffixCount; + final modSuffixStart = modifiedLines.length - suffixCount; + for (int i = 0; i < suffixCount; i++) { + final line = originalLines[origSuffixStart + i]; + leftResult.add(DiffLine( + type: DiffLineType.unchanged, + text: line, + lineNumber: origSuffixStart + i + 1, + )); + rightResult.add(DiffLine( + type: DiffLineType.unchanged, + text: line, + lineNumber: modSuffixStart + i + 1, + )); + } + + return SplitDiffResult( + leftLines: leftResult, + rightLines: rightResult, + changeRowIndices: changeRowIndices, + additionsCount: additions, + deletionsCount: deletions, + ); + } + + /// 将双屏结果或文本转换为单屏内联 (Unified) 差异行列表 + static List toUnifiedDiff(String originalText, String modifiedText) { + final originalLines = _splitLines(originalText); + final modifiedLines = _splitLines(modifiedText); + + final diffOps = _computeDiffOperations(originalLines, modifiedLines); + final result = []; + + int origLineNo = 1; + int modLineNo = 1; + + for (final op in diffOps) { + switch (op.type) { + case _DiffOpType.equal: + result.add(UnifiedDiffLine( + type: DiffLineType.unchanged, + text: op.text, + oldLineNumber: origLineNo++, + newLineNumber: modLineNo++, + )); + break; + case _DiffOpType.delete: + result.add(UnifiedDiffLine( + type: DiffLineType.deleted, + text: op.text, + oldLineNumber: origLineNo++, + newLineNumber: null, + )); + break; + case _DiffOpType.insert: + result.add(UnifiedDiffLine( + type: DiffLineType.added, + text: op.text, + oldLineNumber: null, + newLineNumber: modLineNo++, + )); + break; + } + } + + return result; + } + + static List _splitLines(String text) { + if (text.isEmpty) return []; + return const LineSplitter().convert(text); + } + + /// 计算差异编辑脚本 (基于标准动态规划 LCS 矩阵,针对超长文本具备平滑防御) + static List<_DiffOp> _computeDiffOperations(List a, List b) { + final n = a.length; + final m = b.length; + + if (n == 0) { + return b.map((text) => _DiffOp(_DiffOpType.insert, text)).toList(); + } + if (m == 0) { + return a.map((text) => _DiffOp(_DiffOpType.delete, text)).toList(); + } + + // 防御过大矩阵导致的 OOM (单次差异超过 200,000 元素积时快速回退) + if (n * m > 250000) { + return [ + ...a.map((text) => _DiffOp(_DiffOpType.delete, text)), + ...b.map((text) => _DiffOp(_DiffOpType.insert, text)), + ]; + } + + // LCS 动态规划 + final dp = List.generate(n + 1, (_) => List.filled(m + 1, 0)); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (a[i] == b[j]) { + dp[i + 1][j + 1] = dp[i][j] + 1; + } else { + dp[i + 1][j + 1] = math.max(dp[i + 1][j], dp[i][j + 1]); + } + } + } + + // 回溯生成操作队列 + final ops = <_DiffOp>[]; + int i = n; + int j = m; + + while (i > 0 || j > 0) { + if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) { + ops.add(_DiffOp(_DiffOpType.equal, a[i - 1])); + i--; + j--; + } else if (j > 0 && (i == 0 || dp[i][j - 1] >= dp[i - 1][j])) { + ops.add(_DiffOp(_DiffOpType.insert, b[j - 1])); + j--; + } else if (i > 0 && (j == 0 || dp[i][j - 1] < dp[i - 1][j])) { + ops.add(_DiffOp(_DiffOpType.delete, a[i - 1])); + i--; + } + } + + return ops.reversed.toList(); + } +} + +enum _DiffOpType { equal, delete, insert } + +class _DiffOp { + final _DiffOpType type; + final String text; + + _DiffOp(this.type, this.text); +} diff --git a/lib/utils/syntax_highlight_helper.dart b/lib/utils/syntax_highlight_helper.dart index da0d9e2..7f976d6 100644 --- a/lib/utils/syntax_highlight_helper.dart +++ b/lib/utils/syntax_highlight_helper.dart @@ -1,3 +1,4 @@ +import 'package:flutter/painting.dart'; import 'package:path/path.dart' as p; import 'package:re_editor/re_editor.dart'; import 'package:re_highlight/languages/all.dart'; @@ -183,4 +184,31 @@ class SyntaxHighlightHelper { if (langId == null) return null; return builtinAllLanguages[langId]; } + + static final Highlight _highlightInstance = Highlight()..registerLanguages(builtinAllLanguages); + + /// 针对单行代码生成带语法高亮的 TextSpan(供 Diff 视图等只读代码渲染) + static TextSpan highlightLine({ + required String code, + required String? filePath, + required TextStyle baseStyle, + required Map highlightTheme, + }) { + if (code.isEmpty) { + return TextSpan(text: '', style: baseStyle); + } + final langId = getLanguageId(filePath); + if (langId == null) { + return TextSpan(text: code, style: baseStyle); + } + try { + final result = _highlightInstance.highlight(code: code, language: langId); + final renderer = TextSpanRenderer(baseStyle, highlightTheme); + result.render(renderer); + return renderer.span ?? TextSpan(text: code, style: baseStyle); + } catch (_) { + return TextSpan(text: code, style: baseStyle); + } + } } + diff --git a/lib/widgets/code_editor_drawer.dart b/lib/widgets/code_editor_drawer.dart index 49ca61d..fa17309 100644 --- a/lib/widgets/code_editor_drawer.dart +++ b/lib/widgets/code_editor_drawer.dart @@ -1,5 +1,6 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/providers/distro_provider.dart'; +import 'package:code_editor/providers/git_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/run_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; @@ -9,6 +10,7 @@ import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/views/project_management_view.dart'; import 'package:code_editor/widgets/project_history_widget.dart'; import 'package:code_editor/widgets/file_tree_widget.dart'; +import 'package:code_editor/widgets/git/git_panel_widget.dart'; import 'package:code_editor/widgets/search/search_panel_widget.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; @@ -142,6 +144,7 @@ class _CodeEditorDrawerState extends State { required int index, required IconData icon, required String label, + int? badgeCount, }) { final theme = Theme.of(context); final isSelected = _selectedIndex == index; @@ -188,6 +191,36 @@ class _CodeEditorDrawerState extends State { ? colorScheme.primary : colorScheme.onSurfaceVariant.withValues(alpha: 0.7), ), + if (badgeCount != null && badgeCount > 0) + Positioned( + right: 4, + bottom: 5, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), + constraints: const BoxConstraints( + minWidth: 16, + minHeight: 16, + ), + decoration: BoxDecoration( + color: colorScheme.primary, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: theme.colorScheme.surfaceContainerLow, + width: 1.2, + ), + ), + alignment: Alignment.center, + child: Text( + badgeCount > 99 ? '99+' : badgeCount.toString(), + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.bold, + color: colorScheme.onPrimary, + height: 1.1, + ), + ), + ), + ), ], ), ), @@ -200,6 +233,9 @@ class _CodeEditorDrawerState extends State { AppLocalizations l10n, ThemeData theme, ) { + final gitProvider = context.watch(); + final gitBadgeCount = (gitProvider?.isGitRepo ?? false) ? (gitProvider?.totalChangedCount ?? 0) : 0; + return Container( width: 48, decoration: BoxDecoration( @@ -236,6 +272,7 @@ class _CodeEditorDrawerState extends State { index: 2, icon: Icons.alt_route_rounded, label: l10n.drawerTabGit, + badgeCount: gitBadgeCount, ), ], ), @@ -449,45 +486,6 @@ class _CodeEditorDrawerState extends State { - Widget _buildGitPlaceholder( - BuildContext context, - AppLocalizations l10n, - ThemeData theme, - ) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Container( - decoration: BoxDecoration( - color: theme.colorScheme.primaryContainer, - ), - child: SafeArea( - bottom: false, - left: false, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0), - child: Row( - children: [ - Expanded( - child: Text( - l10n.drawerTabGit, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.bold, - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - ), - ], - ), - ), - ), - ), - const Expanded(child: SizedBox.shrink()), - ], - ); - } - @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -502,12 +500,12 @@ class _CodeEditorDrawerState extends State { children: [ _buildActivityBar(context, l10n, theme), Expanded( - child: IndexedStack( + child: _LazyIndexedStack( index: _selectedIndex, - children: [ - _buildExplorerPage(context, l10n, theme, rootPath, hasProject), - const SearchPanelWidget(), - _buildGitPlaceholder(context, l10n, theme), + builders: [ + (ctx) => _buildExplorerPage(ctx, l10n, theme, rootPath, hasProject), + (ctx) => const SearchPanelWidget(), + (ctx) => const GitPanelWidget(), ], ), ), @@ -516,3 +514,53 @@ class _CodeEditorDrawerState extends State { ); } } + +/// 惰性按需挂载的 IndexedStack,仅在 Tab 首次被激活时实例化子 Widget, +/// 并通过 Offstage + TickerMode 永久保持状态与滚动偏移,杜绝抽屉初次滑出时全量构建卡顿。 +class _LazyIndexedStack extends StatefulWidget { + final int index; + final List builders; + + const _LazyIndexedStack({ + required this.index, + required this.builders, + }); + + @override + State<_LazyIndexedStack> createState() => _LazyIndexedStackState(); +} + +class _LazyIndexedStackState extends State<_LazyIndexedStack> { + late final Set _activatedIndices; + + @override + void initState() { + super.initState(); + _activatedIndices = {widget.index}; + } + + @override + void didUpdateWidget(covariant _LazyIndexedStack oldWidget) { + super.didUpdateWidget(oldWidget); + _activatedIndices.add(widget.index); + } + + @override + Widget build(BuildContext context) { + return Stack( + fit: StackFit.expand, + children: List.generate(widget.builders.length, (i) { + final isActivated = _activatedIndices.contains(i); + final isSelected = widget.index == i; + + return Offstage( + offstage: !isSelected, + child: TickerMode( + enabled: isSelected, + child: isActivated ? widget.builders[i](context) : const SizedBox.shrink(), + ), + ); + }), + ); + } +} diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index a35f422..77288bc 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -501,47 +501,24 @@ class _CodeEditorWidgetState extends State { curOpt.pattern != query || curOpt.caseSensitive != searchProvider.caseSensitive || curOpt.regex != searchProvider.isRegex) { - if (query.isEmpty) { - if (curVal != null && curOpt?.pattern.isNotEmpty == true) { - // 注意:不能直接调用 _findController!.close(), - // 因为 re_editor 内部在 value == null 时会强制执行 widget.focusNode.requestFocus(), - // 导致侧边抽屉中的搜索输入框在内容清空时瞬间失去焦点。 - // 此处同时临时锁定 _focusNode.canRequestFocus 并赋空匹配正则,彻底杜绝编辑器抢夺焦点。 - final wasCanRequest = _focusNode.canRequestFocus; - _focusNode.canRequestFocus = false; - try { - _findController!.value = const CodeFindValue( - option: CodeFindOption( - pattern: r'(?!)', - caseSensitive: false, - regex: true, - ), - replaceMode: false, - searching: false, - ); - } finally { - _focusNode.canRequestFocus = wasCanRequest; - } - } - } else { - final wasCanRequest = _focusNode.canRequestFocus; - _focusNode.canRequestFocus = false; - try { - _findController!.value = CodeFindValue( - option: CodeFindOption( - pattern: query, - caseSensitive: searchProvider.caseSensitive, - regex: searchProvider.isRegex, - ), - replaceMode: false, - searching: true, - ); - if (_findController!.findInputController.text != query) { - _findController!.findInputController.text = query; - } - } finally { - _focusNode.canRequestFocus = wasCanRequest; - } + // 严禁设置 _focusNode.canRequestFocus = false! + // 在 Flutter 框架中,当编辑区拥有焦点时(用户正在编辑代码输入), + // 将 canRequestFocus 置为 false 会强制触发 unfocus(),紧接着在输入时又重获焦点, + // 造成软键盘反复弹起收起(一跳一跳的致命抖动)。 + // 同时此处保持 _findController.value 非 null(pattern 为 query), + // re_editor 在 pattern 为空时会自动将 matches 清空,既彻底清除了高亮, + // 又避免了在 value == null 时触发 re_editor 内部偷夺焦点的 requestFocus()。 + _findController!.value = CodeFindValue( + option: CodeFindOption( + pattern: query, + caseSensitive: searchProvider.caseSensitive, + regex: searchProvider.isRegex, + ), + replaceMode: false, + searching: query.isNotEmpty, + ); + if (_findController!.findInputController.text != query) { + _findController!.findInputController.text = query; } } } @@ -798,7 +775,11 @@ class _CodeEditorWidgetState extends State { } catch (_) {} final searchProvider = context.watch(); - _syncSearchHighlight(searchProvider); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _syncSearchHighlight(searchProvider); + } + }); final l10n = AppLocalizations.of(context); final hasNoProject = widget.rootPath == null || widget.rootPath!.trim().isEmpty; @@ -1130,7 +1111,18 @@ class _CodeEditorWidgetState extends State { _controller = newController; _findController?.dispose(); - _findController = CodeFindController(newController); + _findController = CodeFindController( + newController, + const CodeFindValue( + option: CodeFindOption( + pattern: '', + caseSensitive: false, + regex: false, + ), + replaceMode: false, + searching: false, + ), + ); _currentLoadedPath = fullFilePath; _currentIndentSize = activeIndentSize; _errorMessage = null; @@ -1196,7 +1188,18 @@ class _CodeEditorWidgetState extends State { _controller = newController; _findController?.dispose(); - _findController = CodeFindController(newController); + _findController = CodeFindController( + newController, + const CodeFindValue( + option: CodeFindOption( + pattern: '', + caseSensitive: false, + regex: false, + ), + replaceMode: false, + searching: false, + ), + ); _currentLoadedPath = fullFilePath; _currentIndentSize = activeIndentSize; _errorMessage = null; diff --git a/lib/widgets/file_item_widget.dart b/lib/widgets/file_item_widget.dart index a868bf1..c26f028 100644 --- a/lib/widgets/file_item_widget.dart +++ b/lib/widgets/file_item_widget.dart @@ -1,10 +1,12 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/file_item.dart'; +import 'package:code_editor/providers/git_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/services/permission_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/utils/file_icon_utils.dart'; +import 'package:code_editor/utils/git_decoration_utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; @@ -30,6 +32,14 @@ class _FileItemWidgetState extends State { return listen ? context.watch() : context.read(); } + static GitProvider? _getGitProvider(BuildContext context, {bool listen = false}) { + try { + return listen ? context.watch() : context.read(); + } catch (_) { + return null; + } + } + @override Widget build(BuildContext context) { return _buildFileItem(context, widget.fileItem); @@ -39,22 +49,41 @@ class _FileItemWidgetState extends State { final theme = Theme.of(context); final projectProvider = _getProjectProvider(context, listen: true); final tabProvider = _getTabProvider(context, listen: true); + final gitProvider = _getGitProvider(context, listen: true); + final isDark = theme.brightness == Brightness.dark; + final indent = EdgeInsets.only(left: item.depth * 16.0 + 8.0, right: 8.0); + // 获取 Git 状态修饰 + final gitFileStatus = !item.isDirectory && gitProvider != null + ? gitProvider.getFileStatus(item.path) + : null; + final gitDirStatusType = item.isDirectory && gitProvider != null + ? gitProvider.getDirectoryStatus(item.path) + : null; + + final Color? gitColor = !item.isDirectory + ? (gitFileStatus != null + ? GitDecorationUtils.getStatusColor(gitFileStatus.statusType, isDark: isDark) + : null) + : (gitDirStatusType != null + ? GitDecorationUtils.getStatusColor(gitDirStatusType, isDark: isDark) + : null); + // 判断该文件是否处于被剪切状态 final isCut = projectProvider.isItemCut(item.path); // 判断该文件是否为当前正在编辑/修改的文件 final isSelected = !item.isDirectory && tabProvider.isFileSelected(item.path); - // 文字样式:剪切时变灰,选中时高亮,其余正常 + // 文字样式:剪切时变灰,选中时高亮,有 Git 状态时使用 Git 状态色,其余正常 final itemTextStyle = theme.textTheme.bodyMedium?.copyWith( fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, color: isCut ? theme.colorScheme.onSurface.withValues(alpha: 0.38) : isSelected ? theme.colorScheme.primary - : null, + : gitColor, ); final iconColor = isCut @@ -64,36 +93,95 @@ class _FileItemWidgetState extends State { : null; if (item.isDirectory) { + Widget? dirTrailing; + if (gitColor != null && gitDirStatusType != null) { + dirTrailing = SizedBox( + width: 18, + height: 18, + child: Center( + child: Container( + width: 7, + height: 7, + decoration: BoxDecoration( + color: gitColor, + shape: BoxShape.circle, + ), + ), + ), + ); + } + return GestureDetector( onLongPressStart: (details) { _showContextMenu(item, details.globalPosition); }, - child: ExpansionTile( - key: PageStorageKey(item.path), - initiallyExpanded: item.isOpen, - tilePadding: indent, - leading: Icon( - item.isOpen ? Icons.folder_open_outlined : Icons.folder_outlined, - color: isCut ? iconColor : null, - size: 20, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 1.0), + child: Material( + color: Colors.transparent, + child: ListTile( + contentPadding: indent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8.0), + ), + dense: true, + leading: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + item.isOpen ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_right, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 4), + Icon( + item.isOpen ? Icons.folder_open_outlined : Icons.folder_outlined, + color: isCut ? iconColor : (item.isOpen ? theme.colorScheme.primary : null), + size: 20, + ), + ], + ), + title: Text( + item.name, + style: itemTextStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: dirTrailing, + onTap: () { + final newExpanded = !item.isOpen; + setState(() { + item.isOpen = newExpanded; + }); + _getProjectProvider(context).toggleDirectory(item, newExpanded); + }, + ), ), - title: Text( - item.name, - style: itemTextStyle, - ), - dense: true, - onExpansionChanged: (bool expanded) { - setState(() { - item.isOpen = expanded; - }); - _getProjectProvider(context).toggleDirectory(item, expanded); - }, - children: item.children - .map((child) => FileItemWidget(fileItem: child)) - .toList(), ), ); } else { + Widget? fileTrailing; + if (gitColor != null && gitFileStatus != null) { + final letter = GitDecorationUtils.getStatusLetter(gitFileStatus.statusType); + if (letter != null && letter.isNotEmpty) { + fileTrailing = SizedBox( + width: 18, + height: 18, + child: Center( + child: Text( + letter, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: gitColor, + height: 1.0, + ), + ), + ), + ); + } + } + return GestureDetector( onLongPressStart: (details) { _showContextMenu(item, details.globalPosition); @@ -117,7 +205,10 @@ class _FileItemWidgetState extends State { title: Text( item.name, style: itemTextStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, ), + trailing: fileTrailing, dense: true, onTap: () { final scaffold = Scaffold.maybeOf(context); diff --git a/lib/widgets/file_tree_widget.dart b/lib/widgets/file_tree_widget.dart index 38af097..dfe9e85 100644 --- a/lib/widgets/file_tree_widget.dart +++ b/lib/widgets/file_tree_widget.dart @@ -1,4 +1,5 @@ import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/file_item.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/widgets/file_item_widget.dart'; import 'package:flutter/material.dart'; @@ -53,13 +54,27 @@ class FileTreeWidget extends StatelessWidget { ); } + // 3. 动态扁平化已展开的目录树,使所有深度的文件节点均能通过 ListView.builder 获得真正的行级虚拟化 + final flatItems = []; + void flatten(List list) { + for (final it in list) { + flatItems.add(it); + if (it.isDirectory && it.isOpen && it.children.isNotEmpty) { + flatten(it.children); + } + } + } + flatten(items); + return ListView.builder( key: const PageStorageKey('code_editor_file_tree_list'), padding: const EdgeInsets.symmetric(horizontal: 4.0), - itemCount: items.length, + itemCount: flatItems.length, itemBuilder: (context, index) { + final item = flatItems[index]; return FileItemWidget( - fileItem: items[index], + key: ValueKey(item.path), + fileItem: item, ); }, ); diff --git a/lib/widgets/git/git_diff_page.dart b/lib/widgets/git/git_diff_page.dart new file mode 100644 index 0000000..7c99f1c --- /dev/null +++ b/lib/widgets/git/git_diff_page.dart @@ -0,0 +1,1865 @@ +import 'dart:math' as math; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +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 '../../utils/file_icon_utils.dart'; +import '../../utils/git_diff_helper.dart'; +import '../../utils/syntax_highlight_helper.dart'; + +/// 独立的 Git Diff 文件差异对比页面 +class GitDiffPage extends StatefulWidget { + final GitFileStatus file; + final GitProvider gitProvider; + + const GitDiffPage({ + super.key, + required this.file, + required this.gitProvider, + }); + + @override + State createState() => _GitDiffPageState(); +} + +class _GitDiffPageState extends State { + bool _isLoading = true; + String? _errorMessage; + SplitDiffResult? _splitResult; + List _unifiedLines = const []; + + bool _isSplitMode = true; + double _splitRatio = 0.5; + + // 缩放字号状态(初始使用编辑区字号,双屏同步缩放,单屏独立,后续缩放不影响编辑区和设置) + double? _splitFontSize; + double? _unifiedFontSize; + + // 双屏分屏手势状态管理(基于 Listener 原生指针跟踪,对标 code_editor_widget 彻底根除抖动) + final Map _splitPointers = {}; + int? _splitPointer1; + int? _splitPointer2; + double? _splitInitialDistance; + double? _splitInitialFontSize; + double? _splitActiveZoomFontSize; + Offset? _splitInitialLocalFocal; + Offset? _splitCurrentLocalFocal; + double _splitFocalLineContinuous = 0.0; + double _splitFocalCharContinuous = 0.0; + bool _isSplitPinching = false; + Offset? _splitLastPanPos; + VelocityTracker? _splitVelocityTracker; + bool _isDraggingDivider = false; + + // 单屏内联手势状态管理 + final Map _unifiedPointers = {}; + int? _unifiedPointer1; + int? _unifiedPointer2; + double? _unifiedInitialDistance; + double? _unifiedInitialFontSize; + double? _unifiedActiveZoomFontSize; + Offset? _unifiedInitialLocalFocal; + Offset? _unifiedCurrentLocalFocal; + double _unifiedFocalLineContinuous = 0.0; + double _unifiedFocalCharContinuous = 0.0; + bool _isUnifiedPinching = false; + Offset? _unifiedLastPanPos; + VelocityTracker? _unifiedVelocityTracker; + + // 左屏滚动控制器(垂直、水平、行号) + late final ScrollController _leftVController; + late final ScrollController _leftHController; + late final ScrollController _leftGutterController; + + // 右屏滚动控制器(垂直、水平、行号) + late final ScrollController _rightVController; + late final ScrollController _rightHController; + late final ScrollController _rightGutterController; + + // 单屏内联滚动控制器 + late final ScrollController _unifiedVController; + late final ScrollController _unifiedHController; + late final ScrollController _unifiedGutterController; + + bool _syncingSplit = false; + bool _syncingUnified = false; + + int _currentChangeIndex = -1; + late GitFileStatus _currentFile; + + // 语法高亮缓存(key: 'fontSize-themeId-code') + final Map _highlightSpanCache = {}; + + @override + void initState() { + super.initState(); + _currentFile = widget.file; + + _leftVController = ScrollController(); + _leftHController = ScrollController(); + _leftGutterController = ScrollController(); + + _rightVController = ScrollController(); + _rightHController = ScrollController(); + _rightGutterController = ScrollController(); + + _unifiedVController = ScrollController(); + _unifiedHController = ScrollController(); + _unifiedGutterController = ScrollController(); + + // 双屏同步滚动监听(左栏与右栏、行号区垂直与水平全向无缝联动) + _leftVController.addListener(_onLeftVScrolled); + _leftGutterController.addListener(_onLeftGutterScrolled); + _leftHController.addListener(_onLeftHScrolled); + + _rightVController.addListener(_onRightVScrolled); + _rightGutterController.addListener(_onRightGutterScrolled); + _rightHController.addListener(_onRightHScrolled); + + // 单屏内联视图代码区与行号区垂直同步滚动 + _unifiedVController.addListener(_onUnifiedVScrolled); + _unifiedGutterController.addListener(_onUnifiedGutterScrolled); + + _loadDiff(); + } + + void _onLeftVScrolled() { + if (_syncingSplit) return; + _syncingSplit = true; + final offset = _leftVController.offset; + if (_leftGutterController.hasClients) { + _leftGutterController.jumpTo(offset.clamp(0.0, _leftGutterController.position.maxScrollExtent)); + } + if (_rightVController.hasClients) { + _rightVController.jumpTo(offset.clamp(0.0, _rightVController.position.maxScrollExtent)); + } + if (_rightGutterController.hasClients) { + _rightGutterController.jumpTo(offset.clamp(0.0, _rightGutterController.position.maxScrollExtent)); + } + _syncingSplit = false; + } + + void _onLeftGutterScrolled() { + if (_syncingSplit || !_leftVController.hasClients) return; + _syncingSplit = true; + _leftVController.jumpTo(_leftGutterController.offset.clamp(0.0, _leftVController.position.maxScrollExtent)); + _syncingSplit = false; + } + + void _onLeftHScrolled() { + if (_syncingSplit) return; + _syncingSplit = true; + final offset = _leftHController.offset; + if (_rightHController.hasClients) { + _rightHController.jumpTo(offset.clamp(0.0, _rightHController.position.maxScrollExtent)); + } + _syncingSplit = false; + } + + void _onRightVScrolled() { + if (_syncingSplit) return; + _syncingSplit = true; + final offset = _rightVController.offset; + if (_rightGutterController.hasClients) { + _rightGutterController.jumpTo(offset.clamp(0.0, _rightGutterController.position.maxScrollExtent)); + } + if (_leftVController.hasClients) { + _leftVController.jumpTo(offset.clamp(0.0, _leftVController.position.maxScrollExtent)); + } + if (_leftGutterController.hasClients) { + _leftGutterController.jumpTo(offset.clamp(0.0, _leftGutterController.position.maxScrollExtent)); + } + _syncingSplit = false; + } + + void _onRightGutterScrolled() { + if (_syncingSplit || !_rightVController.hasClients) return; + _syncingSplit = true; + _rightVController.jumpTo(_rightGutterController.offset.clamp(0.0, _rightVController.position.maxScrollExtent)); + _syncingSplit = false; + } + + void _onRightHScrolled() { + if (_syncingSplit) return; + _syncingSplit = true; + final offset = _rightHController.offset; + if (_leftHController.hasClients) { + _leftHController.jumpTo(offset.clamp(0.0, _leftHController.position.maxScrollExtent)); + } + _syncingSplit = false; + } + + void _onUnifiedVScrolled() { + if (_syncingUnified || !_unifiedGutterController.hasClients) return; + _syncingUnified = true; + _unifiedGutterController.jumpTo(_unifiedVController.offset.clamp(0.0, _unifiedGutterController.position.maxScrollExtent)); + _syncingUnified = false; + } + + void _onUnifiedGutterScrolled() { + if (_syncingUnified || !_unifiedVController.hasClients) return; + _syncingUnified = true; + _unifiedVController.jumpTo(_unifiedGutterController.offset.clamp(0.0, _unifiedVController.position.maxScrollExtent)); + _syncingUnified = false; + } + + @override + void dispose() { + _leftVController.removeListener(_onLeftVScrolled); + _leftGutterController.removeListener(_onLeftGutterScrolled); + _leftHController.removeListener(_onLeftHScrolled); + _leftVController.dispose(); + _leftHController.dispose(); + _leftGutterController.dispose(); + + _rightVController.removeListener(_onRightVScrolled); + _rightGutterController.removeListener(_onRightGutterScrolled); + _rightHController.removeListener(_onRightHScrolled); + _rightVController.dispose(); + _rightHController.dispose(); + _rightGutterController.dispose(); + + _unifiedVController.removeListener(_onUnifiedVScrolled); + _unifiedGutterController.removeListener(_onUnifiedGutterScrolled); + _unifiedVController.dispose(); + _unifiedHController.dispose(); + _unifiedGutterController.dispose(); + + super.dispose(); + } + + Future _loadDiff() async { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + + final repoPath = widget.gitProvider.currentRepoPath; + if (repoPath == null) { + setState(() { + _isLoading = false; + _errorMessage = '未选择 Git 仓库'; + }); + return; + } + + try { + final baseContent = await widget.gitProvider.gitService.getFileBaseContent(repoPath, _currentFile); + final modifiedContent = await widget.gitProvider.gitService.getFileModifiedContent(repoPath, _currentFile); + + final split = GitDiffHelper.computeSplitDiff(baseContent ?? '', modifiedContent); + final unified = GitDiffHelper.toUnifiedDiff(baseContent ?? '', modifiedContent); + + if (mounted) { + setState(() { + _splitResult = split; + _unifiedLines = unified; + _isLoading = false; + _currentChangeIndex = split.changeRowIndices.isNotEmpty ? 0 : -1; + }); + } + } catch (e) { + if (mounted) { + setState(() { + _isLoading = false; + _errorMessage = e.toString(); + }); + } + } + } + + void _navigateToNextChange(double splitRowHeight, double unifiedRowHeight) { + final split = _splitResult; + if (split == null || split.changeRowIndices.isEmpty) return; + + setState(() { + _currentChangeIndex = (_currentChangeIndex + 1) % split.changeRowIndices.length; + }); + _scrollToChangeRow(split.changeRowIndices[_currentChangeIndex], splitRowHeight, unifiedRowHeight); + } + + void _navigateToPrevChange(double splitRowHeight, double unifiedRowHeight) { + final split = _splitResult; + if (split == null || split.changeRowIndices.isEmpty) return; + + setState(() { + _currentChangeIndex = (_currentChangeIndex - 1 + split.changeRowIndices.length) % split.changeRowIndices.length; + }); + _scrollToChangeRow(split.changeRowIndices[_currentChangeIndex], splitRowHeight, unifiedRowHeight); + } + + void _scrollToChangeRow(int rowIndex, double splitRowHeight, double unifiedRowHeight) { + if (_isSplitMode) { + final targetOffset = rowIndex * splitRowHeight; + if (_leftVController.hasClients) { + final maxScroll = _leftVController.position.maxScrollExtent; + _leftVController.animateTo( + targetOffset.clamp(0.0, maxScroll), + duration: const Duration(milliseconds: 250), + curve: Curves.easeInOut, + ); + } + if (_rightVController.hasClients) { + final maxScroll = _rightVController.position.maxScrollExtent; + _rightVController.animateTo( + targetOffset.clamp(0.0, maxScroll), + duration: const Duration(milliseconds: 250), + curve: Curves.easeInOut, + ); + } + } else { + if (_unifiedVController.hasClients) { + final maxScroll = _unifiedVController.position.maxScrollExtent; + final targetOffset = rowIndex * unifiedRowHeight; + _unifiedVController.animateTo( + targetOffset.clamp(0.0, maxScroll), + duration: const Duration(milliseconds: 250), + curve: Curves.easeInOut, + ); + } + } + } + + // --- 双屏分屏指针手势处理(对标 code_editor_widget.dart,彻底消除抖动并实现双屏同步) --- + void _handleSplitPointerDown( + PointerDownEvent event, + double currentFontSize, + double rowH, + double charW, + double leftWidth, + double dividerWidth, + ) { + _splitPointers[event.pointer] = event.position; + if (_splitPointers.length == 1) { + final localX = event.localPosition.dx; + if (localX >= leftWidth && localX <= leftWidth + dividerWidth) { + _isDraggingDivider = true; + } else { + _isDraggingDivider = false; + _splitLastPanPos = event.position; + _splitVelocityTracker = VelocityTracker.withKind(event.kind); + _splitVelocityTracker?.addPosition(event.timeStamp, event.position); + } + } else if (_splitPointers.length >= 2 && !_isSplitPinching) { + _isDraggingDivider = false; + final keys = _splitPointers.keys.toList(); + _splitPointer1 = keys[0]; + _splitPointer2 = keys[1]; + + final p1 = _splitPointers[_splitPointer1]!; + final p2 = _splitPointers[_splitPointer2]!; + + _splitInitialDistance = (p1 - p2).distance; + _splitInitialFontSize = _splitActiveZoomFontSize ?? currentFontSize; + _splitActiveZoomFontSize = _splitInitialFontSize; + + final globalFocal = (p1 + p2) / 2; + final renderBox = context.findRenderObject() as RenderBox?; + final localFocal = renderBox != null ? renderBox.globalToLocal(globalFocal) : globalFocal; + _splitInitialLocalFocal = localFocal; + + final curV = _leftVController.hasClients ? _leftVController.offset : 0.0; + final curH = _leftHController.hasClients ? _leftHController.offset : 0.0; + + _splitFocalLineContinuous = (curV + localFocal.dy) / math.max(1.0, rowH); + _splitFocalCharContinuous = (curH + localFocal.dx) / math.max(1.0, charW); + + _splitLastPanPos = null; + setState(() { + _isSplitPinching = true; + }); + } + } + + void _handleSplitPointerMove(PointerMoveEvent event) { + if (!_splitPointers.containsKey(event.pointer)) return; + _splitPointers[event.pointer] = event.position; + + if (_isSplitPinching) { + if (_splitPointer1 != null && + _splitPointer2 != null && + _splitPointers.containsKey(_splitPointer1) && + _splitPointers.containsKey(_splitPointer2) && + _splitInitialDistance != null && + _splitInitialDistance! > 10.0 && + _splitInitialFontSize != null && + _splitInitialLocalFocal != null) { + final p1 = _splitPointers[_splitPointer1]!; + final p2 = _splitPointers[_splitPointer2]!; + + final currentDistance = (p1 - p2).distance; + final rawScale = currentDistance / _splitInitialDistance!; + + final minScale = SettingsProvider.minFontSize / _splitInitialFontSize!; + final maxScale = (SettingsProvider.maxFontSize + 8.0) / _splitInitialFontSize!; + final clampedScale = rawScale.clamp(minScale * 0.9, maxScale * 1.1); + + final continuousFontSize = ((_splitInitialFontSize! * clampedScale) * 10).round() / 10.0; + final newFontSize = continuousFontSize.clamp( + SettingsProvider.minFontSize, + SettingsProvider.maxFontSize + 8.0, + ); + + final newRowH = (newFontSize * 1.45 + 4.0).roundToDouble(); + final newCharW = newFontSize * 0.60; + + final currentGlobalFocal = (p1 + p2) / 2; + final renderBox = context.findRenderObject() as RenderBox?; + final currentLocalFocal = renderBox != null + ? renderBox.globalToLocal(currentGlobalFocal) + : currentGlobalFocal; + _splitCurrentLocalFocal = currentLocalFocal; + + final targetScrollV = _splitFocalLineContinuous * newRowH - currentLocalFocal.dy; + final targetScrollH = _splitFocalCharContinuous * newCharW - currentLocalFocal.dx; + + _jumpSplitScroll(targetScrollV, targetScrollH); + + if (_splitFontSize != newFontSize) { + setState(() { + _splitFontSize = newFontSize; + _splitActiveZoomFontSize = newFontSize; + }); + } + } + } else if (_splitPointers.length == 1 && !_isSplitPinching && !_isDraggingDivider) { + _splitVelocityTracker?.addPosition(event.timeStamp, event.position); + final curPos = event.position; + if (_splitLastPanPos != null) { + final delta = curPos - _splitLastPanPos!; + _scrollSplitByDelta(delta); + } + _splitLastPanPos = curPos; + } + } + + void _finishSplitPinchZoom() { + final finalSize = _splitActiveZoomFontSize; + if (finalSize != null) { + final double targetFontSize = finalSize + .clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize + 8.0) + .roundToDouble(); + _splitFontSize = targetFontSize; + final finalH = (targetFontSize * 1.45 + 4.0).roundToDouble(); + final finalW = targetFontSize * 0.60; + final currentLocalFocal = _splitCurrentLocalFocal ?? _splitInitialLocalFocal; + if (currentLocalFocal != null) { + final targetScrollV = _splitFocalLineContinuous * finalH - currentLocalFocal.dy; + final targetScrollH = _splitFocalCharContinuous * finalW - currentLocalFocal.dx; + _jumpSplitScroll(targetScrollV, targetScrollH); + } + } + setState(() { + _isSplitPinching = false; + _splitPointer1 = null; + _splitPointer2 = null; + _splitInitialDistance = null; + _splitInitialFontSize = null; + _splitActiveZoomFontSize = null; + _splitInitialLocalFocal = null; + _splitCurrentLocalFocal = null; + }); + } + + void _handleSplitPointerUp(PointerUpEvent event) { + _splitPointers.remove(event.pointer); + if (_isSplitPinching && + (_splitPointers.length < 2 || event.pointer == _splitPointer1 || event.pointer == _splitPointer2)) { + _finishSplitPinchZoom(); + } else if (!_isSplitPinching && _splitPointers.isEmpty) { + if (!_isDraggingDivider && _splitVelocityTracker != null) { + final estimate = _splitVelocityTracker!.getVelocity(); + final velocity = estimate.pixelsPerSecond; + _flingSplit(velocity); + } + _isDraggingDivider = false; + _splitLastPanPos = null; + } + } + + void _handleSplitPointerCancel(PointerCancelEvent event) { + _splitPointers.remove(event.pointer); + if (_isSplitPinching) { + _finishSplitPinchZoom(); + } + _isDraggingDivider = false; + _splitLastPanPos = null; + } + + void _jumpSplitScroll(double targetV, double targetH) { + _syncingSplit = true; + if (_leftVController.hasClients) { + final maxV = _leftVController.position.maxScrollExtent; + final clampedV = targetV.clamp(0.0, math.max(maxV, targetV)).toDouble(); + _leftVController.jumpTo(clampedV); + if (_leftGutterController.hasClients) _leftGutterController.jumpTo(clampedV); + } + if (_rightVController.hasClients) { + final maxV = _rightVController.position.maxScrollExtent; + final clampedV = targetV.clamp(0.0, math.max(maxV, targetV)).toDouble(); + _rightVController.jumpTo(clampedV); + if (_rightGutterController.hasClients) _rightGutterController.jumpTo(clampedV); + } + if (_leftHController.hasClients) { + final maxH = _leftHController.position.maxScrollExtent; + final clampedH = targetH.clamp(0.0, math.max(maxH, targetH)).toDouble(); + _leftHController.jumpTo(clampedH); + } + if (_rightHController.hasClients) { + final maxH = _rightHController.position.maxScrollExtent; + final clampedH = targetH.clamp(0.0, math.max(maxH, targetH)).toDouble(); + _rightHController.jumpTo(clampedH); + } + _syncingSplit = false; + } + + void _scrollSplitByDelta(Offset delta) { + _syncingSplit = true; + if (_leftVController.hasClients) { + final maxV = _leftVController.position.maxScrollExtent; + final newV = (_leftVController.offset - delta.dy).clamp(0.0, maxV); + _leftVController.jumpTo(newV); + if (_leftGutterController.hasClients) _leftGutterController.jumpTo(newV); + } + if (_rightVController.hasClients) { + final maxV = _rightVController.position.maxScrollExtent; + final newV = (_rightVController.offset - delta.dy).clamp(0.0, maxV); + _rightVController.jumpTo(newV); + if (_rightGutterController.hasClients) _rightGutterController.jumpTo(newV); + } + if (_leftHController.hasClients) { + final maxH = _leftHController.position.maxScrollExtent; + final newH = (_leftHController.offset - delta.dx).clamp(0.0, maxH); + _leftHController.jumpTo(newH); + } + if (_rightHController.hasClients) { + final maxH = _rightHController.position.maxScrollExtent; + final newH = (_rightHController.offset - delta.dx).clamp(0.0, maxH); + _rightHController.jumpTo(newH); + } + _syncingSplit = false; + } + + void _flingSplit(Offset velocity) { + if (velocity.dy.abs() > 60) { + if (_leftVController.hasClients) { + final maxV = _leftVController.position.maxScrollExtent; + final targetV = (_leftVController.offset - velocity.dy * 0.22).clamp(0.0, maxV); + _leftVController.animateTo( + targetV, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + if (_rightVController.hasClients) { + final maxV = _rightVController.position.maxScrollExtent; + final targetV = (_rightVController.offset - velocity.dy * 0.22).clamp(0.0, maxV); + _rightVController.animateTo( + targetV, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + } + if (velocity.dx.abs() > 60) { + if (_leftHController.hasClients) { + final maxH = _leftHController.position.maxScrollExtent; + final targetH = (_leftHController.offset - velocity.dx * 0.22).clamp(0.0, maxH); + _leftHController.animateTo( + targetH, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + if (_rightHController.hasClients) { + final maxH = _rightHController.position.maxScrollExtent; + final targetH = (_rightHController.offset - velocity.dx * 0.22).clamp(0.0, maxH); + _rightHController.animateTo( + targetH, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + } + } + + // --- 单屏内联指针手势处理 --- + void _handleUnifiedPointerDown( + PointerDownEvent event, + double currentFontSize, + double rowH, + double charW, + ) { + _unifiedPointers[event.pointer] = event.position; + if (_unifiedPointers.length == 1) { + _unifiedLastPanPos = event.position; + _unifiedVelocityTracker = VelocityTracker.withKind(event.kind); + _unifiedVelocityTracker?.addPosition(event.timeStamp, event.position); + } else if (_unifiedPointers.length >= 2 && !_isUnifiedPinching) { + final keys = _unifiedPointers.keys.toList(); + _unifiedPointer1 = keys[0]; + _unifiedPointer2 = keys[1]; + + final p1 = _unifiedPointers[_unifiedPointer1]!; + final p2 = _unifiedPointers[_unifiedPointer2]!; + + _unifiedInitialDistance = (p1 - p2).distance; + _unifiedInitialFontSize = _unifiedActiveZoomFontSize ?? currentFontSize; + _unifiedActiveZoomFontSize = _unifiedInitialFontSize; + + final globalFocal = (p1 + p2) / 2; + final renderBox = context.findRenderObject() as RenderBox?; + final localFocal = renderBox != null ? renderBox.globalToLocal(globalFocal) : globalFocal; + _unifiedInitialLocalFocal = localFocal; + + final curV = _unifiedVController.hasClients ? _unifiedVController.offset : 0.0; + final curH = _unifiedHController.hasClients ? _unifiedHController.offset : 0.0; + + _unifiedFocalLineContinuous = (curV + localFocal.dy) / math.max(1.0, rowH); + _unifiedFocalCharContinuous = (curH + localFocal.dx) / math.max(1.0, charW); + + _unifiedLastPanPos = null; + setState(() { + _isUnifiedPinching = true; + }); + } + } + + void _handleUnifiedPointerMove(PointerMoveEvent event) { + if (!_unifiedPointers.containsKey(event.pointer)) return; + _unifiedPointers[event.pointer] = event.position; + + if (_isUnifiedPinching) { + if (_unifiedPointer1 != null && + _unifiedPointer2 != null && + _unifiedPointers.containsKey(_unifiedPointer1) && + _unifiedPointers.containsKey(_unifiedPointer2) && + _unifiedInitialDistance != null && + _unifiedInitialDistance! > 10.0 && + _unifiedInitialFontSize != null && + _unifiedInitialLocalFocal != null) { + final p1 = _unifiedPointers[_unifiedPointer1]!; + final p2 = _unifiedPointers[_unifiedPointer2]!; + + final currentDistance = (p1 - p2).distance; + final rawScale = currentDistance / _unifiedInitialDistance!; + + final minScale = SettingsProvider.minFontSize / _unifiedInitialFontSize!; + final maxScale = (SettingsProvider.maxFontSize + 8.0) / _unifiedInitialFontSize!; + final clampedScale = rawScale.clamp(minScale * 0.9, maxScale * 1.1); + + final continuousFontSize = ((_unifiedInitialFontSize! * clampedScale) * 10).round() / 10.0; + final newFontSize = continuousFontSize.clamp( + SettingsProvider.minFontSize, + SettingsProvider.maxFontSize + 8.0, + ); + + final newRowH = (newFontSize * 1.45 + 4.0).roundToDouble(); + final newCharW = newFontSize * 0.60; + + final currentGlobalFocal = (p1 + p2) / 2; + final renderBox = context.findRenderObject() as RenderBox?; + final currentLocalFocal = renderBox != null + ? renderBox.globalToLocal(currentGlobalFocal) + : currentGlobalFocal; + _unifiedCurrentLocalFocal = currentLocalFocal; + + final targetScrollV = _unifiedFocalLineContinuous * newRowH - currentLocalFocal.dy; + final targetScrollH = _unifiedFocalCharContinuous * newCharW - currentLocalFocal.dx; + + _syncingUnified = true; + if (_unifiedVController.hasClients) { + final maxV = _unifiedVController.position.maxScrollExtent; + final clampedV = targetScrollV.clamp(0.0, math.max(maxV, targetScrollV)).toDouble(); + _unifiedVController.jumpTo(clampedV); + if (_unifiedGutterController.hasClients) _unifiedGutterController.jumpTo(clampedV); + } + if (_unifiedHController.hasClients) { + final maxH = _unifiedHController.position.maxScrollExtent; + final clampedH = targetScrollH.clamp(0.0, math.max(maxH, targetScrollH)).toDouble(); + _unifiedHController.jumpTo(clampedH); + } + _syncingUnified = false; + + if (_unifiedFontSize != newFontSize) { + setState(() { + _unifiedFontSize = newFontSize; + _unifiedActiveZoomFontSize = newFontSize; + }); + } + } + } else if (_unifiedPointers.length == 1 && !_isUnifiedPinching) { + _unifiedVelocityTracker?.addPosition(event.timeStamp, event.position); + final curPos = event.position; + if (_unifiedLastPanPos != null) { + final delta = curPos - _unifiedLastPanPos!; + _syncingUnified = true; + if (_unifiedVController.hasClients) { + final maxV = _unifiedVController.position.maxScrollExtent; + final newV = (_unifiedVController.offset - delta.dy).clamp(0.0, maxV); + _unifiedVController.jumpTo(newV); + if (_unifiedGutterController.hasClients) _unifiedGutterController.jumpTo(newV); + } + if (_unifiedHController.hasClients) { + final maxH = _unifiedHController.position.maxScrollExtent; + final newH = (_unifiedHController.offset - delta.dx).clamp(0.0, maxH); + _unifiedHController.jumpTo(newH); + } + _syncingUnified = false; + } + _unifiedLastPanPos = curPos; + } + } + + void _finishUnifiedPinchZoom() { + final finalSize = _unifiedActiveZoomFontSize; + if (finalSize != null) { + final double targetFontSize = finalSize + .clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize + 8.0) + .roundToDouble(); + _unifiedFontSize = targetFontSize; + final finalH = (targetFontSize * 1.45 + 4.0).roundToDouble(); + final finalW = targetFontSize * 0.60; + final currentLocalFocal = _unifiedCurrentLocalFocal ?? _unifiedInitialLocalFocal; + if (currentLocalFocal != null) { + final targetScrollV = _unifiedFocalLineContinuous * finalH - currentLocalFocal.dy; + final targetScrollH = _unifiedFocalCharContinuous * finalW - currentLocalFocal.dx; + _syncingUnified = true; + if (_unifiedVController.hasClients) { + final maxV = _unifiedVController.position.maxScrollExtent; + final clampedV = targetScrollV.clamp(0.0, math.max(maxV, targetScrollV)).toDouble(); + _unifiedVController.jumpTo(clampedV); + if (_unifiedGutterController.hasClients) _unifiedGutterController.jumpTo(clampedV); + } + if (_unifiedHController.hasClients) { + final maxH = _unifiedHController.position.maxScrollExtent; + final clampedH = targetScrollH.clamp(0.0, math.max(maxH, targetScrollH)).toDouble(); + _unifiedHController.jumpTo(clampedH); + } + _syncingUnified = false; + } + } + setState(() { + _isUnifiedPinching = false; + _unifiedPointer1 = null; + _unifiedPointer2 = null; + _unifiedInitialDistance = null; + _unifiedInitialFontSize = null; + _unifiedActiveZoomFontSize = null; + _unifiedInitialLocalFocal = null; + _unifiedCurrentLocalFocal = null; + }); + } + + void _handleUnifiedPointerUp(PointerUpEvent event) { + _unifiedPointers.remove(event.pointer); + if (_isUnifiedPinching && + (_unifiedPointers.length < 2 || event.pointer == _unifiedPointer1 || event.pointer == _unifiedPointer2)) { + _finishUnifiedPinchZoom(); + } else if (!_isUnifiedPinching && _unifiedPointers.isEmpty) { + if (_unifiedVelocityTracker != null) { + final estimate = _unifiedVelocityTracker!.getVelocity(); + final velocity = estimate.pixelsPerSecond; + if (velocity.dy.abs() > 60 && _unifiedVController.hasClients) { + final maxV = _unifiedVController.position.maxScrollExtent; + final targetV = (_unifiedVController.offset - velocity.dy * 0.22).clamp(0.0, maxV); + _unifiedVController.animateTo( + targetV, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + if (velocity.dx.abs() > 60 && _unifiedHController.hasClients) { + final maxH = _unifiedHController.position.maxScrollExtent; + final targetH = (_unifiedHController.offset - velocity.dx * 0.22).clamp(0.0, maxH); + _unifiedHController.animateTo( + targetH, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + } + _unifiedLastPanPos = null; + } + } + + void _handleUnifiedPointerCancel(PointerCancelEvent event) { + _unifiedPointers.remove(event.pointer); + if (_isUnifiedPinching) { + _finishUnifiedPinchZoom(); + } + _unifiedLastPanPos = null; + } + + Widget _buildZoomBadge(EditorTheme editorTheme, double fontSize) { + return Positioned( + top: 16, + left: 0, + right: 0, + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), + decoration: BoxDecoration( + color: editorTheme.isDark + ? Colors.white.withValues(alpha: 0.85) + : Colors.black.withValues(alpha: 0.75), + borderRadius: BorderRadius.circular(16), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.2), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Text( + '${fontSize.toStringAsFixed(1)} pt', + style: TextStyle( + color: editorTheme.isDark ? Colors.black : Colors.white, + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + ), + ), + ); + } + + TextSpan _getHighlightedLineSpan({ + required String code, + required TextStyle baseStyle, + required EditorTheme editorTheme, + }) { + if (code.isEmpty) { + return TextSpan(text: '', style: baseStyle); + } + final key = '${baseStyle.fontSize}-${editorTheme.id}-$code'; + final cached = _highlightSpanCache[key]; + if (cached != null) { + return cached; + } + final span = SyntaxHighlightHelper.highlightLine( + code: code, + filePath: _currentFile.relativePath, + baseStyle: baseStyle, + highlightTheme: editorTheme.highlightTheme, + ); + _highlightSpanCache[key] = span; + return span; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final l10n = AppLocalizations.of(context)!; + final split = _splitResult; + + // 获取独立的代码编辑器主题与默认字号配置 + EditorTheme editorTheme = EditorTheme.atomOneDark; + double baseFontSize = 14.0; + AppFontItem editorFont = AppFonts.editorJetBrainsMono; + try { + final settings = context.watch(); + editorTheme = settings.editorTheme; + baseFontSize = settings.fontSize; + editorFont = settings.editorFont; + } catch (_) {} + + // 字号计算:双屏统一使用 _splitFontSize,单屏内联使用 _unifiedFontSize,初始使用编辑区字号 + final splitFontSize = _splitFontSize ?? baseFontSize; + final unifiedFontSize = _unifiedFontSize ?? baseFontSize; + + final splitRowHeight = (splitFontSize * 1.45 + 4.0).roundToDouble(); + final unifiedRowHeight = (unifiedFontSize * 1.45 + 4.0).roundToDouble(); + + return Scaffold( + backgroundColor: editorTheme.backgroundColor, + appBar: AppBar( + titleSpacing: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back_rounded), + onPressed: () => Navigator.of(context).pop(), + ), + title: Row( + children: [ + Icon( + FileIconUtils.getIcon(name: _currentFile.fileName, isDirectory: false), + size: 18, + color: colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Flexible( + child: Text( + _currentFile.fileName, + style: const TextStyle(fontSize: 14.5, fontWeight: FontWeight.bold), + overflow: TextOverflow.ellipsis, + ), + ), + if (split != null && (split.additionsCount > 0 || split.deletionsCount > 0)) ...[ + const SizedBox(width: 6), + if (split.additionsCount > 0) + Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(3), + ), + child: Text( + '+${split.additionsCount}', + style: const TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: Colors.green, + fontFamily: 'JetBrains Mono', + ), + ), + ), + if (split.deletionsCount > 0) ...[ + const SizedBox(width: 3), + Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), + decoration: BoxDecoration( + color: Colors.red.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(3), + ), + child: Text( + '-${split.deletionsCount}', + style: const TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: Colors.red, + fontFamily: 'JetBrains Mono', + ), + ), + ), + ], + ], + ], + ), + if (_currentFile.directoryPath.isNotEmpty) + Text( + _currentFile.directoryPath, + style: TextStyle( + fontSize: 10.5, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + actions: [ + // 上一处更改 + IconButton( + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + splashRadius: 16, + iconSize: 20, + icon: const Icon(Icons.keyboard_arrow_up_rounded), + tooltip: l10n.gitDiffPrevChange, + onPressed: (_splitResult?.changeRowIndices.isNotEmpty ?? false) + ? () => _navigateToPrevChange(splitRowHeight, unifiedRowHeight) + : null, + ), + // 下一处更改 + IconButton( + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + splashRadius: 16, + iconSize: 20, + icon: const Icon(Icons.keyboard_arrow_down_rounded), + tooltip: l10n.gitDiffNextChange, + onPressed: (_splitResult?.changeRowIndices.isNotEmpty ?? false) + ? () => _navigateToNextChange(splitRowHeight, unifiedRowHeight) + : null, + ), + // 切换分栏 / 内联 + IconButton( + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + splashRadius: 16, + iconSize: 18, + icon: Icon(_isSplitMode ? Icons.view_agenda_outlined : Icons.vertical_split_outlined), + tooltip: _isSplitMode ? l10n.gitDiffUnifiedView : l10n.gitDiffSplitView, + onPressed: () { + setState(() { + _isSplitMode = !_isSplitMode; + }); + }, + ), + const SizedBox(width: 8), + ], + ), + body: _buildBody( + context, + theme, + l10n, + editorTheme, + editorFont, + splitFontSize, + unifiedFontSize, + splitRowHeight, + unifiedRowHeight, + ), + ); + } + + Widget _buildBody( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + EditorTheme editorTheme, + AppFontItem editorFont, + double splitFontSize, + double unifiedFontSize, + double splitRowHeight, + double unifiedRowHeight, + ) { + if (_isLoading) { + return Container( + color: editorTheme.backgroundColor, + width: double.infinity, + height: double.infinity, + child: const Center(child: CircularProgressIndicator()), + ); + } + + if (_errorMessage != null) { + return Container( + color: editorTheme.backgroundColor, + width: double.infinity, + height: double.infinity, + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, size: 44, color: Colors.red), + const SizedBox(height: 12), + Text( + _errorMessage!, + style: TextStyle(fontSize: 13, color: editorTheme.textColor), + ), + const SizedBox(height: 12), + FilledButton.icon( + onPressed: _loadDiff, + icon: const Icon(Icons.refresh, size: 16), + label: Text(l10n.gitRefresh), + ), + ], + ), + ), + ); + } + + final split = _splitResult; + if (split == null || (split.leftLines.isEmpty && split.rightLines.isEmpty)) { + return Container( + color: editorTheme.backgroundColor, + width: double.infinity, + height: double.infinity, + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.check_circle_outline_rounded, + size: 48, + color: editorTheme.gutterTextColor.withValues(alpha: 0.6), + ), + const SizedBox(height: 12), + Text( + l10n.gitDiffNoChanges, + style: TextStyle( + fontSize: 13, + color: editorTheme.gutterTextColor, + fontFamily: editorFont.fontFamily, + ), + ), + ], + ), + ), + ); + } + + if (_isSplitMode) { + return _buildSplitDiffView( + context, + theme, + l10n, + split, + editorTheme, + editorFont, + splitFontSize, + splitRowHeight, + ); + } else { + return _buildUnifiedDiffView( + context, + theme, + l10n, + editorTheme, + editorFont, + unifiedFontSize, + unifiedRowHeight, + ); + } + } + + /// 构建双屏并排对比视图(左右两个内容区完全同步滚动与同步缩放,对标编辑器彻底消除抖动) + Widget _buildSplitDiffView( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + SplitDiffResult split, + EditorTheme editorTheme, + AppFontItem editorFont, + double splitFontSize, + double splitRowHeight, + ) { + final subHeaderBg = editorTheme.isDark + ? const Color(0xFF1E2227) + : const Color(0xFFEEEEEE); + final borderColor = editorTheme.gutterTextColor.withValues(alpha: 0.25); + + final displayFontSize = _splitActiveZoomFontSize ?? splitFontSize; + final displayRowHeight = (displayFontSize * 1.45 + 4.0).roundToDouble(); + final displayCharWidth = displayFontSize * 0.60; + + return LayoutBuilder( + builder: (ctx, constraints) { + final totalWidth = constraints.maxWidth; + const dividerWidth = 18.0; + final availableWidth = totalWidth - dividerWidth; + final leftWidth = availableWidth * _splitRatio; + final rightWidth = availableWidth * (1.0 - _splitRatio); + + return Listener( + behavior: HitTestBehavior.opaque, + onPointerDown: (e) => _handleSplitPointerDown( + e, + displayFontSize, + displayRowHeight, + displayCharWidth, + leftWidth, + dividerWidth, + ), + onPointerMove: _handleSplitPointerMove, + onPointerUp: _handleSplitPointerUp, + onPointerCancel: _handleSplitPointerCancel, + child: Stack( + children: [ + IgnorePointer( + ignoring: _isSplitPinching, + child: Container( + color: editorTheme.backgroundColor, + width: double.infinity, + height: double.infinity, + child: Column( + children: [ + // 双屏顶栏:原始版本 vs 修改版本标签 + Container( + height: 30, + decoration: BoxDecoration( + color: subHeaderBg, + border: Border(bottom: BorderSide(color: borderColor, width: 1.0)), + ), + child: Row( + children: [ + SizedBox( + width: leftWidth, + child: ClipRect( + child: leftWidth < 28 + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.history_rounded, size: 14, color: editorTheme.gutterTextColor), + if (leftWidth >= 65) ...[ + const SizedBox(width: 4), + Expanded( + child: Text( + l10n.gitDiffOriginal, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: editorTheme.gutterTextColor, + fontFamily: editorFont.fontFamily, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ], + ), + ), + ), + ), + SizedBox( + width: dividerWidth, + child: Center( + child: Container( + width: 1.0, + height: 16, + color: borderColor, + ), + ), + ), + SizedBox( + width: rightWidth, + child: ClipRect( + child: rightWidth < 28 + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.edit_note_rounded, size: 15, color: theme.colorScheme.primary), + if (rightWidth >= 65) ...[ + const SizedBox(width: 4), + Expanded( + child: Text( + l10n.gitDiffModified, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: theme.colorScheme.primary, + fontFamily: editorFont.fontFamily, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ], + ), + ), + ), + ), + ], + ), + ), + + // 双屏代码对比区域(左右两侧完全同步滚动、同步缩放) + Expanded( + child: Row( + children: [ + // 左栏 (原始文件) + SizedBox( + width: leftWidth, + child: _buildSideCodePane( + vController: _leftVController, + hController: _leftHController, + gutterController: _leftGutterController, + lines: split.leftLines, + isLeft: true, + editorTheme: editorTheme, + fontSize: displayFontSize, + editorFont: editorFont, + rowHeight: displayRowHeight, + viewportWidth: leftWidth, + ), + ), + + // 中间可拖拽竖直分割线(宽大舒适触控手柄) + GestureDetector( + behavior: HitTestBehavior.opaque, + onHorizontalDragUpdate: (details) { + setState(() { + _splitRatio = (_splitRatio + details.delta.dx / availableWidth).clamp(0.05, 0.95); + }); + }, + onDoubleTap: () { + setState(() { + _splitRatio = 0.5; + }); + }, + child: Container( + width: dividerWidth, + height: double.infinity, + color: editorTheme.backgroundColor, + child: Stack( + alignment: Alignment.center, + children: [ + // 背景通顶细线 + Container( + width: 1.0, + height: double.infinity, + color: borderColor, + ), + // 加大加宽的胶囊形拖动手柄按钮(宽 14,高 56) + Container( + width: 14.0, + height: 56.0, + decoration: BoxDecoration( + color: editorTheme.isDark + ? const Color(0xFF282C34) + : const Color(0xFFE5E7EB), + borderRadius: BorderRadius.circular(7), + border: Border.all( + color: editorTheme.gutterTextColor.withValues(alpha: 0.35), + width: 1.0, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.15), + blurRadius: 3, + offset: const Offset(0, 1), + ), + ], + ), + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 6.0, + height: 2.0, + decoration: BoxDecoration( + color: editorTheme.gutterTextColor.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular(1), + ), + ), + const SizedBox(height: 3.5), + Container( + width: 6.0, + height: 2.0, + decoration: BoxDecoration( + color: editorTheme.gutterTextColor.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular(1), + ), + ), + const SizedBox(height: 3.5), + Container( + width: 6.0, + height: 2.0, + decoration: BoxDecoration( + color: editorTheme.gutterTextColor.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular(1), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + + // 右栏 (修改文件) + SizedBox( + width: rightWidth, + child: _buildSideCodePane( + vController: _rightVController, + hController: _rightHController, + gutterController: _rightGutterController, + lines: split.rightLines, + isLeft: false, + editorTheme: editorTheme, + fontSize: displayFontSize, + editorFont: editorFont, + rowHeight: displayRowHeight, + viewportWidth: rightWidth, + ), + ), + ], + ), + ), + ], + ), + ), + ), + + // 缩放实时字号胶囊悬浮气泡 + if (_isSplitPinching && _splitActiveZoomFontSize != null) + _buildZoomBadge(editorTheme, _splitActiveZoomFontSize!), + ], + ), + ); + }, + ); + } + + /// 单侧独立代码视图(整区横向同步滚动、行号区内显示符号、完整语法高亮) + Widget _buildSideCodePane({ + required ScrollController vController, + required ScrollController hController, + required ScrollController gutterController, + required List lines, + required bool isLeft, + required EditorTheme editorTheme, + required double fontSize, + required AppFontItem editorFont, + required double rowHeight, + required double viewportWidth, + }) { + if (viewportWidth <= 0) { + return const SizedBox.shrink(); + } + + final gutterBg = editorTheme.gutterBackgroundColor ?? editorTheme.backgroundColor; + final gutterDividerColor = editorTheme.gutterTextColor.withValues(alpha: 0.25); + final isDark = editorTheme.isDark; + + // 计算行号栏宽度 + final totalLines = lines.length; + final digits = totalLines > 0 ? '$totalLines'.length : 1; + final charW = fontSize * 0.60; + final gutterWidth = math.max(44.0, digits * charW + 24.0); + + // 视口极限狭窄自适应判定(彻底根治 RenderFlex 水平溢出) + final bool hasCodeArea = viewportWidth > (gutterWidth + 1.0); + final double actualGutterWidth = hasCodeArea + ? gutterWidth + : math.max(0.0, viewportWidth - 1.0); + final bool hasDivider = viewportWidth >= 1.0; + + // 计算代码最长行宽度,支撑整区横向同步滚动 + int maxChars = 0; + for (final l in lines) { + if (l.text.length > maxChars) { + maxChars = l.text.length; + } + } + final codeContentAvailableWidth = math.max(10.0, viewportWidth - gutterWidth - 1.0); + final maxCodeWidth = math.max(codeContentAvailableWidth, maxChars * charW + 200.0); + + return Stack( + children: [ + // 1. 全屏底层常驻背景与垂直分割线 + Positioned.fill( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (actualGutterWidth > 0) + Container( + width: actualGutterWidth, + color: gutterBg, + ), + if (hasDivider) + Container( + width: 1.0, + color: gutterDividerColor, + ), + if (hasCodeArea) + Expanded( + child: Container(color: editorTheme.backgroundColor), + ), + ], + ), + ), + + // 2. 主体视口内容 + Positioned.fill( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 固定的行号栏(符号在行号区显示,垂直随代码同步滚动,水平不滚出;极限狭窄时平滑右对齐裁切防溢出) + if (actualGutterWidth > 0) + SizedBox( + width: actualGutterWidth, + child: ClipRect( + child: OverflowBox( + alignment: Alignment.centerRight, + minWidth: 0, + maxWidth: gutterWidth, + child: SizedBox( + width: gutterWidth, + child: ListView.builder( + controller: gutterController, + physics: const NeverScrollableScrollPhysics(), + itemCount: lines.length, + itemExtent: rowHeight, + padding: const EdgeInsets.only(bottom: 240.0), + itemBuilder: (ctx, index) { + final line = lines[index]; + final isDeleted = line.type == DiffLineType.deleted; + final isAdded = line.type == DiffLineType.added; + final isEmpty = line.type == DiffLineType.empty; + + Color? rowBgColor; + if (isDeleted) { + rowBgColor = Colors.red.withValues(alpha: isDark ? 0.22 : 0.14); + } else if (isAdded) { + rowBgColor = Colors.green.withValues(alpha: isDark ? 0.22 : 0.14); + } else if (isEmpty) { + rowBgColor = isDark ? Colors.white.withValues(alpha: 0.035) : Colors.black.withValues(alpha: 0.035); + } + + final signColor = isDeleted + ? (isDark ? const Color(0xFFEF5350) : const Color(0xFFD32F2F)) + : (isDark ? const Color(0xFF66BB6A) : const Color(0xFF2E7D32)); + + return Container( + height: rowHeight, + color: rowBgColor, + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Row( + children: [ + // 行号 + Expanded( + child: Text( + line.lineNumber != null ? '${line.lineNumber}' : '', + textAlign: TextAlign.right, + style: TextStyle( + fontSize: (fontSize - 1).clamp(SettingsProvider.minFontSize - 1.0, SettingsProvider.maxFontSize + 8.0), + fontFamily: editorFont.fontFamily, + fontFamilyFallback: editorFont.fallback, + height: 1.4, + color: isDeleted || isAdded ? signColor : editorTheme.gutterTextColor, + ), + ), + ), + const SizedBox(width: 4), + // 加号/减号符号严格显示在行号区内! + SizedBox( + width: 12, + child: Center( + child: Text( + isDeleted ? '-' : (isAdded ? '+' : ''), + style: TextStyle( + fontSize: (fontSize - 1).clamp(SettingsProvider.minFontSize - 1.0, SettingsProvider.maxFontSize + 8.0), + fontWeight: FontWeight.bold, + fontFamily: editorFont.fontFamily, + fontFamilyFallback: editorFont.fallback, + height: 1.4, + color: signColor, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), + ), + ), + ), + + // 行号与代码之间的常驻分隔坚线 + if (hasDivider) + Container( + width: 1.0, + color: gutterDividerColor, + ), + + // 代码内容区(仅当空间足够容纳代码区时构建 Expanded,彻底根除视口极限挤压时的 RenderFlex 水平溢出) + 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.0), + itemBuilder: (ctx, index) { + final line = lines[index]; + final isDeleted = line.type == DiffLineType.deleted; + final isAdded = line.type == DiffLineType.added; + final isEmpty = line.type == DiffLineType.empty; + + Color? rowBgColor; + if (isDeleted) { + rowBgColor = Colors.red.withValues(alpha: isDark ? 0.22 : 0.14); + } else if (isAdded) { + rowBgColor = Colors.green.withValues(alpha: isDark ? 0.22 : 0.14); + } else if (isEmpty) { + rowBgColor = isDark ? Colors.white.withValues(alpha: 0.035) : Colors.black.withValues(alpha: 0.035); + } + + final baseStyle = TextStyle( + fontSize: fontSize, + fontFamily: editorFont.fontFamily, + fontFamilyFallback: editorFont.fallback, + height: 1.4, + color: editorTheme.textColor, + ); + + // 获取带语法高亮的 TextSpan + final span = _getHighlightedLineSpan( + code: line.text, + baseStyle: baseStyle, + editorTheme: editorTheme, + ); + + return Container( + height: rowHeight, + color: rowBgColor, + alignment: Alignment.centerLeft, + padding: const EdgeInsets.only(left: 6.0, right: 160.0), + child: Text.rich( + span, + overflow: TextOverflow.visible, + softWrap: false, + ), + ); + }, + ), + ), + ), + ), + ], + ), + ), + ], + ); + } + + /// 构建单屏内联 (Unified) 对比视图(单行号列、带完整语法高亮、全向平滑滚动与基于 Listener 的稳定缩放) + Widget _buildUnifiedDiffView( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + EditorTheme editorTheme, + AppFontItem editorFont, + double unifiedFontSize, + double unifiedRowHeight, + ) { + final gutterBg = editorTheme.gutterBackgroundColor ?? editorTheme.backgroundColor; + final gutterDividerColor = editorTheme.gutterTextColor.withValues(alpha: 0.25); + final isDark = editorTheme.isDark; + final lines = _unifiedLines; + + final displayFontSize = _unifiedActiveZoomFontSize ?? unifiedFontSize; + final displayRowHeight = (displayFontSize * 1.45 + 4.0).roundToDouble(); + final displayCharWidth = displayFontSize * 0.60; + + final totalLines = lines.length; + final digits = totalLines > 0 ? '$totalLines'.length : 1; + final gutterWidth = math.max(44.0, digits * displayCharWidth + 24.0); + + int maxChars = 0; + for (final l in lines) { + if (l.text.length > maxChars) { + maxChars = l.text.length; + } + } + final screenWidth = MediaQuery.of(context).size.width; + final codeContentAvailableWidth = math.max(10.0, screenWidth - gutterWidth - 1.0); + final maxCodeWidth = math.max(codeContentAvailableWidth, maxChars * displayCharWidth + 200.0); + + return Listener( + behavior: HitTestBehavior.opaque, + onPointerDown: (e) => _handleUnifiedPointerDown( + e, + displayFontSize, + displayRowHeight, + displayCharWidth, + ), + onPointerMove: _handleUnifiedPointerMove, + onPointerUp: _handleUnifiedPointerUp, + onPointerCancel: _handleUnifiedPointerCancel, + child: Stack( + children: [ + IgnorePointer( + ignoring: _isUnifiedPinching, + child: Container( + color: editorTheme.backgroundColor, + width: double.infinity, + height: double.infinity, + child: Stack( + children: [ + // 全屏背景与常驻行号竖线 + Positioned.fill( + child: Row( + children: [ + Container( + width: gutterWidth, + color: gutterBg, + ), + Container( + width: 1.0, + color: gutterDividerColor, + ), + Expanded( + child: Container(color: editorTheme.backgroundColor), + ), + ], + ), + ), + + // 内联差异内容 + Positioned.fill( + child: Row( + children: [ + // 单行号列(仅显示一列行号与符号指示器,消除双行号混乱) + SizedBox( + width: gutterWidth, + child: ListView.builder( + controller: _unifiedGutterController, + physics: const NeverScrollableScrollPhysics(), + itemCount: lines.length, + itemExtent: displayRowHeight, + padding: const EdgeInsets.only(bottom: 240.0), + itemBuilder: (ctx, index) { + final line = lines[index]; + final isDeleted = line.type == DiffLineType.deleted; + final isAdded = line.type == DiffLineType.added; + + Color? rowBgColor; + if (isDeleted) { + rowBgColor = Colors.red.withValues(alpha: isDark ? 0.22 : 0.14); + } else if (isAdded) { + rowBgColor = Colors.green.withValues(alpha: isDark ? 0.22 : 0.14); + } + + final signColor = isDeleted + ? (isDark ? const Color(0xFFEF5350) : const Color(0xFFD32F2F)) + : (isDark ? const Color(0xFF66BB6A) : const Color(0xFF2E7D32)); + + // 仅显示单个行号:删除行显示旧号,新增/修改/未改行显示新号 + final int? lineNum = isDeleted ? line.oldLineNumber : (line.newLineNumber ?? line.oldLineNumber); + + return Container( + height: displayRowHeight, + color: rowBgColor, + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Row( + children: [ + // 单列行号 + Expanded( + child: Text( + lineNum != null ? '$lineNum' : '', + textAlign: TextAlign.right, + style: TextStyle( + fontSize: (displayFontSize - 1).clamp(SettingsProvider.minFontSize - 1.0, SettingsProvider.maxFontSize + 8.0), + fontFamily: editorFont.fontFamily, + fontFamilyFallback: editorFont.fallback, + height: 1.4, + color: isDeleted || isAdded ? signColor : editorTheme.gutterTextColor, + ), + ), + ), + const SizedBox(width: 4), + // 符号指示器(+ / -)同样在行号区内! + SizedBox( + width: 12, + child: Center( + child: Text( + isDeleted ? '-' : (isAdded ? '+' : ''), + style: TextStyle( + fontSize: (displayFontSize - 1).clamp(SettingsProvider.minFontSize - 1.0, SettingsProvider.maxFontSize + 8.0), + fontWeight: FontWeight.bold, + fontFamily: editorFont.fontFamily, + fontFamilyFallback: editorFont.fallback, + height: 1.4, + color: signColor, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), + + // 分隔坚线 + Container( + width: 1.0, + color: gutterDividerColor, + ), + + // 纯代码内容区(整区横向同步滚动,支持完整语法高亮) + Expanded( + child: SingleChildScrollView( + controller: _unifiedHController, + scrollDirection: Axis.horizontal, + physics: const NeverScrollableScrollPhysics(), + child: SizedBox( + width: maxCodeWidth, + child: ListView.builder( + controller: _unifiedVController, + physics: const NeverScrollableScrollPhysics(), + itemCount: lines.length, + itemExtent: displayRowHeight, + padding: const EdgeInsets.only(bottom: 240.0), + itemBuilder: (ctx, index) { + final line = lines[index]; + final isDeleted = line.type == DiffLineType.deleted; + final isAdded = line.type == DiffLineType.added; + + Color? rowBgColor; + if (isDeleted) { + rowBgColor = Colors.red.withValues(alpha: isDark ? 0.22 : 0.14); + } else if (isAdded) { + rowBgColor = Colors.green.withValues(alpha: isDark ? 0.22 : 0.14); + } + + final baseStyle = TextStyle( + fontSize: displayFontSize, + fontFamily: editorFont.fontFamily, + fontFamilyFallback: editorFont.fallback, + height: 1.4, + color: editorTheme.textColor, + ); + + // 获取带语法高亮的 TextSpan + final span = _getHighlightedLineSpan( + code: line.text, + baseStyle: baseStyle, + editorTheme: editorTheme, + ); + + return Container( + height: displayRowHeight, + color: rowBgColor, + alignment: Alignment.centerLeft, + padding: const EdgeInsets.only(left: 6.0, right: 160.0), + child: Text.rich( + span, + overflow: TextOverflow.visible, + softWrap: false, + ), + ); + }, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + + // 缩放实时字号胶囊悬浮气泡 + if (_isUnifiedPinching && _unifiedActiveZoomFontSize != null) + _buildZoomBadge(editorTheme, _unifiedActiveZoomFontSize!), + ], + ), + ); + } +} diff --git a/lib/widgets/git/git_graph_painter.dart b/lib/widgets/git/git_graph_painter.dart new file mode 100644 index 0000000..3a5fd07 --- /dev/null +++ b/lib/widgets/git/git_graph_painter.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; +import '../../models/git_model.dart'; + +/// VS Code 风格 Git 提交历史拓扑图绘制器 +class GitGraphPainter extends CustomPainter { + final GitCommit commit; + final bool isFirstCommit; + final ColorScheme colorScheme; + + static const double laneWidth = 14.0; + static const double startOffset = 14.0; + + // 经典多分支着色调色板 + static const List laneColors = [ + Color(0xFF2196F3), // 蓝 + Color(0xFF4CAF50), // 绿 + Color(0xFFFF9800), // 橙 + Color(0xFFE91E63), // 粉红 + Color(0xFF9C27B0), // 紫 + Color(0xFF00BCD4), // 青 + Color(0xFFFFEB3B), // 黄 + Color(0xFF795548), // 棕 + ]; + + static Color getLaneColor(int lane) { + return laneColors[lane % laneColors.length]; + } + + const GitGraphPainter({ + required this.commit, + required this.isFirstCommit, + required this.colorScheme, + }); + + @override + void paint(Canvas canvas, Size size) { + final centerY = size.height / 2; + final nodeX = startOffset + commit.lane * laneWidth; + final nodeColor = getLaneColor(commit.lane); + + final linePaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.round; + + // 1. 绘制穿透此行的其他活跃通道 + for (final lane in commit.activeLanes) { + if (lane == commit.lane) continue; + final x = startOffset + lane * laneWidth; + linePaint.color = getLaneColor(lane); + canvas.drawLine(Offset(x, 0), Offset(x, size.height), linePaint); + } + + // 2. 绘制进入当前节点的连线(如果不是首个展示的提交,说明上方有子提交连入) + if (!isFirstCommit) { + linePaint.color = nodeColor; + canvas.drawLine(Offset(nodeX, 0), Offset(nodeX, centerY), linePaint); + } + + // 3. 绘制当前节点连向父提交的连线 + for (final targetLane in commit.outgoingLanes) { + final targetX = startOffset + targetLane * laneWidth; + linePaint.color = nodeColor; + + if (targetLane == commit.lane) { + // 直线向下连到下一行 + canvas.drawLine(Offset(nodeX, centerY), Offset(nodeX, size.height), linePaint); + } else { + // 跨分支弧线(贝塞尔平滑曲线) + final path = Path(); + path.moveTo(nodeX, centerY); + final controlY = centerY + (size.height - centerY) * 0.5; + path.cubicTo(nodeX, controlY, targetX, controlY, targetX, size.height); + canvas.drawPath(path, linePaint); + } + } + + // 4. 绘制提交节点 + final bgPaint = Paint() + ..style = PaintingStyle.fill + ..color = colorScheme.surface; + + final dotPaint = Paint() + ..style = PaintingStyle.fill + ..color = nodeColor; + + // 节点外围背景微隔离圈,防止与连线黏连 + canvas.drawCircle(Offset(nodeX, centerY), 6.5, bgPaint); + + if (commit.isHead) { + // HEAD 节点:外圈光环 + 内部实心 + final haloPaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2.2 + ..color = nodeColor; + canvas.drawCircle(Offset(nodeX, centerY), 6.0, haloPaint); + canvas.drawCircle(Offset(nodeX, centerY), 3.2, dotPaint); + } else { + // 普通节点:实心圆 + canvas.drawCircle(Offset(nodeX, centerY), 4.5, dotPaint); + } + } + + @override + bool shouldRepaint(covariant GitGraphPainter oldDelegate) { + return oldDelegate.commit != commit || + oldDelegate.isFirstCommit != isFirstCommit || + oldDelegate.colorScheme != colorScheme; + } +} diff --git a/lib/widgets/git/git_panel_widget.dart b/lib/widgets/git/git_panel_widget.dart new file mode 100644 index 0000000..e805c2d --- /dev/null +++ b/lib/widgets/git/git_panel_widget.dart @@ -0,0 +1,3112 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/git_model.dart'; +import '../../providers/git_provider.dart'; +import '../../providers/tab_provider.dart'; +import '../../utils/dialog_utils.dart'; +import '../../utils/file_icon_utils.dart'; +import 'git_diff_page.dart'; +import 'git_graph_painter.dart'; + +/// Git 版本控制侧边栏面板组件 +class GitPanelWidget extends StatefulWidget { + const GitPanelWidget({super.key}); + + @override + State createState() => _GitPanelWidgetState(); +} + +class _GitPanelWidgetState extends State { + final ScrollController _scrollController = ScrollController(); + final TextEditingController _commitMsgController = TextEditingController(); + final GlobalKey _branchBarKey = GlobalKey(); + bool _stagedExpanded = true; + bool _unstagedExpanded = true; + bool _graphExpanded = true; + bool _showTagsInSelector = false; + GitProvider? _gitProvider; + + @override + void initState() { + super.initState(); + final gitProvider = context.read(); + _gitProvider = gitProvider; + _stagedExpanded = gitProvider.stagedExpanded; + _unstagedExpanded = gitProvider.unstagedExpanded; + _graphExpanded = gitProvider.graphExpanded; + _showTagsInSelector = gitProvider.showTagsInSelector; + _commitMsgController.text = gitProvider.commitMessage; + + _commitMsgController.addListener(_onCommitMsgChanged); + _scrollController.addListener(_onScrollChanged); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _scrollController.hasClients && gitProvider.scrollOffset > 0) { + final maxScroll = _scrollController.position.maxScrollExtent; + final target = gitProvider.scrollOffset.clamp(0.0, maxScroll); + _scrollController.jumpTo(target); + } + }); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _gitProvider = context.read(); + } + + void _onCommitMsgChanged() { + _gitProvider?.setCommitMessage(_commitMsgController.text); + } + + void _onScrollChanged() { + if (_scrollController.hasClients) { + _gitProvider?.setScrollOffset(_scrollController.offset); + } + } + + @override + void dispose() { + _commitMsgController.removeListener(_onCommitMsgChanged); + _scrollController.removeListener(_onScrollChanged); + _scrollController.dispose(); + _commitMsgController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final gitProvider = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 顶部操作栏 + _buildHeader(context, theme, l10n, gitProvider), + + // 主体内容区 + Expanded( + child: _buildBody(context, theme, l10n, gitProvider), + ), + ], + ); + } + + /// 顶部标题与操作栏 + Widget _buildHeader( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + final repos = gitProvider.repositories; + final currentRepo = gitProvider.currentRepo; + final branch = gitProvider.currentBranch; + + return Container( + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer, + ), + child: SafeArea( + bottom: false, + left: false, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + // 第一行:标题、多仓库切换、刷新、更多操作 + Row( + children: [ + // 标题 + Text( + l10n.drawerTabGit, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + + const SizedBox(width: 8), + + // 多仓库切换下拉菜单(若发现多个仓库) + if (repos.length > 1) ...[ + PopupMenuButton( + tooltip: l10n.gitSwitchRepo, + initialValue: gitProvider.currentRepoPath, + onSelected: (path) => gitProvider.switchRepository(path), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: theme.colorScheme.surface.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 0.8, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.source_outlined, + size: 14, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 4), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 110), + child: Text( + currentRepo?.name ?? l10n.gitRepository, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurface, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + const SizedBox(width: 2), + Icon( + Icons.arrow_drop_down, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + ), + itemBuilder: (ctx) { + return repos.map((r) { + final isSelected = r.rootPath == gitProvider.currentRepoPath; + return PopupMenuItem( + value: r.rootPath, + child: Row( + children: [ + Icon( + r.isRoot ? Icons.folder_special_outlined : Icons.folder_outlined, + size: 16, + color: isSelected ? theme.colorScheme.primary : null, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + r.name, + style: TextStyle( + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, + fontSize: 13, + ), + overflow: TextOverflow.ellipsis, + ), + if (r.currentBranch != null) + Text( + r.currentBranch!, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + if (isSelected) + Icon(Icons.check, size: 16, color: theme.colorScheme.primary), + ], + ), + ); + }).toList(); + }, + ), + const SizedBox(width: 6), + ], + + const Spacer(), + + // 刷新按钮 + if (gitProvider.hasProject && gitProvider.gitInstalled) + IconButton( + icon: const Icon(Icons.refresh, size: 18), + tooltip: l10n.gitRefresh, + visualDensity: VisualDensity.compact, + onPressed: gitProvider.isLoading ? null : () => gitProvider.refresh(), + ), + + // 更多操作 (撤销上次提交、Stash 贮藏等) + if (gitProvider.hasProject && gitProvider.gitInstalled && gitProvider.hasRepository) + _buildMoreActionsMenu(context, theme, l10n, gitProvider), + ], + ), + + // 第二行:当前分支/标签栏与行更多操作按钮 + if (currentRepo != null && branch != null && branch.isNotEmpty) ...[ + const SizedBox(height: 6), + Row( + children: [ + Expanded( + child: _buildBranchSelectorBar(context, theme, l10n, gitProvider, branch), + ), + const SizedBox(width: 6), + _buildBranchRowMoreButton(context, theme, l10n, gitProvider, branch), + ], + ), + ], + ], + ), + ), + ), + ); + } + + /// 独立分支/标签切换条组件(Title 下方独占一行,点击展开下拉分支/标签菜单) + Widget _buildBranchSelectorBar( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + String currentBranch, + ) { + return Material( + color: Colors.transparent, + child: InkWell( + key: _branchBarKey, + borderRadius: BorderRadius.circular(6), + onTap: () => _showBranchOrTagSelectorMenu(context, theme, l10n, gitProvider, currentBranch), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: theme.colorScheme.surface.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4), + width: 0.8, + ), + ), + child: Row( + children: [ + Icon( + gitProvider.isCurrentRefTag ? Icons.local_offer_outlined : Icons.call_split_rounded, + size: 14, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + currentBranch, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurface, + fontFamily: 'JetBrains Mono', + ), + overflow: TextOverflow.ellipsis, + ), + ), + if (gitProvider.stashCount > 0) ...[ + Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + decoration: BoxDecoration( + color: theme.colorScheme.tertiaryContainer, + borderRadius: BorderRadius.circular(4), + ), + child: Text( + 'stash: ${gitProvider.stashCount}', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onTertiaryContainer, + ), + ), + ), + const SizedBox(width: 4), + ], + Icon( + Icons.arrow_drop_down, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + ), + ), + ); + } + + /// 展开分支或标签选择下拉菜单(包含顶部单选按钮与列表) + Future _showBranchOrTagSelectorMenu( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + String currentBranch, + ) async { + final renderBox = _branchBarKey.currentContext?.findRenderObject() as RenderBox?; + if (renderBox == null) return; + + final offset = renderBox.localToGlobal(Offset.zero); + final size = renderBox.size; + + await showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: 'DismissBranchMenu', + barrierColor: Colors.transparent, + pageBuilder: (dialogCtx, anim1, anim2) { + return _BranchOrTagSelectorMenuDialog( + offset: offset, + size: size, + theme: theme, + l10n: l10n, + gitProvider: gitProvider, + currentBranch: currentBranch, + initialShowTags: _showTagsInSelector, + onModeChanged: (isTag) { + _showTagsInSelector = isTag; + gitProvider.setShowTagsInSelector(isTag); + }, + onSwitchBranch: (b) async { + final res = await gitProvider.switchBranch(b); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast(context, l10n.gitSwitchBranchSuccess(b), type: ToastType.success); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + }, + onSwitchTag: (t) async { + final res = await gitProvider.switchTag(t); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast(context, l10n.gitSwitchTagSuccess(t), type: ToastType.success); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + }, + ); + }, + ); + } + + /// 行分支/标签更多按钮(动态展示分支操作或标签操作,去除背景与边框) + Widget _buildBranchRowMoreButton( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + String currentBranch, + ) { + final colorScheme = theme.colorScheme; + final isTag = gitProvider.isCurrentRefTag; + final canDeleteBranch = gitProvider.branches.where((b) => b != currentBranch).isNotEmpty; + final canDeleteTag = gitProvider.tags.isNotEmpty; + + return SizedBox( + width: 32, + height: 32, + child: PopupMenuButton( + key: const ValueKey('branch_row_more_button'), + icon: Icon(Icons.more_vert, size: 18, color: colorScheme.onSurfaceVariant), + tooltip: isTag ? l10n.gitTags : l10n.gitBranches, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + onSelected: (action) { + switch (action) { + case 'create_branch': + _showCreateBranchDialog(context, l10n, gitProvider); + break; + case 'delete_branch': + _showDeleteBranchDialog(context, l10n, gitProvider, currentBranch); + break; + case 'create_tag': + _showCreateTagDialog(context, l10n, gitProvider); + break; + case 'delete_tag': + _showDeleteTagDialog(context, l10n, gitProvider); + break; + } + }, + itemBuilder: (ctx) { + final branchItems = [ + PopupMenuItem( + value: 'create_branch', + child: Row( + children: [ + Icon(Icons.call_split_rounded, size: 16, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Text(l10n.gitCreateBranch, style: const TextStyle(fontSize: 13)), + ], + ), + ), + PopupMenuItem( + value: 'delete_branch', + enabled: canDeleteBranch, + child: Row( + children: [ + Icon(Icons.delete_outline, size: 16, color: theme.colorScheme.error), + const SizedBox(width: 8), + Text(l10n.gitDeleteBranch, style: TextStyle(fontSize: 13, color: theme.colorScheme.error)), + ], + ), + ), + ]; + + final tagItems = [ + PopupMenuItem( + value: 'create_tag', + child: Row( + children: [ + Icon(Icons.local_offer_outlined, size: 16, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Text(l10n.gitCreateTag, style: const TextStyle(fontSize: 13)), + ], + ), + ), + PopupMenuItem( + value: 'delete_tag', + enabled: canDeleteTag, + child: Row( + children: [ + Icon(Icons.delete_outline, size: 16, color: theme.colorScheme.error), + const SizedBox(width: 8), + Text(l10n.gitDeleteTag, style: TextStyle(fontSize: 13, color: theme.colorScheme.error)), + ], + ), + ), + ]; + + if (isTag) { + return [ + ...tagItems, + const PopupMenuDivider(), + ...branchItems, + ]; + } else { + return [ + ...branchItems, + const PopupMenuDivider(), + ...tagItems, + ]; + } + }, + ), + ); + } + + /// 顶部更多操作菜单(撤销上次提交、Stash 等) + Widget _buildMoreActionsMenu( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + return PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 18), + tooltip: l10n.gitMoreActions, + padding: EdgeInsets.zero, + onSelected: (action) async { + switch (action) { + case 'undo_commit': + _handleUndoLastCommit(context, l10n, gitProvider); + break; + case 'stash': + _handleStash(context, l10n, gitProvider); + break; + case 'stash_pop': + _handleStashPop(context, l10n, gitProvider); + break; + } + }, + itemBuilder: (ctx) => [ + PopupMenuItem( + value: 'undo_commit', + enabled: gitProvider.commits.isNotEmpty, + child: Row( + children: [ + const Icon(Icons.undo, size: 16), + const SizedBox(width: 8), + Text(l10n.gitUndoLastCommit, style: const TextStyle(fontSize: 13)), + ], + ), + ), + PopupMenuItem( + value: 'stash', + enabled: gitProvider.changedFiles.isNotEmpty, + child: Row( + children: [ + const Icon(Icons.archive_outlined, size: 16), + const SizedBox(width: 8), + Text(l10n.gitStashChanges, style: const TextStyle(fontSize: 13)), + ], + ), + ), + PopupMenuItem( + value: 'stash_pop', + enabled: gitProvider.stashCount > 0, + child: Row( + children: [ + const Icon(Icons.unarchive_outlined, size: 16), + const SizedBox(width: 8), + Text( + '${l10n.gitStashPop}${gitProvider.stashCount > 0 ? ' (${gitProvider.stashCount})' : ''}', + style: const TextStyle(fontSize: 13), + ), + ], + ), + ), + ], + ); + } + + /// 创建新分支对话框 + Future _showCreateBranchDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final controller = TextEditingController(); + final name = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitCreateBranch), + content: TextField( + controller: controller, + autofocus: true, + decoration: InputDecoration( + hintText: l10n.gitBranchNameHint, + isDense: true, + ), + onSubmitted: (val) { + final trimmed = val.trim(); + if (trimmed.isNotEmpty) { + Navigator.of(dialogCtx).pop(trimmed); + } + }, + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () { + final trimmed = controller.text.trim(); + if (trimmed.isNotEmpty) { + Navigator.of(dialogCtx).pop(trimmed); + } + }, + child: Text(l10n.confirm), + ), + ], + ), + ); + + if (name != null && name.isNotEmpty && context.mounted) { + final res = await gitProvider.createBranch(name); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitCreateBranchSuccess(name), + type: ToastType.success, + ); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + } + + /// 删除分支对话框 + Future _showDeleteBranchDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + String currentBranch, + ) async { + final deletableBranches = gitProvider.branches.where((b) => b != currentBranch).toList(); + if (deletableBranches.isEmpty) { + DialogUtils.showToast(context, l10n.gitCannotDeleteCurrentBranch, type: ToastType.warning); + return; + } + + final selected = await showDialog( + context: context, + builder: (dialogCtx) => _ItemSelectionDialog( + title: l10n.gitSelectBranchToDelete, + searchHint: l10n.gitSearchBranches, + emptyText: l10n.gitNoBranches, + itemIcon: Icons.call_split_rounded, + items: deletableBranches, + cancelText: l10n.cancel, + ), + ); + + if (selected != null && context.mounted) { + final confirm = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitDeleteBranch), + content: Text(l10n.gitDeleteBranchConfirm(selected)), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.error, + ), + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.gitDeleteBranch), + ), + ], + ), + ); + + if (confirm == true && context.mounted) { + final res = await gitProvider.deleteBranch(selected); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast(context, l10n.gitDeleteBranchSuccess(selected), type: ToastType.success); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + } + } + + /// 创建新标签对话框 + Future _showCreateTagDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final nameCtrl = TextEditingController(); + final msgCtrl = TextEditingController(); + + final ok = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitCreateTag), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: nameCtrl, + autofocus: true, + decoration: InputDecoration( + hintText: l10n.gitTagNameHint, + isDense: true, + ), + ), + const SizedBox(height: 10), + TextField( + controller: msgCtrl, + decoration: InputDecoration( + hintText: l10n.gitTagMessageHint, + isDense: true, + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () { + if (nameCtrl.text.trim().isNotEmpty) { + Navigator.of(dialogCtx).pop(true); + } + }, + child: Text(l10n.confirm), + ), + ], + ), + ); + + if (ok == true && context.mounted) { + final tagName = nameCtrl.text.trim(); + final msg = msgCtrl.text.trim(); + final res = await gitProvider.createTag(tagName, message: msg.isNotEmpty ? msg : null); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast(context, l10n.gitCreateTagSuccess(tagName), type: ToastType.success); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + } + + /// 删除标签对话框 + Future _showDeleteTagDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + if (gitProvider.tags.isEmpty) { + DialogUtils.showToast(context, l10n.gitNoTags, type: ToastType.warning); + return; + } + + final selected = await showDialog( + context: context, + builder: (dialogCtx) => _ItemSelectionDialog( + title: l10n.gitSelectTagToDelete, + searchHint: l10n.gitSearchTags, + emptyText: l10n.gitNoTags, + itemIcon: Icons.local_offer_outlined, + items: gitProvider.tags, + cancelText: l10n.cancel, + ), + ); + + if (selected != null && context.mounted) { + final confirm = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitDeleteTag), + content: Text(l10n.gitDeleteTagConfirm(selected)), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.error, + ), + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.gitDeleteTag), + ), + ], + ), + ); + + if (confirm == true && context.mounted) { + final res = await gitProvider.deleteTag(selected); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast(context, l10n.gitDeleteTagSuccess(selected), type: ToastType.success); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + } + } + + /// 处理撤销上一次提交 + Future _handleUndoLastCommit( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final confirm = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitUndoLastCommit), + content: Text(l10n.gitUndoLastCommitConfirm), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.confirm), + ), + ], + ), + ); + + if (confirm == true && context.mounted) { + final res = await gitProvider.undoLastCommit(); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitUndoLastCommitSuccess, + type: ToastType.success, + ); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + } + + /// 处理暂存工作区修改 (Stash) + Future _handleStash( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final res = await gitProvider.stash(); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitStashChangesSuccess, + type: ToastType.success, + ); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + + /// 处理恢复最近暂存 (Stash Pop) + Future _handleStashPop( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + if (gitProvider.stashCount == 0) { + DialogUtils.showToast(context, l10n.gitNoStashFound, type: ToastType.info); + return; + } + final res = await gitProvider.stashPop(); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitStashPopSuccess, + type: ToastType.success, + ); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + + /// 面板主体内容路由调度 + Widget _buildBody( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + // 1. 未打开工程目录 + if (!gitProvider.hasProject) { + return _buildEmptyState( + theme: theme, + icon: Icons.folder_open_rounded, + title: l10n.noOpenDirectory, + subtitle: null, + ); + } + + // 2. 宿主/容器未安装 Git 命令行工具 + if (!gitProvider.gitInstalled) { + return _buildGitNotInstalledView(context, theme, l10n, gitProvider); + } + + // 3. 正在加载中且尚未加载出任何仓库 + if (gitProvider.isLoading && !gitProvider.hasRepository) { + return const Center(child: CircularProgressIndicator()); + } + + // 4. 当前工程未初始化 Git 仓库 + if (!gitProvider.hasRepository) { + return _buildUninitializedRepoView(context, theme, l10n, gitProvider); + } + + // 5. 已检测到 Git 仓库,展示变更与状态列表 + return _buildRepoChangesView(context, theme, l10n, gitProvider); + } + + /// Git 未安装时的引导与同步安装视图 + Widget _buildGitNotInstalledView( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + return LayoutBuilder( + builder: (layoutCtx, constraints) { + return SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: IntrinsicHeight( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Spacer(), + + // 图标(温和友好的源码分支图标,避免警示性红黄色) + Center( + child: Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer.withValues(alpha: 0.4), + shape: BoxShape.circle, + ), + child: Icon( + Icons.alt_route_rounded, + size: 48, + color: theme.colorScheme.primary, + ), + ), + ), + + const SizedBox(height: 20), + + // 标题:温和提示需要安装 Git + Text( + l10n.gitNeedInstall, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.center, + ), + + const Spacer(), + + // 页面下方明显的【安装 Git】按钮 + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: FilledButton.icon( + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + icon: const Icon(Icons.download_rounded, size: 18), + label: Text( + l10n.gitInstallAction, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + onPressed: () => _handleInstallGit(this.context, l10n, gitProvider), + ), + ), + ], + ), + ), + ), + ), + ); + }, + ); + } + + /// 点击安装 Git 按钮,弹出同步阻塞 Dialog 并执行安装 + Future _handleInstallGit( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final navigator = Navigator.of(context, rootNavigator: true); + + // 弹出同步阻塞 Dialog + showDialog( + context: context, + barrierDismissible: false, + builder: (dialogCtx) { + return PopScope( + canPop: false, + child: AlertDialog( + contentPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + content: Row( + children: [ + const SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 2.8), + ), + const SizedBox(width: 20), + Expanded( + child: Text( + l10n.gitInstallingProgress, + style: const TextStyle(fontSize: 14), + ), + ), + ], + ), + ), + ); + }, + ); + + // 执行后台安装 + final result = await gitProvider.installGit(); + + // 关闭同步阻塞 Dialog + if (navigator.mounted) { + navigator.pop(); + } + + if (mounted) { + if (result.success) { + DialogUtils.showToast( + this.context, + l10n.gitInstallSuccess, + type: ToastType.success, + ); + } else { + DialogUtils.showToast( + this.context, + l10n.gitInstallFailed(result.stderr), + type: ToastType.error, + ); + } + } + } + + /// 未初始化 Git 仓库视图 + Widget _buildUninitializedRepoView( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + return LayoutBuilder( + builder: (context, constraints) { + return SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: IntrinsicHeight( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Spacer(), + + // 图标 + Center( + child: Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer.withValues(alpha: 0.4), + shape: BoxShape.circle, + ), + child: Icon( + Icons.merge_type_rounded, + size: 48, + color: theme.colorScheme.primary, + ), + ), + ), + + const SizedBox(height: 20), + + // 标题 + Text( + l10n.gitNoRepoFound, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.center, + ), + + const SizedBox(height: 10), + + // 说明 + Text( + l10n.gitNoRepoDesc, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + height: 1.4, + ), + textAlign: TextAlign.center, + ), + + const Spacer(), + + // 页面下方明显的【初始化 Git 仓库】按钮 + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: FilledButton.icon( + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + icon: const Icon(Icons.add_circle_outline, size: 18), + label: Text( + l10n.gitInitRepo, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + onPressed: () => _handleInitRepository(this.context, l10n, gitProvider), + ), + ), + ], + ), + ), + ), + ), + ); + }, + ); + } + + /// 点击初始化按钮,弹出同步阻塞 Dialog 并执行 git init + Future _handleInitRepository( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final navigator = Navigator.of(context, rootNavigator: true); + + // 弹出同步阻塞 Dialog(不可随意点击空白区域退出) + showDialog( + context: context, + barrierDismissible: false, + builder: (dialogCtx) { + return PopScope( + canPop: false, + child: AlertDialog( + contentPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + content: Row( + children: [ + const SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 2.8), + ), + const SizedBox(width: 20), + Expanded( + child: Text( + l10n.gitInitializing, + style: const TextStyle(fontSize: 14), + ), + ), + ], + ), + ), + ); + }, + ); + + // 执行后台初始化 + final result = await gitProvider.initRepository(); + + // 关闭同步阻塞 Dialog + if (navigator.mounted) { + navigator.pop(); + } + + if (mounted) { + if (result.success) { + DialogUtils.showToast( + this.context, + l10n.gitInitSuccess, + type: ToastType.success, + ); + } else { + DialogUtils.showToast( + this.context, + l10n.gitInitFailed(result.stderr), + type: ToastType.error, + ); + } + } + } + + /// 已初始化仓库的变更列表视图 + Widget _buildRepoChangesView( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + final colorScheme = theme.colorScheme; + final staged = gitProvider.stagedFiles; + final unstaged = gitProvider.unstagedFiles; + final tabProvider = context.read(); + + return Column( + children: [ + // 顶部提交信息输入区与提交按钮 + _buildCommitBox(context, theme, l10n, gitProvider), + const Divider(height: 1, thickness: 0.8), + + // 虚拟化列表区 (暂存更改 + 更改 + 图表,真正按需渲染视口内元素,防卡顿) + Expanded( + child: CustomScrollView( + controller: _scrollController, + slivers: [ + const SliverToBoxAdapter(child: SizedBox(height: 6)), + + // 1. 暂存区变更 (Staged Changes) + if (staged.isNotEmpty) ...[ + SliverToBoxAdapter( + child: _buildSectionHeader( + theme: theme, + title: l10n.gitStagedChanges, + count: staged.length, + isExpanded: _stagedExpanded, + onToggle: () { + setState(() { + _stagedExpanded = !_stagedExpanded; + gitProvider.setStagedExpanded(_stagedExpanded); + }); + }, + actions: [ + IconButton( + visualDensity: const VisualDensity(horizontal: -4, vertical: -4), + iconSize: 15, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + splashRadius: 12, + icon: Icon(Icons.remove, color: colorScheme.onSurfaceVariant.withValues(alpha: 0.8)), + tooltip: l10n.gitUnstageAll, + onPressed: () async { + final res = await gitProvider.unstageAll(); + if (mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(this.context, res.stderr, type: ToastType.error); + } + }, + ), + ], + ), + ), + if (_stagedExpanded) + SliverList.builder( + itemCount: staged.length, + itemBuilder: (ctx, index) => _buildFileItem( + context, + theme, + l10n, + staged[index], + tabProvider, + gitProvider, + ), + ), + const SliverToBoxAdapter(child: SizedBox(height: 6)), + ], + + // 2. 工作区变更 (Unstaged Changes) + SliverToBoxAdapter( + child: _buildSectionHeader( + theme: theme, + title: l10n.gitChanges, + count: unstaged.length, + isExpanded: _unstagedExpanded, + onToggle: () { + setState(() { + _unstagedExpanded = !_unstagedExpanded; + gitProvider.setUnstagedExpanded(_unstagedExpanded); + }); + }, + actions: [ + if (unstaged.isNotEmpty) ...[ + IconButton( + visualDensity: const VisualDensity(horizontal: -4, vertical: -4), + iconSize: 15, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + splashRadius: 12, + icon: Icon(Icons.undo_rounded, color: colorScheme.onSurfaceVariant.withValues(alpha: 0.8)), + tooltip: l10n.gitDiscardAll, + onPressed: () => _handleDiscardAllUnstaged(context, l10n, gitProvider), + ), + IconButton( + visualDensity: const VisualDensity(horizontal: -4, vertical: -4), + iconSize: 15, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + splashRadius: 12, + icon: Icon(Icons.add, color: colorScheme.onSurfaceVariant.withValues(alpha: 0.8)), + tooltip: l10n.gitStageAll, + onPressed: () async { + final res = await gitProvider.stageAll(); + if (mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(this.context, res.stderr, type: ToastType.error); + } + }, + ), + ], + ], + ), + ), + if (_unstagedExpanded) ...[ + if (unstaged.isEmpty && staged.isEmpty) + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(26, 6, 16, 6), + child: Row( + children: [ + Icon( + Icons.done_all_rounded, + size: 16, + color: colorScheme.primary.withValues(alpha: 0.7), + ), + const SizedBox(width: 8), + Text( + l10n.gitNoChanges, + style: TextStyle( + fontSize: 11.5, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.65), + ), + ), + ], + ), + ), + ) + else + SliverList.builder( + itemCount: unstaged.length, + itemBuilder: (ctx, index) => _buildFileItem( + context, + theme, + l10n, + unstaged[index], + tabProvider, + gitProvider, + ), + ), + ], + + const SliverToBoxAdapter(child: SizedBox(height: 8)), + + // 3. 提交历史图表 (Graph) + SliverToBoxAdapter( + child: _buildSectionHeader( + theme: theme, + title: l10n.gitGraphTitle, + count: gitProvider.totalCommitsCount > 0 + ? gitProvider.totalCommitsCount + : gitProvider.commits.length, + isExpanded: _graphExpanded, + onToggle: () { + setState(() { + _graphExpanded = !_graphExpanded; + gitProvider.setGraphExpanded(_graphExpanded); + }); + }, + actions: [ + // 全部展开按钮 + IconButton( + visualDensity: const VisualDensity(horizontal: -4, vertical: -4), + iconSize: 15, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + splashRadius: 12, + icon: Icon( + Icons.unfold_more_rounded, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.8), + ), + tooltip: l10n.gitExpandAll, + onPressed: () async { + if (!_graphExpanded) { + setState(() { + _graphExpanded = true; + gitProvider.setGraphExpanded(true); + }); + } + await gitProvider.loadAllCommits(); + }, + ), + // 刷新按钮 + IconButton( + visualDensity: const VisualDensity(horizontal: -4, vertical: -4), + iconSize: 15, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + splashRadius: 12, + icon: Icon(Icons.refresh_rounded, color: colorScheme.onSurfaceVariant.withValues(alpha: 0.8)), + tooltip: l10n.gitRefresh, + onPressed: () => gitProvider.refresh(), + ), + ], + ), + ), + if (_graphExpanded) ...[ + if (gitProvider.commits.isEmpty) + SliverToBoxAdapter( + child: _buildNoCommitsItem(theme, l10n), + ) + else ...[ + SliverList.builder( + itemCount: gitProvider.commits.length, + itemBuilder: (ctx, index) => _buildCommitItem( + context, + theme, + l10n, + gitProvider.commits[index], + index == 0, + ), + ), + SliverToBoxAdapter( + child: _buildCommitsFooter(context, theme, l10n, gitProvider), + ), + ], + ], + + const SliverToBoxAdapter(child: SizedBox(height: 16)), + ], + ), + ), + ], + ); + } + + /// 图表底部懒加载与分页统计栏(对标搜索结果懒加载设计) + Widget _buildCommitsFooter( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + if (gitProvider.commits.isEmpty) return const SizedBox.shrink(); + + final colorScheme = theme.colorScheme; + final loaded = gitProvider.commits.length; + final total = gitProvider.totalCommitsCount > 0 ? gitProvider.totalCommitsCount : loaded; + final hasMore = gitProvider.hasMoreCommits; + final remaining = (total - loaded).clamp(0, total); + + if (gitProvider.isLoadingMoreCommits) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16), + alignment: Alignment.center, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + color: colorScheme.primary, + ), + ), + const SizedBox(width: 8), + Text( + l10n.gitLoadingMoreCommits, + style: TextStyle( + fontSize: 11.5, + color: colorScheme.primary, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ); + } + + if (hasMore) { + final nextCount = math.min(50, remaining); + return InkWell( + onTap: () => gitProvider.loadMoreCommits(count: 50), + child: Container( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.expand_more, size: 16, color: colorScheme.primary), + const SizedBox(width: 6), + Text( + l10n.gitLoadMoreCommits(nextCount), + style: TextStyle( + fontSize: 12, + color: colorScheme.primary, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + const SizedBox(height: 2), + Text( + l10n.gitLoadedCommitsCount(loaded, total), + style: TextStyle( + fontSize: 10.5, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + ), + ], + ), + ), + ); + } + + // 已全部加载完毕提示 + return Container( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + alignment: Alignment.center, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.check_circle_outline_rounded, + size: 13, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + ), + const SizedBox(width: 5), + Text( + l10n.gitAllCommitsLoaded(loaded), + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.55), + ), + ), + ], + ), + ); + } + + /// 提交控制台(输入框与提交按钮) + Widget _buildCommitBox( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider gitProvider, + ) { + final colorScheme = theme.colorScheme; + final hasChanges = gitProvider.totalChangedCount > 0; + + return Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 14, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextField( + controller: _commitMsgController, + maxLines: 3, + minLines: 1, + style: const TextStyle(fontSize: 12.5), + decoration: InputDecoration( + hintText: l10n.gitCommitMessageHint, + hintStyle: TextStyle( + fontSize: 12, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + isDense: true, + contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + filled: true, + fillColor: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide( + color: colorScheme.outlineVariant.withValues(alpha: 0.5), + ), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide( + color: colorScheme.outlineVariant.withValues(alpha: 0.35), + ), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide(color: colorScheme.primary, width: 1.2), + ), + ), + onSubmitted: (_) => _handleCommit(context, l10n, gitProvider), + ), + const SizedBox(height: 8), + FilledButton.icon( + style: FilledButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), + ), + icon: const Icon(Icons.check, size: 16), + label: Text( + l10n.gitCommit, + style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold), + ), + onPressed: (!hasChanges || gitProvider.isLoading) + ? null + : () => _handleCommit(context, l10n, gitProvider), + ), + ], + ), + ); + } + + /// 处理 Commit 提交 + Future _handleCommit( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final msg = _commitMsgController.text.trim(); + if (msg.isEmpty) { + DialogUtils.showToast(context, l10n.gitNoCommitMessage, type: ToastType.warning); + return; + } + + // 如果暂存区为空但工作区有改动,提示是否全部暂存并直接提交 + if (gitProvider.stagedFiles.isEmpty && gitProvider.unstagedFiles.isNotEmpty) { + final confirm = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitCommit), + content: Text(l10n.gitNoStagedChangesToCommit), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.gitStageAllAndCommit), + ), + ], + ), + ); + + if (confirm != true || !context.mounted) return; + + final stageRes = await gitProvider.stageAll(); + if (!stageRes.success) { + if (context.mounted) { + DialogUtils.showToast(context, stageRes.stderr, type: ToastType.error); + } + return; + } + } + + final res = await gitProvider.commit(msg); + if (!context.mounted) return; + + if (res.success) { + _commitMsgController.clear(); + gitProvider.setCommitMessage(''); + DialogUtils.showToast(context, l10n.gitCommitSuccess, type: ToastType.success); + } else { + DialogUtils.showToast( + context, + l10n.gitCommitFailed(res.stderr.isNotEmpty ? res.stderr : res.stdout), + type: ToastType.error, + ); + } + } + + /// 处理放弃单个文件的更改 (Discard Changes) + Future _handleDiscardFile( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + GitFileStatus file, + ) async { + final confirm = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitDiscardConfirm), + content: Text(l10n.gitDiscardConfirmDesc(file.fileName)), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.error, + ), + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.gitDiscardChange), + ), + ], + ), + ); + + if (confirm == true && context.mounted) { + final res = await gitProvider.discardFile(file); + if (context.mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + + /// 处理放弃所有未暂存更改 + Future _handleDiscardAllUnstaged( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final confirm = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text(l10n.gitDiscardAllChangesTitle), + content: Text(l10n.gitDiscardAllChangesConfirm), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogCtx).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.error, + ), + onPressed: () => Navigator.of(dialogCtx).pop(true), + child: Text(l10n.gitDiscardAll), + ), + ], + ), + ); + + if (confirm == true && context.mounted) { + final res = await gitProvider.discardAllUnstaged(); + if (context.mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + } + + + + /// 变更分组标头(支持折叠/展开、数量胶囊及右侧操作按钮列表) + Widget _buildSectionHeader({ + required ThemeData theme, + required String title, + required int count, + required bool isExpanded, + required VoidCallback onToggle, + List actions = const [], + }) { + final colorScheme = theme.colorScheme; + + return InkWell( + onTap: onToggle, + borderRadius: BorderRadius.circular(4), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3), + child: Row( + children: [ + // 折叠指示箭头 + Icon( + isExpanded ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_right, + size: 18, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.8), + ), + const SizedBox(width: 4), + + // 分组标题 + Text( + title, + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.bold, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.85), + letterSpacing: 0.3, + ), + ), + + const Spacer(), + + // 操作按钮列表 (紧凑排布) + for (final action in actions) ...[ + action, + const SizedBox(width: 2), + ], + + const SizedBox(width: 2), + + // 变更数量胶囊徽标 + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + count.toString(), + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ), + ); + } + + /// 暂无提交条目 + Widget _buildNoCommitsItem(ThemeData theme, AppLocalizations l10n) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 26, vertical: 10), + child: Text( + l10n.gitNoCommits, + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ); + } + + /// 单个提交历史项(VS Code 风格线性图表与提交元信息) + Widget _buildCommitItem( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitCommit commit, + bool isFirst, + ) { + final colorScheme = theme.colorScheme; + final maxLane = [commit.lane, ...commit.activeLanes, ...commit.outgoingLanes] + .fold(0, (m, l) => l > m ? l : m); + final graphWidth = (maxLane + 1) * 14.0 + 16.0; + + return InkWell( + onTap: () => _showCommitDetails(context, theme, l10n, commit), + child: Container( + constraints: const BoxConstraints(minHeight: 46), + padding: const EdgeInsets.only(right: 10), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 线性拓扑图形 (动态撑满行高从 y=0 到 y=height,上下行无缝连接 0 间隙,RepaintBoundary 绘制隔离) + RepaintBoundary( + child: SizedBox( + width: graphWidth, + child: CustomPaint( + painter: GitGraphPainter( + commit: commit, + isFirstCommit: isFirst, + colorScheme: colorScheme, + ), + ), + ), + ), + + const SizedBox(width: 4), + + // 提交内容与元信息 (垂直边距移入内部,不影响外层拓扑连线的顶天立地) + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 5.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Ref 引用胶囊标签 (多标签采用 Wrap 自动折行,杜绝横向溢出) + if (commit.refs.isNotEmpty) ...[ + Wrap( + spacing: 4, + runSpacing: 2, + children: [ + for (final ref in commit.refs) + _buildRefBadge(context, theme, ref), + ], + ), + const SizedBox(height: 3), + ], + + // 提交信息 (充分利用整行宽度,最多两行并省略溢出) + Text( + commit.subject, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + ), + overflow: TextOverflow.ellipsis, + maxLines: 2, + ), + + const SizedBox(height: 2), + + // 短哈希 • 作者 • 相对时间 + Row( + children: [ + Text( + commit.shortHash, + style: TextStyle( + fontFamily: 'monospace', + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: colorScheme.primary, + ), + ), + Expanded( + child: Text( + ' • ${commit.authorName} • ${commit.relativeDate}', + style: TextStyle( + fontSize: 10, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.65), + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + /// Git Ref 引用徽标(分支、HEAD、Tag 标签) + Widget _buildRefBadge(BuildContext context, ThemeData theme, String ref) { + final colorScheme = theme.colorScheme; + final isTag = ref.contains('tag:'); + final isHead = ref.startsWith('HEAD'); + final label = ref.replaceFirst('HEAD -> ', '').replaceFirst('tag: ', ''); + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + decoration: BoxDecoration( + color: isHead + ? colorScheme.primary.withValues(alpha: 0.15) + : colorScheme.secondaryContainer.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(4), + border: Border.all( + color: isHead + ? colorScheme.primary.withValues(alpha: 0.4) + : colorScheme.outlineVariant.withValues(alpha: 0.4), + width: 0.8, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + isTag + ? Icons.label_outline_rounded + : (isHead ? Icons.navigation_rounded : Icons.fork_right_rounded), + size: 11, + color: isHead ? colorScheme.primary : colorScheme.onSecondaryContainer, + ), + const SizedBox(width: 2), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 120), + child: Text( + label, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: isHead ? colorScheme.primary : colorScheme.onSecondaryContainer, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ); + } + + /// 弹出提交详情面板 + void _showCommitDetails( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitCommit commit, + ) { + final colorScheme = theme.colorScheme; + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: colorScheme.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (ctx) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 16, 20, 20), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 顶部滑动指示条 + Center( + child: Container( + width: 36, + height: 4, + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: colorScheme.outlineVariant.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(2), + ), + ), + ), + + // 标题 + Row( + children: [ + Icon(Icons.commit_rounded, color: colorScheme.primary, size: 20), + const SizedBox(width: 8), + Text( + l10n.gitCommitDetails, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + ], + ), + const SizedBox(height: 16), + + // 提交描述 + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(8), + ), + child: SelectableText( + commit.subject, + style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600), + ), + ), + const SizedBox(height: 12), + + // 提交完整哈希 + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.gitCommitHash, + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + ), + const SizedBox(height: 2), + SelectableText( + commit.hash, + style: TextStyle( + fontSize: 11.5, + fontFamily: 'monospace', + color: colorScheme.primary, + ), + ), + ], + ), + ), + IconButton( + icon: const Icon(Icons.copy_rounded, size: 18), + tooltip: l10n.gitCopyHash, + onPressed: () { + Clipboard.setData(ClipboardData(text: commit.hash)); + Navigator.of(ctx).pop(); + DialogUtils.showToast(context, l10n.gitHashCopied, type: ToastType.info); + }, + ), + ], + ), + const Divider(height: 16, thickness: 0.6), + + // 作者(独占一行,长邮箱完整展示) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.gitCommitAuthor, + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + ), + const SizedBox(height: 2), + SelectableText( + commit.authorEmail.isNotEmpty + ? '${commit.authorName} <${commit.authorEmail}>' + : commit.authorName, + style: const TextStyle(fontSize: 12), + ), + ], + ), + const Divider(height: 16, thickness: 0.6), + + // 提交日期(单独开一行) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.gitCommitDate, + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + ), + const SizedBox(height: 2), + Text( + commit.relativeDate, + style: const TextStyle(fontSize: 12), + ), + ], + ), + + if (commit.parentHashes.isNotEmpty) ...[ + const Divider(height: 16, thickness: 0.6), + Text( + l10n.gitCommitParent, + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + ), + const SizedBox(height: 4), + Wrap( + spacing: 6, + runSpacing: 4, + children: commit.parentHashes.map((p) { + final shortP = p.length > 7 ? p.substring(0, 7) : p; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + shortP, + style: TextStyle(fontSize: 10.5, fontFamily: 'monospace', color: colorScheme.primary), + ), + ); + }).toList(), + ), + ], + ], + ), + ), + ); + }, + ); + } + + /// 单个文件变更条目 + Widget _buildFileItem( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitFileStatus file, + TabProvider? tabProvider, + GitProvider gitProvider, + ) { + final (badgeText, badgeColor) = _getStatusBadge(file.statusType); + final colorScheme = theme.colorScheme; + + return InkWell( + onTap: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => GitDiffPage( + file: file, + gitProvider: gitProvider, + ), + ), + ); + }, + onLongPress: () => _showFileContextMenu(context, theme, l10n, file, tabProvider, gitProvider), + child: Padding( + padding: const EdgeInsets.fromLTRB(26.0, 3.0, 10.0, 3.0), + child: Row( + children: [ + // 文件类型图标 + Icon( + FileIconUtils.getIcon(name: file.fileName, isDirectory: false), + size: 16, + color: colorScheme.onSurfaceVariant, + ), + + const SizedBox(width: 8), + + // 文件名与所在路径 (垂直排布:文件名在上,所在相对路径在下方) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + file.fileName, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w500, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + if (file.directoryPath.isNotEmpty) + Text( + file.directoryPath, + style: TextStyle( + fontSize: 10.5, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.55), + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ], + ), + ), + + const SizedBox(width: 4), + + // 单文件暂存 (+) 或取消暂存 (-) 按钮(紧凑化) + IconButton( + visualDensity: const VisualDensity(horizontal: -4, vertical: -4), + iconSize: 15, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 22, minHeight: 22), + splashRadius: 12, + icon: Icon( + file.isStaged ? Icons.remove : Icons.add, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.85), + ), + tooltip: file.isStaged ? l10n.gitUnstageChange : l10n.gitStageChange, + onPressed: () async { + if (file.isStaged) { + final res = await gitProvider.unstageFile(file.relativePath); + if (context.mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } else { + final res = await gitProvider.stageFile(file.relativePath); + if (context.mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + }, + ), + + const SizedBox(width: 4), + + // Git 状态标徽 (M, U, A, D, R, !) + Container( + constraints: const BoxConstraints(minWidth: 16), + alignment: Alignment.center, + padding: const EdgeInsets.symmetric(horizontal: 3.5, vertical: 1), + decoration: BoxDecoration( + color: badgeColor.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(3), + ), + child: Text( + badgeText, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.bold, + color: badgeColor, + fontFamily: 'JetBrains Mono', + ), + ), + ), + ], + ), + ), + ); + } + + /// 文件项长按上下文菜单 (包含暂存/取消暂存、放弃更改、添加到 .gitignore、打开文件等) + void _showFileContextMenu( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitFileStatus file, + TabProvider? tabProvider, + GitProvider gitProvider, + ) { + final isUntracked = file.statusType == GitFileStatusType.untracked; + final colorScheme = theme.colorScheme; + + showModalBottomSheet( + context: context, + backgroundColor: colorScheme.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (bottomSheetCtx) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 顶部拖动条 + Container( + width: 36, + height: 4, + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.3), + borderRadius: BorderRadius.circular(2), + ), + ), + + // 文件头部信息 + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4), + child: Row( + children: [ + Icon( + FileIconUtils.getIcon(name: file.fileName, isDirectory: false), + size: 20, + color: colorScheme.primary, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + file.fileName, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14), + overflow: TextOverflow.ellipsis, + ), + if (file.directoryPath.isNotEmpty) + Text( + file.directoryPath, + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + ), + + const Divider(height: 16), + + // 查看差异 (Diff View) + ListTile( + dense: true, + leading: Icon( + Icons.difference_outlined, + size: 20, + color: colorScheme.primary, + ), + title: Text(l10n.gitDiff), + onTap: () { + Navigator.of(bottomSheetCtx).pop(); + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => GitDiffPage( + file: file, + gitProvider: gitProvider, + ), + ), + ); + }, + ), + + // 暂存 / 取消暂存 + ListTile( + dense: true, + leading: Icon( + file.isStaged ? Icons.remove_circle_outline : Icons.add_circle_outline, + size: 20, + color: colorScheme.primary, + ), + title: Text(file.isStaged ? l10n.gitUnstageChange : l10n.gitStageChange), + onTap: () async { + Navigator.of(bottomSheetCtx).pop(); + if (file.isStaged) { + final res = await gitProvider.unstageFile(file.relativePath); + if (context.mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } else { + final res = await gitProvider.stageFile(file.relativePath); + if (context.mounted && !res.success && res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + }, + ), + + // 放弃更改 (撤销更改) + ListTile( + dense: true, + leading: Icon( + Icons.undo_rounded, + size: 20, + color: colorScheme.error, + ), + title: Text( + l10n.gitDiscardChange, + style: TextStyle(color: colorScheme.error), + ), + onTap: () { + Navigator.of(bottomSheetCtx).pop(); + _handleDiscardFile(context, l10n, gitProvider, file); + }, + ), + + // 未跟踪文件可添加到 .gitignore + if (!file.isStaged && isUntracked) + ListTile( + dense: true, + leading: Icon( + Icons.visibility_off_outlined, + size: 20, + color: colorScheme.onSurfaceVariant, + ), + title: Text(l10n.gitAddToGitignore), + onTap: () async { + Navigator.of(bottomSheetCtx).pop(); + final ok = await gitProvider.addToGitignore(file.relativePath); + if (context.mounted && ok) { + DialogUtils.showToast(context, l10n.gitAddedToGitignore, type: ToastType.success); + } + }, + ), + + // 打开文件 + ListTile( + dense: true, + leading: Icon( + Icons.open_in_new_rounded, + size: 20, + color: colorScheme.onSurfaceVariant, + ), + title: Text(l10n.gitOpenFile), + onTap: () async { + Navigator.of(bottomSheetCtx).pop(); + if (tabProvider != null) { + await tabProvider.openFile(file.path); + } + if (context.mounted) { + Navigator.of(context).maybePop(); + } + }, + ), + ], + ), + ), + ); + }, + ); + } + + /// 获取状态徽标文案与颜色 + (String, Color) _getStatusBadge(GitFileStatusType type) { + switch (type) { + case GitFileStatusType.modified: + return ('M', Colors.orange); + case GitFileStatusType.untracked: + return ('U', Colors.green); + case GitFileStatusType.added: + return ('A', Colors.green); + case GitFileStatusType.deleted: + return ('D', Colors.red); + case GitFileStatusType.renamed: + return ('R', Colors.blue); + case GitFileStatusType.unmerged: + return ('!', Colors.purple); + default: + return ('?', Colors.grey); + } + } + + /// 通用空状态布局 + Widget _buildEmptyState({ + required ThemeData theme, + required IconData icon, + required String title, + String? subtitle, + }) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + icon, + size: 48, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.4), + ), + const SizedBox(height: 14), + Text( + title, + style: TextStyle( + fontSize: 13.5, + color: theme.colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + ), + if (subtitle != null) ...[ + const SizedBox(height: 6), + Text( + subtitle, + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + textAlign: TextAlign.center, + ), + ], + ], + ), + ), + ); + } +} + +/// 独立分支与标签下拉浮层(支持按需虚拟化加载与搜索过滤) +class _BranchOrTagSelectorMenuDialog extends StatefulWidget { + final Offset offset; + final Size size; + final ThemeData theme; + final AppLocalizations l10n; + final GitProvider gitProvider; + final String currentBranch; + final bool initialShowTags; + final ValueChanged onModeChanged; + final ValueChanged onSwitchBranch; + final ValueChanged onSwitchTag; + + const _BranchOrTagSelectorMenuDialog({ + required this.offset, + required this.size, + required this.theme, + required this.l10n, + required this.gitProvider, + required this.currentBranch, + required this.initialShowTags, + required this.onModeChanged, + required this.onSwitchBranch, + required this.onSwitchTag, + }); + + @override + State<_BranchOrTagSelectorMenuDialog> createState() => _BranchOrTagSelectorMenuDialogState(); +} + +class _BranchOrTagSelectorMenuDialogState extends State<_BranchOrTagSelectorMenuDialog> { + late bool _showTags; + late final TextEditingController _searchCtrl; + String _searchQuery = ''; + + @override + void initState() { + super.initState(); + _showTags = widget.initialShowTags; + _searchCtrl = TextEditingController(); + } + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colorScheme = widget.theme.colorScheme; + final branches = widget.gitProvider.branches.isNotEmpty + ? widget.gitProvider.branches + : [widget.currentBranch]; + final tags = widget.gitProvider.tags; + + final query = _searchQuery.trim().toLowerCase(); + final filteredBranches = query.isEmpty + ? branches + : branches.where((b) => b.toLowerCase().contains(query)).toList(); + final filteredTags = query.isEmpty + ? tags + : tags.where((t) => t.toLowerCase().contains(query)).toList(); + + return Stack( + children: [ + Positioned( + left: widget.offset.dx, + top: widget.offset.dy + widget.size.height + 4, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () {}, + child: Material( + elevation: 8, + borderRadius: BorderRadius.circular(8), + color: colorScheme.surface, + clipBehavior: Clip.antiAlias, + child: Container( + width: widget.size.width.clamp(200.0, 280.0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 0.8, + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 顶部单选按钮(分支 vs 标签) + Padding( + padding: const EdgeInsets.fromLTRB(8, 4, 8, 2), + child: RadioGroup( + groupValue: _showTags, + onChanged: (v) { + if (v != null) { + setState(() { + _showTags = v; + _searchQuery = ''; + _searchCtrl.clear(); + }); + widget.onModeChanged(v); + } + }, + child: Row( + children: [ + // 分支单选 + Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(6), + onTap: () { + setState(() { + _showTags = false; + _searchQuery = ''; + _searchCtrl.clear(); + }); + widget.onModeChanged(false); + }, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Radio( + value: false, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.compact, + ), + Text( + widget.l10n.gitBranches, + style: TextStyle( + fontSize: 12, + fontWeight: !_showTags ? FontWeight.bold : FontWeight.normal, + color: !_showTags ? colorScheme.primary : colorScheme.onSurface, + ), + ), + ], + ), + ), + ), + ), + // 标签单选 + Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(6), + onTap: () { + setState(() { + _showTags = true; + _searchQuery = ''; + _searchCtrl.clear(); + }); + widget.onModeChanged(true); + }, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Radio( + value: true, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.compact, + ), + Text( + widget.l10n.gitTags, + style: TextStyle( + fontSize: 12, + fontWeight: _showTags ? FontWeight.bold : FontWeight.normal, + color: _showTags ? colorScheme.primary : colorScheme.onSurface, + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + + // 搜索过滤框(分支与标签均提供即时搜索过滤) + Padding( + padding: const EdgeInsets.fromLTRB(8, 2, 8, 4), + child: SizedBox( + height: 28, + child: TextField( + controller: _searchCtrl, + style: const TextStyle(fontSize: 11.5), + decoration: InputDecoration( + hintText: _showTags ? widget.l10n.gitSearchTags : widget.l10n.gitSearchBranches, + hintStyle: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + prefixIcon: Icon(Icons.search, size: 14, color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6)), + prefixIconConstraints: const BoxConstraints(minWidth: 26, minHeight: 26), + isDense: true, + contentPadding: const EdgeInsets.symmetric(horizontal: 6, vertical: 0), + filled: true, + fillColor: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(6), + borderSide: BorderSide.none, + ), + ), + onChanged: (val) { + setState(() { + _searchQuery = val; + }); + }, + ), + ), + ), + + const Divider(height: 1, thickness: 0.8), + + // 下方列表(按需虚拟化构建) + _showTags + ? _buildTagList(context, colorScheme, filteredTags) + : _buildBranchList(context, colorScheme, filteredBranches), + ], + ), + ), + ), + ), + ), + ], + ); + } + + Widget _buildBranchList(BuildContext dialogCtx, ColorScheme colorScheme, List branches) { + if (branches.isEmpty) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Center( + child: Text( + widget.l10n.gitNoBranches, + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ), + ); + } + + const double itemHeight = 36.0; + final double listHeight = (branches.length * itemHeight).clamp(36.0, 240.0); + + return SizedBox( + height: listHeight, + child: ListView.builder( + itemExtent: itemHeight, + itemCount: branches.length, + padding: const EdgeInsets.symmetric(vertical: 2), + itemBuilder: (ctx, index) { + final b = branches[index]; + final isCurrent = b == widget.currentBranch; + return InkWell( + onTap: () { + Navigator.of(dialogCtx).pop(); + if (!isCurrent) { + widget.onSwitchBranch(b); + } + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + Icon( + Icons.call_split_rounded, + size: 15, + color: isCurrent ? colorScheme.primary : colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + b, + style: TextStyle( + fontSize: 12.5, + fontFamily: 'JetBrains Mono', + fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal, + color: isCurrent ? colorScheme.primary : colorScheme.onSurface, + ), + overflow: TextOverflow.ellipsis, + ), + ), + if (isCurrent) ...[ + const SizedBox(width: 6), + Icon(Icons.check, size: 16, color: colorScheme.primary), + ], + ], + ), + ), + ); + }, + ), + ); + } + + Widget _buildTagList(BuildContext dialogCtx, ColorScheme colorScheme, List tags) { + if (tags.isEmpty) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + child: Center( + child: Text( + widget.l10n.gitNoTags, + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ), + ); + } + + const double itemHeight = 36.0; + final double listHeight = (tags.length * itemHeight).clamp(36.0, 240.0); + + return SizedBox( + height: listHeight, + child: ListView.builder( + itemExtent: itemHeight, + itemCount: tags.length, + padding: const EdgeInsets.symmetric(vertical: 2), + itemBuilder: (ctx, index) { + final t = tags[index]; + final isCurrent = widget.currentBranch == t || widget.currentBranch.contains(t); + return InkWell( + onTap: () { + Navigator.of(dialogCtx).pop(); + widget.onSwitchTag(t); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + Icon( + Icons.local_offer_outlined, + size: 15, + color: isCurrent ? colorScheme.primary : colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + t, + style: TextStyle( + fontSize: 12.5, + fontFamily: 'JetBrains Mono', + fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal, + color: isCurrent ? colorScheme.primary : colorScheme.onSurface, + ), + overflow: TextOverflow.ellipsis, + ), + ), + if (isCurrent) ...[ + const SizedBox(width: 6), + Icon(Icons.check, size: 16, color: colorScheme.primary), + ], + ], + ), + ), + ); + }, + ), + ); + } +} + +/// 支持即时搜索过滤与虚拟化滚动的单项选择弹窗(用于删除分支/标签选择) +class _ItemSelectionDialog extends StatefulWidget { + final String title; + final String searchHint; + final String emptyText; + final IconData itemIcon; + final List items; + final String cancelText; + + const _ItemSelectionDialog({ + required this.title, + required this.searchHint, + required this.emptyText, + required this.itemIcon, + required this.items, + required this.cancelText, + }); + + @override + State<_ItemSelectionDialog> createState() => _ItemSelectionDialogState(); +} + +class _ItemSelectionDialogState extends State<_ItemSelectionDialog> { + late final TextEditingController _searchCtrl; + String _searchQuery = ''; + + @override + void initState() { + super.initState(); + _searchCtrl = TextEditingController(); + } + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final query = _searchQuery.trim().toLowerCase(); + final filtered = query.isEmpty + ? widget.items + : widget.items.where((i) => i.toLowerCase().contains(query)).toList(); + + final viewInsets = MediaQuery.viewInsetsOf(context); + final screenHeight = MediaQuery.sizeOf(context).height; + final availableHeight = (screenHeight - viewInsets.bottom - 240.0).clamp(60.0, 320.0); + + const double itemHeight = 40.0; + final double listHeight = (filtered.length * itemHeight).clamp(40.0, availableHeight); + + return AlertDialog( + title: Text(widget.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + contentPadding: const EdgeInsets.fromLTRB(16, 12, 16, 0), + content: SizedBox( + width: double.maxFinite, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 搜索输入框 + SizedBox( + height: 36, + child: TextField( + controller: _searchCtrl, + style: const TextStyle(fontSize: 13), + decoration: InputDecoration( + hintText: widget.searchHint, + hintStyle: TextStyle( + fontSize: 12, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + prefixIcon: Icon(Icons.search, size: 16, color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6)), + prefixIconConstraints: const BoxConstraints(minWidth: 32, minHeight: 32), + suffixIcon: _searchQuery.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, size: 14), + onPressed: () { + _searchCtrl.clear(); + setState(() => _searchQuery = ''); + }, + padding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + ) + : null, + suffixIconConstraints: const BoxConstraints(minWidth: 28, minHeight: 28), + isDense: true, + contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + filled: true, + fillColor: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide.none, + ), + ), + onChanged: (val) { + setState(() { + _searchQuery = val; + }); + }, + ), + ), + const SizedBox(height: 8), + const Divider(height: 1, thickness: 0.8), + // 虚拟化列表 + if (filtered.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Center( + child: Text( + widget.emptyText, + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ), + ) + else + Flexible( + child: SizedBox( + height: listHeight, + child: ListView.builder( + itemExtent: itemHeight, + itemCount: filtered.length, + padding: const EdgeInsets.symmetric(vertical: 2), + itemBuilder: (ctx, index) { + final item = filtered[index]; + return InkWell( + borderRadius: BorderRadius.circular(6), + onTap: () => Navigator.of(context).pop(item), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), + child: Row( + children: [ + Icon(widget.itemIcon, size: 16, color: colorScheme.primary), + const SizedBox(width: 10), + Expanded( + child: Text( + item, + style: const TextStyle(fontSize: 13, fontFamily: 'JetBrains Mono'), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ); + }, + ), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(widget.cancelText), + ), + ], + ); + } +} diff --git a/lib/widgets/search/search_panel_widget.dart b/lib/widgets/search/search_panel_widget.dart index b2e3c4d..b4b21f4 100644 --- a/lib/widgets/search/search_panel_widget.dart +++ b/lib/widgets/search/search_panel_widget.dart @@ -459,6 +459,15 @@ class _SearchPanelWidgetState extends State { maxLines: 1, ), ), + if (options.mode == SearchMode.fileName && result.fileResults.isNotEmpty) ...[ + IconButton( + visualDensity: VisualDensity.compact, + iconSize: 18, + tooltip: l10n.expandAll, + icon: const Icon(Icons.unfold_more), + onPressed: () => searchProvider.loadAllFiles(), + ), + ], if (options.mode == SearchMode.text && result.fileResults.isNotEmpty) ...[ IconButton( visualDensity: VisualDensity.compact, @@ -781,6 +790,44 @@ class _SearchPanelWidgetState extends State { final visibleFiles = allFiles.take(visibleFilesCount).toList(); final hasMoreFiles = allFiles.length > visibleFilesCount; final remainingFilesCount = allFiles.length - visibleFilesCount; + final isFileNameMode = options.mode == SearchMode.fileName; + + // 将搜索树状结构扁平化为一维条目列表,供单一 ListView.builder 进行真正的行级虚拟化 + final List<_SearchRowItem> flattenedItems = []; + if (isFileNameMode) { + for (final file in visibleFiles) { + flattenedItems.add(_SearchFileNameRowItem(file)); + } + } else { + for (final file in visibleFiles) { + flattenedItems.add(_SearchFileHeaderRowItem(file)); + if (file.isExpanded) { + final currentMatchesLimit = searchProvider.getFileMatchesLimit( + file.filePath, + SearchPanelWidget.defaultFileMatchesPageSize, + ); + final allMatches = file.matches; + final visibleMatchesCount = allMatches.length < currentMatchesLimit + ? allMatches.length + : currentMatchesLimit; + for (var i = 0; i < visibleMatchesCount; i++) { + flattenedItems.add(_SearchMatchLineRowItem(file, allMatches[i])); + } + if (allMatches.length > visibleMatchesCount) { + flattenedItems.add( + _SearchLoadMoreMatchesRowItem( + file, + allMatches.length - visibleMatchesCount, + ), + ); + } + } + } + } + + if (hasMoreFiles) { + flattenedItems.add(_SearchLoadMoreFilesRowItem(remainingFilesCount)); + } return MediaQuery.removePadding( context: context, @@ -789,377 +836,55 @@ class _SearchPanelWidgetState extends State { key: const PageStorageKey('project_search_results_list'), controller: _scrollController, padding: EdgeInsets.zero, - itemCount: visibleFiles.length + (hasMoreFiles ? 1 : 0), - itemBuilder: (context, fileIndex) { - if (fileIndex == visibleFiles.length) { - return _buildLoadMoreFilesTile( - theme, - l10n, - remainingFilesCount, - searchProvider, - ); - } - - final fileResult = visibleFiles[fileIndex]; - final isExpanded = fileResult.isExpanded; - final dirName = p.dirname(fileResult.relativePath); - final hasDir = dirName != '.' && dirName.isNotEmpty; - - final currentMatchesLimit = searchProvider.getFileMatchesLimit( - fileResult.filePath, - SearchPanelWidget.defaultFileMatchesPageSize, - ); - final allMatches = fileResult.matches; - final visibleMatchesCount = allMatches.length < currentMatchesLimit - ? allMatches.length - : currentMatchesLimit; - final visibleMatches = allMatches.take(visibleMatchesCount).toList(); - final hasMoreMatches = allMatches.length > visibleMatchesCount; - final remainingMatchesCount = allMatches.length - visibleMatchesCount; - - final isFileNameMode = options.mode == SearchMode.fileName; - - if (isFileNameMode) { - // 文件名/文件夹名匹配模式:普通扁平 item,不折叠,高亮直接绘制在主标题文件名上 - final match = fileResult.matches.isNotEmpty ? fileResult.matches.first : null; - final iconData = FileIconUtils.getIcon( - name: fileResult.fileName, - isDirectory: fileResult.isDirectory, - ); - - return InkWell( - onTap: () async { - if (fileResult.isDirectory) { - // 点击文件夹搜索项:展开并跳转到目录 - final projectProvider = context.read(); - if (projectProvider != null) { - final cleanRoot = projectProvider.rootPath; - if (cleanRoot != null) { - final updatedOpenPaths = List.from(projectProvider.openDirectoryPaths); - if (!updatedOpenPaths.contains(fileResult.filePath)) { - updatedOpenPaths.add(fileResult.filePath); - } - await projectProvider.toggleDirectory( - FileItem( - path: fileResult.filePath, - name: fileResult.fileName, - relativePath: fileResult.relativePath, - isDirectory: true, - ), - true, - ); - } - } - } else { - // 点击文件搜索项:打开并进入编辑该文件 - if (tabProvider != null) { - await tabProvider.openFile(fileResult.filePath); - } - } - if (context.mounted) { - Navigator.of(context).maybePop(); - } - }, - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 10.0, - vertical: 6.0, - ), - child: Row( - children: [ - Icon( - iconData, - size: 18, - color: fileResult.isDirectory - ? theme.colorScheme.primary - : theme.colorScheme.onSurfaceVariant, - ), - const SizedBox(width: 8), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - // 主标题:文件名带关键词高亮 - _buildFileNameHighlightedTitle( - fileResult.fileName, - match, - theme, - ), - if (hasDir) - Padding( - padding: const EdgeInsets.only(top: 2.0), - child: Text( - dirName, - style: TextStyle( - fontSize: 11, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - ), - ], - ), - ), - ], - ), + itemCount: flattenedItems.length, + itemBuilder: (context, index) { + final item = flattenedItems[index]; + return switch (item) { + _SearchFileNameRowItem(:final file) => _buildFileNameTile( + context, + theme, + file, + tabProvider, ), - ); - } - - // 文本内容匹配模式:可折叠树形结构展示 - final iconData = FileIconUtils.getIcon( - name: fileResult.fileName, - isDirectory: fileResult.isDirectory, - ); - - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // 文件分组条目 - InkWell( - onTap: () => searchProvider.toggleFileExpanded(fileResult), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 10.0, - vertical: 6.0, - ), - child: Row( - children: [ - Icon( - isExpanded - ? Icons.keyboard_arrow_down - : Icons.keyboard_arrow_right, - size: 18, - color: theme.colorScheme.onSurfaceVariant, - ), - const SizedBox(width: 4), - Icon( - iconData, - size: 16, - color: theme.colorScheme.primary, - ), - const SizedBox(width: 8), - // 主标题文件名,副标题相对路径(一上一下) - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - fileResult.fileName, - style: const TextStyle( - fontWeight: FontWeight.w600, - fontSize: 13, - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - if (hasDir) - Padding( - padding: const EdgeInsets.only(top: 2.0), - child: Text( - dirName, - style: TextStyle( - fontSize: 11, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - ), - ], - ), - ), - const SizedBox(width: 6), - - // 匹配次数 Badge - Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: theme.colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(10), - ), - child: Text( - '${fileResult.matchCount}', - style: TextStyle( - fontSize: 10.5, - fontWeight: FontWeight.bold, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ), - - // 文件级全部替换按钮:仅在展开替换输入框时展示 - if (options.mode == SearchMode.text && options.isReplaceExpanded) - IconButton( - visualDensity: VisualDensity.compact, - style: IconButton.styleFrom( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, - minimumSize: Size.zero, - padding: const EdgeInsets.all(4), - ), - constraints: const BoxConstraints( - minWidth: 24, - minHeight: 24, - ), - iconSize: 16, - icon: const Icon(Icons.find_replace), - tooltip: l10n.replaceAllInFile, - onPressed: tabProvider == null - ? null - : () async { - final confirmed = await DialogUtils.showConfirmDialog( - context, - title: l10n.confirmReplaceFileTitle, - message: l10n.confirmReplaceFileMessage( - fileResult.fileName, - fileResult.matchCount, - options.replaceText, - ), - confirmText: l10n.replaceSingleMatch, - ); - if (!confirmed || !context.mounted) return; - - final count = await searchProvider.replaceFileMatches( - file: fileResult, - tabProvider: tabProvider, - ); - if (context.mounted && count > 0) { - DialogUtils.showSuccessToast( - context, - l10n.replaceSuccess(count), - ); - } - }, - ), - ], - ), - ), + _SearchFileHeaderRowItem(:final file) => _buildFileHeaderTile( + context, + theme, + l10n, + file, + searchProvider, + tabProvider, + options, ), - - // 展开展示具体匹配行(按需分页加载) - if (isExpanded) ...[ - ...visibleMatches.map((match) { - return InkWell( - onTap: () async { - if (tabProvider != null) { - // 1. 打开文件并切换 tab - await tabProvider.openFile(fileResult.filePath); - // 2. 发送行定位与选区高亮事件 - tabProvider.navigateTo( - filePath: fileResult.filePath, - line: match.lineNumber - 1, - column: match.matchStart, - length: match.matchEnd - match.matchStart, - ); - } - // 3. 移动端抽屉收起(保留宽屏适配) - if (context.mounted) { - Navigator.of(context).maybePop(); - } - }, - child: Padding( - padding: const EdgeInsets.fromLTRB(36.0, 4.0, 10.0, 4.0), - child: Row( - children: [ - // 行号 - ConstrainedBox( - constraints: const BoxConstraints(minWidth: 28), - child: Text( - '${match.lineNumber}:', - style: TextStyle( - fontFamily: 'JetBrains Mono', - fontSize: 11.5, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), - ), - ), - ), - const SizedBox(width: 4), - - // 代码文本摘要(黄色高亮匹配部分) - Expanded( - child: _buildHighlightedSnippet(match, theme), - ), - - // 行单项替换按钮:仅在展开替换输入框时展示 - if (options.mode == SearchMode.text && options.isReplaceExpanded) - IconButton( - visualDensity: VisualDensity.compact, - style: IconButton.styleFrom( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, - minimumSize: Size.zero, - padding: const EdgeInsets.all(3), - ), - constraints: const BoxConstraints( - minWidth: 22, - minHeight: 22, - ), - iconSize: 15, - icon: const Icon(Icons.redo), - tooltip: l10n.replaceSingleMatch, - onPressed: tabProvider == null - ? null - : () async { - final success = await searchProvider.replaceSingleMatch( - file: fileResult, - match: match, - tabProvider: tabProvider, - ); - if (context.mounted && success) { - DialogUtils.showSuccessToast( - context, - l10n.replaceSuccess(1), - ); - } - }, - ), - ], - ), - ), - ); - }), - - // 文件内更多匹配项加载按钮 - if (hasMoreMatches) - InkWell( - onTap: () { - searchProvider.loadMoreMatches( - fileResult.filePath, - SearchPanelWidget.defaultFileMatchesPageSize, - SearchPanelWidget.defaultFileMatchesPageSize, - ); - }, - child: Padding( - padding: const EdgeInsets.fromLTRB(36.0, 6.0, 10.0, 8.0), - child: Row( - children: [ - Icon( - Icons.more_horiz, - size: 16, - color: theme.colorScheme.primary, - ), - const SizedBox(width: 6), - Expanded( - child: Text( - l10n.searchLoadMoreMatches(remainingMatchesCount), - style: TextStyle( - fontSize: 11.5, - color: theme.colorScheme.primary, - fontWeight: FontWeight.w500, - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - ), - ], - ), - ), - ), - ], - ], - ); + _SearchMatchLineRowItem(:final file, :final match) => + _buildMatchLineTile( + context, + theme, + l10n, + file, + match, + searchProvider, + tabProvider, + options, + ), + _SearchLoadMoreMatchesRowItem( + :final file, + :final remainingMatchesCount + ) => + _buildLoadMoreMatchesTile( + theme, + l10n, + file, + remainingMatchesCount, + searchProvider, + ), + _SearchLoadMoreFilesRowItem(:final remainingFilesCount) => + _buildLoadMoreFilesTile( + theme, + l10n, + remainingFilesCount, + searchProvider, + ), + }; }, ), ); @@ -1206,4 +931,426 @@ class _SearchPanelWidgetState extends State { ), ); } + + /// 构建文件名/目录名匹配模式的单项条目 + Widget _buildFileNameTile( + BuildContext context, + ThemeData theme, + FileSearchResult fileResult, + TabProvider? tabProvider, + ) { + final match = fileResult.matches.isNotEmpty ? fileResult.matches.first : null; + final iconData = FileIconUtils.getIcon( + name: fileResult.fileName, + isDirectory: fileResult.isDirectory, + ); + final dirName = p.dirname(fileResult.relativePath); + final hasDir = dirName != '.' && dirName.isNotEmpty; + + return InkWell( + onTap: () async { + if (fileResult.isDirectory) { + final projectProvider = context.read(); + if (projectProvider != null) { + final cleanRoot = projectProvider.rootPath; + if (cleanRoot != null) { + final updatedOpenPaths = List.from(projectProvider.openDirectoryPaths); + if (!updatedOpenPaths.contains(fileResult.filePath)) { + updatedOpenPaths.add(fileResult.filePath); + } + await projectProvider.toggleDirectory( + FileItem( + path: fileResult.filePath, + name: fileResult.fileName, + relativePath: fileResult.relativePath, + isDirectory: true, + ), + true, + ); + } + } + } else { + if (tabProvider != null) { + await tabProvider.openFile(fileResult.filePath); + } + } + if (context.mounted) { + Navigator.of(context).maybePop(); + } + }, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 6.0, + ), + child: Row( + children: [ + Icon( + iconData, + size: 18, + color: fileResult.isDirectory + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + _buildFileNameHighlightedTitle( + fileResult.fileName, + match, + theme, + ), + if (hasDir) + Padding( + padding: const EdgeInsets.only(top: 2.0), + child: Text( + dirName, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + /// 构建文本匹配模式下的文件分组头部条目 + Widget _buildFileHeaderTile( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + FileSearchResult fileResult, + SearchProvider searchProvider, + TabProvider? tabProvider, + SearchOptions options, + ) { + final isExpanded = fileResult.isExpanded; + final dirName = p.dirname(fileResult.relativePath); + final hasDir = dirName != '.' && dirName.isNotEmpty; + final iconData = FileIconUtils.getIcon( + name: fileResult.fileName, + isDirectory: fileResult.isDirectory, + ); + + return InkWell( + onTap: () => searchProvider.toggleFileExpanded(fileResult), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 6.0, + ), + child: Row( + children: [ + Icon( + isExpanded + ? Icons.keyboard_arrow_down + : Icons.keyboard_arrow_right, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 4), + Icon( + iconData, + size: 16, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 8), + // 主标题文件名,副标题相对路径(一上一下) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + fileResult.fileName, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + if (hasDir) + Padding( + padding: const EdgeInsets.only(top: 2.0), + child: Text( + dirName, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + const SizedBox(width: 6), + + // 匹配次数 Badge + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${fileResult.matchCount}', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + + // 该文件折叠项全部展开按钮:一键展开并展示该文件内所有匹配行 + IconButton( + visualDensity: VisualDensity.compact, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(4), + ), + constraints: const BoxConstraints( + minWidth: 24, + minHeight: 24, + ), + iconSize: 16, + icon: const Icon(Icons.unfold_more_rounded), + tooltip: l10n.searchExpandAllMatchesInFile, + onPressed: () { + searchProvider.expandAndLoadAllMatchesForFile(fileResult); + }, + ), + + // 文件级全部替换按钮:仅在展开替换输入框时展示 + if (options.mode == SearchMode.text && options.isReplaceExpanded) + IconButton( + visualDensity: VisualDensity.compact, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(4), + ), + constraints: const BoxConstraints( + minWidth: 24, + minHeight: 24, + ), + iconSize: 16, + icon: const Icon(Icons.find_replace), + tooltip: l10n.replaceAllInFile, + onPressed: tabProvider == null + ? null + : () async { + final confirmed = await DialogUtils.showConfirmDialog( + context, + title: l10n.confirmReplaceFileTitle, + message: l10n.confirmReplaceFileMessage( + fileResult.fileName, + fileResult.matchCount, + options.replaceText, + ), + confirmText: l10n.replaceSingleMatch, + ); + if (!confirmed || !context.mounted) return; + + final count = await searchProvider.replaceFileMatches( + file: fileResult, + tabProvider: tabProvider, + ); + if (context.mounted && count > 0) { + DialogUtils.showSuccessToast( + context, + l10n.replaceSuccess(count), + ); + } + }, + ), + ], + ), + ), + ); + } + + /// 构建具体代码匹配行条目 + Widget _buildMatchLineTile( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + FileSearchResult fileResult, + LineMatch match, + SearchProvider searchProvider, + TabProvider? tabProvider, + SearchOptions options, + ) { + return InkWell( + onTap: () async { + if (tabProvider != null) { + // 1. 打开文件并切换 tab + await tabProvider.openFile(fileResult.filePath); + // 2. 发送行定位与选区高亮事件 + tabProvider.navigateTo( + filePath: fileResult.filePath, + line: match.lineNumber - 1, + column: match.matchStart, + length: match.matchEnd - match.matchStart, + ); + } + // 3. 移动端抽屉收起(保留宽屏适配) + if (context.mounted) { + Navigator.of(context).maybePop(); + } + }, + child: Padding( + padding: const EdgeInsets.fromLTRB(36.0, 4.0, 10.0, 4.0), + child: Row( + children: [ + // 行号 + ConstrainedBox( + constraints: const BoxConstraints(minWidth: 28), + child: Text( + '${match.lineNumber}:', + style: TextStyle( + fontFamily: 'JetBrains Mono', + fontSize: 11.5, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ), + const SizedBox(width: 4), + + // 代码文本摘要(黄色高亮匹配部分) + Expanded( + child: _buildHighlightedSnippet(match, theme), + ), + + // 行单项替换按钮:仅在展开替换输入框时展示 + if (options.mode == SearchMode.text && options.isReplaceExpanded) + IconButton( + visualDensity: VisualDensity.compact, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(3), + ), + constraints: const BoxConstraints( + minWidth: 22, + minHeight: 22, + ), + iconSize: 15, + icon: const Icon(Icons.redo), + tooltip: l10n.replaceSingleMatch, + onPressed: tabProvider == null + ? null + : () async { + final success = await searchProvider.replaceSingleMatch( + file: fileResult, + match: match, + tabProvider: tabProvider, + ); + if (context.mounted && success) { + DialogUtils.showSuccessToast( + context, + l10n.replaceSuccess(1), + ); + } + }, + ), + ], + ), + ), + ); + } + + /// 构建文件内更多匹配项加载按钮条目 + Widget _buildLoadMoreMatchesTile( + ThemeData theme, + AppLocalizations l10n, + FileSearchResult fileResult, + int remainingMatchesCount, + SearchProvider searchProvider, + ) { + return InkWell( + onTap: () { + searchProvider.loadMoreMatches( + fileResult.filePath, + SearchPanelWidget.defaultFileMatchesPageSize, + SearchPanelWidget.defaultFileMatchesPageSize, + ); + }, + child: Padding( + padding: const EdgeInsets.fromLTRB(36.0, 6.0, 10.0, 8.0), + child: Row( + children: [ + Icon( + Icons.more_horiz, + size: 16, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + l10n.searchLoadMoreMatches(remainingMatchesCount), + style: TextStyle( + fontSize: 11.5, + color: theme.colorScheme.primary, + fontWeight: FontWeight.w500, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + ); + } +} + +/// 扁平化虚拟条目抽象基类 +sealed class _SearchRowItem {} + +/// 文件名检索模式条目 +class _SearchFileNameRowItem extends _SearchRowItem { + final FileSearchResult file; + _SearchFileNameRowItem(this.file); +} + +/// 文本内容检索模式下的文件分组头部条目 +class _SearchFileHeaderRowItem extends _SearchRowItem { + final FileSearchResult file; + _SearchFileHeaderRowItem(this.file); +} + +/// 文本内容检索模式下的具体代码匹配行条目 +class _SearchMatchLineRowItem extends _SearchRowItem { + final FileSearchResult file; + final LineMatch match; + _SearchMatchLineRowItem(this.file, this.match); +} + +/// 文件内加载更多匹配项条目 +class _SearchLoadMoreMatchesRowItem extends _SearchRowItem { + final FileSearchResult file; + final int remainingMatchesCount; + _SearchLoadMoreMatchesRowItem(this.file, this.remainingMatchesCount); +} + +/// 搜索结果底部加载更多文件条目 +class _SearchLoadMoreFilesRowItem extends _SearchRowItem { + final int remainingFilesCount; + _SearchLoadMoreFilesRowItem(this.remainingFilesCount); } diff --git a/test/drawer_activity_bar_test.dart b/test/drawer_activity_bar_test.dart index 597d149..00d8a02 100644 --- a/test/drawer_activity_bar_test.dart +++ b/test/drawer_activity_bar_test.dart @@ -1,10 +1,13 @@ import 'dart:io'; import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/models/project_history.dart'; +import 'package:code_editor/providers/git_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/providers/search_provider.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/git_service.dart'; import 'package:code_editor/services/internal_project_service.dart'; import 'package:code_editor/widgets/code_editor_drawer.dart'; import 'package:code_editor/widgets/file_tree_widget.dart'; @@ -24,6 +27,8 @@ void main() { late TabProvider tabProvider; late SettingsProvider settingsProvider; late RunProvider runProvider; + late SearchProvider searchProvider; + late GitProvider gitProvider; setUp(() async { SharedPreferences.setMockInitialValues({}); @@ -37,6 +42,8 @@ void main() { tabProvider = TabProvider()..bindProjectProvider(projectProvider); settingsProvider = SettingsProvider(); runProvider = RunProvider(); + searchProvider = SearchProvider()..bindRootPath(testProjectDir.path); + gitProvider = GitProvider(); await projectProvider.switchProject( ProjectHistory( @@ -47,6 +54,7 @@ void main() { }); tearDown(() { + GitService.instance.resetForTesting(); InternalProjectService.instance.customProjectsDir = null; if (tempBaseDir.existsSync()) { tempBaseDir.deleteSync(recursive: true); @@ -60,6 +68,8 @@ void main() { ChangeNotifierProvider.value(value: tabProvider), ChangeNotifierProvider.value(value: settingsProvider), ChangeNotifierProvider.value(value: runProvider), + ChangeNotifierProvider.value(value: searchProvider), + ChangeNotifierProvider.value(value: gitProvider), ], child: MaterialApp( localizationsDelegates: const [ diff --git a/test/git_file_tree_decoration_test.dart b/test/git_file_tree_decoration_test.dart new file mode 100644 index 0000000..0e831df --- /dev/null +++ b/test/git_file_tree_decoration_test.dart @@ -0,0 +1,158 @@ +import 'package:code_editor/models/file_item.dart'; +import 'package:code_editor/models/git_model.dart'; +import 'package:code_editor/providers/git_provider.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/utils/git_decoration_utils.dart'; +import 'package:code_editor/widgets/file_item_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +void main() { + group('GitDecorationUtils Tests', () { + test('getStatusLetter returns correct letter for each type', () { + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.modified), 'M'); + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.untracked), 'U'); + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.added), 'A'); + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.deleted), 'D'); + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.unmerged), '!'); + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.renamed), 'R'); + expect(GitDecorationUtils.getStatusLetter(GitFileStatusType.ignored), isNull); + }); + + test('getPriority orders conflict > deleted > modified > added > untracked', () { + final unmergedP = GitDecorationUtils.getPriority(GitFileStatusType.unmerged); + final deletedP = GitDecorationUtils.getPriority(GitFileStatusType.deleted); + final modifiedP = GitDecorationUtils.getPriority(GitFileStatusType.modified); + final addedP = GitDecorationUtils.getPriority(GitFileStatusType.added); + final untrackedP = GitDecorationUtils.getPriority(GitFileStatusType.untracked); + + expect(unmergedP > deletedP, isTrue); + expect(deletedP > modifiedP, isTrue); + expect(modifiedP > addedP, isTrue); + expect(addedP > untrackedP, isTrue); + }); + }); + + group('GitProvider File Tree Map Tests', () { + test('getFileStatus and getDirectoryStatus aggregate bottom-up correctly', () { + final provider = GitProvider(); + const root = '/mock/repo'; + final changedFiles = [ + const GitFileStatus( + path: '/mock/repo/lib/widgets/button.dart', + relativePath: 'lib/widgets/button.dart', + statusType: GitFileStatusType.modified, + ), + const GitFileStatus( + path: '/mock/repo/lib/main.dart', + relativePath: 'lib/main.dart', + statusType: GitFileStatusType.untracked, + ), + const GitFileStatus( + path: '/mock/repo/lib/widgets/header.dart', + relativePath: 'lib/widgets/header.dart', + statusType: GitFileStatusType.unmerged, + ), + ]; + + provider.setStateForTesting( + rootPath: root, + currentRepoPath: root, + changedFiles: changedFiles, + ); + + // 直接查文件 + final btnStatus = provider.getFileStatus('/mock/repo/lib/widgets/button.dart'); + expect(btnStatus, isNotNull); + expect(btnStatus!.statusType, GitFileStatusType.modified); + + final mainStatus = provider.getFileStatus('/mock/repo/lib/main.dart'); + expect(mainStatus, isNotNull); + expect(mainStatus!.statusType, GitFileStatusType.untracked); + + // 查目录:/mock/repo/lib/widgets 同时含有 modified 和 unmerged -> 聚合出 unmerged(最高优先级) + final widgetsDirStatus = provider.getDirectoryStatus('/mock/repo/lib/widgets'); + expect(widgetsDirStatus, GitFileStatusType.unmerged); + + // 查父级目录:/mock/repo/lib 继承最高优先级 unmerged + final libDirStatus = provider.getDirectoryStatus('/mock/repo/lib'); + expect(libDirStatus, GitFileStatusType.unmerged); + + // 查不存在的文件 + final absent = provider.getFileStatus('/mock/repo/lib/unknown.dart'); + expect(absent, isNull); + }); + }); + + group('FileItemWidget Git Decoration UI Tests', () { + testWidgets('renders letter trailing for modified file and colored dot for folder', (tester) async { + final gitProvider = GitProvider(); + final projectProvider = ProjectProvider(); + final tabProvider = TabProvider(); + + const filePath = '/test/project/file.dart'; + const dirPath = '/test/project/dir'; + + gitProvider.setStateForTesting( + rootPath: '/test/project', + currentRepoPath: '/test/project', + changedFiles: [ + const GitFileStatus( + path: filePath, + relativePath: 'file.dart', + statusType: GitFileStatusType.modified, + ), + const GitFileStatus( + path: '/test/project/dir/nested.dart', + relativePath: 'dir/nested.dart', + statusType: GitFileStatusType.untracked, + ), + ], + ); + + final fileItem = FileItem( + path: filePath, + name: 'file.dart', + isDirectory: false, + depth: 0, + ); + + final dirItem = FileItem( + path: dirPath, + name: 'dir', + isDirectory: true, + depth: 0, + ); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: gitProvider), + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + home: Scaffold( + body: Column( + children: [ + FileItemWidget(fileItem: fileItem), + FileItemWidget(fileItem: dirItem), + ], + ), + ), + ), + ), + ); + + await tester.pumpAndSettle(); + + // 验证文件项中出现了 'M' 标识 + expect(find.text('M'), findsOneWidget); + + // 验证文件夹项中没有文本字母标识,但渲染了实心圆点 + expect(find.text('dir'), findsOneWidget); + }); + }); +} diff --git a/test/git_repository_test.dart b/test/git_repository_test.dart new file mode 100644 index 0000000..a000c7b --- /dev/null +++ b/test/git_repository_test.dart @@ -0,0 +1,1322 @@ +import 'dart:io'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/git_model.dart'; +import 'package:code_editor/models/project_history.dart'; +import 'package:code_editor/providers/git_provider.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/providers/search_provider.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/git_service.dart'; +import 'package:code_editor/services/internal_project_service.dart'; +import 'package:code_editor/utils/git_diff_helper.dart'; +import 'package:code_editor/widgets/code_editor_drawer.dart'; +import 'package:code_editor/widgets/git/git_diff_page.dart'; +import 'package:code_editor/widgets/git/git_panel_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + late Directory testProjectDir; + late ProjectProvider projectProvider; + late TabProvider tabProvider; + late SettingsProvider settingsProvider; + late RunProvider runProvider; + late SearchProvider searchProvider; + late GitProvider gitProvider; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + GitService.instance.resetForTesting(); + tempBaseDir = Directory.systemTemp.createTempSync('git_repository_test_'); + testProjectDir = Directory(p.join(tempBaseDir.path, 'git_test_project'))..createSync(recursive: true); + + InternalProjectService.instance.customProjectsDir = + Directory(p.join(tempBaseDir.path, 'files', 'projects')); + + projectProvider = ProjectProvider(); + tabProvider = TabProvider()..bindProjectProvider(projectProvider); + settingsProvider = SettingsProvider(); + runProvider = RunProvider(); + searchProvider = SearchProvider()..bindRootPath(testProjectDir.path); + gitProvider = GitProvider(); + + await projectProvider.switchProject( + ProjectHistory( + rootPath: testProjectDir.path, + lastOpenedFilePath: null, + ), + ); + }); + + tearDown(() { + GitService.instance.resetForTesting(); + InternalProjectService.instance.customProjectsDir = null; + if (tempBaseDir.existsSync()) { + try { + tempBaseDir.deleteSync(recursive: true); + } catch (_) {} + } + }); + + Widget buildTestApp({Widget? home}) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: runProvider), + ChangeNotifierProvider.value(value: searchProvider), + ChangeNotifierProvider.value(value: gitProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: home ?? + const Scaffold( + drawer: CodeEditorDrawer(), + body: Center(child: Text('Main Editor')), + ), + ), + ); + } + + group('GitService Unit Tests', () { + test('checkGitInstalled reports true when git --version succeeds', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult(1, 1, '', 'unknown'); + }; + + final status = await GitService.instance.checkGitInstalled(forceRefresh: true); + expect(status.isInstalled, isTrue); + expect(status.version, contains('git version 2.45.0')); + }); + + test('checkGitInstalled reports false when git executable is not found', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + throw const ProcessException('git', ['--version'], 'No such file or directory', 2); + }; + + final status = await GitService.instance.checkGitInstalled(forceRefresh: true); + expect(status.isInstalled, isFalse); + expect(status.errorMessage, contains('No such file or directory')); + }); + + test('installGit runs process and refreshes environment status', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('install-git')) { + return ProcessResult(0, 0, 'Git installed\n', ''); + } + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final result = await GitService.instance.installGit(); + expect(result.success, isTrue); + + final status = await GitService.instance.checkGitInstalled(); + expect(status.isInstalled, isTrue); + }); + + test('isGitRepository correctly checks existence of .git directory or file', () { + final repoDir = Directory(p.join(testProjectDir.path, 'repo1'))..createSync(); + expect(GitService.instance.isGitRepository(repoDir.path), isFalse); + + // Create .git directory + Directory(p.join(repoDir.path, '.git')).createSync(); + expect(GitService.instance.isGitRepository(repoDir.path), isTrue); + + // Create submodule with .git file + final submoduleDir = Directory(p.join(testProjectDir.path, 'submodule'))..createSync(); + File(p.join(submoduleDir.path, '.git')).writeAsStringSync('gitdir: ../.git/modules/sub'); + expect(GitService.instance.isGitRepository(submoduleDir.path), isTrue); + }); + + test('detectRepositories discovers both root repo and nested/submodule repos', () async { + // 1. Root repo + Directory(p.join(testProjectDir.path, '.git')).createSync(); + + // 2. Nested repo inside packages/core + final nestedDir = Directory(p.join(testProjectDir.path, 'packages', 'core'))..createSync(recursive: true); + Directory(p.join(nestedDir.path, '.git')).createSync(); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('branch') || args.contains('symbolic-ref')) { + return ProcessResult(0, 0, 'main\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final repos = await GitService.instance.detectRepositories(testProjectDir.path); + expect(repos.length, equals(2)); + + final root = repos.firstWhere((r) => r.isRoot); + expect(root.rootPath, equals(p.normalize(testProjectDir.path))); + expect(root.currentBranch, equals('main')); + + final nested = repos.firstWhere((r) => !r.isRoot); + expect(nested.rootPath, equals(p.normalize(nestedDir.path))); + expect(nested.name, equals(p.normalize('packages/core'))); + }); + + test('getGitStatus parses porcelain status output accurately', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.contains('status')) { + final stdout = + '?? untracked.dart\n' + ' M modified_worktree.dart\n' + 'M staged_modified.dart\n' + 'MM both_modified.dart\n' + 'A staged_new.dart\n' + ' D deleted.dart\n' + 'R old.dart -> new.dart\n'; + return ProcessResult(0, 0, stdout, ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final statuses = await GitService.instance.getGitStatus(testProjectDir.path); + expect(statuses.length, equals(8)); + + // Untracked + final untracked = statuses.firstWhere((s) => s.relativePath == 'untracked.dart'); + expect(untracked.statusType, equals(GitFileStatusType.untracked)); + expect(untracked.isStaged, isFalse); + + // Worktree modified + final modifiedWorktree = statuses.firstWhere((s) => s.relativePath == 'modified_worktree.dart'); + expect(modifiedWorktree.statusType, equals(GitFileStatusType.modified)); + expect(modifiedWorktree.isStaged, isFalse); + + // Staged modified + final stagedMod = statuses.firstWhere((s) => s.relativePath == 'staged_modified.dart'); + expect(stagedMod.statusType, equals(GitFileStatusType.modified)); + expect(stagedMod.isStaged, isTrue); + + // Staged added + final added = statuses.firstWhere((s) => s.relativePath == 'staged_new.dart'); + expect(added.statusType, equals(GitFileStatusType.added)); + expect(added.isStaged, isTrue); + + // Staged renamed + final renamed = statuses.firstWhere((s) => s.relativePath == 'new.dart'); + expect(renamed.statusType, equals(GitFileStatusType.renamed)); + expect(renamed.isStaged, isTrue); + expect(renamed.originalPath, equals('old.dart')); + }); + + test('getLog parses commit history and computes graph lanes accurately', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('log')) { + final stdout = + 'commit1\x00c1\x00commit2\x00Author 1\x00a1@test.com\x001700000000\x002 days ago\x00feat: initial\x00HEAD -> main, origin/main\n' + 'commit2\x00c2\x00\x00Author 2\x00a2@test.com\x001699990000\x003 days ago\x00chore: init repo\x00\n'; + return ProcessResult(0, 0, stdout, ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final commits = await GitService.instance.getLog(testProjectDir.path); + expect(commits.length, equals(2)); + expect(commits[0].hash, equals('commit1')); + expect(commits[0].shortHash, equals('c1')); + expect(commits[0].subject, equals('feat: initial')); + expect(commits[0].isHead, isTrue); + expect(commits[0].refs, contains('HEAD -> main')); + expect(commits[0].lane, equals(0)); + expect(commits[1].hash, equals('commit2')); + expect(commits[1].shortHash, equals('c2')); + }); + + test('GitService tag operations execute correct git arguments', () async { + final executedArgs = >[]; + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + executedArgs.add(args); + if (args.contains('tag') && args.contains('-l')) { + return ProcessResult(0, 0, 'v1.0.0\nv1.1.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final tags = await GitService.instance.getTags(testProjectDir.path); + expect(tags, equals(['v1.0.0', 'v1.1.0'])); + + final createRes = await GitService.instance.createTag(testProjectDir.path, 'v1.2.0', message: 'Release 1.2'); + expect(createRes.success, isTrue); + expect(executedArgs.last, equals(['tag', '-a', 'v1.2.0', '-m', 'Release 1.2'])); + + final deleteRes = await GitService.instance.deleteTag(testProjectDir.path, 'v1.0.0'); + expect(deleteRes.success, isTrue); + expect(executedArgs.last, equals(['tag', '-d', 'v1.0.0'])); + + final checkoutRes = await GitService.instance.checkoutTag(testProjectDir.path, 'v1.1.0'); + expect(checkoutRes.success, isTrue); + expect(executedArgs.last, equals(['checkout', 'v1.1.0'])); + }); + }); + + group('GitProvider Unit Tests', () { + test('bindRootPath clears and refreshes state', () async { + gitProvider.setStateForTesting( + rootPath: '/old/path', + repositories: [ + const GitRepositoryInfo(rootPath: '/old/path', name: 'old', isRoot: true), + ], + currentRepoPath: '/old/path', + currentBranch: 'dev', + ); + + expect(gitProvider.hasRepository, isTrue); + expect(gitProvider.currentBranch, equals('dev')); + + gitProvider.bindRootPath(null); + expect(gitProvider.hasRepository, isFalse); + expect(gitProvider.currentRepoPath, isNull); + }); + + test('createTag, deleteTag, and switchTag update provider state', () async { + final repoPath = p.normalize(testProjectDir.path); + gitProvider.setStateForTesting( + rootPath: repoPath, + currentRepoPath: repoPath, + currentBranch: 'main', + tags: ['v1.0.0'], + ); + + var currentTagsOutput = 'v1.0.0\nv2.0.0\n'; + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('tag') && args.contains('-l')) { + return ProcessResult(0, 0, currentTagsOutput, ''); + } + if (args.contains('checkout')) { + return ProcessResult(0, 0, 'Note: checking out v2.0.0.\nHEAD is now at 1234567\n', ''); + } + if (args.contains('symbolic-ref') || args.contains('branch')) { + return ProcessResult(0, 0, 'detached (1234567)\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final createRes = await gitProvider.createTag('v2.0.0'); + expect(createRes.success, isTrue); + expect(gitProvider.tags, equals(['v1.0.0', 'v2.0.0'])); + + final switchRes = await gitProvider.switchTag('v2.0.0'); + expect(switchRes.success, isTrue); + + currentTagsOutput = 'v2.0.0\n'; + final deleteRes = await gitProvider.deleteTag('v1.0.0'); + expect(deleteRes.success, isTrue); + expect(gitProvider.tags, equals(['v2.0.0'])); + }); + + test('initRepository sets isInitializing, runs init, and refreshes', () async { + gitProvider.setStateForTesting(rootPath: testProjectDir.path); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.contains('init')) { + Directory(p.join(testProjectDir.path, '.git')).createSync(); + return ProcessResult(0, 0, 'Initialized empty Git repository\n', ''); + } + if (args.contains('branch') || args.contains('symbolic-ref')) { + return ProcessResult(0, 0, 'main\n', ''); + } + if (args.contains('status')) { + return ProcessResult(0, 0, '', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + expect(gitProvider.hasRepository, isFalse); + final res = await gitProvider.initRepository(); + expect(res.success, isTrue); + expect(gitProvider.hasRepository, isTrue); + expect(gitProvider.currentRepo?.isRoot, isTrue); + expect(gitProvider.currentBranch, equals('main')); + }); + + test('switchRepository switches current repo and loads details', () async { + final path1 = p.normalize('/repo1'); + final path2 = p.normalize('/repo2'); + final repo1 = GitRepositoryInfo(rootPath: path1, name: 'repo1', isRoot: true, currentBranch: 'main'); + final repo2 = GitRepositoryInfo(rootPath: path2, name: 'repo2', isRoot: false, currentBranch: 'feature'); + + gitProvider.setStateForTesting( + rootPath: path1, + repositories: [repo1, repo2], + currentRepoPath: path1, + currentBranch: 'main', + ); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (workingDirectory == path2 && args.contains('branch')) { + return ProcessResult(0, 0, 'feature\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + expect(gitProvider.currentRepoPath, equals(path1)); + await gitProvider.switchRepository(path2); + expect(gitProvider.currentRepoPath, equals(path2)); + }); + }); + + group('GitPanelWidget UI Tests', () { + testWidgets('Displays no project view when project is null or empty', (tester) async { + projectProvider.setHistoryForTesting(const ProjectHistory(rootPath: null, lastOpenedFilePath: null)); + gitProvider.bindRootPath(null); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.text('当前未打开项目'), findsOneWidget); + }); + + testWidgets('Displays Git install guidance view without not-found warning or code box, provides install button', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: false, + repositories: [], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // 不再指明 "未检测到 Git" / "Git not found" + expect(find.text('未检测到 Git'), findsNothing); + // 副文本和终端代码框已移除 + expect(find.text('apt update && apt install -y git'), findsNothing); + // 温和提示需要安装 Git + expect(find.text('需要安装 Git'), findsOneWidget); + // 在下面主动提供【安装 Git】按钮 + expect(find.text('安装 Git'), findsOneWidget); + }); + + testWidgets('Tapping install Git button pops blocking dialog and executes installation', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: false, + repositories: [], + isLoading: false, + ); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('install-git')) { + await Future.delayed(const Duration(milliseconds: 100)); + return ProcessResult(0, 0, 'Git installed successfully\n', ''); + } + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + final installButton = find.text('安装 Git'); + expect(installButton, findsOneWidget); + + // Tap install button + await tester.tap(installButton); + await tester.pump(); + + // Verify synchronous blocking dialog is shown with text while installing + expect(find.text('正在安装 Git...'), findsOneWidget); + + // Await completion of installation and dialog dismissal + await tester.pump(const Duration(milliseconds: 150)); + await tester.pump(const Duration(milliseconds: 300)); + + // Dialog is dismissed + expect(find.text('正在安装 Git...'), findsNothing); + + // Drain toast timer + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('Displays uninitialized view with prominent button when repo is not initialized', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [], + isLoading: false, + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.text('当前工程尚未初始化为 Git 仓库'), findsOneWidget); + expect(find.text('初始化 Git 仓库'), findsOneWidget); + }); + + testWidgets('Tapping initialize button pops blocking dialog and executes git init', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [], + isLoading: false, + ); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('init')) { + await Future.delayed(const Duration(milliseconds: 100)); + Directory(p.join(testProjectDir.path, '.git')).createSync(); + return ProcessResult(0, 0, 'Initialized empty Git repository\n', ''); + } + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.contains('branch') || args.contains('symbolic-ref')) { + return ProcessResult(0, 0, 'main\n', ''); + } + if (args.contains('status')) { + return ProcessResult(0, 0, '', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + final initButton = find.text('初始化 Git 仓库'); + expect(initButton, findsOneWidget); + + // Tap initialize button + await tester.tap(initButton); + await tester.pump(); + + // Verify synchronous blocking dialog is shown with text while initializing + expect(find.text('正在初始化 Git 仓库...'), findsOneWidget); + + // Await completion of initialization and dialog dismissal + await tester.pump(const Duration(milliseconds: 150)); + await tester.pump(const Duration(milliseconds: 300)); + + // Dialog is dismissed + expect(find.text('正在初始化 Git 仓库...'), findsNothing); + + // Now repo is initialized! + expect(gitProvider.hasRepository, isTrue); + expect(find.text('main'), findsOneWidget); + expect(find.text('暂无任何文件更改'), findsOneWidget); + + // Drain toast timer so no pending timers remain + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('Displays changes and opens file on tap when repository has changes', (tester) async { + final changeItem = GitFileStatus( + path: p.normalize(p.join(testProjectDir.path, 'lib', 'main.dart')), + relativePath: 'lib/main.dart', + statusType: GitFileStatusType.modified, + isStaged: false, + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + changedFiles: [changeItem], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.text('更改'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('main.dart'), findsOneWidget); + expect(find.text('lib'), findsOneWidget); + expect(find.text('M'), findsOneWidget); + expect(find.byIcon(Icons.add), findsWidgets); + expect(find.byIcon(Icons.undo_rounded), findsWidgets); + + // Tapping file calls openFile on TabProvider + await tester.tap(find.text('main.dart')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + }); + + testWidgets('Displays dropdown switcher when multiple repositories are detected', (tester) async { + final repo1 = GitRepositoryInfo( + rootPath: p.normalize(testProjectDir.path), + name: 'root_project', + isRoot: true, + currentBranch: 'main', + ); + final repo2 = GitRepositoryInfo( + rootPath: p.normalize(p.join(testProjectDir.path, 'packages', 'core')), + name: 'packages/core', + isRoot: false, + currentBranch: 'dev', + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [repo1, repo2], + currentRepoPath: repo1.rootPath, + currentBranch: 'main', + changedFiles: [], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Dropdown button should show the active repository name + expect(find.text('root_project'), findsOneWidget); + expect(find.byTooltip('切换仓库'), findsOneWidget); + + // Open dropdown menu + await tester.tap(find.byTooltip('切换仓库')); + await tester.pumpAndSettle(); + + // Should show both repositories in menu + expect(find.text('packages/core'), findsOneWidget); + }); + + testWidgets('ActivityBar displays badge with changed files count', (tester) async { + final item1 = GitFileStatus( + path: p.normalize(p.join(testProjectDir.path, 'lib', 'a.dart')), + relativePath: 'lib/a.dart', + statusType: GitFileStatusType.modified, + isStaged: false, + ); + final item2 = GitFileStatus( + path: p.normalize(p.join(testProjectDir.path, 'lib', 'b.dart')), + relativePath: 'lib/b.dart', + statusType: GitFileStatusType.added, + isStaged: true, + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + changedFiles: [item1, item2], + ); + + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Badge on ActivityBar Git item displays "2" + expect(find.text('2'), findsWidgets); + }); + + testWidgets('Staged changes displays with unstage button and commit box', (tester) async { + final stagedItem = GitFileStatus( + path: p.normalize(p.join(testProjectDir.path, 'lib', 'staged.dart')), + relativePath: 'lib/staged.dart', + statusType: GitFileStatusType.added, + isStaged: true, + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + changedFiles: [stagedItem], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.text('暂存的更改'), findsOneWidget); + expect(find.text('staged.dart'), findsOneWidget); + expect(find.byTooltip('取消暂存更改'), findsOneWidget); + expect(find.byTooltip('全部取消暂存更改'), findsOneWidget); + expect(find.text('提交'), findsOneWidget); + }); + + testWidgets('CodeEditorDrawer switches to Git tab (index 2) seamlessly', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [], + isLoading: false, + ); + + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Switch to Git tab (icon Icons.alt_route_rounded) + await tester.tap(find.byIcon(Icons.alt_route_rounded)); + await tester.pumpAndSettle(); + + expect(CodeEditorDrawer.lastSelectedTabIndex, equals(2)); + expect(find.byType(GitPanelWidget), findsOneWidget); + expect(find.text('当前工程尚未初始化为 Git 仓库'), findsOneWidget); + }); + + testWidgets('GitPanelWidget displays Graph section with commit history and details dialog', (tester) async { + final commit1 = GitCommit( + hash: 'abcdef1234567890abcdef1234567890abcdef12', + shortHash: 'abcdef1', + parentHashes: const ['1234567'], + authorName: 'TestDev', + authorEmail: 'dev@test.com', + authorDate: DateTime.now(), + relativeDate: '10 minutes ago', + subject: 'feat: add git graph support', + refs: const ['HEAD -> main'], + lane: 0, + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + changedFiles: [], + commits: [commit1], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Check Graph section header + expect(find.text('图表'), findsOneWidget); + expect(find.text('feat: add git graph support'), findsOneWidget); + expect(find.text('abcdef1'), findsOneWidget); + expect(find.text('main'), findsWidgets); + + // Tap on commit to open details modal + await tester.tap(find.text('feat: add git graph support')); + await tester.pumpAndSettle(); + + expect(find.text('提交详情'), findsOneWidget); + expect(find.text('TestDev '), findsOneWidget); + expect(find.byTooltip('复制哈希'), findsOneWidget); + }); + + testWidgets('GitPanelWidget displays branch selector in separate row and more actions menu', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + branches: ['main', 'feature/login'], + tags: ['v1.0.0'], + changedFiles: [], + stashCount: 1, + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Branch button exists with branch name and stash count indicator + expect(find.text('main'), findsOneWidget); + expect(find.text('stash: 1'), findsOneWidget); + + // Tap branch button to open anchored popup menu + await tester.tap(find.text('main')); + await tester.pumpAndSettle(); + + // Dropdown menu has Radio toggle for 分支 and 标签 + expect(find.text('分支'), findsWidgets); + expect(find.text('标签'), findsOneWidget); + expect(find.text('feature/login'), findsOneWidget); + + // Tap 标签 radio to switch list to tags + await tester.tap(find.text('标签')); + await tester.pumpAndSettle(); + + // Should now show tags list + expect(find.text('v1.0.0'), findsOneWidget); + + // Tap outside to dismiss the menu + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + + // More actions menu icon exists next to branch bar + expect(find.byKey(const ValueKey('branch_row_more_button')), findsOneWidget); + + // Open more actions menu (since last selected was Tag, it offers Tag actions) + await tester.tap(find.byKey(const ValueKey('branch_row_more_button'))); + await tester.pumpAndSettle(); + + expect(find.text('创建新标签'), findsOneWidget); + expect(find.text('删除标签'), findsOneWidget); + }); + + testWidgets('Long pressing a changed file item opens context menu with actions', (tester) async { + final untrackedItem = GitFileStatus( + path: p.normalize(p.join(testProjectDir.path, 'untracked.txt')), + relativePath: 'untracked.txt', + statusType: GitFileStatusType.untracked, + isStaged: false, + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + changedFiles: [untrackedItem], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.text('untracked.txt'), findsOneWidget); + + // Long press file item to trigger BottomSheet context menu + await tester.longPress(find.text('untracked.txt')); + await tester.pumpAndSettle(); + + expect(find.text('暂存更改'), findsOneWidget); + expect(find.text('放弃更改'), findsOneWidget); + expect(find.text('添加到 .gitignore'), findsOneWidget); + expect(find.text('打开文件'), findsOneWidget); + }); + + testWidgets('Tapping 创建新标签 opens dialog and creates tag', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + branches: ['main'], + tags: [], + changedFiles: [], + ); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('tag') && args.contains('v1.0.0')) { + return ProcessResult(0, 0, '', ''); + } + if (args.contains('tag') && args.contains('-l')) { + return ProcessResult(0, 0, 'v1.0.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Open selector and switch to Tag + await tester.tap(find.text('main')); + await tester.pumpAndSettle(); + await tester.tap(find.text('标签')); + await tester.pumpAndSettle(); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + + // Tap more button + await tester.tap(find.byKey(const ValueKey('branch_row_more_button'))); + await tester.pumpAndSettle(); + + // Tap 创建新标签 + await tester.tap(find.text('创建新标签')); + await tester.pumpAndSettle(); + + // Verify dialog is open + expect(find.byType(AlertDialog), findsOneWidget); + final dialogTextFields = find.descendant(of: find.byType(AlertDialog), matching: find.byType(TextField)); + expect(dialogTextFields, findsNWidgets(2)); + + // Enter tag name + await tester.enterText(dialogTextFields.first, 'v1.0.0'); + await tester.pumpAndSettle(); + + // Tap confirm + await tester.tap(find.text('确定')); + await tester.pumpAndSettle(); + + // Provider tags updated + expect(gitProvider.tags, contains('v1.0.0')); + + // Drain toast timer + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('GitPanelWidget restores collapsed state and draft commit message from in-memory cache', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + branches: ['main'], + changedFiles: [], + ); + + // Mount GitPanelWidget + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Enter draft commit message + final commitInput = find.byType(TextField).first; + await tester.enterText(commitInput, 'WIP: in-memory draft message'); + await tester.pumpAndSettle(); + + // Collapse "更改" section + expect(find.text('暂无任何文件更改'), findsOneWidget); + await tester.tap(find.text('更改')); + await tester.pumpAndSettle(); + expect(find.text('暂无任何文件更改'), findsNothing); + + // Unmount GitPanelWidget (simulating switching away or closing drawer) + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: SizedBox()))); + await tester.pumpAndSettle(); + + // Re-mount GitPanelWidget + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Verify draft commit message is restored from memory + expect(find.text('WIP: in-memory draft message'), findsOneWidget); + + // Verify collapsed state is restored from memory + expect(find.text('暂无任何文件更改'), findsNothing); + }); + + testWidgets('GitPanelWidget efficiently handles thousands of tags with virtualization and search', (tester) async { + final manyTags = List.generate(2000, (i) => 'v$i.0.0'); + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + branches: ['main'], + tags: manyTags, + changedFiles: [], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Open selector and switch to Tag + await tester.tap(find.text('main')); + await tester.pumpAndSettle(); + await tester.tap(find.text('标签')); + await tester.pumpAndSettle(); + + // Search input appears because tags count > 5 + final searchField = find.byWidgetPredicate( + (w) => w is TextField && w.decoration?.hintText == '搜索标签...', + ); + expect(searchField, findsOneWidget); + + // Filter with search query + await tester.enterText(searchField, 'v199'); + await tester.pumpAndSettle(); + + expect(find.text('v199.0.0'), findsOneWidget); + + // Tap tag outside + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + }); + + testWidgets('Branch search box is always visible and row icon switches only when selecting a specific tag', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + branches: ['main', 'feature/login'], + tags: ['v1.0.0'], + changedFiles: [], + ); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('checkout') && args.contains('v1.0.0')) { + return ProcessResult(0, 0, '', ''); + } + if (args.contains('describe') && args.contains('--exact-match')) { + return ProcessResult(0, 0, 'v1.0.0\n', ''); + } + if (args.contains('tag') && args.contains('-l')) { + return ProcessResult(0, 0, 'v1.0.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Initially on branch 'main': row icon is call_split_rounded + expect(find.byIcon(Icons.call_split_rounded), findsWidgets); + expect(find.byIcon(Icons.local_offer_outlined), findsNothing); + + // Open selector dropdown + await tester.tap(find.text('main')); + await tester.pumpAndSettle(); + + // Branch search box is visible even with only 2 branches + final branchSearchField = find.byWidgetPredicate( + (w) => w is TextField && w.decoration?.hintText == '搜索分支...', + ); + expect(branchSearchField, findsOneWidget); + + // Filter branches + await tester.enterText(branchSearchField, 'login'); + await tester.pumpAndSettle(); + expect(find.text('feature/login'), findsOneWidget); + + // Switch to Tag mode inside dialog + await tester.tap(find.text('标签')); + await tester.pumpAndSettle(); + + // Crucial: The row button behind still shows call_split_rounded, NOT converted to local_offer_outlined yet! + expect(gitProvider.isCurrentRefTag, isFalse); + + // Tap on specific tag 'v1.0.0' to checkout tag + await tester.tap(find.text('v1.0.0')); + await tester.pumpAndSettle(); + + // Now row button has converted to tag icon and displays 'v1.0.0' + expect(gitProvider.isCurrentRefTag, isTrue); + expect(find.text('v1.0.0'), findsOneWidget); + expect(find.byIcon(Icons.local_offer_outlined), findsWidgets); + + // Drain toast timer + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('Delete tag and branch dialogs contain search input and filter items in real-time', (tester) async { + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + branches: ['main', 'feat/auth', 'feat/profile'], + tags: ['v1.0.0', 'v2.0.0', 'release-2026'], + changedFiles: [], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Open more actions menu + await tester.tap(find.byKey(const ValueKey('branch_row_more_button'))); + await tester.pumpAndSettle(); + + // Tap '删除分支' + await tester.tap(find.text('删除分支')); + await tester.pumpAndSettle(); + + // Verify search input exists in delete branch dialog + final branchSearch = find.byWidgetPredicate( + (w) => w is TextField && w.decoration?.hintText == '搜索分支...', + ); + expect(branchSearch, findsOneWidget); + + // Filter branches + await tester.enterText(branchSearch, 'auth'); + await tester.pumpAndSettle(); + expect(find.text('feat/auth'), findsOneWidget); + expect(find.text('feat/profile'), findsNothing); + + // Cancel dialog + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + + // Open more actions menu again + await tester.tap(find.byKey(const ValueKey('branch_row_more_button'))); + await tester.pumpAndSettle(); + + // Tap '删除标签' + await tester.tap(find.text('删除标签')); + await tester.pumpAndSettle(); + + // Verify search input exists in delete tag dialog + final tagSearch = find.byWidgetPredicate( + (w) => w is TextField && w.decoration?.hintText == '搜索标签...', + ); + expect(tagSearch, findsOneWidget); + + // Filter tags + await tester.enterText(tagSearch, 'release'); + await tester.pumpAndSettle(); + expect(find.text('release-2026'), findsOneWidget); + expect(find.text('v1.0.0'), findsNothing); + + // Cancel dialog + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + }); + + test('GitDiffHelper computeSplitDiff and toUnifiedDiff', () { + const orig = 'line1\nline2\nline3\nline4'; + const mod = 'line1\nline2_modified\nline3\nline4\nline5'; + + final split = GitDiffHelper.computeSplitDiff(orig, mod); + expect(split.leftLines.length, equals(split.rightLines.length)); + expect(split.additionsCount, equals(2)); + expect(split.deletionsCount, equals(1)); + expect(split.changeRowIndices.isNotEmpty, isTrue); + + final unified = GitDiffHelper.toUnifiedDiff(orig, mod); + expect(unified.any((l) => l.type == DiffLineType.added), isTrue); + expect(unified.any((l) => l.type == DiffLineType.deleted), isTrue); + expect(unified.any((l) => l.type == DiffLineType.unchanged), isTrue); + }); + + testWidgets('Clicking file in Git panel opens GitDiffPage', (WidgetTester tester) async { + tester.view.physicalSize = const Size(1200, 1600); + tester.view.devicePixelRatio = 1.0; + addTearDown(() => tester.view.resetPhysicalSize()); + + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('status')) { + return ProcessResult(0, 0, ' M test_file.dart\n', ''); + } + if (args.contains('rev-parse')) { + return ProcessResult(0, 0, '${testProjectDir.path}\n', ''); + } + if (args.contains('show')) { + return ProcessResult(0, 0, 'void main() {\n print("old");\n}\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final file = File(p.join(testProjectDir.path, 'test_file.dart')); + file.writeAsStringSync('void main() {\n print("new");\n}\n'); + + final changedItem = GitFileStatus( + path: file.path, + relativePath: 'test_file.dart', + statusType: GitFileStatusType.modified, + isStaged: false, + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentRepoPath: testProjectDir.path, + currentBranch: 'main', + changedFiles: [changedItem], + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.text('test_file.dart'), findsOneWidget); + + await tester.tap(find.text('test_file.dart')); + await tester.pumpAndSettle(); + + expect(find.byType(GitDiffPage), findsOneWidget); + expect(find.text('原始版本'), findsOneWidget); + expect(find.text('修改版本'), findsOneWidget); + + final toggleButton = find.byTooltip('单屏内联'); + expect(toggleButton, findsOneWidget); + await tester.tap(toggleButton); + await tester.pumpAndSettle(); + + final splitToggleButton = find.byTooltip('双屏分栏'); + expect(splitToggleButton, findsOneWidget); + await tester.tap(splitToggleButton); + await tester.pumpAndSettle(); + + expect(find.text('原始版本'), findsOneWidget); + expect(find.text('修改版本'), findsOneWidget); + + // 验证双指捏合缩放手势与实时字号气泡 + final center = tester.getCenter(find.text('原始版本')); + final touch1 = await tester.startGesture(center + const Offset(0, 100), pointer: 1); + final touch2 = await tester.startGesture(center + const Offset(100, 100), pointer: 2); + await tester.pump(); + + await touch2.moveTo(center + const Offset(200, 100)); + await tester.pump(); + + expect(find.textContaining('pt'), findsOneWidget); + + await touch1.up(); + await touch2.up(); + await tester.pumpAndSettle(); + + expect(find.textContaining('pt'), findsNothing); + + // 验证极限拖拽分割线至最左侧/最右侧(代码区被压缩至看不见),彻底杜绝 RenderFlex 水平溢出 + final centerScreen = tester.getCenter(find.byType(GitDiffPage)); + await tester.dragFrom(centerScreen, const Offset(-380, 0)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + + await tester.dragFrom(centerScreen, const Offset(380, 0)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); + + testWidgets('GitPanelWidget displays commit pagination footer and expand all button', (tester) async { + final commit1 = GitCommit( + hash: 'abcdef1234567890', + shortHash: 'abcdef1', + subject: 'feat: commit 1', + authorName: 'TestDev', + authorEmail: 'dev@test.com', + authorDate: DateTime.now(), + relativeDate: '2 hours ago', + parentHashes: [], + refs: ['HEAD -> main'], + lane: 0, + activeLanes: [], + outgoingLanes: [], + ); + + gitProvider.setStateForTesting( + rootPath: testProjectDir.path, + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: testProjectDir.path, + name: 'git_test_project', + isRoot: true, + currentBranch: 'main', + ), + ], + currentBranch: 'main', + commits: [commit1], + totalCommitsCount: 15, + ); + + await tester.pumpWidget(buildTestApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + // Verify CustomScrollView is present (virtualized rendering) + expect(find.byType(CustomScrollView), findsOneWidget); + + // Verify Expand All button in Graph section header + expect(find.byTooltip('全部展开'), findsOneWidget); + + // Verify lazy loading footer shows loaded vs total + expect(find.text('已显示 1 / 15 个提交'), findsOneWidget); + expect(find.text('加载更多提交 (14)'), findsOneWidget); + + // When all commits are loaded + gitProvider.setStateForTesting( + totalCommitsCount: 1, + ); + await tester.pumpAndSettle(); + + expect(find.text('已显示全部 1 个提交'), findsOneWidget); + }); + }); +} + diff --git a/test/project_search_test.dart b/test/project_search_test.dart index 0386238..c49a4c3 100644 --- a/test/project_search_test.dart +++ b/test/project_search_test.dart @@ -1,7 +1,9 @@ import 'dart:io'; import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/editor_tab_item.dart'; import 'package:code_editor/models/project_history.dart'; import 'package:code_editor/models/search_model.dart'; +import 'package:code_editor/providers/git_provider.dart'; import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/run_provider.dart'; import 'package:code_editor/providers/search_provider.dart'; @@ -13,6 +15,7 @@ import 'package:code_editor/widgets/code_editor_drawer.dart'; import 'package:code_editor/widgets/code_editor_widget.dart'; import 'package:code_editor/widgets/search/search_panel_widget.dart'; import 'package:flutter/material.dart'; +import 'package:re_editor/re_editor.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; @@ -28,6 +31,7 @@ void main() { late SettingsProvider settingsProvider; late RunProvider runProvider; late SearchProvider searchProvider; + late GitProvider gitProvider; setUp(() async { SharedPreferences.setMockInitialValues({}); @@ -42,6 +46,7 @@ void main() { settingsProvider = SettingsProvider(); runProvider = RunProvider(); searchProvider = SearchProvider()..bindRootPath(testProjectDir.path); + gitProvider = GitProvider(); await projectProvider.switchProject( ProjectHistory( @@ -197,6 +202,7 @@ void main() { ChangeNotifierProvider.value(value: settingsProvider), ChangeNotifierProvider.value(value: runProvider), ChangeNotifierProvider.value(value: searchProvider), + ChangeNotifierProvider.value(value: gitProvider), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -396,6 +402,7 @@ void main() { ChangeNotifierProvider.value(value: settingsProvider), ChangeNotifierProvider.value(value: runProvider), ChangeNotifierProvider.value(value: searchProvider), + ChangeNotifierProvider.value(value: gitProvider), ], child: const MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -570,6 +577,7 @@ void main() { ChangeNotifierProvider.value(value: settingsProvider), ChangeNotifierProvider.value(value: runProvider), ChangeNotifierProvider.value(value: searchProvider), + ChangeNotifierProvider.value(value: gitProvider), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -658,5 +666,75 @@ void main() { expect(mockFiles[1].isExpanded, isTrue); expect(searchProvider.scrollOffset, equals(150.0)); }); + + testWidgets('Editor focus and keyboard stability: focus is not lost or bounced during editing or search clear', (tester) async { + final mainPath = p.normalize(p.join(testProjectDir.path, 'lib', 'main.dart')); + final tabMain = EditorTabItem( + path: mainPath, + content: 'void main() {\n print("hello");\n}\n', + originalContent: 'void main() {\n print("hello");\n}\n', + isLoaded: true, + isModified: false, + ); + tabProvider.setOpenTabsForTesting([tabMain], activePath: mainPath); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: runProvider), + ChangeNotifierProvider.value(value: searchProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: CodeEditorWidget( + filePath: mainPath, + rootPath: testProjectDir.path, + ), + ), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); + + // Find CodeEditor focus node + final codeEditorFinder = find.byType(CodeEditor); + expect(codeEditorFinder, findsOneWidget); + final codeEditor = tester.widget(codeEditorFinder); + final focusNode = codeEditor.focusNode!; + + // 1. Focus the editor (user taps editor to bring up soft keyboard) + focusNode.requestFocus(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + expect(focusNode.hasFocus, isTrue); + expect(focusNode.canRequestFocus, isTrue); + + // 2. Perform search in text mode + searchProvider.setMode(SearchMode.text); + searchProvider.setQuery('void'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + // Focus should NOT be lost or disabled + expect(focusNode.hasFocus, isTrue); + expect(focusNode.canRequestFocus, isTrue); + + // 3. Clear search query to empty (simulating user deleting search text) + searchProvider.setQuery(''); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + // Focus must remain rock solid! canRequestFocus must NEVER be set to false! + expect(focusNode.hasFocus, isTrue); + expect(focusNode.canRequestFocus, isTrue); + }); }); }